示例#1
0
def show_progress_bar(scan_job):
    from ipywidgets import FloatProgress, Label, VBox, HBox
    from IPython.display import display
    progress_bars = []
    scan_progress = FloatProgress(value=0.0, min=0.0, max=1.0, step=0.01, bar_style='info')
    scan_label = Label('Scan user repositories')
    box = VBox([
        Label('GitHub user "{}"'.format(scan_job.args[-1])),
        HBox([ scan_progress, scan_label ]),
        ])
    display(box)
    bar_styles = {'queued': 'info', 'started': 'info', 'deferred': 'warning', 'failed': 'danger', 'finished': 'success' }
    while True:
        scan_job.refresh()
        if 'finished' in scan_job.meta:
            percentage_complete = sum(scan_job.meta['finished'].values()) / max(sum(scan_job.meta['steps'].values()), 1)
            scan_progress.value = 1.0 if scan_job.status == 'finished' else max(0.01, percentage_complete) # the metadata is bogus once the job is finished
        scan_progress.bar_style = bar_styles[scan_job.status]
        if scan_job.status == 'finished':
            scan_progress.value = 1.0
            scan_progress.bar_style = bar_styles[scan_job.status]
            break
        elif scan_job.status == 'failed':
            scan_progress.value = max(0.01, scan_progress.value)
            break
        else:
            time.sleep(2)
def __plot_cell(description, bold=False):
  if bold:
    return Box([Label(description)],
               layout=Layout(border='solid 2px', width='100%'))
  else:
    return Box([Label(description)],
               layout=Layout(border='solid 1px', width='100%'))
 def q_box(q_title, q_in_latex):
     return VBox([
         Label(q_title, layout=Layout(width='auto')),
         Label(q_in_latex, layout=Layout(width='auto'))
     ],
                 layout=Layout(border='thin solid grey',
                               width=FillGapsBox.Q_AND_A_WIDTH))
示例#4
0
def generate_pdp_grid(models: list) -> GridBox:
    children = []

    # Row 1
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose a PDP method'))
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose one or more model(s)'))

    # Row 2
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        Select(description='Type',
               options=[elem.name for elem in PDPType],
               disabled=False))
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        SelectMultiple(description='Model(s)',
                       options=[model.name for model in models],
                       disabled=False))

    return GridBox(children=children,
                   layout=Layout(width='auto',
                                 grid_template_columns="50% 50%",
                                 grid_template_rows='auto',
                                 align_items='center',
                                 grid_gap='3px 3px'))
示例#5
0
def mk_cbk_ui(width='100%'):
    """ Create ipywidget and a callback to pass to `dc.load(progress_cbk=..)`

        :param width: Width of the UI, for example: '80%' '200px' '30em'
    """
    from ipywidgets import VBox, HBox, Label, Layout, IntProgress
    from timeit import default_timer as t_now

    pbar = IntProgress(min=0, max=100, value=0,
                       layout=Layout(width='100%'))
    lbl_right = Label("")
    lbl_left = Label("")
    info = HBox([lbl_left, lbl_right],
                layout=Layout(justify_content="space-between"))

    ui = VBox([info, HBox([pbar])],
              layout=Layout(width=width))

    t0 = t_now()

    def cbk(n, ntotal):
        elapsed = t_now() - t0

        pbar.max = ntotal
        pbar.value = n

        lbl_right.value = "{:d} of {:d}".format(n, ntotal)
        lbl_left.value = "FPS: {:.1f}".format(n/elapsed)

    return ui, cbk
示例#6
0
def generate_pdp_feature_selection_grid(models: list) -> GridBox:
    children = []

    # Row 1
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Feature 1 for ...'))
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='(optional) Feature 2 for ...'))

    for model in models:
        # Row 2 -> Row (2 + len(models))
        # if you change the description of this widget,
        # you have to also adjust it in the notebook function call.
        features = model.features_ohe.copy()
        features.insert(0, 'None')

        children.append(
            Select(description="... " + model.name,
                   options=model.features_ohe,
                   disabled=False))
        children.append(
            Select(description="... " + model.name,
                   options=features,
                   value='None',
                   disabled=False))

    return GridBox(children=children,
                   layout=Layout(width='auto',
                                 grid_template_columns="50% 50%",
                                 grid_template_rows='auto',
                                 align_items='center',
                                 grid_gap='3px 3px'))
 def make_header():
     return HBox(
         (Label("Use", layout=_checkbox_layout),
          Label("Page Search Name",
                layout=_label_layout), Label("Remove",
                                             layout=_remove_layout),
          Label("Search Result", layout=_additional_info_layout)))
