Python ipywidgets.HTML Examples

The following are 30 code examples of ipywidgets.HTML(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipywidgets , or try the search function .
Example #1
Source File: chart.py    From ipygee with MIT License 8 votes vote down vote up
def renderWidget(chart, width=None, height=None):
    """ Render a pygal chart into a Jupyter Notebook """
    from ipywidgets import HTML

    b64 = base64.b64encode(chart.render()).decode('utf-8')

    src = 'data:image/svg+xml;charset=utf-8;base64,'+b64

    if width and not height:
        html = '<embed src={} width={}></embed>'.format(src, width)
    elif height and not width:
        html = '<embed src={} height={}></embed>'.format(src, height)
    elif width and height:
        html = '<embed src={} height={} width={}></embed>'.format(src,
                                                                  height,
                                                                  width)
    else:
        html = '<embed src={}>'.format(src)

    return HTML(html) 
Example #2
Source File: options.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _widget(self):
        if not hasattr(self, "_cached_widget"):
            try:
                import ipywidgets

                children = [ipywidgets.HTML("<h2>Cluster Options</h2>")]
                children.extend([f.widget() for f in self._fields.values()])
                column = ipywidgets.Box(
                    children=children,
                    layout=ipywidgets.Layout(
                        display="flex", flex_flow="column", align_items="stretch"
                    ),
                )
                widget = ipywidgets.Box(children=[column])
            except ImportError:
                widget = None
            object.__setattr__(self, "_cached_widget", widget)
        return self._cached_widget 
Example #3
Source File: options.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def widget(self):
        import ipywidgets

        def handler(change):
            self.set(change.new)

        input = self._widget()
        input.observe(handler, "value")
        self._widgets.add(input)

        label = ipywidgets.HTML(
            "<p style='font-weight: bold; margin-right: 8px'>%s:</p>" % self.label
        )

        row = ipywidgets.Box(
            children=[label, input],
            layout=ipywidgets.Layout(
                display="flex", flex_flow="row wrap", justify_content="space-between"
            ),
        )

        return row 
Example #4
Source File: compute.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def make_header(self):
        img = io.open(os.path.join(mdt.PACKAGEPATH, '_static_data/img/banner.png'), 'r+b').read()
        encoded = base64.b64encode(img).decode('ascii')
        img = '<img style="max-width:100%" src=data:image/png;base64,'+('%s>'%encoded)
        links = [self._makelink(*args) for args in
                   (("http://moldesign.bionano.autodesk.com/", 'About'),
                    ("https://github.com/autodesk/molecular-design-toolkit/issues", 'Issues'),
                    ("http://bionano.autodesk.com/MolecularDesignToolkit/explore.html",
                     "Tutorials"),
                    ('http://autodesk.github.io/molecular-design-toolkit/', 'Documentation'),
                    ('https://lifesciences.autodesk.com/', 'Adsk LifeSci')
                    )]
        linkbar = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.join(links)
        return ipy.HTML(("<span style='float:left;font-size:0.8em;font-weight:bold'>Version: "
                         "{version}</span>"
                         "<span style='float:right'>{linkbar}</span>"
                         "<p>{img}</p>").format(img=img, linkbar=linkbar, version=mdt.__version__)) 
Example #5
Source File: jobs_widget.py    From qiskit-ibmq-provider with Apache License 2.0 6 votes vote down vote up
def _title_builder(sel_dict: dict) -> str:
    """Build the title string for the jobs table.

    Args:
        sel_dict: Dictionary containing information on jobs.

    Returns:
        HTML string for title.
    """
    if 'day' not in sel_dict.keys():
        title_str = 'Jobs in {mon} {yr} ({num})'.format(mon=MONTH_NAMES[sel_dict['month']],
                                                        yr=sel_dict['year'],
                                                        num=len(sel_dict['jobs']))
    else:
        title_str = 'Jobs on {day} {mon} {yr} ({num})'.format(day=sel_dict['day'],
                                                              mon=MONTH_NAMES[sel_dict['month']],
                                                              yr=sel_dict['year'],
                                                              num=len(sel_dict['jobs']))
    return "<h4>{}</h4>".format(title_str) 
Example #6
Source File: job_widgets.py    From qiskit-ibmq-provider with Apache License 2.0 6 votes vote down vote up
def make_labels() -> widgets.HBox:
    """Makes the labels widget.

    Returns:
        The labels widget.
    """
    labels0 = widgets.HTML(value="<h5>Job ID</h5>",
                           layout=widgets.Layout(width='190px'))
    labels1 = widgets.HTML(value='<h5>Backend</h5>',
                           layout=widgets.Layout(width='165px'))
    labels2 = widgets.HTML(value='<h5>Status</h5>',
                           layout=widgets.Layout(width='125px'))
    labels3 = widgets.HTML(value='<h5>Est. Start Time</h5>',
                           layout=widgets.Layout(width='100px'))

    labels = widgets.HBox(children=[labels0, labels1, labels2, labels3],
                          layout=widgets.Layout(width='700px',
                                                margin='0px 0px 0px 35px'))
    return labels 
Example #7
Source File: visualization.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def __init__(self, pyname, getversion=False):
        self.displays = {}
        self.pyname = pyname
        self.getversion = getversion

        self.nbv_display = VBox()
        self.widgets_display = VBox()
        self.warning = ipywidgets.HTML()

        super().__init__()
        children = [ipywidgets.HTML("<h4><center>%s</center></h4>" % self.pyname,
                                    layout=ipywidgets.Layout(align_self='center')),
                    ipywidgets.HTML(self.HEADER)]

        for location in install.nbextension_ordered_paths():
            self.state = install.get_installed_versions(self.pyname, self.getversion)
            props = self._get_props(location)
            self.displays[location] = ExtensionInstallLocation(self, props)
            children.append(self.displays[location])

        children.append(self.warning)

        self.children = children
        self._highlight_active() 
Example #8
Source File: visualization.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def __init__(self, parent, props):
        super().__init__(layout=ipywidgets.Layout(align_items='flex-end'))
        self.parent = parent
        self.props = props
        self.install_button = ipywidgets.Button()
        self.install_button.add_class('nbv-table-row')
        self.remove_button = ipywidgets.Button(description='remove')
        self.remove_button.add_class('nbv-table-row')
        self.html = ipywidgets.HTML()

        if self.props['writable'] == 'INSTALLED':
            self.chidlren = (self.html,)
        else:
            self.children = (self.html, self.install_button, self.remove_button)
        self.install_button.on_click(self.install)
        self.remove_button.on_click(self.uninstall)
        self.rerender() 
Example #9
Source File: images.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def __init__(self, image, client):
        self._err = False
        self._client = client
        self.image = image
        self.status = ipy.HTML(layout=ipy.Layout(width="20px"))
        self.html = ipy.HTML(value=image, layout=ipy.Layout(width="400px"))
        self.html.add_class('nbv-monospace')
        self.msg = ipy.HTML(layout=ipy.Layout(width='300px'))
        self.button = ipy.Button(layout=ipy.Layout(width='100px'))
        if mdt.compute.config.devmode:
            self.button.on_click(self.rebuild)
        else:
            self.button.on_click(self.pull)
        self._reactivate_button()
        self._set_status_value()
        super().__init__(children=[self.status, self.html, self.button, self.msg]) 
Example #10
Source File: geombuilder.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def _set_tool_state(self, *args):
        """ Observes the `viewer.selected_atom_indices` list and updates the tool panel accordingly

        Returns:
            Tuple(ipywidgets.BaseWidget): children of the tool panel
        """
        atoms = self.viewer.selected_atoms
        with self.viewer.hold_trait_notifications():
            for shape in self._widgetshapes.values():
                if shape == '_axes':
                    self.viewer.draw_axes(False)
                else:
                    self.viewer.remove(shape)
            self._widgetshapes = {}

        if len(atoms) == 1:
            self._setup_atom_tools(atoms)
        elif len(atoms) == 2:
            self._setup_distance_tools(atoms)
        elif len(atoms) == 3:
            self._setup_angle_tools(atoms)
        elif len(atoms) == 4:
            self._setup_dihedral_tools(atoms)
        else:
            self.tool_holder.children = (ipy.HTML('Please click on 1-4 atoms'),) 
Example #11
Source File: components.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def __init__(self, format=None, *args, **kwargs):
        description = kwargs.pop('description', 'FloatSlider')
        min = kwargs.setdefault('min', 0.0)
        max = kwargs.setdefault('max', 10.0)
        self.formatstring = format
        self.header = ipy.HTML()
        self.readout = ipy.Text(layout=ipy.Layout(width='100px'))
        self.readout.on_submit(self.parse_value)

        kwargs.setdefault('readout', False)
        self.slider = ipy.FloatSlider(*args, **process_widget_kwargs(kwargs))
        self.minlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(self.formatstring.format(min)))
        self.maxlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(self.formatstring.format(max)))
        self.sliderbox = HBox([self.minlabel, self.slider, self.maxlabel])
        traitlets.link((self, 'description'), (self.header, 'value'))
        traitlets.link((self, 'value'), (self.slider, 'value'))
        self.description = description
        self.update_readout()
        super().__init__([self.header,
                                                  self.readout,
                                                  self.sliderbox]) 
