Example #1
0
    def displayPrepare(self, env):
        '''
        准备数据
        :param env: 当前环境
        :return: 
        '''
        self.env = env
        if not self.cf.isReady():
            print(Fore.RED + '配置项尚未初始化!')
        else:
            self.boxParams = VBox()
            self.boxParams.layout = Layout(flex_flow = 'column', display = 'flex')
            self.packageWidgets()
            display(self.boxParams)

            self.gdParamValue = qgrid.show_grid(pd.DataFrame([]),
                                                grid_options = {'filterable': False, 'autoHeight': True,
                                                                'editable': False})
            self.gdParamValue.layout = Layout(width = '90%')
            self.packageParams()
            self.txtBodyValue = Textarea(value = self.data if self.data is not None else '')
            self.txtBodyValue.layout = Layout(width = '90%', height = '200px', margin = '6px 2px 2px 2px')

            boxRequest = Box([
                VBox([Label(value = '请求参数值:'), self.gdParamValue],
                     layout = Layout(flex = '1 1 0%', width = 'auto')),
                VBox([Label(value = '请求体参数值:'), self.txtBodyValue],
                     layout = Layout(flex = '1 1 0%', width = 'auto'))],
                layout = Layout(flex_flow = 'row', display = 'flex'))
            acRef = Accordion(children = [boxRequest])
            acRef.set_title(0, '输入参考')
            toggleRefDisplay(acRef)
            display(acRef)
            ref.append(acRef)
    def __init__(self):
        plt.close("all")
        self.backend = TextInputLoop(use_widget=True)
        self.highlighter = SentimentHighlighter(self.backend)
        self.backend.add_interface(self.highlighter)
        self.backend.start()

        self.cwd_label = Label(
            value="Working directory: {}".format(Path.cwd()),
            layout=dict(margin="2px 0px 0px 20px"),
        )
        self.save_path = Text(
            value=str(Path("saved_html.html")),
            description='Save path:',
            disabled=False,
            layout=dict(width="50%"),
        )
        self.save_button = Button(
            value=False,
            description='Save to HTML',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='',
            icon='',
            layout=Layout(width='18%', margin="2px 0px 0px 20px"),
        )
        self.progress_label = Label(
            value="",
            layout=dict(margin="2px 0px 0px 20px"),
        )

        self.full_contrast = Checkbox(value=False,
                                      description='Full Contrast',
                                      disabled=False)
        self.do_highlighting = Checkbox(value=True,
                                        description='Do Highlighting',
                                        disabled=False)

        box1 = HBox(
            (self.do_highlighting, self.full_contrast),
            layout=Layout(align_content="flex-start"),
        )

        box2 = HBox(
            (self.save_path, self.save_button),
            layout=Layout(align_content="flex-start"),
        )

        self.storage_dashboard = VBox(
            (box1, self.cwd_label, box2, self.progress_label))

        # Set observers
        self.save_button.on_click(self._save)
        self.full_contrast.observe(self._special_options)
        self.do_highlighting.observe(self._special_options)

        # noinspection PyTypeChecker
        display(self.storage_dashboard)
Example #3
0
    def _update_clusters(self) -> None:
        """
        Updates the clusters currently being displayed.
        """
        line = HBox(
            children=[Label("-" * 186, layout=Layout(margin="0 0 0 18px"))])
        self._sel_all.value = False

        cluster_page = self._clusterer.get_page(
            self._page_pos, self._page_pos + self._page_size)

        label_layout = Layout(height="22px", width="360px")
        box_children = [line]
        for idx, cluster in enumerate(cluster_page):
            labels = []
            for cluster_val, cnt in cluster:
                if cnt > 1:
                    cluster_val += f" ({cnt} rows)"
                labels.append(Label(cluster_val, layout=label_layout))

            totals_vals = sum(cnt for _, cnt in cluster)
            distinct_vals = len(cluster)

            self._reprs[idx].value = cluster[0][0]
            self._checks[idx].value = False
            box_children.append(
                HBox([
                    Label(str(distinct_vals),
                          layout=Layout(width="60px", margin="0 0 0 60px")),
                    Label(str(totals_vals),
                          layout=Layout(width="60px", margin="0 0 0 50px")),
                    VBox(children=labels, layout=Layout(margin="0 0 0 80px")),
                    self._checks[idx],
                    self._reprs[idx],
                ]))

            box_children.append(line)

        # no clusters to display
        if len(cluster_page) == 0:
            box_children = [
                Label(
                    "No clusters, try a different clustering method",
                    layout=Layout(margin="170px 0 0 360px"),
                )
            ]

        self._cluster_vbox.children = box_children
        cluster_and_next_prev = [self._cluster_vbox]
        self._add_next_prev_button_row(cluster_and_next_prev)
        self._cluster_and_next_prev.children = cluster_and_next_prev
