示例#1
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)
    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)
示例#3
0
def toggleRefDisplay(wd):
    '''
    切换参考区域
    :param wd: 参考区域
    :return: 
    '''
    config = Config(GLOBAL_SECTION)
    if config.readConf(GLOBAL_SECTION, 'ref', 'True') == str(True):
        wd.layout = Layout()
    else:
        wd.layout = Layout(display = 'none')
示例#4
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()
示例#5
0
    def __init__(self, size=None, layout=None, **kwargs):

        self._callbacks = []
        self._value_callbacks = []
        if layout is None and size is not None:
            layout = Layout(width='%ipx' % size, height='%ipx' % size)
        super(HTMLButton, self).__init__(layout=layout,
                                         dependencies=('CustomWidgets', ),
                                         **kwargs)
示例#6
0
    def __init__(self):

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

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

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

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

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

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

        # Initialize field
        self.collector = None

        self.start_button.on_click(self._start_video)
示例#7
0
 def __init__(self, name, validator=None, no_name=False, **kwargs):
     self.name = name
     self.__validator = validator if validator is not None else lambda x: True
     self.__text = Text(name, description='name')
     self.__text.continuous_update = False
     self.__text.observe(self.__on_name_changed, names='value')
     if no_name:
         kwargs['children'] = kwargs['children']
     else:
         kwargs['children'] = (self.__text, *kwargs['children'])
     kwargs['layout'] = Layout(margin='10px 10px')
     super().__init__(**kwargs)
示例#8
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)
示例#9
0
def _create_notebook_form(entity_id, entity_type, message, responses,
                          credentials):
    check_package('ipywidgets')

    from ipywidgets.widgets import HTML, Layout, Button, GridspecLayout

    text = HTML(message)

    button_yes = Button(description='Yes',
                        button_style='info',
                        layout=Layout(height='32px', width='176px'))
    button_no = Button(description='No',
                       button_style='',
                       layout=Layout(height='32px', width='176px'))

    buttons = GridspecLayout(1, 5)
    buttons[0, 0] = button_yes
    buttons[0, 1] = button_no

    def disable_buttons():
        button_yes.disabled = True
        button_no.disabled = True

    def on_button_yes_clicked(b):
        disable_buttons()
        response = trigger_subscription(entity_id, entity_type, credentials)
        if response:
            display(HTML(responses.get('ok')))
        else:
            display(HTML(responses.get('error')))

    def on_button_no_clicked(b):
        disable_buttons()
        display(HTML(responses.get('cancel')))

    button_yes.on_click(on_button_yes_clicked)
    button_no.on_click(on_button_no_clicked)

    return (text, buttons)
示例#10
0
    def on_execute_clicked(self, b):
        '''
        点击执行请求按钮
        :param b: 按钮
        :return: 
        '''
        debug.out('on_execute_clicked event')
        import requests
        if self.interface['method'] == 'GET':
            self.r = requests.get('http://' + self.env.server + self.interface['url'], params = self.params)
            self.htmExecute.value = '<span style="color:#208FFB">[%s请求执行完成] --> %s</span>' % (
                self.interface['method'], self.r.url)
        elif self.interface['method'] == 'POST':
            if self.interface.get('body', False) != False:
                self.r = requests.post('http://' + self.env.server + self.interface['url'], params = self.params,
                                       data = self.data)
            else:
                self.r = requests.post('http://' + self.env.server + self.interface['url'], params = self.params)
            self.htmExecute.value = '<span style="color:#208FFB">[%s请求执行完成] --> %s</span>' % (
                self.interface['method'], self.r.url)
        else:
            self.htmExecute.value = '<span style="color:red">[%s接口方法填写错误,请求未执行]</span>' % self.interface['method']

        if self.gdResult is not None:
            import json
            output = json.loads(self.r.text)
            resultCode = output['resultCode']
            debug.out('resultCode = %s' % resultCode)
            if resultCode == 1:
                debug.out('response output: %s' % output)
                self.htmResult.value = '<span style="color:#208FFB">[请求成功] 返回数据:</span>'
                for field in self.interface['output']:
                    output = output[field]
                df = pd.DataFrame(output)
                self.gdResult.df = df
                self.gdResult.layout = Layout()
            else:
                self.htmResult.value = output['<span style="color:red">请求失败:%s</span>' % output['resultMsg']]
                self.gdResult.layout = Layout(display = 'none')
    def _get_statement_output(self, session, statement_id):
        retries = 1
        progress = FloatProgress(value=0.0,
                                 min=0,
                                 max=1.0,
                                 step=0.01,
                                 description='Progress:',
                                 bar_style='info',
                                 orientation='horizontal',
                                 layout=Layout(width='50%', height='25px'))
        session.ipython_display.display(progress)

        while True:
            statement = session.http_client.get_statement(
                session.id, statement_id)
            status = statement[u"state"].lower()

            self.logger.debug(u"Status of statement {} is {}.".format(
                statement_id, status))

            if status not in FINAL_STATEMENT_STATUS:
                progress.value = statement.get('progress', 0.0)
                session.sleep(retries)
                retries += 1
            else:
                statement_output = statement[u"output"]
                progress.close()

                if statement_output is None:
                    return (True, u"", MIMETYPE_TEXT_PLAIN)

                if statement_output[u"status"] == u"ok":
                    data = statement_output[u"data"]
                    if MIMETYPE_IMAGE_PNG in data:
                        image = Image(
                            base64.b64decode(data[MIMETYPE_IMAGE_PNG]))
                        return (True, image, MIMETYPE_IMAGE_PNG)
                    elif MIMETYPE_TEXT_HTML in data:
                        return (True, data[MIMETYPE_TEXT_HTML],
                                MIMETYPE_TEXT_HTML)
                    else:
                        return (True, data[MIMETYPE_TEXT_PLAIN],
                                MIMETYPE_TEXT_PLAIN)
                elif statement_output[u"status"] == u"error":
                    return (False, statement_output[u"evalue"] + u"\n" +
                            u"".join(statement_output[u"traceback"]),
                            MIMETYPE_TEXT_PLAIN)
                else:
                    raise LivyUnexpectedStatusException(
                        u"Unknown output status from Livy: '{}'".format(
                            statement_output[u"status"]))
