def make_form(): k1 = widgets.Text( value='Hello World', placeholder='KA', description='Keyword A', disabled=False, layout=widgets.Layout(width='50%') ) k2 = widgets.Text( value='Hello Wrld', placeholder='KB', description='Keyword B', disabled=False, layout=widgets.Layout(width='50%') ) s = widgets.IntSlider( value=70, min=20, max=80, step=1, description='% for train:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d' ) w = widgets.VBox((k1,k2,s)) return w, k1, k2, s
def displayOptions(self): clear_output() self.html = widgets.HTML( '<h4>Sqlite database "%s" exists, do you want to overwrite?</h4>' '<h4>choose <b>yes</b> will <span style="color:red"><b>clear all the data</b></span> in that database file</h4>' % self.dbpath) self.toggle = widgets.ToggleButtons( options=['Yes', 'No'], description='', disabled=False, value='No', button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Replace the old database', 'Append data to the old database'], layout=widgets.Layout(width='70%') # icons=['check'] * 3 ) self.toggle.observe(self.on_click, 'value') self.html2 = widgets.HTML( '<h4>Do you want to import new data?</h4>') self.toggle2 = widgets.ToggleButtons( options=['Yes', 'No'], description='', disabled=False, value='No', button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Add new data to db', 'Use existing data in db'], layout=widgets.Layout(width='70%') ) # pad the descriptions list if it is shorter than options list self.resetParameters() self.box = self.updateBox() display(self.box) pass
def _generate_visual(self): 'Layout widgets.' sorted_widgets = [] for i in [ 'macro_stress_strain', 'plastic_stress_strain', 'shear_stress_strain', 'hardening_rate', ]: if i in self._widgets: sorted_widgets.append(self._widgets[i]) vertical_children = [] for w in sorted_widgets: horizontal_children = [w['fig']] vertical_sub_children = [v for k, v in w['controls'].items()] horizontal_children.append( widgets.VBox( vertical_sub_children, layout=widgets.Layout( margin='5rem 0 0 5rem', width='40%', #border='1px solid red', ))) vertical_children.append( widgets.HBox( horizontal_children, layout=widgets.Layout(margin='0', #border='1px solid blue', ))) return widgets.VBox(vertical_children)
def createHistoryPanel(self): self.activeui = widgets.SelectMultiple( options=[], value=[], rows=4, disabled=False ) self.activeui.layout = widgets.Layout(width='99%') self.historyui = widgets.SelectMultiple( options=[], value=[], rows=4, disabled=False ) self.historyui.layout = widgets.Layout(width='99%') bt = widgets.Button( description = 'Recreate plot', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='re creates plot', ) bt.on_click(lambda e : GlueManagerWidget.restorePlot(self)) hb4 = widgets.HBox([self.historyui, bt]) vb4 = widgets.VBox([self.activeui, hb4]) return vb4
def __init__(self, instrument='CG1D', facility='HFIR', list_files=[], oncat=None, projection=[], with_progressbar=False): projection.append('ingested') if with_progressbar: box1 = widgets.HBox([widgets.Label("Retrieving Metadata ...", layout=widgets.Layout(width='30%')), widgets.IntProgress(max=len(list_files), layout=widgets.Layout(width='70%'))]) display(box1) slider = box1.children[1] self.datafiles = {} for _index, _file in enumerate(list_files): self.datafiles[_file] = oncat.Datafile.retrieve(_file, facility=facility, instrument=instrument, projection=projection) if with_progressbar: slider.value = _index if with_progressbar: box1.close()
def __init__(self, text, correct, *wrong, sonst=False, inst=None): self.selection = "" self.richtig = correct def makeAnswers(correct, wrong): allAnsw = ["Keine der Alternativen"] + wrong allAnsw.append(correct) allAnsw.sort() return allAnsw allAnsw = makeAnswers(correct, list(wrong)) textbox = widgets.HTML(value='<h4 style="font-size:14px;">{}</h4>'.format(text)) instbox = widgets.HTML(value='<i>{}</i>'.format(inst), layout=widgets.Layout(justify_content="center")) answer = widgets.Dropdown(options = allAnsw, value= allAnsw[0], description="Antwort:", layout={'width': '500px'}) button = widgets.Button(description="Korrekt?",layout=widgets.Layout(width="250px")) super().__init__(children=[textbox, instbox, answer, button]) def on_change_drop(change): if change['type'] == 'change' and change['name']=='value': self.selection = change['new'] button.style.button_color = None answer.observe(on_change_drop) def on_button_clicked(b): if self.selection == self.richtig: b.style.button_color = 'lightgreen' else: b.style.button_color = 'red' button.on_click(on_button_clicked)
def __init__(self, options=None, is_lower_better=True, **kwargs): self.is_desc = is_lower_better self.options = None self.curr_option = None self.sort = widgets.Button(icon=self.sort_icon, disabled=True, layout=widgets.Layout(**BUTTON_LAYOUT)) self.prev = widgets.Button(icon="angle-left", disabled=True, layout=widgets.Layout(**BUTTON_LAYOUT)) self.drop = widgets.Dropdown(layout=widgets.Layout(**TEXT_LAYOUT)) self.next = widgets.Button(icon="angle-right", disabled=True, layout=widgets.Layout(**BUTTON_LAYOUT)) # Handler definition self.sort.on_click(self.reverse_options) self.prev.on_click(self.prev_option) self.drop.observe(self.select_option, names="value") self.next.on_click(self.next_option) super().__init__(**kwargs) if options is not None: self.update_state(0, options)
def __bottom_panel(self): list_ui = [] if self.prev_button: self.prev_button_ui = widgets.Button( description="<< Previous Step", tooltip='Click to move to previous step', button_style='success', disabled=False, layout=widgets.Layout(width='20%')) self.prev_button_ui.on_click(self.prev_button_clicked) list_ui.append(self.prev_button_ui) self.current_state_label_ui = widgets.Label( " ", layout=widgets.Layout(width='70%')) list_ui.append(self.current_state_label_ui) if self.next_button: self.next_button_ui = widgets.Button( description="Next Step>>", tooltip='Click to move to next step', button_style='warning', disabled=True, layout=widgets.Layout(width='20%')) list_ui.append(self.next_button_ui) self.next_button_ui.on_click(self.next_button_clicked) self.bottom_panel = widgets.HBox(list_ui)
def list_elements(self): retrieve_material = RetrieveMaterialMetadata(material='all') self.list_returned = retrieve_material.full_list_material() # import pprint # pprint.pprint(list_returned) box4 = widgets.HBox([ widgets.Label("List of elements", layout=widgets.Layout(width=self.label_width)), widgets.Text(','.join(self.list_of_elements), layout=widgets.Layout(width='20%')) ]) box5 = widgets.HBox([ widgets.Label("Nbr Bragg Edges", layout=widgets.Layout(width=self.label_width)), widgets.Text(str(8), layout=widgets.Layout(width='20%')) ]) vertical_box = widgets.VBox([box4, box5]) display(vertical_box) self.list_elements_ui = box4.children[1] self.nbr_bragg_edges_ui = box5.children[1]
def display_metadata_list(self): self.list_images = self.get_list_of_images() list_images = self.list_images self.record_file_extension(filename=list_images[0]) image0 = list_images[0] o_image0 = Image.open(image0) info = collections.OrderedDict(sorted(o_image0.tag_v2.items())) display_format = [] list_default_value_selected = [] dict_of_metadata = {} for tag, value in info.items(): formatted_string = "{} -> {}".format(tag, value) dict_of_metadata[formatted_string] = tag display_format.append(formatted_string) if tag in self.default_metadata_to_select: list_default_value_selected.append(formatted_string) self.box1 = widgets.HBox([widgets.Label("Select Metadata:", layout=widgets.Layout(width='10%')), widgets.SelectMultiple(options=display_format, value=list_default_value_selected, layout=widgets.Layout(width='50%', height='300px'))]) display(self.box1) self.dict_of_metadata = dict_of_metadata
def __init__(self, *, slider_min, slider_max, slide_fn=None, **kwargs): self.slider = widgets.FloatSlider(min=slider_min, max=slider_max, step=1, readout=False, layout=widgets.Layout(width="80%")) self.slider.observe(slide_fn, "value") slider_box = [widgets.HTML(value=str(slider_min)), self.slider, widgets.HTML(value=str(slider_max))] self.slider_box = widgets.HBox(slider_box, layout=widgets.Layout(justify_content="center")) super().__init__(**kwargs)
def updateBox(self): self.text_areas = [ widgets.Textarea(value='\n'.join(self.filters[type_name]), placeholder=self.placeholder, description='"' + type_name + '" :', disabled=False, layout=widgets.Layout(width=self.width, height=self.height)) for type_name in self.types ] if self.width.endswith("%"): column_width = str(int(self.width[:-1]) + 5) + '%' elif self.width.endswith("px"): column_width = str(int(self.width[:-2] + 10)) + 'px' else: column_width = str(int(self.width) + 10) boxed_text_areas = widgets.HBox([ widgets.VBox(self.text_areas[0::2], layout=widgets.Layout(width=column_width)), (widgets.VBox(self.text_areas[1::2], layout=widgets.Layout(width=column_width)) if len(self.text_areas) > 0 else None) ], layout=widgets.Layout(width='100%')) rows = [self.title] + [boxed_text_areas] + self.addSeparator() + [ self.addPreviousNext(self.show_previous, self.show_next) ] self.box = widgets.VBox(rows, layout=widgets.Layout(display='flex', flex_grown='column')) pass
def __init__(self, rl_ch=12, ud_ch=13, bus=1): self.sg = ServoGroup(rl_ch=rl_ch, ud_ch=ud_ch, bus=bus) self.sg.reset() #Pan and tilt go to default position #Setup various widgets self.panel_step_move = NineButton( button_list=['↖', '↑', '↗', '←', 'reset', '→', '↙', '↓', '↘']) self.panel_far_move = NineButton( button_list=['◤', '▲', '◥', '◄', 'reset', '►', '◣', '▼', '◢']) self.image_widget = widgets.Image( format='jpeg', width=400, height=300) #Display resolution setting self.snap_count = widgets.IntText(description='count:', layout=widgets.Layout(width='140px'), value=0) self.rl_textbox = widgets.IntText(layout=widgets.Layout(width='140px'), value=self.sg.read()[0], description='rl:') self.ud_textbox = widgets.IntText(layout=widgets.Layout(width='140px'), value=self.sg.read()[1], description='ud:') self.rl_slider = widgets.FloatSlider(min=-1, max=1, value=0, step=0.02, description='rl') self.ud_slider = widgets.FloatSlider(min=-1, max=1, value=0, step=0.02, description='ud') self.snap_dir = 'snap' #Folder name for saving snapshot self.camera_link = None self.press_count = 0
def retrieve_parameters(self): if self.uniqueness: list_of_input_files = glob.glob( os.path.join(self.working_dir, '*' + self.dominant_extension)) list_of_input_files.sort() self.result = self.Result(list_files=list_of_input_files, ext=self.dominant_extension, uniqueness=True) else: list_of_maj_ext = [ _ext for _ext in self.counter_extension.keys() if self.counter_extension[_ext] == self.dominant_number ] box = widgets.HBox([ widgets.Label("Select Extension to work with", layout=widgets.Layout(width='20%')), widgets.Dropdown(options=list_of_maj_ext, layout=widgets.Layout(width='20%'), value=list_of_maj_ext[0]) ]) display(box) self.dropdown_ui = box.children[1]
def createSubsetsPanel(self): self.subsetsui = widgets.HBox([], layout=widgets.Layout(display='flex', flex_flow='wrap')) self.updateSubsets() cr = widgets.Button( description='Create subset from selection', disabled=False, button_style='', tooltip='create a new subset from current selection', layout=widgets.Layout(width='100%')) tx = widgets.Text(value='', placeholder='New subset name', disabled=False, layout=widgets.Layout(width='auto')) cr.on_click( lambda e: GlueManagerWidget.createSubsetFromSelection(self, tx)) hb1 = widgets.HBox([cr], layout=widgets.Layout(width='auto')) vb1 = widgets.VBox([self.subsetsui, tx, hb1], layout=widgets.Layout(width='auto')) return vb1
def get_header(self): """ Builds the header section for the Hangman app. Contains: Mystery Word: A blank word representing the word to be guessed. Letters are revealed following correct guesses. Remaining Guesses: The number of guesses remaining before the player loses the game. Player Info: The current players' name, score and win percentage. The appearence of the header section is dependent on the status of the current game. """ info = { -1: ['red', self.game.target_word], 0: ['black', ' '.join(self.game.word)], 1: ['green', self.game.target_word] } mystery_word = widgets.HTML( f"<h1><font color={info[self.game.status][0]}>Mystery Word:\ {info[self.game.status][1]}</h1>", layout=widgets.Layout(width="500px")) remaining_guesses = widgets.HTML( f"<h2><font color='black'>Remaining Guesses:\ {str(self.game.remaining_guesses)}</h2>", layout=widgets.Layout(height='auto')) player_info = self.get_player_info() self.header = widgets.HBox( [widgets.VBox([mystery_word, remaining_guesses]), player_info])
def retrieve_time_stamp(list_images): [_, ext] = os.path.splitext(list_images[0]) if ext.lower() in ['.tiff', '.tif']: ext = 'tif' elif ext.lower() == '.fits': ext = 'fits' else: raise ValueError box = widgets.HBox([widgets.Label("Retrieving Time Stamp", layout=widgets.Layout(width='20%')), widgets.IntProgress(min=0, max=len(list_images), value=0, layout=widgets.Layout(width='50%')) ]) progress_bar = box.children[1] display(box) list_time_stamp = [] list_time_stamp_user_format = [] for _index, _file in enumerate(list_images): _time_stamp = MetadataHandler.get_time_stamp(file_name=_file, ext=ext) _time_stamp = _convert_epics_timestamp_to_rfc3339_timestamp(_time_stamp) list_time_stamp.append(_time_stamp) _user_format = convert_to_human_readable_format(_time_stamp) list_time_stamp_user_format.append(_user_format) progress_bar.value = _index + 1 box.close() return {'list_images': list_images, 'list_time_stamp': list_time_stamp, 'list_time_stamp_user_format': list_time_stamp_user_format}
def __load_files(self): progress_bar_layout = widgets.Layout(border='1px solid blue') hbox = widgets.HBox([ widgets.IntProgress(description="FUll Progress", layout=progress_bar_layout), widgets.Label(value='', layout=widgets.Layout(width='10%')) ]) w = hbox.children[0] nbr_groups = len(self.exp_dict.keys()) w.max = nbr_groups label = hbox.children[1] label.value = f"0/{nbr_groups}" display(hbox) for _index, _key in enumerate(self.exp_dict.keys()): _item = self.exp_dict[_key] _path = _item['folder'] list_files = _item['list_of_files'] full_list_files = [ os.path.join(_path, _file) for _file in list_files ] o_norm = Normalization() o_norm.load(file=full_list_files, notebook=True) _data = o_norm.data['sample']['data'] _item['list_of_images'] = _data self.exp_dict[_key] = _item w.value = _index + 1 label.value = f"{_index+1}/{nbr_groups}" hbox.close() display(widgets.Label(value="Done!"))
def __init__(self, *, plot_fn=None, click_fn=None, unclick_fn=None, marker_params=None, title="", init_click_coords=None, toolbar_position="left", figsize=(4.5, 4.5)): list_args = align_args(plot_fn, click_fn, unclick_fn, marker_params, title) self.plot_fn_list, self.click_fn_list, self.unclick_fn_list, marker_params_list, self.title_list = list_args self.marker_params_list = [] for params in marker_params_list: if params is None: params = {} params = {"marker": "+", "color": "black", **params} self.marker_params_list.append(params) self.n_views = len(self.plot_fn_list) self.current_view = 0 self.click_time = None self.click_marker = None self.init_click_coords = init_click_coords # Construct a figure self.toolbar_position = toolbar_position if toolbar_position is None: toolbar_position = "left" with plt.ioff(): # Add tight_layout to always correctly show colorbar ticks self.fig, self.ax = plt.subplots(figsize=figsize, tight_layout=True) # pylint: disable=invalid-name self.fig.canvas.header_visible = False self.fig.canvas.toolbar_visible = False self.fig.canvas.toolbar_position = toolbar_position # Setup event handlers self.fig.interactive_plotter = self # Always keep reference to self for all plots to remain interactive self.fig.canvas.mpl_connect("resize_event", self.on_resize) if self.is_clickable: self.fig.canvas.mpl_connect("button_press_event", self.on_click) self.fig.canvas.mpl_connect("button_release_event", self.on_release) self.fig.canvas.mpl_connect("key_press_event", self.on_press) # Build plot box self.title_widget = widgets.HTML(value="", layout=widgets.Layout(**TEXT_LAYOUT)) self.view_button = widgets.Button( icon="exchange", tooltip="Switch to the next view", layout=widgets.Layout(**BUTTON_LAYOUT)) self.view_button.on_click(self.on_view_toggle) self.header = self.construct_header() self.toolbar = self.construct_toolbar() self.box = self.construct_box()
class Carousel(w.Box, _CollectionMixin, _FauxTitleMixin): layout = w.Layout( flex_flow='row nowrap', overflow_x='auto', overflow_y='visible', max_width='100%', ) output_layout = w.Layout(flex='1 0 auto') #w.Layout(min_width='60%')
def merging(self, output_folder): """combine images using algorithm provided""" # get merging algorithm merging_algo = self.combine_method.value algorithm = self.__add if merging_algo == 'mean': algorithm = self.__mean # get output folder output_folder = os.path.abspath(output_folder) # create dictionary of how the images will be combined merging_dict = self.__create_merging_dictionary() self.merginc_dict_debugging = merging_dict # create final list of files to merge final_dict_of_files_to_merge = self.__create_dict_of_files_to_merge(merging_dict) self.final_dict_of_files_to_merge_debugging = final_dict_of_files_to_merge final_nbr_folders = len(merging_dict.keys()) folder_level_ui = widgets.HBox([widgets.Label("Folder Progress:", layout=widgets.Layout(width='20%')), widgets.IntProgress(max=final_nbr_folders, layout=widgets.Layout(width='50%'))]) display(folder_level_ui) w1 = folder_level_ui.children[1] nbr_files_to_merge = self.nbr_files_in_each_folder file_level_ui = widgets.HBox([widgets.Label("File Progress:", layout=widgets.Layout(width='20%')), widgets.IntProgress(max=nbr_files_to_merge, layout=widgets.Layout(width='50%'))]) display(file_level_ui) w2 = file_level_ui.children[1] for _index_final_folder, _final_folder in enumerate(final_dict_of_files_to_merge.keys()): file_handler.make_or_reset_folder(os.path.join(output_folder, _final_folder)) list_files_to_merge = final_dict_of_files_to_merge[_final_folder] for _index_files_to_merge, _files_to_merge in enumerate(list_files_to_merge): _files_to_merge = [_file for _file in _files_to_merge] self.files_to_merge_for_testing = _files_to_merge o_load = Normalization() o_load.load(file=_files_to_merge) _data = o_load.data['sample']['data'] combined_data = self.__merging_algorithm(algorithm, _data) self.combined_data_for_testing = combined_data _base_name_file = os.path.basename(_files_to_merge[0]) output_file_name = os.path.join(output_folder, _final_folder, _base_name_file) file_handler.save_data(data=combined_data, filename=output_file_name) w2.value = _index_files_to_merge + 1 w1.value = _index_final_folder + 1
def createSubsetsPanel(self): self.subsetsui = widgets.SelectMultiple( options=[sset.label for sset in self.gluemanager.data.subsets], value=[], rows=4, disabled=False ) self.subsetsui.layout = widgets.Layout(width='99%') bt = widgets.Button( description='Create new Subset.', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='createa new subset from current selection', ) bt.layout = widgets.Layout(width='99%') tx = widgets.Text( value='', placeholder='new subset name', disabled=False ) tx.layout = widgets.Layout(width='99%') bt.on_click(lambda e : GlueManagerWidget.createSubsetFromSelection(self, tx)) dl = widgets.Button( description='remove selected Subsets', disabled=False, button_style='danger', tooltip='Removes active subsets from the data workspace', ) dl.layout = widgets.Layout(width='99%') dl.on_click(lambda e : GlueManagerWidget.deleteSubsetFromSelection(self)) sl = widgets.Button( description='Hide selected subsets', disabled=False, button_style='warning', tooltip='', ) sl.layout = widgets.Layout(width='99%') vb = widgets.VBox([dl, sl]) vb2 = widgets.VBox([tx, bt]) hb1 = widgets.HBox([vb2,self.subsetsui,vb]) vb3 = widgets.VBox([hb1]) return vb3
def export(self): output_folder = self.output_folder_ui.selected input_folder_basename = os.path.basename(self.image_folder) output_folder = os.path.join( output_folder, input_folder_basename + '_with_timestamp_info') if os.path.exists(output_folder): import shutil shutil.rmtree(output_folder) os.makedirs(output_folder) text_x = self.preview.widget.result['text_x'] text_y = self.preview.widget.result['text_y'] pre_text = self.preview.widget.result['pre_text'] post_text = self.preview.widget.result['post_text'] color = self.preview.widget.result['color'] def plot_selected_image(index): _short_file = os.path.basename(self.list_files[index]) output_file_name = os.path.abspath( os.path.join(output_folder, _short_file + '.png')) font = { 'family': 'serif', 'color': color, 'weight': 'normal', 'size': 16 } fig = plt.figure(figsize=(15, 10)) gs = gridspec.GridSpec(1, 1) ax = plt.subplot(gs[0, 0]) im = ax.imshow(self.images_array[index], interpolation='nearest') plt.title("image index {}".format(index)) plt.text(text_x, text_y, "{}{:.2f}{}".format(pre_text, self.list_time_offset[index], post_text), fontdict=font) fig.colorbar(im) plt.savefig(output_file_name) plt.close(fig) box = widgets.HBox([ widgets.Label("Exporting Images:", layout=widgets.Layout(width='20%')), widgets.IntProgress(min=0, max=len(self.list_files) - 1, layout=widgets.Layout(width='50%')) ]) progress_bar = box.children[1] display(box) for _index in np.arange(len(self.list_files)): plot_selected_image(index=_index) progress_bar.value = _index + 1
def print_result(self): timestamp_text_area = ["File name -> Time stamp (s)\n"] for _index, _file in enumerate(self.list_files): _short_file = os.path.basename(_file) _time = self.list_time_stamp[_index] _text = "{} -> {}".format(_short_file, _time) timestamp_text_area.append(_text) timestamp_text_area = "\n".join(timestamp_text_area) relative_text_area = [ "file name -> (current image acquistion time - previous image acquisition time) \n" ] for _index, _file in enumerate(self.list_files): _short_file = os.path.basename(_file) _relative_time = self.relative_time_offset[_index] _text = "{} -> {}".format(_short_file, _relative_time) relative_text_area.append(_text) relative_text_area = "\n".join(relative_text_area) absolute_text_area = [ "file name -> (current image acquistion time - first image acquisition time) \n" ] for _index, _file in enumerate(self.list_files): _short_file = os.path.basename(_file) _absolute_time = self.absolute_time_offset[_index] _text = "{} -> {}".format(_short_file, _absolute_time) absolute_text_area.append(_text) absolute_text_area = "\n".join(absolute_text_area) children = [ widgets.Textarea("", layout=widgets.Layout(width="100%", height="300px")), widgets.Textarea("", layout=widgets.Layout(width="100%", height="300px")), widgets.Textarea("", layout=widgets.Layout(width="100%", height="300px")) ] tab = widgets.Tab() tab.children = children tab.set_title(0, "Time Stamp(s)") tab.set_title(1, "Relative (s)") tab.set_title(2, "Absolute (s)") timestamp_text = children[0] timestamp_text.value = timestamp_text_area relative_text = children[1] relative_text.value = relative_text_area absolute_text = children[2] absolute_text.value = absolute_text_area display(tab)
def select_gamma_coefficient(self): self.gamma_coeff_ui = widgets.HBox([ widgets.Label("Gamma Coefficient:", layout=widgets.Layout(width="20%")), widgets.FloatSlider(value=gamma_filtering_coefficient, min=0, max=1, layout=widgets.Layout(width="50%")) ]) display(self.gamma_coeff_ui)
def select_vertical_pixel_binning(self): box = widgets.HBox([widgets.Label("Vertical Binning", layout=widgets.Layout(width='20%')), widgets.Dropdown(options=['1','2','3','4','5','6','7','8','9'], value='1', layout=widgets.Layout(width='20%')), ]) display(box) self.bin_ui = box.children[1]
def select_instrument(self): list_instruments = list(LIST_SANS_INSTRUMENTS.keys()) instrument_ui = widgets.HBox([ widgets.Label("Select your instrument", layout=widgets.Layout(width='15%')), widgets.Select(options=list_instruments, layout=widgets.Layout(width='30%', height='50px')) ]) display(instrument_ui) self.instrument_list_ui = instrument_ui.children[1]
def create_view_all_comments_widget(ws_names2id: Dict[str, str], ws_paths: Dict[str, WorkspacePaths], output): """Create an ipywidget UI to display the contents of all comment files within a particular workspace.""" workspace_chooser = widgets.Dropdown( options=ws_names2id, value=None, description='<b>Choose a workspace to view:</b>', style={'description_width': 'initial'}, layout=widgets.Layout(width='900px') ) def on_choose_workspace(changed): with output: output.clear_output() workspace_paths = ws_paths[changed['new']] try: comment_files = tf.io.gfile.glob(pattern=workspace_paths.get_comment_file_glob()) except tf.errors.PermissionDeniedError as e: target_workspace = [name for name, id in ws_names2id.items() if id == changed['new']] display(HTML(f'''<div class="alert alert-block alert-danger"> <b>Warning:</b> Unable to view HTML snapshots in workspace {target_workspace} from <b>this workspace</b>. <hr><p><pre>{e.message}</pre></p> </div>''')) return if not comment_files: display(HTML('''<div class="alert alert-block alert-warning"> No comment files found for HTML snapshots in this workspace.</div>''')) return def get_comment(f): with tf.io.gfile.GFile(f, 'r') as fh: return fh.readlines() def process_task(f): return f, get_comment(f) max_pool = 8 with Pool(max_pool) as p: pool_outputs = list(tqdm(p.imap(process_task, comment_files), total=len(comment_files))) comments = pd.DataFrame.from_dict({f.replace(workspace_paths.get_subfolder(), ''): c[0] for f, c in pool_outputs}, orient = 'index', columns = ['comment'] ).reset_index() comments[['extra', 'author', 'date', 'time', 'item']] = comments['index'].str.split(pat='/', expand=True) display(comments[['date', 'time', 'author', 'item', 'comment']].sort_values(by=['date', 'time']).reset_index(drop=True)) workspace_chooser.observe(on_choose_workspace, names='value') return widgets.VBox( [widgets.HTML(''' <h3>View all comments for a workspace</h3> <p>Use the dropdown to choose a workspace. Then this will display the contents of all comment files for the selected workspace. <br>The user, date, time, and notebook name are shown in the left column. The comment is shown in the right column. </p><hr>'''), workspace_chooser], layout=widgets.Layout(width='auto', border='solid 1px grey'))
def __init__(self, text, correctChoice, *wrongChoices, sonst=False, inst=single): choices = list(wrongChoices) choices.append(correctChoice) choices.sort() buttons = [ widgets.Button(description=choice, layout=widgets.Layout(width="250px")) for choice in choices ] if sonst: buttons.append( widgets.Button(description="Keine der anderen Möglichkeiten", layout=widgets.Layout(width="250px"))) def on_button_clicked(b): choice = b.description if b.style.button_color == 'lightgreen' or b.style.button_color == 'red': b.style.button_color = None else: b.style.button_color = 'lightgreen' if choice == self.correct else 'red' if self.answered: #b.style.button_color = None #self.answered = False return self.answered = True # textbox.layout.border = "2px solid lightgreen" if choice == self.correct else "2px solid red" for button in buttons: button.on_click(on_button_clicked) allbox = [] while not buttons == []: if len(buttons) > 2: allbox.append(widgets.HBox(children=[buttons[0], buttons[1]])) buttons.pop(0) buttons.pop(0) else: allbox.append(widgets.HBox(children=buttons)) break textbox = widgets.HTML( value='<h4 style="font-size:14px;">{}</h4>'.format(text), layout=widgets.Layout(justify_content="center")) instbox = widgets.HTML(value='<i>{}</i>'.format(inst), layout=widgets.Layout(justify_content="center")) super().__init__(children=[textbox, instbox] + allbox) self.correct = correctChoice self.answered = False
def export(self): output_folder = self.output_folder_ui.selected input_folder_basename = os.path.basename(self.folder_ui.selected) output_folder = os.path.join( output_folder, input_folder_basename + '_vs_metadata_screenshots') if os.path.exists(output_folder): import shutil shutil.rmtree(output_folder) os.makedirs(output_folder) def plot_images_and_profile(file_index=0): fig = plt.figure(figsize=(15, 10)) gs = gridspec.GridSpec(1, 2) _short_file = os.path.basename(self.images_list[file_index]) _time = self.metadata_profile[_short_file]['time'] _metadata = self.metadata_profile[_short_file]['metadata'] ax_img = plt.subplot(gs[0, 0]) ax_img.imshow(self.images_array[file_index]) plt.title("{}".format(_short_file)) ax_plot = plt.subplot(gs[0, 1]) ax_plot.plot(self.time_array, self.metadata_array, '*') ax_plot.axvline(x=_time, color='r') plt.xlabel('Time (s)') plt.ylabel(self.metadata_name) output_file_name = os.path.abspath( os.path.join(output_folder, _short_file + '.png')) plt.savefig(output_file_name) plt.close(fig) box = widgets.HBox([ widgets.Label("Exporting Images:", layout=widgets.Layout(width='20%')), widgets.IntProgress(min=0, max=self.nbr_images - 1, layout=widgets.Layout(width='50%')) ]) progress_bar = box.children[1] display(box) for _index in np.arange(self.nbr_images): plot_images_and_profile(file_index=_index) progress_bar.value = _index + 1 box.close() display( HTML('<span style="font-size: 20px; color:blue">Images created in ' + output_folder + '</span>'))