Example #12
Source File: job_widgets.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def make_labels():
    """Makes the labels widget.

    Returns:
        widget: The labels widget.
    """
    labels0 = widgets.HTML(value="<h5>Job ID</h5>",
                           layout=widgets.Layout(width='190px'))
    labels1 = widgets.HTML(value='<h5>Backend</h5>',
                           layout=widgets.Layout(width='145px'))
    labels2 = widgets.HTML(value='<h5>Status</h5>',
                           layout=widgets.Layout(width='95px'))
    labels3 = widgets.HTML(value='<h5>Queue</h5>',
                           layout=widgets.Layout(width='70px'))
    labels4 = widgets.HTML(value='<h5>Message</h5>')

    labels = widgets.HBox(children=[labels0, labels1, labels2, labels3, labels4],
                          layout=widgets.Layout(width='600px',
                                                margin='0px 0px 0px 37px'))
    return labels 
Example #13
Source File: progress_bar.py    From threeML with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def animate(self, iteration):

        # We only update the progress bar if the progress has gone backward,
        # or if the progress has increased by at least 1%. This is to avoid
        # updating it too much, which would fill log files in text mode,
        # or slow down the computation in HTML mode

        this_percent = iteration / float(self._iterations) * 100.0

        if this_percent - self._last_printed_percent < 0 or (this_percent - self._last_printed_percent) >= 1:

            self._last_iteration = self._animate(iteration)

            self._last_printed_percent = this_percent

        else:

            self._last_iteration = iteration 
