def __init__(self, ipython): """Public constructor.""" if VariableInspectorWindow.instance is not None: raise Exception( """Only one instance of the Variable Inspector can exist at a time. Call close() on the active instance before creating a new instance. If you have lost the handle to the active instance, you can re-obtain it via `VariableInspectorWindow.instance`.""") VariableInspectorWindow.instance = self self.closed = False self.namespace = NamespaceMagics() self.namespace.shell = ipython.kernel.shell self._popout = widgets.PopupWidget() self._popout.description = "Variable Inspector" self._popout.button_text = self._popout.description self._modal_body = widgets.ContainerWidget() self._modal_body.set_css('overflow-y', 'scroll') self._modal_body_label = widgets.HTMLWidget(value='Not hooked') self._modal_body.children = [self._modal_body_label] self._popout.children = [ self._modal_body, ] self._ipython = ipython self._ipython.register_post_execute(self._fill)
def _value_changed(self, __ ,value): title = widgets.HTMLWidget(value ='<h5>%s</h5>' % self.description) children = [title] for elem in value: wcont = widgets.ContainerWidget(description = str(elem)) wtitle = widgets.LatexWidget(value = str(elem)) edit_button = widgets.ButtonWidget(description = "Edit") delete_button = widgets.ButtonWidget(description = "Delete") wcont.children = [wtitle, edit_button, delete_button] def edit_f(button): if self.add_representation: wr = self.add_representation(self.klass, container_widget = widgets.PopupWidget, ) else: raise NotImplementedError() def edit_callback(obj): wr.cont.close() wr.edit_object(elem) wr.edit_callback = edit_callback edit_button.on_click(edit_f) def delete_f(button): l = list(self.value) l.remove(elem) self.value = l delete_button.on_click(delete_f) children.append(wcont) wcont.on_displayed(self._set_style) add_button = widgets.ButtonWidget(description = "Add %s" % self.klass.__name__) def add_f(button): if self.add_representation: wr = self.add_representation(self.klass, container_widget = widgets.PopupWidget, ) def handler(obj): self.value = list(self.value) + [obj] wr.cont.close() wr.create_handler = handler else: raise NotImplementedError() wr.create_object() add_button.on_click(add_f) children.append(add_button) self.children = children self._fire_children_displayed()
def factorizer(): box = widgets.ContainerWidget() header = widgets.HTMLWidget(value="<h1>Integer Factorizer</h1><br>") number = widgets.IntSliderWidget(description="Number:", value=100) speed = widgets.FloatSliderWidget(description="Delay:", min=0.0, max=0.2, value=0.1, step=0.01) subbox = widgets.ContainerWidget() button = widgets.ButtonWidget(description="Calculate") subbox.children = [button] box.children = [header, number, speed, subbox] display(box) box.add_class('align-center') box.add_class('center') box.add_class('well well-small') box.set_css('width', 'auto') subbox.remove_class('vbox') subbox.add_class('hbox') # subbox.add_class('end') def handle_caclulate(sender): plot_primes(number.value, delay=speed.value) button.on_click(handle_caclulate)
def make_form(self, css_classes): iocont = widgets.ContainerWidget() css_classes[iocont] = ('iobject-container') add_child(iocont, widgets.HTMLWidget(value="<h3>%s</h3>" % self.name)) for inp in self.free_inputs: #We have to filter none kw... allkw = dict(description=inp.name, value=inp.value, default=inp.default) kw = { key: value for (key, value) in allkw.items() if value is not None } w = widgets.TextWidget(**kw) inp.widget = w w.traits()['value'].allow_none = True traitlets.link((inp, 'value'), (w, 'value')) def set_exec(_w): self.executed = False w.on_trait_change(set_exec, name='value') add_child(iocont, w) for out in self.free_outputs: w = widgets.HTMLWidget() out.widget = w add_child(iocont, w) w.traits()['value'].allow_none = True traitlets.link((out, 'value'), (w, 'value')) button = widgets.ButtonWidget(description="Execute %s" % self.name) def _run(b): self.executed = False self.run_sync() button.on_click(_run) add_child(iocont, button) self.widget = iocont self.widget.button = button self.has_widget = True self._toggle_executed() return iocont
def displayResultsDialog(self): self.resultWidget = widgets.SelectWidget(description='File info:', values=[]) fileDetail = widgets.TextWidget(description='Detail') self.resultLink = widgets.HTMLWidget(value=getDownloadResultLink(None)) def updateFileDetail(item, value): fileDetail.value = unicode(value) self.resultWidget.on_trait_change(updateFileDetail, 'value') display(self.resultWidget, fileDetail, self.resultLink)
def display_chart_chartjs(sc_est2012_sex, show_javascript, show, div): sc_est2012_sex_template = jinja2.Template( """ require(["chartjs"], function() { var data = { labels : {{ labels }}, datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", data : {{ dataset_male }} }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", data : {{ dataset_female }} } ] } var ctx = $('#chart_chartjs')[0].getContext('2d'); new Chart(ctx).Bar(data,{}); }); """ ) if show == 'by_region': data_frame = sc_est2012_sex.groupby(['REGION', 'SEX'], as_index=False)[['POPEST2012_CIV']].sum() labels = [region_codes[code] for code in data_frame['REGION'].drop_duplicates()] elif show == 'by_division': data_frame = sc_est2012_sex.groupby(['DIVISION', 'SEX'], as_index=False)[['POPEST2012_CIV']].sum() labels = [division_codes[code] for code in data_frame['DIVISION'].drop_duplicates()] elif show == 'by_state': data_frame = sc_est2012_sex.groupby(['STATE', 'SEX'], as_index=False)[['POPEST2012_CIV']].sum() data_frame = pd.merge(data_frame, state, left_on='STATE', right_on='STATE') labels = data_frame['STATE_NAME'].drop_duplicates().tolist() dataset_male = data_frame[data_frame.SEX == 1]['POPEST2012_CIV'].tolist() dataset_female = data_frame[data_frame.SEX == 2]['POPEST2012_CIV'].tolist() rendered_template = sc_est2012_sex_template.render( labels=dumps(labels), dataset_male=dumps(dataset_male), dataset_female=dumps(dataset_female), ) if show_javascript: display(widgets.PopupWidget(children=(widgets.HTMLWidget(value='<div style="width:600px; height: 400px; overflow:scroll;"><pre>{}</pre></div>'.format(rendered_template)),))) display(Javascript(rendered_template))
def make_control(self): control_container = widgets.ContainerWidget() run_all_btn = widgets.ButtonWidget(description="Run all") def _ra(btn): result = self.run_all() display(result) run_all_btn.on_click(_ra) add_child(control_container, widgets.HTMLWidget(value="<h2>%s</h2>" % self.name)) add_child(control_container, run_all_btn) css_classes = {control_container: 'control-container'} for node in self.sorted_iterate(): add_child(control_container, node.make_form(css_classes)) display(control_container) for (widget, klass) in css_classes.items(): if isinstance(widget, widgets.ContainerWidget): widget.remove_class("vbox") widget.add_class(klass)
def __call__(self): # Initalize image widget if (ViewMagic.options['backend'] == 'mpld3' or ViewMagic.options['fig'] == 'svg'): self.image_widget = widgets.HTMLWidget() else: self.image_widget = widgets.ImageWidget() if self.cached: self.image_widget.value = list(self.frames.values())[0] else: self.image_widget.value = self._plot_figure(0) self.image_widget.set_css(self.css) # Initialize interactive widgets interactive_widget = widgets.interactive(self.update_widgets, **self.pwidgets) interactive_widget.set_css(self.css) # Display widgets display(interactive_widget) display(self.image_widget) return '' # Suppresses outputting ViewableElement repr when called through hook
def __init__(self, header='Automatic Display System'): ''' This is simply an HTML display widget, and is going to contain stuff which you want to be displayed at any times ''' self.header = widgets.LatexWidget(value=header) display(self.header) self.header.font_size = '15pt' self.header.margin = '5pt' self.clearButton = widgets.ButtonWidget( description='Clear the Display') self.clearButton.on_click(callback=self.clearDisplay) self.visibleButton = widgets.ButtonWidget(description='Toggle Display') self.visibleButton.on_click(callback=self.toggleDisplay) self.container = widgets.HBox() self.container.background_color = '#999999' self.container.width = '100%' display(self.container) self.container.children = [self.clearButton, self.visibleButton] self.textToDisplay = '[-------------- %s -----------]' % header self.dispFrame = widgets.HTMLWidget() self.dispFrame.background_color = '#F0F0F0' self.dispFrame.margin = '5pt' self.dispFrame.width = '100%' self.dispFrame.height = '300px' display(self.dispFrame) self.display() return
def __init__(self, df): Browse.instance = self self.closed = False self._popout = widgets.PopupWidget() self._popout.description = getattr(df, 'name', 'df') self._popout.button_text = self._popout.description self._modal_body = widgets.ContainerWidget() self._modal_body.set_css('overflow-y', 'scroll') self._modal_body_label = widgets.HTMLWidget(value='Not hooked') self._modal_body.children = [self._modal_body_label] self._popout.children = [ self._modal_body, ] self._df = df self._ipython = get_ipython() self._ipython.register_post_execute(self._fill) self.ncols = len(df._info_axis) self.nrows = len(df)
from IPython.html import widgets from IPython.display import clear_output, display, HTML, Image, Javascript # From http://nbviewer.ipython.org/gist/anonymous/840b5cec9e19f3e39090 hbox = lambda x: (x.remove_class("vbox"), x.add_class("hbox")) # frame = lambda x: x.set_css({ "border": "outset 1px", "padding": 5, "border-radius": 5, "display": "inline-box", "margin": "5px" }) # Example if __name__ == "__main__": c = widgets.CheckboxWidget( description="", value=True) #, width=100, font_size='14pt', fore_color='red') t = widgets.HTMLWidget( value= "how solution with a very long text how to align on the left? how solution with a very long text how to align on the left? how solution with a very long text how to align on the left?" ) t.set_css({'font-size': 16, 'width': '80%', 'margin-top': 4}) cont = widgets.ContainerWidget(children=[c, t]) frame(cont) display(cont) _ = hbox(cont)
def as_widget(self): bokeh_widget= widgets.HTMLWidget() bokeh_widget.value = notebook_div(self.plot) return bokeh_widget
def display_ipython(self): """Displays the scene using an IPython widget inside an IPython notebook cell. Notes ===== IPython widgets are only supported by IPython versions >= 2.0.0. """ # Raise error whenever display_ipython() is called and IPython is # not installed or IPython < '2.0.0' if IPython is None: raise ImportError('IPython is not installed but is required. ' + 'Please install IPython >= 2.0 and try again') elif ipython_less_than_3 is None: raise ImportError('You have IPython ' + IPython.__version__ + ' installed but PyDy supports IPython >= 2.0.0' + 'Please update IPython and try again') self.create_static_html(silent=True) # Only create the constants input boxes and the rerun simulation # button if the scene was generated with a System. if self._system is not None: # Construct a container that holds all of the constants input # text widgets. if ipython_less_than_3: self._constants_container = widgets.ContainerWidget() self._constants_container.set_css({"max-height": "10em", "overflow-y": "scroll", "display": "block"}) else: self._constants_container = widgets.Box() self._constants_container._css = [("canvas", "width", "100%")] self._constants_text_widgets = OrderedDict() self._fill_constants_widgets() # Add all of the constants widgets to the container. self._constants_container.children = \ self._constants_text_widgets.values() self._initialize_rerun_button() display(self._constants_container) display(self._rerun_button) with open("static/index_ipython.html", 'r') as html_file: html = html_file.read() html = html.format(load_url='static/' + self._scene_json_file) if ipython_less_than_3: self._html_widget = widgets.HTMLWidget(value=html) self._html_widget.set_css({"display": "block", "float": "left"}) else: self._html_widget = widgets.HTML(value=html) display(self._html_widget)
def display_chart_d3(data, show_javascript, states, div): sub_est_2012_df_by_state_template = jinja2.Template( """ // Based on http://www.recursion.org/d3-for-mere-mortals/ require(["d3"], function(d3) { var data = [] {% for row in data %} data.push({ 'state': '{{ row[4] }}', 'population': {{ row[1] }} }); {% endfor %} d3.select("#chart_d3_interactive svg").remove() var margin = {top: 20, right: 20, bottom: 30, left: 40}, width = 800 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; var x = d3.scale.ordinal() .rangeRoundBands([0, width], .25); var y = d3.scale.linear() .range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left") .ticks(10) .tickFormat(d3.format('.1s')); var svg = d3.select("#chart_d3_interactive").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); x.domain(data.map(function(d) { return d.state; })); y.domain([0, d3.max(data, function(d) { return d.population; })]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Population"); svg.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.state); }) .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.population); }) .attr("height", function(d) { return height - y(d.population); }); }); """ ) rendered_template = sub_est_2012_df_by_state_template.render( data=data[data['STUSAB'].map(lambda v: v in states)].itertuples() ) if show_javascript: display(widgets.PopupWidget(children=(widgets.HTMLWidget(value='<div style="width:600px; height: 400px; overflow:scroll;"><pre>{}</pre></div>'.format(rendered_template)),))) display(Javascript(rendered_template))
# In[27]: values = { record['STUSAB']: "{0} - {1}".format(record['STUSAB'], record['STATE_NAME']) for record in state[['STUSAB', 'STATE_NAME']].sort('STUSAB').to_dict(outtype='records') } i = interact( display_chart_d3, data=widgets.fixed(sub_est_2012_df_by_state), show_javascript=widgets.CheckboxWidget(value=False), states=MultipleSelectWidget( value=['CA', 'NY'], values=values, values_order=sorted(values.keys()) ), div=widgets.HTMLWidget(value='<div id="chart_d3_interactive"></div>') ) # We've also added a show_javascript checkbox to display the generated code on a pop-up. # Although D3 is capable of creating [incredible charts](https://github.com/mbostock/d3/wiki/Gallery), it has a steep learning curve and it can be overkill if what you want are just simple charts. Let us explore simpler alternatives. # ## Part 2 - Embedding Chart.js # On the previous part we used [D3.js](http://d3js.org/) to embed interactive charts onto an IPython Notebook. D3.js is an extremely flexible library capable of creating incredible charts, but it can be hard to use. If all we need is just a simple chart without much work, there are other charting libraries that can do just that. # # [Chart.js](http://www.chartjs.org/) is an HTML5 charting library capable of producing beautiful graphics with very little code. First we need to declare the requirement using RequireJS: # In[28]:
def display_ipython(self): """ Method to display the visualization inside the Ipython notebook. It is only supported by IPython versions>=2.0.0 """ self.create_static_html(silent=True) self._widget_dict = OrderedDict() self.container = widgets.ContainerWidget() components = [] for var, init_val in \ zip(self.constant_variables, self.constant_values): self._widget_dict[str(var)] = widgets.FloatTextWidget( value=init_val, description=str(var)) components.append(self._widget_dict[str(var)]) self.button = widgets.ButtonWidget(description="Rerun Simulations") def button_click(clicked): self.button.add_class('disabled') self.button.description = 'Rerunning Simulation ...' self.constant_values = [] for i in self._widget_dict.values(): self.constant_values.append(i.value) if self.system is not None: #update system constants self.system.constants = dict( zip(self.system.constants, self.constant_values)) self.generate_visualization_json_system(self.system) else: self.generate_visualization_json( self.dynamic_variables, self.constant_variables, self.dynamic_values, self.constant_values, fps=self.fps, outfile_prefix=self.outfile_prefix) self.create_static_html(overwrite=True, silent=True) js = 'jQuery("#json-input").val("{}");'.format( 'static/' + self.scene_json_file) display(Javascript(js)) display(Javascript('jQuery("#simulation-load").click()')) self.button.remove_class('disabled') self.button.description = 'Rerun Simulation' self.button.on_click(button_click) #components.append(button) html_file = open("static/index_ipython.html") self.html_widget = widgets.HTMLWidget(value=html_file.read().format( load_url='static/' + self.scene_json_file)) self.container.children = components self.container.set_css({ "max-height": "10em", "overflow-y": "scroll", "display": "block" }) self.html_widget.set_css({"display": "block", "float": "left"}) display(self.container) display(self.button) display(self.html_widget) self.button.add_class('btn-info')