Example #4
0
def columns_accordion_widget(df):
    accordion = Accordion(selected_index=None, layout=layout)
    children = []
    for i, colname in enumerate(df.columns):
        accordion.set_title(i, colname)

        # build each column dummy output (accordion children)
        child_widget = Label()  # column_output_widget(df, colname)
        children.append(child_widget)

    # set accordion children
    accordion.children = children

    # create accordion handler
    flag = {}

    def accordion_handler(change):
        children = list(change.owner.children)
        for i in range(len(children)):
            if change.new == i and (not flag.get(i, 0)):
                # build child widget
                colname = change.owner._titles[str(i)]
                column_output_widget(df,
                                     colname,
                                     index=i,
                                     children=children,
                                     parent=change.owner)
                flag[i] = 1
                break
        return

    # set observer
    accordion.observe(accordion_handler)

    return accordion
Example #5
0
    def __init__(self,
                 nrows,
                 ncols,
                 make_widget,
                 description=u"",
                 transform=None):
        """
        Create a :class:`Grid` widget.

        INPUT:

        - ``nrows``, ``ncols`` -- number of rows and columns in the grid

        - ``make_widget`` -- a function of two arguments ``(i,j)``
          returning the widget to be placed at position ``(i,j)``.

        - ``description`` -- an optional label.

        - ``transform`` -- an optional transformation, see :class:`TransformWidget`.

        EXAMPLES::

            sage: from sage.repl.ipython_kernel.widgets import Grid, EvalText
            sage: w = Grid(2, 2, lambda i,j: EvalText(str(j+4*i)),
            ....:         description="2x2 matrix", transform=matrix)
            sage: w
            Grid(value=[[0, 1], [4, 5]], children=(Label(value=u'2x2 matrix'), VBox(children=(EvalText(value=u'0'), EvalText(value=u'4'))), VBox(children=(EvalText(value=u'1'), EvalText(value=u'5')))))
            sage: w.get_interact_value()
            [0 1]
            [4 5]

        TESTS::

            sage: w = Grid(0, 1, lambda i,j: EvalText())
            Traceback (most recent call last):
            ...
            ValueError: Grid requires a positive number of rows and columns
        """
        if nrows < 1 or ncols < 1:
            raise ValueError(
                "Grid requires a positive number of rows and columns")
        super(Grid, self).__init__(transform=transform)

        label = Label(description)
        link((label, "value"), (self, "description"))

        self.cols = []
        for j in range(ncols):
            col = VBox()
            widgets = []
            for i in range(nrows):
                w = make_widget(i, j)
                w.observe(self._update, names="value")
                widgets.append(w)
            col.children = widgets
            self.cols.append(col)
        self.children = [label] + self.cols
        self._update()
Example #6
0
    def __init__(self):

        self.start_button = Button(
            value=False,
            description='Start Camera',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Start the camera and the recognition algorithm.',
            icon='')

        self.select_network = Dropdown(
            options=KerasDetector.available_models,
            value=KerasDetector.available_models[0],
            description='Algorithm:',
            disabled=False,
        )

        self.label_names = Text(
            value='',
            placeholder='separated by commas',
            description='Labels',
            disabled=False,
        )

        self.num_pictures = IntText(value=2.0,
                                    description='#pictures',
                                    disabled=False,
                                    layout=Layout(width='18%'))

        self.text = Label(value='',
                          layout=Layout(justify_content='space-around', ))

        self.widget_box = VBox((HBox(
            (self.start_button, self.label_names, self.num_pictures,
             self.select_network),
            layout=Layout(justify_content="space-around")), self.text))

        # Initialize field
        self.collector = None

        self.start_button.on_click(self._start_video)
