Exemple #1
0
 def __init__(self):
     self.currentConnection = None
     self.currentDB = ''
     self.tableOut = Output(layout=Layout(max_width='30%'))
     self.schemaOut = Output()
     self.tableSelect = Dropdown(
         options=[''],
         value='',
         description='Table:',
         disabled=False,
     )
     self.databaseSelect = Dropdown(
         options=['sqlite-sakila', 'chinook'],
         value='sqlite-sakila',
         description='Database:',
         disabled=False,
     )
     self.tableSelect.observe(self.tableChange, names='value')
     self.databaseSelect.observe(self.databaseChange, names='value')
     self.displayDatabases = VBox([
         HBox(
             [self.tableOut,
              VBox([self.databaseSelect, self.tableSelect])]),
         self.schemaOut
     ])
     self.changeDatabase()
Exemple #2
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)
Exemple #3
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()
Exemple #4
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()
Exemple #5
0
    def __build_gui(self):

        children = []
        titles = ['materials']
        item_layout = Layout(margin='20px', flex_flow='row wrap')

        if self.__lp:

            box_materials = HBox(layout=item_layout)

            for index, color in self.__lp.get_colors().items():
                editor = make_color_editor(color, index, no_name=True)
                if editor:
                    editor.observe(self.__on_editor_changed(color))
                    box_materials.children = (*box_materials.children, editor)

            children.append(
                VBox([self.__menu('materials', box_materials), box_materials]))

            for category_name in self.__lp.get_category_names():

                box_scalars = HBox(layout=item_layout)
                box_curves = HBox(layout=item_layout)

                for scalar in self.__lp.get_category_scalars(category_name):

                    editor = make_scalar_editor(scalar, False)
                    if editor:
                        editor.observe(self.__on_editor_changed(scalar))
                        box_scalars.children = (*box_scalars.children, editor)

                for param in self.__lp.get_category_graphicalparameters(
                        category_name):

                    editor = make_curve_editor(param, False)
                    if editor:
                        editor.observe(self.__on_editor_changed(param))
                        box_curves.children = (*box_curves.children, editor)

                children.append(
                    VBox([
                        self.__menu('scalars', box_scalars,
                                    category_name), box_scalars,
                        self.__menu('curves', box_curves, category_name),
                        box_curves
                    ]))
                titles.append(category_name)

        return (children, titles)
Exemple #6
0
    def __init__(self, lp, filename='', **kwargs):

        self.__lp = lp
        self.filename = filename
        self.__accordion = Accordion()
        self.__auto_apply_cbx = Checkbox(description='Auto apply')
        self.__auto_save_cbx = Checkbox(description='Auto save')
        self.__apply_btn = Button(description='Apply changes')
        self.__save_btn = Button(description='Save changes')
        self.__add_category_btn = Button(description='Add category')
        self.__add_category_txt = Text(placeholder='category name')
        self.__initialize()

        super().__init__([
            VBox([
                HBox([
                    HBox((self.__apply_btn, self.__auto_apply_cbx)),
                    HBox((self.__save_btn, self.__auto_save_cbx)),
                    HBox((self.__add_category_btn, self.__add_category_txt))
                ],
                     layout=Layout(flex_flow='row wrap', margin='5px')),
                self.__accordion
            ],
                 layout=Layout(margin='5px'))
        ], **kwargs)
Exemple #7
0
def columns_output_widget(df):
    col_acc = columns_accordion_widget(df)

    # set an observer handler
    # col_acc.observe(accordion_handler)
    co_widget = VBox([col_acc])
    return co_widget
Exemple #8
0
def glimpse_output_widget(df):
    stats_info = summary_stats_widget(df)
    table_info = table_info_widget(df)
    glimpse_output = VBox([table_info, stats_info],
                          layout=layout,
                          display='flex')
    return glimpse_output
    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)
Exemple #10
0
 def __call__(self, parameterized, **params):
     self.p = param.ParamOverrides(self, params)
     self._widgets = {}
     self.parameterized = parameterized
     self.blocked = self.execute is not None
     widgets = self.widgets()
     vbox = VBox(children=widgets)
     display(vbox)
     if self.execute:
         self.event_loop()
    def __init__(self,
                 view_pixel_cubes=True,
                 view_coordinates=True,
                 fig_size=(12, 8),
                 coordinates_history=False):
        self._fig_size = fig_size
        self._view_pixel_cubes = view_pixel_cubes
        self._view_coordinates = view_coordinates
        self._coordinates_history = coordinates_history

        # Fields
        self.fig = self.canvas = self.axes = None

        # Make widgets
        rgb_widgets = []
        for text in ["Red", "Green", "Blue"]:
            rgb_widgets.append(
                FloatSlider(
                    value=0.0,
                    min=0,
                    max=1.0,
                    step=0.01,
                    description='{}:'.format(text),
                    disabled=False,
                    continuous_update=False,
                    orientation='horizontal',
                    readout=True,
                    readout_format='.2f',
                ))
        self.rgb_widgets = rgb_widgets

        # Make widget box
        self.rgb_box = VBox(rgb_widgets)

        # Assign pixel-viewer to sliders events
        for val in self.rgb_box.children:
            val.observe(self.show_pixel)

        # Get RGB-values
        self.rgb = [val.value for val in self.rgb_widgets]

        # Start when widgets are displayed
        self.rgb_box.on_displayed(self.show_pixel)
Exemple #12
0
    def history_ui():
        date_wid = widgets.DatePicker(description='Pick a Date',
                                     value=dt.datetime.today(),
                                     disabled=False)




        def filter_data(date):
            d = read(dr['MAT']+'Timesheet.pkl')
            date=dt.datetime(date.year,date.month,date.day)
            c1=(d['From']>date)*(d['To']<=date+pd.to_timedelta('23:59:59'))
            c11=d[c1]

            idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1]
            c12=d.loc[idx]
            c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))]

            for j in ['From','To']:
                c11[j]=[c11[j].iloc[i].strftime('%H:%M:%S') for i in range(len(c11[j]))]

            c13=pd.concat((c10,c11))
            display(c13)

        def total_df(date):
            d = read(dr['MAT']+'Timesheet.pkl')
            date=dt.datetime(date.year,date.month,date.day)
            c1=(d['From']>pd.to_datetime(date))*(d['To']<=pd.to_datetime(date)+pd.to_timedelta('23:59:59'))
            c11=d[c1]

            idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1]
            c12=d.loc[idx]
            c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))]
            c13=pd.concat((c10,c11))

            acts=sorted(list(set(c13['Activity'])))

            act1=pd.Series(acts)
            tot=[c13[c13['Activity']==j]['Duration'].sum() for j in act1]
            tot1=pd.Series(tot)
            tot2=pd.DataFrame({'Activity': act1,'Total Duration':tot1})
            tot2 = tot2.sort_values(by='Total Duration',ascending=False)
            tot2 = tot2.reset_index(drop=True)
            display(tot2)



        out1 = widgets.interactive_output(filter_data, {'date': date_wid})
        out2 = widgets.interactive_output(total_df, {'date': date_wid})

        ui = VBox([date_wid,HBox([out1,out2])])

        return ui
