diff --git a/branca/colormap.py b/branca/colormap.py index a6f4164..89359c9 100644 --- a/branca/colormap.py +++ b/branca/colormap.py @@ -12,13 +12,14 @@ import math from branca.element import ENV, Figure, JavascriptLink, MacroElement -from branca.six import binary_type, text_type from branca.utilities import legend_scaler from jinja2 import Template import pkg_resources +from six import binary_type, text_type + resource_package = __name__ resource_path_schemes = '/_schemes.json' diff --git a/branca/element.py b/branca/element.py index cde2bf4..12f39d3 100644 --- a/branca/element.py +++ b/branca/element.py @@ -6,16 +6,18 @@ """ +import base64 +import json import warnings +from collections import OrderedDict from uuid import uuid4 from jinja2 import Environment, PackageLoader, Template -from collections import OrderedDict -import json -import base64 -from .six import urlopen, text_type, binary_type -from .utilities import _camelify, _parse_size, none_min, none_max +from six import binary_type, text_type +from six.moves.urllib.request import urlopen + +from .utilities import _camelify, _parse_size, none_max, none_min ENV = Environment(loader=PackageLoader('branca', 'templates')) @@ -43,9 +45,9 @@ class Element(object): """ _template = Template( - "{% for name, element in this._children.items() %}\n" - " {{element.render(**kwargs)}}" - "{% endfor %}" + '{% for name, element in this._children.items() %}\n' + ' {{element.render(**kwargs)}}' + '{% endfor %}' ) def __init__(self, template=None, template_name=None): @@ -96,7 +98,7 @@ def get_bounds(self): def add_children(self, child, name=None, index=None): """Add a child.""" - warnings.warn("Method `add_children` is deprecated. Please use `add_child` instead.", + warnings.warn('Method `add_children` is deprecated. Please use `add_child` instead.', FutureWarning, stacklevel=2) return self.add_child(child, name=name, index=index) @@ -187,7 +189,7 @@ def to_dict(self, depth=-1, **kwargs): class JavascriptLink(Link): """Create a JavascriptLink object based on a url. - + Parameters ---------- url : str @@ -215,7 +217,7 @@ def __init__(self, url, download=False): class CssLink(Link): """Create a CssLink object based on a url. - + Parameters ---------- url : str @@ -277,7 +279,7 @@ class Figure(Element): '\n' ) - def __init__(self, width="100%", height=None, ratio="60%", title=None, figsize=None): + def __init__(self, width='100%', height=None, ratio='60%', title=None, figsize=None): super(Figure, self).__init__() self._name = 'Figure' self.header = Element() @@ -374,10 +376,10 @@ def add_subplot(self, x, y, n, margin=0.05): height = height*(1-2.*margin) div = Div(position='absolute', - width="{}%".format(100.*width), - height="{}%".format(100.*height), - left="{}%".format(100.*left), - top="{}%".format(100.*top), + width='{}%'.format(100.*width), + height='{}%'.format(100.*height), + left='{}%'.format(100.*left), + top='{}%'.format(100.*top), ) self.add_child(div) return div @@ -406,7 +408,7 @@ class Html(Element): '{% if this.script %}{{this.data}}{% else %}{{this.data|e}}{% endif %}' ) # noqa - def __init__(self, data, script=False, width="100%", height="100%"): + def __init__(self, data, script=False, width='100%', height='100%'): super(Html, self).__init__() self._name = 'Html' self.script = script @@ -449,7 +451,7 @@ class Div(Figure): ) def __init__(self, width='100%', height='100%', - left="0%", top="0%", position='relative'): + left='0%', top='0%', position='relative'): super(Figure, self).__init__() self._name = 'Div' @@ -479,8 +481,8 @@ def get_root(self): def render(self, **kwargs): """Renders the HTML representation of the element.""" figure = self._parent - assert isinstance(figure, Figure), ("You cannot render this Element " - "if it's not in a Figure.") + assert isinstance(figure, Figure), ('You cannot render this Element ' + 'if it is not in a Figure.') for name, element in self._children.items(): element.render(**kwargs) @@ -539,7 +541,7 @@ class IFrame(Element): For example figsize=(10, 5) will result in width="600px", height="300px". """ - def __init__(self, html=None, width="100%", height=None, ratio="60%", + def __init__(self, html=None, width='100%', height=None, ratio='60%', figsize=None): super(IFrame, self).__init__() self._name = 'IFrame' @@ -600,7 +602,7 @@ class MacroElement(Element): {% endmacro %} """ - _template = Template(u"") + _template = Template(u'') def __init__(self): super(MacroElement, self).__init__() @@ -609,8 +611,8 @@ def __init__(self): def render(self, **kwargs): """Renders the HTML representation of the element.""" figure = self.get_root() - assert isinstance(figure, Figure), ("You cannot render this Element " - "if it's not in a Figure.") + assert isinstance(figure, Figure), ('You cannot render this Element ' + 'if it is not in a Figure.') header = self._template.module.__dict__.get('header', None) if header is not None: diff --git a/branca/six.py b/branca/six.py deleted file mode 100644 index 46ef1c0..0000000 --- a/branca/six.py +++ /dev/null @@ -1,24 +0,0 @@ -import sys - -PY3 = sys.version_info[0] == 3 - -if PY3: - text_type = str - binary_type = bytes -else: - text_type = unicode # noqa - binary_type = str - -if PY3: - def iteritems(d, **kw): - return iter(d.items(**kw)) -else: - def iteritems(d, **kw): - return iter(d.iteritems(**kw)) - -if PY3: - import urllib.request - urlopen = urllib.request.urlopen -else: - import urllib - urlopen = urllib.urlopen diff --git a/branca/utilities.py b/branca/utilities.py index 0a6090c..6df6b2c 100644 --- a/branca/utilities.py +++ b/branca/utilities.py @@ -7,18 +7,20 @@ """ -from __future__ import absolute_import -from __future__ import print_function -from __future__ import division +from __future__ import absolute_import, division, print_function +import base64 +import json import math -import zlib import struct -import json -import pkg_resources -import base64 +import zlib + from jinja2 import Environment, PackageLoader +import pkg_resources + +from six import binary_type, text_type + try: import pandas as pd except ImportError: @@ -29,8 +31,6 @@ except ImportError: np = None -from branca.six import text_type, binary_type - def get_templates(): """Get Jinja templates.""" @@ -113,11 +113,11 @@ def color_brewer(color_code, n=6): # Raise an error if the n requested is greater than the maximum. if n > maximum_n: - raise ValueError("The maximum number of colors in a" - " ColorBrewer sequential color series is 253") + raise ValueError('The maximum number of colors in a' + ' ColorBrewer sequential color series is 253') if n < minimum_n: - raise ValueError("The minimum number of colors in a" - " ColorBrewer sequential color series is 3") + raise ValueError('The minimum number of colors in a' + ' ColorBrewer sequential color series is 3') if color_code[-2:] == '_r': base_code = color_code[:-2] @@ -146,7 +146,7 @@ def color_brewer(color_code, n=6): core_schemes = json.loads(core_schemes_string)['codes'] if base_code not in core_schemes: - raise ValueError(base_code + " is not a valid ColorBrewer code") + raise ValueError(base_code + ' is not a valid ColorBrewer code') try: schemes[core_color_code] @@ -163,11 +163,11 @@ def color_brewer(color_code, n=6): if base_code + '_' in key: matching_quals.append(int(key.split('_')[1])) - raise ValueError("Expanded color support is not available" - " for Qualitative schemes; restrict the" - " number of colors for the " + base_code + - " code to between " + str(min(matching_quals)) + - " and " + str(max(matching_quals)) + raise ValueError('Expanded color support is not available' + ' for Qualitative schemes; restrict the' + ' number of colors for the ' + base_code + + ' code to between ' + str(min(matching_quals)) + + ' and ' + str(max(matching_quals)) ) else: if not color_reverse: @@ -198,11 +198,11 @@ def split_six(series=None): """ if pd is None: - raise ImportError("The Pandas package is required" - " for this functionality") + raise ImportError('The Pandas package is required' + ' for this functionality') if np is None: - raise ImportError("The NumPy package is required" - " for this functionality") + raise ImportError('The NumPy package is required' + ' for this functionality') def base(x): if x > 0: @@ -244,13 +244,13 @@ def image_to_url(image, colormap=None, origin='upper'): fileformat = image.name.lower().split('.')[-1] else: fileformat = 'png' - url = "data:image/{};base64,{}".format( + url = 'data:image/{};base64,{}'.format( fileformat, base64.b64encode(image.read()).decode('utf-8')) elif (not (isinstance(image, text_type) or isinstance(image, binary_type))) and hasattr(image, '__iter__'): # We got an array-like object. png = write_png(image, origin=origin, colormap=colormap) - url = "data:image/png;base64," + base64.b64encode(png).decode('utf-8') + url = 'data:image/png;base64,' + base64.b64encode(png).decode('utf-8') else: # We got an URL. url = json.loads(json.dumps(image)) @@ -265,7 +265,7 @@ def write_png(data, origin='upper', colormap=None): for an inline PNG like this: >>> png_str = write_png(array) - >>> "data:image/png;base64,"+png_str.encode('base64') + >>> 'data:image/png;base64,'+png_str.encode('base64') Inspired from http://stackoverflow.com/questions/902761/saving-a-numpy-array-as-an-image @@ -290,8 +290,8 @@ def write_png(data, origin='upper', colormap=None): PNG formatted byte string """ if np is None: - raise ImportError("The NumPy package is required" - " for this functionality") + raise ImportError('The NumPy package is required' + ' for this functionality') if colormap is None: def colormap(x): @@ -301,16 +301,16 @@ def colormap(x): height, width, nblayers = array.shape if nblayers not in [1, 3, 4]: - raise ValueError("Data must be NxM (mono), " - "NxMx3 (RGB), or NxMx4 (RGBA)") + raise ValueError('Data must be NxM (mono), ' + 'NxMx3 (RGB), or NxMx4 (RGBA)') assert array.shape == (height, width, nblayers) if nblayers == 1: array = np.array(list(map(colormap, array.ravel()))) nblayers = array.shape[1] if nblayers not in [3, 4]: - raise ValueError("colormap must provide colors of" - "length 3 (RGB) or 4 (RGBA)") + raise ValueError('colormap must provide colors of' + 'length 3 (RGB) or 4 (RGBA)') array = array.reshape((height, width, nblayers)) assert array.shape == (height, width, nblayers) @@ -335,20 +335,20 @@ def colormap(x): def png_pack(png_tag, data): chunk_head = png_tag + data - return (struct.pack("!I", len(data)) + + return (struct.pack('!I', len(data)) + chunk_head + - struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head))) + struct.pack('!I', 0xFFFFFFFF & zlib.crc32(chunk_head))) return b''.join([ b'\x89PNG\r\n\x1a\n', - png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)), + png_pack(b'IHDR', struct.pack('!2I5B', width, height, 8, 6, 0, 0, 0)), png_pack(b'IDAT', zlib.compress(raw_data, 9)), png_pack(b'IEND', b'')]) def _camelify(out): - return (''.join(["_" + x.lower() if i < len(out)-1 and x.isupper() and out[i+1].islower() # noqa - else x.lower() + "_" if i < len(out)-1 and x.islower() and out[i+1].isupper() # noqa + return (''.join(['_' + x.lower() if i < len(out)-1 and x.isupper() and out[i+1].islower() # noqa + else x.lower() + '_' if i < len(out)-1 and x.islower() and out[i+1].isupper() # noqa else x.lower() for i, x in enumerate(list(out))])).lstrip('_').replace('__', '_') # noqa @@ -363,7 +363,7 @@ def _parse_size(value): value = float(value.strip('%')) assert 0 <= value <= 100 except Exception: - msg = "Cannot parse value {!r} as {!r}".format + msg = 'Cannot parse value {!r} as {!r}'.format raise ValueError(msg(value, value_type)) return value, value_type diff --git a/requirements-dev.txt b/requirements-dev.txt index 1bcea33..446c4d0 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,10 @@ flake8 +flake8-builtins +flake8-comprehensions +flake8-import-order +flake8-mutable +flake8-print +flake8-quotes nbsphinx pytest selenium diff --git a/requirements.txt b/requirements.txt index 8ce973e..1c51498 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,2 @@ -Jinja2 +jinja2 +six diff --git a/tests/test_iframe.py b/tests/test_iframe.py index 22ff775..afa5b06 100644 --- a/tests/test_iframe.py +++ b/tests/test_iframe.py @@ -25,8 +25,8 @@ def test_rendering_utf8_iframe(): iframe = elem.IFrame(html=u'

Cerrahpaşa Tıp Fakültesi

') options = Options() - options.set_headless() - driver = Firefox(firefox_options=options) + options.add_argument('-headless') + driver = Firefox(options=options) driver.get('data:text/html,' + iframe.render()) driver.switch_to.frame(0) diff --git a/tests/test_notebooks.py b/tests/test_notebooks.py index 16ccc85..86c5597 100644 --- a/tests/test_notebooks.py +++ b/tests/test_notebooks.py @@ -8,6 +8,7 @@ import os import sys + import branca.utilities if sys.version_info[:2] == (3, 4):