Example #7
0
    def create_settings(self):
        word = self.create_checkbox('define', 'pos', 'grammar', 'examples')
        phrase = self.create_checkbox('text', 'define', 'examples')
        dictionary = self.create_checkbox('Cambridge', 'Merriam', 'Etymology')
        merriam = self.create_checkbox('first use', 'etymology')
        etymology = self.create_checkbox('description', 'image(if any)')
        translate = self.create_checkbox('requirment')

        setting = GridspecLayout(8, 6)
        setting[0, 2] = Label('settings')
        setting[1, 1:len(dictionary) + 1] = Box(dictionary)
        setting[1, 0] = Label('dictionary')
        setting[2, 2] = Label('output')
        setting[3, 0] = Label('word')
        setting[3, 1:len(word) + 1] = Box(word)
        setting[4, 0] = Label('phrase')
        setting[4, 1:len(phrase) + 1] = Box(phrase)
        setting[5, 0] = Label('Merriam')
        setting[5, 1:len(merriam) + 1] = Box(merriam)
        setting[6, 0] = Label('Etymology')
        setting[6, 1:len(etymology) + 1] = Box(etymology)
        setting[7, 0] = Label('Translate')
        setting[7, 1:len(translate) + 1] = Box(translate)
        return setting
Example #8
0
def RGB_colourspace_models_transformation_matrix_widget():

    title_Label = Label('RGB Colourspace Models Transformation Matrix')
    title_Label.add_class('widget-title')

    default_layout = {'flex': '1 1 auto', 'width': 'auto'}
    input_colourspace_Dropdown = Dropdown(
        options=sorted(colour.RGB_COLOURSPACES), layout=default_layout)

    output_colourspace_Dropdown = Dropdown(
        options=sorted(colour.RGB_COLOURSPACES), layout=default_layout)

    chromatic_adaptation_transforms_Dropdown = Dropdown(
        options=sorted(colour.CHROMATIC_ADAPTATION_TRANSFORMS),
        layout=default_layout)

    formatter_Dropdown = Dropdown(
        options=['str', 'repr', 'Nuke'], layout=default_layout)

    decimals_IntSlider = IntSlider(value=10, max=15, layout=default_layout)

    RGB_to_RGB_matrix_Textarea = Textarea(rows=3, layout=default_layout)
    RGB_to_RGB_matrix_Textarea.add_class('widget-output-textarea')

    def set_RGB_to_RGB_matrix_Textarea():
        M = colour.RGB_to_RGB_matrix(
            colour.RGB_COLOURSPACES[input_colourspace_Dropdown.value],
            colour.RGB_COLOURSPACES[output_colourspace_Dropdown.value],
            chromatic_adaptation_transforms_Dropdown.value)

        with colour.utilities.numpy_print_options(
                formatter={
                    'float':
                    ('{{:0.{0}f}}'.format(decimals_IntSlider.value)).format
                },
                threshold=np.nan):
            if formatter_Dropdown.value == 'str':
                M = str(M)
            elif formatter_Dropdown.value == 'repr':
                M = repr(M)
            else:
                M = NUKE_COLORMATRIX_NODE_TEMPLATE.format(
                    nuke_format_matrix(M, decimals_IntSlider.value),
                    '{0}_to_{1}'.format(
                        input_colourspace_Dropdown.value.replace(' ', '_'),
                        output_colourspace_Dropdown.value.replace(' ', '_')))

            RGB_to_RGB_matrix_Textarea.rows = len(M.split('\n'))
            RGB_to_RGB_matrix_Textarea.value = M

    def on_input_change(change):
        if change['type'] == 'change' and change['name'] == 'value':
            set_RGB_to_RGB_matrix_Textarea()

    input_colourspace_Dropdown.observe(on_input_change)
    output_colourspace_Dropdown.observe(on_input_change)
    chromatic_adaptation_transforms_Dropdown.observe(on_input_change)
    formatter_Dropdown.observe(on_input_change)
    decimals_IntSlider.observe(on_input_change)

    set_RGB_to_RGB_matrix_Textarea()

    widget = Box([
        VBox(
            [
                title_Label,
                Textarea(
                    'This widget computes the colour transformation '
                    'matrix from the Input RGB Colourspace to the '
                    'Output RGB Colourspace using the given '
                    'Chromatic Adaptation Transform.',
                    rows=2,
                    layout=default_layout),
                Label('Input RGB Colourspace'),
                input_colourspace_Dropdown,
                Label('Output RGB Colourspace'),
                output_colourspace_Dropdown,
                Label('Chromatic Adaptation Transform'),
                chromatic_adaptation_transforms_Dropdown,
                Label('Formatter'),
                formatter_Dropdown,
                HBox([Label('Decimals:'), decimals_IntSlider]),
                Label('RGB Transformation Matrix'),
                RGB_to_RGB_matrix_Textarea,
            ],
            layout={
                'border': 'solid 2px',
                'width': '55%'
            })
    ])

    return widget
