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,814,607
2020-7-9
https://stackoverflow.com/questions/62814607/pdfkit-warning-blocked-access-to-file
I am getting an error(Blocked access to the file) in HTML to pdf conversion using pdfkit library while using a local image in my HTML file. How can I use local images in my HTML file?
I faced the same problem. I solved it by adding "enable-local-file-access" option to pdfkit.from_file(). options = { "enable-local-file-access": None } pdfkit.from_file(html_file_name, pdf_file_name, options=options)
12
38
62,803,633
2020-7-8
https://stackoverflow.com/questions/62803633/timestamp-object-has-no-attribute-dt
I am trying to convert a new column in a dataframe through a function based on the values in the date column, but get an error indicating "Timestamp object has no attribute dt." However, if I run this outside of a function, the dt attribute works fine. Any guidance would be appreciated. This code runs with no issues: s...
I'm guessing you should remove .dt in the second case. When you do apply it's applying to each element, .dt is needed when it's a group of data, if it's only one element you don't need .dt otherwise it will raise {AttributeError: 'Timestamp' object has no attribute 'dt'} reference: https://stackoverflow.com/a/48967889/...
34
56
62,895,219
2020-7-14
https://stackoverflow.com/questions/62895219/getting-error-in-airflow-dag-unsupported-operand-types-for-list-and-lis
I am new to Apache airflow and DAG. There are total 6 tasks in the DAG (task1, task2, task3, task4, task5, task6). But at the time of running the DAG we are getting the error below. DAG unsupported operand type(s) for >>: 'list' and 'list' Below is my code for the DAG. Please help. I am new to airflow. from airflow imp...
What is your desired Task Dependency? Do you want to run task_4 after task_2 only or after task_2 and task_3 Based on that answer, use one of the following: (use this if task_4 should run after both task_2 and task_3 are completed) task_1 >> [task_2 , task_3] task_2 >> [task_4, task_5] >> task_6 task_3 >> [task_4, task...
9
11
62,876,777
2020-7-13
https://stackoverflow.com/questions/62876777/documenting-and-detailing-a-single-script-based-on-the-comments-inside
I am going to write a set of scripts, each independent from the others but with some similarities. The structure will most likely be the same for all the scripts and probably looks like: # -*- coding: utf-8 -*- """ Small description and information @author: Author """ # Imports import numpy as np import math from scipy...
Docstrings instead of comments In order to make things easier for yourself, you probably want to make use of docstrings rather than comments: A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of ...
7
3
62,854,761
2020-7-11
https://stackoverflow.com/questions/62854761/python3-8-whats-the-difference-between-importerror-and-modulenotfounderror
In python3.8, what's the difference between ImportError and ModuleNotFoundError? I'm just wondering what the difference is and why they matter.
According to the python docs: The ImportError is raised when an import statement has trouble successfully importing the specified module. Typically, such a problem is due to an invalid or incorrect path, which will raise a ModuleNotFoundError in Python 3.6 and newer versions.
27
8
62,903,056
2020-7-14
https://stackoverflow.com/questions/62903056/elementclickinterceptedexception-message-element-click-intercepted-element-is
I am trying to click on the first box (ASN / DSD) But I get this error message: selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <input type="radio" name="docTypes" ng-model="$ctrl.documentTypes.selected" id="documentType-0" ng-change="$ctrl.onChangeDocumentType(...
This error message... selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <input type="radio" name="docTypes" ng-model="$ctrl.documentTypes.selected" id="documentType-0" ng-change="$ctrl.onChangeDocumentType()" ng-value="documentType" tabindex="0" class="ng-pristine ...
7
20
62,827,291
2020-7-10
https://stackoverflow.com/questions/62827291/warning-pip-is-configured-with-locations-that-require-tls-ssl-however-the-ssl
I would like to use Python3.8.x on Google Cloud Compute Engine. First, I created an instance with gcloud command. gcloud compute instances create \ pegasus-test \ --zone=asia-northeast1-b \ --machine-type=n1-highmem-8 \ --boot-disk-size=500GB \ --image-project=ml-images \ --image-family=tf-1-15 \ --maintenance-policy T...
I had the same issue and had to spend a few days to tackle. After exploring many different solutions, this worked for the pip ssl issue.
16
18
62,891,917
2020-7-14
https://stackoverflow.com/questions/62891917/how-to-change-the-colour-of-an-image-using-a-mask
I am writing a code to change the color of hair in the facial picture of a person. Doing this I made a model and was able to get a mask of the parts of the hair. But now I am stuck at a problem how to change the color of it. Below is the output mask and input image passed. Can you suggest me the method that could be ...
Since they both have the same shape, you can mask the image of the face using mask image. We first need to perform binary thresholding on it, so it can be used as a b&w mask. Then we can perform boolean indexing based on whether a value is 0 or 255, and assign a new color, such as green? import cv2 mask = cv2.imread('e...
12
31
62,899,860
2020-7-14
https://stackoverflow.com/questions/62899860/how-can-i-resolve-typeerror-cannot-safely-cast-non-equivalent-float64-to-int6
I'm trying to convert a few float columns to int in a DF but I'm getting above error. I've tried both to convert it as well as to fillna to 0(which I prefer not to do, as in my dataset the NA is required). What am I doing wrong? I've tried both: orginalData[NumericColumns] = orginalData[NumericColumns].astype('Int64') ...
import numpy as np orginalData[NumericColumns] = orginalData[NumericColumns].fillna(0).astype(np.int64, errors='ignore') For NaNs you need to replace the NaNs with 0, then do the type casting
20
4
62,796,591
2020-7-8
https://stackoverflow.com/questions/62796591/breakpoint-in-except-clause-doesnt-have-access-to-the-bound-exception
Consider the following example: try: raise ValueError('test') except ValueError as err: breakpoint() # at this point in the debugger, name 'err' is not defined Here, after the breakpoint is entered, the debugger doesn't have access to the exception instance bound to err: $ python test.py --Return-- > test.py(4)<module...
breakpoint() is not a breakpoint in the sense that it halts execution at the exact location of this function call. Instead it's a shorthand for import pdb; pdb.set_trace() which will halt execution at the next line of code (it calls sys.settrace under the covers). Since there is no more code inside the except block, ex...
10
12
62,880,911
2020-7-13
https://stackoverflow.com/questions/62880911/generate-video-from-numpy-arrays-with-opencv
I am trying to use the openCV VideoWriter class to generate a video from numpy arrays. I am using the following code: import numpy as np import cv2 size = 720*16//9, 720 duration = 2 fps = 25 out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'X264'), fps, size) for _ in range(fps * duration): data = np.random...
The first issue is that you are trying to create a video using black and white frames while VideoWriter assumes color by default. VideoWriter has a 5th boolean parameter where you can pass False to specify that the video is to be black and white. The second issue is that the dimensions that cv2 expects are the opposite...
14
20
62,886,283
2020-7-14
https://stackoverflow.com/questions/62886283/python-requests-post-how-to-send-request-body-encoded-as-application-x-www-fo
I'm doign an app with the Spotify API. My problem is I'm trying to get an access_token but It's not working. In the docs it says i need to send the body encoded as application/x-www-form-urlencoded so I search a little bit and It should work just setting request_body as a dictionary. This is the code of my function: d...
You can specify the request type in the request header. headers = {'Content-Type': 'application/x-www-form-urlencoded'} response = requests.post(endpoint, data=request_body, headers=headers) print(response)
11
22
62,885,911
2020-7-13
https://stackoverflow.com/questions/62885911/pip-freeze-creates-some-weird-path-instead-of-the-package-version
I am working on developing a python package. I use pip freeze > requirements.txt to add the required package into the requirement.txt file. However, I realized that some of the packages, instead of the package version, have some path in front of them. numpy==1.19.0 packaging==20.4 pandas @ file:///opt/concourse/worker/...
It looks like this is an open issue with pip freeze in version 20.1, the current workaround is to use: pip list --format=freeze > requirements.txt In a nutshell, this is caused by changing the behavior of pip freeze to include direct references for distributions installed from direct URL references. You can read more ...
178
367
62,883,329
2020-7-13
https://stackoverflow.com/questions/62883329/how-to-deal-with-large-dependencies-in-aws-lambda
I am using AWS Lambda and the functions I need to deploy require many different packages. Using serverless-python-requirements the zip file that is generated is 169.5MB, far greater than the 50MB limit. I have tried using Lambda Layers, but this doesn't solve the size issue. I have also tried dumping the zip file in an...
Very recently, AWS announced the support of EFS for Lambda.Read the announcement here. EFS or the Elastic File System is the NFS file system for compute nodes. Read more about them here. With this now you can essentially attach a network storage to your lambda function. I have personally used it to load huge reference ...
11
15
62,875,416
2020-7-13
https://stackoverflow.com/questions/62875416/python-peewee-improperlyconfigured-mysql-driver-not-installed
I tried to make a MySQL connection with peewee and followed the tutorial from their website: peewee quickstart So my code is the following: from peewee import * db = MySQLDatabase( host='127.0.0.1', user='root', password='', database='db_test' ) class Person(Model): name = CharField() birthday = DateField() class Meta:...
The docs are clear, as is the error message: http://docs.peewee-orm.com/en/latest/peewee/database.html#using-mysql Install pymysql or mysqldb. To use the non-standard mysql-connector driver, you need to import the playhouse.mysql_ext module and use the MySQLConnectorDatabase implementation: http://docs.peewee-orm.com/e...
12
6
62,853,875
2020-7-11
https://stackoverflow.com/questions/62853875/stopping-python-container-is-slow-sigterm-not-passed-to-python-process
I made a simple python webserver based on this example, which runs inside Docker FROM python:3-alpine WORKDIR /app COPY entrypoint.sh . RUN chmod +x entrypoint.sh COPY src src CMD ["python", "/app/src/api.py"] ENTRYPOINT ["/app/entrypoint.sh"] Entrypoint: #!/bin/sh echo starting entrypoint set -x exec "$@" Stopping t...
Since the script runs as pid 1 as desired and setting init: true in docker-compose.yml doesn't seem to change anything, I took a deeper drive in this topic. This leads me figuring out multiple mistakes I did: Logging The approach of printing a message when SIGTERM is catched was designed as simple test case to see if t...
16
22
62,869,201
2020-7-13
https://stackoverflow.com/questions/62869201/upgrading-pycharm-venv-python-version
I have python 3.6 in my venv on PyCharm. However, I want to change that to Python 3.8. I have already installed 3.8, so how do I change my venv python version? I am on windows 10. Changing the version on the project intepreter settings seems to run using the new venv not my existing venv with all the packages I have in...
You need to create a new virtual environment with the interpreter which version is 3.8. Go to Settings => Project => Python Interpreter Click on the vertical 3 dots, and click on "Add". Select Virtualenv Environment => New Environment Choose as base interpreter the one which version is 3.8 (the one you just i...
9
7
62,858,552
2020-7-12
https://stackoverflow.com/questions/62858552/why-cant-i-import-geopy-distance-vincenty-on-jupyter-notebook-i-installed-ge
from geopy.distance import vincenty I just installed the geopy package 2.0.0, I want to use geopy.distance.vincenty() as this doc says. However, it returns ImportError: cannot import name 'vincenty' from 'geopy.distance'. And if I try from geopy import distance it becomes AttributeError: module 'geopy.distance' has n...
Yes, it has been removed. Look at the changelog's Breaking Changes section which contains this entry: Removed geopy.distance.vincenty, use geopy.distance.geodesic instead.
11
29
62,864,163
2020-7-12
https://stackoverflow.com/questions/62864163/why-does-equality-not-appear-to-be-a-symmetric-relation-in-python
I'm learning about comparison operators, and I was playing around with True and False statements. I ran the following code in the Python shell: not(5>7) == True As expected, this returned True. However, I then ran the following code: True == not(5>7) and there was a syntax error. Why was this? If the first line of co...
The syntax error seems to be caused by the not keyword, not (pun intended) the equality operator: True == not (5 > 7) # SyntaxError: invalid syntax True == (not (5 > 7)) # True The explanation can be found in the docs: not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b),...
23
33
62,806,175
2020-7-9
https://stackoverflow.com/questions/62806175/xarray-combine-by-coords-return-the-monotonic-global-index-error
I am trying to combine two spatial xarray datasets using combine_by_coords. These two datasets are two tiles next to each other. So there are overlapping coordinates. In the overlapping regions, the variable values of one of the datasets is nan. I used the "combine_by_coords" with compat='no_conflicts' option. However,...
This isn't a bug, it's throwing the error it should be throwing given your input. However I can see how the documentation doesn't make it very clear as to why this is happening! combine_by_coords and combine_nested do two things: they concatenate (using xr.concat), and they merge (using xr.merge). merge groups variable...
15
16
62,844,211
2020-7-11
https://stackoverflow.com/questions/62844211/updating-sagemaker-endpoint-with-new-endpoint-configuration
A bit confused with automatisation of Sagemaker retraining the model. Currently I have a notebook instance with Sagemaker LinearLerner model making the classification task. So using Estimator I'm making training, then deploying the model creating Endpoint. Afterwards using Lambda function for invoke this endpoint, I ad...
If I am understanding the question correctly, you should be able to use CreateEndpointConfig near the end of the training job, then use UpdateEndpoint: Deploys the new EndpointConfig specified in the request, switches to using newly created endpoint, and then deletes resources provisioned for the endpoint using the pre...
7
4
62,845,884
2020-7-11
https://stackoverflow.com/questions/62845884/how-can-i-show-syntax-highlighted-python-code-in-a-html-page
Is it somehow possible to show syntax-highlighted python code in a webpage? I found this: <pre class="brush: python"> # python code here </pre> However, it shows all the code in black. I want import to be orange, strings to be green. Is it possible to do this? Thank you!
If you wish to only display code, python in this case, consider using Github gist. You can then embed it using the 'embed' option on the top right corner. It will give you a script tag that you can copy and add to your webpage like so: <script src="https://gist.github.com/username/a39a422ebdff6e732753b90573100b16.js"><...
13
6
62,824,783
2020-7-9
https://stackoverflow.com/questions/62824783/pytest-cov-does-not-read-pyproject-toml
Pytest cov is not reading its setting from the pyproject.toml file. I am using nox, so I run the test with: python3 -m nox It seems I have the same issue even without nox. In fact, after running a poetry install: poetry run pytest --cov=src passes the test poetry run pytest --cov does not pass the test In particular...
Turning the comment into an answer: Check the current treatment of the src directory. Right now, it seems to be a namespace package which is not what you intend. Either switch to the src layout: # pyproject.toml [tool.poetry] ... packages = [ { include = 'project', from = 'src' } ] [tool.coverage.run] ... source = ['pr...
12
8
62,840,719
2020-7-10
https://stackoverflow.com/questions/62840719/how-to-correctly-access-properties-in-a-json-from-python
EDIT: As pointed out by some users, the request does not actually returns a JSON, but a string encoded JSON. The issue here is not actually parsing the JSON in python, but writing it in such a way that a request can be sent to the API. Therefore, it's not necessary to use the json python library. I'm using the various ...
So with the JSON representation in the docs: { "presentationId": string, "pageSize": { object (Size) }, "slides": [ { object (Page) } ], "title": string, "masters": [ { object (Page) } ], "layouts": [ { object (Page) } ], "locale": string, "revisionId": string, "notesMaster": { object (Page) } } You can access the sli...
8
6
62,838,129
2020-7-10
https://stackoverflow.com/questions/62838129/using-global-variables-inside-a-nested-function-in-python
I read this code (given below) and my understanding was that, if a variable is declared global inside a function and if it is modified then it's value will change permanently. x = 15 def change(): global x x = x + 5 print("Value of x inside a function :", x) change() print("Value of x outside a function :", x) Output:...
In add, x is not a global variable; it's local to add. You either need to make it global as well, so that add and change are referring to the same variable def add(): global x x = 15 def change(): global x x = 20 print("Before making changes: ", x) print("Making change") change() print("After making change: ", x) add()...
9
12
62,800,189
2020-7-8
https://stackoverflow.com/questions/62800189/pytorch-lightning-move-tensor-to-correct-device-in-validation-epoch-end
I would like to create a new tensor in a validation_epoch_end method of a LightningModule. From the official docs (page 48) it is stated that we should avoid direct .cuda() or .to(device) calls: There are no .cuda() or .to() calls. . . Lightning does these for you. and we are encouraged to use type_as method to trans...
did you check part 3.4 (page 34) in the doc you linked ? LightningModules know what device they are on! construct tensors on the device directly to avoid CPU->Device transfer t = tensor.rand(2, 2).cuda()# bad (self is lightningModule)t = tensor.rand(2,2, device=self.device)# good I had a similar issue to create tens...
14
25
62,827,538
2020-7-10
https://stackoverflow.com/questions/62827538/in-cython-class-whats-the-difference-of-using-init-and-cinit
Code block 1 using __init__ %%cython -3 cdef class c: cdef: int a str s def __init__(self): self.a=1 self.s="abc" def get_vals(self): return self.a,self.s m=c() print(m.get_vals()) Code block 2 using __cinit__ %%cython -3 cdef class c: cdef: int a str s def __cinit__(self): # cinit here self.a=1 self.s="abc" def get_v...
It's mainly about inheritance. Suppose I inherit from your class C: class D(C): def __init__(self): pass # oops forgot to call C.__init__ class E(C): def __init__(self): super().__init__(self) super().__init__(self) # called it twice How __init__ ends up being called is entirely up to the classes that inherit from it....
8
9
62,811,311
2020-7-9
https://stackoverflow.com/questions/62811311/installing-awscli-on-alpine-how-to-fix-modulenotfounderror-no-module-named
Context I had a dockerfile based on postgres:11-alpine that was working in the past (probably a few months since it was last built) with the following definition: FROM postgres:11-alpine RUN apk update # install aws cli # taken from: https://github.com/anigeo/docker-awscli/blob/master/Dockerfile RUN \ apk -Uuv add grof...
The problem seems to actually be caused by deleting py-pip. As far as I know, the aim of the apk del was to reduce the size of the final docker image. I'm not sure why deleting py-pip used to work when the file was using the python package. So the following now seems to be working: RUN \ apk -Uuv add groff less python3...
7
12
62,805,973
2020-7-9
https://stackoverflow.com/questions/62805973/how-do-i-extract-all-of-the-text-from-a-pdf-using-indexing
I am new to Python and coding in general. I'm trying to create a program that will OCR a directory of PDFs then extract the text so I can later pick out specific things. However, I am having trouble getting pdfPlumber to extract all the text from all of the pages. You can index from start to an end, but if the end is u...
The pdfplumber git page says pdfplumber.open returns an instance of the pdfplumber.PDF class. That instance has the pages property which is a list of pdfplumber.Page instances - one per Page loaded from your pdf. Looking at your code, if you do: total_pages = len(pdf.pages) You should get the total pages for the curre...
7
19
62,819,600
2020-7-9
https://stackoverflow.com/questions/62819600/detect-and-remove-outliers-as-step-of-a-pipeline
I have a problem, I'm trying to build my own class to put into a pipeline in python, but it doesn't work. The problem I am trying to solve is a multiclass classification problem. What I want to do this to add a step in the pipeline to detect and remove outliers. I found this detect and remove outliers in pipeline pytho...
The error is because the transform method def transform(self, X, y) requires both X and y to be passed in, but whatever is calling it is only passing X. (I can't see where it's called from in your code so assume it's being called by the underlying library). I don't know if making y optional (def transform(self, X, y=No...
7
5
62,818,306
2020-7-9
https://stackoverflow.com/questions/62818306/what-is-the-most-efficient-way-to-fill-missing-values-in-this-data-frame
I have the following pandas dataframe : df = pd.DataFrame([ ['A', 2017, 1], ['A', 2019, 1], ['B', 2017, 1], ['B', 2018, 1], ['C', 2016, 1], ['C', 2019, 1], ], columns=['ID', 'year', 'number']) and am looking for the most efficient way to fill the missing years with a default value of 0 for the column number The expect...
A slightly faster approach rather than using explode is to use pd.Series constructor. And you can use .iloc if years are already sorted from earliest to latest. idx = df.groupby('ID')['year'].apply(lambda x: pd.Series(np.arange(x.iloc[0], x.iloc[-1]+1))).reset_index() df.set_index(['ID','year']).reindex(pd.MultiIndex.f...
24
20
62,818,625
2020-7-9
https://stackoverflow.com/questions/62818625/read-local-json-file-with-python
I want to read a JSON file with Python : Here is part of my JSON file : { "Jointure":[ { "IDJointure":1, "societe":"S.R.T.K", "date":"2019/01/01", "heure":"05:47:00"}, { "IDJointure":2, "societe":"S.R.T.K", "date":"2019/01/01", "heure":"05:50:00"}]} This is the code : import json data = json.loads('Data2019.json') for...
Try pandas import pandas as pd patients_df = pd.read_json('E:/datasets/patients.json') patients_df.head()
12
-9
62,793,544
2020-7-8
https://stackoverflow.com/questions/62793544/efficient-way-to-remove-half-of-the-duplicate-items-in-a-list
If I have a list say l = [1, 8, 8, 8, 1, 3, 3, 8] and it's guaranteed that every element occurs an even number of times, how do I make a list with all elements of l now occurring n/2 times. So since 1 occurred 2 times, it should now occur once. Since 8 occurs 4 times, it should now occur twice. Since 3 occurred twice, ...
If order isn't important, a way would be to get the odd or even indexes only after a sort. Those lists will be the same so you only need one of them. l = [1,8,8,8,1,3,3,8] l.sort() # Get all odd indexes odd = l[1::2] # Get all even indexes even = l[::2] print(odd) print(odd == even) Result: [1, 3, 8, 8] True
60
106
62,810,872
2020-7-9
https://stackoverflow.com/questions/62810872/pairwise-distances-between-two-islands-connected-components-in-numpy-array
Consider the following image, stored as a numpy array: a = [[0,0,0,0,0,1,1,0,0,0], [0,0,0,0,1,1,1,1,0,0], [0,0,0,0,0,1,1,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,2,0,0,0,0], [0,0,0,0,0,2,2,0,0,0], [0,0,0,0,0,2,0,0,0,0], [0,0,0,0,3,3,3,0,0,0], [4,0,0,0,0,0,0,0,0,0], [4,4,0,0,0,0,0,0,0,0], [4,4,4,0,0,0,0,0,0,0]] a = np....
This is what you would need: from scipy.spatial.distance import cdist def Distance(a, m, n): return cdist(np.argwhere(a==m),np.argwhere(a==n),'minkowski',p=1.).min() or similarly per @MaxPowers comment (claim: cityblock is faster): return cdist(np.argwhere(a==m),np.argwhere(a==n),'cityblock').min() Find the location...
9
8
62,802,006
2020-7-8
https://stackoverflow.com/questions/62802006/aws-sam-cli-fresh-install-throws-error-dyld-library-not-loaded-executable-p
I am trying to use the AWS SAM CLI installed through Homebrew and I am seeing the following error when I try to use sam with any command: dyld: Library not loaded: @executable_path/../.Python Referenced from: /usr/local/Cellar/aws-sam-cli/0.53.0/libexec/bin/python3.7 Reason: image not found Looking at the .Python file...
Looks like 0.53.0 comes with python3.7 executables, there is a workaround until it is fixed: brew install --build-from-source aws-sam-cli https://github.com/awslabs/aws-sam-cli/issues/2101 https://github.com/aws/homebrew-tap/issues/93
13
19
62,808,852
2020-7-9
https://stackoverflow.com/questions/62808852/cant-run-ipython-on-cmd
I successfully installed ipython via pip. I wanted then to use it by launching it through windows 10 command prompt but am getting the following error 'ipython' is not recognized as an internal or external command, operable program or batch file. I have gone through many questions on stackoverflow but cannot get a rel...
Search in your machine the ipython application (directory in which it is installled) and the add the path to PATH environment variables. For example in my case location was C:\Users\DELL\AppData\Local\Programs\Python\Python37\Scripts Add this path to PATH environment variable (see here) and your problem is solved.
12
6
63,438,979
2020-7-8
https://stackoverflow.com/questions/63438979/python-pmdarima-autoarima-does-not-work-with-large-data
I have a Dataframe with around 80.000 observations taken every 15 min. The seasonal parameter m is assumed with 96, because every 24h the pattern repeats. When I insert these informations in my auto_arima algorithm, it takes a long time (some hours) until the following error message is given out: MemoryError: Unable to...
I don't recall the exact source where I read this, but neither auto.arima nor pmdarima are really optimized to scale, which might explain the issues you are facing. But there are some more important things to note about your question: With 80K data points at 15 minute intervals, ARIMA probably isn't the best type of mo...
7
13
62,798,296
2020-7-8
https://stackoverflow.com/questions/62798296/how-to-hide-axis-lines-but-show-ticks-in-a-chart-in-altair-while-actively-using
I am aware of using axis=None to hide axis lines. But when you have actively used axis to modify the graph, is it possible to keep just the ticks, but hide the axis lines for both X and Y axis? For example, here is a graph I have where I'd like it to happen - import pandas as pd import altair as alt df = pd.DataFrame({...
Vega-Lite calls the axis line the domain. You can hide it by passing domain=False to the axis configuration: import pandas as pd import altair as alt df = pd.DataFrame({'a': [1,2,3,4], 'b':[2000,4000,6000,8000]}) alt.Chart(df).mark_trail().encode( x=alt.X('a:Q', axis=alt.Axis(titleFontSize=12, title='Time →', labelColo...
10
11
62,785,679
2020-7-8
https://stackoverflow.com/questions/62785679/typevar-describing-a-class-that-must-subclass-more-than-one-class
I would like to create a type annotation T that describes a type that must be a subclass of both class A and class B. T = TypeVar('T', bound=A) only specifies that T must be a subclass of A. T = TypeVar('T', A, B) only specifies that T must be a subclass of A or a subclass of B but not necessarily both. I actually want...
What you are looking for is an intersection type. Strictly speaking, I do not believe Python's type annotations support this (at least not yet). However, you can get something similar with a Protocol: from typing import Protocol, TypeVar class A: def foo(self) -> int: return 42 class B: def bar(self) -> bool: return Fa...
9
8
62,786,028
2020-7-8
https://stackoverflow.com/questions/62786028/importerror-libgthread-2-0-so-0-cannot-open-shared-object-file-no-such-file-o
I was builting a web app with streamlit, OpenCV and Torch on local machine. The whole project went well until I built a Docker file and was about to transport it to my Google Cloud Platform. Can anyone tell me what is really going wrong here? Here is my Dockerfile: FROM pytorch/pytorch:latest RUN pip install virtualen...
Maybe, you should run following command before pip. apt update apt-get install -y libglib2.0-0 libsm6 libxrender1 libxext6
22
42
62,670,991
2020-7-1
https://stackoverflow.com/questions/62670991/read-csv-from-azure-blob-storage-and-store-in-a-dataframe
I'm trying to read multiple CSV files from blob storage using python. The code that I'm using is: blob_service_client = BlobServiceClient.from_connection_string(connection_str) container_client = blob_service_client.get_container_client(container) blobs_list = container_client.list_blobs(folder_root) for blob in blobs_...
Base on @sahaj-raj-malla answer: 2 snippets of code to load (or save) file from blob: shorter load with pandas [necessary to pip install adlfs fsspec ] import pandas as pd account_name = "my_account_stage_name" account_key = "loooooooooooooooooooooong_acccccooooooooount_keeeeeeeeeeeeeeeeey$$$$***$$$$$$$$$$$$$$2222222...
8
5
62,695,786
2020-7-2
https://stackoverflow.com/questions/62695786/error-215assertion-failed-scn-1-m-cols-in-function-cvperspectivetra
Below is a python script that calculates the homography between two images and then map a desired point from one image to another import cv2 import numpy as np if __name__ == '__main__' : # Read source image. im_src = cv2.imread(r'C:/Users/kjbaili/.spyder-py3/webcam_calib/homography/khaledd 35.0 sec.jpg') # Five corner...
You are passing wrong arguments to cv2.getPerspectiveTransform(). The function expects a set of four coordinates in the original image and the new coordinates in the transformed image. You can directly pass the pts_src and pts_dst to the function and you will get the transformation matrix. You can then get the transfor...
8
2
62,671,226
2020-7-1
https://stackoverflow.com/questions/62671226/plotly-dash-how-to-reset-the-n-clicks-attribute-of-a-dash-html-button
I have a basic datatable in plotly/dash. My goal is to upload (or print for the sake of the example...) after I press the upload-button. The issue is, that I can't figure out how to get the n_clicks attribute of the button back to zero. So what happens is that after I clicked the button for the first time it prints con...
You could use the dash.callback_context property to trigger the callback only when the number of clicks has changed rather than after the first click. See the section on "Determining which Button Changed with callback_context" in the Dash documentation. The following is an example of how you could update your callback....
11
14
62,748,978
2020-7-6
https://stackoverflow.com/questions/62748978/python-annotate-variable-as-key-of-a-typeddict
Basically a distilled down version of this (as yet unanswered) question. I want to state that a variable should only take on values that are keys in a TypedDict. At present I'm defining a separate Literal type to represent the keys, for example: from typing import Literal, TypedDict class MyTD(TypedDict): a: int b: int...
Using MyPy, I don't think this is possible. I ran this experiment: from typing import TypedDict class MyTD(TypedDict): a: str b: int d = MyTD(a='x', b=2) reveal_type(list(d)) The MyPy output was: Revealed type is "builtins.list[builtins.str]" This indicates that internally it is not tracking the keys as literals. Oth...
16
4
62,687,193
2020-7-2
https://stackoverflow.com/questions/62687193/how-to-create-a-pathlib-relative-path-with-a-dot-starting-point
I needed to create a relative path starting with the current directory as a "." dot For example, in windows ".\envs\.some.env" or "./envs/.some.env" elsewhere I wanted to do this using pathlib. A solution was found, but it has a kludgy replace statement. Is there a better way to do this using pathlib? The usage was dja...
Here's a multi-platform idea: import ntpath import os import posixpath from pathlib import Path, PurePosixPath, PureWindowsPath def dot_path(pth): """Return path str that may start with '.' if relative.""" if pth.is_absolute(): return os.fsdecode(pth) if isinstance(pth, PureWindowsPath): return ntpath.join(".", pth) el...
10
3
62,771,868
2020-7-7
https://stackoverflow.com/questions/62771868/axiserror-axis-1-is-out-of-bounds-for-array-of-dimension-1-when-calculating-acc
I try to predict 10 classes using this code #Predicting the Test set rules y_pred = model.predict(traindata) y_pred = np.argmax(y_pred, axis=1) y_true = np.argmax(testdata, axis=1) target_names = ["akLembut","akMundur","akTajam","caMenaik", "caMenurun", "coretanTengah", "garisAtas", "garisBawah", "garisBawahBanyak", "t...
My guess is that your test_data array is only one-dimensional, so change to y_true = np.argmax(testdata, axis=0)
14
18
62,764,148
2020-7-6
https://stackoverflow.com/questions/62764148/how-to-import-an-existing-requirements-txt-into-a-poetry-project
I am trying out Poetry in an existing project. It used pyenv and virtual env originally so I have a requirements.txt file with the project's dependencies. I want to import the requirements.txt file using Poetry, so that I can load the dependencies for the first time. I've looked through poetry's documentation, but I ha...
poetry doesn't support this directly. But if you have a handmade list of required packages (at best without any version numbers), that only contain the main dependencies and not the dependencies of a dependency you could do this: $ cat requirements.txt | xargs poetry add
196
259
62,714,153
2020-7-3
https://stackoverflow.com/questions/62714153/does-ansible-shell-module-need-python-on-target-server
I have a very basic playbook that simply runs a script using the shell module on the target remote host. In the output it however fails stating python interpreter not found. Installing python on each target is not the solution I can pursue. Is it possible to use my Ansible automation to run the playbook and execute the...
Any ansible operation requires python on the target node except the raw and script modules. Please note that these two modules are primarily meant to install ansible requirements (i.e. Python and its mandatory modules) on targets where they are missing. In other words, Python is definitely a requirement to run ansible ...
12
21
62,731,561
2020-7-4
https://stackoverflow.com/questions/62731561/discord-send-message-only-from-python-app-to-discord-channel-one-way-communic
I am designing an app where I can send notification to my discord channel when something happen with my python code (e.g new user signup on my website). It will be a one way communication as only python app will send message to discord channel. Here is what I have tried. import os import discord import asyncio TOKEN = ...
You can send the message to a Discord webhook. First, make a webhook in the Discord channel you'd like to send messages to. Then, use the discord.Webhook.from_url method to fetch a Webhook object from the URL Discord gave you. Finally, use the discord.Webhook.send method to send a message using the webhook. If you're u...
22
35
62,684,468
2020-7-1
https://stackoverflow.com/questions/62684468/pythons-requests-triggers-cloudflares-security-while-urllib-does-not
I'm working on an automated web scraper for a Restaurant website, but I'm having an issue. The said website uses Cloudflare's anti-bot security, which I would like to bypass, not the Under-Attack-Mode but a captcha test that only triggers when it detects a non-American IP or a bot. I'm trying to bypass it as Cloudflare...
This really piqued my interests. The requests solution that I was able to get working. Solution Finally narrow down the problem. When you use requests it uses urllib3 connection pool. There seems to be some inconsistency between a regular urllib3 connection and a connection pool. A working solution: import requests fro...
18
15
62,710,057
2020-7-3
https://stackoverflow.com/questions/62710057/access-color-from-plotly-color-scale
Is there a way in Plotly to access colormap colours at any value along its range? I know I can access the defining colours for a colourscale from plotly.colors.PLOTLY_SCALES["Viridis"] but I am unable to find how to access intermediate / interpolated values. The equivalent in Matplotlib is shown in this question. Ther...
This answer extend the already good one provided by Adam. In particular, it deals with the inconsistency of Plotly's color scales. In Plotly, you specify a built-in color scale by writing colorscale="name_of_the_colorscale". This suggests that Plotly already has a built-in tool that somehow convert the color scale to a...
12
9
62,725,822
2020-7-4
https://stackoverflow.com/questions/62725822/why-does-a-type-hint-float-accept-int-while-it-is-not-even-a-subclass
On the one hand, I have learned that numbers that can be int or float should be type annotated as float (sources: PEP 484 Type Hints and this stackoverflow question): def add(a: float, b: float): return a + b On the other hand, an int is not an instance of float: issubclass(int, float) returns False isinstance(42, fl...
Are int/float a special case in type annotations? float is a special case. int is not. PEP 484 says, in the paragraph below the one referenced by the link in your question: when an argument is annotated as having type float, an argument of type int is acceptable; So accepting int where float is annotated is expli...
14
14
62,759,863
2020-7-6
https://stackoverflow.com/questions/62759863/how-to-use-pyav-or-opencv-to-decode-a-live-stream-of-raw-h-264-data
The data was received by socket ,with no more shell , they are pure I P B frames begin with NAL Header(something like 00 00 00 01). I am now using pyav to decode the frames ,but i can only decode the data after the second pps info(in key frame) was received(so the chunk of data I send to my decode thread can begin with...
After hours of finding an answer for this as well. I figure this out myself. For single thread, you can do the following: rawData = io.BytesIO() container = av.open(rawData, format="h264", mode='r') cur_pos = 0 while True: data = await websocket.recv() rawData.write(data) rawData.seek(cur_pos) for packet in container.d...
8
11
62,678,765
2020-7-1
https://stackoverflow.com/questions/62678765/finally-always-runs-just-before-the-return-in-try-block-then-why-update-in-fina
Finally block runs just before the return statement in the try block, as shown in the below example - returns False instead of True: >>> def bool_return(): ... try: ... return True ... finally: ... return False ... >>> bool_return() False Similarly, the following code returns value set in the Finally block: >>> def nu...
I think the problem you have is more related to value assignment than what try and finally do. I suggest to read Facts and myths about Python names and values. When you return a value, it just like assigning the value to a variable, result for example, and finally always execute to reassign the value. Then, your exampl...
23
1
62,709,815
2020-7-3
https://stackoverflow.com/questions/62709815/clienterror-an-error-occurred-internalfailure-when-calling-the-publish-operat
I am simply trying to publish to an SNS topic using a lambda function. The function code as follows, with ARN being the actual SNS topic ARN: import boto3 print('Loading function') def lambda_handler(event, context): client = boto3.client('sns') response = client.publish( TargetArn='ARN', Message="Test", ) return respo...
In case if anyone is facing this issue, make sure you use the correct ARN - use the ARN of the Topic instead of the subscription.
7
6
62,748,241
2020-7-6
https://stackoverflow.com/questions/62748241/check-if-datetime-object-in-pandas-has-a-timezone
I'm importing data into pandas and want to remove any timezones – if they're present in the data. If the data has a time zone, the following code works successfully: col = "my_date_column" df[col] = pd.to_datetime(df[col]).dt.tz_localize(None) # We don't want timezones... If the data does not contain a timezone, I'd l...
Assuming you have a column of type datetime, you can check the tzinfo of each timestamp in the column. It's basically described here (although this is not specific to pytz). Ex: import pandas as pd # example series: s = pd.Series([ pd.Timestamp("2020-06-06").tz_localize("Europe/Berlin"), # tzinfo defined pd.Timestamp("...
8
8
62,681,257
2020-7-1
https://stackoverflow.com/questions/62681257/tf-keras-model-predict-is-slower-than-straight-numpy
Thanks, everyone for trying to help me understand the issue below. I have updated the question and produced a CPU-only run and GPU-only of the run. In general, it also appears that in either case a direct numpy calculation hundreds of times faster than the model. predict(). Hopefully, this clarifies that this does not ...
We observe that the main issue is the cause of the Eager Execution mode. We give shallow look at your code and corresponding results as per CPU and GPU bases. It is true that numpy doesn't operate on GPU, so unlike tf-gpu, it doesn't encounter any data shifting overhead. But also it's quite noticeable how much fast com...
13
18
62,732,358
2020-7-4
https://stackoverflow.com/questions/62732358/how-to-find-which-dll-failed-in-importerror-dll-load-failed-while-importing-i
Context Are there commands to enhance the error message that is received such that python displays which .dll file it cannot find? For error: python test_cv2.py Traceback (most recent call last): File "test_cv2.py", line 1, in <module> import cv2 File "E:\Anaconda3\envs\py38\lib\site-packages\cv2\__init__.py", line 5, ...
Short answer: No. Although it is probably not completely impossible, it would require to bind a tool like dependenciesGUI in Python, in order to be able to call it in that given context (namely taking into account the actually search path for dll in Python and already loaded dynamics libraries). It would be quite a lot...
18
0
62,681,388
2020-7-1
https://stackoverflow.com/questions/62681388/residual-plot-for-residual-vs-predicted-value-in-python
I have run a KNN model. Now i want to plot the residual vs predicted value plot. Every example from different websites shows that i have to first run a linear regression model. But i couldn't understand how to do this. Can anyone help? Thanks in advance. Here is my model- train, validate, test = np.split(df.sample(frac...
Residuals are nothing but how much your predicted values differ from actual values. So, it's calculated as actual values-predicted values. In your case, it's residuals = y_test-y_pred. Now for the plot, just use this; import matplotlib.pyplot as plt plt.scatter(residuals,y_pred) plt.show()
12
9
62,784,718
2020-7-7
https://stackoverflow.com/questions/62784718/how-does-the-value-of-the-name-parameter-to-setuptools-setup-affect-the-results
I recently received a bundle of Python code, written by a graduate student at an academic lab, and consisting of a Python script and about half dozen single-file Python modules, used by by the script. All these files (script and modules) are on the same directory. I wanted to use pip to install this code in a virtual e...
Preamble: The Python glossary defines a package as "a Python module which can contain submodules or recursively, subpackages". What setuptools and the like create is usually referred to as a distribution which can bundle one or more packages (hence the parameter setup(packages=...)). I will use this meaning for the ter...
9
6
62,743,132
2020-7-5
https://stackoverflow.com/questions/62743132/ubuntu-18-04-command-pyenv-not-found-did-you-mean
So here is my Ubuntu version: No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 18.04.2 LTS Release: 18.04 Codename: bionic I'm trying to run the following command: pyenv install 3.6.2 but i get the error: Command 'pyenv' not found, did you mean: command 'pyvenv' from deb python3-venv command 'p...
First see if you have the curl already installed in your machine using the command: $ curl --version If you don't have, install the curl using: $ sudo apt-get install curl After that install the pyenv using the command: $curl https://pyenv.run | bash And after installation update your bashrc adding the lines: export PA...
32
82
62,745,734
2020-7-5
https://stackoverflow.com/questions/62745734/mypy-declares-iobytes-incompatible-with-binaryio
Consider the following code: from io import TextIOWrapper from typing import List from zipfile import ZipFile def read_zip_lines(zippath: str, filename: str) -> List[str]: with ZipFile(zippath) as zf: with zf.open(filename) as bfp: with TextIOWrapper(bfp, 'utf-8') as fp: return fp.readlines() Running mypy v0.782 on th...
This shorter test case with mypy 0.782 gets the same error: binary_file = io.open('foo.bin', 'rb') text_file = io.TextIOWrapper(binary_file, encoding='utf-8', newline='') whether binary_file is explicitly declared as IO[bytes] or inferred. Fix: Use mypy 0.770 or mypy 0.790. It was a regression in mypy's typeshed (Iss...
11
5
62,739,178
2020-7-5
https://stackoverflow.com/questions/62739178/django-save-multiple-versions-of-an-image
My application needs to save multiple versions of an uploaded Image. One high quality image and another one just for thumbnails use (low quality). Currently this is working most of the time but sometimes the save method simply fails and all of my Thumbnail images are getting deleted, especially then if I use the remove...
maybe if we look at the problem from another angle, we could solve it otherwise, out of the box. signals are very handy when it comes to handle images (add, update and delete) and below how i managed to solve your issue: in models.py: # from django.template.defaultfilters import slugify class Post(models.Model): id = m...
7
11
62,767,438
2020-7-7
https://stackoverflow.com/questions/62767438/expand-1-dim-vector-by-using-taylor-series-of-log1ex-in-python
I need to non-linearly expand on each pixel value from 1 dim pixel vector with taylor series expansion of specific non-linear function (e^x or log(x) or log(1+e^x)), but my current implementation is not right to me at least based on taylor series concepts. The basic intuition behind is taking pixel array as input neuro...
This is a really interesting question but I can't say that I'm clear on it as of yet. So, while I have some thoughts, I might be missing the thrust of what you're looking to do. It seems like you want to develop your own activation function instead of using something RELU or softmax. Certainly no harm there. And you ga...
10
7
62,686,305
2020-7-1
https://stackoverflow.com/questions/62686305/errorbar-in-legend-pandas-bar-plot
Is it possible to show the error bars in the legend? (Like i draw in red) They do not necessarily have to be the correct length, it is enough for me if they are indicated and recognizable. My working sample: import pandas as pd import matplotlib.pyplot as plt test = pd.DataFrame(data={'one':2000,'two':300,'three':50,'f...
The method I came up with was to draw 'ax.barh' and 'ax1.errorbar()' and then superimpose the legends of each on top of each other. On one side, I minimized the transparency so that the legend below is visible; the error bar looks different because I made it biaxial. import pandas as pd import matplotlib.pyplot as plt ...
9
2
62,683,732
2020-7-1
https://stackoverflow.com/questions/62683732/combining-strings-and-ints-to-create-a-date-string-results-in-typeerror
I am trying to combine the lists below to display a date in the format 'dd/hh:mm'. the lists are as follows: dd = [23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27] hh = [21, 23, 7, 9, 16, 19, 2, 5, 12, 15, 22, 1, 8, 11, 18, 21, 2, 8, 12, 12, 13, 13, 18, 22] mm = [18, 39, 3...
The following should work: finaltimes = ['{}/{}:{}'.format(*tpl) for tpl in zip(dd, hh, m)]
8
11
62,748,654
2020-7-6
https://stackoverflow.com/questions/62748654/python-3-8-shared-memory-resource-tracker-producing-unexpected-warnings-at-appli
I am using a multiprocessing.Pool which calls a function in 1 or more subprocesses to produce a large chunk of data. The worker process creates a multiprocessing.shared_memory.SharedMemory object and uses the default name assigned by shared_memory. The worker returns the string name of the SharedMemory object to the m...
In theory and based on the current implementation of SharedMemory, the warnings should be expected. The main reason is that every shared memory object you have created is being tracked twice: first, when it's produced by one of the processes in the Pool object; and second, when it's consumed by the main process. This i...
20
14
62,766,200
2020-7-7
https://stackoverflow.com/questions/62766200/create-csv-from-xml-json-using-python-pandas
I am trying to parse to an xml into multiple different Files - Sample XML <integration-outbound:IntegrationEntity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <integrationEntityHeader> <integrationTrackingNumber>281#963-4c1d-9d26-877ba40a4b4b#1583507840354</integrationTrackingNumber> <referenceCodeForEntity>2...
The xml is converted to dict and then the parsing logic is written , the reason for this is because the same can be used for json . The stackoverflow is amazingly helpful and the solution is build based on the responses from all these links . For simplicity i have created a 3 level nest xml. This works on Python3 <?xml...
8
2
62,775,254
2020-7-7
https://stackoverflow.com/questions/62775254/why-does-my-pygame-window-not-fit-in-my-4k3840x2160-monitor-scale-of-pygame-w
So I was trying to make a game with python and pygame but I noticed that I couldn't make a high resolution display because when I tried to make a display with more pixels, the pygame window was too big for my 4k (3840x2160) monitor. I should note that my monitor is connected to an old Dell laptop with a resolution of (...
After a bunch of source diving I believe I have found the solution: pyautogui imports pyscreeze for the functions center, grab, pixel, pixelMatchesColor, screenshot. On lines 63 to 71 of pyscreeze/__init__.py is the following: if sys.platform == 'win32': # On Windows, the monitor scaling can be set to something besides...
7
5
62,744,659
2020-7-5
https://stackoverflow.com/questions/62744659/attributeerror-tuple-object-has-no-attribute-rank-when-calling-fit-on-a-ker
I want to build a Neural Network with two inputs: for image data and for numeric data. So I wrote custom data generator for that. The train and validation dataframes contain 11 columns: image_name — path to the image; 9 numeric features; target — class for the item (last column). The code for custom generator (based ...
You need to convert all the individual objects returned by both the training and validation generators to Numpy arrays: yield [np.array(imgs), np.array(cols)], np.array(targets) Alternatively, a simpler and much more efficient solution is to not iterate over the data batch at all; instead, we can take advantage of th...
10
9
62,701,809
2020-7-2
https://stackoverflow.com/questions/62701809/count-if-in-multiple-index-dataframe
I have a multi-index dataframe and I want to know the percentage of clients who paid a certain threshold of debt for each of the 3 criteria: City, Card and Collateral. This is a working script: import pandas as pd d = {'City': ['Tokyo','Tokyo','Lisbon','Tokyo','Tokyo','Lisbon','Lisbon','Lisbon','Tokyo','Lisbon','Tokyo'...
TL;DR group_cols = ['City', 'Card', 'Colateral'] debt_col = '% Debt Paid' # (1) Bin the data that is in non-zero-width intervals bins = pd.IntervalIndex.from_breaks((0, 0.25, 0.5, 0.75, 1, np.inf), closed='right') ser_pt1 = df.groupby(group_cols, sort=False)[debt_col]\ .value_counts(bins=bins, sort=False, normalize=Tru...
7
4
62,765,652
2020-7-6
https://stackoverflow.com/questions/62765652/how-to-debug-the-stack-trace-that-causes-a-subsequent-exception-in-python
Python (and ipython) has very powerful post-mortem debugging capabilities, allowing variable inspection and command execution at each scope in the traceback. The up/down debugger commands allow changing frame for the stack trace of the final exception, but what about the __cause__ of that exception, as defined by the r...
You can use the with_traceback(tb) method to preserve the original exception's traceback: try: foo() except TypeError as err: barz = 5 raise ValueError().with_traceback(err.__traceback__) from err Note that I have updated the code to raise an exception instance rather than the exception class. Here is the full code sn...
12
8
62,717,970
2020-7-3
https://stackoverflow.com/questions/62717970/how-to-convert-data-type-for-list-of-tuples-string-to-float
g = [('Books', '10.000'),('Pen', '10'),('test', 'a')] Here '10.000' and '10' are strings How to convert to below format, string to float Expected out [('Books', 10.000),('Pen', 10),('test', 'a')] Here 10.000 and 10 are floats and a has to be string newresult = [] for x in result: if x.isalpha(): newresult.append(x) el...
you have a problem in your code because the x that you are using is a tuple. The elements of the list you provided are tuples type (String,String) so you need one more iteration on the elemts of the tuples. I have modified your code to : newresult = [] for tuple in result: temp = [] for x in tuple: if x.isalpha(): temp...
9
4
62,719,641
2020-7-3
https://stackoverflow.com/questions/62719641/why-pytorch-model-takes-multiple-image-size-inside-the-model
I am using a simple object detection model in PyTorch and using a Pytoch Model for Inferencing. When I am using a simple iterator over the code for k, image_path in enumerate(image_list): image = imgproc.loadImage(image_path) print(image.shape) with torch.no_grad(): y, feature = net(x) result = image.cuda() It prints ...
PyTorch has what is called a Dynamic Computational Graph (other explanation). It allows the graph of the neural network to dynamically adapt to its input size, from one input to the next, during training or inference. This is what you observe in your first example: providing an image as a Tensor of size [1, 3, 384, 320...
9
12
62,679,083
2020-7-1
https://stackoverflow.com/questions/62679083/how-do-i-separate-overlapping-cards-from-each-other-using-python-opencv
I am trying to detect playing cards and transform them to get a bird's eye view of the card using python opencv. My code works fine for simple cases but I didn't stop at the simple cases and want to try out more complex ones. I'm having problems finding correct contours for cards.Here's an attached image where I am try...
There are lots of approaches to find overlapping objects in the image. The information you have for sure is that your cards are all rectangles, mostly white and have the same size. Your variables are brightness, angle, may be some perspective distortion. If you want a robust solution, you need to address all that issue...
12
7
62,703,400
2020-7-2
https://stackoverflow.com/questions/62703400/python-how-to-type-hint-a-callable-with-wrapped
When passing around functions, I normally type hint them with typing.Callable. The docs for collections.abc.Callable state that it has four dunder methods: class collections.abc.Callable ABCs for classes that provide respectively the methods __contains__(), __hash__(), __len__(), and __call__(). At one point, I want ...
Obviously the easy answer is to add a # type: ignore comment. However, this isn't actually solving the problem, IMO. I decided to make a type stub for a callable with a __wrapped__ attribute. Based on this answer, here is my current solution: from typing import Callable, cast class WrapsCallable: """Stub for a Callable...
8
3
62,742,387
2020-7-5
https://stackoverflow.com/questions/62742387/how-to-use-weights-in-a-logistic-regression
I want to calculate (weighted) logistic regression in Python. The weights were calculated to adjust the distribution of the sample regarding the population. However, the results don´t change if I use weights. import numpy as np import pandas as pd import statsmodels.api as sm The data looks like this. The target varia...
I think one way is to use smf.glm() where you can provide the weights as freq_weights , you should check this section on weighted glm and see whether it is what you want to achieve. Below I provide an example where it is used in the same way as weights= in R : import pandas as pd import numpy as np import seaborn as sn...
11
13
62,721,186
2020-7-3
https://stackoverflow.com/questions/62721186/explain-a-surprising-parity-in-the-rounding-direction-of-apparent-ties-in-the-in
Consider the collection of floating-point numbers of the form 0.xx5 between 0.0 and 1.0: [0.005, 0.015, 0.025, 0.035, ..., 0.985, 0.995] I can make a list of all 100 such numbers easily in Python: >>> values = [n/1000 for n in range(5, 1000, 10)] Let's look at the first few and last few values to check we didn't make ...
It turns out that one can prove something stronger, that has nothing particularly to do with decimal representations or decimal rounding. Here's that stronger statement: Theorem. Choose a positive integer n <= 2^1021, and consider the sequence of length n consisting of the fractions 1/2n, 3/2n, 5/2n, ..., (2n-1)/2n. C...
8
4
62,697,599
2020-7-2
https://stackoverflow.com/questions/62697599/unable-to-send-receive-data-via-hc-12-uart-in-python
I've written some code to communicate between two Raspberry Pi's, using identical HC-12 433Mhz transceivers. I was able to successfully echo between the two Pi's using a direct serial connection and echo/cat, however am unable to replicate this using HC-12s, which theoretically work by a similar principal. I'm using th...
The pyserial readlines() function relies on the timeout parameter to know when end-of-file is reached - this is warned about in the doco. So with no timeout, the end never occurs, so it keeps buffering all lines read forever. So you can just add a timeout to the serial port open, and your existing code will begin to wo...
8
4
62,782,979
2020-7-7
https://stackoverflow.com/questions/62782979/logger-info-not-working-in-django-logging
Following is the logging snippet I have used in my django settings.py file. All the GET,POST requests are getting written to log but when i wrote logger.info("print something"), its not getting printed/captured in console as well as the log file Please suggest a workaround to capture logger.info() logs views.py import ...
It's probably because your views module doesn't have a logging level set, so it will inherit the root logger's default level of WARNING. If you add a root entry with a level of INFO, similarly to the documented examples, you should see messages from other modules. Alternatively you can specify logger names under the lo...
8
8
62,770,893
2020-7-7
https://stackoverflow.com/questions/62770893/how-to-add-another-attribute-in-dictionary-inside-a-one-line-for-loop
I have a list of dictionary and a string. I want to add a selected attribute in each dictionary inside the list. I am wondering if this is possible using a one liner. Here are my inputs: saved_fields = "apple|cherry|banana".split('|') fields = [ { 'name' : 'cherry' }, { 'name' : 'apple' }, { 'name' : 'orange' } ] This...
I don't necessarily think "one line way" is the best way. s = set(saved_fields) # set lookup is more efficient for d in fields: d['status'] = d['name'] in s fields # [{'name': 'cherry', 'status': True}, # {'name': 'apple', 'status': True}, # {'name': 'orange', 'status': False}] Simple. Explicit. Obvious. This updates ...
8
15
62,780,290
2020-7-7
https://stackoverflow.com/questions/62780290/more-efficient-way-to-add-columns-with-same-string-values-in-multiple-dataframes
I want to add a new column, Category, in each of my 8 similar dataframes. The values in this column are the same, they are also the df name, like df1_p8 in this example. I have used: In: df61_p8.insert(3,"Category","df61_p8", True) # or simply, df61_p8['Category']='df61_p8' Out: code violation_description Category 8949...
Keep it simple and explicit. for col_val, df in [ ('df61_p1', df61_p1), ('df61_p2', df61_p2), ('df61_p3', df61_p3), ('df61_p4', df61_p4), ('df61_p5', df61_p5), ('df61_p6', df61_p6), ('df61_p7', df61_p7), ('df61_p8', df61_p8), ]: df['Category'] = col_val While there are certainly more 'meta-programming-ey' ways of acco...
7
2
62,713,741
2020-7-3
https://stackoverflow.com/questions/62713741/tkinter-and-32-bit-unicode-duplicating-any-fix
I only want to show Chip, but I get both Chip AND Dale. It doesn't seem to matter which 32 bit character I put in, tkinter seems to duplicate them - it's not just chipmunks. I'm thinking that I may have to render them to png and then place them as images, but that seems a bit ... heavy-handed. Any other solutions? Is t...
The fundamental problem is that Tcl and Tk are not very happy with non-BMP (Unicode Basic Multilingual Plane) characters. Prior to 8.6.10, what happens is anyone's guess; the implementation simply assumed such characters didn't exist and was known to be buggy when they actually turned up (there's several tickets on var...
7
7
62,760,929
2020-7-6
https://stackoverflow.com/questions/62760929/how-can-i-run-a-streamlit-app-from-within-a-python-script
Is there a way to run the command streamlit run APP_NAME.py from within a python script, that might look something like: import streamlit streamlit.run("APP_NAME.py") As the project I'm working on needs to be cross-platform (and packaged), I can't safely rely on a call to os.system(...) or subprocess.
Hopefully this works for others: I looked into the actual streamlit file in my python/conda bin, and it had these lines: import re import sys from streamlit.cli import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main()) From here, you can see that running s...
28
28
62,768,327
2020-7-7
https://stackoverflow.com/questions/62768327/typing-protocol-class-init-method-not-called-during-explicit-subtype-const
Python's PEP 544 introduces typing.Protocol for structural subtyping, a.k.a. "static duck typing". In this PEP's section on Merging and extending protocols, it is stated that The general philosophy is that protocols are mostly like regular ABCs, but a static type checker will handle them specially. Thus, one would ex...
You can't instantiate a protocol class directly. This is currently implemented by replacing a protocol's __init__ with a method whose sole function is to enforce this restriction: def _no_init(self, *args, **kwargs): if type(self)._is_protocol: raise TypeError('Protocols cannot be instantiated') ... class Protocol(Gene...
12
16
62,757,921
2020-7-6
https://stackoverflow.com/questions/62757921/is-aws-boto-python-supporting-ses-signature-version-4
Due to AWS deprecating Signature Version 3 in Oct 2020 for SES, I want to handle this issue with AWS boto (Python). But I didn't see any doc related to boto supporting signature version 4 for SES. Is anyone having similar issue and have solutions?
My recommendation is that you migrate from boto, which is essentially deprecated, to boto3 because boto3 supports signature v4 by default (with the exception of S3 pre-signed URLs which has to be explicitly configured).
8
3
62,731,198
2020-7-4
https://stackoverflow.com/questions/62731198/wsl-2-pycharm-debugger-connection-time-out
I set up Pycharm to use a virtualenv inside wls 2, It works fine, I mean, I can run my project throught the button "run", The problem is I can't use the debugger, it's says connection time out, let me show you the full [erros][1]. ('Connecting to ', '172.21.176.1', ':', '63597') Could not connect to 172.21.176.1: 6359...
Firewall was the case. Unbloking connections from Pycharm (Eset firewall in my case) helped. See https://youtrack.jetbrains.com/issue/PY-39051
9
13
62,678,377
2020-7-1
https://stackoverflow.com/questions/62678377/plotly-how-to-set-up-multiple-subplots-with-grouped-legends
for each subplot I have 3 seperate line:2017 ,2018 and 2019 with 3 times "go.Scatter", each subplot represents one country (25 countries) with always these 3 years. I can use the subplot sample code but then all the 75 legends (25 X 3) will be all together with different colors and it's messy. I don't need different co...
A correct combination of legendgroup and showlegend should do the trick. With the setup below, all 2017 traces are assigned to the same legendgroup="2017". And all 2017 traces except the first have showlegend=False. And of course the same goes for the 2018 traces. Give it a try! Plot Complete code from plotly.subplots...
10
25
62,740,922
2020-7-5
https://stackoverflow.com/questions/62740922/check-if-value-exists-in-file
I am trying to read the following file line by line and check if a value exists in the file. What I am trying currently is not working. What am I doing wrong? If the value exists I do nothing. If it does not then I write it to the file. file.txt: 123 345 234 556 654 654 Code: file = open("file.txt", "a+") lines = file...
There are two problems here: .readlines() returns lines with \n not trimmed, so your check will not work properly. a+ mode opens a file with position set to the end of the file. So your readlines() currently returns an empty list! Here is a direct fixed version of your code, also adding context manager to auto-close ...
10
12
62,738,960
2020-7-5
https://stackoverflow.com/questions/62738960/on-aws-elastic-search-messageuser-anonymous-is-not-authorized-to-perform
I have created AWS elasticsearch domain https://search-xx-xx.us-east-1.es.amazonaws.com/ On click both elastic url and kibana below is the error i got {"Message":"User: anonymous is not authorized to perform: es:ESHttpGet"} Below is code which is working fine import boto3 from requests_aws4auth import AWS4Auth from el...
This error would indicate your ElasticSearch service does not support anonymous requests (those not signed with valid IAM credentials). Although your policy sees ok the official allow all policy looks like the below { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "e...
29
37
62,732,402
2020-7-4
https://stackoverflow.com/questions/62732402/can-i-omit-optional-if-i-set-default-to-none
For example: def foo(bar: int = None): pass When I check a type/annotation of bar pycharm tells me that it is Optional[int]. bar: int = None looks much cleaner rather then bar: Optional[int] = None, especially when you have 10+ parameters. So can I simply omit Optional? Will tools like mypy or other linters highlight ...
No. Omitting Optional was previously allowed, but has since been removed. A past version of this PEP allowed type checkers to assume an optional type when the default value is None [...] This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit. Some...
56
61
62,723,766
2020-7-3
https://stackoverflow.com/questions/62723766/how-to-get-type-hints-for-an-objects-attributes
I want to get the type hints for an object's attributes. I can only get the hints for the class and not an instance of it. I have tried using foo_instance.__class__ from here but that only shows the class variables. So in the example how do I get the type hint of bar? class foo: var: int = 42 def __init__(self): self.b...
This information isn't evaluated and only exists in the source code. if you must get this information, you can use the ast module and extract the information from the source code yourself, if you have access to the source code. You should also ask yourself if you need this information because in most cases reevaluating...
12
2
62,728,854
2020-7-4
https://stackoverflow.com/questions/62728854/how-to-place-spacy-en-core-web-md-model-in-python-package
I am building a python package and I am using Spacy library and Spacy model en_core_web_md. It can't be installed using pip. You can install it like this python -m spacy download en_core_web_md I have place en_core_web_md folder in my Python package. simple_eda init.py simple_eda.py en_core_web_md tests setup.py ...
This solved my issue. try: nlp = spacy.load('en') except OSError: print('Downloading language model for the spaCy POS tagger\n' "(don't worry, this will only happen once)", file=stderr) from spacy.cli import download download('en') nlp = spacy.load('en')
7
16
62,716,521
2020-7-3
https://stackoverflow.com/questions/62716521/plotly-how-to-add-text-to-existing-figure
Is it possible to add some text on the same html file as my plotly graph? For example : This is the code that generates a graph : data = pd.read_csv('file.csv') data.columns = ['price', 'place', 'date'] fig = px.scatter(data, x = "place", y = "price", ) fig.write_html("done.html") This graph will generate a pyplot gra...
You can use fig.update_layout(margin=dict()) to make room for an explanation, and then fig.add_annotation() to insert any text you'd like below the figure utself to get this: Complete code: import plotly.graph_objects as go import numpy as np x = np.arange(-4,5) y=x**3 yticks=list(range(y.min(), y.max(), 14)) #yticks....
11
21
62,722,599
2020-7-3
https://stackoverflow.com/questions/62722599/how-can-i-use-pytest-django-to-create-a-user-object-only-once-per-session
First, I tired this: @pytest.mark.django_db @pytest.fixture(scope='session') def created_user(django_db_blocker): with django_db_blocker.unblock(): return CustomUser.objects.create_user("User", "UserPassword") def test_api_create(created_user): user = created_user() assert user is not None But I got an UndefinedTable ...
@hoefling had the answer, I needed to pass django_db_setup instead. @pytest.fixture(scope='session') def created_user(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): return CustomUser.objects.create_user("User", "UserPassword")
7
10
62,705,271
2020-7-2
https://stackoverflow.com/questions/62705271/connect-to-flask-server-from-other-devices-on-same-network
Dear smart people of stackoverflow, I know this question has been asked a lot here but none of the posted solutions have worked for me as of yet. Any help here would be much appreciated: The Problem: Cannot connect to flask app server from other devices (PCs, mobiles) on the same network. (in other words: localhost wor...
I solved the issue by changing my home network profile to private instead of public, which allows my PC to be discoverable. Completely overlooked that! Hope this helps someone!
12
14
62,716,077
2020-7-3
https://stackoverflow.com/questions/62716077/remove-white-border-from-dots-in-a-seaborn-scatterplot
The scatterplot from seaborn produces dots with a small white boarder. This is helpful if there are a few overlapping dots, but it becomes visually noisy once there are many overlaying dots. How can the white borders be removed? import seaborn as sns; sns.set() import matplotlib.pyplot as plt tips = sns.load_dataset("t...
Instead of edgecolors use linewidth = 0: import seaborn as sns; sns.set() import matplotlib.pyplot as plt tips = sns.load_dataset("tips") ax = sns.scatterplot(x="total_bill", y="tip", data=tips, linewidth=0)
17
23
62,715,570
2020-7-3
https://stackoverflow.com/questions/62715570/failing-to-install-psycopg2-binary-on-new-docker-container
I have encountered a problem while trying to run my django project on a new Docker container. It is my first time using Docker and I can't seem to find a good way to run a django project on it. Having tried multiple tutorials, I always get the error about psycopg2 not being installed. requirements.txt: -i https://pypi....
On Alpine Linux, you will need to compile all packages, even if a pre-compiled binary wheel is available on PyPI. On standard Linux-based images, you won't (https://pythonspeed.com/articles/alpine-docker-python/ - there are also other articles I've written there that might be helpful, e.g. on security). So change your ...
41
27
62,706,402
2020-7-2
https://stackoverflow.com/questions/62706402/difference-between-python-console-and-terminal-in-pycharm
I am a beginner in Python. I started using PyCharm recently but I don't know what's the difference between Terminal and console. Some of the commands in Terminal do not work in console.
Before we can talk about the differences, we need to talk about what the two are in practice. The Terminal, essentially replaces your command-prompt/power-shell on windows and the terminal app on Mac, giving you a way to access them without leaving PyCharm. The PyCharm console on the other hand, is a more advanced ver...
8
8
62,712,023
2020-7-3
https://stackoverflow.com/questions/62712023/selenium-with-chrome-driver-taking-screenshots-at-double-resolution-on-retina-di
I am using Selenium with Chrome driver to taking some website screenshots. I need the screenshots to be at very specific resolution (1024x768). I've noticed that although the browser is correctly set at this resolution, the screenshot on disk is saved at double resolution (2048x1536). I suspect this is due the retina r...
Found a possible solution: chrome_options.add_argument('--force-device-scale-factor=1')
7
13