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
63,505,647
2020-8-20
https://stackoverflow.com/questions/63505647/add-external-margins-with-constrained-layout
When generating a figure to save to a pdf file, I'd like to adjust the positioning of the figure relative to the edges of the page, for example to add an inch margin along all sides. As far as I can tell, the solutions to do this (for example, in this question) either: don't work with constrained_layout mode -- applyi...
You can set the rectangle that the layout engine operates within. See the rect parameter for each engine at https://matplotlib.org/stable/api/layout_engine_api.html. It's unfortunately not a very friendly part of the API, especially because TightLayoutEngine and ConstrainedLayoutEngine have different semantics for rect...
12
1
63,580,229
2020-8-25
https://stackoverflow.com/questions/63580229/how-to-save-uploadfile-in-fastapi
I accept the file via POST. When I save it locally, I can read the content using file.read (), but the name via file.name incorrect(16) is displayed. When I try to find it by this name, I get an error. What might be the problem? My code: @router.post( path="/upload", response_model=schema.ContentUploadedResponse, ) as...
Background UploadFile is just a wrapper around SpooledTemporaryFile, which can be accessed as UploadFile.file. SpooledTemporaryFile() [...] function operates exactly as TemporaryFile() does And documentation about TemporaryFile says: Return a file-like object that can be used as a temporary storage area. [..] It wil...
50
70
63,500,773
2020-8-20
https://stackoverflow.com/questions/63500773/python-security-update-installation-on-windows
Python security updates are source only updates. There is no windows installer. For instance the page for python 3.6.12 states: Security fix releases are produced periodically as needed and are source-only releases; binary installers are not provided. Could someone explain how I can update/patch a Python installation...
To install security patches after the last full bugfix release, you must build Python from source: Compile the Binaries Install Visual Studio 2019 Community and select: the Python development workload, and the Python native development tools (this is under Optional, but is necessary in order to build python from so...
20
15
63,511,090
2020-8-20
https://stackoverflow.com/questions/63511090/how-can-i-smooth-data-in-python
I'm using Python to detect some patterns on OHLC data. My problem is that the data I have is very noisy (I'm using Open data from the Open/High/Low/Close dataset), and it often leads me to incorrect or weak outcomes. Is there any way to "smooth" this data, or to make it less noisy, to improve my results? What algorithm...
Smoothing is a pretty rich subject; there are several methods each with features and drawbacks. Here is one using scipy: import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.signal import savgol_filter # noisy data x = [6903.79, 6838.04, 6868.57, 6621.25, 7101.99, 7026.78, 7248.6, 7121.4, 6...
6
11
63,564,559
2020-8-24
https://stackoverflow.com/questions/63564559/greenlet-error-cannot-switch-to-a-different-thread
I have a Flask application, getting this error while trying to integrate flask with faust. app.py import mode.loop.eventlet import logging import logging.config import json from flask import Flask from elasticapm.contrib.flask import ElasticAPM def create_app(): app = Flask(__name__) configure_apm(app) configure_loggin...
Something similar happened to me when I tried to debug a flask application using Pycharm. What I finally did to eventually solve my issue was to enable gevent compatibility in Pycharm: File -> settings -> Build,Execution,Deployment -> Python debugger -> Gevent compatible
12
18
63,536,505
2020-8-22
https://stackoverflow.com/questions/63536505/tkinter-geometry-management
I see and saw a lot of questions for tkinter that quite often asks not about errors in their code, but asks how do I organize my GUI. So I would like to have an answer that focus on that and help beginners to orientate them a little bit.
Basic knowlege about tkinters geometry management The geometry management of tkinter is characterized by this Quote here: By default a top-level window appears on the screen in its natural size, which is the one determined internally by its widgets and geometry managers. Toplevels Your Toplevel is the first question...
6
12
63,506,885
2020-8-20
https://stackoverflow.com/questions/63506885/how-to-authenticate-google-apis-google-drive-api-from-google-compute-engine-an
Our company is working on processing data from Google Sheets (within Google Drive) from Google Cloud Platform and we are having some problems with the authentication. There are two different places where we need to run code that makes API calls to Google Drive: within production in Google Compute Engine, and within dev...
One method for making the authentication from development environments easy is to use Service Account impersonation. Here is a blog about using service account impersonation, including the benefits of doing this. @johnhanley (who wrote the blog post) is a great guy and has lots of very informative answers on SO also! T...
9
6
63,511,413
2020-8-20
https://stackoverflow.com/questions/63511413/fastapi-redirection-for-trailing-slash-returns-non-ssl-link
When we call an endpoint and a redirect occurs due to a missing trailing slash. As you can see in the image below, when a request is made to https://.../notifications, the FastAPI server responds with a redirect to http://.../notifications/ I suspect that it's an app configuration issue rather than a server configurati...
This is because your application isn't trusting the reverse proxy's headers overriding the scheme (the X-Forwarded-Proto header that's passed when it handles a TLS request). There's a few ways we can fix that: If you're running the application straight from uvicorn server, try using the flag --forwarded-allow-ips '*'....
59
42
63,560,005
2020-8-24
https://stackoverflow.com/questions/63560005/draw-curved-lines-to-connect-points-in-matplotlib
So I am trying to plot curved lines to join points, here is the code I am using:- def hanging_line(point1, point2): a = (point2[1] - point1[1])/(np.cosh(point2[0]) - np.cosh(point1[0])) b = point1[1] - a*np.cosh(point1[0]) x = np.linspace(point1[0], point2[0], 100) y = a*np.cosh(x) + b return (x,y) n_teams = 4 n_weeks ...
Here is an approach using bezier curves. The sequence [...., i-indent, i, i + 0.8, ...] will put control points at each integer position i and some space before and after. The plot below used indent=0.8; indent=0 would create straight lines; with indent>1 the curves would be intersecting more. Other variations will mak...
22
21
63,492,123
2020-8-19
https://stackoverflow.com/questions/63492123/how-do-add-an-assembled-field-to-a-pydantic-model
Say I have model class UserDB(BaseModel): first_name: Optional[str] = None last_name: Optional[str] = None How do I make another model that is constructed from this one and has a field that changes based on the fields in this model? For instance, something like this class User(BaseModel): full_name: str = first_name +...
If you do not want to keep first_name and last_name in User then you can customize __init__. use validator for setting full_name. Both methods do what you want: from typing import Optional from pydantic import BaseModel, validator class UserDB(BaseModel): first_name: Optional[str] = None last_name: Optional[str] = No...
25
24
63,561,028
2020-8-24
https://stackoverflow.com/questions/63561028/how-to-detect-collisions-between-two-rectangular-objects-or-images-in-pygame
I am making a game in which the player has to use a bowl to catch falling items. I have some images of items in a list and an image of a bowl that is used to catch the items. The items keep on falling and reset to the top of the screen if they reach the boundary (bottom edge). I got this logic done which allows the ite...
Use pygame.Rect objects and colliderect() to detect the collision between the bounding rectangles of 2 objects or 2 images: rect1 = pygame.Rect(x1, y1, w1, h1) rect2 = pygame.Rect(x2, y2, w2, h2) if rect1.colliderect(rect2): # [...] If you have to images (pygame.Surface objects), the bounding rectangle of can be get b...
9
4
63,514,464
2020-8-20
https://stackoverflow.com/questions/63514464/graph-to-connect-sentences
I have a list of sentences of a few topics (two) like the below: Sentences Trump says that it is useful to win the next presidential election. The Prime Minister suggests the name of the winner of the next presidential election. In yesterday's conference, the Prime Minister said that it is very important to win the nex...
Didn't implement NLP for verb / noun separation, just added a list of good words. They can be extracted and normalized with spacy relatively easy. Please note that walk occurs in 1,2,5 sentences and forms a triad. import re import networkx as nx import matplotlib.pyplot as plt plt.style.use("ggplot") sentences = [ "I w...
9
4
63,515,267
2020-8-21
https://stackoverflow.com/questions/63515267/how-to-get-all-or-multiple-pairs-historical-klines-from-binance-api-in-one-re
I have a trading bot that trades multiple pairs (30-40). It uses the previous 5m candle for the price input. Therefore, I get 5m history for ALL pairs one by one. Currently, the full cycle takes about 10 minutes, so the 5m candles get updated once in 10m, which is no good. Any ideas on how to speed things up?
I think the best option for you will be websocket connection. You cannot recieve kline data once per eg. 5 minutes, but you can recieve every change in candle like you see it in graph. Binance API provide only this, but in compound with websocket connection it will by realy fast, not 10 minutes. After recieve data you ...
12
11
63,546,429
2020-8-23
https://stackoverflow.com/questions/63546429/binascii-error-incorrect-padding-in-python-django
I am trying to save the base64 encoded image in the django rest framework. First of all, we make a code to insert the base64 encoded image into the imagefield and test it, and the following error appears. binascii.Error: Incorrect padding What I don't understand is that I've used the same code before and there was no...
I'm not sure this applies to your situation, depending on where you're storing your encoded data. I had the same error, but it related to some encoded session data. I cleared out the session data (cookies, cache etc) in the browser Devtools, and it fixed my issue. Just posting this in case it applies or helps others wh...
7
23
63,552,169
2020-8-23
https://stackoverflow.com/questions/63552169/some-python-objects-were-not-bound-to-checkpointed-values
I am trying to get started with Tensorflow 2.0 Object Detection API. I have gone through the installation following the official tutorial and I pass all the tests. However, I keep getting an error message that I don't understand when I try to run the main module. This is how I run it: python model_main_tf2.py --model_d...
From the file name you provided (ssd_resnet50_v1_fpn_640x640_coco17_tpu-8), I can see you are trying to work with an object detection task. Therefore, in your pipeline.config file change this line: fine_tune_checkpoint_type: "classification" To: fine_tune_checkpoint_type: "detection" This should solve your problem.
17
52
63,583,502
2020-8-25
https://stackoverflow.com/questions/63583502/removing-duplicates-from-pandas-rows-replace-them-with-nans-shift-nans-to-end
Problem How to remove duplicate cells from each row, considering each row separately (and perhaps replace them with NaNs) in a Pandas dataframe? It would be even better if we could shift all newly created NaNs to the end of each row. Related but different posts Posts on how to remove entire rows which are deemed dupl...
You can stack and then drop_duplicates that way. Then we need to pivot with the help of a cumcount level. The stack preserves the order the values appear in along the rows and the cumcount ensures that the NaN will appear in the end. df1 = df.stack().reset_index().drop(columns='level_1').drop_duplicates() df1['col'] = ...
34
30
63,564,017
2020-8-24
https://stackoverflow.com/questions/63564017/keras-accuracy-doesnt-improve-more-than-59-percent
Here is the code I tried: # normalizing the train data cols_to_norm = ["WORK_EDUCATION", "SHOP", "OTHER",'AM','PM','MIDDAY','NIGHT', 'AVG_VEH_CNT', 'work_traveltime', 'shop_traveltime','work_tripmile','shop_tripmile', 'TRPMILES_sum', 'TRVL_MIN_sum', 'TRPMILES_mean', 'HBO', 'HBSHOP', 'HBW', 'NHB', 'DWELTIME_mean','TRVL_...
In short: NNs are rarely the best models for classifying either small amounts data or the data that is already compactly represented by a few non-heterogeneous columns. Often enough, boosted methods or GLM would produce better results from a similar amount of effort. What can you do with your model? Counterintuitively,...
7
3
63,478,525
2020-8-19
https://stackoverflow.com/questions/63478525/pdb-skip-restart-when-finished
With python -m pdb -c "c" script.py the debug mode is entered, when a problem occurs. From the doc, I figured out that the option -c "c" (Python 3.2+) saves me to hit c + Enter each time at program start. Yet, when the program finishes normally, it outputs The program finished and will be restarted and I still have t...
You can add multiple commands for -c in a sequence. METHOD 1: Quitting only if no error is encountered You can just give another command q to jump out of pdb mode incase no error is encountered. If an error is encountered, however, it will enter the debug mode where you will have to continue hitting c and enter to move...
7
5
63,490,533
2020-8-19
https://stackoverflow.com/questions/63490533/how-does-the-predict-proba-function-in-lightgbm-work-internally
This is in reference to understanding, internally, how the probabilities for a class are predicted using LightGBM. Other packages, like sklearn, provide thorough detail for their classifiers. For example: LogisticRegression returns: Probability estimates. The returned estimates for all classes are ordered by the lab...
LightGBM, like all gradient boosting methods for classification, essentially combines decision trees and logistic regression. We start with the same logistic function representing the probabilities (a.k.a. softmax): P(y = 1 | X) = 1/(1 + exp(Xw)) The interesting twist is that the feature matrix X is composed from the t...
19
15
63,581,844
2020-8-25
https://stackoverflow.com/questions/63581844/pycharm-run-tool-window-run-tab-window-is-missing
So recently my PyCharm is missing its run tool window that usually show the run/debug results. it is now replaced with python console and services, which is really frustrating because It's just showing gibberish and command-prompt-like format. How do I return the run tool window back as my main run/debug window? I have...
From what I understand you want the run icon pinned to your lower toolbar. (This corresponds to running whatever your last chosen configuration was.) Two easy steps: 1º View -> Tool Windows -> Run 2º Right-click run icon on lower tool bar -> View Mode -> Dock Pinned Edit after OP feedback: If your Run (Alt+4) option ...
9
7
63,556,777
2020-8-24
https://stackoverflow.com/questions/63556777/sqlalchemy-add-all-ignore-duplicate-key-integrityerror
I'm adding a list of objects entries to a database. Sometimes it may happen that one of this objects is already in the database (I do not have any control on that). With only one IntegrityError all the transactions will fail, i.e. all the objects in entries will not be inserted into the database. try: session.add_all(e...
I depends on what backend you're using. PostgreSQL has a wonderful INSERT() ON CONFLICT DO NOTHING clause which you can use with SQLAlchemy: from sqlalchemy.dialects.postgresql import insert session.execute(insert(MyTable) .values(my_entries) .on_conflict_do_nothing()) MySQL has the similar INSERT IGNORE clause, but S...
15
18
63,519,761
2020-8-21
https://stackoverflow.com/questions/63519761/python-typeerror-required-field-type-ignores-missing-from-module-in-jupyter
I have been having issues with my jupyter notebook for a few days. I didn't fix them at the time but have decided to now. Earlier whenever I executed anything in the jupyter notebook, It showed a lengthy list of errors in the terminal(not in the notebook). I tried the same in jupyterlab but again, the same error. I upg...
As stated here https://github.com/aiidateam/aiida-core/issues/3559 This might be due to ipython 5.8.0 incompatible with Python 3.8 issue.
10
20
63,570,108
2020-8-24
https://stackoverflow.com/questions/63570108/how-can-i-set-max-line-length-in-vscode-for-python
For JavaScript formatter works fine but not for Python. I have installed autopep8 but it seems that I can't set max line length. I tried this: "python.formatting.autopep8Args": [ "--max-line-length", "79", "--experimental" ] and my settings.json looks like this: { "workbench.colorTheme": "One Dark Pro", "git.autofetch...
From autopep8-usage, the default value of max-line-length is 79, so you can change to other value and have a try. About the effect of autopep8 in vscode, I made a test with the same settings as yours, like the following screenshot shows: every print sentence line-length is over 79, the first and the second print() par...
17
9
63,587,821
2020-8-25
https://stackoverflow.com/questions/63587821/divide-two-pandas-columns-of-lists-by-each-other
I have a df like this: col1 col2 [1,3,4,5] [3,3,6,2] [1,4,5,5] [3,8,4,3] [1,3,4,8] [8,3,7,2] Trying to divide the elements in the lists in col1 and col2 together to get what's in the result column: col1 col2 result [1,3,4,5] [3,3,6,2] [.33,1,.66,2.5] [1,4,5,5] [3,8,4,3] [.33,.5,1.25,1.66] [1,3,4,8] [8,3,7,2] [.33,1,.5...
You can use list comprehension with apply, this is conditional on both the lists being of same length df['result'] = df.apply(lambda x: [np.round(x['col1'][i]/x['col2'][i], 2) for i in range(len(x['col1']))], axis = 1) col1 col2 result 0 [1, 3, 4, 5] [3, 3, 6, 2] [0.33, 1.0, 0.67, 2.5] 1 [1, 4, 5, 5] [3, 8, 4, 3] [0.33...
8
5
63,587,766
2020-8-25
https://stackoverflow.com/questions/63587766/in-a-plotly-scatter-plot-how-do-you-join-two-set-of-points-with-a-line
I have the following code import plotly.graph_objs as go layout1= go.Layout(title=go.layout.Title(text="A graph",x=0.5), xaxis={'title':'x[m]'}, yaxis={'title':'y[m]','range':[-10,10]}) point_plot=[ go.Scatter(x=[3,4],y=[1,2],name="V0"), go.Scatter(x=[1,2],y=[1,1],name="V0"), go.Scatter(x=[5,6],y=[2,3],name="GT") ] go....
You can combine two V0 segments in a single scatter and add an extra point with np.nan to split two segments value as follows: import plotly.graph_objs as go import numpy as np layout1= go.Layout(title=go.layout.Title(text="A graph",x=0.5), xaxis={'title':'x[m]'}, yaxis={'title':'y[m]','range':[-10,10]}) point_plot=[ g...
6
3
63,580,313
2020-8-25
https://stackoverflow.com/questions/63580313/update-specific-subplot-axes-in-plotly
Setup: I'm tring to plot a subplots with plotly library, but can't figure out how to reference a specific subplots' axis to change its' name (or other properties). In Code 1 I show a simple example where I add two plots one on thop of the other with plotly.subplots.make_subplots. Code 1 import numpy as np from plotly...
With the help from this answer I as able to solve it, by referencing the xaxis for plot on the position row=1, col=1 and the xaxis1 for the plot on the row=2, col=1 position. The full solution is in Code 1. Code 1: import numpy as np from plotly.subplots import make_subplots from math import exp fig = make_subplots(2, ...
7
15
63,584,368
2020-8-25
https://stackoverflow.com/questions/63584368/pip-install-psycopg2-error-command-x86-64-linux-gnu-gcc-failed-with-exit-st
I get the following error when trying to install psycopg2: (venv) root@scw-determined-panini:/app# pip install psycopg2 Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/a8/8f/1c5690eebf148d1d1554fc00ccf9101e134636553dbb75bdfef4f85d7647/psycopg2-2.8.5.tar.gz Building wheels for collected package...
For Ubuntu use sudo apt install libpq-dev thanks
22
89
63,581,308
2020-8-25
https://stackoverflow.com/questions/63581308/edit-yaml-file-with-bash
I'm trying to edit the following YAML file db: host: 'x.x.x.x.x' main: password: 'password_main' admin: password: 'password_admin' To edit the host part, I got it working with sed -i "/^\([[:space:]]*host: \).*/s//\1'$DNS_ENDPOINT'/" config.yml But I can't find a way to update the password for main and admin (which a...
$ awk -v new="'sumthin'" 'prev=="main:"{sub(/\047.*/,""); $0=$0 new} {prev=$1} 1' file db: host: 'x.x.x.x.x' main: password: 'sumthin' admin: password: 'password_admin' or if your new text can contain escape sequences that you don't want expanded (e.g. \t or \n), as seems likely when setting a password, then: new="'su...
17
5
63,553,845
2020-8-24
https://stackoverflow.com/questions/63553845/pandas-read-json-valueerror-protocol-not-known
I ran the following code a while ago and it worked but now there is the following error. How to solve it? ValueError: protocol not known. import json temp = json.dumps([status._json for status in tweet]) # create JSON newdf = pd.read_json(temp, orient='records')
As far as I could debug this issue is caused by an update of pandas. The 1.1.0 update had changed few things on the read_json function. I could make my code work when setting pandas version to 1.0.5 https://pandas.pydata.org/docs/whatsnew/v1.1.0.html
23
7
63,577,356
2020-8-25
https://stackoverflow.com/questions/63577356/get-hour-of-year-from-a-datetime
Is there a simple way to obtain the hour of the year from a datetime? dt = datetime(2019, 1, 3, 00, 00, 00) # 03/01/2019 00:00 dt_hour = dt.hour_of_year() # should be something like that Expected output: dt_hour = 48 It would be nice as well to obtain minutes_of_year and seconds_of_year
One way of implementing this yourself is this: def hour_of_year(dt): beginning_of_year = datetime.datetime(dt.year, 1, 1, tzinfo=dt.tzinfo) return (dt - beginning_of_year).total_seconds() // 3600 This first creates a new datetime object representing the beginning of the year. We then compute the time since the beginni...
11
6
63,563,496
2020-8-24
https://stackoverflow.com/questions/63563496/exclude-tests-in-pytest-configuration-file
I would like to be able to exclude instead of include certain python test files in the pytest.ini configuration file. According to the docs including tests boils down to something like this: # content of pytest.ini [pytest] pytest_files=test_main.py test_common.py To exclude files however, only command line options ar...
You can add any command line options in pytest.ini under addopts. In your case this should work: pytest.ini [pytest] addopts = --ignore=test_common.py As has been noted in the comments, --ignore takes a path (relative or absolute), not just a module name. From the output of pytest -h: --ignore=path ignore path during...
14
20
63,520,908
2020-8-21
https://stackoverflow.com/questions/63520908/does-imblearn-pipeline-turn-off-sampling-for-testing
Let us suppose the following code (from imblearn example on pipelines) ... # Instanciate a PCA object for the sake of easy visualisation pca = PCA(n_components=2) # Create the samplers enn = EditedNearestNeighbours() renn = RepeatedEditedNearestNeighbours() # Create the classifier knn = KNN(1) # Make the splits X_train...
Great question(s). To go through them in the order you posted: First, it is clear to me that over-, under-, and mixed-sampling are procedures to be applied to the training set, not to the test/validation set. Please correct me here if I am wrong. That is correct. You certainly do not want to test (whether that be o...
10
13
63,561,537
2020-8-24
https://stackoverflow.com/questions/63561537/how-to-mark-individual-parameterized-tests-with-a-marker
I have been trying to parameterize my tests using @pytest.mark.parametrize, and I have a marketer @pytest.mark.test("1234"), I use the value from the test marker to do post the results to JIRA. Note the value given for the marker changes for every test_data. Essentially the code looks something like below. @pytest.mark...
It's explained here in the documentation: https://docs.pytest.org/en/stable/example/markers.html#marking-individual-tests-when-using-parametrize To show it here as well, it'd be: @pytest.mark.foo @pytest.mark.parametrize(("n", "expected"), [ pytest.param(1, 2, marks=pytest.mark.T1), pytest.param(2, 3, marks=pytest.mark...
11
15
63,552,044
2020-8-23
https://stackoverflow.com/questions/63552044/how-to-extract-feature-vector-from-single-image-in-pytorch
I am attempting to understand more about computer vision models, and I'm trying to do some exploring of how they work. In an attempt to understand how to interpret feature vectors more I'm trying to use Pytorch to extract a feature vector. Below is my code that I've pieced together from various places. import torch imp...
All the default nn.Modules in pytorch expect an additional batch dimension. If the input to a module is shape (B, ...) then the output will be (B, ...) as well (though the later dimensions may change depending on the layer). This behavior allows efficient inference on batches of B inputs simultaneously. To make your co...
7
8
63,528,693
2020-8-21
https://stackoverflow.com/questions/63528693/whats-the-difference-between-mock-magicmockspec-someclass-and-mock-create-aut
I'm trying to understand the difference between these two mock constructs and when is it appropriate to use either. I tested it in the interpreter, e.g.: >>> mm = mock.MagicMock(spec=list) >>> ca = mock.create_autospec(list) >>> mm <MagicMock spec='list' id='140372375801232'> >>> mm() <MagicMock name='mock()' id='14037...
The main difference between using the spec argument and using create_autospec is recursiveness. In the first case, the object itself is specced, while the called object is not: >>> mm = mock.MagicMock(spec=list) >>> mm <MagicMock spec='list' id='2868486557120'> >>> mm.foo Traceback (most recent call last): File "<stdin...
14
13
63,550,773
2020-8-23
https://stackoverflow.com/questions/63550773/dynamic-adding-function-to-class-and-make-it-as-bound-method
I am new in python. I want to write an add_function method for this class to add any function to my class dynamically. This function can manipulate some attributes of my class but it is written outside the class. Assume this class and its method. import numpy as np import feature_function as ffun class Features: def __...
Your addfunction binds its argument to the instance self, not to the class. Bind the argument to the class, e.g. via type(self) or a classmethod: class Features: ... # Add function dynamically by user @classmethod def add_function(cls, name, methodToRun, type ): name2 = '__' + name setattr(cls, mangle_attr(self, name2)...
6
5
63,548,053
2020-8-23
https://stackoverflow.com/questions/63548053/python-fill-missing-values-according-to-frequency
I have seen a lot of cases missing values are either filled by mean or medians. I was wondering how can we fill misssing values with frequency. Here is my setup: import numpy as np import pandas as pd df = pd.DataFrame({'sex': [1,1,1,1,0,0,np.nan,np.nan,np.nan]}) df['sex_fillna'] = df['sex'].fillna(df.sex.mode()[0]) pr...
Check with value_counts + np.random.choice s = df.sex.value_counts(normalize=True) df['sex_fillna'] = df['sex'] df.loc[df.sex.isna(), 'sex_fillna'] = np.random.choice(s.index, p=s.values, size=df.sex.isna().sum()) df Out[119]: sex sex_fillna 0 1.0 1.0 1 1.0 1.0 2 1.0 1.0 3 1.0 1.0 4 0.0 0.0 5 0.0 0.0 6 NaN 0.0 7 NaN 1....
12
6
63,530,701
2020-8-21
https://stackoverflow.com/questions/63530701/python-package-to-plot-two-heatmaps-in-one-split-each-square-into-two-triangles
I've been searching around but couldn't find an easy solution to plot two heatmaps in one graphic by having each square in the heatmap split into two triangles (similar to the attached graphic I saw in a paper). Does anybody know a Python package that is able to do this? I tried seaborn but I don't think it has an easy...
plt.tripcolor colors a mesh of triangles similar to how plt.pcolormesh colors a rectangular mesh. Also similar to pcolormesh, care has to be taken that there is one row and one column of vertices less than there are triangles. Furthermore, the arrays need to be made 1D (np.ravel). All this renumbering to 1D can be a bi...
8
12
63,533,664
2020-8-22
https://stackoverflow.com/questions/63533664/matplotlib-vertical-space-between-legend-symbols
I have an issue with customizing the legend of my plot. I did lot's of customizing but couldnt get my head around this one. I want the symbols (not the labels) to be equally spaced in the legend. As you can see in the example, the space between the circles in the legend, gets smaller as the circles get bigger. any idea...
It's a bit tricky, but you could measure the legend elements and reposition them to have a constant inbetween distance. Due to the pixel positioning, the plot can't be resized afterwards. I tested the code inside PyCharm with the 'Qt5Agg' backend. And in a Jupyter notebook, both with %matplotlib inline and with %matplo...
7
3
63,538,588
2020-8-22
https://stackoverflow.com/questions/63538588/python-dictionary-object-syntaxerror-expression-cannot-contain-assignment-per
I am creating a dictionary object, it gets created while I use "Statement 1", however I get an error message while try create a dictionary object using same keys and values with "Statement 2". Statement 1: dmap = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'} Statement 2: dmap = dict(0='Mon', 1...
dict is a regular callable which accepts keyword arguments. As per the Python syntax, keyword arguments are of the form identifier '=' expression. An identifier may not start with a digit, which excludes number literals. keyword_item ::= identifier "=" expression That dict does by default create a dictionary that acc...
8
6
63,528,797
2020-8-21
https://stackoverflow.com/questions/63528797/how-do-i-count-the-letters-in-llanfairpwllgwyngyllgogerychwyrndrobwllllantysilio
How do I count the letters in Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch? print(len('Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')) Says 58 Well if it was that easy I wouldn't be asking you, now would I?! Wikipedia says (https://en.wikipedia.org/wiki/Llanfairpwllgwyngyll#Placename_and_to...
Like many problems to do with strings, this can be done in a simple way with a regex. >>> word = 'Llanfairpwllgwyn|gyllgogerychwyrndrobwllllantysiliogogogoch' >>> import re >>> pattern = re.compile(r'ch|dd|ff|ng|ll|ph|rh|th|[^\W\d_]', flags=re.IGNORECASE) >>> len(pattern.findall(word)) 51 The character class [^\W\d_] ...
82
58
63,533,237
2020-8-22
https://stackoverflow.com/questions/63533237/how-to-see-where-exactly-torch-is-installed-pip-vs-conda-torch-installation
On my machine i can't "pip install torch" - i get infamous "single source externally managed error" - i could not fix it and used "conda install torch" from anaconda. Still, checking version is easy - torch.__version__ But how to see where is it installed -the home dir of torch? Suppose if I had had both torches instal...
You can get torch module location which is imported in your script import torch print(torch.__file__)
7
14
63,532,921
2020-8-22
https://stackoverflow.com/questions/63532921/deep-copy-of-list-in-python
CODE IN PYCHARM [1]: https://i.sstatic.net/aBP1r.png I tried to make a deep copy of a list l, but seems like the slicing method doesn't work somehow?I don't want the change in x to be reflected in l. So how should I make a deep copy and what is wrong in my code? This was my code- def processed(matrix,r,i): matrix[r].ap...
Your code does indeed succeed in creating a shallow copy. This can be seen by inspecting the IDs of the two outer lists, and noting that they differ. >>> id(l) 140505607684808 >>> id(x) 140505607684680 Or simply comparing using is: >>> x is l False However, because it is a shallow copy rather than a deep copy, the co...
6
11
63,529,904
2020-8-21
https://stackoverflow.com/questions/63529904/how-do-i-address-oserror-mysql-config-not-found-error-during-elastic-beanstal
Problem I am trying to deploy a very simple app on Elastic Beanstalk with a small database backend. I try to install mysqlclient as part of the process outlined by AWS here. However, when I deploy my app, I get the following error from my Elastic Beanstalk logs as it tries to download the package: Collecting mysqlclien...
For Amazon linux 2 you should be able to install it with yum. Thus, you can have in your .ebextensions a file called, e.g. 01_packages.config with the content: packages: yum: MySQL-python: [] You can add further yum dependencies if you require more.
11
9
63,529,127
2020-8-21
https://stackoverflow.com/questions/63529127/identify-all-overlapping-tuples-in-list
I've currently got a list of tuples (though I control creation of the list and tuples, so they could be altered in type if needed). Each tuple has a start and end integer and a string with an ID for that range's source. What I'm trying to do is identify all of the overlapping ranges within the tuples. Currently I have ...
This should work: import operator def get_overlaps(end, remaining): output = [] for r in remaining: if r[0] < end: # starts before the end output.append(r[2]) continue break return output def get_all_overlaps(lst): # thanks @Elan-R for this simplification for i, (start, end, name) in enumerate(lst): overlaps = get_over...
6
2
63,521,088
2020-8-21
https://stackoverflow.com/questions/63521088/destroy-object-of-class-python
Hi i'm trying to destroy a class object if the condition of an if statement(inside a while is met) global variablecheck class createobject: def __init__(self,userinput): self.userinput = input self.method() def method(self): while True: if self.userinput == variablecheck print('the object created using this class is st...
Think of it that way: you're asking a class to self-destruct using an inner method, which is kind of like trying to eat your own mouth. Luckily for you, Python features garbage collection, meaning your class will be automatically destroyed once all of its references have gone out of scope. If you need to do something s...
8
27
63,518,441
2020-8-21
https://stackoverflow.com/questions/63518441/how-to-read-a-bearer-token-from-postman-into-python-code
I am trying to create an API that receives arguments from postman. The body of the api contains two arguments: { "db":"EUR", "env":"test" } I parsed these two arguments in the code as below: parser = reqparse.RequestParser() parser.add_argument('fab', type=str, required=True, help='Fab name must be provided.') parser....
The Bearer token is sent in the headers of the request as 'Authorization' header, so you can get it in python flask as follows: headers = flask.request.headers bearer = headers.get('Authorization') # Bearer YourTokenHere token = bearer.split()[1] # YourTokenHere
10
26
63,516,924
2020-8-21
https://stackoverflow.com/questions/63516924/typeerror-init-got-an-unexpected-keyword-argument-requote
Traceback (most recent call last): File "Chiyo.py", line 1, in <module> import discord File "/home/ubuntu/.local/lib/python3.6/site-packages/discord/__init__.py", line 25, in <module> from .client import Client File "/home/ubuntu/.local/lib/python3.6/site-packages/discord/client.py", line 34, in <module> import aiohttp...
Install yarl 1.4.2 pip install -U yarl==1.4.2
11
14
63,485,231
2020-8-19
https://stackoverflow.com/questions/63485231/whats-the-computational-complexity-of-iloc-in-pandas-dataframes
I'm trying to understand what's the execution complexity of the iloc function in pandas. I read the following Stack Exchange thread (Pandas DataFrame search is linear time or constant time?) that: "accessing single row by index (index is sorted and unique) should have runtime O(m) where m << n_rows" mentioning that i...
There likely isn't one answer for the runtime complexity of iloc. The method accepts a huge range of input types, and that flexibility necessarily comes with costs. These costs are likely to include both large constant factors and non-constant costs that are almost certainly dependent on the way in which it is used. On...
10
5
63,494,812
2020-8-19
https://stackoverflow.com/questions/63494812/how-can-i-distinguish-a-digitally-created-pdf-from-a-searchable-pdf
I am currently analyzing a set of PDF files. I want to know how many of the PDF files fall in those 3 categories: Digitally Created PDF: The text is there (copyable) and it is guaranteed to be correct as it was created directly e.g. from Word Image-only PDF: A scanned document Searchable PDF: A scanned document, but a...
With PyMuPDF you can easily remove all text as is required for @ypnos' suggestion. As an alternative, with PyMuPDF you can also check whether text is hidden in a PDF. In PDF's relevant "mini-language" this is triggered by the command 3 Tr ("text render mode", e.g. see page 402 of https://www.adobe.com/content/dam/acom/...
15
4
63,503,512
2020-8-20
https://stackoverflow.com/questions/63503512/python-type-hinting-own-class-in-method
Edit: I notice people commenting about how the type hint should not be used with __eq__, and granted, it shouldn't. But that's not the point of my question. My question is why can't the class be used as type hint in the method parameters, but can be used in the method itself? Python type hinting has proven very useful...
The name Foo doesn't yet exist, so you need to use 'Foo' instead. (mypy and other type checkers should recognize this as a forward reference.) def __eq__(self, other: 'Foo'): return self.id == other.id Alternately, you can use from __future__ import annotations which prevents evaluation of all annotations and simply ...
27
36
63,502,556
2020-8-20
https://stackoverflow.com/questions/63502556/pyspark-read-nested-json-from-a-string-type-column-and-create-columns
I have a dataframe in PySpark with 3 columns - json, date and object_id: ----------------------------------------------------------------------------------------- |json |date |object_id| ----------------------------------------------------------------------------------------- |{'a':{'b':0,'c':{'50':0.005,'60':0,'100':0...
There are 2 ways to do it: use the get_json_object function, like this: import pyspark.sql.functions as F df = spark.createDataFrame(['{"a":{"b":0,"c":{"50":0.005,"60":0,"100":0},"d":0.01,"e":0,"f":2}}', '{"a":{"m":0,"n":{"50":0.005,"60":0,"100":0},"d":0.01,"e":0,"f":2}}', '{"g":{"h":0,"j":{"50":0.005,"80":0,"100":0}...
8
15
63,483,246
2020-8-19
https://stackoverflow.com/questions/63483246/how-to-call-an-api-from-another-api-in-fastapi
I was able to get the response of one API from another but unable to store it somewhere(in a file or something before returning the response) response=RedirectResponse(url="/apiname/") (I want to access a post request with header and body) I want to store this response content without returning it. Yes, if I return t...
I didn't exactly get the way to store response without returning using fastapi/starlette directly. But I found a workaround for completing this task. For the people trying to implement same thing, Please consider this way. import requests def test_function(request: Request, path_parameter: path_param): request_exampl...
17
14
63,491,991
2020-8-19
https://stackoverflow.com/questions/63491991/how-to-use-the-ccf-method-in-the-statsmodels-library
I am having some trouble with the ccf() method in the (Python) statsmodels library. The equivalent operation works fine in R. ccf produces a cross-correlation function between two variables, A and B in my example. I am interested to understand the extent to which A is a leading indicator for B. I am using the following...
The statsmodels ccf function only produces forward lags, i.e. Corr(x_[t+k], y_[t]) for k >= 0. But one way to compute the backwards lags is by reversing the order of the both the input series and the output. backwards = smt.ccf(test['A'][::-1], test['B'][::-1], adjusted=False)[::-1] forwards = smt.ccf(test['A'], test['...
8
14
63,491,221
2020-8-19
https://stackoverflow.com/questions/63491221/modulenotfounderror-no-module-named-virtualenv-seed-embed-via-app-data-when-i
I was creating a new virtual environment on Ubuntu 20.04: $ virtualenv my_env But it gave an error: ModuleNotFoundError: No module named 'virtualenv.seed.embed.via_app_data' Other info: $ virtualenv --version virtualenv 20.0.17 from /usr/lib/python3/dist-packages/virtualenv/__init__.py
Try to create the virtual environment using directly venv module python3 -m venv my_env
113
65
63,484,742
2020-8-19
https://stackoverflow.com/questions/63484742/how-to-write-in-env-file-from-python-code
I want to write in the .env using python code. This is what I tried but it's not working:- os.environ['username'] = 'John' os.environ['email'] = 'abc@gmail.com'
os.environ is a Python dictionary containing the environment. In order to change the environment variables in your currently running process, and any children process spawned with fork, you should use os.putenv as follows: import os os.putenv("username", "John") os.putenv("email", "abc@gmail.com") Do notice, this chan...
8
8
63,480,172
2020-8-19
https://stackoverflow.com/questions/63480172/permanently-saving-train-data-in-google-colab
I have train data for 50GB. My google drive capacity was 15GB so I upgraded it to 200GB and I uploaded my train data to my google drive I connected to colab, but I can not find my train data in colab session, So I manually uploaded to colab which has 150GB capacity. It says, it will be deleted when my colab connection ...
The way you can do this is to mount your google drive into colab environment. Assume your files are kept under a folder named myfolder in your google drive. This is what I would suggest, do this before you read/write any file: import os from google.colab import drive MOUNTPOINT = '/content/gdrive' DATADIR = os.path.joi...
7
7
63,459,424
2020-8-17
https://stackoverflow.com/questions/63459424/how-to-add-multiple-graphs-to-dash-app-on-a-single-browser-page
How do I add multiple graphs show in in picture on a same page? I am trying to add html.Div components to following code to update the page layout to add more graphs like that on single page, but these newly added graphs do not get shown on a page, only old graph is shown in picture is visible. What element should I m...
To add the same figure multiple times, you just need to extend your app.layout. I have extended you code below as an example. import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import pandas as pd import plotly.express as px external_stylesheet...
19
50
63,400,683
2020-8-13
https://stackoverflow.com/questions/63400683/python-logging-with-loguru-log-request-params-on-fastapi-app
I have a fastapi application and I want to log every request made on it. I'm trying to use loguru and uvicorn for this, but I don't know how to print the headers and request params (if have one) associated with each request. I want something like this: INFO 2020-08-13 13:36:33.494 uvicorn.protocols.http.h11_impl:send -...
A dependency on a router level could be used (thanks to @lsabi in the comments below): import sys import uvicorn from fastapi import FastAPI, Request, APIRouter, Depends from loguru import logger from starlette.routing import Match logger.remove() logger.add(sys.stdout, colorize=True, format="<green>{time:HH:mm:ss}</gr...
10
19
63,392,426
2020-8-13
https://stackoverflow.com/questions/63392426/how-to-use-tailwindcss-with-django
How to use all features of TailwindCSS in a Django project (not only the CDN), including a clean workflow with auto-reloading and CSS minify step to be production-ready?
There are (at least) 3 different methods to install Tailwind with Django properly. 1st method: NPM This is the preferred method if you need node in your project (e.g : add plugins like Daisy UI, or have a SPA) Installing tailwindCSS and build/minify processes Create a new directory within your Django project, in which...
43
106
63,448,679
2020-8-17
https://stackoverflow.com/questions/63448679/typeerror-init-subclass-takes-no-keyword-arguments
I'm trying to create a metaclass but when I assign it to another class I receive the error: TypeError: __init_subclass__() takes no keyword arguments But I don't implement any __init_subclass__. Why is this function being called? class Meta(type): def __new__(cls, name, bases, dct): return super().__new__(cls, name, ...
Change meta to metaclass. Any keyword arguments passed to the signature of your class are passed to its parent's __init_subclass__ method. Since you entered meta instead of metaclass this meta kwarg is passed to its parent's (object) __init_subclass__ method: >>> object.__init_subclass__(meta=5) TypeError: __init_subcl...
16
20
63,449,011
2020-8-17
https://stackoverflow.com/questions/63449011/why-do-i-get-cuda-out-of-memory-when-running-pytorch-model-with-enough-gpu-memo
I am asking this question because I am successfully training a segmentation network on my GTX 2070 on laptop with 8GB VRAM and I use exactly the same code and exactly the same software libraries installed on my desktop PC with a GTX 1080TI and it still throws out of memory. Why does this happen, considering that: The ...
Most of the people (even in the thread below) jump to suggest that decreasing the batch_size will solve this problem. In fact, it does not in this case. For example, it would have been illogical for a network to train on 8GB VRAM and yet to fail to train on 11GB VRAM, considering that there were no other applications c...
8
12
63,460,126
2020-8-18
https://stackoverflow.com/questions/63460126/typeerror-type-object-is-not-subscriptable-in-a-function-signature
Why am I receiving this error when I run this code? Traceback (most recent call last): File "main.py", line 13, in <module> def twoSum(self, nums: list[int], target: int) -> list[int]: TypeError: 'type' object is not subscriptable nums = [4,5,6,7,8,9] target = 13 def twoSum(self, nums: list[int], target: int) -> list[...
The following answer only applies to Python < 3.9 The expression list[int] is attempting to subscript the object list, which is a class. Class objects are of the type of their metaclass, which is type in this case. Since type does not define a __getitem__ method, you can't do list[...]. To do this correctly, you need t...
59
69
63,403,758
2020-8-13
https://stackoverflow.com/questions/63403758/is-oop-possible-using-discord-py-without-cogs
These last few days, I've been trying to adapt the structure of a discord bot written in discord.py to a more OOP one (because having functions lying around isn't ideal). But I have found way more problems that I could have ever expected. The thing is that I want to encapsulate all my commands into a single class, but ...
To register the command you should use self.add_command(setup), but you can't have the self argument in the setup method, so you could do something like this: from discord.ext import commands class MyBot(commands.Bot): def __init__(self, command_prefix, self_bot): commands.Bot.__init__(self, command_prefix=command_pref...
10
19
63,414,448
2020-8-14
https://stackoverflow.com/questions/63414448/pip3-throws-undefined-symbol-xml-sethashsalt
I am having python 3.6.8 on oracle Linux EL7 I installed pip3 using yum install python36-pip however, when ever I invoke pip3 it is having library error pip3 Traceback (most recent call last): File "/bin/pip3", line 8, in <module> from pip import main File "/usr/lib/python3.6/site-packages/pip/__init__.py", line 42, i...
libexpat.so.1 pointing to wrong location. Fixed it with export LD_LIBRARY_PATH=/lib64/:${LD_LIBRARY_PATH} ldd /usr/lib64/python3.6/lib-dynload/pyexpat.cpython-36m-x86_64-linux-gnu.so linux-vdso.so.1 => (0x00007fff073f1000) libexpat.so.1 => /lib64/libexpat.so.1 (0x00007f9ba53ce000) libpython3.6m.so.1.0 => /lib64/libpyt...
7
13
63,443,583
2020-8-17
https://stackoverflow.com/questions/63443583/seaborn-valueerror-zero-size-array-to-reduction-operation-minimum-which-has-no
I ran this scatter plot seaborn example from their own website, import seaborn as sns; sns.set() import matplotlib.pyplot as plt tips = sns.load_dataset("tips") # this works: ax = sns.scatterplot(x="total_bill", y="tip", data=tips) # But adding 'hue' gives the error below: ax = sns.scatterplot(x="total_bill", y="tip", ...
This issue seems to be resolved for matplotlib==3.3.2. seaborn: Scatterplot fails with matplotlib==3.3.1 #2194 With matplotlib version 3.3.1 A workaround is to send a list to hue, by using .tolist() Use hue=tips.time.tolist(). The normal behavior adds a title to the legend, but sending a list to hue does not add...
36
37
63,404,192
2020-8-13
https://stackoverflow.com/questions/63404192/pip-install-tensorflow-cannot-find-file-called-client-load-reporting-filter-h
I keep failing to run pip install on the tensorflow package. First it downloads the .whl file, then goes through a bunch of already satisfied requirements until it gets to installing collected packages: tensorflow, at which point here's the error I get: ERROR: Could not install packages due to an EnvironmentError: [Err...
I hit the same issue on Win10. Rather than renaming my filesystem, I found a good solution in this Python documentation. To summarize the instructions there to change MAX_PATH, either: Enable the "Enable Win32 long paths" group policy: Run gpedit (or searching for "Edit Group Policy" in the Control Panel) Find the "E...
14
40
63,449,770
2020-8-17
https://stackoverflow.com/questions/63449770/oserror-cannot-load-library-gobject-2-0-error-0x7e
I installed the package weasyprint according to the instructions Installing weasyprint (Django project). My system: win 10. I have installed gtk3 and it is present in my PATH import weasyprint ... @staff_member_required def order_admin_pdf(request, order_id): # Получаем заказ по ID: order = get_object_or_404(Order, id...
Starting from Python 3.8 DLL dependencies for extension modules and DLLs loaded with ctypes on Windows are now resolved more securely. Only the system paths, the directory containing the DLL or PYD file, and directories added with add_dll_directory() are searched for load-time dependencies. Specifically, PATH and the c...
21
13
63,421,086
2020-8-14
https://stackoverflow.com/questions/63421086/modulenotfounderror-no-module-named-webdriver-manager-error-even-after-instal
I've installed webdrivermanager on my windows-10 system C:\Users\username>pip install webdrivermanager Requirement already satisfied: webdrivermanager in c:\python\lib\site-packages (0.8.0) Requirement already satisfied: lxml in c:\python\lib\site-packages (from webdrivermanager) (4.5.1) Requirement already satisfied: ...
Update (thanks to Vishal Kharde) The documentation now suggests: pip install webdriver-manager Solution: Install it like that: pip install webdriver_manager instead of pip install webdrivermanager. Requirements: The newest version, according to the documentation supports python 3.6 or newer versions: Reference: htt...
44
87
63,467,815
2020-8-18
https://stackoverflow.com/questions/63467815/how-to-access-columntransformer-elements-in-gridsearchcv
I wanted to find out the correct naming convention when referring to individual preprocessor included in ColumnTransformer (which is part of a pipeline) in param_grid for grid_search. Environment & sample data: import seaborn as sns from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.impute ...
You were close, the correct way to declare it is like this: param_grid = {'preprocessor__num__imputer__strategy' : ['mean', 'median'], 'preprocessor__num__discritiser__n_bins' : range(5,10), 'classiffier__C' : [0.1, 10, 100], 'classiffier__solver' : ['liblinear', 'saga']} Here is the full code: import seaborn as sns f...
8
13
63,466,010
2020-8-18
https://stackoverflow.com/questions/63466010/what-is-the-recommended-way-to-access-data-from-r-data-table-in-python-can-i-av
Is there some recommended way to pass data from R (in the form of data.table) to Python without having to save the data to disc? I know I could use python modules from R using reticulate (and I suppose the same thing can be done on the other side using rpy2), but from what I've read that hurts the overall performance o...
There is no recommended way. In theory you have to dump R data.frame to disk and read it in python. In practice (assuming production grade operating system), you can use "RAM disk" location /dev/shm/ so you essentially write data to a file that resides in RAM memory and then read it from RAM directly, without the need ...
11
7
63,460,213
2020-8-18
https://stackoverflow.com/questions/63460213/how-to-define-colors-in-a-figure-using-plotly-graph-objects-and-plotly-express
There are many questions and answers that touch upon this topic one way or another. With this contribution I'd like to clearly show why an easy approch such as marker = {'color' : 'red'} will work for plotly.graph_objects (go), but color='red' will not for plotly.express (px) although color is an attribute of both px.L...
First, if an explanation of the broader differences between go and px is required, please take a look here and here. And if absolutely no explanations are needed, you'll find a complete code snippet at the very end of the answer which will reveal many of the powers with colors in plotly.express Part 1: The Essence: It...
38
63
63,432,473
2020-8-16
https://stackoverflow.com/questions/63432473/access-to-fetch-url-been-blocked-by-cors-policy-no-access-control-allow-orig
I'm am trying to fetch a serverless function from a react app in development mode with the following code. let response = await fetch(url, { method: 'POST', mode: 'cors', body: "param=" + paramVar, }) .then(response => response.json()); The backend function is a Python Cloud function with the following code: def main(...
There was actually a bug in the backend that was only triggered by some additional headers added by the browser. In that particular case, the server was returning a 404 error which wouldn't contain my header definitions and would cause the CORS policy block. I was only able to identify the bug after I used devtools to ...
22
-3
63,388,030
2020-8-13
https://stackoverflow.com/questions/63388030/warningtensorflowwrite-grads-will-be-ignored-in-tensorflow-2-0-for-the-tens
I am using the following lines of codes to visualise the gradients of an ANN model using tensorboard tensorboard_callback = tf.compat.v1.keras.callbacks.TensorBoard(log_dir='./Graph', histogram_freq=1, write_graph = True, write_grads =True, write_images = False) tensorboard_callback .set_model(model) %tensorboard --lo...
Write_Grads was not implemented in TF2.x. This is one of the highly expected feature request that is still open. Please check this GitHub issue as feature request. So, we only need to import TF1.x modules and use write_grads as shown in the following code. # Load the TensorBoard notebook extension %load_ext tensorboard...
7
6
63,475,461
2020-8-18
https://stackoverflow.com/questions/63475461/unable-to-import-opengl-gl-in-python-on-macos
I am using OpenGL to render a scene in python. My code works perfectly fine on windows but, for some reason, I'm having issues when importing opengl.gl on MacOS. The issue arises when calling from OpenGL.GL import ... in both python scripts and the python console. More specifically here is the exact call in my script: ...
This error is because Big Sur no longer has the OpenGL library nor other system libraries in standard locations in the file system and instead uses a cache. PyOpenGL uses ctypes to try to locate the OpenGL library and it fails to find it. Fixing ctypes in Python so that it will find the library is the subject of this p...
13
33
63,379,968
2020-8-12
https://stackoverflow.com/questions/63379968/using-requirements-txt-to-automatically-install-packages-from-conda-channels-and
I'm trying to set a conda environment using a requirements.txt file that a coworker shared with me. My coworker uses Python in a Mac without Anaconda, and I'm using it in a Windows machine with Anaconda. The file requirements.txt was generated with the command pip freeze and looks like this: absl-py==0.7.1 affine==2.3....
Using requirements.txt with conda There's no problem at all using a requirements.txt file when creating a conda environment. In fact, you can also set additional channels at creation time: conda create --name my-env-name --file requirements.txt --channel <NAME_OF_CHANNEL> for example, in the case of the first package ...
15
22
63,436,496
2020-8-16
https://stackoverflow.com/questions/63436496/is-it-possible-to-have-python-ides-offer-autocompletion-for-dynamically-generate
Are there any tricks I can employ to get IDEs to offer code completion for dynamically generated class attributes? For instance class A: def __init__(self): setattr(self, "a", 5) This code will set the class attribute of A called a to the value of 5. But IDEs do not know about a and therefore you do not get code comp...
I believe you will find the answer here. In short, Pycharm currently does not (and probably in the observable future will not) support dynamic attributes. That's because it analyzes code statically, and can't "see" what attributes a class might have. On the other hand, when you run your code in (say) iPython, once an i...
18
15
63,472,664
2020-8-18
https://stackoverflow.com/questions/63472664/pandas-explode-function-not-working-for-list-of-string-column
To explode list like column to row, we can use pandas explode() function. My pandas' version '0.25.3' The given example worked for me and another answer of Stackoverflow.com works as expected but it doesn't work for my dataset. city nested_city 0 soto ['Soto'] 1 tera-kora ['Daniel'] 2 jan-thiel ['Jan Thiel'] 3 westpun...
You need to ensure that your column is of list type to be able to use pandas' explode(). Here is a working solution: from ast import literal_eval test_data['nested_city'] = test_data['nested_city'].apply(literal_eval) #convert to list type test_data['nested_city'].explode() To explode multiple columns at a time, you c...
10
26
63,439,648
2020-8-16
https://stackoverflow.com/questions/63439648/why-protobuf-is-smaller-in-memory-than-normal-dictlist-in-python
I have a large structure of primitive types within nested dict/list. The structure is quite complicated and doesn't really matter. If I represent it in python's built-in types (dict/list/float/int/str) it takes 1.1 GB, but if I store it in protobuf and load it to memory it is significantly smaller. ~250 MB total. I'm w...
"Simple" python objects, such as int or float, need much more memory than their C-counterparts used by protobuf. Let's take a list of Python integers as example compared to an array of integers, as for example in an array.array (i.e. array.array('i', ...)). The analysis for array.array is simple: discarding some overhe...
7
11
63,413,064
2020-8-14
https://stackoverflow.com/questions/63413064/how-to-build-hybrid-model-of-random-forest-and-particle-swarm-optimizer-to-find
I need to find optimal discount for each product (in e.g. A, B, C) so that I can maximize total sales. I have existing Random Forest models for each product that map discount and season to sales. How do I combine these models and feed them to an optimiser to find the optimum discount per product? Reason for model selec...
you can find a complete solution below ! The fundamental differences with your approach are the following : Since the Random Forest model takes as input the season feature, optimal discounts must be computed for every season. Inspecting the documentation of pyswarm, the con function yields an output that must comply w...
12
4
63,472,161
2020-8-18
https://stackoverflow.com/questions/63472161/google-coding-challenge-question-2020-unspecified-words
I got the following problem for the Google Coding Challenge which happened on 16th August 2020. I tried to solve it but couldn't. There are N words in a dictionary such that each word is of fixed length and M consists only of lowercase English letters, that is ('a', 'b', ...,'z') A query word is denoted by Q. The len...
I guess my first try would have been to replace the ? with a . in the query, i.e. change ?at to .at, and then use those as regular expressions and match them against all the words in the dictionary, something as simple as this: import re for q in queries: p = re.compile(q.replace("?", ".")) print(sum(1 for w in words i...
29
20
63,380,108
2020-8-12
https://stackoverflow.com/questions/63380108/indexing-different-sized-ranges-in-a-2d-numpy-array-using-a-pythonic-vectorized
I have a numpy 2D array, and I would like to select different sized ranges of this array, depending on the column index. Here is the input array a = np.reshape(np.array(range(15)), (5, 3)) example [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11] [12 13 14]] Then, list b = [4,3,1] determines the different range sizes for each co...
We can use broadcasting to generate an appropriate mask and then masking does the job - In [150]: a Out[150]: array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]) In [151]: b Out[151]: [4, 3, 1] In [152]: mask = np.arange(len(a))[:,None] < b In [153]: a.T[mask.T] Out[153]: array([0, 3, 6, 9, 1, 4, 7,...
9
6
63,370,330
2020-8-12
https://stackoverflow.com/questions/63370330/show-progress-bar-while-uploading-to-s3-using-presigned-url
I'm trying to upload a file in my s3 bucket using a pre-signed URL, it works perfectly and uploads the data to the bucket successfully, however, the files that I upload are very large and I need to be able to show the progress bar. I have tried many solutions available on StackOverflow and other blog posts but nothing ...
The following code would work fine for Python, I found it here import logging import argparse from boto3 import Session import requests logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class S3MultipartUploadUtil: """ AWS S3 Multipart Upload Uril """ def __init__(self, session: ...
9
3
63,457,762
2020-8-17
https://stackoverflow.com/questions/63457762/error-could-not-find-a-version-that-satisfies-the-requirement-pprint-from-r-r
I am trying to install a NLP suite on my macbook pro, which is updated to the most recent software version Catalina 10.15.6. So far, I have installed Anaconda 3.8, created a version 3.7 NLP environment by conda create -n NLP python=3.7, and activated the NLP environment by conda activate NLP. My next step is to install...
pprint is part of the standard library, therefore cannot be present in requirements.txt. If one of your requirements is stated to require pprint you'll get an error. To install without dependencies use the --no-deps command for pip. However, this does not guarantee that the installation actually worked as you are likel...
10
10
63,475,529
2020-8-18
https://stackoverflow.com/questions/63475529/what-is-r-called
I am seeing this for the first time. I wanted to know what the !r in the last line of the code called so that I can search about it. I found this piece of code on: https://adamj.eu/tech/2020/08/10/a-guide-to-python-lambda-functions/ class Puppy: def __init__(self, name, cuteness): self.name = name self.cuteness = cuten...
It's a format string conversion flag that tells the formatter to call repr on the object before formatting the string. Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().
7
13
63,471,726
2020-8-18
https://stackoverflow.com/questions/63471726/get-full-request-url-from-inside-apiview-in-django-rest-framework
Is there a method, or an attribute in request object that I can access to return me the URL exactly as the client requested? With the query params included? I've checked request.build_absolute_uri after looking at this question but it just returns the URL without the query params. I need the URL because my API response...
To get full path, including query string, you want request.get_full_path()
9
15
63,473,901
2020-8-18
https://stackoverflow.com/questions/63473901/python-dynamically-create-class-while-providing-arguments-to-init-subclass
How can I dynamically create a subclass of my class and provide arguments to its __init_subclass__() method? Example class: class MyClass: def __init_subclass__(cls, my_name): print(f"Subclass created and my name is {my_name}") Normally I'd implement my subclass as such: class MySubclass(MyClass, my_name="Ellis"): pas...
The basic documentation for type does not mention that it accepts an unlimited number of keyword-only arguments, which you would supply through the keywords in a class statement. The only place this is hinted in is in the Data Model in the section Creating the class object: Once the class namespace has been populated ...
9
12
63,464,944
2020-8-18
https://stackoverflow.com/questions/63464944/keras-loss-and-metrics-values-do-not-match-with-same-function-in-each
I am using keras with a custom loss function like below: def custom_fn(y_true, y_pred): # changing y_true, y_pred values systematically return mean_absolute_percentage_error(y_true, y_pred) Then I am calling model.compile(loss=custom_fn) and model.fit(X, y,..validation_data=(X_val, y_val)..) Keras is then saving loss ...
This blog post suggests that keras adds any regularisation used in the training when calculating the validation loss. And obviously, when calculating the metric of choice no regularisation is applied. This is why it occurs with any loss function of choice as stated in the question. This is something I could not find an...
7
5
63,463,514
2020-8-18
https://stackoverflow.com/questions/63463514/django-how-to-check-if-django-is-hitting-database-for-certain-query
I want to optimize the django app and for this I would like to know How can I check if my query is hitting database or I am getting result/return value from cached version? For example: products = Products.objects.filter(product_name__icontains="natural") if not products.exist(): return Response(...) total_products = p...
Check the lenth of connection.queries in this way, from django.conf import settings settings.DEBUG = True from django.db import connection print(len(connection.queries)) # do something with the database products = Products.objects.filter(product_name__icontains="natural") print(len(connection.queries)) # and execute th...
10
24
63,455,683
2020-8-17
https://stackoverflow.com/questions/63455683/when-is-asyncios-default-scheduler-fair
It's my understanding that asyncio.gather is intended to run its arguments concurrently and also that when a coroutine executes an await expression it provides an opportunity for the event loop to schedule other tasks. With that in mind, I was surprised to see that the following snippet ignores one of the inputs to asy...
whichever of the those executes first, they immediately await aprint() and give the scheduler the opportunity to run another coroutine if desired This part is a common misconception. Python's await doesn't mean "yield control to the event loop", it means "start executing the awaitable, allowing it to suspend us alo...
8
9
63,387,253
2020-8-13
https://stackoverflow.com/questions/63387253/pyspark-setting-executors-cores-and-memory-local-machine
So I looked at a bunch of posts on Pyspark, Jupyter and setting memory/cores/executors (and the associated memory). But I appear to be stuck - Question 1: I dont see my machine utilizing either the cores or the memory. Why? Can I do some adjustments to the excutors/cores/memory to optimize speed of reading the file? Qu...
spark.sparkContext.stop() spark = SparkSession.builder.config(conf=conf).getOrCreate() df = spark.read.json("../Data/inasnelylargefile.json.gz") Add this: df.show() ##OR df.persist() The comparison you are doing is not apples to apples, spark performs lazy evaluation, meaning if you don't call an action over your ope...
12
2
63,446,690
2020-8-17
https://stackoverflow.com/questions/63446690/how-to-pack-a-python-to-exe-while-keeping-py-source-code-editable
I am creating a python script that should modify itself and be portable. I can achieve each one of those goals separately, but not together. I use cx_freeze or pyinstaller to pack my .py to exe, so it's portable; but then I have a lot of .pyc compiled files and I can't edit my .py file from the software itself. Is ther...
First define your main script (cannot be changed) main_script.py. In a subfolder (e.g. named data) create patch_script.py main_script.py: import sys sys.path.append('./data') import patch_script inside the subfolder: data\patch_script.py: print('This is the original file') In the root folder create a spec file e.g. by...
10
4
63,376,024
2020-8-12
https://stackoverflow.com/questions/63376024/vs-code-intellisense-not-working-with-conda-python-environment
Intellisense: not working with conda (above), working fine when normal Python (below) As shown above, Intellisense does not work in VS Code when Conda Environment is set as Python interpreter, it is just keeps “Loading…”. When normal Python interpreter is set (that comes when installing Python extension), Intellisense ...
I found a similar problem, they solve it through explicitly set the python.pythonPath, you can refer to this page. In your problem, only when selecting the conda interpreter the Intellisense not work as the Intellisense was provided by the Language Server, Could you try these? Select a different Language Server, The L...
12
9
63,442,415
2020-8-16
https://stackoverflow.com/questions/63442415/changing-font-size-of-all-qlabel-objects-pyqt5
I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size. How...
While the provided answers should have already given you enough suggestions, I'd like to add some insight. Are there python sources for Qt? First of all, you cannot find "the class written in python", because (luckily) there's none. PyQt is a binding: it is an interface to the actual Qt library, which is written in C++...
8
15
63,419,097
2020-8-14
https://stackoverflow.com/questions/63419097/prefect-how-to-avoid-rerunning-a-task
In Prefect, suppose I have some pipeline which runs f(date) for every date in a list, and saves it to a file. This is a pretty common ETL operation. In airflow, if I run this once, it will backfill for all historical dates. If I run it again, it will know that the task has been run, and only run any new tasks that have...
Prefect has many first-class ways of handling caching, depending on how much control you want. For every task, you can specify whether results should be cached, how long they should be cached, and how the cache should be invalidated (age, different inputs to the task, flow parameter values, etc.). The simplest way to c...
10
14
63,399,459
2020-8-13
https://stackoverflow.com/questions/63399459/how-to-save-the-browser-sessions-in-selenium
I am using Selenium to Log In to an account. After Logging In I would like to save the session and access it again the next time I run the python script so I don't have to Log In again. Basically I want to chrome driver to work like the real google chrome where all the cookies/sessions are saved. This way I don't have ...
This is the solution I used: # I am giving myself enough time to manually login to the website and then printing the cookie time.sleep(60) print(driver.get_cookies()) # Than I am using add_cookie() to add the cookie/s that I got from get_cookies() driver.add_cookie({'domain': ''}) This may not be the best way to imple...
13
4
63,436,120
2020-8-16
https://stackoverflow.com/questions/63436120/django-new-version-3-1-the-settings-file-have-some-changes
On Django new version 3.1, the settings file have some changes, and I came to ask how I have to proceed to set my static files? The way that I usually did doesn't work more. Last versions: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Version 3.1: from pathlib import Path BASE_DIR = ...
This change makes it a lot easier for you to define your STATIC and MEDIA variables. You don't even need to import os for this purpose and all you need is to add following codes to your settings.py: BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # which shows the root directory of your project STATIC_ROOT...
9
10
63,435,483
2020-8-16
https://stackoverflow.com/questions/63435483/tensorflow-in-python-3-9-installation-error-failure-to-install-tensorflow-win
While installing TensorFlow on Windows having python 3.9 installed using the following command: pip install tensorflow Following error occurred with the warning: WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] The system cannot find ...
Run the same command using --user pip install --user package_name or you can try to restart the terminal and run it as admin
16
54
63,416,894
2020-8-14
https://stackoverflow.com/questions/63416894/correlation-values-in-pairplot
Is there a way to show pair-correlation values with seaborn.pairplot(), as in the example below (created with ggpairs() in R)? I can make the plots using the attached code, but cannot add the correlations. Thanks import numpy as np import seaborn as sns import matplotlib.pyplot as plt iris = sns.load_dataset('iris') g ...
If you use PairGrid instead of pairplot, then you can pass a custom function that would calculate the correlation coefficient and display it on the graph: from scipy.stats import pearsonr def reg_coef(x,y,label=None,color=None,**kwargs): ax = plt.gca() r,p = pearsonr(x,y) ax.annotate('r = {:.2f}'.format(r), xy=(0.5,0.5...
9
15
63,416,546
2020-8-14
https://stackoverflow.com/questions/63416546/twine-is-defaulting-long-description-content-type-to-text-x-rst
Heres is my setup setup( name="`...", version="...", description=..., long_description_content_type="text/markdown", long_description=README, author="...", classifiers=[...], packages=["..."], include_package_data=True, ) I used the following command to package my project python setup.py sdist bdist_wheel but when I ...
I attempted to switch the order of the "long_description_content_type" and the "long_description" arguments and instead of assigning the description argument to a variable containing the description, I assigned it directly to the description. Doing so has resolved my issue setup( name="Futshane_TBG", version="1.0.0", d...
9
12