示例#8
0
def divide_images_interface():
    
    parameters = []
    
    print('\x1b[1m'+"Input directory")
    input_dir = FileChooser('./datasets')
    display(input_dir)
    print('\x1b[1m'+"Output directory")
    output_dir = FileChooser('./datasets')
    display(output_dir)

    label_layout = Layout(width='100px',height='30px')

    width_divider = HBox([Label('Width divider:', layout=label_layout), widgets.IntText(
        value=2, description='', disabled=False)])
    display(width_divider)
    height_divider = HBox([Label('Height divider:', layout=label_layout), widgets.IntText(
        value=2, description='', disabled=False)])
    display(height_divider)
    
    parameters.append(input_dir)
    parameters.append(output_dir)
    parameters.append(width_divider)
    parameters.append(height_divider)
    return parameters
示例#9
0
 def display(self):
     return VBox([HBox([self.cam_out, self.ref_img_out]),
                  HBox([Label('rotate  '), self.rot]),
                  HBox([Label('crop top'), self.ct]),
                  HBox([Label('crop left'), self.cl]),
                  HBox([Label('size'), self.sz]),
                  HBox([self.prev, self.next])])
示例#10
0
    def __init__(self):
        super(PassGenGUI, self).__init__(description='Password container')
        self.model = PassGen()
        self.layout.width = '100%'
        self.layout.align_items = 'flex-start'
        style = {'description_width': 'initial'}
        self._length = IntSlider(min=8, max=20,
                                 description='Password Length',
                                 style=style)
        link((self._length, 'value'), (self.model, 'password_length'))

        self._top_label = Label(value='Generated password:'******' ')
        self._password_text.layout.margin = '0 0 0 20px'
        link((self._password_text, 'value'), (self.model, 'password'))

        self.children = [self._top_label,
                         self._password_text,
                         self._length, self._special,
                         self._numbers]
示例#11
0
def Test():
    print("Run test file...")

    from ipywidgets import HBox, Label

    #    KernelSizeSlider = FloatSlider(min = 0, max = 10, \
    #                     value = 1)
    #    description = Label("Kernelsize (0 - auto)")
    #
    #    HBox((description, KernelSizeSlider))

    label = Label('A really long description')
    KernelSizeSlider = FloatSlider(min=0, max=10, value=1)
    HBox([label, KernelSizeSlider])

    #    frame_slider = IntSlider(min = 1, max = 10, description = "Frame")

    def printX(x):
        print(x)

#    interact(printX, x = frame_slider)

    interact(printX, x=KernelSizeSlider)

    label = Label('A really long description')
    my_slider = IntSlider()
    HBox([label, my_slider])

    print("... Test file finished")
 def make_header():
     return HBox((
         Label("Use", layout=_checkbox_layout),
         Label("Name", layout=_editable_label_layout),
         Label("Text", layout=_editable_text_layout),
         Label("Remove", layout=_remove_layout),
     ))
