PKqI#&nnbowtie/__init__.py""" Bowtie """ __version__ = '0.0.16' from bowtie._layout import Layout from bowtie._command import command PKIgjbowtie/_command.py# -*- coding: utf-8 -*- """ Decorates a function for Bowtie. Reference --------- https://gist.github.com/carlsmith/800cbe3e11f630ac8aa0 """ import sys import inspect from subprocess import call import click def command(func): """ Decorates a function for building a Bowtie application and turns it into a command line interface. """ @click.group(options_metavar='[-p ] [--help]') @click.option('--path', '-p', default='build', type=str, help='Path to build the app.') @click.pass_context def cmd(ctx, path): """ Bowtie CLI to help build and run your app. """ ctx.obj = path # pylint: disable=unused-variable @cmd.command() @click.pass_context def build(ctx): """ Writes the app, downloads the packages, and bundles it with Webpack. """ try: func(ctx.obj) except TypeError: func() @cmd.command(context_settings=dict(ignore_unknown_options=True)) @click.argument('extra', nargs=-1, type=click.UNPROCESSED) @click.pass_context def serve(ctx, extra): """ Serves the Bowtie app locally. """ line = ('./{}/src/server.py'.format(ctx.obj),) + extra call(line) @cmd.command(context_settings=dict(ignore_unknown_options=True)) @click.argument('extra', nargs=-1, type=click.UNPROCESSED) @click.pass_context def dev(ctx, extra): """ Recompiles the app for development. """ line = ('webpack', '-d') + extra call(line, cwd=ctx.obj) @cmd.command(context_settings=dict(ignore_unknown_options=True)) @click.argument('extra', nargs=-1, type=click.UNPROCESSED) @click.pass_context def prod(ctx, extra): """ Recompiles the app for production. """ line = ('webpack', '-p') + extra call(line, cwd=ctx.obj) locale = inspect.stack()[1][0].f_locals module = locale.get("__name__", None) if module == "__main__": try: arg = sys.argv[1:] except IndexError: arg = '--help', # pylint: disable=no-value-for-parameter sys.exit(cmd(arg)) return cmd PK4rIbowtie/_compat.py# -*- coding: utf-8 -*- """ python 2/3 compatability """ import sys from os import makedirs IS_PY2 = sys.version_info < (3, 0) if IS_PY2: # pylint: disable=invalid-name makedirs_lib = makedirs # pylint: disable=function-redefined,missing-docstring def makedirs(name, mode=0o777, exist_ok=False): try: makedirs_lib(name, mode=mode) except OSError: if not exist_ok: raise PK{Ijbowtie/_component.py# -*- coding: utf-8 -*- """ Bowtie Component classes, all visual and control components inherit these """ # need this for get commands on python2 from __future__ import unicode_literals # pylint: disable=redefined-builtin from builtins import bytes from functools import wraps import json from datetime import datetime, date, time import msgpack import flask from flask_socketio import emit from future.utils import with_metaclass import eventlet from eventlet.queue import LightQueue def json_conversion(obj): """ Encode additional objects to JSON. """ try: # numpy isn't an explicit dependency of bowtie # so we can't assume it's available import numpy as np if isinstance(obj, np.ndarray) or isinstance(obj, np.generic): return obj.tolist() except ImportError: pass if isinstance(obj, datetime) or isinstance(obj, time) or isinstance(obj, date): return obj.isoformat() raise TypeError('Not sure how to serialize {} of type {}'.format(obj, type(obj))) def jdumps(data): """ Encoding Python object to JSON string with additional encoders. """ return json.dumps(data, default=json_conversion) def encoders(obj): """ Convert objects to msgpack encodable ones. """ try: # numpy isn't an explicit dependency of bowtie # so we can't assume it's available import numpy as np if isinstance(obj, np.ndarray) or isinstance(obj, np.generic): # https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html return obj.tolist() except ImportError: pass if isinstance(obj, datetime) or isinstance(obj, time) or isinstance(obj, date): return obj.isoformat() return obj def pack(x): """ Encode ``x`` into msgpack with additional encoders. """ return bytes(msgpack.packb(x, default=encoders)) def unpack(x): """ Decode ``x`` from msgpack into a string. """ return msgpack.unpackb(bytes(x['data']), encoding='utf8') def make_event(event): """ Creates an event from a method signature. """ # pylint: disable=missing-docstring @property @wraps(event) def actualevent(self): name = event.__name__[3:] # pylint: disable=protected-access return '{uuid}#{event}'.format(uuid=self._uuid, event=name) return actualevent def is_event(attribute): """ Test if a method is an event. """ return attribute.startswith('on_') def make_command(command): """ Creates an command from a method signature. """ # pylint: disable=missing-docstring @wraps(command) def actualcommand(self, *args, **kwds): data = command(self, *args, **kwds) name = command.__name__[3:] # pylint: disable=protected-access signal = '{uuid}#{event}'.format(uuid=self._uuid, event=name) if flask.has_request_context(): emit(signal, {'data': pack(data)}) else: sio = flask.current_app.extensions['socketio'] sio.emit(signal, {'data': pack(data)}) eventlet.sleep() return actualcommand def is_command(attribute): """ Test if a method is an command. """ return attribute.startswith('do_') class _Maker(type): def __new__(mcs, name, parents, dct): for k in dct: if is_event(k): dct[k] = make_event(dct[k]) if is_command(k): dct[k] = make_command(dct[k]) return super(_Maker, mcs).__new__(mcs, name, parents, dct) class Component(with_metaclass(_Maker, object)): """ All visual and control classes subclass this so their events and commands get transformed by the metaclass. """ _NEXT_UUID = 0 @classmethod def _next_uuid(cls): cls._NEXT_UUID += 1 return cls._NEXT_UUID def __init__(self): # wanted to put "self" instead of "Component" # was surprised that didn't work self._uuid = Component._next_uuid() super(Component, self).__init__() def get(self, timeout=10): """ Sends a ``get`` command to the react component. Returns the the retreived data. """ event = LightQueue(1) if flask.has_request_context(): emit('{}#get'.format(self._uuid), callback=lambda x: event.put(unpack(x))) else: sio = flask.current_app.extensions['socketio'] sio.emit('{}#get'.format(self._uuid), callback=lambda x: event.put(unpack(x))) return event.get(timeout=timeout) PK{I1R6"6"bowtie/_layout.py# -*- coding: utf-8 -*- """ Defines the Layout class. """ import os from os import path import inspect import shutil import stat from collections import namedtuple, defaultdict from subprocess import Popen from flask import Markup from jinja2 import Environment, FileSystemLoader from markdown import markdown from bowtie._compat import makedirs from bowtie.control import _Controller from bowtie.visual import _Visual _Import = namedtuple('_Import', ['module', 'component']) _Control = namedtuple('_Control', ['instantiate', 'caption']) _Schedule = namedtuple('_Control', ['seconds', 'function']) class YarnError(Exception): """ Errors from ``Yarn``. """ pass class WebpackError(Exception): """ Errors from ``Webpack``. """ pass class Layout(object): """Create a Bowtie App. Parameters ---------- title : str, optional Title of the HTML. description : str, optional Describe the app in Markdown, inserted in control pane. basic_auth : bool, optional Enable basic authentication. username : str, optional Username for basic authentication. password : str, optional Password for basic authentication. background_color : str, optional Background color of the control pane. directory : str, optional Location where app is compiled. host : str, optional Host IP address. port : int, optional Host port number. debug : bool, optional Enable debugging in Flask. Disable in production! """ _packages = [ 'antd', 'babel-core', 'babel-loader', 'babel-plugin-transform-object-rest-spread', 'babel-polyfill', 'babel-preset-es2015', 'babel-preset-react', 'babel-preset-stage-0', 'classnames', 'core-js', 'css-loader', 'extract-text-webpack-plugin', 'less', 'less-loader', 'lodash.clonedeep', 'msgpack-lite', 'node-sass', 'normalize.css', 'postcss-modules-values', 'react', 'react-dom', 'sass-loader', 'socket.io-client', 'style-loader', 'webpack@1.14.0' ] def __init__(self, title='Bowtie App', description='Bowtie App\n---', basic_auth=False, username='username', password='password', background_color='White', directory='build', host='0.0.0.0', port=9991, debug=False): self.background_color = background_color self.basic_auth = basic_auth self.controllers = [] self.debug = debug self.description = Markup(markdown(description)) self.directory = directory self.functions = [] self.host = host self.imports = set() self.init = None self.packages = set([]) self.password = password self.port = port self.schedules = [] self.subscriptions = defaultdict(list) self.templates = set(['progress.jsx']) self.title = title self.username = username self.visuals = [[]] def add_visual(self, visual, next_row=False): """Add a visual to the layout. Parameters ---------- visual : bowtie._Visual A Bowtie visual instance. next_row : bool, optional Add this visual to the next row. """ assert isinstance(visual, _Visual) # pylint: disable=protected-access self.packages.add(visual._PACKAGE) self.templates.add(visual._TEMPLATE) self.imports.add(_Import(component=visual._COMPONENT, module=visual._TEMPLATE[:visual._TEMPLATE.find('.')])) if next_row and self.visuals[-1]: self.visuals.append([]) self.visuals[-1].append(visual) def add_controller(self, control): """Add a controller to the layout. Parameters ---------- control : bowtie._Controller A Bowtie controller instance. """ assert isinstance(control, _Controller) # pylint: disable=protected-access self.packages.add(control._PACKAGE) self.templates.add(control._TEMPLATE) self.imports.add(_Import(component=control._COMPONENT, module=control._TEMPLATE[:control._TEMPLATE.find('.')])) self.controllers.append(_Control(instantiate=control._instantiate, caption=control.caption)) def subscribe(self, event, func): """Call a function in response to an event. Parameters ---------- event : str Name of the event. func : callable Function to be called. """ quoted = "'{}'".format(event) self.subscriptions[quoted].append(func.__name__) def load(self, func): """Call a function on load. Parameters ---------- func : callable Function to be called. """ self.init = func.__name__ def schedule(self, seconds, func): """Call a function periodically. Parameters ---------- seconds : float Minimum interval of function calls. func : callable Function to be called. """ self.schedules.append(_Schedule(seconds, func.__name__)) def build(self): """Compiles the Bowtie application. """ file_dir = path.dirname(__file__) env = Environment(loader=FileSystemLoader( path.join(file_dir, 'templates') )) server = env.get_template('server.py') index = env.get_template('index.html') react = env.get_template('index.jsx') src, app, templates = create_directories(directory=self.directory) webpack_src = path.join(file_dir, 'src/webpack.config.js') shutil.copy(webpack_src, self.directory) server_path = path.join(src, server.name) # [1] grabs the parent stack and [1] grabs the filename source_filename = inspect.stack()[1][1] with open(server_path, 'w') as f: f.write( server.render( basic_auth=self.basic_auth, username=self.username, password=self.password, source_module=os.path.basename(source_filename)[:-3], subscriptions=self.subscriptions, schedules=self.schedules, initial=self.init, host="'{}'".format(self.host), port=self.port, debug=self.debug ) ) perms = os.stat(server_path) os.chmod(server_path, perms.st_mode | stat.S_IEXEC) with open(path.join(templates, index.name), 'w') as f: f.write( index.render(title=self.title) ) for template in self.templates: template_src = path.join(file_dir, 'src', template) shutil.copy(template_src, app) for i, visualrow in enumerate(self.visuals): for j, visual in enumerate(visualrow): # pylint: disable=protected-access self.visuals[i][j] = visual._instantiate(), visual.progress._instantiate() with open(path.join(app, react.name), 'w') as f: f.write( react.render( description=self.description, background_color=self.background_color, components=self.imports, controls=self.controllers, visuals=self.visuals ) ) init = Popen('yarn init -y', shell=True, cwd=self.directory).wait() if init != 0: raise YarnError('Error running "yarn init -y"') self.packages.discard(None) packages = ' '.join(self._packages + list(self.packages)) install = Popen('yarn add {}'.format(packages), shell=True, cwd=self.directory).wait() if install != 0: raise YarnError('Error install node packages') dev = Popen('webpack -d', shell=True, cwd=self.directory).wait() if dev != 0: raise WebpackError('Error building with webpack') def create_directories(directory='build'): """ Create all the necessary subdirectories for the build. """ src = path.join(directory, 'src') templates = path.join(src, 'templates') app = path.join(src, 'app') makedirs(app, exist_ok=True) makedirs(templates, exist_ok=True) return src, app, templates PKJXIu bowtie/_progress.py# -*- coding: utf-8 -*- """ Progress component """ from bowtie._component import Component class Progress(Component): """This component is used by all visual components and is not meant to be used alone. By default, it is not visible. It is an opt-in feature and you can happily use Bowtie without using the progress indicators at all. It is useful for indicating progress to the user for long-running processes. It can be accessed through the ``.progress`` accessor. Examples -------- >>> plotly = Plotly() >>> def callback(x): >>> plotly.progress.do_visible(True) >>> plotly.progress.do_percent(0) >>> compute1() >>> plotly.progress.do_inc(50) >>> compute2() >>> plotly.progress.do_visible(False) """ _TEMPLATE = 'progress.jsx' _COMPONENT = 'CProgress' _PACKAGE = 'antd' _TAG = ('') def _instantiate(self): return self._TAG.format( uuid="'{}'".format(self._uuid) ) # pylint: disable=no-self-use def do_percent(self, percent): """Set the percentage of the progress. Parameters ---------- percent : number Sets the progress to this percentage. Returns ------- None """ return percent def do_inc(self, inc): """Increments the progress indicator. Parameters ---------- inc : number Value to increment the progress. Returns ------- None """ return inc def do_visible(self, visible): """Hides and shows the progress indicator. Parameters ---------- visible : bool If ``True`` shows the progress indicator otherwise it is hidden. Returns ------- None """ return visible def do_active(self): """Hides and shows the progress indicator. Returns ------- None """ pass def do_success(self): """Hides and shows the progress indicator. Returns ------- None """ pass def do_error(self): """Hides and shows the progress indicator. Returns ------- None """ pass PK֫I?--bowtie/control.py# -*- coding: utf-8 -*- """ Control components """ from collections import Iterable from bowtie._component import Component, jdumps # pylint: disable=too-few-public-methods class _Controller(Component): """ Used to test if a an object is a controller. All controllers must inherit this class. """ pass class Button(_Controller): """Create a button. Parameters ---------- label : str, optional Label on the button. caption : str, optional Heading text. """ _TEMPLATE = 'button.jsx' _COMPONENT = 'SimpleButton' _PACKAGE = None _TAG = ('') def __init__(self, label='', caption=''): super(Button, self).__init__() self._instantiate = self._TAG.format( label="'{}'".format(label), uuid="'{}'".format(self._uuid) ) self.caption = caption def on_click(self): """Emits an event when the button is clicked. | **Payload:** ``None``. Returns ------- str Name of click event. """ pass class DropDown(_Controller): """Create a drop down. Parameters ---------- labels : array-like, optional List of strings which will be visible to the user. values : array-like, optional List of values associated with the labels that are hidden from the user. multi : bool, optional If multiple selections are allowed. caption : str, optional Heading text. """ _TEMPLATE = 'dropdown.jsx' _COMPONENT = 'DropDown' _PACKAGE = 'react-select' _TAG = ('') def __init__(self, labels=None, values=None, multi=False, caption=''): super(DropDown, self).__init__() if labels is None and values is None: labels = [] values = [] options = [dict(value=value, label=str(label)) for value, label in zip(values, labels)] self._instantiate = self._TAG.format( options=jdumps(options), multi='true' if multi else 'false', uuid="'{}'".format(self._uuid) ) self.caption = caption def on_change(self): """Emits an event when the selection changes. | **Payload:** ``dict`` with keys "value" and "label". """ pass # pylint: disable=no-self-use def do_options(self, labels, values): """Replaces the drop down fields. Parameters ---------- labels : array-like List of strings which will be visible to the user. values : array-like List of values associated with the labels that are hidden from the user. Returns ------- None """ return [dict(label=l, value=v) for l, v in zip(labels, values)] def _jsbool(x): """Convert Python bool to JS bool. """ return repr(x).lower() class Switch(_Controller): """Specific Date Pickers inherit this class. """ _TEMPLATE = 'switch.jsx' _COMPONENT = 'Toggle' _PACKAGE = 'antd' _TAG = ('') def __init__(self, initial=False, caption=''): super(Switch, self).__init__() self._instantiate = self._TAG.format( uuid="'{}'".format(self._uuid), defaultChecked=_jsbool(initial) ) self.caption = caption def on_switch(self): """Emits an event when the switch is toggled. | **Payload:** ``bool`` status of the switch. Returns ------- str Name of event. """ pass class _DatePickers(_Controller): """Specific Date Pickers inherit this class. """ _TEMPLATE = 'date.jsx' _COMPONENT = 'PickDates' _PACKAGE = 'antd' _TAG = ('') def __init__(self, date_type=False, month_type=False, range_type=False, caption=''): super(_DatePickers, self).__init__() self._instantiate = self._TAG.format( uuid="'{}'".format(self._uuid), date_type=_jsbool(date_type), month_type=_jsbool(month_type), range_type=_jsbool(range_type) ) self.caption = caption class DatePicker(_DatePickers): """Date Picker Parameters ---------- caption : str, optional Heading text. """ def __init__(self, caption=''): super(DatePicker, self).__init__(date_type=True, caption=caption) def on_change(self): """Emits an event when a date is selected. | **Payload:** ``str`` of the form ``"yyyy-mm-dd"``. Returns ------- str Name of event. """ pass class MonthPicker(_DatePickers): """Date Picker Parameters ---------- caption : str, optional Heading text. """ def __init__(self, caption=''): super(MonthPicker, self).__init__(month_type=True, caption=caption) def on_change(self): """Emits an event when a month is selected. | **Payload:** ``str`` of the form ``"yyyy-mm"``. Returns ------- str Name of event. """ pass class RangePicker(_DatePickers): """Date Picker Parameters ---------- caption : str, optional Heading text. """ def __init__(self, caption=''): super(RangePicker, self).__init__(range_type=True, caption=caption) def on_change(self): """Emits an event when a range is selected. | **Payload:** ``list`` of two dates ``["yyyy-mm-dd", "yyyy-mm-dd"]``. Returns ------- str Name of event. """ pass class Slider(_Controller): """Create a slider. Parameters ---------- start : number or list with two values, optional Determines the starting value. If a list of two values are given it will be a range slider. ranged : bool, optional If this is a range slider. minimum : number, optional Minimum value of the slider. maximum : number, optional Maximum value of the slider. step : number, optional Step size. caption : str, optional Heading text. References ---------- https://ant.design/components/slider/ """ _TEMPLATE = 'slider.jsx' _COMPONENT = 'AntSlider' _PACKAGE = 'antd' _TAG = ('') def __init__(self, start=None, ranged=False, minimum=0, maximum=100, step=1, caption=''): super(Slider, self).__init__() if not start: start = [0, 0] if ranged else 0 elif isinstance(start, Iterable): start = list(start) ranged = True self._instantiate = self._TAG.format( uuid="'{}'".format(self._uuid), range=_jsbool(ranged), minimum=minimum, maximum=maximum, start=start, step=step, marks={minimum: str(minimum), maximum: str(maximum)} ) self.caption = caption def on_change(self): """Emits an event when the slider's value changes. | **Payload:** ``number`` or ``list`` of values. Returns ------- str Name of event. """ pass def on_after_change(self): """Emits an event when the slider control is released. | **Payload:** ``number`` or ``list`` of values. Returns ------- str Name of event. """ pass class Nouislider(_Controller): """Create a slider. Parameters ---------- start : number or list with two values, optional Determines the starting value. If a list of two values are given it will be a range slider. minimum : number, optional Minimum value of the slider. maximum : number, optional Maximum value of the slider. tooltips : bool, optional Show a popup text box. caption : str, optional Heading text. References ---------- https://refreshless.com/nouislider/events-callbacks/ """ _TEMPLATE = 'nouislider.jsx' _COMPONENT = 'Nouislider' _PACKAGE = 'nouislider' _TAG = ('') def __init__(self, start=0, minimum=0, maximum=100, tooltips=True, caption=''): super(Nouislider, self).__init__() if not isinstance(start, Iterable): start = [start] else: start = list(start) self._instantiate = self._TAG.format( uuid="'{}'".format(self._uuid), min=minimum, max=maximum, start=start, tooltips='true' if tooltips else 'false' ) self.caption = caption def on_update(self): """Emits an event when the slider is moved. https://refreshless.com/nouislider/events-callbacks/ | **Payload:** ``list`` of values. Returns ------- str Name of event. """ pass def on_slide(self): """Emits an event when the slider is moved. https://refreshless.com/nouislider/events-callbacks/ | **Payload:** ``list`` of values. Returns ------- str Name of event. """ pass def on_set(self): """Emits an event when the slider is moved. https://refreshless.com/nouislider/events-callbacks/ | **Payload:** ``list`` of values. Returns ------- str Name of event. """ pass def on_change(self): """Emits an event when the slider is moved. https://refreshless.com/nouislider/events-callbacks/ | **Payload:** ``list`` of values. Returns ------- str Name of event. """ pass def on_start(self): """Emits an event when the slider is moved. https://refreshless.com/nouislider/events-callbacks/ | **Payload:** ``list`` of values. Returns ------- str Name of event. """ pass def on_end(self): """Emits an event when the slider is moved. https://refreshless.com/nouislider/events-callbacks/ | **Payload:** ``list`` of values. Returns ------- str Name of event. """ pass PKKbIތD!D!bowtie/visual.py# -*- coding: utf-8 -*- """ Visual components """ from bowtie._component import Component, jdumps from bowtie._progress import Progress # pylint: disable=too-few-public-methods class _Visual(Component): """ Used to test if a an object is a controller. All controllers must inherit this class. """ def __init__(self): self.progress = Progress() super(_Visual, self).__init__() class Table(_Visual): """Table Component with filtering and sorting Parameters ---------- columns : list, optional List of column names to display. results_per_page : int, optional Number of rows on each pagination of the table. """ _TEMPLATE = 'table.jsx' _COMPONENT = 'AntTable' _PACKAGE = 'antd' _TAG = ('') def __init__(self, data=None, columns=None, results_per_page=10): self.data = [] self.columns = [] if data: self.data, self.columns = self._make_data(data) elif columns: self.columns = self._make_columns(columns) self.results_per_page = results_per_page super(Table, self).__init__() def _instantiate(self): return self._TAG.format( uuid="'{}'".format(self._uuid), columns=self.columns, results_per_page=self.results_per_page ) @staticmethod def _make_columns(columns): """ doc """ return [dict(title=str(c), dataIndex=str(c), key=str(c)) for c in columns] @staticmethod def _make_data(data): """ doc """ jsdata = [] for idx, row in data.iterrows(): row.index = row.index.astype(str) rdict = row.to_dict() rdict.update(dict(key=str(idx))) jsdata.append(rdict) return jsdata, Table._make_columns(data.columns) # pylint: disable=no-self-use def do_data(self, data): """Replaces the columns and data of the table. Parameters ---------- data : pandas.DataFrame Returns ------- None """ return self._make_data(data) def do_columns(self, columns): """Updates the columns of the table Parameters ---------- columns : array-like List of strings. Returns ------- None """ return self._make_columns(columns) class SmartGrid(_Visual): """Table Component with filtering and sorting Parameters ---------- columns : list, optional List of column names to display. results_per_page : int, optional Number of rows on each pagination of the table. """ _TEMPLATE = 'griddle.jsx' _COMPONENT = 'SmartGrid' _PACKAGE = 'griddle-react' _TAG = ('') def __init__(self, columns=None, results_per_page=10): if columns is None: columns = [] self.columns = columns self.results_per_page = results_per_page super(SmartGrid, self).__init__() def _instantiate(self): return self._TAG.format( uuid="'{}'".format(self._uuid), columns=jdumps(self.columns), results_per_page=self.results_per_page ) # pylint: disable=no-self-use def do_update(self, data): """Updates the data of the table Parameters ---------- data : list of dicts Each entry in the list must be a dict with the same keys which are the columns of the table. Returns ------- None """ return data class SVG(_Visual): """SVG image, mainly for matplotlib plots. Parameters ---------- preserve_aspect_ratio : bool, optional If ``True`` it preserves the aspect ratio otherwise it will stretch to fill up the space available. """ _TEMPLATE = 'svg.jsx' _COMPONENT = 'SVG' _PACKAGE = None _TAG = ('') def __init__(self, preserve_aspect_ratio=False): self.preserve_aspect_ratio = preserve_aspect_ratio super(SVG, self).__init__() def _instantiate(self): return self._TAG.format( uuid="'{}'".format(self._uuid), preserve_aspect_ratio='true' if self.preserve_aspect_ratio else 'false' ) # pylint: disable=no-self-use def do_image(self, image): """Replaces the image. Parameters ---------- image : str Generated by ``savefig`` from matplotlib with ``format=svg``. Returns ------- None Examples -------- >>> from io import StringIO >>> import matplotlib >>> matplotlib.use('Agg') >>> import matplotlib.pyplot as plt >>> image = SVG() >>> >>> def callback(x): >>> sio = StringIO() >>> plt.plot(range(5)) >>> plt.savefig(sio, format='svg') >>> sio.seek(0) >>> s = sio.read() >>> idx = s.find('>> s = s[idx:] >>> image.do_image(s) """ return image class Plotly(_Visual): """ Plotly component. """ _TEMPLATE = 'plotly.jsx' _COMPONENT = 'PlotlyPlot' _PACKAGE = 'plotly.js' _TAG = ('') def __init__(self, init=None): if init is None: init = dict(data=[], layout={'autosize': False}) self.init = init super(Plotly, self).__init__() def _instantiate(self): return self._TAG.format( uuid="'{}'".format(self._uuid), init=jdumps(self.init), ) ## Events def on_click(self): """Plotly click event. | **Payload:** TODO. Returns ------- str Name of event. """ pass def on_beforehover(self): """Emits an event before hovering over a point. | **Payload:** TODO. Returns ------- str Name of event. """ pass def on_hover(self): """Emits an event after hovering over a point. | **Payload:** TODO. Returns ------- str Name of event. """ pass def on_unhover(self): """Emits an event when hover is removed. | **Payload:** TODO. Returns ------- str Name of event. """ pass def on_select(self): """Emits an event when points are selected with a tool. | **Payload:** TODO. Returns ------- str Name of event. """ pass ## Commands # pylint: disable=no-self-use def do_all(self, plot): """Replaces the entire plot. Parameters ---------- plot : dict Dict that can be plotted with Plotly. Returns ------- None """ return plot def do_data(self, data): """Replaces the data portion of the plot. Parameters ---------- data : list of traces List of data to replace the old data. Returns ------- None """ return data def do_layout(self, layout): """Updates the layout. Parameters ---------- layout : dict Contains layout information. Returns ------- None """ return layout def do_config(self, config): """Updates the configuration of the plot. Parameters ---------- config : dict Plotly config information. Returns ------- None """ return config PKJXI*Ơbowtie/src/button.jsximport React from 'react'; import { Button } from 'antd'; import 'antd/dist/antd.css'; export default class SimpleButton extends React.Component { constructor(props) { super(props); } handleClick = event => { this.props.socket.emit(this.props.uuid + '#click'); } render() { return ( ); } } SimpleButton.propTypes = { label: React.PropTypes.string.isRequired, uuid: React.PropTypes.string.isRequired, socket: React.PropTypes.object.isRequired }; PKЮ}InmGGbowtie/src/datagrid.jsximport 'react-datagrid/index.css'; import React from 'react'; import DataGrid from 'react-datagrid'; export default class Table extends React.Component { render() { var data = [ { id: '1', firstName: 'John', lastName: 'Bobson'}, { id: '2', firstName: 'Bob', lastName: 'Mclaren'}, { id: '3', firstName: 'Bob', lastName: 'Mclaren'}, { id: '4', firstName: 'Bob', lastName: 'Mclaren'}, { id: '5', firstName: 'Bob', lastName: 'Mclaren'}, { id: '6', firstName: 'Bob', lastName: 'Mclaren'}, { id: '7', firstName: 'Bob', lastName: 'Mclaren'}, { id: '8', firstName: 'Bob', lastName: 'Mclaren'}, { id: '9', firstName: 'Bob', lastName: 'Mclaren'}, { id: '10', firstName: 'Bob', lastName: 'Mclaren'}, { id: '11', firstName: 'Bob', lastName: 'Mclaren'}, { id: '12', firstName: 'Bob', lastName: 'Mclaren'}, { id: '13', firstName: 'Bob', lastName: 'Mclaren'}, { id: '14', firstName: 'Bob', lastName: 'Mclaren'}, { id: '15', firstName: 'Bob', lastName: 'Mclaren'}, { id: '16', firstName: 'Bob', lastName: 'Mclaren'}, { id: '17', firstName: 'Bob', lastName: 'Mclaren'}, { id: '18', firstName: 'Bob', lastName: 'Mclaren'}, { id: '19', firstName: 'Bob', lastName: 'Mclaren'}, { id: '20', firstName: 'Bob', lastName: 'Mclaren'}, { id: '21', firstName: 'Bob', lastName: 'Mclaren'}, { id: '22', firstName: 'Bob', lastName: 'Mclaren'}, { id: '23', firstName: 'Bob', lastName: 'Mclaren'}, { id: '24', firstName: 'Bob', lastName: 'Mclaren'} ]; var columns = [ { name: 'firstName'}, { name: 'lastName'} ]; return ( ); } } Table.propTypes = { uuid: React.PropTypes.string.isRequired, socket: React.PropTypes.object.isRequired }; PKI bowtie/src/date.jsximport React from 'react'; import { DatePicker, LocaleProvider } from 'antd'; import enUS from 'antd/lib/locale-provider/en_US'; import 'antd/dist/antd.css'; // import 'antd/lib/date-picker/style/index.css'; const { MonthPicker, RangePicker } = DatePicker; var msgpack = require('msgpack-lite'); export default class PickDates extends React.Component { constructor(props) { super(props); this.state = {value: null}; } handleChange = (moment, ds) => { this.setState({value: moment}); this.props.socket.emit(this.props.uuid + '#change', msgpack.encode(ds)); } componentDidMount() { var socket = this.props.socket; var uuid = this.props.uuid; socket.on(uuid + '#get', this.getValue); } getValue = (data, fn) => { fn(msgpack.encode(this.state.value)); } render () { if (this.props.date) { return ( ); } else if (this.props.month) { return ( ); } else { return ( ); } } } PickDates.propTypes = { uuid: React.PropTypes.string.isRequired, socket: React.PropTypes.object.isRequired, date: React.PropTypes.bool.isRequired, month: React.PropTypes.bool.isRequired, range: React.PropTypes.bool.isRequired, }; PKЮ}IXXXbowtie/src/dropdown.jsximport React from 'react'; import Select from 'react-select'; // Be sure to include styles at some point, probably during your bootstrapping import 'react-select/dist/react-select.css'; var msgpack = require('msgpack-lite'); export default class DropDown extends React.Component { constructor(props) { super(props); this.state = {value: null, options: this.props.initOptions}; this.handleChange = this.handleChange.bind(this); // this.getValue = this.getValue.bind(this); this.newOptions = this.newOptions.bind(this); } handleChange(value) { this.setState({value}); this.props.socket.emit(this.props.uuid + '#change', msgpack.encode(value)); } newOptions(data) { var arr = new Uint8Array(data['data']); this.setState({value: null, options: msgpack.decode(arr)}); } componentDidMount() { var socket = this.props.socket; var uuid = this.props.uuid; socket.on(uuid + '#get', this.getValue); socket.on(uuid + '#options', this.newOptions); } getValue = (data, fn) => { fn(msgpack.encode(this.state.value)); } render () { return (