Example #14
Source File: leaflet.py    From traffic with MIT License 6 votes vote down vote up
def point_leaflet(point: "PointMixin", **kwargs) -> Marker:
    """Returns a Leaflet layer to be directly added to a Map.

    .. warning::
        This is only available if the Leaflet `plugin <plugins.html>`_ is
        activated. (true by default)

    The elements passed as kwargs as passed as is to the Marker constructor.
    """

    default = dict()
    if hasattr(point, "name"):
        default["title"] = point.name

    kwargs = {**default, **kwargs}
    marker = Marker(location=(point.latitude, point.longitude), **kwargs)

    label = HTML()
    label.value = repr(point)
    marker.popup = label

    return marker 
Example #15
Source File: variable_inspector.py    From lantern with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        self._sc = Sidecar(title='Variables')
        get_ipython().user_ns_hidden['widgets'] = widgets
        get_ipython().user_ns_hidden['NamespaceMagics'] = NamespaceMagics

        self.closed = False
        self.namespace = NamespaceMagics()
        self.namespace.shell = get_ipython().kernel.shell

        self._box = widgets.Box()
        self._box.layout.overflow_y = 'scroll'
        self._table = widgets.HTML(value='Not hooked')
        self._box.children = [self._table]

        self._ipython = get_ipython()
        self._ipython.events.register('post_run_cell', self._fill) 