示例#12
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])
示例#13
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)
示例#14
0
 def __init__(self,
              icon='question',
              color='#333',
              icon_size=20,
              size=40,
              layout=None,
              **kwargs):
     self._icon = icon
     self._color = color
     self._size = icon_size
     if layout is None:
         layout = Layout(width='%ipx' % size, height='%ipx' % size)
     super(ToolButton, self).__init__(html=self._html(),
                                      layout=layout,
                                      **kwargs)
示例#15
0
    def __init__(self):
        self.setting = self.create_settings()
        self.keyword = Textarea(
            value='',
            placeholder='Search dictionary and press enter',
            description='',
            disabled=False,
            rows=1,
            layout=Layout(width='50%'))
        self.search_button = self.create_button('search')
        self.save_button = self.create_button('save file')
        self.out = Output()
        self.results = {}

        self.search_button.on_click(self.search)
        self.save_button.on_click(self.save_file)
        self.keyword.observe(self.adjust_keyword_size, 'value')
示例#16
0
    def packageWidgets(self):
        '''
        打包组件
        :return: 
        '''
        debug.out('package request widgets')
        self.paramWidgets = {}
        self.txtBody = None
        for param, ptype in self.interface['params'].items():
            value = self.cf.readConf(self.default['interface'], param)
            if ptype == 'int':
                pw = IntText(description = param + ':',
                             value = value if value is not None else 0,
                             layout = Layout(width = '90%'))
            elif ptype == 'date':
                pw = DatePicker(description = param + ':',
                                value = value if value is not None else '',
                                layout = Layout(width = '90%'))
            elif ptype == 'companyId':
                pw = Text(description = param + ':',
                          value = value if value is not None else self.env.tester['companyId'],
                          layout = Layout(width = '90%'))
            elif ptype == 'openId':
                pw = Text(description = param + ':',
                          value = value if value is not None else self.env.tester['openId'],
                          layout = Layout(width = '90%'))
            else:
                pw = Text(description = param + ':',
                          value = value if value is not None else '',
                          layout = Layout(width = '90%'))
            pw.observe(self.on_param_change)
            self.paramWidgets[param] = pw

        self.txtBody = Textarea(description = 'body data:', value = '')
        self.txtBody.layout = Layout(display = 'none')

        debug.out(self.interface.get('body', False))
        if self.interface.get('body', False) != False:
            debug.out('interface have body data to package widget')
            value = self.cf.readConf(self.default['interface'], 'body')
            self.txtBody.value = value if value is not None else ''
            self.txtBody.layout = Layout(width = '90%', height = '200px')

        tmpWds = [wd for wd in self.paramWidgets.values()]
        tmpWds.append(self.txtBody)
        self.boxParams.children = tmpWds
示例#17
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
示例#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.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)
示例#20
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()
    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)