示例#13
0
    def __get_widgets(self, chromosomes, browser, frame=None):
        if frame is None:
            frame = HTML()
        tracks = self.__get_tracks_name(browser)
        widgets = OrderedDict([
            ("chromosomes_list", Dropdown(options=chromosomes)),
            ("left_button", Button(icon="arrow-left")),
            ("right_button", Button(icon="arrow-right")),
            ("zoom_out_button", Button(icon="search-minus")),
            ("zoom_in_button", Button(icon="search-plus")),
            ("range_textbox", Text(placeholder="genome range like: 'chr1:10000-20000'")),
            ("go_button", Button(description="Go")),

            ("range_slider", IntRangeSlider(continuous_update=False, readout=False, layout=Layout(width='90%'))),
            ("range_min_label", Label("", layout=Layout(width='2%'))),
            ("range_max_label", Label("", layout=Layout(width='20%'))),

            ("auto_check_box", Checkbox(value=True, description="Auto Range",
                                        layout=Layout(width='120px'),
                                        style={'description_width': 'initial'})),
            ("track_min_val_float_text",
             FloatText(value=0.0001, description="Track's min value:", step=0.5, disabled=True,
                       layout=Layout(width='30%'),
                       style={'description_width': 'initial'})),
            ("track_max_val_float_text", FloatText(value=10, description="Track's max value:", step=0.5, disabled=True,
                                                   layout=Layout(width='30%'),
                                                   style={'description_width': 'initial'})),
            ("track_dropdown", Dropdown(options=[ALL_BW_MARK] + tracks,
                                        value=ALL_BW_MARK,
                                        description="Select track",
                                        disabled=True,
                                        )),
            ("frame", frame)
        ])
        return widgets
    def __init__(self, view):
        layout = Layout(width="initial")
        self._step_backward = Button(tooltip="Step backward",
                                     icon="step-backward",
                                     layout=layout)
        self._step_forward = Button(tooltip="Step forward",
                                    icon="step-forward",
                                    layout=layout)
        self._begin = Button(tooltip="Begin",
                             icon="fast-backward",
                             layout=layout)
        self._end = Button(tooltip="End", icon="fast-forward", layout=layout)
        self._backward = Button(tooltip="Play backward",
                                icon="backward",
                                layout=layout)
        self._play = Button(tooltip="Play", icon="play", layout=layout)
        self._pause = Button(tooltip="Pause", icon="pause", layout=layout)
        self._frame_label = Label("frame: ")
        self._frame = Label("")
        self._speed_label = Label("speed: ")
        self._speed_slider = IntSlider(0, 0, 10, 1)
        player_controls = HBox([
            self._begin, self._backward, self._step_backward, self._pause,
            self._play, self._step_forward, self._end, self._frame_label,
            self._frame, self._speed_label, self._speed_slider
        ])
        VBox.__init__(self, [view, player_controls])

        self._model = PlayerModel(view, self)
        self._controller = PlayerThread(self._model, self).start()
示例#15
0
def sdof_interact():
    """Create interactive plots of characteristics of SDOF system."""
    m_slide = widgets.FloatSlider(min=1e-5, max=20, step=.1, value=5,
                                  continuous_update=False)
    k_slide = FloatSlider(min=1e-5, max=1000, step=1., value=100,
                          continuous_update=False)
    c_slide = FloatSlider(min=-1, max=200, step=.1, value=2,
                          continuous_update=False)

    m_label = widgets.Label('Mass')
    c_label = Label('Damping')
    k_label = Label('Stiffness')

    m_slider = widgets.VBox([m_label, m_slide])
    c_slider = widgets.VBox([c_label, c_slide])
    k_slider = widgets.VBox([k_label, k_slide])

    ui = widgets.HBox([m_slider, c_slider, k_slider])

    out = widgets.interactive_output(plot_sdof_resp,
                                     {'m': m_slide,
                                      'c': c_slide, 'k': k_slide})

    sdof_responses = widgets.VBox([ui, out])
    return sdof_responses
示例#16
0
文件: widget.py 项目: snr2718/veritas
 def __init__(self):
     self.t1 = Label('', layout=Layout(width='10%', height='10%'))
     self.f = IntProgress(min=0, max=100)
     self.t2 = Label('', layout=Layout(width='10%', height='10%'))
     self.t3 = Label('loss:- acc:-',
                     layout=Layout(width='30%', height='10%'))
     self.hb = HBox([self.t1, self.f, self.t2, self.t3])
