Esempio n. 1
0
def layout():

    date_select = DateRangeSlider(name="period",
                                  title="Period:",
                                  value=(start, end),
                                  bounds=(bounds_start, bounds_end),
                                  value_labels='show',
                                  range=(dict(days=1), None))
    date_select.on_change('value', on_date_change)

    country_select = Select(title="Host Site Country:",
                            value="World",
                            options=country_choices)
    country_select.on_change('value', on_country_change)

    controls = VBoxModelForm(_children=[
        Paragraph(text="Date Range"),
        Paragraph(text=""),  # spacing hack
        Paragraph(text=""),
        date_select,
        country_select
    ])

    vboxsmall = VBoxModelForm(_children=[controls, source_par])
    #hbox1 = HBox(children=[job_loc_plot_builder(), vboxsmall])
    #hbox2 = HBox(children=[weekday_builder(), jobtype_builder()])
    #layout = VBox(children=[hbox1, hbox2])
    layout = VBox(children=[vboxsmall])

    return layout
Esempio n. 2
0
def graphData(listTextData):
    listYear, listTTR, listRepetitionPercent, listTitle = getListYears(
        listTextData), getListTTR(listTextData), getListRepetitionPercent(
            listTextData), getListTitles(listTextData)
    # print(str(xPosnList)) # TEST
    # print(str(yPosnList)) # TEST
    # print(str(listRepetitionPercent)) # TEST
    # print(str(titleList)) # TEST
    ttrGraph = createTTRGraph(listYear, listTTR, listTitle)
    w1 = widgetbox(
        Paragraph(text="""Hover over data points to view more information"""))
    w2 = widgetbox(
        Paragraph(text="""Hover over data points to view more information"""))
    w3 = widgetbox(
        Paragraph(
            text=
            """Click the line/circle tab, legend categories, and hover over data."""
        ))
    wordRepetitionGraph = createWordRepetitionGraph(listYear,
                                                    listRepetitionPercent,
                                                    listTitle)
    wtirLineTab, wtirCircleTab = createWTIRGraph(
        listTextData, listYear, listTitle,
        "line"), createWTIRGraph(listTextData, listYear, listTitle, "circle")
    tabs = Tabs(tabs=[wtirLineTab, wtirCircleTab])

    graphs, widgets = [ttrGraph, wordRepetitionGraph, tabs], [w1, w2, w3]
    cols = []
    for i in range(0, 3):
        r = row(graphs[i], widgets[i])
        cols.append(r)
    output_file("test.html", title="Test")
    # show(column(ttrGraph, wordRepetitionGraph, wtirGraph))
    show(column(cols))
    return
