Exemplo n.º 1
0
    def add_rank_table(self):

        columns = [
            TableColumn(field="tool", title="Tool"),
            TableColumn(field="score",
                        title="Weighted Score",
                        formatter=NumberFormatter(format="0.00")),
            TableColumn(field="rank", title="Rank")
        ]

        self.data_table = DataTable(columns=columns,
                                    source=self.source,
                                    reorderable=True)

        buttons = zip(
            [self.ranking[k][0] for k in self.chosen_criteria],
            [self.ranking[k][1] for k in self.chosen_criteria],
            [self.weight_sliders[k] for k in self.weight_sliders.keys()])

        self.app_layout.children.pop(1)

        b_layout = [[t[0], t[1], t[2]] for t in buttons]

        b_layout.append([self.rank_submit, self.b])
        b_layout.append(widgetbox(self.data_table))
        b_layout.append([self.clear_button])
        b_layout.insert(0, [Spacer(width=300), self.swing_table])
        self.app_layout.children.append(layout(b_layout))
Exemplo n.º 2
0
 def get_history_module(self):
     self.history_dict = {
         k: list(self.history[k])
         for k in self.config['controllables']
     }
     self.history_dict['pred.'] = [''] * len(self.history)
     # self.history_dict['imple.'] = ['V'] * len(self.history)
     self.his_table_source = ColumnDataSource(self.history_dict)
     cols = [
         TableColumn(field=k, title=k) for k in self.config['controllables']
     ]
     # cols.extend([TableColumn(field='pred.', title='pred.'), TableColumn(field='imple.', title='imple.')])
     cols.extend([TableColumn(field='pred.', title='pred.')])
     his_table = DataTable(source=self.his_table_source,
                           columns=cols,
                           width=200,
                           height=800,
                           editable=True,
                           reorderable=False)
     title = Div(text='History',
                 sizing_mode="stretch_width",
                 style={
                     'font-size': '150%',
                     'color': self.txt_color
                 })
     self.his_panel.append(title)
     self.his_panel.append(his_table)
Exemplo n.º 3
0
        def modify_doc(doc):
            data = {'x': [1, 2, 3, 4], 'y': [10, 20, 30, 40]}
            source = ColumnDataSource(data)

            plot = Plot(plot_height=400,
                        plot_width=400,
                        x_range=Range1d(0, 1),
                        y_range=Range1d(0, 1),
                        min_border=0)
            plot.add_tools(
                CustomAction(callback=CustomJS(args=dict(s=source),
                                               code=RECORD("data", "s.data"))))

            table = DataTable(
                columns=[TableColumn(field="x"),
                         TableColumn(field="y")],
                source=source,
                editable=False)

            btn = Button(label="Click Me!", css_classes=["foo"])

            @btn.on_click
            def btn_click():
                source.patch({"x": [(0, 42)]})

            doc.add_root(column(plot, table, btn))
Exemplo n.º 4
0
    def test_columns_sortable(self, bokeh_model_page: BokehModelPage) -> None:
        data = {'x': [1,2,3,4], 'y': [4, 3, 2, 1], 'd': ['foo', 'bar', 'baz', 'quux']}
        source = ColumnDataSource(data)
        table = DataTable(columns=[
            TableColumn(field="x", title="x"),
            TableColumn(field="y", title="y", sortable=False),
            TableColumn(field="d", title="d", sortable=True),
        ], source=source)

        page = bokeh_model_page(table)

        # index column
        h1 = get_table_header(page.driver, table, 1)
        assert "slick-header-sortable" in h1.get_attribute('class')

        h2 = get_table_header(page.driver, table, 2)
        assert "slick-header-sortable" in h2.get_attribute('class')

        h3 = get_table_header(page.driver, table, 3)
        assert "slick-header-sortable" not in h3.get_attribute('class')

        h4 = get_table_header(page.driver, table, 4)
        assert "slick-header-sortable" in h4.get_attribute('class')

        assert page.has_no_console_errors()
Exemplo n.º 5
0
    def setup_method(self):
        source = ColumnDataSource({'values': self.values})
        column = TableColumn(field='values', title='values', editor=self.editor())
        self.table = DataTable(source=source, columns=[column], editable=True, width=600)

        # this is triggered on selection changes
        source.selected.js_on_change('indices', CustomJS(args=dict(s=source), code=RECORD("values", "s.data.values")))