示例#22
0
    def __init__(self, logviews=None):
        if logviews is None:
            logviews = []

        line = Text(value='',
                    placeholder='log filters',
                    layout=Layout(width='200px'),
                    disabled=False)

        icon_info = ToolButton(value=True,
                               toggleable=True,
                               button_color='#bdbdbd',
                               pressed_color='#eee',
                               icon='info-circle',
                               color='#2176ff')

        def info_color(value):
            icon_info.color = '#2176ff' if value else '#333'

        icon_info.on_value_changed(info_color)

        icon_warn = ToolButton(value=True,
                               toggleable=True,
                               button_color='#bdbdbd',
                               pressed_color='#eee',
                               icon='exclamation-triangle',
                               color='#eba427')

        def warn_color(value):
            icon_warn.color = '#eba427' if value else '#333'

        icon_warn.on_value_changed(warn_color)

        icon_error = ToolButton(value=True,
                                toggleable=True,
                                button_color='#bdbdbd',
                                pressed_color='#eee',
                                icon='exclamation-circle',
                                color='#c71e1e')

        def error_color(value):
            icon_error.color = '#c71e1e' if value else '#333'

        icon_error.on_value_changed(error_color)

        icon_debug = ToolButton(value=True,
                                toggleable=True,
                                button_color='#bdbdbd',
                                pressed_color='#eee',
                                icon='code',
                                color='#111')

        def debug_color(value):
            icon_debug.color = '#111' if value else '#333'

        icon_debug.on_value_changed(debug_color)

        space = HTML(layout=Layout(width='25px'))
        case_sensitive = HTMLButton(value=True,
                                    html='Aa',
                                    size=40,
                                    button_color='#bdbdbd',
                                    pressed_color='#eee',
                                    toggleable=True)

        super(LogToolBar, self).__init__([
            icon_info, icon_warn, icon_error, icon_debug, space, line,
            case_sensitive
        ])
        self.info = icon_info
        self.warn = icon_warn
        self.error = icon_error
        self.debug = icon_debug
        self.filter = line
        self.case = case_sensitive
        if not isinstance(logviews, list):
            logviews = [logviews]

        self._logviews = []
        for logview in logviews:
            self.link_to(logview)
示例#23
0
def mk_map_region_selector(map=None, height="600px", **kwargs):
    from ipyleaflet import Map, WidgetControl, FullScreenControl, DrawControl
    from ipywidgets.widgets import Layout, Button, HTML
    from types import SimpleNamespace

    state = SimpleNamespace(selection=None, bounds=None, done=False)

    btn_done = Button(description="done", layout=Layout(width="5em"))
    btn_done.style.button_color = "green"
    btn_done.disabled = True

    html_info = HTML(layout=Layout(flex="1 0 20em", width="20em", height="3em"))

    def update_info(txt):
        html_info.value = '<pre style="color:grey">' + txt + "</pre>"

    def render_bounds(bounds):
        (lat1, lon1), (lat2, lon2) = bounds
        txt = "lat: [{:.{n}f}, {:.{n}f}]\nlon: [{:.{n}f}, {:.{n}f}]".format(
            lat1, lat2, lon1, lon2, n=4
        )
        update_info(txt)

    if map is None:
        m = Map(**kwargs) if len(kwargs) else Map(zoom=2)
        m.scroll_wheel_zoom = True
        m.layout.height = height
    else:
        m = map
        render_bounds(m.bounds)

    widgets = [
        WidgetControl(widget=btn_done, position="topright"),
        WidgetControl(widget=html_info, position="bottomleft"),
    ]
    for w in widgets:
        m.add_control(w)

    draw = DrawControl()

    draw.circle = {}
    draw.polyline = {}
    draw.circlemarker = {}

    shape_opts = {"fillColor": "#fca45d", "color": "#000000", "fillOpacity": 0.1}
    draw.rectangle = {"shapeOptions": shape_opts, "metric": ["km", "m"]}
    poly_opts = {"shapeOptions": dict(**shape_opts)}
    poly_opts["shapeOptions"]["original"] = dict(**shape_opts)
    poly_opts["shapeOptions"]["editing"] = dict(**shape_opts)

    draw.polygon = poly_opts
    draw.edit = True
    draw.remove = True
    m.add_control(draw)
    m.add_control(FullScreenControl())

    def on_done(btn):
        state.done = True
        btn_done.disabled = True
        m.remove_control(draw)
        for w in widgets:
            m.remove_control(w)

    def bounds_handler(event):
        bounds = event["new"]
        render_bounds(bounds)
        (lat1, lon1), (lat2, lon2) = bounds
        state.bounds = dict(lat=(lat1, lat2), lon=(lon1, lon2))

    def on_draw(event):
        v = event["new"]
        action = event["name"]
        if action == "last_draw":
            state.selection = v["geometry"]
        elif action == "last_action" and v == "deleted":
            state.selection = None

        btn_done.disabled = state.selection is None

    draw.observe(on_draw)
    m.observe(bounds_handler, ("bounds",))
    btn_done.on_click(on_done)

    return m, state