Esempio n. 3
0
    def get_layout_query(self):
        heading_text="A program that displays every episode's rating for the tv_series."
        heading=Paragraph(text=heading_text,width=400)
        self.Search = Button(label="Search")
        self.btnGroupchoose = RadioButtonGroup(name='choose', labels=["By imdbID", "By Title"], active=0)
        paragraph = Paragraph(text="Search way")
        self.Parameter_input = TextInput(value="", title="ID or Title:", placeholder="ID or Title")
        self.select = Select(title="Season:", value="None", options=["None"])
        self.Status=Paragraph(text="Status:",width=200)
        self.Tvtext=Paragraph(text="Tv:",width=200)
        self.Seasontext=Paragraph(text="Season:",width=200)

        x=[]
        y=[]
        source = ColumnDataSource(data=dict(x=x, y=y))

        p = figure(x_range=x,plot_height=400,title="Season rating",
                   toolbar_location=None, tools="")

        p.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
        p.xaxis.major_label_orientation = 1

        self.Search.on_click(self.search_click)
        self.select.on_change('value',self.select_click)

        self.layout_query = layout(
            [
                [heading],
                [[widgetbox(paragraph, width=100),widgetbox(self.btnGroupchoose)],
                [widgetbox(self.Parameter_input)],
                [widgetbox(self.Search, width=100)],],
                [[self.Status,self.Tvtext,self.Seasontext],self.select],
                p
            ]
        )
 def __init__(self,Vis,Plotter):
     # setup random by selecting a seed (so that numbers are truly random)
     seed()
     # save car viewer
     self.Vis=Vis
     # save graph plotter
     self.Plotter=Plotter
     # choose a random velocity between 0.5 and 10 (steps of 0.5)
     self.v=randrange(5,100,5)/10.0
     # tell the car viewer about this choice
     self.Vis.setV(self.v)
     
     ## set up interactions
     # input for v0 or v(s)
     self.Vs = TextInput(value=str(self.v), title="Initial Velocity",width=300)
     self.Vs.on_change('value',self.getNewV)
     # choice of v0 or v(s) method
     self.VMethod = Select(title="", value="Initial Velocity",
         options=["Initial Velocity", "Distance-dependent Velocity"])
     self.VMethod.on_change('value',self.changeModel)
     # get user value for acceleration
     self.UserAcceleration = TextInput(value="", title="Acceleration :")
     # button which runs the simulation
     self.startSim = Button(label="Start",button_type="success",width=100)
     self.startSim.on_click(self.test)
     # reset button
     self.reset_button = Button(label="Reset",button_type="success")
     self.reset_button.on_click(self.Reset)
     #self.idealAcc = -self.v**2/40.0
     # checkbox for whether equations as a function of time are visible
     #self.eqVis = checkbox_group = CheckboxGroup(labels=["Show equations as a function of the time"], active=[])
     self.eqVis = CheckboxGroup(labels=["Show equations as a function of the time"], active=[])
     self.eqVis.on_change('active',self.toggleEquation)
     # save space to write equations as a function of time
     self.eqst = Paragraph(text="")
     self.eqvt = Paragraph(text="")
     # user input for t(s) to be tested against simulation
     self.UserTs = TextInput(value="", title="t(s) = ",width=200)
     # button to allow sqrt to be used in t(s)
     self.TsSqrt = Button(label="Insert: " u"\u221A",button_type="success",width=100)
     self.TsSqrt.on_click(self.addSqrtTs)
     # user input for v(s) (or a(s)) to be tested against simulation
     self.UserVs = TextInput(value="", title="v(s) = ",width=200)
     # button to allow sqrt to be used in v(s)/a(s)
     self.VsSqrt = Button(label="Insert: " u"\u221A",button_type="success",width=100)
     self.VsSqrt.on_click(self.addSqrtVs)
     # button to plot t(s) and v(s)/a(s) over simulation data
     self.TestEqs = Button(label="Check equations",button_type="success",width=100)
     self.TestEqs.on_click(self.plot_attempt)
     
     # initialise initial time and displacement
     self.t = 0
     self.s = 0
     # remember which model is being used
     self.va='v'  # v for v0 and a for v(s)
     # save layout
     self.Layout = column(row(self.Vs,self.VMethod),row(self.UserAcceleration,self.startSim),self.reset_button,self.eqVis,
         self.eqst,self.eqvt,row(self.UserTs,self.TsSqrt),row(self.UserVs,self.VsSqrt),self.TestEqs)