Exemplo n.º 6
0
    def make_table_tab(source):
        def get_formatter(data):
            if data.dtype.name == 'datetime64[ns]':
                return DateFormatter(format='%Y-%m-%d %H:%M:%S')
            if data.dtype.name in ['float64', 'int64']:
                return NumberFormatter(format='0.0[000]')
            if data.dtype.name == 'bool':
                return BooleanFormatter()

            return StringFormatter()

        table_columns = [
            TableColumn(field='index',
                        title='',
                        formatter=get_formatter(df.index))
        ]

        for col in df.columns:
            fmt = get_formatter(df[col])
            title = col
            table_col = TableColumn(field=col, title=title, formatter=fmt)
            table_columns.append(table_col)

        data_table = DataTable(source=source,
                               columns=table_columns,
                               width=1600,
                               height=800)
        panel = Panel(child=data_table, title="Table View")
        return panel
Exemplo n.º 7
0
    def setup_sel_table(self, **kwargs):
        """
        ???+ note "Set up a bokeh `DataTable` widget for viewing selected data points."

            | Param      | Type   | Description                  |
            | :--------- | :----- | :--------------------------- |
            | `**kwargs` |        | forwarded to the `DataTable` |
        """
        def auto_columns(df):
            return [TableColumn(field=_col, title=_col) for _col in df.columns]

        sel_source = ColumnDataSource(dict())
        sel_columns = auto_columns(self.dfs["train"])
        self.sel_table = DataTable(source=sel_source,
                                   columns=sel_columns,
                                   **kwargs)

        def update_selection(selected_df):
            """
            Callback function.
            """
            # push results to bokeh data source
            self.sel_table.columns = auto_columns(selected_df)
            sel_source.data = selected_df.to_dict(orient="list")

            self._good(
                f"Selection table: latest selection with {selected_df.shape[0]} entries."
            )

        self._callback_update_selection = update_selection
Exemplo n.º 8
0
    def _make_data_table(self):
        """ Builds the datatable portion of the final plot.

        """
        columns = [
            TableColumn(field="props", title="Property"),
            TableColumn(field="values", title="Value"),
        ]
        prop_source = ColumnDataSource(self._prop_df)
        model_id = self._node_source.data["index"][0]
        groupfilter = GroupFilter(column_name="id", group=model_id)

        data_table2_view = CDSView(source=prop_source, filters=[groupfilter])
        data_table2 = DataTable(
            source=prop_source,
            view=data_table2_view,
            columns=columns,
            visible=False,
            index_position=None,
            fit_columns=True,
            editable=False,
        )

        self._groupfilter = groupfilter
        self._prop_source = prop_source
        return data_table2
    def __create_transactions_table(self, source):
        """Creates Transactions DataTable with DataSource source passed as it's ColumnData Source.

            DataTable defines 4 fields that need to be passed in the source ColumnDataSource .data attribute:
                - .date
                - .product
                - .price
                - .shop
            Those attributes correspond to column names in .original_df and it's derivatives. Created DataTable will
            show details of those 4 columns for every transaction necessary. Additionally, .date field will be
            formatted to %d-%m-%Y format (31-01-2019) and .price field will be formatted into 0,0.00 format
            (1,897.34).

            DataTable has it's index (counter) column removed for clarity.

            Returns created DataTable.
        """
        columns = [
            TableColumn(field=self.date, title="Date", formatter=DateFormatter(format="%d-%m-%Y")),
            TableColumn(field=self.product, title="Product"),
            TableColumn(field=self.price, title="Price", formatter=NumberFormatter(format="0,0.00")),
            TableColumn(field=self.shop, title="Shop")
        ]

        dt = DataTable(source=source, columns=columns, header_row=True, index_position=None)
        return dt