示例#24
0
from pyfirmata import Arduino, util
import IPython.display
from ipywidgets.widgets import Layout
import ipywidgets as widgets


placa = Arduino('/dev/ttyUSB0')

botao = widgets.Button(description="Luz",mycolor='white',layout=Layout(width='1213px'))
botao.style.button_color = 'green'
#botao2 = widgets.Button(description="Luz",button_style='warning',layout=Layout(width='1213px'))
estado_botao = widgets.Output()
display(botao, estado_botao)
    

def liga_desliga(b):
    with estado_botao:
        estado = placa.digital[13].read()
        if estado == True:
            placa.digital[13].write(0)
            botao.style.button_color = 'green'
        else:
            placa.digital[13].write(1)
            botao.style.button_color = 'gold'
        IPython.display.clear_output(wait=True)
                        

botao.on_click(liga_desliga)
示例#25
0
 def __init__(self, space='25px'):
     if isinstance(space, int):
         space = '%ipx' % space
     super(VSpace, self).__init__(layout=Layout(height=space))
示例#26
0
def compose(
    scatters,
    select_mappers=None,
    hover_mappers=None,
    row_height=320,
):
    n_rows = 1

    if all(isinstance(el, list) for el in scatters):
        # Nested lists
        n_rows = len(scatters)
        n_cols = len(scatters[0])
    else:
        n_cols = len(scatters)

    try:
        scatters = [item for sublist in scatters for item in sublist]
    except TypeError:
        # Probably not a nested list
        pass

    try:
        select_mappers = [
            item for sublist in select_mappers for item in sublist
        ]
    except TypeError:
        # Probably not a nested list
        pass

    try:
        hover_mappers = [item for sublist in hover_mappers for item in sublist]
    except TypeError:
        # Probably not a nested list
        pass

    complete_scatters = list(
        zip_longest(scatters, select_mappers or [], hover_mappers or []))

    assert len(scatters) == n_rows * n_cols, 'Should equal'

    # We need to store the specific handlers created by called
    # `base_select_handler(index)` and `base_hover_handler(index)` to
    # dynamically un- and re-observe
    scatter_select_handlers = []
    scatter_hover_handlers = []

    def base_select_handler(index):
        def select_handler(change):
            if change['new'] is None:
                for i, complete_scatter in enumerate(complete_scatters):
                    if i != index:
                        sc, _, _ = complete_scatter
                        # Unsubscribe to avoid cyclic updates
                        sc.widget.unobserve(scatter_select_handlers[i],
                                            names='selection')
                        sc.widget.selection = []
                        # Re-subscribe to listen to changes coming from the JS kernel
                        sc.widget.observe(scatter_select_handlers[i],
                                          names='selection')

            else:
                for i, complete_scatter in enumerate(complete_scatters):
                    if i != index:
                        sc, select_mapper, _ = complete_scatter
                        # Unsubscribe to avoid cyclic updates
                        sc.widget.unobserve(scatter_select_handlers[i],
                                            names='selection')

                        if select_mapper is None:
                            sc.widget.selection = [
                                int(x) for x in change['new']
                            ]
                        else:
                            sc.widget.selection = [
                                int(x)
                                for x in select_mapper(index, change['new'])
                            ]

                        # Re-subscribe to listen to changes coming from the JS kernel
                        sc.widget.observe(scatter_select_handlers[i],
                                          names='selection')

        return select_handler

    def base_hover_handler(index):
        def hover_handler(change):
            if change['new'] is None:
                for i, complete_scatter in enumerate(complete_scatters):
                    if i != index:
                        sc, _, _ = complete_scatter
                        # Unsubscribe to avoid cyclic updates
                        sc.widget.unobserve(scatter_hover_handlers[i],
                                            names='hovering')
                        sc.widget.hovering = -1
                        # Re-subscribe to listen to changes coming from the JS kernel
                        sc.widget.observe(scatter_hover_handlers[i],
                                          names='hovering')

            else:
                for i, complete_scatter in enumerate(complete_scatters):
                    if i != index:
                        sc, _, hover_mapper = complete_scatter
                        # Unsubscribe to avoid cyclic updates
                        sc.widget.unobserve(scatter_hover_handlers[i],
                                            names='hovering')

                        if hover_mapper is None:
                            sc.widget.hovering = int(change['new'])
                        else:
                            sc.widget.hovering = int(
                                hover_mapper(index, change['new']))

                        # Re-subscribe to listen to changes coming from the JS kernel
                        sc.widget.observe(scatter_hover_handlers[i],
                                          names='hovering')

        return hover_handler

    for index, scatter in enumerate(scatters):
        scatter.height(row_height)
        scatter.widget.unobserve_all()  # Clear previous observers

        select_handler = base_select_handler(index)
        hover_handler = base_hover_handler(index)

        scatter_select_handlers.append(select_handler)
        scatter_hover_handlers.append(hover_handler)

        scatter.widget.observe(select_handler, names='selection')
        scatter.widget.observe(hover_handler, names='hovering')

    return GridBox(children=[scatter.widget.show() for scatter in scatters],
                   layout=Layout(grid_template_columns=' '.join(
                       ['auto' for x in range(n_cols)]),
                                 grid_template_rows=' '.join([
                                     f'{row_height}px' for x in range(n_rows)
                                 ]),
                                 grid_gap='2px'))
    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)