示例#17
0
 def configure_controllers(self):
     from ipywidgets import (interactive, Label, VBox, FloatSlider,
                             IntSlider, Checkbox)
     # continuous update
     self.continuous_update_button = Checkbox(
         value=False,
         description='Continuous update',
         disabled=False,
         indent=False,
     )
     self.controllers["continuous_update"] = interactive(
         self.set_continuous_update, value=self.continuous_update_button)
     # subplot
     number_of_plots = len(self.plotter.renderers)
     if number_of_plots > 1:
         self.sliders["subplot"] = IntSlider(value=number_of_plots - 1,
                                             min=0,
                                             max=number_of_plots - 1,
                                             step=1,
                                             continuous_update=False)
         self.controllers["subplot"] = VBox([
             Label(value='Select the subplot'),
             interactive(
                 self.set_subplot,
                 index=self.sliders["subplot"],
             )
         ])
     # azimuth
     default_azimuth = self.plotter.renderer._azimuth
     self.sliders["azimuth"] = FloatSlider(value=default_azimuth,
                                           min=-180.,
                                           max=180.,
                                           step=10.,
                                           continuous_update=False)
     # elevation
     default_elevation = self.plotter.renderer._elevation
     self.sliders["elevation"] = FloatSlider(value=default_elevation,
                                             min=-180.,
                                             max=180.,
                                             step=10.,
                                             continuous_update=False)
     # distance
     eps = 1e-5
     default_distance = self.plotter.renderer._distance
     self.sliders["distance"] = FloatSlider(value=default_distance,
                                            min=eps,
                                            max=2. * default_distance - eps,
                                            step=default_distance / 10.,
                                            continuous_update=False)
     # camera
     self.controllers["camera"] = VBox([
         Label(value='Camera settings'),
         interactive(
             self.set_camera,
             azimuth=self.sliders["azimuth"],
             elevation=self.sliders["elevation"],
             distance=self.sliders["distance"],
         )
     ])
    def _make_table(self):
        # Global styles
        styles = [
            dict(selector="tr", props=[
                ("height", self.row_height),
                ("vertical-align", "middle"),
                ("text-align", "center"),
                ("width", self.column_width),
            ]),
            dict(selector="td", props=[
                ("padding-bottom", self.table_cell_paddings),
                ("padding-top", self.table_cell_paddings),
                ("vertical-align", "middle"),
                ("text-align", "center"),
                ("width", self.column_width),
            ]),
            dict(selector="th", props=[
                ("padding-bottom", self.table_cell_paddings),
                ("padding-top", self.table_cell_paddings),
                ("vertical-align", "middle"),
                ("text-align", "center"),
                ("width", self.column_width),
            ]),
        ]

        # Make styler for DataFrame
        styler = self.df.style.set_table_attributes('class="table"') \
            .set_table_styles(styles) \
            .apply(self.selection_colorize, axis=None)

        # Render HTML table from DataFrame
        html = styler.render()

        # Build visual components
        v_row_buttons = VBox(
            [Label(description='', layout=dict(height=self.row_height,
                                               width=self.row_button_width,
                                               padding=self.button_padding)),
             *self.row_button_list],
        )
        v_bottom = HBox([
            v_row_buttons,
            HTML(html)
        ])
        v_col_buttons = HBox(
            [Label(description='', layout=dict(height=self.row_height,
                                               width=self.row_button_width,
                                               padding=self.button_padding)),
             Label(description='', layout=dict(height=self.row_height,
                                               width=self.column_width,
                                               padding=self.button_padding)),
             *self.column_button_list],
        )

        # Make dashboard
        self._table = VBox(
            (v_col_buttons, v_bottom,),
            layout=dict(width="{}pt".format(self.table_width))
        )