Exemple #13
0
 def displayResponse(self):
     '''
     查看结果
     :return: 
     '''
     if not self.cf.isReady():
         print(Fore.RED + '配置项尚未初始化!')
     else:
         self.htmResult = HTML(value = '')
         self.gdResult = qgrid.show_grid(pd.DataFrame([]))
         boxResult = VBox([self.htmResult, self.gdResult])
         display(boxResult)
    def __init__(self, fig_size=(10, 6)):
        self.fig_size = fig_size
        files = list(sorted(list(storage_dir.glob("*.npy"))))
        file_names = [val.name for val in files]

        self.start_button = Button(
            value=False,
            description='Show!',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            icon='')

        self.w_dropdown = Dropdown(options=file_names,
                                   value=file_names[0],
                                   description='File:',
                                   disabled=False,
                                   layout={"margin": "10px"})

        style = {'description_width': 'initial'}
        self.w_camera_position = RadioButtons(
            options=['xyz', 'x', 'y', "z"],
            description='Camera viewpoint:',
            disabled=False,
            style=style,
        )

        self.w_show_mean = Checkbox(
            value=False,
            description='Show Averages',
            disabled=False,
            # button_style='',  # 'success', 'info', 'warning', 'danger' or ''
            # icon='check',
            layout={
                "justify_content": "space-around",
                'width': '250px',
                "margin": "10px"
            })

        self.fig = None
        self.ax = None

        self.container = VBox((
            HBox([self.w_dropdown, self.start_button]),
            HBox(
                [self.w_show_mean, self.w_camera_position],
                layout=Layout(justify_content="space-around", width="100%"),
            ),
        ), )

        # Assign viewer to events
        self.start_button.on_click(self.update)
Exemple #15
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
Exemple #16
0
 def __init__(self, qNo):
     self.qNo = qNo
     self.qOut = Output()
     self.queryArea = Textarea(
         value='',
         placeholder='Type your Query here',
         description='',
         disabled=False,
         #layout = Layout(max_width='30%')
     )
     self.execute = Button(
         description='Execute',
         disabled=False,
         button_style='',  # 'success', 'info', 'warning', 'danger' or ''
         tooltip='Execute',
         #layout = Layout(max_width='20%')
     )
     self.resultMessage = Output()
     self.execute.on_click(self.executeQuery)
     self.yourOutput = Output(layout=Layout())
     self.expectedOutput = Output(layout=Layout())
     self.yourOut = Output()
     self.expectOut = Output()
     with self.yourOut:
         display(HTML('<b>Your Ouput:</b>'))
     with self.expectOut:
         display(HTML('<b>Expected Ouput:</b>'))
     self.disPlayWindow = VBox([HBox([self.qOut,self.queryArea,self.execute,self.resultMessage]),\
     VBox([VBox([self.expectOut,self.expectedOutput]\
                ),VBox([self.yourOut,self.yourOutput])])]\
                               ,layout = Layout(width='80%'))
     self.qset = pd.read_csv('questions.csv')
     self.questionData = self.qset.loc[self.qset.qNo == self.qNo]
     expected = self.getExpected()
     with self.expectedOutput:
         display(expected)
     with self.qOut:
         print(self.questionData.question.values[0])
Exemple #17
0
    def displayExecute(self):
        '''
        执行请求
        :return: 
        '''
        if not self.cf.isReady():
            print(Fore.RED + '配置项尚未初始化!')
        elif self.env.tester is not None:
            self.btnExecute = Button(description = '执行请求', button_style = 'primary')
            btnCopy = Button(description = '复制请求链接')

            self.btnExecute.on_click(self.on_execute_clicked)
            btnCopy.on_click(self.on_copy_clicked)

            self.htmExecute = HTML(value = '')
            # boxExecute = VBox([Box([self.btnExecute, btnCopy]), self.htmExecute])
            boxExecute = VBox([self.btnExecute, self.htmExecute])

            display(boxExecute)
Exemple #18
0
    def __add_category(self, name):
        if not name or name in self.__lp.get_category_names():
            return

        item_layout = Layout(margin='20px', flex_flow='row wrap')
        acc = self.__accordion
        box_scalars = HBox(layout=item_layout)
        box_curves = HBox(layout=item_layout)

        acc.children = (*self.__accordion.children,
                        VBox([
                            self.__menu('scalars', box_scalars, name),
                            box_scalars,
                            self.__menu('curves', box_curves, name), box_curves
                        ]))
        acc.set_title(len(acc.children) - 1, name)
        self.__lp.add_category(name)
        if self.__auto_save:
            self.__save()
    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)