示例#28
0
# Dashboard
from ipywidgets.widgets import HBox, VBox, Tab, Layout, HTML

from .utils.content_widgets import (glimpse_output_widget, cf_output_widget,
                                    pp_output_widget, columns_output_widget)
import logging

logging.basicConfig(filename='tensorprobe.log',
                    filemode='a',
                    level=logging.DEBUG,
                    datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)

layout = Layout(height="100%", width="100%")


class Dashboard(object):
    def __init__(self):
        self.dashboard = HBox([])
        self.tab = Tab(layout=layout)
        self.titles = [
            'Glimpse', 'Columns', 'Cross filters', 'Pairwise Patterns'
        ]

        # set titles for tab cell
        for i, title in enumerate(self.titles):
            self.tab.set_title(i, title)

    def __call__(self, df):
        # build dashboard
        logger.info("building dashboard...")
示例#29
0
def mk_map_region_selector(height='600px', **kwargs):
    from ipyleaflet import Map, WidgetControl, FullScreenControl, DrawControl
    from ipywidgets.widgets import Layout, Button, HTML
    from types import SimpleNamespace

    state = SimpleNamespace(selection=None, bounds=None, done=False)

    btn_done = Button(description='done', layout=Layout(width='5em'))
    btn_done.style.button_color = 'green'
    btn_done.disabled = True

    html_info = HTML(
        layout=Layout(flex='1 0 20em', width='20em', height='3em'))

    def update_info(txt):
        html_info.value = '<pre style="color:grey">' + txt + '</pre>'

    m = Map(**kwargs) if len(kwargs) else Map(zoom=2)
    m.scroll_wheel_zoom = True
    m.layout.height = height

    widgets = [
        WidgetControl(widget=btn_done, position='topright'),
        WidgetControl(widget=html_info, position='bottomleft'),
    ]
    for w in widgets:
        m.add_control(w)

    draw = DrawControl()

    draw.circle = {}
    draw.polyline = {}
    draw.circlemarker = {}

    shape_opts = {
        "fillColor": "#fca45d",
        "color": "#000000",
        "fillOpacity": 0.1
    }
    draw.rectangle = {"shapeOptions": shape_opts}
    poly_opts = {"shapeOptions": dict(**shape_opts)}
    poly_opts["shapeOptions"]["original"] = dict(**shape_opts)
    poly_opts["shapeOptions"]["editing"] = dict(**shape_opts)

    draw.polygon = poly_opts
    draw.edit = True
    draw.remove = True
    m.add_control(draw)
    m.add_control(FullScreenControl())

    def on_done(btn):
        state.done = True
        btn_done.disabled = True
        m.remove_control(draw)
        for w in widgets:
            m.remove_control(w)

    def bounds_handler(event):
        (lat1, lon1), (lat2, lon2) = event['new']
        txt = 'lat: [{:.{n}f}, {:.{n}f}]\nlon: [{:.{n}f}, {:.{n}f}]'.format(
            lat1, lat2, lon1, lon2, n=4)
        update_info(txt)
        state.bounds = dict(lat=(lat1, lat2), lon=(lon1, lon2))

    def on_draw(event):
        v = event['new']
        action = event['name']
        if action == 'last_draw':
            state.selection = v['geometry']
        elif action == 'last_action' and v == 'deleted':
            state.selection = None

        btn_done.disabled = state.selection is None

    draw.observe(on_draw)
    m.observe(bounds_handler, ('bounds', ))
    btn_done.on_click(on_done)

    return m, state
示例#30
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