示例#19
0
    def __init__(self, dataframe, column):
        self.dataframe = dataframe
        self.column = column

        # Record choices for processing steps
        self.categorical_value = None
        self.null_replacement_choice = None
        self.preprocess_choice = None
        self.show_original_figure = False
        self.show_new_figure = False

        ## Description section ##

        # Place datatype and null_percentage information
        self.colname_widget = Label(
            value=self.column.name,
            layout=Layout(width='15%',
                          height='25px'))  ###### adjust to make it look nicer
        self.dtype_widget = Label(layout=DESCRIBE_LAYOUT)
        self.null_percentage_widget = Label(layout=DESCRIBE_LAYOUT)
        self.distinct_widget = Label(layout=DESCRIBE_LAYOUT)
        self.categorical_dropdown = Dropdown(
            options=['Categorical', "Discrete", 'Continuous', 'Null'],
            value='Continuous',
            disabled=False,
            layout=CLICK_LAYOUT)

        # Place distribution figures
        self.fig_old_widget_wrapper = VBox([])
        self.fig_new_widget_wrapper = VBox([])

        # Place original statistcs (mean, median etc)
        original_description = describe_column(self.column)
        self.original_statistics = HBox([
            Label(value=original_description['minimum'], layout=STATS_LAYOUT),
            Label(value=original_description['maximum'], layout=STATS_LAYOUT),
            Label(value=original_description['median'], layout=STATS_LAYOUT),
            Label(value=original_description['mean'], layout=STATS_LAYOUT),
            Label(value=original_description['std'], layout=STATS_LAYOUT)
        ])

        # Place new statistics
        (self.minimum_widget, self.maximum_widget, self.median_widget,
         self.mean_widget,
         self.std_widget) = [Label(layout=STATS_LAYOUT) for i in range(5)]

        # Define preprocessing dropdown
        self.knn_checkbox_widget = HBox([])
        self.null_replacement_dropdown = Dropdown(
            options=['None', 'Mean', 'Median', "KNN"],
            value='None',
            disabled=False if self.column.isnull().sum() > 0 else True,
            layout=CLICK_LAYOUT)

        self.preprocess_dropdown = Dropdown(
            options=['None', 'Scale', 'Normalize'],
            value='None',
            disabled=False if self.column.isnull().sum() == 0 else True,
            layout=CLICK_LAYOUT)
示例#20
0
    def initialize(self, options: dict):

        if "parcelSource" not in options:
            return

        # keep only the relevant information
        ps_opt = options["parcelSource"]

        if "type" not in ps_opt:
            return

        source_opt = [a[1] for a in self.sources.options]

        if ps_opt["type"] in source_opt:

            self.sources.value = ps_opt["type"]
            view_options = VBox()

            info_txt = Label("From Text File only")
            info_txt_rest = Label("From Text File and RESTFul")
            info_shape = Label("From Shape File")
            info_json = Label("From GeoJSON File")

            if self.sources.value == 'txt':
                source = source_from_txt()
                source.initialize(ps_opt)
                view_options.children = [info_txt, source]
            elif self.sources.value == 'txt_rest':
                source = source_from_txt_rest()
                source.initialize(ps_opt)
                view_options.children = [info_txt_rest, source]
            elif self.sources.value == 'shape':
                source = source_from_shape()
                source.initialize(ps_opt)
                view_options.children = [info_shape, source]
            elif self.sources.value == 'json':
                source = source_from_shape('json')
                source.initialize(ps_opt)
                view_options.children = [info_json, source]

            self.children = [
                self.sources_box, view_options, self.wb_save, self.whb_load
            ]

        def on_source_change(change):
            view_options.children = []
            if self.sources.value == 'txt':
                view_options.children = [info_txt, source_from_txt()]
            elif self.sources.value == 'txt_rest':
                view_options.children = [info_txt_rest, source_from_txt_rest()]
            elif self.sources.value == 'shape':
                view_options.children = [info_shape, source_from_shape()]
            elif self.sources.value == 'json':
                view_options.children = [info_json, source_from_shape('json')]

        self.sources.observe(on_source_change, 'value')
示例#21
0
def generate_local_interpretation_grid(models: list) -> GridBox:
    children = []

    # Row 1
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose an interpretation method'))
    children.append(
        Label(layout=Layout(width='auto', height='auto'),
              value='Choose one or more model(s)'))

    # Row 2
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        Select(description='Type',
               options=[elem.name for elem in LocalInterpreterType],
               disabled=False))
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        SelectMultiple(description='Model(s)',
                       options=[model.name for model in models],
                       disabled=False))

    # Row 3
    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        RadioButtons(options=[elem.name for elem in ExampleType],
                     layout={'width': 'max-content'},
                     description='Example(s) type:',
                     disabled=False))

    # if you change the description of this widget,
    # you have to also adjust it in the notebook function call.
    children.append(
        IntSlider(
            value=1,
            min=1,
            max=10,
            step=1,
            description='Number of examples:',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='d',
        ))

    return GridBox(children=children,
                   layout=Layout(width='auto',
                                 grid_template_columns="50% 50%",
                                 grid_template_rows='auto',
                                 align_items='center',
                                 grid_gap='3px 3px'))