Example #9
0
def RGB_colourspace_models_chromatically_adapted_primaries_widget():

    title_Label = Label(
        'RGB Colourspace Models Chromatically Adapted Primaries')
    title_Label.add_class('widget-title')

    default_layout = {'flex': '1 1 auto', 'width': 'auto'}
    input_colourspace_Dropdown = Dropdown(
        options=sorted(colour.RGB_COLOURSPACES), layout=default_layout)

    illuminant_Dropdown = Dropdown(
        options=sorted(
            colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']),
        layout=default_layout)

    chromatic_adaptation_transforms_Dropdown = Dropdown(
        options=sorted(colour.CHROMATIC_ADAPTATION_TRANSFORMS),
        layout=default_layout)

    formatter_Dropdown = Dropdown(
        options=['str', 'repr'], layout=default_layout)

    decimals_IntSlider = IntSlider(value=10, max=15, layout=default_layout)

    primaries_Textarea = Textarea(rows=3, layout=default_layout)
    primaries_Textarea.add_class('widget-output-textarea')

    def set_primaries_Textarea():
        input_colourspace = colour.RGB_COLOURSPACES[
            input_colourspace_Dropdown.value]

        P = colour.chromatically_adapted_primaries(
            input_colourspace.primaries, input_colourspace.whitepoint,
            colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][
                illuminant_Dropdown.value],
            chromatic_adaptation_transforms_Dropdown.value)

        with colour.utilities.numpy_print_options(
                formatter={
                    'float':
                    ('{{:0.{0}f}}'.format(decimals_IntSlider.value)).format
                },
                threshold=np.nan):
            if formatter_Dropdown.value == 'str':
                P = str(P)
            elif formatter_Dropdown.value == 'repr':
                P = repr(P)

            primaries_Textarea.rows = len(P.split('\n'))
            primaries_Textarea.value = P

    def on_input_change(change):
        if change['type'] == 'change' and change['name'] == 'value':
            set_primaries_Textarea()

    input_colourspace_Dropdown.observe(on_input_change)
    illuminant_Dropdown.observe(on_input_change)
    chromatic_adaptation_transforms_Dropdown.observe(on_input_change)
    formatter_Dropdown.observe(on_input_change)
    decimals_IntSlider.observe(on_input_change)

    set_primaries_Textarea()

    widget = Box([
        VBox(
            [
                title_Label,
                Textarea(
                    'This widget computes the Chromatically Adapted Primaries '
                    'of the given RGB Colourspace Model to the given '
                    'Illuminant using the '
                    'given Chromatic Adaptation Transform.',
                    rows=3,
                    layout=default_layout),
                Label('Input RGB Colourspace'),
                input_colourspace_Dropdown,
                Label('Illuminant'),
                illuminant_Dropdown,
                Label('Chromatic Adaptation Transform'),
                chromatic_adaptation_transforms_Dropdown,
                Label('Formatter'),
                formatter_Dropdown,
                HBox([Label('Decimals:'), decimals_IntSlider]),
                Label('RGB Transformation Matrix'),
                primaries_Textarea,
            ],
            layout={
                'border': 'solid 2px',
                'width': '55%'
            })
    ])

    return widget