Exemplo n.º 10
0
    def test_multi_row_copy(self, bokeh_model_page) -> None:
        data = {'x': [1,2,3,4], 'y': [0,1,2,3], 'd': ['foo', 'bar', 'baz', 'quux']}
        source = ColumnDataSource(data)
        table = DataTable(columns=[
            TableColumn(field="x", title="x"),
            TableColumn(field="y", title="y"),
            TableColumn(field="d", title="d"),
        ], source=source)

        text_input = TextInput(css_classes=["foo"])
        text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value")))

        page = bokeh_model_page(column(table, text_input))

        row = get_table_row(page.driver, 1)
        row.click()

        row = get_table_row(page.driver, 3)
        shift_click(page.driver, row)

        enter_text_in_element(page.driver, row, Keys.INSERT, mod=Keys.CONTROL, click=0, enter=False)

        input_el = page.driver.find_element_by_css_selector('.foo')
        enter_text_in_element(page.driver, input_el, Keys.INSERT, mod=Keys.SHIFT, enter=False)
        enter_text_in_element(page.driver, input_el, "")

        results = page.results

        # XXX (bev) these should be newlines with a TextAreaInput but TextAreaInput
        # is not working in tests for some reason presently
        assert results['value'] == '0\t1\t0\tfoo 1\t2\t1\tbar 2\t3\t2\tbaz'

        assert page.has_no_console_errors()
Exemplo n.º 11
0
    def test_single_row_copy_with_zero(self, bokeh_model_page) -> None:
        data = {'x': [1,2,3,4], 'y': [0,0,0,0], 'd': ['foo', 'bar', 'baz', 'quux']}
        source = ColumnDataSource(data)
        table = DataTable(columns=[
            TableColumn(field="x", title="x"),
            TableColumn(field="y", title="y"),
            TableColumn(field="d", title="d"),
        ], source=source)

        text_input = TextInput(css_classes=["foo"])
        text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value")))

        page = bokeh_model_page(column(table, text_input))

        row = get_table_row(page.driver, 2)
        row.click()

        enter_text_in_element(page.driver, row, Keys.INSERT, mod=Keys.CONTROL, click=0, enter=False)

        input_el = page.driver.find_element_by_css_selector('.foo')
        enter_text_in_element(page.driver, input_el, Keys.INSERT, mod=Keys.SHIFT, enter=False)
        enter_text_in_element(page.driver, input_el, "")

        sleep(0.5)
        results = page.results

        assert results['value'] == '1\t2\t0\tbar'

        assert page.has_no_console_errors()
Exemplo n.º 12
0
    def test_multi_row_copy(self, bokeh_model_page):
        data = {'x': [1,2,3,4], 'y': [0, 1, 2, 3], 'd': ['foo', 'bar', 'baz', 'quux']}
        source = ColumnDataSource(data)
        table = DataTable(columns=[
            TableColumn(field="x", title="x"),
            TableColumn(field="y", title="y"),
            TableColumn(field="d", title="d"),
        ], source=source)

        text_input = TextAreaInput(css_classes=["foo"])
        text_input.js_on_change('value', CustomJS(code=RECORD("value", "cb_obj.value")))

        page = bokeh_model_page(column(table, text_input))

        # select the third row
        row = get_table_row(page.driver, 1)
        row.click()

        row = get_table_row(page.driver, 3)
        shift_click(page.driver, row)

        enter_text_in_element(page.driver, row, Keys.INSERT, mod=Keys.CONTROL, click=0, enter=False)

        input_el = page.driver.find_element_by_css_selector('.foo')
        enter_text_in_element(page.driver, input_el, Keys.INSERT, mod=Keys.SHIFT, enter=False)
        #enter_text_in_element(page.driver, input_el, "")

        sleep(2.0)
        results = page.results

        assert results['value'] == '0\t1\t0\tfoo\n1\t2\t1\tbar\n2\t3\t2\tbaz\n'

        assert page.has_no_console_errors()
Exemplo n.º 13
0
    def display_eval_scores(self, saved_eval_scores_dict_path):
        """
        Publishes the evaluation scores table to the server.

        :param saved_eval_scores_dict_path: file path to the evaluation scores for each layer
        :return: None
        """
        infile = open(saved_eval_scores_dict_path, 'rb')
        eval_scores_dict = pickle.load(infile)
        infile.close()

        eval_scores_data_frame = pd.DataFrame.from_dict(eval_scores_dict).T
        eval_scores_data_frame.columns = eval_scores_data_frame.columns.map(
            str)
        eval_scores_data_frame.insert(0, 'layers',
                                      eval_scores_data_frame.index)

        source = ColumnDataSource(data=eval_scores_data_frame)
        columns = [
            TableColumn(field=Ci, title=Ci)
            for Ci in eval_scores_data_frame.columns
        ]  # bokeh columns
        eval_scores_data_table = DataTable(source=source,
                                           columns=columns,
                                           width=1500)

        self.__document.add_root(eval_scores_data_table)
