def setup_widget(self): ### grid widget construction: def items_callback (index, column): items = {} for tool,output in self.metadata.items(): for row,col in output.get('Cell_errors', []): if row == index and self.columns[col] == column: items [f"info_{tool}"] = f"False : Detected By {tool}" items ["label_False"] = 'Label as False' for action, text in zip(['label', 'update'], ['Labeld By', 'Updated By']): for name, data in self.collaborators.items(): df = data[action] val = df.loc[index,column] if name == self.user_id or pd.isna(val): continue key = f"{action}_{val}_{name}" items[key]= f"{val} : {text} {name}" return items def click_callback(index, column, key): action, val = key.split('_')[0:2] if action == 'update': self.grid_widget.edit_cell(index,column, val) elif action == 'label': self.label.loc[index,column] = val context_menu = { 'items_callback' : items_callback, 'click_callback' : click_callback } grid_widget = qgrid.show_grid(self, context_menu = context_menu) def handle_cell_edited(event, grid_widget): index, column, new_value = event['index'], event['column'], event['new'] self.loc[index, column] = new_value grid_widget.on('cell_edited', handle_cell_edited) self.grid_widget = grid_widget #refresh button refresh_button = Button(description='Refresh') refresh_button.on_click(self.refresh) #commit button commit_button = Button(description='Commit') commit_button.on_click(self.commit) def get_widget(): self.refresh() return VBox([ HBox([refresh_button,commit_button]), grid_widget ]) self.get_widget = get_widget
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 create_button(self, name): button = Button(description=name, disabled=False, button_style='info', tooltip='Click me', icon='') return button
def displayGlobalButton(): ''' 显示全局按钮 :return: ''' config = Config(GLOBAL_SECTION) if not config.isReady(): config.initConf(GLOBAL_SECTION) config.writeConf(GLOBAL_SECTION, 'ref', 'True') config.writeConf(GLOBAL_SECTION, 'debug', 'False') isDisplayRef = config.readConf(GLOBAL_SECTION, 'ref', 'True') == str(True) isDisplayDebug = config.readConf(GLOBAL_SECTION, 'debug', 'True') == str(True) btnRef = ToggleButton(description = '隐藏参考信息' if isDisplayRef else '显示参考信息', value = isDisplayRef) btnDebug = ToggleButton(description = '隐藏调试信息' if isDisplayDebug else '显示调试信息', value = isDisplayDebug) btnDebugClear = Button(description = '清除调试信息') debug.setCleaner(btnDebugClear) if isDisplayDebug: debug.enable() else: debug.disable() btnRef.observe(on_ref_change) btnDebug.observe(on_debug_change) btnDebugClear.on_click(on_debugclear_clicked) boxGlobal = Box([btnRef, btnDebug, btnDebugClear]) display(boxGlobal)
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)
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]
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)
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)
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)
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, 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])
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.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()
D_widget = IntSlider(min=10, max=100, step=1, value=50) p_widget = FloatSlider(min=0.0, max=1.0, step=0.1, value=0.5) P_widget = IntSlider(min=5, max=50, step=5, value=20) A_widget = FloatSlider(min=0.0, max=1.0, step=0.1, value=0.5) params = interact(set_params, nn=nn_widget, np=np_widget, D=D_widget, p=p_widget, P=P_widget, A=A_widget) button_init = Button(description="Init", on_click=init) button_init.on_click(init) button_init ########## """ Button( description='Click me', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', icon='check' # (FontAwesome names without the `fa-` prefix) ) """ #button_init = Button(description="Init")
def displayInterface(self): ''' 显示组件 :return: ''' if not self.cf.isReady(): print(Fore.RED + '配置项尚未初始化!') self.btnInit = Button(description = '立即初始化', button_style = 'danger') self.btnInit.on_click(self.on_init_clicked) display(self.btnInit) else: self.catagoryname = self.cf.readConf(self.default['interface'], 'catagoryname') # 类别名称 self.catagoryname = self.default[ 'catagory'] if self.catagoryname is None else self.catagoryname # 未设置时使用默认配置 self.interfacename = self.cf.readConf(self.default['interface'], 'interfacename') # 接口名称 self.interfacename = self.default[ 'interface'] if self.interfacename is None else self.interfacename # 未设置时使用默认配置 self.catagory = interfaces.get(self.catagoryname, None) if self.catagoryname is not None else None # 类别信息 self.interfaces = self.catagory.get('interface', None) if self.catagory is not None else None # 类别下所有接口信息 self.interface = self.interfaces.get(self.interfacename, None) if self.interfaces is not None and self.interfacename is not None else None # 接口信息 # 组件初始化 self.dpCatagory = Dropdown( options = [key for key in interfaces.keys()], value = self.catagoryname if self.catagoryname is not None else None, description = '类别:' ) debug.out('interfacename = %s' % self.interfacename) tmpOptions = [key for key in interfaces[self.dpCatagory.value]['interface']] if self.catagory is not None else [] self.dpInterface = Dropdown( options = tmpOptions, value = self.interfacename if self.interfacename in tmpOptions else None, description = '接口:' ) self.dpCatagory.observe(self.on_catagory_change) self.dpInterface.observe(self.on_interface_change) self.htmInterface = HTML(value = self.choiceResult()) self.gdParam = qgrid.show_grid(pd.DataFrame(None)) self.gdBody = qgrid.show_grid(pd.DataFrame(None)) if self.interface is not None: self.dfParams = pd.DataFrame(self.interface.get('params', ['无']), index = [0]).T self.dfParams.columns = ['请求参数类型'] self.gdParam = qgrid.show_grid(self.dfParams, grid_options = {'filterable': False, 'editable': False}) self.gdParam.layout = Layout(width = '90%') self.dfBody = pd.DataFrame(self.interface.get('body', ['无'])) self.dfBody.columns = ['请求体参数名称'] self.gdBody = qgrid.show_grid(self.dfBody, grid_options = {'filterable': False, 'editable': False}) self.gdBody.layout = Layout(width = '90%') debug.out('display from interface object=%s' % self) display(self.dpCatagory) display(self.dpInterface) boxRequest = Box([VBox([Label(value = '请求参数:'), self.gdParam], layout = Layout(flex = '1 1 0%', width = 'auto')), VBox([Label(value = '请求体参数:'), self.gdBody], layout = Layout(flex = '1 1 0%', width = 'auto'))], layout = Layout(flex_flow = 'row', display = 'flex')) boxRef = VBox([self.htmInterface, boxRequest]) acRef = Accordion(children = [boxRef]) acRef.set_title(0, '接口参考') toggleRefDisplay(acRef) display(acRef) ref.append(acRef)
def __menu(self, parameter_type, box, category_name=None): btn_add = Button(description='Add') ddn_add = Dropdown() if parameter_type == 'scalars': def fn_add(self): value = None if ddn_add.value == 'Integer': value = 1 elif ddn_add.value == 'Float': value = 1.0 elif ddn_add.value == 'Bool': value = True name = f'{ddn_add.value}_{len(box.children)}' scalar = self.__lp.add_scalar(name, value, category=category_name) editor = make_scalar_editor(scalar) editor.observe(self.__on_editor_changed(scalar)) box.children = (*box.children, editor) if self.__auto_save: self.__save() if self.__auto_apply: self.on_lpy_context_change(self.__lp.dumps()) ddn_add.options = ['Integer', 'Float', 'Bool'] elif parameter_type == 'materials': def fn_add(self): index = max(self.__lp.get_colors().keys()) + 1 if len( self.__lp.get_colors().keys()) else 0 self.__lp.set_color( index, pgl.Material(ambient=(80, 80, 80), diffuse=1)) editor = make_color_editor(self.__lp.get_color(index), index, no_name=True) editor.observe( self.__on_editor_changed(self.__lp.get_color(index))) box.children = (*box.children, editor) if self.__auto_save: self.__save() if self.__auto_apply: self.on_lpy_context_change(self.__lp.dumps()) ddn_add.options = ['Color'] elif parameter_type == 'curves': def fn_add(self): name = f'{ddn_add.value}_{len(box.children)}' if ddn_add.value == 'Function': curve = self.__lp.add_function(name, category=category_name) else: curve = self.__lp.add_curve(name, category=category_name) editor = make_curve_editor(curve) editor.observe(self.__on_editor_changed(curve)) box.children = (*box.children, editor) if self.__auto_save: self.__save() if self.__auto_apply: self.on_lpy_context_change(self.__lp.dumps()) ddn_add.options = ['Curve', 'Function'] btn_add.on_click(lambda x: fn_add(self)) return HBox((btn_add, ddn_add))
def __init__(self, df: pd.DataFrame, col_name: str, df_name: str, page_size: int): self._clusterer = Clusterer(df, col_name, df_name) self._clusterer.cluster("fingerprint") self._page_size = page_size # clustering dropdown and export code checkbox, used in the top row self._clustering_method_label = Label( " Clustering Method: ", layout=Layout(margin="2px 0 0 20px")) self._clustering_method_drop = Dropdown( options=[ "fingerprint", "ngram-fingerprint", "phonetic-fingerprint", "levenshtein" ], layout=Layout(width="150px", margin="0 0 0 10px"), ) self._clustering_method_drop.observe(self._cluster_method_change, names="value") self._export_code = Checkbox( value=True, description="export code", layout=Layout(width="165px", margin="0 0 0 482px"), style={"description_width": "initial"}, ) self._dropds = HBox( [ self._clustering_method_label, self._clustering_method_drop, self._export_code, ], layout=Layout(height="35px", margin="10px 0 0 0"), ) # text boxes for clustering parameters used in the top row self._ngram_text = Text( value=DEFAULT_NGRAM, description="n-gram", layout=Layout(width="130px"), continuous_update=False, ) self._radius_text = Text( value=DEFAULT_RADIUS, description="Radius", layout=Layout(width="130px"), continuous_update=False, ) self._block_chars_text = Text( value=DEFAULT_BLOCK_SIZE, description="Block Chars", layout=Layout(width="130px"), continuous_update=False, ) self._ngram_text.observe(self._param_recluster, names="value") self._radius_text.observe(self._param_recluster, names="value") self._block_chars_text.observe(self._param_recluster, names="value") # create header labels, second row headers = HBox( [ Label("Distinct values", layout=Layout(margin="0 0 0 10px")), Label("Total values", layout=Layout(margin="0 0 0 35px")), Label("Cluster values", layout=Layout(margin="0 0 0 95px")), Label("Merge?", layout=Layout(margin="0 0 0 295px")), Label("Representative value", layout=Layout(margin="0 0 0 50px")), ], layout=Layout(margin="10px"), ) # create buttons for bottom row self._sel_all = Checkbox(description="Select all", layout=Layout(width="165px")) self._sel_all.observe(self._select_all, names="value") merge_and_recluster = Button(description="Merge and Re-Cluster", layout=Layout(margin="0 0 0 466px", width="150px")) merge_and_recluster.on_click(self._execute_merge) finish = Button(description="Finish", layout=Layout(margin="0 0 0 10px")) finish.on_click(self._close) # next and previous page buttons self._next_button = Button(description="Next") self._next_button.on_click(self._next_page) self._prev_button = Button(description="Previous", layout=Layout(margin="0 0 0 20px")) self._prev_button.on_click(self._prev_page) # an index in the clusters Series indicating the start of the current page self._page_pos = 0 # loading label, displayed when re-clustering or next page load self._loading_label = Label("Loading...", layout=Layout(margin="170px 0 0 440px")) # displayed when the user enters a non integer value into a clustering parameter text box self._invalid_param_label = Label( "Invalid clustering parameter, please enter an integer", layout=Layout(margin="170px 0 0 350px"), ) self._reprs = [ Text(layout=Layout(width="200px", margin="0 10px 0 40px")) for _ in range(self._page_size) ] self._checks = [ Checkbox(indent=False, layout=Layout(width="auto", margin="0 0 0 20px")) for _ in range(self._page_size) ] # VBox containing a VBox with all the clusters in the first row and an optional # second row containing next and previous page buttons self._cluster_and_next_prev = VBox() self._cluster_vbox = VBox( layout=Layout(height="450px", flex_flow="row wrap")) footer = HBox([self._sel_all, merge_and_recluster, finish]) box_children = [ self._dropds, headers, self._cluster_and_next_prev, footer ] box_layout = Layout(display="flex", flex_flow="column", align_items="stretch", border="solid") self._box = Box(children=box_children, layout=box_layout) self._update_clusters()
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
def __init__(self): """ :param int i: """ self.test_sound = None self.test_data = None self.select_test_data_options = None self.select_test_data = Dropdown( options={'Record test data': 0, 'Load test data files': 1 }, value=0, description='Choose training data:', disabled=False, layout=Layout(width='400px'), style={'description_width': '160px'}, ) self.select_test_data.observe(self.on_change) self.select_nseconds = Dropdown( options={ '2s': 2, '3s': 3, '5s': 5 }, value=2, description='Choose recording length:', disabled=False, layout=Layout(width='400px', display='block'), style={'description_width': '160px'}, ) self.container = Output( value="", ) self.submit_button = Button( value=False, description='Get test data', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='TEST: use recorded sounds or record new', icon='' ) self.play_button = Button( value=False, description='Play the recording', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltip='TEST: play recorded or loaded sounds', icon='' ) self.widget_box = VBox( ( HBox( ( VBox(( self.select_test_data, self.select_nseconds ), ), VBox(( self.submit_button, self.play_button ), ) ), ), self.container ), ) self.submit_button.on_click(self._run) self.play_button.on_click(self._playback)
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)
from ipywidgets.widgets import Dropdown, Text, Button, HBox, VBox from IPython.display import display, clear_output import pandas as pd from FileValidator.app import TheValidator def get_clicked(b): clear_output() #resets output every time you click the button csv_to_dataframe = pd.read_csv(FILE_PATH.value) validate_app = TheValidator(csv_to_dataframe, FUNCTION.value) output = validate_app.main() output.to_csv(FILE_PATH.value.replace('.csv', '_validated.csv'), sep=',') print('Validated! Please verify the output') FILE_PATH = Text(placeholder='Path to file') VALIDATE_BUTTON = Button(description="Validate!", button_style="primary") FUNCTION = Dropdown(description="Select a File Type", options=['FileType1']) VALIDATE_BUTTON.on_click(get_clicked) FILE_PATH.layout.width = '75%' display(FILE_PATH, FUNCTION) display(VALIDATE_BUTTON)
def __init__(self, model, *args, **kwargs): self.model = model self._fields = {field: Text() for field in self.model.fields} self.radio_button_group = RadioButtons( description="When:", options=[ "All", "30 Days", "24 Hours", "1 Year", "1 Week", "1 Hour" ], ) self.refresh_button = Button(description="Refresh") date_buttons = VBox([self.radio_button_group, self.refresh_button]) self.since_widget = DatetimePicker() self.until_widget = DatetimePicker() date_range = HBox([ Label(value="Date range:"), self.since_widget, Label(value="-"), self.until_widget, ]) grid_children = [] for field, text in self._fields.items(): grid_children.append(Label(value=f"{field}:")) grid_children.append(text) text_grid = GridBox(children=grid_children, layout=Layout(grid_template_columns="30% 70%")) text_input = VBox([date_range, text_grid]) children = (date_buttons, text_input) if self.model.text_search_supported: full_text_label = Label("Full Text Search:") self.text_search_input = Text() text_grid.children += (full_text_label, self.text_search_input) self.text_search_input.observe(self._on_text_view_changed, "value") self.model.events.text.connect(self._on_text_model_changed) super().__init__(children, **kwargs) self.radio_button_group.observe(self._on_radio_button_changed, "value") self.refresh_button.on_click(self._on_reload_request) self.model.events.reload.connect(self._on_reload) self.model.events.query.connect(self._on_reload) self.since_widget.observe(self._on_since_view_changed, "value") self.model.events.since.connect(self._on_since_model_changed) self.until_widget.observe(self._on_until_view_changed, "value") self.model.events.until.connect(self._on_until_model_changed) # Set these values here so the model picks the values up self.model.since = GRACE_HOPPER_BIRTHDAY self.model.until = timedelta() self.radio_button_group.index = self.radio_button_group.options.index( "All") for field, text in zip(self.model.fields, self._fields.values()): def on_field_text_changed(change, field=field): self.model.field_search.update({field: change["new"]}) text.observe(on_field_text_changed, "value") self.model.events.field_search_updated.connect( self._on_field_search_updated)
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)
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
style=style) params = interact(set_params, nn=nn_widget, np=np_widget, D=D_widget, p=p_widget, P=P_widget, A=A_widget) #button_init = Button(description="Init", on_click = init) #button_init.on_click(init) #button_init ########## """ Button( description='Click me', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', icon='check' # (FontAwesome names without the `fa-` prefix) ) """ #button_init = Button(description="Init") #button_init.on_click(init) #p = interact(plot_data, rho_0=FloatSlider(min=0.01, max=0.2, step=0.01, value=0.01), f=IntSlider(0,0,10)) """ # Erdos Renyi network
def __init__(self): self.start_button = Button( value=False, description='Start Camera', disabled=False, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Start the camera and the recognition algorithm.', icon='') self.use_recorded = RadioButtons( options=['Webcam', 'MP4'], value='Webcam', description='Input', disabled=False, layout=Layout(width='320px'), style={'description_width': '150px'}, ) self.video_path = Text( value='', placeholder=str(Path("path", "to", "video.mp4")), description='Video path:', disabled=True, layout=Layout(width='320px'), style={'description_width': '150px'}, ) self.select_network = Dropdown( options=KerasDetector.available_models, value=KerasDetector.available_models[0], description='Algorithm:', disabled=False, layout=Layout(width='220px'), style={'description_width': '100px'}, ) self.select_frontend = Dropdown( options=["opencv", "matplotlib"], value="opencv", description='Frontend:', disabled=False, layout=Layout(width='220px', padding='8px 0 0 0'), style={'description_width': '100px'}, ) self.video_length = FloatText( value=12.0, description='Video length [s]:', disabled=False, layout=Layout(width='250px'), style={'description_width': '130px'}, ) self.select_framerate = Dropdown( options=[3, 5, 10, 15, 24], value=15, description='Frame rate:', disabled=False, layout=Layout(width='250px', padding='8px 0 0 0'), style={'description_width': '130px'}, ) self.static_text = Label( value="Working directory: {}".format(Path.cwd()), layout=Layout(margin='30px 0 0 0'), ) self.progress_text = Label(value='', ) self.text_box = VBox((self.static_text, self.progress_text), layout=Layout(justify_content="flex-start")) self.widget_box = VBox( (HBox((VBox((self.start_button, ), layout=Layout(justify_content="space-around")), VBox((self.use_recorded, self.video_path), layout=Layout(justify_content="space-around")), VBox((self.video_length, self.select_framerate), layout=Layout(justify_content="space-around")), VBox((self.select_network, self.select_frontend), layout=Layout(justify_content="space-around"))), ), HBox((self.text_box, ), layout=Layout(justify_content="flex-start"))), ) self.start_button.on_click(self._start_video) self.use_recorded.observe(self.refresh_state)