Example #16
Source File: configurator.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def __init__(self, paramlist, paramdefs, title=None):
        super(Configurator, self).__init__(layout=ipy.Layout(display='flex',
                                                             flex_flow='column',
                                                             align_self='flex-start',
                                                             align_items='stretch',
                                                             max_width='100%'))
        self.paramlist = paramlist
        self.paramdefs = paramdefs

        self.apply_button = ipy.Button(description='Apply')
        self.apply_button.on_click(self.apply_values)

        self.reset_button = ipy.Button(description='Reset')
        self.reset_button.on_click(self.reset_values)
        self.buttons = ipy.Box([self.reset_button, self.apply_button],
                               layout=ipy.Layout(align_self='center'))

        self.selectors = collections.OrderedDict([(p.name, ParamSelector(p)) for p in paramdefs])
        self.reset_values()

        title = utils.if_not_none(title, 'Configuration')
        self.title = ipy.HTML('<center><h4>%s</h4></center><hr>' % title,
                              align_self='center')

        self.currentconfig = ipy.Textarea(description='<i>Current params</i>',
                                          disabled=True,
                                          value=self._pretty_print_config(),
                                          layout=ipy.Layout(width='350px', min_height='300px',
                                                            max_height='500px',
                                                            display='flex', flex_flow='column'))
        self.middle = HBox([VBox(list(self.selectors.values())), self.currentconfig])
        self.children = [self.title, self.middle, self.buttons] 
Example #17
Source File: progress_bar.py    From threeML with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _setup(self):

        # Setup the widget, which is a bar between 0 and 100

        self._bar = FloatProgress(min=0, max=100)

        # Set explicitly the bar to 0

        self._bar.value = 0

        # Setup also an HTML label (which will contain the progress, the elapsed time and the foreseen
        # completion time)

        self._title_cell = HTML()

        if self._title is not None:

            self._title_cell.value = "%s : " % self._title

        self._label = HTML()
        self._vbox = VBox(children=[self._title_cell, self._label, self._bar])

        # Display everything

        display(self._vbox)

        self._animate(0) 
Example #18
Source File: simple.py    From CoolBox with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, browser, *args, **kwargs):
        chromosomes = browser.chrom_lengthes.keys()
        frame_widget = HTML()
        self.navigation_bar = NavigationBar(chromosomes, frame_widget)
        super().__init__(browser, frame_widget, *args, **kwargs) 
Example #19
Source File: trajectory_viewer.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def make_controls(self):
        self.playbutton = ipy.Play(value=0,
                                   min=0,
                                   max=self.traj.num_frames-1)

        self.slider = ipy.IntSlider(value_selects='framenum', value=0,
                                    description='Frame:', min=0, max=len(self.traj)-1,
                                    readout=False)
        self.readout = ipy.HTML(value='/%d' % (self.traj.num_frames - 1))
        self.annotation = ipy.HTML()

        traitlets.link((self.playbutton, 'value'), (self.slider, 'value'))
        traitlets.link((self.slider, 'value'), (self, 'current_frame'))
        return VBox((self.annotation,
                     HBox((self.playbutton, self.slider, self.readout)))) 
Example #20
Source File: my_iplot.py    From lddmm-ot with MIT License 5 votes vote down vote up
def my_iplot(figure_or_data, show_link=False, link_text='Export to plot.ly',
		  validate=True, image=None, filename='plot_image', image_width=800,
		  image_height=600) :
	plot_html, plotdivid, width, height = _plot_html(
		figure_or_data, show_link, link_text, validate,
		'100%', 525, global_requirejs=True)
	#display(HTML(plot_html))
	wid = widgets.HTML(
		value=plot_html,
		placeholder='Some HTML',
		description='Some HTML',
		disabled=False
	)
	
	return (wid, plotdivid) 
Example #21
Source File: images.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def __init__(self, client):
        self.client = client

        images = self._get_images()
        self.header = ipy.HTML(
                '<span class="nbv-table-header" style="width:950px"">Image status</span>',
                layout=ipy.Layout(align_items='flex-end'))
        super().__init__([self.header] + [DockerImageView(im, client) for im in sorted(images)]) 
Example #22
Source File: test_widget_box.py    From pySINDy with MIT License 5 votes vote down vote up
def test_construction_with_children(self):
        html = widgets.HTML('some html')
        slider = widgets.IntSlider()
        box = widgets.Box([html, slider])
        children_state = box.get_state()['children']
        assert children_state == [
            widgets.widget._widget_to_json(html, None),
            widgets.widget._widget_to_json(slider, None),
        ] 