Exemplo n.º 14
0
    def _get_resource_widget(self):
        resources = []
        num_annotated_texts = []
        num_annotations = []

        for resource in self.resources:
            resources.append(resource.resource_id)
            annotated_texts = resource.get_annotated_texts()
            num_annotated_texts.append(len(annotated_texts))
            num_annotations.append(
                sum([len(at.annotations) for at in annotated_texts]))

        data = dict(resource=resources,
                    sentences=num_annotated_texts,
                    annotations=num_annotations)
        source = ColumnDataSource(data)

        columns = [
            TableColumn(field="resource", title="Resource", width=500),
            TableColumn(field="sentences", title="Sentences", width=70),
            TableColumn(field="annotations", title="Annotations", width=880),
        ]

        data_table = DataTable(source=source,
                               columns=columns,
                               min_height=100,
                               max_height=1000,
                               height=(len(resources) + 1) * 28,
                               width=1500,
                               autosize_mode="none",
                               sizing_mode="scale_both")

        return [Div(text='<h2>Resources</h2>'), data_table]
Exemplo n.º 15
0
 def make_stock_picking_table(stock_picking_table_source):
     columns = []
     for colnames in stock_picking_table_source.data.keys():
         if colnames !='index':
             columns.append(TableColumn(field=colnames, title=colnames, width=6*len(colnames)))
     stock_picking_table = DataTable(source=stock_picking_table_source, columns=columns, width=4000, height = 500)
     return (stock_picking_table)
Exemplo n.º 16
0
def build_stmt_table(
        pred_stmt_dict: Dict, tnt_grp: RadioButtonGroup,
        b_grp: RadioButtonGroup, cc_grp: RadioButtonGroup
) -> Tuple[DataTable, ColumnDataSource, CDSView]:
    stmttable_cds = ColumnDataSource(pred_stmt_dict)
    stmtcolumn = [
        TableColumn(field="statement_text", title="Statement", width=4000)
    ]
    js_filter = CustomJSFilter(args=dict(stmttable_cds=stmttable_cds,
                                         tnt_grp=tnt_grp,
                                         b_grp=b_grp,
                                         cc_grp=cc_grp),
                               code=dashboard_constants.cdsview_jsfilter_code)
    stmt_view = CDSView(source=stmttable_cds, filters=[js_filter])
    stmttable = DataTable(source=stmttable_cds,
                          columns=stmtcolumn,
                          header_row=False,
                          index_position=None,
                          view=stmt_view,
                          height_policy='max',
                          width_policy='max',
                          fit_columns=False,
                          scroll_to_selection=False,
                          margin=(5, 5, 5, 5),
                          width=300,
                          height=300,
                          min_height=50,
                          css_classes=['box', 'stmt_table'])
    return stmttable, stmttable_cds, stmt_view
Exemplo n.º 17
0
 def make_stock_return_table_3(stock_return_table_3_source): 
     columns = []
     for colnames in stock_return_table_3_source.data.keys():
         if colnames !='index':
             columns.append(TableColumn(field=colnames, title=colnames, width=6*len(colnames)))
     stock_return_table_3 = DataTable(source=stock_return_table_3_source, columns=columns)
     return (stock_return_table_3)
Exemplo n.º 18
0
    def test_row_highlights_reflect_js_selection(self,
                                                 bokeh_model_page) -> None:

        source = ColumnDataSource({'values': [1, 2]})
        col = TableColumn(field='values', title='values')
        table = DataTable(source=source,
                          columns=[col],
                          editable=False,
                          width=600)

        button = ButtonWrapper("Click",
                               callback=CustomJS(args=dict(s=source),
                                                 code="""
            s.selected.indices = [1]
        """))

        page = bokeh_model_page(column(button.obj, table))

        row0 = get_table_cell(page.driver, 1, 1)
        assert 'selected' not in row0.get_attribute('class')

        row1 = get_table_cell(page.driver, 2, 1)
        assert 'selected' not in row1.get_attribute('class')

        button.click(page.driver)

        row0 = get_table_cell(page.driver, 1, 1)
        assert 'selected' not in row0.get_attribute('class')

        row1 = get_table_cell(page.driver, 2, 1)
        assert 'selected' in row1.get_attribute('class')

        assert page.has_no_console_errors()