Example #10
0
    disabled=False,
    indent=False,
    layout={'width': 'max-content'},  # If the items' names are long
)

# Export single date images
export_summary_images = Checkbox(
    value=False,
    description='Export to Drive',
    disabled=False,
    indent=False,
    layout={'width': 'max-content'}  # If the items' names are long
)

lbl = Label(value=('Select parameters for exporting single date images - '
                   'WARNING can be hundreds of images:'),
            style={'description_width': 'initial'})
single_date_export_label = HBox([lbl])

lbl = Label(
    value=('Select parameters for exporting summary date images - i.e. '
           'the percentage (%) of inundation:'),
    style={'description_width': 'initial'})
summary_date_export_label = HBox([lbl])

export_variables = Accordion(children=[
    VBox([
        single_date_export_label, band_option, export_images,
        summary_date_export_label, summary_band_option, water_threshold,
        export_summary_images
    ])
Example #11
0
    def __init__(self):
        self.start_button = Button(
            value=False,
            description='Start Camera',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Start the camera to take pictures for classifier ',
            icon='',
            layout=Layout(width='25%'),
        )

        self.save_button = Button(
            value=False,
            description='Save images',
            disabled=True,
            button_style=
            'danger',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Save images to folder ',
            icon='',
            layout=Layout(width='18%', margin="2px 0px 0px 20px"),
        )
        self.load_button = Button(
            value=False,
            description='Load images',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Load images from folder ',
            icon='',
            layout=Layout(width='18%', margin="2px 0px 0px 20px"),
        )

        self.save_path = Text(
            value=str(Path("path", "to", "directory")),
            description='Save path:',
            disabled=False,
        )

        self.num_pictures = FloatText(
            value=12,
            description='#pictures:',
            disabled=False,
            layout=Layout(width='20%'),
        )

        self.use_augmentation = Checkbox(
            value=False,
            description='Augmentation',
            disabled=False,
            tooltip='Use Augmentation',
            icon='check',
        )

        self.progress_text = Label(
            value='',
            layout=Layout(margin="5px 0px 5px 20px"),
        )

        self.widget_box = VBox((
            HBox(
                (self.num_pictures, self.use_augmentation, self.start_button),
                layout=Layout(align_content="flex-start"),
            ),
            HBox(
                (self.progress_text, ),
                layout=Layout(align_content="flex-start"),
            ),
            HBox(
                (self.save_path, self.save_button, self.load_button),
                layout=Layout(align_content="flex-start"),
            ),
        ))

        self.start_button.on_click(self._start_video)
        self.save_button.on_click(self._save_images)
        self.load_button.on_click(self._load_images)

        self.collector = ImageCollector()
Example #12
0
 def make_label(text):
     label_layout = {'width': '200px'}
     return Label(value=text, layout=label_layout)
Example #13
0
    def __init__(self, df: pd.DataFrame, col_name: str, df_name: str,
                 page_size: int):
        self._clusterer = Clusterer(df, col_name, df_name)
        self._clusterer.cluster("fingerprint")

        self._page_size = page_size

        # clustering dropdown and export code checkbox, used in the top row
        self._clustering_method_label = Label(
            " Clustering Method: ", layout=Layout(margin="2px 0 0 20px"))
        self._clustering_method_drop = Dropdown(
            options=[
                "fingerprint", "ngram-fingerprint", "phonetic-fingerprint",
                "levenshtein"
            ],
            layout=Layout(width="150px", margin="0 0 0 10px"),
        )
        self._clustering_method_drop.observe(self._cluster_method_change,
                                             names="value")
        self._export_code = Checkbox(
            value=True,
            description="export code",
            layout=Layout(width="165px", margin="0 0 0 482px"),
            style={"description_width": "initial"},
        )
        self._dropds = HBox(
            [
                self._clustering_method_label,
                self._clustering_method_drop,
                self._export_code,
            ],
            layout=Layout(height="35px", margin="10px 0 0 0"),
        )
        # text boxes for clustering parameters used in the top row
        self._ngram_text = Text(
            value=DEFAULT_NGRAM,
            description="n-gram",
            layout=Layout(width="130px"),
            continuous_update=False,
        )
        self._radius_text = Text(
            value=DEFAULT_RADIUS,
            description="Radius",
            layout=Layout(width="130px"),
            continuous_update=False,
        )
        self._block_chars_text = Text(
            value=DEFAULT_BLOCK_SIZE,
            description="Block Chars",
            layout=Layout(width="130px"),
            continuous_update=False,
        )
        self._ngram_text.observe(self._param_recluster, names="value")
        self._radius_text.observe(self._param_recluster, names="value")
        self._block_chars_text.observe(self._param_recluster, names="value")

        # create header labels, second row
        headers = HBox(
            [
                Label("Distinct values", layout=Layout(margin="0 0 0 10px")),
                Label("Total values", layout=Layout(margin="0 0 0 35px")),
                Label("Cluster values", layout=Layout(margin="0 0 0 95px")),
                Label("Merge?", layout=Layout(margin="0 0 0 295px")),
                Label("Representative value",
                      layout=Layout(margin="0 0 0 50px")),
            ],
            layout=Layout(margin="10px"),
        )

        # create buttons for bottom row
        self._sel_all = Checkbox(description="Select all",
                                 layout=Layout(width="165px"))
        self._sel_all.observe(self._select_all, names="value")

        merge_and_recluster = Button(description="Merge and Re-Cluster",
                                     layout=Layout(margin="0 0 0 466px",
                                                   width="150px"))
        merge_and_recluster.on_click(self._execute_merge)

        finish = Button(description="Finish",
                        layout=Layout(margin="0 0 0 10px"))
        finish.on_click(self._close)

        # next and previous page buttons
        self._next_button = Button(description="Next")
        self._next_button.on_click(self._next_page)

        self._prev_button = Button(description="Previous",
                                   layout=Layout(margin="0 0 0 20px"))
        self._prev_button.on_click(self._prev_page)

        # an index in the clusters Series indicating the start of the current page
        self._page_pos = 0
        # loading label, displayed when re-clustering or next page load
        self._loading_label = Label("Loading...",
                                    layout=Layout(margin="170px 0 0 440px"))
        # displayed when the user enters a non integer value into a clustering parameter text box
        self._invalid_param_label = Label(
            "Invalid clustering parameter, please enter an integer",
            layout=Layout(margin="170px 0 0 350px"),
        )

        self._reprs = [
            Text(layout=Layout(width="200px", margin="0 10px 0 40px"))
            for _ in range(self._page_size)
        ]
        self._checks = [
            Checkbox(indent=False,
                     layout=Layout(width="auto", margin="0 0 0 20px"))
            for _ in range(self._page_size)
        ]

        # VBox containing a VBox with all the clusters in the first row and an optional
        # second row containing next and previous page buttons
        self._cluster_and_next_prev = VBox()
        self._cluster_vbox = VBox(
            layout=Layout(height="450px", flex_flow="row wrap"))

        footer = HBox([self._sel_all, merge_and_recluster, finish])

        box_children = [
            self._dropds, headers, self._cluster_and_next_prev, footer
        ]

        box_layout = Layout(display="flex",
                            flex_flow="column",
                            align_items="stretch",
                            border="solid")
        self._box = Box(children=box_children, layout=box_layout)
        self._update_clusters()
Example #14
0
    def displayInterface(self):
        '''
        显示组件
        :return: 
        '''
        if not self.cf.isReady():
            print(Fore.RED + '配置项尚未初始化!')
            self.btnInit = Button(description = '立即初始化', button_style = 'danger')
            self.btnInit.on_click(self.on_init_clicked)
            display(self.btnInit)
        else:
            self.catagoryname = self.cf.readConf(self.default['interface'], 'catagoryname') # 类别名称
            self.catagoryname = self.default[
                'catagory'] if self.catagoryname is None else self.catagoryname # 未设置时使用默认配置
            self.interfacename = self.cf.readConf(self.default['interface'], 'interfacename') # 接口名称
            self.interfacename = self.default[
                'interface'] if self.interfacename is None else self.interfacename # 未设置时使用默认配置
            self.catagory = interfaces.get(self.catagoryname, None) if self.catagoryname is not None else None # 类别信息
            self.interfaces = self.catagory.get('interface', None) if self.catagory is not None else None # 类别下所有接口信息
            self.interface = self.interfaces.get(self.interfacename,
                                                 None) if self.interfaces is not None and self.interfacename is not None else None # 接口信息
            # 组件初始化
            self.dpCatagory = Dropdown(
                options = [key for key in interfaces.keys()],
                value = self.catagoryname if self.catagoryname is not None else None,
                description = '类别:'
            )
            debug.out('interfacename = %s' % self.interfacename)
            tmpOptions = [key for key in
                          interfaces[self.dpCatagory.value]['interface']] if self.catagory is not None else []
            self.dpInterface = Dropdown(
                options = tmpOptions,
                value = self.interfacename if self.interfacename in tmpOptions else None,
                description = '接口:'
            )

            self.dpCatagory.observe(self.on_catagory_change)
            self.dpInterface.observe(self.on_interface_change)

            self.htmInterface = HTML(value = self.choiceResult())
            self.gdParam = qgrid.show_grid(pd.DataFrame(None))
            self.gdBody = qgrid.show_grid(pd.DataFrame(None))

            if self.interface is not None:
                self.dfParams = pd.DataFrame(self.interface.get('params', ['无']), index = [0]).T
                self.dfParams.columns = ['请求参数类型']
                self.gdParam = qgrid.show_grid(self.dfParams,
                                               grid_options = {'filterable': False, 'editable': False})
                self.gdParam.layout = Layout(width = '90%')

                self.dfBody = pd.DataFrame(self.interface.get('body', ['无']))
                self.dfBody.columns = ['请求体参数名称']
                self.gdBody = qgrid.show_grid(self.dfBody, grid_options = {'filterable': False, 'editable': False})
                self.gdBody.layout = Layout(width = '90%')

            debug.out('display from interface object=%s' % self)
            display(self.dpCatagory)
            display(self.dpInterface)

            boxRequest = Box([VBox([Label(value = '请求参数:'), self.gdParam],
                                   layout = Layout(flex = '1 1 0%', width = 'auto')),
                              VBox([Label(value = '请求体参数:'), self.gdBody],
                                   layout = Layout(flex = '1 1 0%', width = 'auto'))],
                             layout = Layout(flex_flow = 'row', display = 'flex'))
            boxRef = VBox([self.htmInterface, boxRequest])
            acRef = Accordion(children = [boxRef])
            acRef.set_title(0, '接口参考')
            toggleRefDisplay(acRef)
            display(acRef)
            ref.append(acRef)
Example #15
0
    def __init__(self, model, *args, **kwargs):
        self.model = model
        self._fields = {field: Text() for field in self.model.fields}
        self.radio_button_group = RadioButtons(
            description="When:",
            options=[
                "All", "30 Days", "24 Hours", "1 Year", "1 Week", "1 Hour"
            ],
        )
        self.refresh_button = Button(description="Refresh")
        date_buttons = VBox([self.radio_button_group, self.refresh_button])
        self.since_widget = DatetimePicker()
        self.until_widget = DatetimePicker()
        date_range = HBox([
            Label(value="Date range:"),
            self.since_widget,
            Label(value="-"),
            self.until_widget,
        ])

        grid_children = []
        for field, text in self._fields.items():
            grid_children.append(Label(value=f"{field}:"))
            grid_children.append(text)

        text_grid = GridBox(children=grid_children,
                            layout=Layout(grid_template_columns="30% 70%"))

        text_input = VBox([date_range, text_grid])
        children = (date_buttons, text_input)
        if self.model.text_search_supported:
            full_text_label = Label("Full Text Search:")
            self.text_search_input = Text()
            text_grid.children += (full_text_label, self.text_search_input)
            self.text_search_input.observe(self._on_text_view_changed, "value")
            self.model.events.text.connect(self._on_text_model_changed)

        super().__init__(children, **kwargs)

        self.radio_button_group.observe(self._on_radio_button_changed, "value")
        self.refresh_button.on_click(self._on_reload_request)
        self.model.events.reload.connect(self._on_reload)
        self.model.events.query.connect(self._on_reload)

        self.since_widget.observe(self._on_since_view_changed, "value")
        self.model.events.since.connect(self._on_since_model_changed)
        self.until_widget.observe(self._on_until_view_changed, "value")
        self.model.events.until.connect(self._on_until_model_changed)

        # Set these values here so the model picks the values up
        self.model.since = GRACE_HOPPER_BIRTHDAY
        self.model.until = timedelta()
        self.radio_button_group.index = self.radio_button_group.options.index(
            "All")

        for field, text in zip(self.model.fields, self._fields.values()):

            def on_field_text_changed(change, field=field):
                self.model.field_search.update({field: change["new"]})

            text.observe(on_field_text_changed, "value")

        self.model.events.field_search_updated.connect(
            self._on_field_search_updated)
Example #16
0
    def __init__(self):

        self.start_button = Button(
            value=False,
            description='Start Camera',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Start the camera and the recognition algorithm.',
            icon='')

        self.use_recorded = RadioButtons(
            options=['Webcam', 'MP4'],
            value='Webcam',
            description='Input',
            disabled=False,
            layout=Layout(width='320px'),
            style={'description_width': '150px'},
        )

        self.video_path = Text(
            value='',
            placeholder=str(Path("path", "to", "video.mp4")),
            description='Video path:',
            disabled=True,
            layout=Layout(width='320px'),
            style={'description_width': '150px'},
        )

        self.select_network = Dropdown(
            options=KerasDetector.available_models,
            value=KerasDetector.available_models[0],
            description='Algorithm:',
            disabled=False,
            layout=Layout(width='220px'),
            style={'description_width': '100px'},
        )

        self.select_frontend = Dropdown(
            options=["opencv", "matplotlib"],
            value="opencv",
            description='Frontend:',
            disabled=False,
            layout=Layout(width='220px', padding='8px 0 0 0'),
            style={'description_width': '100px'},
        )

        self.video_length = FloatText(
            value=12.0,
            description='Video length [s]:',
            disabled=False,
            layout=Layout(width='250px'),
            style={'description_width': '130px'},
        )

        self.select_framerate = Dropdown(
            options=[3, 5, 10, 15, 24],
            value=15,
            description='Frame rate:',
            disabled=False,
            layout=Layout(width='250px', padding='8px 0 0 0'),
            style={'description_width': '130px'},
        )

        self.static_text = Label(
            value="Working directory: {}".format(Path.cwd()),
            layout=Layout(margin='30px 0 0 0'),
        )
        self.progress_text = Label(value='', )
        self.text_box = VBox((self.static_text, self.progress_text),
                             layout=Layout(justify_content="flex-start"))

        self.widget_box = VBox(
            (HBox((VBox((self.start_button, ),
                        layout=Layout(justify_content="space-around")),
                   VBox((self.use_recorded, self.video_path),
                        layout=Layout(justify_content="space-around")),
                   VBox((self.video_length, self.select_framerate),
                        layout=Layout(justify_content="space-around")),
                   VBox((self.select_network, self.select_frontend),
                        layout=Layout(justify_content="space-around"))), ),
             HBox((self.text_box, ),
                  layout=Layout(justify_content="flex-start"))), )

        self.start_button.on_click(self._start_video)
        self.use_recorded.observe(self.refresh_state)