Exemple #20
0
def predictors_widget(preds, target):
    # plen = len(preds)
    logger.debug("inside predictors_widget")
    preds_btn = []
    for key, val in preds:
        btn = Button(description='%s : %s' % (key, val),
                     disabled=False,
                     button_style='',
                     tooltip=str(val),
                     layout=predbtn_layout,
                     display='flex',
                     flex_flow='column',
                     align_items='stretch')  # , icon='check')
        # set btn color
        btn.style.button_color = 'lightgreen'
        preds_btn.append(btn)

    logger.info("Done creating predictor buttons")

    head_out = HTML(
        "<h3> Predictors of `%s` with their predictive power </h3>" % (target))
    preds_btn.insert(0, head_out)
    children = preds_btn
    preds_widget = VBox(children, layout=pred_wiget_layout)
    bar_w = pp_barplot_widget(preds)
    # set width of bar plot
    bar_w.layout.width = 450

    rightside_vis = HBox([bar_w], display='flex', align_items="stretch")
    #rightside_vis.layout.align_items = 'center'
    rightside_vis.layout.flex = "1.5 1 auto"
    rightside_vis.layout.width = "60%"
    rightside_vis.layout.border = '1px solid black'
    preds_widget.layout.flex = "1 1 auto"
    preds_widget = HBox([preds_widget, rightside_vis],
                        layout=layout,
                        display='flex')
    return preds_widget
    def __init__(self):
        self.data_titles = []
        self.data_scores = []
        self.afinn = None

        self.select = Dropdown(
            options={
                'Politiken.dk': 0,
                'DR.dk': 1,
                'BT.dk': 2,
                'Information.dk': 3,
                'Børsen.dk': 4,
                'Ekstrabladet.dk': 5
            },
            value=0,
            description='Vælg nyhedskilde:',
            disabled=False,
            layout=Layout(width='300px'),
            style={'description_width': '130px'},
        )

        self.container = Output(value="", )

        self.submit_button = Button(
            value=False,
            description='Indlæs nyheder',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Få nyheder fra RSS-feed og lav sentiment-analyse',
            icon='')

        self.widget_box = VBox(
            (self.select, self.submit_button, self.container), )

        self.submit_button.on_click(self._do_sentiment_analysis)
    def __init__(self):
        self.afinn = Afinn(language="da")
        self.speeches_names = [('2018 (Lars Løkke Rasmussen)', '2018'),
                               ('2017 (Lars Løkke Rasmussen)', '2017'),
                               ('2016 (Lars Løkke Rasmussen)', '2016'),
                               ('2015 (Lars Løkke Rasmussen)', '2015'),
                               ('2014 (Helle Thorning-Schmidt)', '2014'),
                               ('2013 (Helle Thorning-Schmidt)', '2013'),
                               ('2012 (Helle Thorning-Schmidt)', '2012'),
                               ('2011 (Helle Thorning-Schmidt)', '2011'),
                               ('2010 (Lars Løkke Rasmussen)', '2010'),
                               ('2009 (Lars Løkke Rasmussen)', '2009'),
                               ('2008 (Anders Fogh Rasmussen)', '2008'),
                               ('2007 (Anders Fogh Rasmussen)', '2007'),
                               ('2006 (Anders Fogh Rasmussen)', '2006'),
                               ('2005 (Anders Fogh Rasmussen)', '2005'),
                               ('2004 (Anders Fogh Rasmussen)', '2004'),
                               ('2003 (Anders Fogh Rasmussen)', '2003'),
                               ('2002 (Anders Fogh Rasmussen)', '2002'),
                               ('2001 (Poul Nyrup Rasmussen)', '2001'),
                               ('2000 (Poul Nyrup Rasmussen)', '2000'),
                               ('1999 (Poul Nyrup Rasmussen)', '1999'),
                               ('1998 (Poul Nyrup Rasmussen)', '1998'),
                               ('1997 (Poul Nyrup Rasmussen)', '1997')]
        self.speeches = {}
        self.speeches_sentiments = {}

        self.select = Dropdown(
            options={
                '2018 (Lars Løkke Rasmussen)': 0,
                '2017 (Lars Løkke Rasmussen)': 1,
                '2016 (Lars Løkke Rasmussen)': 2,
                '2015 (Lars Løkke Rasmussen)': 3,
                '2014 (Helle Thorning-Schmidt)': 4,
                '2013 (Helle Thorning-Schmidt)': 5,
                '2012 (Helle Thorning-Schmidt)': 6,
                '2011 (Helle Thorning-Schmidt)': 7,
                '2010 (Lars Løkke Rasmussen)': 8,
                '2009 (Lars Løkke Rasmussen)': 9,
                '2008 (Anders Fogh Rasmussen)': 10,
                '2007 (Anders Fogh Rasmussen)': 11,
                '2006 (Anders Fogh Rasmussen)': 12,
                '2005 (Anders Fogh Rasmussen)': 13,
                '2004 (Anders Fogh Rasmussen)': 14,
                '2003 (Anders Fogh Rasmussen)': 15,
                '2002 (Anders Fogh Rasmussen)': 16,
                '2001 (Poul Nyrup Rasmussen)': 17,
                '2000 (Poul Nyrup Rasmussen)': 18,
                '1999 (Poul Nyrup Rasmussen)': 19,
                '1998 (Poul Nyrup Rasmussen)': 20,
                '1997 (Poul Nyrup Rasmussen)': 21
            },
            value=0,
            description='Vælg talen:',
            disabled=False,
            layout=Layout(width='400px'),
            style={'description_width': '100px'},
        )

        self.container = Output(value="", )

        self.submit_button = Button(
            value=False,
            description='Indlæs talen',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Indlæs statsministerens tale og lav sentiment-analyse',
            icon='')

        self.widget_box = VBox(
            (self.select, self.submit_button, self.container), )

        self.submit_button.on_click(self._do_sentiment_analysis)
Exemple #23
0
input_lat = BoundedFloatText(value=0.0,
                             min=-99999999999999,
                             max=999999999999999,
                             step=0.0001,
                             description='Latitude:',
                             disabled=False)

input_lon = BoundedFloatText(value=0.0,
                             min=-99999999999999,
                             max=9999999999999,
                             step=0.0001,
                             description='Longitude:',
                             disabled=False)

use_my_own_location = Accordion(
    children=[VBox([check_own, input_lat, input_lon])])

#Upload shapefile:
check_shapefile = Checkbox(
    value=False,
    description='Use shapefile from shapefile_input folder:',
    disabled=False,
    indent=False,
    style={'description_width': 'initial'})

shapefile_loc = Text(
    value='shapefile_inputs/',
    placeholder='Enter the name of the shapefile in the folder',
    description='Name of shapefile:',
    disabled=False,
    style={'description_width': 'initial'})