Esempio n. 5
0
def startserver(doc):
    file_input = FileInput(accept=".ulg, .csv")
    file_input.on_change('value', upload_new_data_sim)
    file_input2 = FileInput(accept=".ulg, .csv")
    file_input2.on_change('value', upload_new_data_real)

    intro_text = Div(text="""<H2>Sim/Real Thiel Coefficient Calculator</H2>""",
                     width=500,
                     height=100,
                     align="center")
    sim_upload_text = Paragraph(text="Upload a simulator datalog:",
                                width=500,
                                height=15)
    real_upload_text = Paragraph(
        text="Upload a corresponding real-world datalog:",
        width=500,
        height=15)
    #checkbox_group = CheckboxGroup(labels=["x", "y", "vx","vy","lat","lon"], active=[0, 1])

    sim_reverse_button = RadioButtonGroup(labels=["Sim Default", "Reversed"],
                                          active=0)
    sim_reverse_button.on_change('active',
                                 lambda attr, old, new: reverse_sim())
    real_reverse_button = RadioButtonGroup(labels=["Real Default", "Reversed"],
                                           active=0)
    real_reverse_button.on_change('active',
                                  lambda attr, old, new: reverse_real())

    simsource_static.selected.on_change('indices', simselection_change)

    # The below are in case you want to see the x axis range change as you pan. Poorly documented elsewhere!
    #ts1.x_range.on_change('end', lambda attr, old, new: print ("TS1 X range = ", ts1.x_range.start, ts1.x_range.end))
    #ts2.x_range.on_change('end', lambda attr, old, new: print ("TS2 X range = ", ts2.x_range.start, ts2.x_range.end))

    ts1.x_range.on_change(
        'end', lambda attr, old, new: change_sim_scale(ts1.x_range.start))
    ts2.x_range.on_change(
        'end', lambda attr, old, new: change_real_scale(ts2.x_range.start))

    # set up layout
    widgets = column(datatype, stats)
    sim_button = column(sim_reverse_button)
    real_button = column(real_reverse_button)
    main_row = row(widgets)
    series = column(ts1, sim_button, ts2, real_button)
    layout = column(main_row, series)

    # initialize
    update()
    doc.add_root(intro_text)

    doc.add_root(sim_upload_text)
    doc.add_root(file_input)
    doc.add_root(real_upload_text)
    doc.add_root(file_input2)
    doc.add_root(layout)
    doc.title = "Flight data"
Esempio n. 6
0
def check_missing_file(root_path, config, totalreport):

    # if not __validate_config_missing_file(config):
    #     raise Exception('Invalid Configuration')

    missing_file = pd.DataFrame(
        columns=['PID', 'FileType', 'FilePath', 'Note'])
    missing_file_table_pid = dict()

    for check in config:
        if check['check_missing_file']:
            missing_file_for_pid = __check_meta_data(root_path, check['pid'],
                                                     check['num_sensor'],
                                                     check['sensor_locations'])
            missing_file_for_pid = missing_file_for_pid.append(
                __check_hourly_data(root_path, check['pid'],
                                    check['check_annotation_file_exist'],
                                    check['check_event'], check['check_EMA'],
                                    check['check_GPS'], check['num_sensor'],
                                    check['num_annotator']))
            missing_file = missing_file.append(missing_file_for_pid)
            missing_file_for_pid.to_csv(
                os.path.join(root_path, check['pid'], 'Derived',
                             'missing_files.csv'))
            missing_file_table_pid[check['pid']] = __graph_table(
                missing_file_for_pid)
        else:
            missing_file_table_pid[check['pid']] = Paragraph(
                text='Missing File Not Checked', style={'color': 'blue'})

    if totalreport:
        missing_file.to_csv(os.path.join(root_path, 'missing_file.csv'))

    return __graph_table(missing_file), missing_file_table_pid
Esempio n. 7
0
 def section_2_lection_44_with_server(self):
     self.text_input = TextInput(value='Input text...')
     button = Button(label='Generate Text')
     self.output = Paragraph()
     button.on_click(self.update_paragraph)
     lay_out = layout([[button, self.text_input], [self.output]])
     curdoc().add_root(lay_out)
Esempio n. 8
0
def upload_file(file_name, file_content):
    import xarray as xr

    data[file_name] = xr.open_dataarray(file_name)  # to improve
    #plot_data_info = {}
    #for dim in [file_name].dims:
    #    plot_data_info[dim] = 0
    #plot_data_info["dim1"] = "x"
    #plot_data_info["dim2"] = "y"
    #plot_series_info[file_name] = plot_data_info

    #plot_series[file_name] = updatePlot(file_name)

    from bokeh.layouts import widgetbox
    from bokeh.models.widgets import Paragraph
    file_name_text = Paragraph(text=file_name, width=200, height=100)

    sliders = generateSliders(file_name)
    file_handels[file_name] = widgetbox([file_name_text] + sliders)

    from bokeh.models.widgets import Slider
    aa = Slider(start=0, end=10, step=1)
    grid = gridplot([[plot, aa], [upload], file_handels.values()])
    curdoc().clear()
    curdoc().add_root(grid)