Example #23
Source File: interfaces.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def __init__(self, xface):
        self.xface = xface

        if xface.is_installed():
            if xface.version_flag:
                v = xface.get_installed_version()
            else:
                v = INSTALLED
        else:
            v = MISSING

        self.maintext = ipy.HTML(
                ('<span class="nbv-table-row nbv-width-med nbv-monospace">'
                 '           {xface.name}</span> '
                 '<span class="nbv-table-row nbv-monospace nbv-width-sm">'
                 '                {localversion}</span> '
                 '<span class="nbv-table-row nbv-monospace nbv-width-sm">'
                 '                {xface.expectedversion}</span>'
                 '<span class="nbv-width-sm nbv-table-row">&nbsp;</span>'  # empty space
                 )
                    .format(xface=xface, localversion=v))

        self.selector = ipy.ToggleButtons(options=['in docker', 'locally'],
                                          value='in docker',
                                          button_style='info')
        self.selector.add_class('nbv-width-lg')
        self.selector.add_class("nbv-table-row")

        self.selector.observe(self._toggle, 'value')
        self.path = ipy.HTML(layout=ipy.Layout(width='150px', font_size='x-small'),
                              value=xface.path if xface.path is not None else '',)

        self.save_button = ipy.Button(description='Make default', layout=ipy.Layout(width='100px'))
        self.save_button.on_click(self.save_selection)
        self.save_button.add_class('nbv-table-row')

        children = [self.maintext, self.selector, self.save_button]

        super().__init__(children=children,
                         layout=ipy.Layout(width='100%', align_items='flex-end')) 
Example #24
Source File: jobs_widget.py    From qiskit-ibmq-provider with Apache License 2.0 5 votes vote down vote up
def jobs_tab(backend: Union[IBMQBackend, FakeBackend]) -> wid.HBox:
    """Construct a widget containing job information for an input backend.

    Args:
        backend: Input backend.

    Returns:
        An widget containing job summary.
    """
    title = wid.HTML('<h4>Click graph to display jobs</h4>')
    table = wid.HTML('', layout=wid.Layout(max_height='500px',
                                           height='500px',
                                           width='100%',
                                           overflow='hidden scroll',))

    sun_wid = _job_summary(backend)
    sun_wid._table = table
    sun_wid._title = title

    left = wid.Box(children=[sun_wid],
                   layout=wid.Layout(width='40%',
                                     overflow='hidden hidden'))

    right = wid.VBox(children=[title, table],
                     layout=wid.Layout(width='60%',
                                       overflow='hidden hidden'))

    out = wid.HBox(children=[left, right],
                   layout=wid.Layout(max_height='500px',
                                     margin='10px'))
    return out 
Example #25
Source File: jobs_widget.py    From qiskit-ibmq-provider with Apache License 2.0 5 votes vote down vote up
def _job_table_builder(sel_dict: dict) -> str:
    """Build the job table.

    Args:
        sel_dict: Dictionary containing information on jobs.

    Returns:
        HTML string for job table.
    """
    table_html = "<table>"
    table_html += """<style>
table {
    width: auto !important;
    font-family:IBM Plex Sans, Arial, sans-serif !important;
}

th, td {
    text-align: left !important;
    padding: 5px !important;
}

tr:nth-child(even) {background-color: #f6f6f6 !important;}
</style>"""

    table_html += "<tr><th>Date</th><th>Job ID / Name</th><th>Status</th></tr>"
    table_footer = "</table>"

    for jdata in sel_dict['jobs']:
        date_str = jdata[0].strftime("%H:%M %Z [%d/%b]")
        _temp_str = "<td>{time}</td><td>{jid}</td><td>{status}</td></tr>"
        # job has a name
        if jdata[2]:
            name = "{name} [{jid}]".format(name=jdata[2],
                                           jid=jdata[1])
        else:
            name = jdata[1]
        table_html += _temp_str.format(time=date_str,
                                       jid=name,
                                       status=jdata[3])
    table_html += table_footer
    return table_html 
Example #26
Source File: cad_display.py    From jupyter-cadquery with Apache License 2.0 5 votes vote down vote up
def __init__(self, width=230, height=300):
        self.html = HTML(
            value="",
            layout=Layout(width=("%dpx" % width), height=("%dpx" % height), border="solid 1px #ddd", overflow="scroll"))
        self.width = width
        self.height = height
        self.number = 0
        self.chunks = [] 
