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 __init__(self, rm, vars=None, show_jobs=True, wide_display=True): self.rm_original = rm if vars is None: fname = os.path.join(rm.savedir_base, '.dashboard_history.json') if os.path.exists(fname): self.vars = hu.load_json(fname) else: self.vars = {} self.vars = vars self.show_jobs = show_jobs self.wide_display = wide_display self.layout = widgets.Layout(width='100px') self.layout_label = widgets.Layout(width='200px') self.layout_dropdown = widgets.Layout(width='200px') self.layout_button = widgets.Layout(width='200px') self.t_savedir_base = widgets.Text( value=str(self.vars['savedir_base']), layout=widgets.Layout(width='600px'), disabled=False) self.t_filterby_list = widgets.Textarea( value=str(self.vars.get('filterby_list')), layout=widgets.Layout(width='600px'), disabled=False)
def initiate(self): self.controller.initiation_in_progress = True datepicker = self._date_picker() self.date_picker.value = pd.to_datetime( self.controller.valid_dates_selection[0]) plot_settings = self._plot_settings() notes = self._notes() self._notes_update() accordion = widgets.Accordion(children=(self._tags_constrain(), self._tags_assign(), plot_settings, notes)) for e, key in enumerate( ['select by tags', 'assign tags', 'plot settings', 'notes']): accordion.set_title(e, key) # accordion.set_title(1, 'plot settings') # accordion.set_title(2, 'notes') l = Layout(flex='0 1 auto', height='240px', min_height='240px', width='auto') self.messages = widgets.Textarea( '\n'.join(self.controller._message), # layout={'width': '100%'}, layout=l) vbox = widgets.VBox([datepicker, accordion, self.messages]) display(vbox) self.controller.initiation_in_progress = False
def create_input(q, textarea=False, code=False): if role == 'student': if not code: if textarea: w = widgets.Textarea(placeholder='Vul in...', value=answers[q]['answer']) else: w = widgets.Text(placeholder='Vul in...', value=answers[q]['answer']) w.question = q w.observe(answer_changed) else: w = widgets.HTML('') else: if len(answers[q]['answer'].strip()): answer = answers[q]['answer'].replace('\n', '<br />') else: if code: answer = '<em style="color: #ccc; font-size: 12pt; margin-bottom: -2px;">Code:</em>' else: answer = '<em style="color: #ccc;">Geen antwoord</em>' w = widgets.HTML("<span class='teacher-answer'>%s</span>" % answer) return w
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 i_show_logs(job_prefix): """ """ from ipywidgets import widgets, Layout from IPython.display import display, clear_output from os.path import isfile outfile = f'{job_prefix}.output' errfile = f'{job_prefix}.error' logfile = f'{job_prefix}.cobaltlog' if (isfile(outfile)): with open(outfile, 'r') as f: out = f.read() with open(errfile, 'r') as f: err = f.read() with open(logfile, 'r') as f: log = f.read() children = [ widgets.Textarea(value=val, layout=Layout(flex='1 1 auto', width='100%', height='400px')) for name, val in [(outfile, out), (errfile, err), (logfile, log)] ] tab = widgets.Tab(children=children, layout=Layout(flex='1 1 auto', width='100%', height='auto')) #ow = widgets.Textarea(value=out,description=outfile) #ew = widgets.Textarea(value=err,description=errfile) #lw = widgets.Textarea(value=log,description=logfile) tab.set_title(0, outfile) tab.set_title(1, errfile) tab.set_title(2, logfile) display(tab) return
def _initialize_widgets(self): """ Set up image display, ROI saving UI and ROI view/edit text box. Creates instance attributes that we'll reference elsewhere """ matplotlib.use( "nbAgg") # Engage interactive mode. this is a global setting self.figure, self.axes = plt.subplots( figsize=(10, 8), num="ROI selection" # num = Figure name in the UI. ) self.figure.tight_layout(pad=0) self.roi_rectangle_selector = RectangleSelector( self.axes, self._handle_rectangle_change, drawtype="box", useblit=True, interactive=True, rectprops=dict(edgecolor="#00ff00", fill=False), ) self.roi_text_box = widgets.Textarea( description="ROIs:", disabled=False, # Since input often goes through invalid states while the user is typing, # Only trigger the callback when user submits or changes focus away continuous_update=False, ) self.roi_text_box.layout.height = "150px" self.roi_text_box.layout.width = "100%" self.roi_text_box.observe(self._handle_roi_text_box_change, names="value") display(self.roi_text_box)
def __init__(self): self._log = OrderedDict() self.functions = {} self.pipeline = [] self.subs = [] self.status_widget = widgets.Textarea( description='Status', value='', layout=widgets.Layout(width='80%')) display(self.status_widget)
def __init__(self, Name, BufferSize=10000, height='500px'): l = Layout(flex='0 1 auto', height=height, min_height='40px', width='auto') self.BufferSize = BufferSize self.tba = widgets.Textarea(value='', placeholder='Type something', description=Name, disabled=False, layout=l) display(self.tba)
def __init__(self, layout=None): self._data = "" self.display_html = display_html super(WidgetConsole, self).__init__(widgets.Textarea()) layout_to_use = { 'color': '#000088', 'background': '#eeeeee', 'width': '100%', 'height': '200px', 'border': '1px solid #999999' } if layout: layout_to_use.update(layout) self.set_layout(**layout_to_use)
def get_selection_files(file_list): global TEXT_WIDGETS_DICT la = widgets.Layout(height='250px', width='500px') content_list = get_selection_file_contents(file_list) merge_list = zip(file_list,content_list) TEXT_WIDGETS_DICT = {} for (my_file,my_content) in merge_list: header = "# selection file: "+my_file+"\n \n" TEXT_WIDGETS_DICT[my_file] = widgets.Textarea( value = header + my_content , place_holder='??', disabled = False, description = "selection file:", layout = la ) return TEXT_WIDGETS_DICT
def _notes(self): def on_change(evt): self.controller.database.set_notes(evt['new']) l = Layout(flex='0 1 auto', height='340px', min_height='340px', width='auto') texarea = widgets.Textarea(value='', placeholder='Type something', description='Notes:', disabled=False, layout=l) texarea.observe(on_change, names='value') self.notes = texarea return texarea
def __init__(self, status_widget: Union[widgets.Textarea, bool] = None): self._log = OrderedDict() self.functions = {} self.pipeline = [] self.subs = [] if status_widget is None: self.status_widget = widgets.Textarea( description='Status', value='', layout=widgets.Layout(width='80%')) display(self.status_widget) elif isinstance(status_widget, widgets.Textarea): self.status_widget = status_widget elif not status_widget: self.status_widget = None
def init_widgets(self): # iter slider numiter = widgets.IntSlider(value=50, min=1, step=1) # start button startbutton = widgets.Button(description='start') startbutton.on_click(lambda x: self.play(numiter.value)) # pack iterslider and start button together buttonbox = widgets.HBox() buttonbox.children = [startbutton, numiter] # draw area self.textarea = widgets.Textarea() # packed widget container = widgets.VBox() container.children = [buttonbox, self.textarea] return container
def __init__(self, on_interact=None, output=None, overwrite_previous_output=True, feedback=False, run=True, action_kws={}, *args, **kwargs): super().__init__(on_interact=on_interact, output=output, overwrite_previous_output=overwrite_previous_output, feedback=feedback, action_kws=action_kws) self.widget = widgets.Textarea(*args, **kwargs) if run: self.run()
def recap_merging_list(self): box0 = widgets.VBox([widgets.Label("List of Runs", layout=widgets.Layout(width='100%')), widgets.Select(options=self.master_list_images_to_combine.keys(), layout=widgets.Layout(width='150px', height='300px'))], layout=widgets.Layout(width="160px")) self.list_of_runs_ui = box0.children[1] box1 = widgets.VBox([widgets.Label("List of positions", layout=widgets.Layout(width='100%')), widgets.Select(options=self.get_list_of_position_for_select_run(), layout=widgets.Layout(width='150px', height='300px'))], layout=widgets.Layout(width="160px")) self.list_of_positions_ui = box1.children[1] box2 = widgets.VBox([widgets.Label("List of Files for this position", layout=widgets.Layout(width='100%')), widgets.Select(options=self.get_list_of_files_for_selected_run_position(), layout=widgets.Layout(width='100%', height='500px'))], layout=widgets.Layout(width="815px")) self.list_of_files_ui = box2.children[1] box3 = widgets.VBox([widgets.Label("Metadata"), widgets.Textarea("", disabled=True), widgets.Label("Error allowed: {}".format(METADATA_ERROR))], layout=widgets.Layout(width="300px")) str_metadata = self.get_str_metadata(metadata_dict=self.get_metadata_for_selected_run_position()) self.metadata_recap_textarea = box3.children[1] self.metadata_recap_textarea.value = str_metadata hori_box = widgets.HBox([box0, box1, box2, box3], layout=widgets.Layout(width='100%')) self.list_of_positions_ui.on_trait_change(self.recap_positions_changed, name='value') self.list_of_runs_ui.on_trait_change(self.recap_runs_changed, name='value') display(hori_box)
def __init__(self, Func=None, Name="textArea", FunctionName="Button", BufferSize=10000, height='500px'): l = Layout(flex='0 1 auto', height=height, min_height='40px', width='auto') self.BufferSize = BufferSize self.tba = widgets.Textarea(value='', placeholder='Type something', description=Name, disabled=False, layout=l) self.button = widgets.Button(description=FunctionName) self.Func = Func self.button.on_click(self.pressButton)
def create_widgets(detections): button_layout = widgets.Layout(width="149px", height="100px") detections_widget = widgets.Textarea() button_stop_stream = widgets.Button(description="Stop the stream", button_style="danger", layout=button_layout) button_start_stream = widgets.Button(description="start the stream", button_style="success", layout=button_layout) button_start_search = widgets.Button(description="restart the search", button_style="success", layout=button_layout) button_stop_search = widgets.Button(description="stop the search", button_style="danger", layout=button_layout) detections_widget.value = str(detections) label_widget = widgets.Dropdown( options=[], #rows=10, description='Detection of:', disabled=False, width="200px") search_for_widget = widgets.Dropdown( options=[], #rows=10, description='Search of:', disabled=False, width="200px") labeling = label_widget button_stream_box = widgets.HBox([button_stop_stream, button_start_stream]) button_search_box = widgets.HBox([button_stop_search, button_start_search]) return (button_stream_box, detections_widget, button_stop_stream, button_start_stream, labeling, search_for_widget, button_search_box, button_start_search, button_stop_search)
def i_list_apps(): """ Show apps saved in the Balsam database """ import os from ipywidgets import widgets, Layout from IPython.display import display, clear_output apps = get_apps() children = [ widgets.Textarea(value=str(app), layout=Layout(flex='1 1 auto', width='400px', height='200px')) for app in apps ] tab = widgets.Accordion(children=children, layout=Layout(flex='1 1 auto', width='500px', height='auto')) for i, app in enumerate(apps): tab.set_title(i, app.name) print(f'Apps in the Balsam database {os.environ["BALSAM_DB_PATH"]}:') display(tab) return
def __init__(self, *args): """ Constructs a Trial object. """ self.textform = args[0] self.inc_crit = args[1] self.ex_crit = args[2] display(Markdown(self.textform.incex_title[0])) display(Markdown(self.textform.incex_title[1])) display(Markdown(self.textform.incex_title[2])) display(self.inc_crit.show()) display(Markdown(self.textform.incex_title[3])) display(Markdown(self.textform.incex_title[4])) display(self.ex_crit.show()) display(Markdown("# Kommentare / Anmerkungen")) self.komm_criteria = widgets.Textarea( value='', description='', disabled=False, style={'description_width': 'initial'}, layout=widgets.Layout(width='auto')) display(self.komm_criteria)
#from transformers import AutoTokenizer, AutoModelWithLMHead #import torch #tokenizer = AutoTokenizer.from_pretrained("gorkemgoknar/gpt2-small-turkish") #model = AutoModelWithLMHead.from_pretrained("drive/MyDrive/Rapgen/gpt2-trap-1epoch") # GPT-2 en fazla 1024 tokenlik bir dizi uretebiliyor # tokenizer.model_max_length=1024 #Çalıştırdığınızda bir textbox ve buton çiziyor. # Textbox'ın içine metnin nasıl başlamasını istediğiniz yazıp butona tıklayarak gerisini ürettirebilirsiniz. # Ben her parçayı corpusta ~ işareti ile başlattığım için direk ~ işaretiyle üretimi başlatıyorum. model.eval() # input sequence textui = widgets.Textarea(value='~\n', placeholder='Type something', description='String:', disabled=False) button = widgets.Button( description='Click me', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', icon='check') display(textui) display(button) def handle_submit(sender): print("yes") text = textui.value
def run_widget(): roll = widgets.ToggleButtons( options=['Keep All', 'Drop Lowest Roll'], value='Drop Lowest Roll', description='Roll Modifications:', style={'description_width': 'initial'}, disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['', ''], ) drop_roll = widgets.IntSlider( value=1, min=0, max=3, step=1, description='If Dropping Rolls, How Many?:', style={'description_width': 'initial'}, layout=Layout(width='50%'), disabled=False, ) stat = widgets.ToggleButtons( options=['Keep All', 'Drop Lowest Stat', 'Replace Lowest Stat'], value='Drop Lowest Stat', description='Stat Modifications:', style={'description_width': 'initial'}, disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['', ''], ) drop_stat = widgets.IntSlider( value=1, min=0, max=3, step=1, description='If Dropping Stats, How Many?:', style={'description_width': 'initial'}, layout=Layout(width='50%'), disabled=False, ) replace_stat = widgets.IntSlider( value=18, min=1, max=20, step=1, description='If Replacing Lowest Stat, With What?:', style={'description_width': 'initial'}, layout=Layout(width='50%'), disabled=False, ) name = widgets.Textarea( value='Roll 1d12 + 2d6 Drop Lowest Roll x 7 Drop Lowest Stat', placeholder='Type something', description='Name of Variant:', disabled=False, style={ 'description_width': 'initial', 'width': '10%' }, layout=Layout(width='50%')) n = widgets.Textarea(value='1\n2', placeholder='Type something', description='Number of each Dice', disabled=False, style={'description_width': 'initial'}, layout=Layout(width='50%', height='100px')) s = widgets.Textarea(value='1,2,3,4,5,6,7,8,9,10,11,12\n1,2,3,4,5,6', placeholder='Type something', description='Sides of each Dice ', disabled=False, style={ 'description_width': 'initial', 'width': '10%' }, layout=Layout(width='50%', height='100px')) interact_manual(runRoller, name=name, n=n, s=s, roll=roll, drop_roll=drop_roll, stat=stat, drop_stat=drop_stat, replace_stat=replace_stat)
def display_recommendation_logger(): def create_get_values(): error_html = HTML() display(error_html) clear_error__button = widgets.Button(description='Clear error') clear_error__button.layout.display = 'none' display(clear_error__button) def clear_error(_): error_html.value = '' clear_error__button.layout.display = 'none' clear_error__button.on_click(clear_error) def set_error(error_msg): error_html.value = '<font color=red>{}</font>'.format( error_msg.replace('\n', '<br>\n').replace(' ', ' '), ) clear_error__button.layout.display = 'block' @contextmanager def get_values(*args): """Get values from ipywidgets On success, clear the values of the ipywidgets. On failure, the values of the ipywidgets will be left alone. """ try: yield [a.value for a in args] except KeyboardInterrupt: raise except Exception as e: import traceback set_error('{}\n{}'.format(str(e), traceback.format_exc())) # don't clear the values of the widgets return for a in args: a.value = '' return return get_values get_values = create_get_values() # create buttons recommendation = widgets.Text( description="Recommendation", layout=widgets.Layout(width='100%'), ) recommended_by = widgets.Text(description="By/from") notes = widgets.Textarea( description="Notes", layout=widgets.Layout(width='100%'), ) location = widgets.Text(description="Location") kind = widgets.Text(description="Kind") url = widgets.Text(description="url") when = widgets.Text(description="When") display(recommendation) display(kind) display(recommended_by) display(notes) display(when) display(url) display(location) html_display_of_duplicate_recommendation = HTML() display(html_display_of_duplicate_recommendation) def log_recommendation(recommendation, recommended_by, notes, location, kind, url, when): with get_values(recommendation, recommended_by, notes, location, kind, url, when) as values: recommendation, recommended_by, notes, location, kind, url, when = values when = when.strip() if when: when = parse_timestr(when) with Base.get_session() as sess: thing = Thing.get_row(recommendation, recommended_by, kind, sess) if abs(datetime.datetime.now() - thing.modified_at).total_seconds() > 1: html_display_of_duplicate_recommendation.value = str(thing) #run_search(thing.name).to_html() message = "an entry with this thing.name already exists" raise Exception(message) thing.notes = notes thing.location_str = location thing.url = url if when: thing.created_at = when sess.commit() return elements = [ recommendation, recommended_by, location, kind, url, when, ] log_recommendation_handler = lambda x: log_recommendation( recommendation, recommended_by, notes, location, kind, url, when, ) for e in elements: e.on_submit(log_recommendation_handler)
def single_question_grading_view(self, direction=None): self.sample = self.get_exam_to_grade(direction) row_layout = Layout(display='Flex', flex_flow='row', align_items='stretch', width='100%') col_layout = Layout(display='flex', flex_flow='column', align_items='stretch', border='solid', width='100%') question = widgets.Textarea(value=self.sample.question_text, placeholder='Type something', disabled=True, layout=Layout(width='90%'), continuous_update=True) answer = widgets.Textarea(value=self.sample.answer_text, placeholder='Answer missing', disabled=True, layout=Layout(width='60%', height='200px', continuous_update=True)) # TODO Fix this 100px to auto zero_button = Button(description='zero points', layout=Layout(width='20%')) grade_button = Button(description='grade : ' + str(self.sample.grade), layout=Layout(width='20%'), continuous_update=True) increase_button = Button(description='add points', layout=Layout(width='20%')) next_button = Button(description='next', layout=Layout(width='20%')) previous_button = Button(description='previous', layout=Layout(width='20%')) feedback = widgets.Output(description='feedback output') with feedback: fd = self.create_rubrics_feedback(self.sample, grade_button) display(fd) row_1 = Box([answer, feedback], layout=row_layout) row_2 = Box([previous_button, zero_button, grade_button, next_button], layout=row_layout) complete = Box([question, row_1, row_2], layout=col_layout) def on_save_button(change): self.save_single_jupyter_notebooks() self.sample = self.get_exam_to_grade() question.value = self.sample.question_text answer.value = self.sample.answer_text with feedback: clear_output() fd = self.create_rubrics_feedback(self.sample, grade_button) display(fd) grade_button.value = 'grade : ' + str(self.sample.grade) def on_zero_button(change): self.sample.grade = 0 self.save_single_jupyter_notebooks() self.sample = self.get_exam_to_grade() question.value = self.sample.question_text answer.value = self.sample.answer_text with feedback: clear_output() fd = self.create_rubrics_feedback(self.sample, grade_button) display(fd) grade_button.description = 'grade : ' \ + str(self.sample.grade) def on_increase_button(change): self.sample.grade += 1 grade_button.description = 'grade : ' \ + str(self.sample.grade) def on_next_button(change): self.sample = self.get_exam_to_grade('next') question.value = self.sample.question_text answer.value = self.sample.answer_text with feedback: clear_output() fd = self.create_rubrics_feedback(self.sample, grade_button) display(fd) grade_button.value = 'grade : ' + str(self.sample.grade) def on_previous_button(change): self.sample = self.get_exam_to_grade('previous') question.value = self.sample.question_text answer.value = self.sample.answer_text with feedback: clear_output() fd = self.create_rubrics_feedback(self.sample, grade_button) display(fd) grade_button.value = 'grade : ' + str(self.sample.grade) grade_button.on_click(on_save_button) zero_button.on_click(on_zero_button) increase_button.on_click(on_increase_button) next_button.on_click(on_next_button) previous_button.on_click(on_previous_button) return complete
def manual_qc_interface( df, variable_list: list, flags: dict or str, review_flag: str = "_review_flag", comment_column: str = "_review_comment", default_flag=None, ): """ Manually QC interface to manually QC oceanographic data, through a Jupyter notebook. :param default_flag: :param comment_column: :param df: DataFrame input to QC :param variable_list: Variable List to review :param flags: Flag convention used :param review_flag: """ # # Generate a copy of the provided dataframe which will be use for filtering and plotting data| # df_temp = df # Retrieve Flag Convention if type(flags) is str: flag_convention = flags flags = flag_conventions[flags] flag_descriptor = f"{flag_convention}\n" + "\n".join([ f"{key} = {item['Meaning']}" for key, item in flag_conventions[flag_convention].items() ]) else: flag_descriptor = "\n".join( [f"{key} = {item}" for key, item in flags.items()]) # Set Widgets of the interface yaxis = widgets.Dropdown( options=variable_list, value=variable_list[0], description="Y Axis:", disabled=False, ) xaxis = widgets.Dropdown( options=["depth", "time"], value="time", description="X Axis:", disabled=False, ) filter_by = widgets.Text( value=None, description="Filter by", placeholder="ex: 20<depth<30", disabled=False, ) filter_by_result = filter_by_result = widgets.HTML( value="{0} records available".format(len(df)), ) apply_filter = widgets.Button( value=False, description="Apply Filter", disabled=False, button_style="success", # 'success', 'info', 'warning', 'danger' or '' tooltip="Apply Filter to the full dataset.", ) flag_selection = widgets.Dropdown(options=list(flags.keys()), description=flag_descriptor, disabled=False) flag_comment = widgets.Textarea( value="", placeholder="Add review comment", description="Comment:", disabled=False, ) apply_flag = widgets.Button( value=False, description="Apply Flag", disabled=False, button_style="success", # 'success', 'info', 'warning', 'danger' or '' tooltip="Apply Flag to select records.", ) accordion = widgets.Accordion() accordion.selected_index = None show_selection = widgets.Button( value=False, description="Show Selection", disabled=False, button_style="success", # 'success', 'info', 'warning', 'danger' or '' tooltip="Present selected records in table.", ) selected_table = widgets.Output() def get_filtered_data(df): """Apply query if available otherwise give back the full dataframe""" try: return df.query(filter_by.value) except ValueError: return df # Create the initial plots # Plot widget with def _get_plots(): """Generate plots based on the dataframe df, yaxis and xaxis values present within the respective widgets and flags in seperate colors""" plots = [] for flag_name, flag_value in flags.items(): if type(flag_value) is dict and "Color" in flag_value: flag_color = flag_value["Color"] flag_meaning = flag_value["Meaning"] else: flag_color = flag_value flag_meaning = flag_value df_temp = get_filtered_data(df) df_flag = df_temp.loc[df_temp[yaxis.value + review_flag] == flag_name] plots += [ go.Scattergl( x=df_flag[xaxis.value], y=df_flag[yaxis.value], mode="markers", name=flag_meaning, marker={ "color": flag_color, "opacity": 1 }, ) ] return tuple(plots) # Initialize Figure Widget and layout f = go.FigureWidget(data=_get_plots(), layout=go.Layout(barmode="overlay")) f.update_layout(margin=dict(l=50, r=20, t=50, b=20)) f.layout.xaxis.title = xaxis.value f.layout.yaxis.title = yaxis.value f.layout.title = "Review" f.update_layout( showlegend=True, legend={ "orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "right", "x": 1, }, ) # Set the update to figure if the drop menu is changed figure_data = f.data def update_filter(query_string=None): """Update filter report below the filter_by cell""" df_temp = get_filtered_data(df) if len(df_temp) == 0: # Give a message back saying no match and don't change anything else filter_by_result.value = "<p style='color:red;'>0 records found</p>" else: # Update text back and update plot with selection filter_by_result.value = "{0} records found".format(len(df_temp)) def update_figure(_): """Update figure with present x and y items in menu""" update_axes(xaxis.value, yaxis.value) def update_axes(xvar, yvar): """ Update figure, based on x,y axis provided :param xvar: :param yvar: """ kk = 0 with f.batch_update(): f.layout.xaxis.title = xvar f.layout.yaxis.title = yvar for plot in _get_plots(): f.data[kk].x = plot.x f.data[kk].y = plot.y kk += 1 def _get_selected_records(): """Method to retrieve the x and y coordinates of the records selected with the plotly lasso tool.""" xs = [] ys = [] for layer in figure_data: if layer["selectedpoints"]: xs += list(layer.x[list(layer["selectedpoints"])]) ys += list(layer.y[list(layer["selectedpoints"])]) return xs, ys def _get_selected_indexes(xs, ys): """Method to retrieve dataframe indexes of the selected x,y records shown on the figure.""" df_temp = get_filtered_data(df) is_indexes_selected = (df_temp[[xaxis.value, yaxis.value]].apply( tuple, axis=1).isin(tuple(zip(xs, ys)))) return df_temp.index[is_indexes_selected].tolist() def selection_fn(_): """Method to update the table showing the selected records.""" xs, ys = _get_selected_records() selected_indexes = _get_selected_indexes(xs, ys) if selected_indexes: with selected_table: selected_table.clear_output() display(df.loc[selected_indexes]) def update_flag_in_dataframe(_): """Tool triggered when flag is applied to selected records.""" # Retrieve selected records and flag column xs, ys = _get_selected_records() selected_indexes = _get_selected_indexes(xs, ys) flag_name = yaxis.value + review_flag comment_name = yaxis.value + comment_column # Create a column for the manual flag if it doesn't exist if flag_name not in df: df[flag_name] = default_flag # Print below the interface what's happening print( "Apply {0} to {1} records to {2}".format(flag_selection.value, len(selected_indexes), flag_name), end="", ) if flag_comment.value: print(" and add comment: {0}".format(flag_comment.value), end="") print(" ... ", end="") # Update flag value within the data frame df.loc[selected_indexes, flag_name] = flag_selection.value # Update comment if flag_comment.value: df.loc[selected_indexes, comment_name] = flag_comment.value # Update figure with the new flags update_figure(True) print("Completed") # Setup the interaction between the different components axis_dropdowns = interactive(update_axes, yvar=yaxis, xvar=xaxis) show_selection.on_click(selection_fn) apply_filter.on_click(update_figure) apply_flag.on_click(update_flag_in_dataframe) filter_data = interactive(update_filter, query_string=filter_by) # Create the interface layout plot_interface = VBox(axis_dropdowns.children) flag_interface = VBox( (flag_selection, flag_comment, apply_flag), layout={"align_items": "flex-end"}, ) filter_by_interface = VBox((filter_by, filter_by_result), layout={"align_items": "flex-end"}) filter_interface = HBox((filter_by_interface, apply_filter)) upper_menu_left = VBox((plot_interface, filter_interface)) upper_menu = HBox((upper_menu_left, flag_interface), layout={"justify_content": "space-between"}) selection_table = VBox((show_selection, selected_table)) return VBox(( upper_menu, f, selection_table, ))
def old_initiate(self): tab_children = [] ########################### # data 1 box d1_vbox_childs = [] ## ### d1_button_next = widgets.Button(description='next measurement') d1_button_prev = widgets.Button(description='prev measurement') d1_button_next.on_click(self.on_d1_botton_next) d1_button_prev.on_click(self.on_d1_botton_prev) d1_box_h_1 = widgets.HBox([d1_button_prev, d1_button_next]) ### d1_vbox_childs.append(d1_box_h_1) ## ### d1_text_path = widgets.Text(placeholder='path name', disabled=False) self.d1_text_path = d1_text_path d1_vbox_childs.append(d1_text_path) ## d1_vbox = widgets.VBox(d1_vbox_childs) tab_children.append({'element': d1_vbox, 'title': 'iMet'}) ############################ # data 2 box d2_vbox_childs = [] ## ### d2_button_next = widgets.Button(description='next measurement') d2_button_prev = widgets.Button(description='prev measurement') self.d2_dropdown_fnames = widgets.Dropdown( options=[ 1 ], #[i.name for i in self.controller.data.dataset2.path2data_list], value=1, #self.controller.data.dataset2.path2active.name, # description='N', disabled=False, ) d2_button_next.on_click(self.on_d2_botton_next) d2_button_prev.on_click(self.on_d2_botton_prev) self.d2_dropdown_fnames.observe(self.on_change_d2_dropdown_fnames) d2_box_h_1 = widgets.HBox( [d2_button_prev, d2_button_next, self.d2_dropdown_fnames]) ### d2_vbox_childs.append(d2_box_h_1) ## ### # text field showing the path d2_text_path = widgets.Text(placeholder='path name', disabled=False) self.d2_text_path = d2_text_path d2_vbox_childs.append(d2_text_path) ## d2_vbox = widgets.VBox(d2_vbox_childs) tab_children.append({'element': d2_vbox, 'title': 'POPS'}) # others box # Tab tab = widgets.Tab([child['element'] for child in tab_children]) for e, child in enumerate(tab_children): tab.set_title(e, child['title']) # accordeon self.accordeon_assigned = widgets.Valid( value=False, description='bound?', ) self.dropdown_popssn = widgets.Dropdown( options=['00', '14', '18'], # value='2', description='popssn', disabled=False, ) self.inttext_deltat = widgets.IntText(value=0, description='deltat', disabled=False) self.inttext_deltat.observe(self.on_inttext_deltat) self.dropdown_gps_bar_bad = widgets.Dropdown( options=[ 'gps', 'baro', 'bad', 'bad_but_usable_gps', 'bad_but_usable_baro' ], value='gps', description='which alt to use:', disabled=False, ) self.button_bind_measurements = widgets.ToggleButton( description='bind/unbind measurements') # button_bind_measurements.on_click(self.deprecated_on_button_bind_measurements) self.button_bind_measurements.observe(self.on_button_bind_measurements) accordon_box = widgets.VBox([ self.accordeon_assigned, self.dropdown_popssn, self.inttext_deltat, self.dropdown_gps_bar_bad, self.button_bind_measurements ]) accordion_children = [accordon_box] accordion = widgets.Accordion(children=accordion_children) accordion.set_title(0, 'do_stuff') # messages self.messages = widgets.Textarea('\n'.join(self.controller._message), layout={'width': '100%'}) # message_box = widgets.HBox([self.messages]) # OverVbox overVbox = widgets.VBox([tab, accordion, self.messages]) display(overVbox) #################### self.update_d1() self.update_d2() self.update_accordeon()
def create_and_display_article_saver(): wide_layout = widgets.Layout(width='100%') # create buttons print("Save article:") url_text_input = widgets.Text(description="Url", layout=wide_layout) display(url_text_input) notes_text_input = widgets.Text(description='Notes', layout=wide_layout) display(notes_text_input) datetime_text_input = widgets.Text(description="Datetime") display(datetime_text_input) print("HTML (if we couldn't grab the page)") html_text_input = widgets.Textarea(description="Html") display(html_text_input) def get_title(content): from bs4 import BeautifulSoup bs = BeautifulSoup(content, 'html.parser') return bs.title.string def get_connection(): import psycopg2 conn = psycopg2.connect(db_connstr) return conn def load_page_content_html(url): # load the content of the page import requests response = requests.get(url) content = response.content.decode() return content def save_article(url, html=None, dt=None, title=None, notes=None): conn = get_connection() cursor = conn.cursor() content = html or load_page_content_html(url) if title is None: title = get_title(content) if dt is None: dt = datetime.datetime.now() insert_sql = """INSERT INTO articles ( datetime, title, notes, url, content ) values ( %(datetime)s, %(title)s, %(notes)s, %(url)s, %(content)s ) """ cursor.execute( insert_sql, { 'datetime': dt, 'title': title, 'notes': notes, 'url': url, 'content': content, }) conn.commit() conn.close() return def handle_input(): # grab the inputs from the user timestr = datetime_text_input.value.strip() # parse time or set empty time to None timefrom = parse_datetime_str(timestr) if timestr else None notestr = notes_text_input.value.strip() url = url_text_input.value.strip() html = html_text_input.value.strip() save_article(url, html=html, dt=timefrom, title=None, notes=notestr) # on success, clear out all the fields datetime_text_input.value = '' notes_text_input.value = '' url_text_input.value = '' html_text_input.value = '' # set up handlers log_event_handler = lambda x: handle_input() datetime_text_input.on_submit(log_event_handler) notes_text_input.on_submit(log_event_handler) url_text_input.on_submit(log_event_handler)
def __init__(self, nmrproblem=None): super().__init__() if not isinstance(nmrproblem, nmrProblem.NMRproblem): self.nmrproblem = nmrproblem self.df = pd.DataFrame() else: self.nmrproblem = nmrproblem self.df = nmrproblem.df # create debug label widget for output self.debugLabel = widgets.Label(value="", layout=widgets.Layout(width="400px")) # create save problem widgets self.saveProblemButtonW = widgets.Button(description="Save Problem") # widgets to obtain problem working directory self.prDirW = widgets.Text(value='', placeholder='problem directory', description='problem directory', disabled=False) self.prDirB = widgets.Button(description='Set Directory') self.upload_problemdir = ipywidgets.widgets.FileUpload( multiple=True, description="Open Existing Problem ", description_tooltip="choose all files in problem directory", layout=widgets.Layout(width='300px')) self.problemNameL = widgets.Label(value=" Problem Name", layout=widgets.Layout(width='100px')) self.spacerL = widgets.Label(value=" ", layout=widgets.Layout(width='50px')) self.problemNameW = widgets.Text(value="Problem Name", description="", layout=widgets.Layout(width='150px')) self.newproblemB = widgets.Button(description="Start New Problem") self.prDirLayout = widgets.HBox([ self.upload_problemdir, self.spacerL, self.problemNameL, self.problemNameW, self.spacerL, self.newproblemB ]) # widgets to obtain info on the molecule # number and tye of atoms in molecule # number of proton resonances in molecule # number of carbon resonance in molecule self.moleculeAtomsW = widgets.Text(value='', placeholder='atoms in molecule', description='atoms', disabled=False) self.pGrpsW = widgets.IntText(value=1, placeholder='H1 groups in spectrum', description='H1 groups', disabled=False) self.cGrpsW = widgets.IntText(value=1, description='C13 groups', disabled=False) self.moleculesSubmitB = widgets.Button(description="Update Molecule") self.moleculeLayout = widgets.VBox([ self.moleculeAtomsW, self.pGrpsW, self.cGrpsW, self.moleculesSubmitB ]) # widgets to set 1D spectral parameters for proton and carbon self.pLabelW = widgets.Label("$^{1}H$") self.pSpecWidthW = widgets.FloatText(value=12.0, tooltip='proton spectral width', description='sw (ppm)', disabled=False) self.pObsFreqW = widgets.FloatText(value=400.0, description='obs (MHz)', disabled=False) self.pTofW = widgets.FloatText(value=5.0, description='tof (ppm)', diabled=False) self.pSizeW = widgets.IntText(value=32768, description='size (pts)', disabled=False) self.pLineBroadeningW = widgets.FloatText(value=0.5, description='lb (Hz)', disabled=False) self.cLabelW = widgets.Label("$^{13}C$") self.cSpecWidthW = widgets.FloatText(value=210.0, description='sw (ppm)', disabled=False) self.cObsFreqW = widgets.FloatText(value=100.0, description='obs (MHz)', disabled=False) self.cTofW = widgets.FloatText(value=5.0, description='tof (ppm)', diabled=False) self.cSizeW = widgets.IntText(value=32768, description='size (pts)', disabled=False) self.cLineBroadeningW = widgets.FloatText(value=0.5, description='lb (Hz)', disabled=False) self.specSubmitB = widgets.Button(description="Update Spectra") self.specLayout = widgets.HBox([ widgets.VBox([ self.pLabelW, self.pObsFreqW, self.pSpecWidthW, self.pTofW, self.pSizeW, self.pLineBroadeningW, self.specSubmitB ]), widgets.VBox([ self.cLabelW, self.cObsFreqW, self.cSpecWidthW, self.cTofW, self.cSizeW, self.cLineBroadeningW ]) ]) self.old = 'All' self.new = 'ALL' self.toggleDF = widgets.ToggleButtons( options=['All', 'integrals-ppm', 'COSY', 'HSQC-HMBC'], description='Display:', disabled=False, button_style='', tooltips=[ 'Show full Dataframe', 'Show COSY Input', 'Show HSQC/HMBC Input' ]) self.sheet1 = ipysheet.from_dataframe(self.df) self.toggleDF.observe(self.toggleValue) self.dfWarningTextW = widgets.Label("Table Messages: OK") self.dfUpdateTableB = widgets.Button(description="update table") self.dfRunAnalysisB = widgets.Button(description="update and run") self.dfButtonsLayout = widgets.HBox( [self.dfUpdateTableB, self.dfRunAnalysisB]) self.dfLayout = widgets.VBox([ self.toggleDF, self.dfWarningTextW, self.sheet1, self.dfButtonsLayout ]) self.accordion = widgets.Accordion(children=[ self.prDirLayout, self.moleculeLayout, self.specLayout, self.dfLayout ]) self.accordion.set_title(0, "Problem Directory") self.accordion.set_title(1, "Molecule") self.accordion.set_title(2, "Spectroscopy") self.accordion.set_title(3, "DataSet") self.page1 = widgets.VBox( [self.accordion, self.saveProblemButtonW, self.debugLabel]) self.H1C131DplotsLayout = widgets.VBox( [widgets.Output(), self.saveProblemButtonW]) self.ymlTitle = widgets.HTML("yml description of problem") self.ymlText = widgets.Textarea( layout=widgets.Layout(width="400px", height="500px")) self.problemYML = widgets.VBox([self.ymlTitle, self.ymlText]) self.children = [self.page1, self.H1C131DplotsLayout, self.problemYML] self.set_title(0, 'Problem Setup') self.set_title(1, 'Problem Plots') self.set_title(2, 'Problem YML') self.upload_problemdir.observe( lambda change: self.on_upload_problemdir(change), names='value') self.moleculesSubmitB.on_click(self.onButtonClicked) self.specSubmitB.on_click(self.onButtonClicked) self.dfUpdateTableB.on_click(self.onButtonClicked) self.dfRunAnalysisB.on_click(self.onButtonClicked) self.saveProblemButtonW.on_click(self.onButtonClicked) self.newproblemB.on_click(self.onButtonClicked)
def i_qsub(): """ Submits a job to the queue with the given parameters. """ from ipywidgets import widgets, Layout, interact_manual from IPython.display import display, clear_output from os.path import isfile inodes = widgets.BoundedIntText(value=1, min=1, max=4394, step=1, description='nodes', disabled=False) iranks_per_node = widgets.BoundedIntText(value=1, min=1, max=64, step=1, description='rank/nodes', disabled=False) iqueue = widgets.Dropdown( options=['debug-flat-quad', 'debug-cache-quad', 'default', 'backfill'], description='queue', value='debug-cache-quad') iwall_minutes = widgets.BoundedIntText(value=10, min=10, max=1440, step=10, description='wall minutes', disabled=False) iscript = widgets.Textarea(value='#!/bin/bash -x \n', description='job script', layout=Layout(flex='0 0 auto', width='auto', height='200px')) iscript_file = widgets.Text(value='', description='job script file name') iproject = widgets.Text(value='', description='project') isave = widgets.Checkbox(value=False, description='save', indent=True) isubmit = widgets.Button(value=False, description='submit', disabled=False, button_style='success', tooltip='submit job', icon='') output = widgets.Output() display(iproject, inodes, iqueue, iwall_minutes, iscript_file, iscript, isubmit, output) jobid = '' def submit_clicked(b): with output: clear_output() jobid = qsub(project=iproject.value, script=iscript.value, script_file=iscript_file.value, queue=iqueue.value, nodes=inodes.value, wall_minutes=iwall_minutes.value) isubmit.on_click(submit_clicked) return
def create_ui(self): # ------------ # Callbacks # ------------ # Callback for image label dropdown menu def dropdown_changed(obj): # Note that updating the dropdown label in code (e.g. in the update_ui() function) # also triggers this change event. Hence need to check if self.bo_updating_ui is False. if obj['type'] == 'change' and obj[ 'name'] == 'value' and not self.bo_updating_ui: img_index = int(obj['owner'].description[6:]) new_label = obj['owner'].value self.dataset.change_label_for_image( self.dataset.images[img_index], new_label) # Callback for "zoom" button def img_button_pressed(obj): img_index = int(obj.value) img_obj = self.dataset.images[img_index] self.update_zoom_ui(img_obj, img_index) # Callback for "next images" or "previous images" buttons def page_button_pressed(obj): self.page_index += int(obj.value) self.page_index = max(0, self.page_index) self.page_index = min(self.page_index, len(self.page_img_indices) - 1) self.update_ui() # Callback for "image page" slider def page_slider_changed(obj): try: self.page_index = int(obj['new']['value']) self.update_ui() except Exception as e: pass # Init self.bo_updating_ui = False # ------------ # UI - image grid # ------------ self.w_imgs = [] self.w_labels = [] self.w_buttons = [] w_img_label_buttons = [] for i in range(self.grid_size[0] * self.grid_size[1]): # Initialize images w_img = widgets.Image(width=200, description="") self.w_imgs.append(w_img) # Initialize dropdown menus w_label = widgets.Dropdown( options=self.label_options, value=self.label_options[self.labels[0].name], text="Image 0", description="Image 0") w_label.layout.width = '200px' w_label.observe(dropdown_changed, names='value') self.w_labels.append(w_label) # Initialize zoom buttons w_button = widgets.Button(description="Image id: ", value="") w_button.layout.width = "100px" w_button.button_style = 'warning' w_button.on_click(img_button_pressed) self.w_buttons.append(w_button) # combine into image grid widget w_img_label_button = widgets.VBox( children=[w_button, w_img, w_label]) w_img_label_button.width = '230px' w_img_label_buttons.append(w_img_label_button) # Image grid widget w_grid_HBoxes = [] for r in range(self.grid_size[0]): hbox = widgets.HBox(children=[ w_img_label_buttons[r * self.grid_size[1] + c] for c in range(self.grid_size[1]) ]) hbox.layout.padding = '10px' w_grid_HBoxes.append(hbox) w_img_grid = widgets.VBox(w_grid_HBoxes) # ------------ # UI - zoom window # ------------ w_next_page_button = widgets.Button(description="Next images", value="1") w_next_page_button.value = "1" # should not be necessary but bug on some jupyter versions otherwise w_next_page_button.layout.width = '120px' w_next_page_button.button_style = 'primary' w_next_page_button.on_click(page_button_pressed) w_previous_page_button = widgets.Button( description="Previous images", value="-1", layout=Layout(color='white', background_color='lightblue')) w_previous_page_button.value = "-1" w_previous_page_button.layout.width = '120px' w_previous_page_button.button_style = 'primary' w_previous_page_button.on_click(page_button_pressed) self.w_page_slider = IntSlider(min=0, max=len(self.page_img_indices) - 1, step=1, value=self.page_index, continuous_update=False, description='Image page:') self.w_page_slider.observe(page_slider_changed) self.w_zoom_header = widgets.Text("") self.w_zoom_header.layout.width = "100px" self.w_zoom_header.layout.color = 'white' self.w_zoom_header.layout.background_color = 'orange' self.w_zoom_img = widgets.Image() self.w_zoom_img.layout.width = '500px' self.w_zoom_text_area = widgets.Textarea() self.w_zoom_text_area.layout.width = '500px' self.w_zoom_text_area.layout.height = '100px' w_zoom_button_slider = widgets.HBox([ widgets.VBox([w_next_page_button, w_previous_page_button]), self.w_page_slider ]) # self.w_zoom_header w_zoom_button_slider.layout.width = '420px' # ------------ # UI - final # ------------ annotation_ui = widgets.HBox(children=[ widgets.VBox(children=[ w_zoom_button_slider, self.w_zoom_img, self.w_zoom_text_area ], width=520), w_img_grid ]) annotation_ui.layout.border_color = 'black' annotation_ui.layout.border_style = 'solid' tabs_ui = widgets.Tab(children=[annotation_ui]) tabs_ui.set_title(0, 'Image Annotation') # Update UI with actual images self.update_ui() return (tabs_ui)