Esempio n. 9
0
 def __init__(self):
     textHeaderTable1 = Paragraph(text='Log information')
     self.LogTable = self.createLogTable()
     self.saveLogTable = Button(label="Export data", button_type="danger")
     self.final_layout = column(textHeaderTable1, self.LogTable, self.saveLogTable)
     self.saveLogTable.on_click(self.ExportTableToCSV)
     return
 def __init__(self, number: int, name: str, gui_name: str,
              choices: List[str]):
     self.number = number
     self.name = name
     self.gui_name = gui_name
     self.choices = choices
     self.text = Paragraph(text=self.gui_name, width=150)
Esempio n. 11
0
def __graph_table(table):
    if table.shape[0] < 1:
        return Paragraph(text='No Exceptions Found', style={'color': 'blue'})
    source = ColumnDataSource(table)
    columns = []
    for name in table.columns.values:
        if pd.core.dtypes.common.is_datetime_or_timedelta_dtype(table[name]):
            columns.append(
                TableColumn(field=name,
                            title=name,
                            formatter=DateFormatter(format='%T')))
        else:
            columns.append(TableColumn(field=name, title=name))

    columns[-1].width = 1000
    # if table.shape[0] >= 9:
    #     height = 280
    # else:
    #     height = 30*table.shape[0] + 10
    height = 280
    data_table = DataTable(source=source,
                           columns=columns,
                           width=1000,
                           height=height,
                           fit_columns=True)

    return layouts.widgetbox(data_table, sizing_mode='fixed')
Esempio n. 12
0
    def create(self):

        self.sources['table'] = ColumnDataSource(dict(x=[], y=[]))
        self.sources['background'] = ColumnDataSource(dict(x=[], y=[]))
        columns = [
                TableColumn(field="x", title="ppm", formatter=NumberFormatter(format="0.00")),
                TableColumn(field="y", title="y", formatter=NumberFormatter(format="0.00"))
            ]
        self.dataTable = DataTable(source=self.sources['table'], columns=columns, reorderable=False, width=500)
        self.sources['table'].on_change('selected', lambda attr, old, new: self.rowSelect(new['1d']['indices']))
        self.sources['table'].on_change('data', lambda attr, old, new: self.dataChanged(old, new))

        self.manual = CustomButton(label="Manual Peaks", button_type="success", width=500, error="Please select area using the peak picking tool.")
        self.manual.on_click(self.manualPeakPicking)

        self.peak = CustomButton(label="Peak By Peak", button_type="primary", width=250, error="Please select area using the peak by peak tool.")
        self.peak.on_click(self.peakByPeakPicking)
        self.peakTool = CustomTapTool.Create(self.peak, tapTool=PeakByPeakTapTool, auto=True, id="peakByPeakTool")

        self.createManualTool()

        self.createDeselectButton()
        self.createDeleteButton()

        self.chemicalShiftReportTitle = Div(text="<strong>Chemical Shift Report</strong>" if getLabel(self.udic) == "13C" else "")
        self.chemicalShiftReport = Paragraph(text=self.getChemicalShiftReport(), width=500)
Esempio n. 13
0
    def tab(self, name):
        initial_line_channels = [
            self.line_checkbox.labels[i] for i in self.line_checkbox.active
        ]
        self.line_dataset = self.generate_line_dataset(self.line_data,
                                                       initial_line_channels)

        initial_scatter_channels = [
            self.scatter_checkbox.labels[i]
            for i in self.scatter_checkbox.active
        ]
        self.scatter_dataset = self.generate_scatter_dataset(
            self.scatter_data, initial_scatter_channels)

        fig = self.generate_figure(self.line_dataset, self.scatter_dataset)

        # For sectioning the figure
        for span_location in self.span_locations.itertuples():
            span = Span(location=span_location.Timestamp,
                        dimension='height',
                        line_color='red',
                        line_dash='dashed',
                        line_width=2)
            fig.add_layout(span)

            # Add hovertool trick
            hovertool_cheat = fig.line(
                [span_location.Timestamp, span_location.Timestamp], [-10, 10],
                line_width=0,
                line_color='red',
                line_dash='dashed')
            hovertool = HoverTool(renderers=[hovertool_cheat],
                                  tooltips=[(span_location.Name,
                                             str(span_location.Timestamp))])
            fig.add_tools(hovertool)

        lineplot_text = Paragraph(text='Lineplot channels')
        scatterplot_text = Paragraph(text='Scatterplot channels')
        self.update_extra_data()

        layout = column(
            self.radio_buttons,
            row(
                column(lineplot_text, self.line_checkbox, scatterplot_text,
                       self.scatter_checkbox), fig, self.extra_data_text))
        return Panel(child=layout, title=name)
 def __init__(self, number: int, name: str, gui_name: str,
              options: List[str]):
     self.number = number
     self.name = name
     self.gui_name = gui_name
     self.options = options
     self.text = Paragraph(text=self.gui_name, width=150)
     self.make_children_incompatible()