Example #27
Source File: ri_client.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def control_panel(ric = None):
    from ipywidgets import Button, HTML,HBox,Accordion
    from IPython.core.display import display
    def fmt(inp):
        if inp is None:
            return "--"
        elif type(inp) is float:
            return "{:.4g}".format(inp)
        else:
            return str(inp)

    if ric is None:
        ric = qkit.ric

    def update_instrument_params(b):
        insdict = ric.get_all_instrument_params()
        for ins in sorted(insdict):
            if not ins in b.accordions:
                b.accordions[ins] = Accordion()
            table = "<table style='line-height:180%'>"  # <tr style='font-weight:bold'><td> Parameter </td><td>Value</td></tr>
            for p in sorted(insdict[ins]):
                table += "<tr><td style='text-align:right;padding-right:10px'>" + str(p) + "</td><td>" + fmt(insdict[ins][p][0]) + insdict[ins][p][
                    1] + "</td></tr>"
            table += """</table>"""
            b.accordions[ins].children = [HTML(table)]
            b.accordions[ins].set_title(0, ins)
        for child in b.accordions.keys():
            if child not in insdict:
                del b.accordions[child]
        b.hbox.children = b.accordions.values()

    update_button = Button(description="Update")
    update_button.on_click(update_instrument_params)
    update_button.accordions = {}
    update_button.hbox = HBox()
    stop_button = Button(description="Stop measurement")
    stop_button.on_click(lambda b: qkit.ric.stop_measure())
    stop_button.button_style = "danger"
    update_instrument_params(update_button)
    display(HBox([update_button,stop_button]),update_button.hbox) 
Example #28
Source File: Progress_Bar.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def _update(self,param=""):
            if self._dummy:
                return
            display(Javascript("$('div#%s0').width('%i%%');" % (self.divid, 100*self.progr/self.max_it)))
            outp = "<table style='width:100%%;border:none'><tr style='border:none'><td style='border:none'>%s (%i/%i) </td><td style='border:none'>&#9992; %s    </td><td style='border:none'>&#128336;  %s   (estimated)</td><td style='border:none'>&#10010;  %s (elapsed) </td><td style='border:none'>&#9866;  %s (remaining)</td></tr></table>"%(param,     #"%s (%i/%i) &#10148;  ETA: %s &#10148; Time elapsed: %s" %(param,
                    self.progr,
                    self.max_it,
                    time.strftime('%Y-%m-%d (%a) %H:%M:%S', time.localtime(time.time() + float(time.time()-self.start_eta_time)/(self.progr-(0 if self.progr == 1 else 1)) * (self.max_it  - self.progr))), #ETA
                    hourformat(self.start_eta_time-self.starttime+float(time.time()-self.start_eta_time)/(self.progr-(0 if self.progr == 1 else 1)) * (self.max_it )), #estimated
                    hourformat(time.time()-self.starttime), #elapsed
                    hourformat(float(time.time()-self.start_eta_time)/(self.progr-(0 if self.progr == 1 else 1)) * (self.max_it  - self.progr))) #remaining
            if self.progr == 1:
                "this is a little academic, but the time between the first and the second iteration has usually a time lag."
                self.start_eta_time = time.time()
            #outp = "%s (%i/%i) &#10148;  ETA: %s &#10148; Time elapsed: %s"%(param,self.progr,self.max_it,time.ctime(time.time() + float(time.time()-self.starttime)/self.progr * (self.max_it - self.progr)),time.strftime('%H:%M:%S',time.gmtime(time.time()-self.starttime)))
            display(Javascript("document.getElementById('%s_text').innerHTML = \"%s\";"%(self.divid,outp)))

            if self.progr == self.max_it:   #end of progress bar
                #Turn the status bar into green
                #Delete all <div> containers
                outp = "%s (%i/%i) &#9992; %s    &#10010;  %s  "%(param,     #"%s (%i/%i) &#10148;  ETA: %s &#10148; Time elapsed: %s" %(param,
                    self.progr,
                    self.max_it,
                    time.strftime('%Y-%m-%d (%a) %H:%M:%S'),
                    hourformat(time.time()-self.starttime))
                display(Javascript("document.getElementById('%s_title').parentNode.remove();"%self.divid)) #title
                self.pb = HTML(
                """
                <div id="%st"> %s</div>
                <div id="%s" style="border: 1px solid black; width:900px;text-align: center; color:white; background-color:green;">%s
                </div>
                """ % (self.name, self.name, self.name, outp))
                display(self.pb) 