Exemplo n.º 19
0
def create_contamination_completeness_table(df):
    from collections import OrderedDict
    contamination_completenes_row_arr = []

    for index, row in df.iterrows():
        list(filter(lambda x: CONT_0_1 in x, row.index))

        def get_row_for_contamination(row, contamination):
            cols = OrderedDict()
            cols['Tool'] = "{} {}".format(row.name, DESCRIPTION_CONTAMINATION_ROW[contamination][COL_TITLE])
            cols[COMPL_0_5] = row["{}{}".format(COMPL_0_5, contamination)]
            cols[COMPL_0_7] = row["{}{}".format(COMPL_0_7, contamination)]
            cols[COMPL_0_9] = row["{}{}".format(COMPL_0_9, contamination)]
            return cols

        contamination_completenes_row_arr.append(get_row_for_contamination(row, CONT_0_1))
        contamination_completenes_row_arr.append(get_row_for_contamination(row, CONT_0_05))
    df = pd.DataFrame(contamination_completenes_row_arr)

    def create_table_column(field):
        if field == "Tool":
            return widgets.TableColumn(title=field, field=field, width=600)
        else:
            return widgets.TableColumn(title=DESCRIPTION_COMPLETENESS_COL[field][COL_TITLE], field=field)

    dt = DataTable(source=bokeh.models.ColumnDataSource(df),
                   columns=list(map(lambda x: create_table_column(x), df.columns.values)),
                   width=TABLE_ELEMENT_WIDTH,
                   reorderable=True,
                   selectable=True)
    return [widgetbox(dt)]
Exemplo n.º 20
0
    def test_row_highlights_reflect_ui_selection(self,
                                                 bokeh_model_page) -> None:

        source = ColumnDataSource({'values': [1, 2]})
        column = TableColumn(field='values', title='values')
        table = DataTable(source=source,
                          columns=[column],
                          editable=False,
                          width=600)

        page = bokeh_model_page(table)

        row0 = get_table_cell(page.driver, 1, 1)
        assert 'selected' not in row0.get_attribute('class')

        row1 = get_table_cell(page.driver, 2, 1)
        assert 'selected' not in row1.get_attribute('class')

        cell = get_table_cell(page.driver, 2, 1)
        cell.click()

        row0 = get_table_cell(page.driver, 1, 1)
        assert 'selected' not in row0.get_attribute('class')

        row1 = get_table_cell(page.driver, 2, 1)
        assert 'selected' in row1.get_attribute('class')

        assert page.has_no_console_errors()
Exemplo n.º 21
0
def save_df_as_image(df, path):
    source = ColumnDataSource(df)
    df_columns = [df.index.name]
    df_columns.extend(df.columns.values)
    columns_for_table=[]

    template="""                
            <div style="color:<%= 
                (function colorfromint(){
                    if (Variation > 0)
                        {return('green')}
                    else if (Variation < 0)
                        {return('red')}
                    else 
                        {return('blue')}
                    }())%>;"> 
                <%=value%>
            </div>
            """
    formatter =  HTMLTemplateFormatter(template=template)

    for column in df_columns:
        if(column == 'Variation'):
            columns_for_table.append(TableColumn(field=column, title=column, formatter=formatter))
        else:
            columns_for_table.append(TableColumn(field=column, title=column))
        
    full_height=(26*len(df.index))
    data_table = DataTable(source=source, columns=columns_for_table,fit_columns=True,height=full_height,width_policy="auto",index_position=None)
        
    export_png(data_table, filename = path)
 def mortality_source_table(self):
     anad_reasons = [
         fish.mortality_reason for fish in self.schedule.dead_fish
         if fish.life_history is LifeHistory.ANADROMOUS
     ]
     res_reasons = [
         fish.mortality_reason for fish in self.schedule.dead_fish
         if fish.life_history is LifeHistory.RESIDENT
     ]
     all_reasons = set(
         list(Counter(res_reasons).keys()) +
         list(Counter(anad_reasons).keys()))
     ac = Counter(anad_reasons)
     rc = Counter(res_reasons)
     anad_pct = list(100 * np.array([ac[reason]
                                     for reason in all_reasons]) /
                     len(anad_reasons))
     res_pct = list(100 * np.array([rc[reason] for reason in all_reasons]) /
                    len(res_reasons))
     source = ColumnDataSource({
         'reason': list(all_reasons),
         'anad pct': anad_pct,
         'res pct': res_pct
     })
     columns = [
         TableColumn(field="reason", title="Mortality reason", width=250),
         TableColumn(field="anad pct", title="% of anadromous", width=125),
         TableColumn(field="res pct", title="% of resident", width=125)
     ]
     return DataTable(source=source,
                      columns=columns,
                      row_headers=False,
                      width=500,
                      height=200)