Esempio n. 15
0
 def section_2_lection_44_without_server(self):
     output_file("simple_bockeh.html")
     self.text_input = TextInput(value='Input text...')
     button = Button(label='Generate Text')
     self.output = Paragraph()
     button.on_click(self.update_paragraph)
     lay_out = layout([[button, self.text_input], [self.output]])
     show(lay_out)
Esempio n. 16
0
 def __init__(self, lda_path, title):
     self.space = Paragraph(text='')
     self.para = Div(
         text=
         '<h2 style="color:#3b3a39;text-align:center;font-size:150%;font-family:Times New Roman;">{}</h1>'
         .format(title),
         width=900)
     self.div = Div(text='{}'.format(self.read_file(lda_path)),
                    width=900,
                    height=500)
Esempio n. 17
0
    def build_heatmap_figure(self):
        names = ["1", "2", "3"]
        p = figure(
            title="",
            x_axis_location="below",
            y_axis_location="right",
            tools="hover,save",
            toolbar_location="above",
            x_range=list(reversed(names)),
            y_range=names,
            tooltips=[
                ('IDs', '@yid, @xid'),
                # ('names', '@yname, @xname'),
                ('Sizes', '@ysize, @xsize'),
                ('Overlap', '@overlap')
            ])

        p.plot_width = 700
        p.plot_height = 550
        p.min_border_left = 100
        p.grid.grid_line_color = None
        p.axis.axis_line_color = None
        p.axis.major_tick_line_color = None
        p.axis.major_label_text_font_size = "5pt"
        p.axis.major_label_standoff = 0
        p.xaxis.major_label_orientation = np.pi / 3

        # self.dsources["audiences"].on_change("data", self.data_changed)
        # color_mapper = LinearColorMapper(palette="Magma256", low=0, high=1)
        self.rect = p.rect('xname',
                           'yname',
                           0.9,
                           0.9,
                           source=self.osource,
                           fill_color='color',
                           alpha=0.4,
                           line_color=None,
                           hover_line_color='black',
                           hover_color='color')
        self.text = p.text(x='xname',
                           y='yname',
                           text='overlap_perc_txt',
                           text_font_size='0.4em',
                           text_align='center',
                           text_baseline='middle',
                           color='color',
                           source=self.osource)

        title = Paragraph(
            text=""" Overlap percentages are relative to y-axis audience""",
            width=600)

        self.heatmap_fig = p

        return column(title, p)
Esempio n. 18
0
def init():
    output_notebook()
    display(Javascript(_init_js))
    but = '<img src="resources/show.png" width="34" height="25" style="display: inline" alt="Slideshow button" title="Enter/Exit RISE Slideshow">'
    txt = Div(text='<h2>You can now start the slideshow!</h3>' +
                   f'<h3 style="margin: 0.5em 0;">Just click the RISE slideshow button above - the one that looks like: {but}<br/>' +
                   '(or you can press alt+R on your keyboard instead if you prefer).</h3>')
    clearbutton = Button(label="Clear")
    clearbutton.js_on_click(CustomJS(code='primes_clear();'))
    cleartext = Paragraph(text='Clear all plots and outputs (e.g. before restarting slideshow).')
    increm = Toggle(label='Incremental', active=True)
    increm.js_on_click(CustomJS(code='primes_incremental(cb_obj.active)'))
    incremtext = Paragraph(text='Update timing plots incrementally (disable for static slide show).')
    repeats = Slider(start=1, end=10, value=3)
    repeats.js_on_change('value', CustomJS(code='primes_repeats(cb_obj.value)'))
    repeatstext = Paragraph(text='Repeats for timing measurements (higher is more accurate, but slower).')
    controls = layout([[clearbutton, cleartext],
                       [increm, incremtext],
                       [repeats, repeatstext]])
    show(column(txt, controls, sizing_mode='stretch_width'))
