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,054,541
2020-7-23
https://stackoverflow.com/questions/63054541/how-to-type-the-new-method-in-a-python-metaclass-so-that-mypy-is-happy
I am trying to type the __new__ method in a metaclass in Python so that it pleases mypy. The code would be something like this (taken from pep-3115 - "Metaclasses in Python 3000" and stripped down a bit): from __future__ import annotations from typing import Type # The metaclass class MetaClass(type): # The metaclass i...
First, the return type is MetaClass, not type. Second, you need to explicitly cast the return value, since type.__new__ doesn't know it is returning an instance of MetaClass. (Its specific return type is determined by its first argument, which isn't known statically.) from __future__ import annotations from typing impo...
11
10
63,051,253
2020-7-23
https://stackoverflow.com/questions/63051253/using-class-or-static-method-as-default-factory-in-dataclasses
I want to populate an attribute of a dataclass using the default_factory method. However, since the factory method is only meaningful in the context of this specific class, I want to keep it inside the class (e.g. as a static or class method). For example: from dataclasses import dataclass, field from typing import Lis...
One possible solution is to move it to __post_init__(self). For example: @dataclass class Deck: cards: List[str] = field(default_factory=list) def __post_init__(self): if not self.cards: self.cards = self.create_cards() def create_cards(self): return ['King', 'Queen'] Output: d1 = Deck() print(d1) # prints Deck(cards=...
11
8
63,047,762
2020-7-23
https://stackoverflow.com/questions/63047762/correct-way-to-register-a-parameter-for-model-in-pytorch
I tried to define a simple model in Pytorch. The model computes negative log prob for a gaussian distribution: import torch import torch.nn as nn class GaussianModel(nn.Module): def __init__(self): super(GaussianModel, self).__init__() self.register_parameter('mean', nn.Parameter(torch.zeros(1), requires_grad=True)) se...
You're over complicating registering your parameter. You can just assign a new self.mean attribute to be an nn.Parameter then use it like a tensor for the most part. nn.Module overrides the __setattr__ method which is called every time you assign a new class attribute. One of the things it does is check to see if you a...
8
18
63,047,555
2020-7-23
https://stackoverflow.com/questions/63047555/no-chrome-binary-at-the-given-path-macos-selenium-python
I just started to work with selenium web driver with chromedrivers. I am using MacOS and When I try to set the path for the chrome browser as a binary path I always face the same error saying no chrome binary at so and so path given. import os from selenium import webdriver from selenium.webdriver.chrome.options import...
This resolved the issue chrome_options.binary_location = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
9
12
63,026,713
2020-7-22
https://stackoverflow.com/questions/63026713/leading-zeros-are-not-allowed-in-python
I have a code for finding the possible combinations of a given string in the list. But facing an issue with leading zero getting error like SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers . How to overcome this issue as I wanted to pass values with leading z...
Finally, I got my answer. Below is the working code. def permute_string(str): if len(str) == 0: return [''] prev_list = permute_string(str[1:len(str)]) next_list = [] for i in range(0,len(prev_list)): for j in range(0,len(str)): new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1] if new_str not in next_list: ...
14
-4
63,038,345
2020-7-22
https://stackoverflow.com/questions/63038345/how-to-make-fastapi-pickup-changes-in-an-api-routing-file-automatically-while-ru
I am running FastApi via docker by creating a sevice called ingestion-data in docker-compose. My Dockerfile : FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 # Environment variable for directory containing our app ENV APP /var/www/app ENV PYTHONUNBUFFERED 1 # Define working directory RUN mkdir -p $APP WORKDIR $APP COP...
Quick answer: Yes :) In the Dockerfile, you copying your app into /var/www/app. The instructions form the Dockerfile are executed when you build your image (docker build -t <imgName>:<tag>) If you change the code later on, how could the image be aware of that? However, you can mount a volume(a directory) from your hos...
7
5
63,039,065
2020-7-22
https://stackoverflow.com/questions/63039065/fig-ax-plt-subplots-meaning
I've been using matplotlib for a while and I don't actually understand what this line does. fig, ax = plt.subplots() Could someone explain?
plt.subplots() is basically a (very nice) shortcut for initializing a figure and subplot axes. See the docs here. In particular, >>> fig, ax = plt.subplots(1, 1) is essentially equivalent to >>> fig = plt.figure() >>> ax = fig.add_subplot(1, 1) But plt.subplots() is most useful for constructing several axes at once, ...
6
9
63,029,186
2020-7-22
https://stackoverflow.com/questions/63029186/set-axis-in-altair-bar-chart-as-a-integer
I am trying to visualization a bar plot of many statistic data, and wanna set y-axis as a integer (there is no float type data in my dataset) This is one of the charts, which I want to change the axis. Image Link This is my python source code to visualization this chart def plot_3(data,x,y,width): selector = alt.select...
You could set tickMinStep=1. import altair as alt import pandas as pd source = pd.DataFrame({ 'a': ['A', 'B', 'C', 'D'], 'b': [2.0, 1.0, 1.0, 3.0] }) alt.Chart(source).mark_bar().encode( alt.X('a:N'), alt.Y('b:Q', axis=alt.Axis(tickMinStep=1)) )
6
9
63,038,379
2020-7-22
https://stackoverflow.com/questions/63038379/add-title-to-networkx-plot
I want my code to create a plot with a title. With the code below the plot gets created but no title. Can someone clue me in on what I am doing wrong? import pandas as pd import networkx as nx from networkx.algorithms import community import matplotlib.pyplot as plt from datetime import datetime ... G = nx.from_pandas_...
I can only think of some intermediate step triggering a call to plt.show before your call to plt.title (though it doesn't look like that should be the case with the shared code). Try setting the title beforehand, and setting an ax, here's an example: plt.figure(figsize=(10,5)) ax = plt.gca() ax.set_title('Random graph'...
10
10
63,026,648
2020-7-22
https://stackoverflow.com/questions/63026648/errormessage-class-decimal-inexact-class-decimal-rounded-while
Code is below import json from decimal import Decimal from pprint import pprint import boto3 def update_movie(title, year, rating=None, plot=None, actors=None, dynamodb=None): if not dynamodb: dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Movies') response = table.update_item( Key={ 'year': year, 'title...
The problem is that DynamoDB's representation of floating-point numbers is different from Python's: DynamoDB represents floating point numbers with a decimal representation. So "8.3" can be represented exactly - with no rounding or inexactness. Python uses, as traditional, base-2 representation, so it can't represent ...
16
33
63,026,749
2020-7-22
https://stackoverflow.com/questions/63026749/atom-cant-search-for-packages-or-themes-in-the-install-packages-section-of-set
I'm new to Atom (and relatively new to programming) and I just installed it about a few hours ago. I was trying to set it up by installing some new packages and themes in the Install Packages section of Settings. It was working fine for a while but now I'm getting errors when I try to search. A red box appears below th...
Atom Server seems to have a problem today. Packages that were installed well a few days ago are not available today.
7
3
63,027,848
2020-7-22
https://stackoverflow.com/questions/63027848/discord-py-error-typeerror-new-got-an-unexpected-keyword-argument-deny
Yesterday, my code was perfectly fine. Everything was running... and it was going great. All of a sudden, this error: TypeError: __new__() got an unexpected keyword argument 'deny_new' pops up in my PyCharm console. I've looked it up on the internet but I've only found a similiar questions with zero answers to it. I h...
Discord pushed a new change that changes the overwrites object. Just reinstall the latest version of Discord.py python3 -m pip install -U discord.py That's it.
58
71
62,983,756
2020-7-19
https://stackoverflow.com/questions/62983756/what-is-pyproject-toml-file-for
Background I was about to try Python package downloaded from GitHub, and realized that it did not have a setup.py, so I could not install it with pip install -e <folder> Instead, the package had a pyproject.toml file which seems to have very similar entries as the setup.py usually has. What I found Googling lead me in...
What is it for? Currently there are multiple packaging tools being popular in Python community and while setuptools still seems to be prevalent it's not a de facto standard anymore. This situation creates a number of hassles for both end users and developers: For setuptools-based packages installation from source / bu...
410
154
62,941,378
2020-7-16
https://stackoverflow.com/questions/62941378/how-to-sort-glob-glob-numerically
I have a bunch of files sorted numerically on a folder, when I try to sort glob.glob I never get the files in the right order. file examples and expected output sorting folder ------ C:\Users\user\Desktop\folder\1 sample.mp3 C:\Users\user\Desktop\folder\2 sample.mp3 C:\Users\user\Desktop\folder\3 sample.mp3 C:\Users\u...
The general answer would catch the number with re.match() and to convert that number (string) to integer with int(). Use these numbers to sort the files with sorted() Code import re import math from pathlib import Path file_pattern = re.compile(r'.*?(\d+).*?') def get_order(file): match = file_pattern.match(Path(file)....
9
6
62,994,795
2020-7-20
https://stackoverflow.com/questions/62994795/how-to-secure-fastapi-api-endpoint-with-jwt-token-based-authorization
I am a little new to FastAPI in python. I am building an API backend framework that needs to have JWT token based authorization. Now, I know how to generate JWT tokens, but not sure how to integrate that with API methods in fast api in Python. Any pointers will be really appreciated.
With some help from my friend and colleague, I was able to solve this problem, and wanted to share this solution with the community. This is how it looks like now: Python Code ---- import json import os import datetime from fastapi import HTTPException, Header from urllib.request import urlopen from jose import jwt fro...
25
13
63,001,988
2020-7-20
https://stackoverflow.com/questions/63001988/how-to-remove-background-of-images-in-python
I have a dataset that contains full width human images I want to remove all the backgrounds in those Images and just leave the full width person, my questions: is there any python code that does that ? and do I need to specify each time the coordinate of the person object?
Here is one way to use Python/OpenCV. Read the input Convert to gray Threshold and invert as a mask Optionally apply morphology to clean up any extraneous spots Anti-alias the edges Convert a copy of the input to BGRA and insert the mask as the alpha channel Save the results Input: import cv2 import numpy as np # l...
16
42
62,980,464
2020-7-19
https://stackoverflow.com/questions/62980464/cant-install-pyqt5-on-python-3-with-spyder-ide
So I'm trying to install the PyQt package so I just did this on my Anaconda Prompt: C:\Users\USER>pip install PyQt5 Collecting PyQt5 Using cached PyQt5-5.15.0-5.15.0-cp35.cp36.cp37.cp38-none-win_amd64.whl (64.5 MB) Collecting PyQt5-sip<13,>=12.8 Using cached PyQt5_sip-12.8.0-cp37-cp37m-win_amd64.whl (62 kB) ERROR: spyd...
To install PyQt5 without errors try this. First install pyqtwebengine version 5.12 and then install pyqt5 version 5.12, using the following commands: pip install --upgrade --user pyqtwebengine==5.12 pip install --upgrade --user pyqt5==5.12 By this, I have successfully installed pyqt5
11
33
62,956,690
2020-7-17
https://stackoverflow.com/questions/62956690/install-local-wheel-file-with-requirements-txt
Have a local package ABC-0.0.2-py3-none-any.whl. I want to install it in the different project through requrements.txt. e.g. requirements.txt ABC==0.0.2 Flask==1.1.2 flask-restplus==0.13.0 gunicorn==20.0.4 Is it possible to install the ABC package this way. ABC-0.0.2-py3-none-any.whl is included in source code. I had ...
This is called a direct reference. Since version 19.3, pip support this in both command line and requirement files. Check out an example from the official documentation. As to OP's question, simply put the local wheel's relative path, i.e., ./<my_wheel_dir>/<my_wheel.whl>, in requirement.txt, e.g., ./local_wheels/ABC-0...
44
65
62,919,271
2020-7-15
https://stackoverflow.com/questions/62919271/how-do-i-define-a-typing-union-dynamically
I am using Typeguard in a couple if projects for type checking at run time in Python. It works pretty well. I have encountered a situation where the type of a function parameter is a typing.Union made up of a few dynamically collected data types. E.g. def find_datatypes(): # some stuff ... return (str, int) # dynamical...
You can kind of do it: my_union = typing.Union[datatypes] At runtime, thing[x, y] is already equivalent to thing[(x, y)]. That said, there are limitations to keep in mind. Particularly, when using string annotations, my_union will have to be available in some_function's global namespace for typeguard or anything else ...
24
18
62,997,313
2020-7-20
https://stackoverflow.com/questions/62997313/remove-first-item-from-python-dict
Good afternoon. I'm sorry if my question may seem dumb or if it has already been posted (I looked for it but didn't seem to find anything. If I'm wrong, please let me know: I'm new here and I may not be the best at searching for the correct questions). I was wondering if it was possible to remove (pop) a generic item f...
ex_dict.popitem() it removes the last (most recently added) element from the dictionary
8
3
62,986,778
2020-7-19
https://stackoverflow.com/questions/62986778/fastapi-handling-and-redirecting-404
How can i redirect a request with FastAPI if there is a HTTPException? In Flask we can achieve that like this: @app.errorhandler(404) def handle_404(e): if request.path.startswith('/api'): return render_template('my_api_404.html'), 404 else: return redirect(url_for('index')) Or in Django we can use django.shortcuts: f...
I know it's too late but this is the shortest approach to handle 404 exceptions in your personal way. Redirect from fastapi.responses import RedirectResponse @app.exception_handler(404) async def custom_404_handler(_, __): return RedirectResponse("/") Custom Jinja Template from fastapi.templating import Jinja2Template...
19
20
63,006,575
2020-7-21
https://stackoverflow.com/questions/63006575/what-is-the-difference-between-maxpool-and-maxpooling-layers-in-keras
I just started working with keras and noticed that there are two layers with very similar names for max-pooling: MaxPool and MaxPooling. I was surprised that I couldn't find the difference between these two on Google; so I am wondering what the difference is between the two if any.
They are the same... You can test it on your own import numpy as np import tensorflow as tf from tensorflow.keras.layers import * # create dummy data X = np.random.uniform(0,1, (32,5,3)).astype(np.float32) pool1 = MaxPool1D()(X) pool2 = MaxPooling1D()(X) tf.reduce_all(pool1 == pool2) # True I used 1D max-pooling but t...
29
21
62,956,054
2020-7-17
https://stackoverflow.com/questions/62956054/how-to-install-pillow-on-termux
I am using Termux for quite a while now and would like to install "Pillow" library on it. Whenever I try to install Pillow using "pip" it shows me the below errors. At first I thought I need to upgrade pip, but it did not help. I have also cleared caches, to no avail. Error $ python3 -m pip install Pillow==7.2.0 Collec...
First download the wheel module from pypi pip install wheel Then install the libjpeg-turbo package. pkg install libjpeg-turbo And now install Pillow with: LDFLAGS="-L/system/lib/" CFLAGS="-I/data/data/com.termux/files/usr/include/" pip install Pillow Note: If you are using an aarch64 device, set the LDFLAGS flag to ...
10
27
62,954,167
2020-7-17
https://stackoverflow.com/questions/62954167/get-a-list-of-all-pytest-node-ids-using-python
Do you know if there is a way to collect all pytest node ids (as presented here) using the pytest python API ? I have found the --collect-only parameter of pytest, but I can't figure out how to get the output using python ? Thanks in advance !
If you want to access nodeids programmatically, best is to write a small plugin that will store them on test collection. Example: import pytest class NodeidsCollector: def pytest_collection_modifyitems(self, items): self.nodeids = [item.nodeid for item in items] def main(): collector = NodeidsCollector() pytest.main(['...
8
6
62,953,704
2020-7-17
https://stackoverflow.com/questions/62953704/valueerror-the-number-of-fixedlocator-locations-5-usually-from-a-call-to-set
this piece of code was working before, however, after creating a new environment , it stopped working for the line plt.xticks(x, months, rotation=25,fontsize=8) if i comment this line then no error, after putting this line error is thrown ValueError: The number of FixedLocator locations (5), usually from a call to set...
I also stumbled across the error and found that making both your xtick_labels and xticks a list of equal length works. So in your case something like : def month(num): # returns month name based on month number num_elements = len(x) X_Tick_List = [] X_Tick_Label_List=[] for item in range (0,num_elements): X_Tick_List.a...
35
17
62,917,910
2020-7-15
https://stackoverflow.com/questions/62917910/how-can-i-export-pandas-dataframe-to-google-sheets-using-python
I managed to read data from a Google Sheet file using this method: # ACCES GOOGLE SHEET googleSheetId = 'myGoogleSheetId' workSheetName = 'mySheetName' URL = 'https://docs.google.com/spreadsheets/d/{0}/gviz/tq?tqx=out:csv&sheet={1}'.format( googleSheetId, workSheetName ) df = pd.read_csv(URL) However, after generating...
Yes, there is a module called "gspread". Just install it with pip and import it into your script. Here you can find the documentation: https://gspread.readthedocs.io/en/latest/ In particular their section on Examples of gspread with pandas. worksheet.update([dataframe.columns.values.tolist()] + dataframe.values.tolist(...
28
22
62,951,520
2020-7-17
https://stackoverflow.com/questions/62951520/pythons-lru-cache-on-inner-function-doesnt-seem-to-work
I'm trying to use functools.lru_cache to cache the result of an inner function, but the cache doesn't seem to work as expected. I have a function that performs some logic and then calls a rather expensive function. I'd like to cache the result of the expensive function call and though I'd just apply the lru_cache to an...
It does not work as intended because the inner_function gets redefined each time partially_cached is called, and so is the cached version. So each cached version gets called only once. See memoizing-decorator-keeping-stored-values Additionally, if you mock a decorated function you need to apply the decorator again. See...
12
9
63,011,748
2020-7-21
https://stackoverflow.com/questions/63011748/contour-iso-z-or-threshold-lines-in-seaborn-heatmap
Is there a way to automatically add contour (iso-z) lines to a heatmap with concrete x and y values? Please consider the official seaborn flights dataset: import seaborn as sns flights = sns.load_dataset("flights") flights = flights.pivot("month", "year", "passengers") sns.heatmap(flights, annot=True, fmt='d') I imagi...
You can use aLineCollection: import seaborn as sns import numpy as np from matplotlib.collections import LineCollection flights = sns.load_dataset("flights") flights = flights.pivot("month", "year", "passengers") ax = sns.heatmap(flights, annot=True, fmt='d') def add_iso_line(ax, value, color): v = flights.gt(value).di...
8
8
62,961,627
2020-7-17
https://stackoverflow.com/questions/62961627/oserror-error-no-file-named-pytorch-model-bin-tf-model-h5-model-ckpt-in
When I load the BERT pretrained model online I get this error OSError: Error no file named ['pytorch_model.bin', 'tf_model.h5', 'model.ckpt.index'] found in directory uncased_L-12_H-768_A-12 or 'from_tf' set to False what should I do?
Here is what I found. Go to the following link, and click the circled to download, rename it to pytorch_model.bin, and drop it to the directory of biobert-nli, then the issue is resolved. Didn't figure out how to clone from the link. https://huggingface.co/gsarti/biobert-nli/tree/main
12
7
63,001,429
2020-7-20
https://stackoverflow.com/questions/63001429/what-is-the-difference-between-pathlib-glob-and-iterdir
Suppose I'm writing code using pathlib and I want to iter over all the files in the same level of a directory. I can do this in two ways: p = pathlib.Path('/some/path') for f in p.iterdir(): print(f) p = pathlib.Path('/some/path') for f in p.glob('*'): print(f) Is one of the options better in any way?
Expansion of my comment: Why put the API to extra work parsing and testing against a filter pattern when you could just... not? glob is better when you need to make use of the filtering feature and the filter is simple and string-based, as it simplifies the work. Sure, hand-writing simple matches (filtering iterdir via...
28
32
62,912,397
2020-7-15
https://stackoverflow.com/questions/62912397/open3d-visualizing-multiple-point-clouds-as-a-video-animation
I have generated multiple point clouds using a RGB+depth video, and would like to visualize the multiple point clouds as a video or animation. Currently I am using Python, part of my code is as follows: for i in range(1,10) pcd = Track.create_pcd(i) o3d.visualization.draw_geometries([pcd]) pcd_list.append(pcd) When I ...
You can use Open3D Non-blocking visualization. It'll be like this vis = o3d.visualization.Visualizer() vis.create_window() # geometry is the point cloud used in your animaiton geometry = o3d.geometry.PointCloud() vis.add_geometry(geometry) for i in range(icp_iteration): # now modify the points of your geometry # you ca...
8
6
62,976,648
2020-7-19
https://stackoverflow.com/questions/62976648/architecture-flask-vs-fastapi
I have been tinkering around Flask and FastAPI to see how it acts as a server. One of the main things that I would like to know is how Flask and FastAPI deal with multiple requests from multiple clients. Especially when the code has efficiency issues (long database query time). So, I tried making a simple code to under...
This seemed a little interesting, so i ran a little tests with ApacheBench: Flask from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class Root(Resource): def get(self): return {"message": "hello"} api.add_resource(Root, "/") FastAPI from fastapi import FastAPI app = F...
51
59
62,934,384
2020-7-16
https://stackoverflow.com/questions/62934384/how-to-add-timestamp-to-each-request-in-uvicorn-logs
When I run my FastAPI server using uvicorn: uvicorn main:app --host 0.0.0.0 --port 8000 --log-level info The log I get after running the server: INFO: Started server process [405098] INFO: Waiting for application startup. INFO: Connect to database... INFO: Successfully connected to the database! INFO: Application star...
You can use Uvicorn's LOGGING_CONFIG import uvicorn from uvicorn.config import LOGGING_CONFIG from fastapi import FastAPI app = FastAPI() def run(): LOGGING_CONFIG["formatters"]["default"]["fmt"] = "%(asctime)s [%(name)s] %(levelprefix)s %(message)s" uvicorn.run(app) if __name__ == '__main__': run() Which will return ...
22
18
62,979,389
2020-7-19
https://stackoverflow.com/questions/62979389/is-there-a-best-practice-to-make-a-package-pep-561-compliant
I'm writing a Python project which is published as a package to a pypi-like repository (using setuptools and twine). I use type hints in my code. The issue is, when importing the package from a different project and running mypy, I get the following error: error: Skipping analyzing 'XXX': found module but no type hints...
As mentioned before, You need to add the py.typed in the package folder of the module. You also need to add that file to the setup.py package_data - otherwise the file would not be part of the package when You deploy it. I personally put the type annotations in the code and dont create extra stub files - but that is on...
43
30
62,986,053
2020-7-19
https://stackoverflow.com/questions/62986053/breaking-cycles-in-a-digraph-with-the-condition-of-preserving-connectivity-for-c
I have a digraph consisting of a strongly connected component (blue) and a set of nodes (orange) that are the inputs to it. The challenge is to break as many cycles as possible with a minimum of removed edges. In addition, there must be a path from each orange node to each blue node. I solve the problem with a brute f...
The problem as stated is NP-Hard. Not sure if it is in NP either. In order to verify NP-hardness of the problem, consider graphs such that every blue node has an incoming edge from an orange node. For such graphs, what we need is that the graph after removing edges continues to be strongly connected. We also assume tha...
10
3
63,001,954
2020-7-20
https://stackoverflow.com/questions/63001954/python-apscheduler-how-does-asyncioscheduler-work
I'm having a hard time understanding how the AsyncIOScheduler works, and how is it non blocking? If my job is executing a blocking function, will the AsyncIOScheduler be blocking? And what if I use AsyncIOScheduler with ThreadPoolExecutor? How does that work? Can I await the job execution?
So, in APScheduler there are 3 important components: The Scheduler The Executor(s) The Datastore(s) For this question, only 1 and 2 are relevant. The Scheduler is simply who decides when to call the jobs based on their interval settings, in the case of AsyncIOScheduler it uses asyncio to make the waiting period non b...
15
10
63,012,515
2020-7-21
https://stackoverflow.com/questions/63012515/how-to-detect-whether-zlib-is-available-and-whether-zip-deflated-is-available
The zipfile.ZipFile documentation says that ZIP_DEFLATED can be used as compression method only if zlib is available, but neither zipfile module specification nor zlib module specification says anything about when zlib might not be available, or how to check for its availability. I work on Windows and when I install an...
On Ubuntu if you install Python 3 using apt, e.g. sudo apt install python3.8, zlib will be installed as a dependency. Another way is to install Python 3 from source code. In this case, you need to install all prerequisites, including zlib1g-dev, (and this action is sometimes forgotten to do) and then compile and insta...
11
12
62,960,983
2020-7-17
https://stackoverflow.com/questions/62960983/simple-captcha-solving
I'm trying to solve some simple captcha using OpenCV and pytesseract. Some of captcha samples are: I tried to the remove the noisy dots with some filters: import cv2 import numpy as np import pytesseract img = cv2.imread(image_path) _, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) img = cv2.morphologyEx(img...
I've taken a much more direct approach to filtering ink splotches from pdf documents. I won't share the whole thing it's a lot of code, but here is the general strategy I adopted: Use Python Pillow library to get an image object where you can manipulate pixels directly. Binarize the image. Find all connected pixels an...
11
2
62,992,595
2020-7-20
https://stackoverflow.com/questions/62992595/pandas-drop-consecutive-duplicate-rows-only-ignoring-specific-columns
I have a dataframe below df = pd.DataFrame({ 'ID': ['James', 'James', 'James', 'James', 'Max', 'Max', 'Max', 'Max', 'Max', 'Park', 'Park','Park', 'Park', 'Tom', 'Tom', 'Tom', 'Tom'], 'From_num': [578, 420, 420, 'Started', 298, 78, 36, 298, 'Started', 28, 28, 311, 'Started', 60, 520, 99, 'Started'], 'To_num': [96, 578, ...
It's a bit late, but does this do what you wanted? This drops consecutive duplicates ignoring "Date". t = df[['ID', 'From_num', 'To_num']] df[(t.ne(t.shift())).any(axis=1)] ID From_num To_num Date 0 James 578 96 2020-05-12 1 James 420 578 2020-02-02 3 James Started 420 2019-06-18 4 Max 298 36 2019-08-26 5 Max 78 298 20...
8
7
62,960,775
2020-7-17
https://stackoverflow.com/questions/62960775/discord-py-make-a-bot-react-to-its-own-messages
I am trying to make my discord bot react to its own message, pretty much. The system works like this: A person uses the command !!bug - And gets a message in DM', she/she is supposed to answer those questions. And then whatever he/she answered, it will be transferred an embedded message to an admin text-channel. But I ...
In discord.py@rewrite, you have to use discord.Message.add_reaction: emojis = ['emoji 1', 'emoji_2', 'emoji 3'] adminBug = bot.get_channel(733721953134837861) message = await adminBug.send(embed=embed) for emoji in emojis: await message.add_reaction(emoji) Then, to exploit reactions, you'll have to use the discord.on_...
9
17
63,019,348
2020-7-21
https://stackoverflow.com/questions/63019348/how-to-set-a-title-above-each-marker-which-represents-a-same-label
I have a first version of legend in the following plot : with the following code : # Plot and save : kmax = 0.3 p11, = plt.plot([0], marker='None', linestyle='None', label='$k_{max} = 0.3$') p1, = plt.plot(FoM_vs_Density_array_1[:,0],FoM_vs_Density_array_1[:,1], '-b', label = '$GC_{sp}$') p2, = plt.plot(FoM_vs_Density...
To tackle your issues you can try the following: 1.1 To increase the space between the markers you can provide the additional parameter pad to HandlerTuple() (from here). It will adjust the spacing between the different marker sections. This will look like: l = plt.legend(..., handler_map={tuple: HandlerTuple(ndivide=N...
9
4
62,993,366
2020-7-20
https://stackoverflow.com/questions/62993366/color-calibration-with-color-checker-using-using-root-polynomial-regression-not
For a quantification project, I am in need of colour corrected images which produce the same result over and over again irrespective of lighting conditions. Every image includes a X-Rite color-checker of which the colors are known in matrix format: Reference=[[170, 189, 103],[46, 163, 224],[161, 133, 8],[52, 52, 52],[1...
Here are a few recommendations: As stated in my comment above we had an implementation issue with the Root-Polynomial variant from Finlayson (2015) which should be fixed in the develop branch. You are passing integer and encoded values to the colour.colour_correction definition. I would strongly recommend that you: C...
10
5
63,017,653
2020-7-21
https://stackoverflow.com/questions/63017653/download-file-using-s3fs
I am trying to download a csv file from an s3 bucket using the s3fs library. I have noticed that writing a new csv using pandas has altered data in some way. So I want to download the file directly in its raw state. The documentation has a download function but I do not understand how to use it: download(self, rpath, l...
for file in files: fs.download(file,'test.csv') Modified to download all files in the directory: import pandas as pd import datetime import os import s3fs import numpy as np #Creds for s3 fs = s3fs.S3FileSystem(key=mykey, secret=mysecretkey) bucket = "s3://mys3bucket/mys3bucket" #files references the entire bucket. fi...
10
13
63,019,506
2020-7-21
https://stackoverflow.com/questions/63019506/python-get-value-of-env-variable-from-a-specific-env-file
In python, is there a way to retrieve the value of an env variable from a specific .env file? For example, I have multiple .env files as follows: .env.a .env.a ... And I have a variable in .env.b called INDEX=4. I tried receiving the value of INDEX by doing the following: import os os.getenv('INDEX') But this value re...
This is a job for ConfigParser or ConfigObj. ConfigParser is built into the Python standard library, but has the drawback that it REALLY wants section names. Below is for Python3. If you're still using Python2, then use import ConfigParser import configparser config = configparser.ConfigParser() config.read('env.b') in...
8
9
63,012,346
2020-7-21
https://stackoverflow.com/questions/63012346/how-to-activate-virtual-environment-in-vscode-when-running-scripts-are-disabled
I created a virtual environment in vscode in a folder called server by typing: python -m venv env And I opened the server folder, select interpreter Python 3.8.1 64-bit('env':venv) then I got following error: I can't find any solution to this and I am stuck for hours.
It seems that it is going to activate the environment through a powershell script. And running such scripts is turned off by default. Also, usually a virtual environment is activated through cmd and .bat script. You could either turn on running powershell script or make VS Code activate an environment through cmd and ....
10
17
63,002,350
2020-7-20
https://stackoverflow.com/questions/63002350/ignore-missing-columns-in-usecol-parameter
I'm reading a table from csv and only want a subset of the columns. The list I'm using to subset contains field names that may not exist in the table I'm reading. For example: # contents of sample.csv: #a,b,c #1,2,3 #4,5,6 subset = ['a', 'c', 'd'] I'd like to return the following, using pandas.read_csv and the subset,...
Use a callable checking if the column is in the subset subset = ['a', 'c', 'd'] df = pd.read_csv('sample.csv', usecols=lambda x: x in subset) a c 0 1 3 1 4 6
7
17
62,982,784
2020-7-19
https://stackoverflow.com/questions/62982784/plotly-bar-chart-change-color-based-on-positive-negative-value-python
I have the following code which plots a bar chart (1 series), but I need the bars to be coloured blue if the 'Net' value is positive, and red if its negative: import pandas as pd import plotly.graph_objects as go df = pd.DataFrame({ 'Net':[15,20,-10,-15], 'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020'] }) ...
You can check documentation here. Full code as following import pandas as pd import plotly.graph_objects as go import numpy as np # Data df = pd.DataFrame({ 'Net':[15,20,-10,-15], 'Date':['07/14/2020','07/15/2020','07/16/2020','07/17/2020'] }) df['Date'] = pd.to_datetime(df['Date']) ## here I'm adding a column with col...
11
19
63,000,388
2020-7-20
https://stackoverflow.com/questions/63000388/how-to-include-simpleimputer-before-countvectorizer-in-a-scikit-learn-pipeline
I have a pandas DataFrame that includes a column of text, and I would like to vectorize the text using scikit-learn's CountVectorizer. However, the text includes missing values, and so I would like to impute a constant value before vectorizing. My initial idea was to create a Pipeline of SimpleImputer and CountVectoriz...
The best solution I have found is to insert a custom transformer into the Pipeline that reshapes the output of SimpleImputer from 2D to 1D before it is passed to CountVectorizer. Here's the complete code: import pandas as pd import numpy as np df = pd.DataFrame({'text':['abc def', 'abc ghi', np.nan]}) from sklearn.impu...
17
15
62,992,438
2020-7-20
https://stackoverflow.com/questions/62992438/how-to-collapse-the-code-section-in-google-colab-notebook-but-keeping-the-result
As you can read on the title, I'm currently trying to make the code section collapsing without collapsing also the results section. For example without the collapse the title/code/result sections look like this: If I try to "collapse" the section will look like this: I'm looking for a solution where I can make collap...
You can start the cell with #@title Then, you can double click the title. It will hide the code part, but keep the output still visible. For example #@title My title greet = "Hello" print(greet) Double clicking "My title" will still show the output "Hello".
8
9
62,966,480
2020-7-18
https://stackoverflow.com/questions/62966480/how-to-disable-pylint-inspections-for-anything-that-uses-my-function
I've made a classproperty descriptor and whenever I use a function decorated with it, I get multiple pylint inspection errors. Here is a sample class with a sample decorated function: class Bar: """ Bar documentation. """ # pylint: disable=no-method-argument @classproperty def foo(): """ Retrieve foo. """ return "foo" ...
I have managed to create a dirty hack by type-hinting the items as None: class Bar: """ Bar documentation. """ # pylint: disable=no-method-argument,function-redefined,too-few-public-methods foo: None @classproperty def foo(): """ Retrieve an object. """ return NotImplementedError("Argument") I would rather avoid havin...
9
4
62,984,477
2020-7-19
https://stackoverflow.com/questions/62984477/running-python-scripts-in-anaconda-environment-through-windows-cmd
I have the following goal: I have a python script, which should be running in my custom Anaconda environment. And this process needs to be automatizated. The first thing I've tried was to create an .exe file of my script using pyinstaller in the Anaconda command prompt, opened in my environment. And put the .exe into W...
You could Create a .bat file (e.g. run_python_script.bat) with contents shown below. Create task in "Task Scheduler" to run the .bat file. 1.a. The .bat file contents with conda environments Check your <condapath>. Your conda.exe is located at <condapath>/Scripts. Put into your .bat file call "<condapath>\Scripts\a...
7
13
62,990,029
2020-7-20
https://stackoverflow.com/questions/62990029/how-to-get-equally-spaced-points-on-a-line-in-shapely
I'm trying to (roughly) equally space the points of a line to a predefined distance. It's ok to have some tolerance between the distances but as close as possible would be desirable. I know I could manually iterate through each point in my line and check the p1 distance vs p2 and add more points if needed. But I wonder...
One way to do that is to use interpolate method that returns points at specified distances along the line. You just have to generate a list of the distances somehow first. Taking the input line example from Roy2012's answer: import numpy as np from shapely.geometry import LineString from shapely.ops import unary_union ...
12
24
62,990,553
2020-7-20
https://stackoverflow.com/questions/62990553/how-to-run-a-python-function-in-kotlin
I am making an app in kotlin. But I know python a lot and made the logic in python. The kotlin is only used for the display. Is there a way to call a python function in kotlin?. A python script can call python scripts but can a Kotlin script call one?
I think there are two normal solutions. Using Polyglot API of GraalVM (https://www.graalvm.org/sdk/javadoc/org/graalvm/polyglot/package-summary.html). Creating a C interface implemented with Python (https://www.linuxjournal.com/article/8497) and calling it with JNI (https://docs.oracle.com/javase/8/docs/technotes/gui...
12
0
62,989,923
2020-7-20
https://stackoverflow.com/questions/62989923/pandas-dataframe-replace-part-of-string-with-value-from-another-column
I having replace issue while I try to replace a string with value from another column. I want to replace 'Length' with df['Length']. df["Length"]= df["Length"].replace('Length', df['Length'], regex = True) Below is my data Input: **Formula** **Length** Length 5 Length+1.5 6 Length-2.5 5 Length 4 5 5 Expected Output: *...
If want replace by another column is necessary use DataFrame.apply: df["Formula"]= df.apply(lambda x: x['Formula'].replace('Length', str(x['Length'])), axis=1) print (df) Formula Length 0 5 5 1 6+1.5 6 2 5-2.5 5 3 4 4 4 5 5 Or list comprehension: df["Formula"]= [x.replace('Length', str(y)) for x, y in df[['Formula','L...
13
18
62,948,421
2020-7-17
https://stackoverflow.com/questions/62948421/how-to-create-point-cloud-file-ply-from-vertices-stored-as-numpy-array
I have some vertices whose coordinates were stored as NumPy array. xyz_np: array([[ 7, 53, 31], [ 61, 130, 116], [ 89, 65, 120], ..., [ 28, 72, 88], [ 77, 65, 82], [117, 90, 72]], dtype=int32) I want to save these vertices as a point cloud file(such as .ply) and visualize it in Blender. I don't have face information.
You can use Open3D to do this. # Pass numpy array to Open3D.o3d.geometry.PointCloud and visualize xyz = np.random.rand(100, 3) pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(xyz) o3d.io.write_point_cloud("./data.ply", pcd) You can also visualize the point cloud using Open3D. o3d.visualization....
13
19
62,988,494
2020-7-20
https://stackoverflow.com/questions/62988494/adjust-width-of-dropdown-menu-option-in-dash-plotly
I am trying to build an app using Dash in Python based on Plotly. I am having hard time in adjusting the width of Dropdown menu options. I have attached code and image below. I would like the width of Dropdown options to be same as the menu width. app.layout = html.Div(children=[ html.H1(children='Welcome to Portfolio...
While its correct to place width: 50% to change the width of the dropdown component, you've placed it in the inner component rather than the parent Div. app.layout = html.Div( children=[ html.H1(children="Welcome to Portfolio Construction Engine!"), html.Div( children="What would you like to do?", style={"font-style": ...
16
24
62,985,961
2020-7-19
https://stackoverflow.com/questions/62985961/how-to-use-requests-session-so-that-headers-are-presevred-and-reused-in-subseque
I might have misunderstood the requests.session object. headers ={'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.28 Safari/537.36'} s = requests.Session() r = s.get('https://www.barchart.com/', headers = headers) print(r.status_code) This works fine and return 20...
You can use session.headers (doc) property to specify headers that are sent with each request: import requests headers ={'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.28 Safari/537.36'} s = requests.session() s.headers = headers # <-- set default headers here r =...
15
20
62,983,674
2020-7-19
https://stackoverflow.com/questions/62983674/the-absolute-value-of-a-complex-number-with-numpy
I have the following script in Python. I am calculating the Fourier Transform of an array. When I want to plot the results (Fourier transform) I am using the absolute value of that calculation. However, I do not know how the absolute value of complex numbers is being produced. Does anyone know how it calculates? I need...
sqrt(Re(z)**2 + Im(z)**2) for z = a + ib this becomes: sqrt(a*a + b*b) It's just the euclidean norm. You have to sum the square of real part and imaginary part (without the i) and do the sqrt of it. https://www.varsitytutors.com/hotmath/hotmath_help/topics/absolute-value-complex-number
10
13
62,978,955
2020-7-19
https://stackoverflow.com/questions/62978955/poetry-ignore-dependency-in-pyproject-toml
I currently have a Python3 project set up with Poetry as the main package manager. Next to that I also have set up a build and some automated testing via Github workflows. My package depends on Tensorflow, although the automated tests can run without it. Unfortunately Tensorflow (which is quite big) is installed every ...
The only other approach that comes to mind would be to move the tensorflow dependency to an extra category, which in poetry would look like this: $ poetry add --extras tensorflow This means that it won't be installed when you run poetry install, unless it is part of a named group that you install explicitly. This can ...
14
15
62,975,325
2020-7-19
https://stackoverflow.com/questions/62975325/why-is-summing-list-comprehension-faster-than-generator-expression
Not sure if title is correct terminology. If you have to compare the characters in 2 strings (A,B) and count the number of matches of chars in B against A: sum([ch in A for ch in B]) is faster on %timeit than sum(ch in A for ch in B) I understand that the first one will create a list of bool, and then sum the values ...
I took a look at the disassembly of each construct (using dis). I did this by declaring these two functions: def list_comprehension(): return sum([ch in A for ch in B]) def generation_expression(): return sum(ch in A for ch in B) and then calling dis.dis with each function. For the list comprehension: 0 BUILD_LIST 0 ...
16
15
62,959,412
2020-7-17
https://stackoverflow.com/questions/62959412/how-to-properly-uninstall-pyenv-on-linux
I have installed pyenv on a raspberry pi but now I want to uninstall it. I already ran the command rm -rf $(pyenv root) but now it says to delete lines from my "shell startup configuration". What does it mean? I found this lines in my .bash_profile files: if command -v pyenv 1>/dev/null 2>&1; then eval"$(pyenv init-)" ...
Delete all 5 lines from both files. Then make sure that in your .bash_profile it tells .bashrc to load
11
8
62,962,703
2020-7-17
https://stackoverflow.com/questions/62962703/how-to-get-numpy-working-properly-in-anaconda-python-3-7-6
I am trying to use NumPy in Python. I have just installed Anaconda Python 3.7, and that all seemed to go smoothly. However, I cannot import numpy(using the line import numpy). When I do, I get the following error: C:\Users\jsmith\anaconda3\lib\site-packages\numpy\__init__.py:140: UserWarning: mkl-service package faile...
As mentioned in the comments by @cel uninstalling and reinstalling numpy using pip uninstall numpy and pip install numpy made it work.
11
22
62,967,062
2020-7-18
https://stackoverflow.com/questions/62967062/disable-publishing-to-pypi-with-poetry
I am a setting up Poetry in combination with Tox to automate builds and testing. The project I am working on however is private and I want to avoid anyone working on it accidentally publishing it to PyPi. I have initialized a project using poetry init and my assumption is that the resulting setup does not result in a v...
As I know poetry does not support such straightforward option yet. But the workaround is possible: [tool.poetry] exclude = ["**"] In TOML format: * denotes a single level wildcard, and ** denotes all files in the given directory hierarchy. exclude = ["**"] option prevents project files from getting into the package wh...
7
5
62,962,623
2020-7-17
https://stackoverflow.com/questions/62962623/how-to-set-background-color-of-the-plot-and-color-for-gridlines
Here is my code: import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Bar( name='Group 1', x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4], error_y=dict(type='data', array=[1, 0.5, 1.5]), width=0.15 )) fig.add_trace(go.Bar( name='Group 2', x=['Var 1', 'Var 2', 'Var 3'], y=[4, 7, 3], error_y=dict(type='data',...
This should help import plotly.graph_objects as go from plotly.graph_objects import Layout # Set layout with background color you want (rgba values) # This one is for white background layout = Layout(plot_bgcolor='rgba(0,0,0,0)') # Use that layout here fig = go.Figure(layout=layout) fig.add_trace(go.Bar( name='Group 1'...
8
19
62,937,310
2020-7-16
https://stackoverflow.com/questions/62937310/python-3-6-type-hinting-for-a-function-accepting-generic-class-type-and-instance
I have a function with the following signature: def wait_for_namespaced_objects_condition( obj_type: Type[NamespacedAPIObject], obj_condition_fun: Callable[[NamespacedAPIObject], bool], ) -> List[NamespacedAPIObject]: ... Important part here are NamespacedAPIObject parameters. This function takes an obj_type as type s...
But Type[T] is TypeVar, so it's not the way to go. No, you are on the right track - TypeVar is definitely the way to go. The problem here is rather in pykube.objects.APIObject class being wrapped in a decorator that mypy cannot deal with yet. Adding type stubs for pykube.objects will resolve the issue. Create a direc...
8
4
62,952,273
2020-7-17
https://stackoverflow.com/questions/62952273/catch-python-exception-and-save-traceback-text-as-string
I'm trying to write a nice error handler for my code, so that when it fails, the logs, traceback and other relevant info get emailed to me. I can't figure out how to take an exception object and extract the traceback. I find the traceback module pretty confusing, mostly because it doesn't deal with exceptions at all. I...
The correct function for tb.something(e) is ''.join(tb.format_exception(None, e, e.__traceback__))
16
23
62,939,781
2020-7-16
https://stackoverflow.com/questions/62939781/adding-files-to-gitignore-in-visual-studio-code
In Visual Studio Code, with git extensions installed, how do you add files or complete folders to the .gitignore file so the files do not show up in untracked changes. Specifically, using Python projects, how do you add the pycache folder and its contents to the .gitignore. I have tried right-clicking in the folder in ...
So after further investigation, it is possible to add files from the pycache folder to the .gitignore file from within VS Code by using the list of untracked changed files in the 'source control' panel. You right-click a file and select add to .gitignore from the pop-up menu. You can't add folders but just the individu...
18
14
62,947,285
2020-7-17
https://stackoverflow.com/questions/62947285/is-there-a-difference-between-series-replace-and-series-map-in-pandas
Both pandas.Series.map and pandas.Series.replace seem to give the same result. Is there a reason for using one over the other? For example: import pandas as pd df = pd.Series(['Yes', 'No']) df 0 Yes 1 No dtype: object df.replace(to_replace=['Yes', 'No'], value=[True, False]) 0 True 1 False dtype: bool df.map({'Yes':T...
Both of these methods are used for substituting values. From Series.replace docs: Replace values given in to_replace with value. From Series.map docs: Used for substituting each value in a Series with another value, that may be derived from a function, a dict or a Series. They differ in the following: replace acce...
17
38
62,937,312
2020-7-16
https://stackoverflow.com/questions/62937312/fastest-and-most-compact-way-to-get-the-smallest-number-that-is-divisible-by-num
I tried my attempt at finding the smallest number that is divisible by numbers from 1 to n, and now I'm looking for advice on ways to further compact/make my solution more efficient. It would be pretty cool if there was an O(1) solution too. def get_smallest_number(n): """ returns the smallest number that is divisible ...
Mathematically, you are computing the least common multiple of 1, 2, ..., n. lcm is easily derived from gcd, and lcm is an associative operation. reduce is useful for applying an associative operation to an interable. We can combine these ideas (as well as improvements due to Mark Dickinson and Eric Postpischil in the ...
9
10
62,935,983
2020-7-16
https://stackoverflow.com/questions/62935983/vary-thickness-of-edges-based-on-weight-in-networkx
I'm trying to draw a network diagram using Python Networkx package. I would like to vary the thickness of the edges based on the weights given to the edges. I am using the following code which draws the diagram, but I cannot get the edge to vary its thickness based on the weight. Can someone help me with this problem? ...
In order to set the widths for each edge, i.e with an array-like of edges, you'll have to use nx.draw_networkx_edges through the width parameter, since nx.draw only accepts a single float. And the weights can be obtaind with nx.get_edge_attributes. Also you can draw with a shell layout using nx.shell_layout and using i...
8
15
62,935,406
2020-7-16
https://stackoverflow.com/questions/62935406/how-to-make-a-signup-view-using-class-based-views-in-django
When I started to use Django, I was using FBVs ( Function Based Views ) for pretty much everything including signing up for new users. But as I delved deep more into projects, I realized that Class-Based Views are usually better for large projects as they are more clean and maintainable but this is not to say that FBVs...
In order to make SignUpView in Django, you need to utilize CreateView and SuccessMessageMixin for creating new users as well as displaying a success message that confirms the account was created successfully. Here's the code : views.py: from .forms import UserRegisterForm from django.views.generic.edit import CreateVie...
8
19
62,925,100
2020-7-15
https://stackoverflow.com/questions/62925100/how-to-control-distance-between-bars-in-bar-chart
I have two peaces of code that produce sameme result, so any could be used for answer. First: import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Bar( name='Group 1', x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4], error_y=dict(type='data', array=[1, 0.5, 1.5]), width=0.15 )) fig.add_trace(go.Bar( name='Gr...
There are 2 properties that you are asking for. They are as follows: bargap - gap between bars of adjacent location coordinates. bargroupgap - gap between bars of the same location coordinate. But there is a catch here, if you set width then both the properties are ignored. So, remove the width value from the code an...
14
25
62,922,491
2020-7-15
https://stackoverflow.com/questions/62922491/change-linewidth-in-python-plotly-px-figure
I'm unclear how to style a line in a plotly express figure, altering color and width. The plotly documentation offers suggestions to style lines using go, but I do not see information for px. Example import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeEx...
Plotly px line styles can be updated with update_traces function see documentation for further information. The following example modifies the prior figure making all of the lines black and thin. import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", ...
9
27
62,918,389
2020-7-15
https://stackoverflow.com/questions/62918389/ceating-dynamodb-table-says-invalid-one-or-more-parameter-values-were-invalid
I am trying to create dynamo db table with python. Below is the script i have. I am trying to create one partition key and sort key and bunch of columns. What I tried: import boto3 dynamodb = boto3.resource('dynamodb') table = dynamodb.create_table( TableName='g_view_data', KeySchema=[ { 'AttributeName': 'customer_id',...
As stated in the AWS documentation, the attributes in KeySchema must also be defined in the AttributeDefinitions. Please try adding customer_id and key_id to your AttributeDefinitions as well. As for the AttributeDefinitions, they are used for the keys only (primary key and indexes). So here is an example that worked f...
11
18
62,918,481
2020-7-15
https://stackoverflow.com/questions/62918481/how-to-create-a-unique-identifier-based-on-multiple-columns
I have a pandas dataframe that looks something like this: brand description former_price discounted_price 0 A icecream 1099.0 855.0 1 A cheese 469.0 375.0 2 B catfood 179.0 119.0 3 C NaN 699.0 399.0 4 NaN icecream 769.0 549.0 5 A icecream 769.0 669.0 I want to create a column that will assign a unique value for each ...
You could try with pd.Series.factorize: df.set_index(['brand','description']).index.factorize()[0]+1 Output: 0 1 1 2 2 3 3 4 4 5 5 1 So you could try this, to assign it to be the first column: df.insert(loc=0, column='product_key', value=df.set_index(['brand','description']).index.factorize()[0]+1) Output: df produ...
8
10
62,917,882
2020-7-15
https://stackoverflow.com/questions/62917882/convert-datetime64ns-utc-pandas-column-to-datetime
I have a dataframe which has timestamp and its datatype is object. 0 2020-07-09T04:23:50.267Z 1 2020-07-09T11:21:55.536Z 2 2020-07-09T11:23:18.015Z 3 2020-07-09T04:03:28.581Z 4 2020-07-09T04:03:33.874Z Name: timestamp, dtype: object I am not aware of the format of the datetime in the above dataframe. I applied pd.to_d...
To remove timezone, use tz_localize: df['timestamp'] = pd.to_datetime(df.timestamp).dt.tz_localize(None) Output: timestamp 0 2020-07-09 04:23:50.267 1 2020-07-09 11:21:55.536 2 2020-07-09 11:23:18.015 3 2020-07-09 04:03:28.581 4 2020-07-09 04:03:33.874
36
65
62,914,335
2020-7-15
https://stackoverflow.com/questions/62914335/python-pandas-query-for-values-in-list
I want to use query() to filter rows in a panda dataframe that appear in a given list. Similar to this question, but I really would prefer to use query() import pandas as pd df = pd.DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]}) mylist =[5,3] I tried: df.query('A.isin(mylist)')
You could try this, using @, that allows us to refer a variable in the environment: df.query('A in @mylist') Or this: df.query('A.isin(@mylist)',engine='python')
12
17
62,910,635
2020-7-15
https://stackoverflow.com/questions/62910635/create-sub-cell-in-spyder
Is there any workaround to create sub-cells in Spyder? E.g. I know that with #%% Cell 1 I can create a new cell. But is there a way to create a sub-cell which is grouped under the cell as in # Cell 1.1 ? I have found this discussion which didn't look encouraging. But I wanted to give it a try and ask here.
As per the post linked, the feature you are asking has been implemented. I just tried it on my Spyder IDE version 4.1.3 and it works by using an increasing number of %. For instance #%% Section 1 some code #%%% Sub-Section 1.1 some more code #%% Section 2 and so on
16
21
62,907,802
2020-7-15
https://stackoverflow.com/questions/62907802/best-way-to-detect-if-checkbox-is-ticked
My work: Scan the paper Check horizontal and vertical line Detect checkbox How to know checkbox is ticked or not At this point, I thought I could find it by using Hierarchical and Contours: Below is my work for i in range (len( contours_region)): #I already have X,Y,W,H of the checkbox through #print(i) #cv2.connecte...
I think erode function help you. Use erosion to make the ticks bigger then count the non zero pixels. Here You can find the basics: import cv2 import numpy as np from google.colab.patches import cv2_imshow img = cv2.imread("image.png"); cv2_imshow(img) kernel = np.ones((3, 3), np.uint8) better_image = cv2.erode(img,ker...
8
2
62,907,815
2020-7-15
https://stackoverflow.com/questions/62907815/pytorch-what-is-the-difference-between-tensor-cuda-and-tensor-totorch-device
In PyTorch, what is the difference between the following two methods in sending a tensor (or model) to GPU: Setup: X = np.array([[1, 3, 2, 3], [2, 3, 5, 6], [1, 2, 3, 4]]) # X = model() X = torch.DoubleTensor(X) Method 1 Method 2 X.cuda() device = torch.device("cuda:0")X = X.to(device) (I don't really need...
There is no difference between the two. Early versions of pytorch had .cuda() and .cpu() methods to move tensors and models from cpu to gpu and back. However, this made code writing a bit cumbersome: if cuda_available: x = x.cuda() model.cuda() else: x = x.cpu() model.cpu() Later versions introduced .to() that basical...
23
31
62,798,421
2020-7-8
https://stackoverflow.com/questions/62798421/how-to-send-file-to-fastapi-endpoint-using-postman
I faced the difficulty of testing api using postman. Through swagger file upload functionality works correctly, I get a saved file on my hard disk. I would like to understand how to do this with Postman. I use the standard way to work with files which I use when working with Django and Flask: Body -> form-data: key=fil...
My code: from fastapi import FastAPI, UploadFile, File app = FastAPI() @app.post("/file/") async def create_upload_file(file: UploadFile = File(...)): return {"filename": file.filename} Setup in Postman: As stated in https://github.com/tiangolo/fastapi/issues/1653, the parameter name for the file is the key value tha...
8
19
62,841,000
2020-7-10
https://stackoverflow.com/questions/62841000/how-is-egg-used-in-pip-install-e
Trying to test editable installs out and I'm not sure how to interpret the results. I intentionally made a typo in the egg= portion but it was still able to locate the egg without any help from me: root@6be8ee41b6c9:/# pip3 install -e git+https://gitlab.com/jame/clientapp.git Could not detect requirement name for 'git+...
This is outdated notation. Nowadays one should use the following notation whenever possible: python -m pip install 'ProjectName @ git+https://example.local/repository.git@1.3.1' My guess, the name matters if the project is a dependency of another project. For example in a case where one wants to install A from PyPI a...
9
5
62,889,093
2020-7-14
https://stackoverflow.com/questions/62889093/what-does-no-build-isolation-do
I am trying to edit a python library and build it from source. Can someone explain what does the following instruction do and why is this method different from pip install package-name done normally? pip install --verbose --no-build-isolation --editable
You can read all the usage options here: https://pip.pypa.io/en/stable/cli/pip_install/ -v, --verbose Give more output. Option is additive, and can be used up to 3 times. --no-build-isolation Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already ins...
33
22
62,822,956
2020-7-9
https://stackoverflow.com/questions/62822956/how-to-make-pip-install-to-path-on-linux
I installed PyInstaller via pip, but when I try to run it I get pyinstaller: command not found After installation of the package the following warning was displayed: WARNING: The scripts pyi-archive_viewer, pyi-bindepend, pyi-grab_version, pyi-makespec, pyi-set_version and pyinstaller are installed in '/home/kevinapetr...
Rather than messing with existing entires in PATH, consider appending to it the location from pip. It usually is ~/.local/bin (consistent with systemd's file-hierarchy). Good place to add/modify environmental variables is ~/.profile file. You do it by adding the following line: export PATH="$HOME/.local/bin:$PATH" You...
11
28
62,884,503
2020-7-13
https://stackoverflow.com/questions/62884503/what-are-the-best-practices-for-repr-with-collection-class-python
I have a custom Python class which essentially encapsulate a list of some kind of object, and I'm wondering how I should implement its __repr__ function. I'm tempted to go with the following: class MyCollection: def __init__(self, objects = []): self._objects = [] self._objects.extend(objects) def __repr__(self): retur...
The official documentation outlines this as how you should handle __repr__: Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an app...
14
39
62,897,548
2020-7-14
https://stackoverflow.com/questions/62897548/why-am-i-getting-a-line-shadow-in-a-seaborn-line-plot
Here is the code: fig=plt.figure(figsize=(14,8)) sns.lineplot(x='season', y='team_strikerate', hue='batting_team', data=overall_batseason) plt.legend(title = 'Teams', loc = 1, fontsize = 12) plt.xlim([2008,2022]) And here is the image Just to let you know, I've already drawn another similar lineplot above this one.
There is line shadow showing the confidence interval, because the dataset contains multiple y(team_strikerate) values for each x(season) value. By default, sns.lineplot() will estimate the mean by aggregating over multiple y values at each x value. After aggregation, the mean of y values at each x value will be plotted...
10
14
62,898,911
2020-7-14
https://stackoverflow.com/questions/62898911/how-to-downgrade-python-version-from-3-8-to-3-7-mac
I'm using Python & okta-aws tools and in order to fetch correct credentials on aws I need to run okta-aws init. But got an error message of Could not read roles from Okta and the system prompted that"Your Pipfile requires python_version 3.7, but you are using 3.8.3 (/usr/local/Cellar/o/1.1.4/l/.venv/bin/python). I've t...
Consider installing pyenv with Homebrew on macOS brew update brew install pyenv OR Clone the repository to get the latest version of pyenv git clone https://github.com/pyenv/pyenv.git ~/.pyenv Define your environment variables (For a recent MacOS you may want to replace ~/.bash_profile with ~/.zshrc as that is the d...
58
204
62,884,183
2020-7-13
https://stackoverflow.com/questions/62884183/trying-to-add-a-colorbar-to-a-seaborn-scatterplot
I'm a geology master's student working on my dissertation with a focus on the Sulfur Dioxide output of a number of volcanoes in the South Pacific. I have a little experience with R but my supervisor recommended python (JupyterLab specifically) for generating figures and data manipulation so I'm pretty new to programmin...
The same method employed in this answer regarding Seaborn barplots can be applied to a scatterplot as well. With your code that would look something like this: # ... norm = plt.Normalize(df['mag'].min(), df['mag'].max()) sm = plt.cm.ScalarMappable(cmap="RdBu", norm=norm) sm.set_array([]) ax = sns.scatterplot(x='longitu...
10
27
62,861,810
2020-7-12
https://stackoverflow.com/questions/62861810/mypy-how-should-i-type-a-dict-that-has-strings-as-keys-and-the-values-can-be-ei
I am using Python 3.8.1 and mypy 0.782. I don't understand why mypy complains about the following code: from typing import Union, List, Dict Mytype = Union[Dict[str, str], Dict[str, List[str]]] s: Mytype = {"x": "y", "a": ["b"]} Mypy gives the following error on line 3: Incompatible types in assignment (expression has...
Because s: Mytype cannot have type Dict[str, str] and type Dict[str, List[str]] at the same time. You could do what you want like this: Mytype = Dict[str, Union[str, List[str]]] But maybe problems, because Dict is invariant Also you could use TypedDict, but only a fixed set of string keys is expected: from typing imp...
15
17
62,798,739
2020-7-8
https://stackoverflow.com/questions/62798739/how-to-update-the-elasticsearch-document-with-python
I am using the code below to add data to Elasticsearch: from elasticsearch import Elasticsearch es = Elasticsearch() es.cluster.health() records = [ {'Name': 'Dr. Christopher DeSimone', 'Specialised and Location': 'Health'}, {'Name': 'Dr. Tajwar Aamir (Aamir)', 'Specialised and Location': 'Health'}, {'Name': 'Dr. Berna...
In Elasticsearch, when data is indexed without providing a custom ID, then a new ID will be created by Elasticsearch for every document you index. Hence, since you are not providing an ID, Elasticsearch generates it automatically. But you also want to check if Name already exists. There are two approaches: Index the d...
9
5
62,830,862
2020-7-10
https://stackoverflow.com/questions/62830862/how-to-install-python3-8-on-debian-10
i've installed debian 10.0.4 yesterday on my pc. it had python version 3.7.3 installed on it , so i tried to update it to version 3.8.3 and now i have version 3.8.3 installed but when i try to install pip using the official get-pip.py it throws an exception . the details is : Traceback (most recent call last): File "<f...
Installing Python 3.8 on Debian 10 Building Python 3.8 on Debian is a relatively straightforward process and will only take a few minutes. Start by installing the packages necessary to build Python source: sudo apt update sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev l...
16
36
62,809,562
2020-7-9
https://stackoverflow.com/questions/62809562/how-do-i-annotate-a-callable-with-args-and-kwargs
I have a function which returns a function. I would like to find a proper type annotation. However, the returned function has *args and *kwargs. How is that annotated within Callable[[Parameters???], ReturnType]? Example: from typing import Callable import io import pandas as pd def get_conversion_function(file_type: s...
As I know, python's typing does not allow do that straightforwardly as stated in the docs of typing.Callable: There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. Callable[..., ReturnType] (literal ellipsis) can be used to type hint a callable taking any ...
26
13
62,821,480
2020-7-9
https://stackoverflow.com/questions/62821480/add-a-trace-to-every-facet-of-a-plotly-figure
I'd like to add a trace to all facets of a plotly plot. For example, I'd like to add a reference line to each daily facet of a scatterplot of the "tips" dataset showing a 15% tip. However, my attempt below only adds the line to the first facet. import plotly.express as px import plotly.graph_objects as go import numpy ...
According to an example from plotly you can pass 'all' as the row and col arguments and even skip empty subplots: fig.add_trace(go.Scatter(...), row='all', col='all', exclude_empty_subplots=True)
7
9
62,856,818
2020-7-12
https://stackoverflow.com/questions/62856818/how-can-i-run-the-fastapi-server-using-pycharm
I have a simple API function as below, from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} I am starting the server using uvicorn command as, uvicorn main:app Since we are not calling any python file directly, it is not possible to call uvicorn command from Pycha...
Method-1: Run FastAPI by calling uvicorn.run(...) In this case, your minimal code will be as follows, # main.py import uvicorn from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) Normally, you'l...
103
219
62,794,219
2020-7-8
https://stackoverflow.com/questions/62794219/tensorflow-gpu-not-showing-in-jupyter-notebook
In terminal windows 10 using cuda 10.1 python 3.7.7 GPU GeForce GTX 1050 4GB >>> import tensorflow as tf 2020-07-08 17:10:50.005569: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll >>> tf.config.list_physical_devices('GPU') 2020-07-08 17:10:55.65748...
It needs to make new kernel for this env and select kernel form jupyter notebook $ conda activate env_name $ pip install ipykernel --user $ python -m ipykernel install --user --name env_name --display-name env_name
8
1
62,801,562
2020-7-8
https://stackoverflow.com/questions/62801562/pandas-explode-multiple-columns
I have DF that has multiple columns. Two of the columns are list of the same len.( col2 and col3 are list. the len of the list is the same). My goal is to list each element on it's own row. I can use the df.explode(). but it only accepts one column. However, I want the pair of the two columns to be 'exploded'. If I do ...
You could set col1 as index and apply pd.Series.explode across the columns: df.set_index('col1').apply(pd.Series.explode).reset_index() Or: df.apply(pd.Series.explode) col1 col2 col3 0 aa 1 1.1 1 aa 2 2.2 2 aa 3 3.3 3 bb 4 4.4 4 bb 5 5.5 5 bb 6 6.6 6 cc 7 7.7 7 cc 8 8.8 8 cc 9 9.9 9 cc 7 7.7 10 cc 8 8.8 11 cc 9 9.9
21
20
62,870,656
2020-7-13
https://stackoverflow.com/questions/62870656/file-system-scheme-local-not-implemented-in-google-colab-tpu
I am using TPU runtime in Google Colab, but having problems in reading files (not sure). I initialized TPU using: import tensorflow as tf import os import tensorflow_datasets as tfds resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR']) tf.config.experimental_connect...
For loading file from local file when using TPU - read them as normal python file.read() (not tf.io). In your case: def load_image(image_path): with open(image_path, "rb") as local_file: # <= change here img = local_file.read() img = tf.image.decode_jpeg(img, channels=3) img = tf.image.resize(img, (299, 299)) img = tf....
15
4
62,815,318
2020-7-9
https://stackoverflow.com/questions/62815318/get-current-jupyter-lab-notebook-name-for-jupyter-lab-version-2-1-and-3-0-1-and
Problem Hi all, As my title suggested it, I would like to get access to the notebook name (in jupyter-lab) as a variable. So I could reuse it in the notebook itself (for example to name some figure files generated in the notebook). I saw that a similar issue was opened years ago [see here]. However I didnt find a satis...
As an alternative you can use the following library: ipynbname #! pip install ipynbname import ipynbname nb_fname = ipynbname.name() nb_path = ipynbname.path() This worked for me and the solution is quite straightforward.
8
21
62,814,861
2020-7-9
https://stackoverflow.com/questions/62814861/difference-between-time-and-time-in-jupyter-notebook
What is the difference between %time and %%time in a Jupyter Notebook Cell?
%time measures execution time of the next line. %%time measures execution time of the whole cell. For instance: %time a = 1 time.sleep(5) CPU times: user 8 µs, sys: 0 ns, total: 8 µs Wall time: 16.9 µs %%time a = 1 time.sleep(5) CPU times: user 1.13 ms, sys: 2.11 ms, total: 3.24 ms Wall time: 5 s
12
23
62,839,068
2020-7-10
https://stackoverflow.com/questions/62839068/memoryerror-unable-to-allocate-mib-for-an-array-with-shape-and-data-type-when
Getting this memory error. But the book/link I am following doesn't get this error. A part of Code: from sklearn.linear_model import SGDClassifier sgd_clf = SGDClassifier() sgd_clf.fit(x_train, y_train) Error: MemoryError: Unable to allocate 359. MiB for an array with shape (60000, 784) and data type float64 I also ge...
Upgrading python-64 bit seems to have solved all the "Memory Error" problem.
16
2