Example #29
Source File: Progress_Bar.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, max_it, name = 'Progress:',est_cycle_time=None,dummy=False):
            if debug:
                print("old style progress bar")
            #create HTML progress bar
            self._dummy = dummy
            if self._dummy:
                return
            self.divid = str(uuid.uuid4())
            self.max_it = max_it
            self.name = name
            self.progr = 0

            #delete existing progress bar with same name
            display(Javascript("if(document.getElementById('%st') !== null) document.getElementById('%st').parentNode.remove()"%(self.name,self.name)))
            #display(Javascript("if(document.getElementById('%s') !== null) document.getElementById('%s').remove()"%(self.name,self.name)))
               
            outp = "<table style='width:100%%;border:none'><tr style='border:none'><td style='border:none'>%s (%i/%i) </td><td style='border:none'>&#9992; %s    </td><td style='border:none'>&#128336;  %s   (estimated)</td><td style='border:none'>&#10010;  %s (elapsed) </td><td style='border:none'>&#9866;  %s (remaining)</td></tr></table>"%("",
                    0,
                    self.max_it,
                    "-?-" if est_cycle_time==None else time.strftime('%Y-%m-%d (%a) %H:%M:%S', time.localtime(time.time() + est_cycle_time * self.max_it )),
                    "--:--:--" if est_cycle_time==None else hourformat(est_cycle_time*self.max_it),
                    "00:00:00",
                    "--:--:--" if est_cycle_time==None else hourformat(est_cycle_time*self.max_it))
           
            self.pb = HTML(
            """
            <div id="%s_title"> %s</div>
            <div id="%s1" style="border: 1px solid black; width:900px">
              <div id="%s0" style="text-align: center; color:white; background-color:blue; width:0%%">&nbsp;</div>
            </div>
            <div id="%s_text">%s</div>
            """ % (self.divid,self.name,self.divid,self.divid,self.divid,outp))
            display(self.pb)
            display(Javascript("$('div#%s').width('%i%%')" % (self.divid, 100*self.progr/self.max_it)))
            sys.stdout.flush()
            self.starttime = time.time()
            self.start_eta_time = time.time() 
Example #30
Source File: Progress_Bar.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,max_it,name= 'Progress:',est_cycle_time=None,dummy=False):
            if debug:
                print("new style progress bar")
            self._dummy=dummy
            if self._dummy:
                return
            self.starttime = time.time()
            self.start_eta_time = self.starttime
            
            self.max_it = max_it
            self.name = name
            self.progr = 0
            
            #check for old (finished) progressbar with the same name
            for p in pb_list:
                if p[0] == self.name:
                    p[1].close()
                    p[2].close()

            self.pb = IntProgress(
                value=0,
                min=0,
                max=self.max_it,
                description=self.name,
                layout={"width": "95%"},
                )     
            
            self.pi = HTML(
                #value = "(0/%i) <br>&#9992; -?-    <br>&#128336;  --:--:--   (estimated)<br>&#10010;  00:00:00 (elapsed) <br>&#9866; --:--:--  (remaining)"% (self.max_it),
                value = "<table style='width:100%%'><tr><td>%s (%i/%i) </td><td>&#9992; %s    </td><td>&#128336;  %s   (estimated)</td><td>&#10010;  %s (elapsed) </td><td>&#9866;  %s (remaining)</td></tr></table>"%("",
                    0,
                    self.max_it,
                    "-?-" if est_cycle_time==None else time.strftime('%Y-%m-%d (%a) %H:%M:%S', time.localtime(time.time() + est_cycle_time * self.max_it )),
                    "--:--:--" if est_cycle_time==None else hourformat(est_cycle_time*self.max_it),
                    "00:00:00",
                    "--:--:--" if est_cycle_time==None else hourformat(est_cycle_time*self.max_it)),
                )

            display(self.pi)
            display(self.pb)