Esempio n. 19
0
def hello():
    global layout_done

    # create pywrapbokeh object
    widgets = WrapBokeh("/", app.logger)

    # see https://github.com/Knio/dominate
    widgets.dominate_document()  # create dominate document
    with widgets.dom_doc.body:  # add css elements here...
        style(raw("""body {background-color:powderblue;}"""))

    # check/get page metrics and get args for the page
    args, _redirect_page_metrics = widgets.process_req(request)
    if not args: return _redirect_page_metrics
    app.logger.info("{} : args {}".format("/", args))

    selected_fruit = args.get("sel_fruit", "Unknown")
    if selected_fruit is not "Unknown":
        selected_fruit = fruits[int(selected_fruit)][1]  # get name of fruit

    # check args here for actions that would redirect to another page
    # if args.get( name ) == something: return redirect( new_url )

    # add bokeh widgets to the pywrapbokeh object
    # - order does not matter
    # - API pattern,
    #   - WrapBokeh.add( <name_of_widget>, <bokeh API>(..., [css_classes=[<name_of_widget>]]))
    #   - if you want to affect widget properties (color, font size, etc) you need to set css_classes
    widgets.add(
        "sel_fruit",
        Select(options=fruits,
               value=None,
               title="Select Fruit",
               css_classes=['sel_fruit']))
    widgets.add_css("sel_fruit", {'select': {'background-color': "#6495ED"}})

    widgets.init()

    # start a bokeh layout
    doc_layout = widgets.layout()

    # append items to the document
    doc_layout.children.append(
        column(
            Div(text="""<h1>Hello World!</h1>"""),
            Paragraph(
                text="""Your favorite fruit is {}""".format(selected_fruit))))

    # append a pywrapbokeh widget
    doc_layout.children.append(widgets.get("sel_fruit"))

    # render page
    return widgets.render(doc_layout)
Esempio n. 20
0
    def __init__(self, Sliders):
        self.Vll, self.Vul, self.Lul = Sliders

        textHeaderTable1 = Paragraph(text='Network Overview')
        self.OverviewTable = self.createOverviewTable()
        self.saveOverview = Button(label="Export data", button_type="danger")
        textHeaderTable2 = Paragraph(text='Voltage Constraint Elements')
        self.VCTable = self.createVCTable()
        self.saveVCTable = Button(label="Export data", button_type="danger")
        textHeaderTable3 = Paragraph(text='Current Constraint Elements')
        self.CCTable = self.createCCTable()
        self.saveCCTable = Button(label="Export data", button_type="danger")
        L1 = column(textHeaderTable1, self.OverviewTable, self.saveOverview)
        L2 = column(textHeaderTable2, self.VCTable, self.saveVCTable)
        L3 = column(textHeaderTable3, self.CCTable, self.saveCCTable)

        self.saveOverview.on_click(self.ExportOverview)
        self.saveVCTable.on_click(self.ExportVCTable)
        self.saveCCTable.on_click(self.ExportCCTable)

        self.final_layout = column(L1, L2, L3)
        return
Esempio n. 21
0
	def tab(self, name):
		fig = figure(
				title='Lomb Scargle Periodogram',
				plot_width=conf.PLOTWIDTH,
				plot_height=conf.PLOTHEIGHT,
				x_axis_label='Frequency',
				y_axis_label='Power'
				)

		fig.line('frequencies', 'power', source=self.plot_data, line_width=2)

		layout = column(Paragraph(text='Lomb Scargle Periodogram of LL-RA physio'), fig)
		return Panel(child=layout, title=name)