Exemple #24
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()
Exemple #25
0
    def ana_ui():
        out_0 = widgets.Output()
        out_1 = widgets.Output()
        out_2 = widgets.Output()
        out_3 = widgets.Output()

        def filter_data(k,date):
            date=dt.datetime(date.year,date.month,date.day)
            c1=(d['From']>pd.to_datetime(date))*(d['To']<=pd.to_datetime(date)+pd.to_timedelta('23:59:59'))

            c11=d[c1]
            idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1]
            c12=d.loc[idx]
            c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))]
            c13=pd.concat((c10,c11))

            c2=c13[c13['Activity']==k]

            return c2

        def update_mat(k,mat,tot,date):
            c11=filter_data(k,date)
            tot[date]=c11['Duration'].sum()

            mat[date]=np.zeros(1440)
            ix=[int(np.round(i.total_seconds()/60)) for i in (c11['From']-date)]
            iy=[int(np.round(i.total_seconds()/60)) for i in (c11['To']-date)]
            for i,j in zip(ix,iy):
                if i<0:
                    mat[date][0:j]=1
                    date1=date-dt.timedelta(1)
                    date1=dt.datetime(date1.year,date1.month,date1.day)
                    if date1 >= dt.datetime(date_from.value.year,date_from.value.month,date_from.value.day):
                        ii=i+1440
                        mat[date1][ii:]=1
                else:
                    mat[date][i:j]=1


        def gen_mat(k,from_date,to_date):
            dates = pd.date_range(from_date,to_date)
            mat={}
            tot={}
            for date in dates:
                date=dt.datetime(date.year,date.month,date.day)
                update_mat(k,mat,tot,date)

            return mat,tot

        def plot_ts(k,tot):
            nmin={i.strftime('%a, %d %b'):tot[i].total_seconds()/60. for i in tot}

            a1=pd.Series(tot)
            a33 = pd.Series(nmin)
            a33 = a33.fillna(0)
            v=[str(tot[i])[7:] for i in tot]

            try:

                title = '%s\nMean = %s\n Regularity = %4.1f %% \n Maximum = %s on %s\n Minimum = %s on %s ' % (
                                k, str(a1.mean())[7:15], 100 * len(a33[a33 > 0]) / len(a33),
                                str(a1[a1 > dt.timedelta(0)].max())[7:15], a33[a33 > 0].argmax(),
                                str(a1[a1 > dt.timedelta(0)].min())[7:15], a33[a33 > 0].argmin())

            except ValueError:
                title = 'No \n %s \n Activitiy ' %(k)

            fig, ax = plt.subplots(figsize=(16, 8))
            plt.subplots_adjust(top=0.8, bottom=0.25)
            a33.plot.bar(width=1, ax=ax, color='g')
            ax.set_ylabel('Minutes', fontweight='bold')

            for j, i in enumerate(ax.patches):
                            if v[j] != '00:00:00':
                                if a33[j] < 0.2 * a33[a33 > 0].max():
                                    ax.text(i.get_x() + 0.45,
                                            1.5 * a33[j],
                                            v[j],
                                            fontsize=10,
                                            color='blue',
                                            rotation=90)
                                else:
                                    ax.text(i.get_x() + 0.45,
                                            0.1 * a33[j],
                                            v[j],
                                            fontsize=10,
                                            color='yellow',
                                            rotation=90)

            fig.suptitle(title, fontsize=18, fontweight='bold')
            fig.savefig(dr['FIG']+'ts.jpg',dpi=72)
            plt.close()
            return dr['FIG']+'ts.jpg'

        def plot_matrix(mat):
            dd1=np.zeros((len(mat),1440))
            for i,j in enumerate(mat):
                dd1[i,:]=mat[j]

            freq=100*(len(np.where(dd1.sum(axis=1)>0)[0])/dd1.shape[0])
            fig,ax=plt.subplots(figsize=(15,6))
            ax.imshow(dd1,aspect='auto',cmap=mpl.colors.ListedColormap(['white','g']))
            labels=[j.strftime('%a %d %b') for j in mat]
            plt.yticks(range(len(mat)),labels);
            xticks=np.arange(60,1440,60)
            xticklabels=np.arange(1,24)
            ax.set_xlabel('Time(hours)',fontweight='bold')
            ax.set_ylabel('Day',fontweight='bold')
            plt.xticks(xticks,xticklabels);
            ax.grid(color='y')
            ax.grid('off')
            fig.suptitle('Time Matrix of %s\nDaily frequency(Percent) = %4.1f' %(act_w.value,freq),fontsize=21,fontweight='bold')
            fig.savefig(dr['FIG']+'matrix.jpg',dpi=72)
            plt.close()
            return dr['FIG']+'matrix.jpg'

        @out_3.capture(clear_output=True, wait=True)
        def plot_act(b):
            d = read(dr['MAT']+'Timesheet.pkl')
            mat,tot=gen_mat(act_w.value,date_from.value,date_to.value)
            display(Image(plot_matrix(mat)))
            display(Image(plot_ts(act_w.value,tot)))

        d = read(dr['MAT']+'Timesheet.pkl')
        acts=set(d['Activity'])
        random_act = np.random.choice(list(acts), 1, replace=False)
        act_w=widgets.Dropdown(options=acts,
                                          value=random_act,
                                          description='Activity',
                                          disabled=False,
                                          )

        date_from = widgets.DatePicker(description='From',
                                       value=dt.date.today()-dt.timedelta(21),
                                       disabled=False)

        date_to = widgets.DatePicker(description='Upto',
                                     value=dt.date.today(),
                                     disabled=False)



        b_mat = widgets.Button(description='Show Matrix',
                       icon='play',
                       button_style='warning',
                       )

        b_mat.on_click(plot_act)

        matrix_ui=VBox([HBox([act_w,date_from,date_to,b_mat]),out_3])

        return matrix_ui