示例#22
0
def display_buttons(row,
                    create_mask_callback,
                    mask_file_name,
                    sentiments=['"negative"', '"positive"', '"neutral"']):
    global mask_df
    sentiment = row.sentiment.tolist()[0]
    words = row.words.tolist()[0]
    sentiment_text = Label(value=sentiment)
    sentiment_wrapper = HBox([sentiment_text],
                             layout=Layout(margin='15px',
                                           justify_content='center'))
    display(sentiment_wrapper)
    buttons = []
    for word in words:
        layout = Layout(width='auto', height='auto', margin='4px')
        button = Button(description=word, layout=layout)

        def on_click(b):
            if b.style.button_color is not None:
                b.style.button_color = None
            else:
                b.style.button_color = '#66CC69'

        button.on_click(on_click)
        buttons.append(button)
    wrapper = HBox(buttons,
                   layout=Layout(flex_flow='row wrap',
                                 justify_content='center'))
    display(wrapper)
    create_button = Button(description='Create Mask',
                           layout=Layout(width='auto',
                                         height='auto',
                                         padding='2px 15px 2px 15px'))
    create_button.style.button_color = '#5EACF9'

    def callback(b):
        mask = []
        for button in buttons:
            mask.append(button.style.button_color is not None)
        clear_output()
        create_mask_callback(row, mask, mask_file_name)

    create_button.on_click(callback)
    create_wrapper = HBox([create_button],
                          layout=Layout(margin='20px',
                                        justify_content='center'))
    display(create_wrapper)
    done_texts = []
    for sent in sentiments:
        new_df = mask_df[mask_df.sentiment == sent]
        done_texts.append(
            Label(value="%s: %s" % (sent, str(len(new_df))),
                  layout=Layout(margin='20px')))
    done_wrapper = HBox(done_texts)
    display(done_wrapper)
示例#23
0
    def _build_procesing_panel(self, processing_info):
        """
        Build up the processing panel for filtering data.

        Parameters
        ----------
        processing_info: dict
            Processing information that contains name and parameters.

        Returns
        -------

        """
        self._processing_parameters = processing_info

        parameter_list = []

        # Add the title to the top of the processing area.
        title = Label('Process: ' + processing_info['name'], style={'font-weight': 'bold', 'font-size': '1.5em'})
        title.layout.width = '100%'

        parameter_list.append(title)

        # Add all the parameters
        for parameter in self._processing_parameters.get('parameters'):
            if isinstance(parameter[1], (int, float, str, list, tuple)):

                label = Label(parameter[0])
                label.layout.width = '50%'

                # TODO: This needs to be cleaned up / generalized.
                if isinstance(parameter[1], int):
                    ft = IntText(value=parameter[1])
                elif isinstance(parameter[1], float):
                    ft = FloatText(value=parameter[1])
                else:
                    ft = Text(value=str(parameter[1]))
                ft.layout.width = '50%'

                box = HBox((label, ft ))
                parameter_list.append(box)

        # Add the Cancel and Process buttons
        cancel_button = Button(description='Cancel', value='Cancel')
        cancel_button.button_style = 'danger'
        cancel_button.on_click(self._processing_cancel_button_callback)

        process_button = Button(description='Process', value='Process')
        process_button.button_style = 'success'
        process_button.on_click(self._processing_process_button_callback)

        parameter_list.append(HBox((process_button, cancel_button)))

        # Add them all to the VBox
        self._processing_vbox.children = tuple(parameter_list)