Esempio n. 22
0
    def create_fig(self, sources):
        """


        """

        if self._type == 'PreText':
            fig = PreText(text=self._text,  **self._args)
        elif self._type == 'Div':
            fig = Div(text=self._text, **self._args)
        elif self._type == 'Paragraph':
            fig = Paragraph(text=self._text, **self._args)

        return fig
Esempio n. 23
0
def create_page(data):
    plot = create_plot(data)
    title = data.variable_metadata['long_name']
    summary = data.dataset_metadata['summary']
    dataset_metadata = json2html.convert(json=data.dataset_metadata)
    variable_metadata = json2html.convert(json=data.variable_metadata)
    title_div = Div(text="""<h1>
                                <b>
                                    {title}
                                </b>
                            </h1>""".format(title=title))

    abstract_text = Div(text="""<details>
                                    <summary>
                                        Summary
                                    </summary>
                                    <p>
                                        {summary}
                                    </p>
                                </details>""".format(summary=summary),
                        width=400,
                        height=200)

    dataset_metadata_div = Div(text="""<details>
                                           <summary>
                                               Dataset Metadata
                                           </summary>
                                           <p>
                                               {dataset_metadata}
                                           </p>
                                        </details>""".format(dataset_metadata=dataset_metadata),
                               width=300,
                               height=100)

    variable_metadata_div = Div(text="""<details>
                                            <summary>
                                                Variable Metadata
                                            </summary>
                                            <p>
                                                {variable_metadata}
                                            </p>
                                        </details>""".format(variable_metadata=variable_metadata),
                                width=200,
                                height=100)

    plot_caption = Paragraph(text="""This text can be a figure caption.""",
                             width=200,
                             height=100)
    return Column(title_div, abstract_text, plot, plot_caption, variable_metadata_div, dataset_metadata_div)
Esempio n. 24
0
def classification_tab():
    pairs = [["stackoverflow.com", "academia.stackexchange.com"],["stackoverflow.com", "softwareengineering.stackexchange.com"]]
    
    # pretrained classification models
    nbsoac = load("app/models/10k_so_ac_bayes_model.joblib")
    nbsose = load("app/models/10k_so_se_bayes_model.joblib")
    svmsoac = load("app/models/10k_so_ac_SVM_model.joblib")
    svmsose = load("app/models/10k_so_se_SVM_model.joblib")
    
    learning_type = RadioButtonGroup(labels=["Bayes", "Support Vector Machine"], active=0)
    
    site_pair = RadioButtonGroup(labels=["Stack Overflow/Academia", "Stack Overflow/Software Engineering"], active=0)
    
    tai = TextAreaInput(value="", rows=6, title="Enter a post message:")
    
    predict = Button(label="Predict", button_type="success")
    
    p = Paragraph(text="""Your Site Prediction will be displayed here""",
            width=300, height=50)
    
    def make_prediction():
        lt = learning_type.active
        sp = site_pair.active
        model = None
        if lt == 0:
            if sp == 0:
                model = nbsoac
            else:
                model = nbsose
        else:
            if sp == 0:
                model = svmsoac
            else:
                model = svmsose
        prediction = model.predict([tai.value])[0]
        p.text = "Message belongs to site: " + pairs[sp][prediction - 1]


    predict.on_click(make_prediction)

    # Put controls in a single element
    controls = WidgetBox(learning_type, site_pair, tai, predict, p)

    # Create a row layout
    layout = row(controls)

    tab = Panel(child=layout, title='Message Site Classification')
    
    return tab
Esempio n. 25
0
def modify_doc(doc):
    p = Paragraph(text=""" """, width=800, height=100)

    def callback(attr, old, new):
        print(
            "called"
        )  # This outputs to console (In Jupyter goes back to UI via Jupyter websocket)
        p.text = "{}:{}->{}".format(
            attr, old, new)  # This outputs to widget UI via bokeh websocket

    slider_bokeh = Slider(start=0, end=100, value=1, step=.1, title="Stuff")

    # widget on_change event can only with bokeh server
    slider_bokeh.on_change("value", callback)
    doc.add_root(widgetbox(p, slider_bokeh))