Exemplo n.º 23
0
    def test_click_sortable(self, bokeh_model_page: BokehModelPage) -> None:
        data = {'x': [1,2,3,4], 'y': [4, 3, 2, 1], 'd': ['foo', 'bar', 'baz', 'quux']}
        source = ColumnDataSource(data)
        table = DataTable(columns=[
            TableColumn(field="x", title="x"),
            TableColumn(field="y", title="y", sortable=False),
            TableColumn(field="d", title="d", sortable=True),
        ], source=source)

        page = bokeh_model_page(table)

        for i, x in enumerate(['foo', 'bar', 'baz', 'quux'], 1):
            elt = get_table_cell(page.driver, table, i, 3)
            assert elt.text == x

        h4 = get_table_header(page.driver, table, 4)
        h4.click()

        for i, x in enumerate(['bar', 'baz', 'foo', 'quux'], 1):
            elt = get_table_cell(page.driver, table, i, 3)
            assert elt.text == x

        h4 = get_table_header(page.driver, table, 4)
        h4.click()

        for i, x in enumerate(['quux', 'foo', 'baz', 'bar'], 1):
            elt = get_table_cell(page.driver, table, i, 3)
            assert elt.text == x

        assert page.has_no_console_errors()
Exemplo n.º 24
0
    def test_server_source_update_does_not_duplicate_data_update_event(
            self, bokeh_server_page: BokehServerPage) -> None:
        btn = Button(label="Click Me!")

        data = {'x': [1, 2, 3, 4], 'y': [10, 20, 30, 40]}
        source = ColumnDataSource(data)

        table = DataTable(
            columns=[TableColumn(field="x"),
                     TableColumn(field="y")],
            source=source,
            editable=False)

        def modify_doc(doc):

            plot = Plot(height=400,
                        width=400,
                        x_range=Range1d(0, 1),
                        y_range=Range1d(0, 1),
                        min_border=0)
            plot.tags.append(
                CustomJS(name="custom-action",
                         args=dict(s=source),
                         code=RECORD("data", "s.data")))

            @btn.on_click
            def btn_click():
                source.data = {'x': [5, 6, 7, 8], 'y': [50, 60, 70, 80]}

            doc.add_root(column(plot, table, btn))

        page = bokeh_server_page(modify_doc)

        page.eval_custom_action()

        results = page.results
        assert results == {'data': {'x': [1, 2, 3, 4], 'y': [10, 20, 30, 40]}}

        btn_el = find_element_for(page.driver, btn)
        btn_el.click()

        page.eval_custom_action()

        results = page.results
        assert results == {'data': {'x': [5, 6, 7, 8], 'y': [50, 60, 70, 80]}}

        # if the server receives something back like:
        #
        # Message 'PATCH-DOC' (revision 1) content: {
        #     'events': [{
        #         'kind': 'ModelChanged',
        #         'model': {'id': '1001'},
        #         'attr': 'data', 'new': {'x': [1, 2, 3, 4, 5], 'y': [10, 20, 30, 40, 50]}
        #     }],
        #     'references': []
        # }
        #
        # Then that means the client got our stream message and erroneously ping
        # ponged a full data update back to us
        assert not has_cds_data_patches(page.message_test_port.received)
Exemplo n.º 25
0
    def get_analyzers_tables(
            self,
            analyzer: bt.analyzers.Analyzer) -> (Paragraph, List[DataTable]):
        """Return a header for this analyzer and one *or more* data tables."""
        if hasattr(analyzer, 'get_analysis_table'):
            title, table_columns_list = analyzer.get_analysis_table()
        else:
            # Analyzer does not provide a table function. Use our generic one
            title, table_columns_list = TableGenerator._get_analysis_table_generic(
                analyzer)

        param_str = get_params_str(analyzer.params)
        if len(param_str) > 0:
            title += f' ({param_str})'

        elems: List[DataTable] = []
        for table_columns in table_columns_list:
            cds = ColumnDataSource()
            columns = []
            for i, c in enumerate(table_columns):
                col_name = f'col{i}'
                cds.add(c[2:], col_name)
                columns.append(
                    TableColumn(field=col_name,
                                title=c[0],
                                formatter=self._get_formatter(c[1])))
            column_height = len(table_columns[0]) * 25
            elems.append(
                DataTable(source=cds,
                          columns=columns,
                          index_position=None,
                          height=column_height))
        return Paragraph(text=title, style={'font-size': 'large'}), elems