示例#24
0
    def __init__(self,
                 displayer: Callable[[Figure, Selection], Callable[[int, Any],
                                                                   None]],
                 resolution: int = None,
                 fig_kw={},
                 children=(),
                 toolbar=(),
                 **ka):
        from ipywidgets import BoundedIntText, IntText, Label

        def select(bounds_):
            i = self.level + 1
            w_level.active = False
            w_level.max = i
            w_level.value = i
            setlevel(i, (resolution, bounds_))
            w_level.active = True

        def show_running(b):
            w_running.icon = 'pause' if b else 'play'

        def show_precision(p):
            w_precision.value = p

        self.select = select
        self.show_precision = show_precision
        self.show_running = show_running

        def setlevel(i, new=None):
            self.level = i
            w_precision.value = display(i, new)
            board.canvas.draw_idle()

        # global design and widget definitions
        w_running = SimpleButton(icon='')
        w_level = BoundedIntText(0,
                                 min=0,
                                 max=0,
                                 layout=dict(width='1.6cm', padding='0cm'))
        w_level.active = True
        w_precision = IntText(0,
                              disabled=True,
                              layout=dict(width='1.6cm', padding='0cm'))
        super().__init__(children,
                         toolbar=(w_running, Label('level:'), w_level,
                                  Label('precision:'), w_precision, *toolbar))
        self.board = board = self.mpl_figure(**fig_kw)
        display = displayer(board, select)
        # callbacks
        w_running.on_click(lambda b: self.setrunning())
        w_level.observe(
            (lambda c: (setlevel(c.new) if w_level.active else None)), 'value')
        super(app, self).__init__(display, **ka)
示例#25
0
 def dias_set(d):
     if d in ['CREODIAS', 'EOSC']:
         from cbm.ipycbm.ipy_ext.dias import creodias
         dias_box.children = [creodias.main()]
     elif d in ['SOBLOO']:
         from cbm.ipycbm.ipy_ext.dias import sobloo
         dias_box.children = [sobloo.main()]
     elif d in ['MUNDI']:
         dias_box.children = [Label('This provider is not supported yet')]
     elif d in ['ONDA']:
         dias_box.children = [Label('This provider is not supported yet')]
     elif d in ['WEKEO']:
         dias_box.children = [Label('This provider is not supported yet')]
示例#26
0
    def build_widget(self):
        widget = []
        
        # dropdown for system selection
        # checkbox for showing/hiding unmodified data
        self.select = Dropdown(options=self.df_all.index.values,description='System:')
        
        # slider array for trimming datapoints
        vbox1 = [HBox([Label('Trim-Lo')],layout={'justify_content':'center'}) ]
        vbox2 = [HBox([Label('Trim-Hi')],layout={'justify_content':'center'}) ]
        self.apply_bg = Checkbox(value=False,description='Subtract BG?')
        vbox3 = [HBox([self.apply_bg],layout={'justify_content':'center'}) ]
        for config in self.df_all.columns:
            sl1 = IntSlider(min=0,max=25,value=7,description='{}'.format(config))
            sl1.style.handle_color = self.df_colors.loc[config]
            vbox1.append(sl1)
            
            sl2 = IntSlider(min=0,max=100,value=15,description='{}'.format(config))
            sl2.style.handle_color = self.df_colors.loc[config]
            vbox2.append(sl2)

            # sl3 = FloatSlider(min=0.001,max=1,value=0.5,description='{}'.format(config))
            sl3 = FloatLogSlider(min=-3,max=0,value=0.5,description='{}'.format(config))
            sl3.style.handle_color = self.df_colors.loc[config]
            vbox3.append(sl3)
        widget.append(HBox([VBox(vbox1), VBox(vbox2)]))
        
        ## store slider objects in dataframe
        self.df_slider = pd.DataFrame(np.transpose([vbox1[1:],vbox2[1:],vbox3[1:]]),index=self.df_all.columns,columns=['Lo','Hi','bgLoc'])
        # self.df_bgslider = pd.DataFrame(np.transpose(vbox3[1:]),index=self.df_all.columns,columns=['Lo','Hi'])
        
        # dropdown for shift-configuration selection
        ops = ['None']
        ops += [str(i) for i in self.df_all.columns.values]
        self.shift_config = Dropdown(options=ops,description='Shift-To:')
        self.shift_factors_out = Output()
        self.show_original = Checkbox(value=True,description='Show Original Data')
        vbox4 = [VBox([self.shift_config,self.show_original]),self.shift_factors_out]

        # widget.append(HBox([VBox(vbox3),VBox(vbox4)]))
        self.bg_out = Output()
        widget.append(HBox([VBox(vbox3),self.bg_out]))
        widget.append(HBox(vbox4))
        
        tabs = Tab(widget)
        tabs.set_title(0,'Data Trimming')
        tabs.set_title(1,'Subtract BG')
        tabs.set_title(2,'Curve Shift')

        self.debug_out = Output()
        return VBox([self.select,tabs,self.debug_out])