Esempio n. 26
0
    def __init__(self):
        # widgets
        self.instructions = Paragraph(text='Enter a word')
        self.text_input = TextInput(value='')
        self.submit_button = Button(label='Submit', button_type="success")
        self.figure = Figure()
        self.projector = UMAP()
        self.layout = column(column(self.instructions,
                                    self.text_input,
                                    self.submit_button,
                                    sizing_mode='fixed'),
                             column(self.figure, sizing_mode='stretch_both'),
                             sizing_mode='stretch_both')

        self.submit_button.on_click(self.handle_submit)
Esempio n. 27
0
    def __init__(self, image_path, text):
        self.space = Paragraph(text='')
        self.para = Div(
            text=
            '<h2 style="color:#3b3a39;text-align:center;font-size:150%;font-family:Times New Roman;">{}</h1>'
            .format(text),
            width=900)

        self.div = Div(
            text=
            '<img src="{}" alt="{}" border="0" height="500" width="800"></img>'
            .format(image_path, text),
            width=900,
            height=500)
        self.div.css_classes = ["custom"]
Esempio n. 28
0
 def make_plot(self, dataframe):
     self.source = ColumnDataSource(data=dataframe)
     self.title = Paragraph(text=TITLE)
     self.data_table = DataTable(
         source=self.source,
         width=390,
         height=275,
         columns=[
             TableColumn(field="zipcode", title="Zipcodes", width=100),
             TableColumn(field="population",
                         title="Population",
                         width=100,
                         formatter=NumberFormatter(format="0,0")),
             TableColumn(field="city", title="City")
         ])
     return column(self.title, self.data_table)
Esempio n. 29
0
    def make_parameters_table():
        """Создание поля ввода данных для подгонки: начальное значение, fix и т.д."""
        name = fit_function_selection_widget.value

        t_width = 10
        t_height = 12

        rows = [
            row(Paragraph(text="name", width=t_width, height=t_height),
                Paragraph(text="Fix", width=t_width, height=t_height),
                Paragraph(text="Init value", width=t_width, height=t_height),
                Paragraph(text="step (error)", width=t_width, height=t_height),
                Paragraph(text="limits", width=t_width, height=t_height),
                Paragraph(text="lower_limit", width=t_width, height=t_height),
                Paragraph(text="upper_limit", width=t_width, height=t_height))
        ]

        fit_handler["input_fields"] = {}

        for param, value in fit.get_function_params(name):
            fit_handler["input_fields"][param] = {}
            fit_handler["input_fields"][param]["fix"] = CheckboxGroup(
                labels=[""], width=t_width, height=t_height)
            fit_handler["input_fields"][param]["Init value"] = TextInput(
                width=t_width, height=t_height, value=str(value))
            fit_handler["input_fields"][param]["step (error)"] = TextInput(
                width=t_width, height=t_height, value='1')
            fit_handler["input_fields"][param]["limits"] = CheckboxGroup(
                labels=[""], width=t_width, height=t_height)
            fit_handler["input_fields"][param]["lower_limit"] = TextInput(
                width=t_width, height=t_height)
            fit_handler["input_fields"][param]["upper_limit"] = TextInput(
                width=t_width, height=t_height)

            rows.append(
                row(Paragraph(text=param, width=t_width, height=t_height),
                    fit_handler["input_fields"][param]["fix"],
                    fit_handler["input_fields"][param]["Init value"],
                    fit_handler["input_fields"][param]["step (error)"],
                    fit_handler["input_fields"][param]["limits"],
                    fit_handler["input_fields"][param]["lower_limit"],
                    fit_handler["input_fields"][param]["upper_limit"]))

        return column(rows)
Esempio n. 30
0
    def bokeh2(self):

        # create some widgets
        button = Button(label="Say HI")
        input = TextInput(value="Bokeh")
        output = Paragraph()

        # add a callback to a widget
        def update():
            output.text = "Hello, " + input.value

        button.on_click(update)

        # create a layout for everything
        layout = column(button, input, output)

        # add the layout to curdoc
        curdoc().add_root(layout)