Exemplo n.º 26
0
    def _addTable(self, src_pred):
        ''' 
        Method adds table under the plot with position of the lines
        
        Parameters
        ----------
        src_pred: ColumnDataSource line coords for pred lesion
        
        Output
        ------
        Returns a table object to be added to the figure
        
        '''
        columns = [
            TableColumn(field='desc', title='description'),
            TableColumn(field='color', title='color'),
            TableColumn(field="x", title="X coordinates"),
            TableColumn(field="y", title="Y coordinates")
        ]

        table = DataTable(source=src_pred,
                          columns=columns,
                          editable=True,
                          height=400)
        return table
Exemplo n.º 27
0
        def modify_doc(doc):

            plot = Plot(plot_height=400,
                        plot_width=400,
                        x_range=Range1d(0, 1),
                        y_range=Range1d(0, 1),
                        min_border=0)
            plot.add_tools(
                CustomAction(callback=CustomJS(args=dict(s=source),
                                               code=RECORD("data", "s.data"))))

            table = DataTable(columns=[
                TableColumn(field="x", title="x", sortable=True),
                TableColumn(field="y", title="y", sortable=True)
            ],
                              source=source,
                              editable=False)

            button = Button(css_classes=["foo"])

            def cb():
                source.stream({'x': [100], 'y': [100]})

            button.on_click(cb)

            doc.add_root(column(plot, table, button))
Exemplo n.º 28
0
    def test_copy_paste_to_textarea(self, bokeh_model_page):
        source = ColumnDataSource(dict(x=[1, 2], y=[1, 1]))
        columns = [
            TableColumn(field='x', title='x'),
            TableColumn(field='y', title='y')
        ]
        table = DataTable(source=source,
                          columns=columns,
                          editable=False,
                          width=600)
        text_area = Div(text='<textarea id="T1"></textarea>')

        page = bokeh_model_page(column(table, text_area))

        # Use reversed order to get the correct order
        copy_table_rows(page.driver, [2, 1])

        # Copy is a little slow
        sleep(0.1)

        element = get_page_element(page.driver, '#T1')

        # Selenium doesn't paste until we write something to the element first
        # textarea works like a cell
        enter_text_in_cell_with_click_enter(page.driver, element, 'PASTED:')

        paste_values(page.driver, element)

        result = element.get_attribute('value')

        # The textarea now contains the content in the datatable
        assert result == '\nPASTED:\n0\t1\t1\n1\t2\t1\n'

        assert page.has_no_console_errors()
Exemplo n.º 29
0
    def test_glyph_selection_updates_table(self, single_plot_page) -> None:
        plot = Plot(height=800, width=1000)

        data = {'x': [1, 2, 3, 4], 'y': [1, 1, 1, 1]}
        source = ColumnDataSource(data)
        table = DataTable(columns=[
            TableColumn(field="x", title="x", sortable=True),
            TableColumn(field="y",
                        title="y",
                        sortable=True,
                        editor=NumberEditor())
        ],
                          source=source,
                          editable=True)

        plot.add_glyph(source, Rect(x='x', y='y', width=1.5, height=1))
        plot.add_tools(
            TapTool(callback=CustomJS(
                code=RECORD("indices", "cb_data.source.selected.indices"))))

        page = single_plot_page(column(plot, table))

        page.click_canvas_at_position(500, 400)
        assert set(page.results["indices"]) == {1, 2}

        assert get_table_selected_rows(page.driver) == {1, 2}

        assert page.has_no_console_errors()

        assert page.has_no_console_errors()
Exemplo n.º 30
0
def create_table(data):
    names = []
    values = []
    data = flatten(data)

    exec_mode = data.pop('execution_mode', '')
    exec_mode = exec_mode + '_' if exec_mode != '' else exec_mode
    data.pop('name', None)

    for key, value in data.items():
        names.append(exec_mode + key)
        values.append(value)

    data = dict(
        names=names,
        values=values,
    )

    source = ColumnDataSource(data)

    columns = [
        TableColumn(field="names", title="Name"),
        TableColumn(field="values", title="Value"),
    ]

    return DataTable(source=source, columns=columns, width=800, height=280)