示例#27
0
    def __init__(self, omx, shapefile):

        if OMX is None:
            raise ModuleNotFoundError('larch.omx')
        if isinstance(omx, str):
            omx = OMX(omx, mode='r')
        self.omx = omx

        self.omx_taz_ids_rows = pd.RangeIndex(1, self.omx.shape[0]+1)
        self.omx_taz_ids_cols = pd.RangeIndex(1, self.omx.shape[1]+1)

        self.shapefile = shapefile

        self.fig = shapefile.plotly_choropleth(show_colorbar=True)

        self.matrix_dropdown = Dropdown(
            # label='Matrix Table',
            options=list(self.omx.data._v_children),
        )

        self.otaz_dropdown = Dropdown(
            options=list(self.omx_taz_ids_rows),
        )

        self.panel = VBox([
            Label(f"File: {self.omx.filename}"),
            HTML(
                value="<hr>",
            ),
            Label("Matrix Table"),
            self.matrix_dropdown,
            Label("Origin TAZ"),
            self.otaz_dropdown,
        ])

        self.matrix_dropdown.observe(self._change_matrix, names='value')
        self.otaz_dropdown.observe(self._change_otaz, names='value')
        self.fig.data[0].on_click(self._set_otaz_by_click)

        self.matrix_name = None
        self.otaz = None

        self.change_view(
            matrix_name=self.matrix_dropdown.value,
            otaz=self.otaz_dropdown.value,
        )

        super().__init__(children=(
            self.fig,
            self.panel,
        ))
示例#28
0
    def create_h_widgets(self):
        """"Create the widget table"""
        dataframe = self.dataframe

        colname_title = Label(value='NAME',
                              layout=Layout(width='15%', height='25px'))
        dtype_title = Label(value='TYPE', layout=DESCRIBE_LAYOUT)
        null_percentage_title = Label(value='NULL', layout=DESCRIBE_LAYOUT)
        distinct_title = Label(value='DISTINCT', layout=DESCRIBE_LAYOUT)

        categorical_title = Label(value='IS CATEGORICAL', layout=CLICK_LAYOUT)
        algorithm_choice_title = Label(value='NULL REPLACE',
                                       layout=CLICK_LAYOUT)
        preprocess_title = Label(value='PREPROCESS', layout=CLICK_LAYOUT)
        show_title = Label(value='SHOW', layout=CLICK_LAYOUT)
        header_hbox = HBox([
            colname_title, dtype_title, null_percentage_title, distinct_title,
            categorical_title, algorithm_choice_title, preprocess_title,
            show_title
        ])

        # create each widget row
        self.rows = []
        for colname in self.colnames:
            row = WidgetRow(self.dataframe, self.dataframe[colname])
            self.rows.append(row)
        content_rows = [row.get_h_widget() for row in self.rows]

        return [header_hbox] + content_rows
 def __init__(self, name: str, size: int, increments: int = 0):
     print(name, flush=True)
     from ipywidgets import HBox, IntProgress, Label
     from IPython.display import display, clear_output
     self.size = size
     self._percent = Label("")
     self._bar = IntProgress(min=0, max=size)
     self._rate = Label("")
     self._duration = Label("")
     ui = HBox([
         self._percent, self._bar,
         Label(sizeof_fmt(size)), self._rate, self._duration
     ])
     display(ui)
     logger.debug(f"'{type(self)}' displayed IPython widget '{ui}'.")
示例#30
0
def run_update(command, widget=None, silent=False):
    out = subprocess.Popen(command,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)
    stdout, stderr = out.communicate()

    display(Label(stdout.decode()))
    if stderr is not None:
        display(Label(stderr))
    if 'Aborting' in stdout.decode():
        text = ("Warning! The above files will be overwritten.\n",
                "If you have important changes,",
                "be sure to make a backup of them first.")
        warning = Label(' '.join(text))
        display(VBox([warning, widget]))