Exemple #26
0
def track():

    import os
    import sys
    import socket
    import platform
    import datetime as dt
    import glob
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import seaborn as sns
    import ipywidgets as widgets
    import imp
    import time
    import pickle
    import threading
    import warnings
    
    from IPython.display import display, HTML, Image, Video
    from ipywidgets import interact, interact_manual, fixed
    from ipywidgets import Label, FloatProgress, FloatSlider, Button
    from ipywidgets.widgets import Layout, HBox, VBox

    warnings.filterwarnings('ignore')

    sns.set()
    plt.rcParams.update({'font.family': 'serif', 'font.weight': 'bold'})

    info = {
        'System ': socket.gethostname(),
        'Platform': platform.platform(),
        'Python Version': sys.version,
        'Python Directory': sys.executable,
        'Current Directory': os.getcwd(),
        'Last Run': dt.datetime.now().strftime('%d %b %Y, %H:%M:%S'),
    }

    dr = {}

    cwd = os.getcwd()
    keys = ['DOC', 'EXT', 'FIG', 'MAT', 'RAW', 'REP', 'STC', 'VID']
    dr.update({k: '%s/%s/' % (cwd, k) for k in keys})
    for k in dr:
        os.makedirs(dr[k], exist_ok=True)

    dpi = 72
    Activity = [
        'Sleeping', 'Drinks', 'Refresh', 'Walk', 'Yoga', 'Gym', 'Breakfast',
        'Driving', 'Management', 'Python', 'Tea', 'Study', 'Lunch', 'Table Tennis',
        'Discussions', 'Report Writing', 'Meetings', 'Presentations',
       'Snacks', 'Stairs', 'Writing', 'Dinner','Housework', 'Family', 'Friends',
        'Meetups', 'Volleyball', 'Housework',
        'Reading non fiction', 'Reading fiction', 'Singing', 'Movie', 'TV Series',
        'YouTube', 'Music', 'Web Surfing', 'Coursera', 'Volleyball', 'Cycling',
        'Traveling', 'Shopping', 'Social Media', 'Entertainment', 'Vocabulary',
        'Thinking','News', 'Video Shooting','Video Editing','Creative Works','Chatting'
    ]

    msg = "Welcome to Time Management !\nSince this is your first time.\nYou have to manually enter your first entry and rerun the cell again to access all features."

    out_0 = widgets.Output()
    out_1 = widgets.Output()
    out_2 = widgets.Output()
    out_3 = widgets.Output()
    out_4 = widgets.Output()
    out_5 = widgets.Output()

    def sync():
        '''
        Sync the timesheets between your local and external sources. It will take no inputs, just run the function.
        It will save 2 minutes of everyday and possible mistakes
        '''

        import shutil
        import time

        if info['Platform'][:7] == 'Windows':
            ep = 'I:/Timesheet.pkl'
        elif info['System ']=='kali':
            ep = '/media/root/UUI/Timesheet.pkl'
        else:
            ep = '/media/prateek/UUI/Timesheet.pkl'

        if not os.path.exists(ep):
            print('%s does not exists ' % (ep))
            return

        lp = dr['MAT'] + 'Timesheet.pkl'

        ext = os.path.getmtime(ep)
        lcl = os.path.getmtime(lp)

        extsz=os.path.getsize(ep)
        lclsz=os.path.getsize(lp)

        print('Local    : %s  %6.2f KB' % (time.ctime(lcl),lclsz/1024.))
        print('External : %s  %6.2f KB' % (time.ctime(ext),extsz/1024.))

        if (lcl > ext) and (lclsz>extsz) :
            shutil.copy(lp, ep)
            print('Copied to external')
        elif (lcl < ext) and (lclsz<extsz) :
            shutil.copy(ep, lp)
            print('Copied to local')
        else:
            print('Already in Sync. Do manually if you do not believe so')

    def update():
        '''
        Update the timesheet from reading the atime logger csv report. Benefits :-
        Save the time spent on manual entries.
        Easily get the time spent upto the second's precision

        This process will always be performed on a local system
        '''

        fn_csv = dr['RAW'] + dt.datetime.today().strftime('report-%d-%m-%Y.csv')

        if not os.path.exists(fn_csv):
            print('%s does not exists' % (fn_csv))
            return

        aa = pd.read_csv(fn_csv)
        idx = aa[aa[aa.columns[0]] == aa.columns[0]].index[0] - 1
        aa1 = aa.loc[0:idx]
        d = read(dr['MAT'] + 'Timesheet.pkl')
        d.iloc[-1]['To']
        b = aa1[pd.to_datetime(aa1['From']) > d.iloc[-1]['To']]
        b1 = {
            'Activity': [i.rstrip() for i in b['Activity type']],
            'From': pd.to_datetime(b['From']),
            'To': pd.to_datetime(b['To']),
            'Notes': b['Comment']
        }
        b11 = pd.DataFrame(b1)
        b12 = b11.reindex(index=b11.index[::-1])
        b12['Duration'] = b12['To'] - b12['From']
        if len(b12) == 0:
            print('Data is already updated')
        else:
            print('%d entries added' % (len(b12)))
        d = pd.concat((d, b12), ignore_index=True)
        d = d.fillna('')
        d.to_pickle(dr['MAT'] + 'Timesheet.pkl')
        d.to_pickle(dr['EXT'] +
                    dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl'))

    @out_5.capture(clear_output=True, wait=True)
    def sync_update():
        '''
        It will sync and update ( from csv) the timesheet
        '''
        sync()
        update()
        sync()
        display(read(dr['MAT'] + 'Timesheet.pkl').tail())

    @out_5.capture(clear_output=True, wait=True)
    def sync_update1(b):
        '''
        It will sync and update ( from csv) the timesheet
        '''
        sync()
        update()
        sync()
        display(read(dr['MAT'] + 'Timesheet.pkl').tail())

    def make_df(lst):
        columns = 'Activity', 'From', 'To', 'Notes'
        a = pd.DataFrame(lst, columns=columns)
        a['Duration'] = a['To'] - a['From']
        return a

    def make_df_id(lst, idx):
        columns = 'Activity', 'From', 'To', 'Notes'
        a = pd.DataFrame(lst, columns=columns, index=[idx - 0.5])
        a['Duration'] = a['To'] - a['From']
        return a


    def read(fn):
        '''
        read the saved variable using pickle library of python.
        '''
        with open(fn, 'rb') as f:
            data = pickle.load(f)
        return data


    def save(dct, fn):
        '''
        It will save the variable using pickle library
        fn : will be the output file name ( can be any .pkl is convention)
        '''
        with open(fn, 'wb') as f:
            pickle.dump(dct, f)


    def loop_1():
        while b_start[1].icon == 'stop':
            To[1].value = str(dt.datetime.today() -
                              pd.to_datetime(From[1].value))[7:-7]
            time.sleep(1)


    def loop_2():
        while b_start[2].icon == 'stop':
            To[2].value = str(dt.datetime.today() -
                              pd.to_datetime(From[2].value))[7:-7]
            time.sleep(1)


    def loop_3():
        while b_start[3].icon == 'stop':
            To[3].value = str(dt.datetime.today() -
                              pd.to_datetime(From[3].value))[7:-7]
            time.sleep(1)


    @out_0.capture(clear_output=True, wait=True)
    def stop_click(b):
        '''
        Function for Manual Time Logging
        '''
        A = Act[0].value
        From_str = From[0].value
        To_str = To[0].value
        N = Notes[0].value

        if os.path.exists(dr['MAT'] + 'Timesheet.pkl'):
            d = read(dr['MAT'] + 'Timesheet.pkl')
        else:
            d = pd.DataFrame(
                columns=['Activity', 'From', 'To', 'Notes', 'Duration'])
        F = pd.to_datetime(From_str)
        T = pd.to_datetime(To_str)
        aa = make_df([[A, F, T, N]])
        d = pd.concat((d, aa), ignore_index=True)
        d.to_pickle(dr['MAT'] + 'Timesheet.pkl')
        d.to_pickle(dr['EXT'] +
                    dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl'))
        display(d.tail())


    @out_1.capture(clear_output=True, wait=True)
    def start_click_1(b):
        '''
        Function for automatic time logging
        '''
        if b_start[1].icon == 'play':
            From[1].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            To[1].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            To[1].description = 'Elapsed Time'
            b_start[1].icon = 'stop'
            b_start[1].button_style = 'danger'
            display(read(dr['MAT'] + 'Timesheet.pkl').tail())
            threading.Thread(target=loop_1).start()

        else:
            To[1].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            To[1].description = 'To'
            b_start[1].icon = 'play'
            b_start[1].button_style = 'success'

            fnn = dr['MAT'] + 'Timesheet.pkl'

            if os.path.exists(fnn):
                d = read(fnn)
            else:
                d = pd.DataFrame(
                    columns=['Activity', 'From', 'To', 'Notes', 'Duration'])
            F = pd.to_datetime(From[1].value)
            T = pd.to_datetime(To[1].value)
            aa = make_df([[Act[1].value, F, T, Notes[1].value]])
            d = pd.concat((d, aa), ignore_index=True)

            d.to_pickle(fnn)
            d.to_pickle(dr['EXT'] +
                        dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl'))

            display(d.tail())


    @out_1.capture(clear_output=True, wait=True)
    def start_click_2(b):
        '''
        Function for automatic time logging
        '''
        if b_start[2].icon == 'play':
            From[2].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            To[2].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            To[2].description = 'Elapsed Time'
            b_start[2].icon = 'stop'
            b_start[2].button_style = 'danger'
            threading.Thread(target=loop_2).start()
            display(read(dr['MAT'] + 'Timesheet.pkl').tail())

        else:
            To[2].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            To[2].description = 'To'
            b_start[2].icon = 'play'
            b_start[2].button_style = 'success'

            fnn = dr['MAT'] + 'Timesheet.pkl'

            if os.path.exists(fnn):
                d = read(fnn)
            else:
                d = pd.DataFrame(
                    columns=['Activity', 'From', 'To', 'Notes', 'Duration'])
            F = pd.to_datetime(From[2].value)
            T = pd.to_datetime(To[2].value)
            aa = make_df([[Act[2].value, F, T, Notes[2].value]])
            d = pd.concat((d, aa), ignore_index=True)

            d.to_pickle(fnn)
            d.to_pickle(dr['EXT'] +
                        dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl'))

            display(d.tail())


    @out_1.capture(clear_output=True, wait=True)
    def start_click_3(b):
        '''
        Function for automatic time logging
        '''
        if b_start[3].icon == 'play':
            From[3].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            To[3].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            To[3].description = 'Elapsed Time'
            b_start[3].icon = 'stop'
            b_start[3].button_style = 'danger'
            threading.Thread(target=loop_3).start()
            display(read(dr['MAT'] + 'Timesheet.pkl').tail())

        else:
            To[3].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            To[3].description = 'To'
            b_start[3].icon = 'play'
            b_start[3].button_style = 'success'

            fnn = dr['MAT'] + 'Timesheet.pkl'

            if os.path.exists(fnn):
                d = read(fnn)
            else:
                d = pd.DataFrame(
                    columns=['Activity', 'From', 'To', 'Notes', 'Duration'])
            F = pd.to_datetime(From[3].value)
            T = pd.to_datetime(To[3].value)
            aa = make_df([[Act[3].value, F, T, Notes[3].value]])
            d = pd.concat((d, aa), ignore_index=True)

            d.to_pickle(fnn)
            d.to_pickle(dr['EXT'] +
                        dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl'))

            display(d.tail())


    @out_2.capture(clear_output=True, wait=True)
    def edit_data_click(b):
        index = IND.value
        col = COL.value
        value = VAL.value
        d = read(dr['MAT'] + 'Timesheet.pkl')
        print('Old Value : %s      New Value : %s' % (d.loc[index, col], value))
        if col == 'Activity':
            if value in Activity:
                d.loc[index, col] = value
            else:
                print(
                    '%s is not in any activity. Please include %s in activity list first'
                    % (value, value))
        elif col in ['From', 'To']:
            value = pd.to_datetime(value)
            d.loc[index, col] = value
        else:
            d.loc[index, col] = value

        d['Duration'] = d['To'] - d['From']
        d.to_pickle(dr['MAT'] + 'Timesheet.pkl')
        d.to_pickle(dr['EXT'] +
                    dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl'))
        print('Here is the new data')
        display(d.loc[index - 2:index + 2])

    @out_2.capture(clear_output=True, wait=True)
    def delete_entry(b):
        idx = IND.value
        d = read(dr['MAT']+'Timesheet.pkl')
        d1=d.drop(idx)
        d1=d1.reset_index(drop=True)
        d1.to_pickle(dr['MAT']+'Timesheet.pkl')
        display(read(dr['MAT']+'Timesheet.pkl').loc[idx-2:idx+2])


    @out_3.capture(clear_output=True, wait=True)
    def stop_click1(b):
        A = Act[4].value
        From_str = From[4].value
        To_str = To[4].value
        N = Notes[4].value
        idx = IND1.value

        F = pd.to_datetime(From_str)
        T = pd.to_datetime(To_str)

        val = make_df_id([[A, F, T, N]], idx)
        d = read(dr['MAT'] + 'Timesheet.pkl')
        d = d.append(val, ignore_index=False)
        d = d.sort_index().reset_index(drop=True)
        d.to_pickle(dr['MAT'] + 'Timesheet.pkl')
        d.to_pickle(dr['EXT'] +
                    dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl'))
        display(d.loc[idx - 2:idx + 2])


    def ana_ui():
        out_0 = widgets.Output()
        out_1 = widgets.Output()
        out_2 = widgets.Output()
        out_3 = widgets.Output()

        def filter_data(k,date):
            date=dt.datetime(date.year,date.month,date.day)
            c1=(d['From']>pd.to_datetime(date))*(d['To']<=pd.to_datetime(date)+pd.to_timedelta('23:59:59'))

            c11=d[c1]
            idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1]
            c12=d.loc[idx]
            c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))]
            c13=pd.concat((c10,c11))

            c2=c13[c13['Activity']==k]

            return c2

        def update_mat(k,mat,tot,date):
            c11=filter_data(k,date)
            tot[date]=c11['Duration'].sum()

            mat[date]=np.zeros(1440)
            ix=[int(np.round(i.total_seconds()/60)) for i in (c11['From']-date)]
            iy=[int(np.round(i.total_seconds()/60)) for i in (c11['To']-date)]
            for i,j in zip(ix,iy):
                if i<0:
                    mat[date][0:j]=1
                    date1=date-dt.timedelta(1)
                    date1=dt.datetime(date1.year,date1.month,date1.day)
                    if date1 >= dt.datetime(date_from.value.year,date_from.value.month,date_from.value.day):
                        ii=i+1440
                        mat[date1][ii:]=1
                else:
                    mat[date][i:j]=1


        def gen_mat(k,from_date,to_date):
            dates = pd.date_range(from_date,to_date)
            mat={}
            tot={}
            for date in dates:
                date=dt.datetime(date.year,date.month,date.day)
                update_mat(k,mat,tot,date)

            return mat,tot

        def plot_ts(k,tot):
            nmin={i.strftime('%a, %d %b'):tot[i].total_seconds()/60. for i in tot}

            a1=pd.Series(tot)
            a33 = pd.Series(nmin)
            a33 = a33.fillna(0)
            v=[str(tot[i])[7:] for i in tot]

            try:

                title = '%s\nMean = %s\n Regularity = %4.1f %% \n Maximum = %s on %s\n Minimum = %s on %s ' % (
                                k, str(a1.mean())[7:15], 100 * len(a33[a33 > 0]) / len(a33),
                                str(a1[a1 > dt.timedelta(0)].max())[7:15], a33[a33 > 0].argmax(),
                                str(a1[a1 > dt.timedelta(0)].min())[7:15], a33[a33 > 0].argmin())

            except ValueError:
                title = 'No \n %s \n Activitiy ' %(k)

            fig, ax = plt.subplots(figsize=(16, 8))
            plt.subplots_adjust(top=0.8, bottom=0.25)
            a33.plot.bar(width=1, ax=ax, color='g')
            ax.set_ylabel('Minutes', fontweight='bold')

            for j, i in enumerate(ax.patches):
                            if v[j] != '00:00:00':
                                if a33[j] < 0.2 * a33[a33 > 0].max():
                                    ax.text(i.get_x() + 0.45,
                                            1.5 * a33[j],
                                            v[j],
                                            fontsize=10,
                                            color='blue',
                                            rotation=90)
                                else:
                                    ax.text(i.get_x() + 0.45,
                                            0.1 * a33[j],
                                            v[j],
                                            fontsize=10,
                                            color='yellow',
                                            rotation=90)

            fig.suptitle(title, fontsize=18, fontweight='bold')
            fig.savefig(dr['FIG']+'ts.jpg',dpi=72)
            plt.close()
            return dr['FIG']+'ts.jpg'

        def plot_matrix(mat):
            dd1=np.zeros((len(mat),1440))
            for i,j in enumerate(mat):
                dd1[i,:]=mat[j]

            freq=100*(len(np.where(dd1.sum(axis=1)>0)[0])/dd1.shape[0])
            fig,ax=plt.subplots(figsize=(15,6))
            ax.imshow(dd1,aspect='auto',cmap=mpl.colors.ListedColormap(['white','g']))
            labels=[j.strftime('%a %d %b') for j in mat]
            plt.yticks(range(len(mat)),labels);
            xticks=np.arange(60,1440,60)
            xticklabels=np.arange(1,24)
            ax.set_xlabel('Time(hours)',fontweight='bold')
            ax.set_ylabel('Day',fontweight='bold')
            plt.xticks(xticks,xticklabels);
            ax.grid(color='y')
            ax.grid('off')
            fig.suptitle('Time Matrix of %s\nDaily frequency(Percent) = %4.1f' %(act_w.value,freq),fontsize=21,fontweight='bold')
            fig.savefig(dr['FIG']+'matrix.jpg',dpi=72)
            plt.close()
            return dr['FIG']+'matrix.jpg'

        @out_3.capture(clear_output=True, wait=True)
        def plot_act(b):
            d = read(dr['MAT']+'Timesheet.pkl')
            mat,tot=gen_mat(act_w.value,date_from.value,date_to.value)
            display(Image(plot_matrix(mat)))
            display(Image(plot_ts(act_w.value,tot)))

        d = read(dr['MAT']+'Timesheet.pkl')
        acts=set(d['Activity'])
        random_act = np.random.choice(list(acts), 1, replace=False)
        act_w=widgets.Dropdown(options=acts,
                                          value=random_act,
                                          description='Activity',
                                          disabled=False,
                                          )

        date_from = widgets.DatePicker(description='From',
                                       value=dt.date.today()-dt.timedelta(21),
                                       disabled=False)

        date_to = widgets.DatePicker(description='Upto',
                                     value=dt.date.today(),
                                     disabled=False)



        b_mat = widgets.Button(description='Show Matrix',
                       icon='play',
                       button_style='warning',
                       )

        b_mat.on_click(plot_act)

        matrix_ui=VBox([HBox([act_w,date_from,date_to,b_mat]),out_3])

        return matrix_ui

    def history_ui():
        date_wid = widgets.DatePicker(description='Pick a Date',
                                     value=dt.datetime.today(),
                                     disabled=False)




        def filter_data(date):
            d = read(dr['MAT']+'Timesheet.pkl')
            date=dt.datetime(date.year,date.month,date.day)
            c1=(d['From']>date)*(d['To']<=date+pd.to_timedelta('23:59:59'))
            c11=d[c1]

            idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1]
            c12=d.loc[idx]
            c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))]

            for j in ['From','To']:
                c11[j]=[c11[j].iloc[i].strftime('%H:%M:%S') for i in range(len(c11[j]))]

            c13=pd.concat((c10,c11))
            display(c13)

        def total_df(date):
            d = read(dr['MAT']+'Timesheet.pkl')
            date=dt.datetime(date.year,date.month,date.day)
            c1=(d['From']>pd.to_datetime(date))*(d['To']<=pd.to_datetime(date)+pd.to_timedelta('23:59:59'))
            c11=d[c1]

            idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1]
            c12=d.loc[idx]
            c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))]
            c13=pd.concat((c10,c11))

            acts=sorted(list(set(c13['Activity'])))

            act1=pd.Series(acts)
            tot=[c13[c13['Activity']==j]['Duration'].sum() for j in act1]
            tot1=pd.Series(tot)
            tot2=pd.DataFrame({'Activity': act1,'Total Duration':tot1})
            tot2 = tot2.sort_values(by='Total Duration',ascending=False)
            tot2 = tot2.reset_index(drop=True)
            display(tot2)



        out1 = widgets.interactive_output(filter_data, {'date': date_wid})
        out2 = widgets.interactive_output(total_df, {'date': date_wid})

        ui = VBox([date_wid,HBox([out1,out2])])

        return ui

    Act = {}
    From = {}
    To = {}
    Notes = {}
    Duration = {}

    random_act = np.random.choice(Activity, 5, replace=False)
    for i in range(5):

        Act[i] = widgets.Dropdown(options=Activity,
                                  value=random_act[i],
                                  description='Activity',
                                  disabled=False,
                                  layout=Layout(width='200px'))

        From[i] = widgets.Text(value='%s' %
                               (dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')),
                               placeholder='Start time',
                               description='From',
                               disabled=False,
                               layout=Layout(width='230px'))

        To[i] = widgets.Text(value='%s' %
                             (dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')),
                             placeholder='Start time',
                             description='To',
                             disabled=False,
                             layout=Layout(width='230px'))

        Notes[i] = widgets.Text(value='',
                                placeholder='Type something',
                                description='Notes',
                                disabled=False,
                                layout=Layout(width='220px'))

    b_stop = Button(description='',
                    icon='play',
                    button_style='info',
                    layout=Layout(width='100px'))

    b_stop1 = Button(description='',
                     icon='play',
                     button_style='info',
                     layout=Layout(width='100px'))

    b_stop.on_click(stop_click)

    b_stop1.on_click(stop_click1)

    add_row_ui = VBox([
        HBox([Act[0], From[0], To[0], Notes[0], b_stop],
             layout=Layout(margin='00000')), out_0
    ])

    b_start = {}
    timer_ui = {}

    for i in range(1, 4):
        b_start[i] = Button(description='',
                            icon='play',
                            button_style='success',
                            layout=Layout(width='100px'))

        timer_ui[i] = HBox([Act[i], b_start[i], From[i], To[i], Notes[i]],
                           layout=Layout(margin='00000'))

    b_start[1].on_click(start_click_1)
    b_start[2].on_click(start_click_2)
    b_start[3].on_click(start_click_3)

    COL = widgets.Dropdown(options=['Activity', 'From', 'To', 'Notes'],
                           value='Activity',
                           description='Columns',
                           disabled=False,
                           layout=Layout(width='200px'))

    app1 = VBox([timer_ui[1], timer_ui[2], timer_ui[3], out_1])


    if os.path.exists(dr['MAT'] + 'Timesheet.pkl'):

        sync_update()

        IND = widgets.Dropdown(options=read(dr['MAT'] + 'Timesheet.pkl').index[:],
                               value=read(dr['MAT'] + 'Timesheet.pkl').index[-1],
                               description='Index',
                               disabled=False,
                               layout=Layout(width='200px'))

        IND1 = widgets.Dropdown(options=read(dr['MAT'] + 'Timesheet.pkl').index[:],
                                value=read(dr['MAT'] + 'Timesheet.pkl').index[-1],
                                description='Index',
                                disabled=False,
                                layout=Layout(width='200px'))

        VAL = widgets.Text(value='',
                           placeholder='Type something',
                           description='Value',
                           disabled=False,
                           layout=Layout(width='300px'))

        b_edit = Button(description='Edit',
                        icon='play',
                        button_style='warning',
                        layout=Layout(width='100px'))

        b_del = Button(description='DELETE',
                        icon='play',
                        button_style='Danger',
                        layout=Layout(width='150px'))

        b_update=Button(description='Refresh',
                        icon='play',
                        button_style='warning',
                        layout=Layout(width='150px'))

        b_update.on_click(sync_update1)

        b_edit.on_click(edit_data_click)
        b_del.on_click(delete_entry)

        update_ui=VBox([b_update,out_5])

        edit_row_ui = VBox(
            [HBox([IND, COL, VAL, b_edit, b_del], layout=Layout(margin='00000')), out_2])

        insert_row_ui = VBox([
            HBox([IND1, Act[4], b_stop1]),
            HBox([From[4], To[4], Notes[4]]), out_3
        ])


        analysis_ui=ana_ui()
        hist=history_ui()
        tab = widgets.Tab()
        tab.children = [update_ui, add_row_ui, edit_row_ui, insert_row_ui, app1, analysis_ui,hist]
        tab.set_title(0, 'Updated Timesheet')
        tab.set_title(1, 'Manual Entry')
        tab.set_title(2, 'Edit Entry')
        tab.set_title(3, 'Insert Row')
        tab.set_title(4, 'Timer')
        tab.set_title(5, 'Analysis')
        tab.set_title(6, 'History')
        tab.box_style = 'danger'

    else:
        
        print(msg)
        tab = widgets.Tab()
        tab.children = [add_row_ui]
        tab.set_title(0, 'Manual Entry')

    return tab
 def get_widget():
     self.refresh()
     return VBox([
                 HBox([refresh_button,commit_button]),
                 grid_widget
         ])
    def __init__(self, wikipedia: Wikipedia, rsspediainit: RsspediaInit):
        """
        :param Wikipedia wikipedia: wikipedia class object initialized with correct language
        :param RsspediaInit rsspediainit: rsspedia init object - prepares the data and embeddings
        """

        self.data_titles = []
        self.data_results = []
        self.rsspediainit = rsspediainit
        self.wikipedia = wikipedia

        self.select_feed = Dropdown(
            options={
                'Politiken.dk': 0,
                'DR.dk': 1,
                'BT.dk': 2,
                'Information.dk': 3,
                'Børsen.dk': 4,
                'Ekstrabladet.dk': 5
            },
            value=0,
            description='Vælg nyhedskilde:',
            disabled=False,
            layout=Layout(width='400px'),
            style={'description_width': '160px'},
        )

        self.select_search = Dropdown(
            options={
                'Okapi BM-25': 0,
                'Explicit Semantic Analysis': 1,
                'FTN-a': 2,
                'FTN-b': 3
            },
            value=0,
            description='Vælg søgnings-algorytme:',
            disabled=False,
            layout=Layout(width='400px'),
            style={'description_width': '160px'},
        )

        self.select_nmatches = Dropdown(
            options={
                '3': 3,
                '5': 5,
                '10': 10
            },
            value=3,
            description='Vælg antal matches:',
            disabled=False,
            layout=Layout(width='400px'),
            style={'description_width': '160px'},
        )

        self.container = Output(value="", )

        self.submit_button = Button(
            value=False,
            description='Indlæs nyheder',
            disabled=False,
            button_style=
            'success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Få nyheder fra RSS-feed og find Wikipedia matches',
            icon='')

        self.widget_box = VBox(
            (self.select_feed, self.select_search, self.select_nmatches,
             self.submit_button, self.container), )

        self.submit_button.on_click(self._run)
    
def on_button_clicked(b):
    if b.sel == 'ecg':
        comp_sel_ecg[b.num].value = []
    elif b.sel == 'eog':
        comp_sel_eog[b.num].value = []
    elif b.sel == 'emg':
        comp_sel_emg[b.num].value = []
        
from ipywidgets.widgets import HBox, VBox
buttons_ecg = [widgets.Button(description='Clear ECG ' + str(i + 1), width='85px', sel='ecg', num=i) for i in range(3)]
buttons_eog = [widgets.Button(description='Clear EOG ' + str(i + 1), width='85px', sel='eog', num=i) for i in range(3)]
buttons_emg = [widgets.Button(description='Clear EMG ' + str(i + 1), width='85px', sel='emg', num=i) for i in range(3)]

header_ecg = widgets.HTML(value='<h2>ECG components</h2>')
header_eog = widgets.HTML(value='<h2>EOG components</h2>')
header_emg = widgets.HTML(value='<h2>EMG components</h2>')

box_ecg = VBox([header_ecg] + [HBox(buttons_ecg)] + [HBox(comp_sel_ecg)])
box_eog = VBox([header_eog] +[HBox(buttons_eog)] + [HBox(comp_sel_eog)])
box_emg = VBox([header_emg] +[HBox(buttons_emg)] + [HBox(comp_sel_emg)])
box_ecg.border_style = 'dotted'
box_ecg.border_radius = '14px'

box_eog.border_style = 'dotted'
box_eog.border_radius = '14px'
box_emg.border_style = 'dotted'
box_emg.border_radius = '14px'
# box_ecg.background_color ='cyan'
box = HBox([box_ecg, box_eog, box_emg])
Exemple #30
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
Exemple #31
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
Exemple #32
0
    def __init__(self):
        self.scaling_type = Select(options=[r'diffusive (fixed relaxation rate)',
                                            r'acoustic (fixed dt)',
                                            r'fixed lattice velocity'])
        self.physical_length = FloatText(value=0.1)
        self.cells_per_length = FloatText(value=256.0)
        self.max_physical_velocity = FloatText(value=0.01)
        self.dx = FloatText(value=self._get_dx())
        self.kinematic_viscosity = BoundedFloatText(value=1.0, min=0, max=1e12)
        self.omega = BoundedFloatText(min=0, max=2, value=1.9)
        self.dt = FloatText(value=0)
        self.max_lattice_velocity = FloatText(disabled=True)
        self.re = FloatText(disabled=True)

        self.processing_update = False

        def make_label(text):
            label_layout = {'width': '200px'}
            return Label(value=text, layout=label_layout)

        def make_buttons(input_widget, inverse=False):
            button_layout = {'width': '20px'}
            factor = 0.5 if inverse else 2.0
            double_btn = Button(description="", button_style='warning', layout=button_layout)
            half_btn = Button(description="", button_style='success', layout=button_layout)

            def double_value(_):
                input_widget.value *= factor

            def half_value(_):
                input_widget.value /= factor

            widgets.jslink((double_btn, 'disabled'), (input_widget, 'disabled'))
            widgets.jslink((half_btn, 'disabled'), (input_widget, 'disabled'))
            double_btn.on_click(double_value)
            half_btn.on_click(half_value)
            return [half_btn, double_btn]

        self.form = VBox([
            HBox([make_label(r'Scaling'), self.scaling_type]),
            HBox([make_label(r"Physical Length $[m]$"), self.physical_length]),
            HBox([make_label(r"Max. velocity $[m/s]$"), self.max_physical_velocity]),
            HBox([make_label(r"Cells per length"), self.cells_per_length] + make_buttons(self.cells_per_length, True)),
            HBox([make_label(r"dx"), self.dx] + make_buttons(self.dx)),
            HBox([make_label(r"Kinematic viscosity $10^{-6}[m^2/s]$"), self.kinematic_viscosity]),
            HBox([make_label(r"Relaxation rate $\omega$"), self.omega]),
            HBox([make_label(r"dt"), self.dt] + make_buttons(self.dt)),
            HBox([make_label(r"Max. lattice velocity"), self.max_lattice_velocity]),
            HBox([make_label(r"Re"), self.re]),
        ])

        # Change listeners
        self.physical_length.observe(self._on_physical_length_change, names='value')
        self.cells_per_length.observe(self._on_cells_per_length_change, names='value')
        self.dx.observe(self._on_dx_change, names='value')
        self.physical_length.observe(self._update_re)
        self.kinematic_viscosity.observe(self._update_re)
        self.max_physical_velocity.observe(self._update_re)

        for obj in [self.scaling_type, self.kinematic_viscosity, self.omega, self.dt, self.max_lattice_velocity]:
            obj.observe(self._update_free_parameter, names='value')

        self._update_free_parameter()
        self._update_re()