def display_decryption(self): style={'description_width' : 'initial'} encrypted_image = widgets.FileUpload( description='Upload Image', accept='image/*', multiple=False, style=style ) display(encrypted_image) encryption_key = widgets.FileUpload( description='Upload Key', accept='.key', multiple=False, style=style ) display(encryption_key) submit_button = widgets.Button( description='Submit', disabled=False, button_style='success', icon='check' ) display(submit_button) submit_button.on_click( lambda *args: self.decrypt(encryption_key.value, encrypted_image.value) )
def __init__(self): from IPython.display import display import ipywidgets as widgets import matplotlib.pyplot as plt from pathlib import Path import pandas as pd import numpy as np sel_file = widgets.FileUpload(accept='.csv, .xlsx, xls', multiple=False) sel_file_output = widgets.Output() self.plot_output = widgets.Output() display(sel_file, sel_file_output) def select_file_eventhandler(sel_file): sel_file_output.clear_output() self.plot_output.clear_output() with sel_file_output: print(sel_file.metadata) if sel_file.metadata[0]['name'].split('.')[1] == 'xlsx': print("Excel file imported") file_name = sel_file.metadata[0]['name'] xls_importer2(sel_file, file_name) else: print("csv file imported") file_name = sel_file.metadata[0]['name'] f = sel_file.data[0] import tempfile TEMPDIR = tempfile.TemporaryFile() TEMPDIR.write(f) TEMPDIR.seek(0) ef = pd.read_csv(TEMPDIR) self.df = pd.DataFrame(ef) self.filenames = self.df.columns.to_list()[1:] with self.plot_output: self.df.plot(kind='line', x=self.df.columns[0], y=self.df.columns[1:], figsize=(15, 10)) plt.show() button = widgets.Button(description="Show Me The Data!") output = widgets.Output() display(button, output) def on_button_clicked(b): with output: sel_file.observe(select_file_eventhandler(sel_file), names='ALL') button.on_click(on_button_clicked) display(self.plot_output)
def __init__(self, title='CDXML to GNR', description="Upload Structure"): try: import openbabel # pylint: disable=unused-import except ImportError: super().__init__([ ipw.HTML("The SmilesWidget requires the OpenBabel library, " "but the library was not found.") ]) return self.title = title self.mols = None self.original_structure = None self.selection = set() self.file_upload = ipw.FileUpload(description=description, multiple=False, layout={'width': 'initial'}) supported_formats = ipw.HTML( """<a href="https://pubs.acs.org/doi/10.1021/ja0697875" target="_blank"> Supported structure formats: ".cdxml" </a>""") self.file_upload.observe(self._on_file_upload, names='value') self.allmols = ipw.Dropdown(options=[None], description='Select mol', value=None, disabled=True) self.allmols.observe(self._on_sketch_selected) super().__init__( children=[self.file_upload, supported_formats, self.allmols])
def _widget_factory(field: FormField): kwargs = { 'description': field.label, 'description_tooltip': field.description } if isinstance(field, IntegerField): widget = ipywidgets.BoundedIntText(value=field.default, min=field.min, max=field.max, **kwargs) elif isinstance(field, DecimalField): widget = ipywidgets.BoundedFloatText(value=field.default, min=field.min, max=field.max, **kwargs) elif isinstance(field, TextField): widget = ipywidgets.Text(placeholder=field.default, **kwargs) elif isinstance(field, BooleanField): widget = ipywidgets.Checkbox(value=field.default, **kwargs) elif isinstance(field, ChoiceField): kwargs.update(options=field.choices) if field.multiple: widget = ipywidgets.SelectMultiple(value=[field.default], **kwargs) elif len(field.choices) <= 5: widget = ipywidgets.RadioButtons(value=field.default, **kwargs) else: widget = ipywidgets.Dropdown(value=field.default, **kwargs) elif isinstance(field, FileField): widget = ipywidgets.FileUpload(accept=field.media_type or field.extension, **kwargs) else: raise TypeError(type(field)) widget.field_name = field.name return widget
def backbone(param): """!@brief Main backbone widget for use in Jupyter notebook This function displays the backbone widgets. @param param (dict) @a options._options_dict['Backbone'] @returns None @sa upload_backbone @sa options._options_dict @sa display_options_widgets """ display(widgets.HTML(value='<H3>Backbone</H3>')) # Display a widget for uploading backbone files w = widgets.interactive(upload_backbone, param=widgets.fixed(param), f=widgets.FileUpload(accept='', multiple=False, description="Backbone File", style={'description_width': 'initial'})) # Add a help box help_box = widgets.Button(description='?', tooltip='Upload a backbone file here. The file will be copied to the current folder.', layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, w]))
def add_base(number_of_bases, param): """!@brief Display widgets to upload the requested number of bases @param number_of_bases (int) The number of additional bases to define @param param (dict) @a options._options_dict['Base'] and dictionaries for the other defined bases @sa bases @sa upload_base @sa options._options_dict @sa view_nglview """ # Capture output. This is used to delete widget when no additional bases are requested out = widgets.Output() display(out) if number_of_bases == 0: out.clear_output() for i in range(number_of_bases): if "Base %i" %(i+1) not in param: param["Base %i" %(i+1)] = copy.deepcopy(param['Base']) # Display a widget for uploading base files w = widgets.interactive(upload_base, param=widgets.fixed(param["Base %i" %(i+1)]), base_number=widgets.fixed(i + 1), f=widgets.FileUpload(accept='', multiple=False, description="Base File", style={'description_width': 'initial'})) # Add a help box help_box = widgets.Button(description='?', tooltip='Upload base file here. The file will be copied to the current folder.', layout=widgets.Layout(width='3%')) display(widgets.HBox([help_box, w]))
def __init__(self): self.initial_name_tags = widgets.VBox([ label_and_input("First Name", text_default_value='First Name'), label_and_input("Middle Initials", text_default_value='Middle Initial(s)'), label_and_input("Last Name", text_default_value="Last Name") ]) self.initial_examples = widgets.VBox([ label_and_input("Initials for \"Xiang-Zhen\": ", text_default_value="X-Z"), label_and_input("Initials for \"Jun Soo\": ", text_default_value="J-S"), label_and_input("Initials for \"Baskin-Sommers\": ", text_default_value="B-S"), label_and_input("Initials for \"van Rooij\": ", text_default_value="vR") ]) self.generate_column_names = widgets.VBox([ label_and_input( "Full Name: ", text_default_value="Compound Name + highest degree"), label_and_input("Role(s): ", text_default_value="Role(s)"), label_and_textarea( "Affiliations Information (as a Python List of List):", text_default_value="[['Affiliation 1 Department, Institution', " "'City (e.g. Brisbane)', 'State', 'Country']]"), ]) self.generate_contribution_priority_order = widgets.VBox( [label_and_textarea("Roles priority: ", text_default_value="[]")]) self.accordion = self.init_accordion() self.clean_file_upload = widgets.FileUpload(accept=".csv", multiple=False) self.start_button = widgets.Button( description='Generate docx', icon="play", tooltip='Generate docx', ) self.generate_status_bar = widgets.Label("") self.generated_output_filename = label_and_input( "Output Filename:", text_default_value="demo.docx") self.generate_tab = widgets.VBox([ widgets.HBox([ self.clean_file_upload, self.start_button, self.generate_status_bar ], layout=widgets.Layout(margin="10px")), self.generated_output_filename, self.accordion ]) self.start_button.on_click(lambda change: self.start_generation())
def __init__(self, title='', description="Upload Structure"): self.title = title self.file_upload = ipw.FileUpload(description=description, multiple=False, layout={'width': 'initial'}) supported_formats = ipw.HTML( """<a href="https://wiki.fysik.dtu.dk/ase/_modules/ase/io/formats.html" target="_blank"> Supported structure formats </a>""") self.file_upload.observe(self._on_file_upload, names='value') super().__init__(children=[self.file_upload, supported_formats])
def model_info(): """ Returns expected input format """ base_image_uploader = ipywidgets.FileUpload(accept="image/*", multiple=False) return render_template('example1.html', slider1=base_image_uploader, widgets=[base_image_uploader])
def __init__(self, title="", description="Upload Structure"): self.title = title self.file_upload = ipw.FileUpload(description=description, multiple=False, layout={"width": "initial"}) supported_formats = ipw.HTML( """<a href="https://wiki.fysik.dtu.dk/ase/ase/io/io.html#ase.io.write" target="_blank"> Supported structure formats </a>""") self.file_upload.observe(self._on_file_upload, names="value") super().__init__(children=[self.file_upload, supported_formats])
def getInstance(self, FileNameDefault=None): self.FileNameDefault = FileNameDefault s = widgets.FileUpload( accept= '', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=True # True to accept multiple files upload else False ) s.style.button_color = "lightgreen" self.widgets = s s.observe(self.ListenerDefault, names='value') return s
def make_upload_btn(): global upload_data_btn upload_data_btn = widgets.FileUpload( accept= '', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=False, # True to accept multiple files upload else False description="Upload data") return upload_data_btn
def image_options(): copyfile('default.jpg', 'photo.jpg') grid = w.GridspecLayout(1, 3) grid[0,0] = w.Button(description='Default') grid[0,1] = w.Button(description='Camera') grid[0,2] = w.FileUpload(accept='.jpg') grid[0,0].on_click(default_photo) grid[0,1].on_click(handle_camera) grid[0,2].observe(upload_photo, 'data') return grid
def firstPage(out, grid): grid = close_FrontPage(out, grid) with open('./leftup.png', 'rb') as f1: leftup = f1.read() grid[1:5, :4] = widgets.Image(value=leftup) f1.close() with open('./rightdown.png', 'rb') as f2: rightdown = f2.read() grid[15:, 25:29] = widgets.Image(value=rightdown) f2.close() with open('./xiaohui.png', 'rb') as f3: content = f3.read() grid[4:13, 9:24] = widgets.Image(value=content) f3.close() file_upload = widgets.FileUpload(accept='.xlsm', multiple=False, layout=widgets.Layout(height='0.8cm', width='3cm'), description='选择文件') enter_button = widgets.Button(description='确定', style={'button_color': '#004080'}, button_style='info', disabled=True, layout=widgets.Layout(height='0.8cm', width='3cm')) grid[15:17, 10:24] = widgets.HBox([ file_upload, widgets.Label(layout=widgets.Layout(height='1cm', width='1cm')), enter_button ], layout=widgets.Layout(height='auto', width='auto')) #监测选择文件组件的变化 def file_upload_metadata_change(change): if change['new'] != []: #已选择文件 enter_button.disabled = False file_upload.observe(file_upload_metadata_change, names='metadata') ''' 设置按钮事件: ''' def act_enterButton(b): mainPage(out, grid, file_upload.metadata[0]['name']) enter_button.on_click(act_enterButton) return
def make_upload_conc_calib_btn(): global upload_conc_calib_btn upload_conc_calib_btn = widgets.FileUpload( accept= '', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=False, # True to accept multiple files upload else False description='Calib Data Upload', layout=calib_layout) return upload_conc_calib_btn
def audio_options(): copyfile('binary_yes', 'audio_bin') grid = w.GridspecLayout(1, 4) grid[0, 0] = w.Button(description='Default YES') grid[0, 1] = w.Button(description='Default NO') grid[0, 2] = w.Button(description='Microphone') grid[0, 3] = w.FileUpload(accept='.wav') grid[0, 0].on_click(default_yes) grid[0, 1].on_click(default_no) grid[0, 2].on_click(handle_microphone) grid[0, 3].observe(upload_wav, 'data') return grid
def __init__(self): self.upload = widgets.FileUpload(multiple=True) self.go_button = widgets.Button(description='Go') self.go_button.on_click(self.do_predict) self.output = widgets.Output() self.cell_model = None super().__init__(( widgets.HBox(( self.upload, self.go_button, )), self.output, ))
def input_flowers(): """ Build an input field for uploading csv files from the notebook. Returns ------- uploader : an upload wrapper from the widget """ from IPython.display import display import ipywidgets as widgets uploader = widgets.FileUpload(accept='.csv', multiple=False) display(uploader) return uploader
def background_image_widget(self): widget = widgets.FileUpload(accept='image/*', description='Select a file', multiple=False) def change_handler(change): [filename] = change.new ext = filename.split('.')[-1] prefix = f'data:image/{ext};base64,' filedata = change.new[filename]['content'] self.background_image = f'{prefix}{base64.b64encode(filedata).decode("utf-8")}' widget.observe(change_handler, names='value') return with_left_label('Background image', widget)
def make_upload_btn(): """ Make upload button widget for getting data file :return: upload data button :rtype: class: widgets.UploadFile """ global upload_data_btn upload_data_btn = widgets.FileUpload( accept= '', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=False, # True to accept multiple files upload else False description="Upload data") return upload_data_btn
def area(): """ Provide map and options to choose area of interest """ center = [65.73, -50.71] zoom = 4 m = Map(center=center, zoom=zoom) global dc, start, end, file, lon_l, lat_l, lon_r, lat_r # Pick date start = widgets.DatePicker(disabled=False) end = widgets.DatePicker(disabled=False) # Select from map dc = DrawControl(rectangle={'shapeOptions': { 'color': '#0000FF' }}, polyline={}, polygon={}, circlemarker={}) m.add_control(dc) # Shapefile file = widgets.FileUpload(accept='.shp', multiple=False) # Bounding box lon_l = widgets.FloatText(description="lon") lat_l = widgets.FloatText(description="lat") lon_r = widgets.FloatText(description="lon") lat_r = widgets.FloatText(description="lat") return (AppLayout(header=VBox([ HTML("<h1>Select area (time and space)</h1>"), HBox([Label("Start Date:"), start, Label("End Date:"), end]) ]), center=m, right_sidebar=VBox([ HTML("<h3>or upload shapefile<h3>"), file, HTML("<h3> <h3>"), HTML("<h3>or bounding box<h3>"), Label("Bottom-left corner"), lon_l, lat_l, Label("Upper-right corner"), lon_r, lat_r ])))
def make_upload_conc_calib_btn(): """ Make upload button widget for getting calibration table :return: upload calibration button :rtype: class: widgets.UploadFile """ global upload_conc_calib_btn upload_conc_calib_btn = widgets.FileUpload( accept= '', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=False, # True to accept multiple files upload else False description='Calib Data Upload', layout=calib_layout) return upload_conc_calib_btn
def createDashBoard(): # Allows the buttons to be accessed globally: Necessary # since some callback functions are dependent on these # widgets. global awsUploadButton global awsProgressRefreshRateSlider # AWS Image Upload Button. awsUploadButton = widgets.Button(description="Upload to AWS") awsUploadButton.on_click(awsImageUpload) # AWS Progress Refresh Rate Selector. awsProgressRefreshRateSlider = widgets.FloatSlider(min=0, max=1.0) # Display GUI. # Note: If new image is being uploaded, this block needs to be # run again. selectimage2uploadButton = widgets.FileUpload(multiple=False) # Specifying which function to run whenever an image is uploaded. selectimage2uploadButton.observe(selectimage2upload, names='value') display(selectimage2uploadButton)
def display_encryption(self): style={'description_width' : 'initial'} encryption_text = widgets.Text( placeholder='Enter Text Here', description='Text to Encrypt:', disabled=False, style=style ) display(encryption_text) encryption_key = widgets.Text( placeholder='Enter Key Here', description='Encryption Key:', disabled=False, style=style ) display(encryption_key) encryption_image = widgets.FileUpload( description='Upload Image', accept='image/*', multiple=False, style=style ) display(encryption_image) submit_button = widgets.Button( description='Submit', disabled=False, button_style='success', icon='check' ) display(submit_button) submit_button.on_click( lambda *args: self.encrypt(encryption_text.value, encryption_key.value, encryption_image.value) )
def createDashBoard(): # Allows the buttons to be accessed globally: Necessary # since some callback functions are dependent on these # widgets. global awsUploadButton global awsProgressRefreshRateSlider # AWS Image Upload Button. awsUploadButton = widgets.Button( description='Upload to AWS', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Upload to AWS') awsUploadButton.on_click(awsImageUpload) # awsUploadButton.on_click(sendImageToLocalPipeline) # AWS Progress Refresh Rate Selector. awsProgressRefreshRateSlider = widgets.IntSlider( value=4, min=0, max=12, step=4, description='Timeout (sec)', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='d') # Display GUI. fileuploader = widgets.FileUpload( accept= '.png', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=False # True to accept multiple files upload else False ) fileuploader.observe(selectimage2upload, names='value') display(fileuploader)
import os #os.chdir('../test_ERT_TL/') p #rint(os.getcwd()) # %% [markdown] # ## Full GUI # %% from lib.geometadp import md_manager obj = md_manager.geo_metadata() obj.manage() # %% import ipywidgets as widgets up = widgets.FileUpload() def onclick(change): #print(change.new) #print(change.new) uploaded_file = up.value[0] uploaded_file["size"] uploaded_file.size up.observe(onclick, 'value') up # %%
def _addInputJupyter(self, name, input, reset=False): """Add an input requirement for Jupyter. Parameters ---------- name : str The name of the input. input : :class:`Requirement <BioSimSpace.Gateway._requirement.Requirement>` The input requirement object. reset : bool Whether to reset the widget data. """ # Create a widget button to indicate whether the requirement value # has been set. button = _widgets.Button( tooltip="The input requirement is unset.", button_style="warning", icon="fa-exclamation-triangle", layout=_widgets.Layout(flex="1 1 auto", width="auto"), disabled=False, ) # Add a Jupyter widget for each of the supported requirement types. # Boolean. if type(input) is _Boolean: # Create a Jupyter toggle button. widget = _widgets.ToggleButton(value=False, description=name, tooltip=input.getHelp(), button_style="", icon="check", disabled=False) # Add the 'set' indicator button to the widget. widget._button = button # Flag that the widget is unset. widget._is_set = False # Get the default value. default = input.getDefault() if default is not None: widget.value = default widget._is_set = True widget._button.tooltip = "The input requirement is set." widget._button.button_style = "success" widget._button.icon = "fa-check" # Store the requirement name. widget._name = name # Bind the callback function. widget.observe(_on_value_change, names="value") # Store the widget. self._widgets[name] = widget # Integer. elif type(input) is _Integer: # Get the list of allowed values. allowed = input.getAllowedValues() # Get the default value. default = input.getDefault() if allowed is not None: # Set the default. if default is None: default = allowed[0] # Create a dropdown for the list of allowed values. widget = _widgets.Dropdown(options=allowed, value=default, description=name, tooltip=input.getHelp(), disabled=False) else: # Get the range of the input. _min = input.getMin() _max = input.getMax() # Whether the integer is unbounded. is_unbounded = True if _min is not None: # Set the default. if default is None: default = _min # Bounded integer. if _max is not None: step = int((_max - _min) / 100) # Create an int slider widget. widget = _widgets.IntSlider(value=default, min=_min, max=_max, step=step, description=name, tooltip=input.getHelp(), continuous_update=False, orientation="horizontal", readout=True, readout_format="d", disabled=False) # Flag that the integer is bounded. is_unbounded = False # Unbounded integer. if is_unbounded: # Create an integer widget. widget = _widgets.IntText(value=default, description=name, tooltip=input.getHelp(), disabled=False) # Add the 'set' indicator button to the widget. widget._button = button # Flag that the widget is unset. widget._is_set = False # Add an attribute to flag whether the widget value has # been set by the user. if input.getDefault() is not None: widget._is_set = True widget._button.tooltip = "The input requirement is set." widget._button.button_style = "success" widget._button.icon = "fa-check" # Store the requirement name. widget._name = name # Bind the callback function. widget.observe(_on_value_change, names="value") # Store the widget. self._widgets[name] = widget # Float types (including those with units). elif type(input) in _float_types: # Get the list of allowed values. allowed = input.getAllowedValues() # Get the default value. default = input.getDefault() # Get the magnitude of types with units. if isinstance(default, _Type): default = default.magnitude() if allowed is not None: # Set the default. if default is None: default = allowed[0] # Get the magnitude of types with units. if isinstance(default, _Type): default = default.magnitude() # Create a dropdown for the list of allowed values. widget = _widgets.Dropdown(options=allowed, value=default, description=name, tooltip=input.getHelp(), disabled=False) else: # Get the range of the input. _min = input.getMin() _max = input.getMax() # Get the magnitude of types with units. if isinstance(_min, _Type): _min = _min.magnitude() if isinstance(_max, _Type): _max = _max.magnitude() # Whether the float is unbounded. is_unbounded = True if _min is not None: # Set the default. if default is None: default = _min # Bounded float. if _max is not None: step = (_max - _min) / 100 # Create a float slider widget. widget = _widgets.FloatSlider(value=default, min=_min, max=_max, step=step, description=name, tooltip=input.getHelp(), continuous_update=False, orientation="horizontal", readout=True, readout_format=".1f", disabled=False) # Flag that the float is bounded. is_unbounded = False # Unbounded float. if is_unbounded: # Create a float widget. widget = _widgets.FloatText(value=default, description=name, tooltip=input.getHelp(), disabled=False) # Add the 'set' indicator button to the widget. widget._button = button # Flag that the widget is unset. widget._is_set = False # Add an attribute to flag whether the widget value has # been set by the user. if input.getDefault() is not None: widget._is_set = True widget._button.tooltip = "The input requirement is set." widget._button.button_style = "success" widget._button.icon = "fa-check" # Store the requirement name. widget._name = name # Bind the callback function. widget.observe(_on_value_change, names="value") # Store the widget. self._widgets[name] = widget # String. elif type(input) is _String: # Get the list of allowed values. allowed = input.getAllowedValues() # Get the default value. default = input.getDefault() if allowed is not None: # Set the default. if default is None: default = allowed[0] # Create a dropdown for the list of allowed values. widget = _widgets.Dropdown(options=allowed, value=default, description=name, tooltip=input.getHelp(), disabled=False) else: if default is None: # Create a text widget without a default. widget = _widgets.Text(placeholder="Type something", description=name, tooltip=input.getHelp(), disabled=False) else: # Create a text widget. widget = _widgets.Text(value=default, placeholder="Type something", description=name, tooltip=input.getHelp(), disabled=False) # Add the 'set' indicator button to the widget. widget._button = button # Flag that the widget is unset. widget._is_set = False # Add an attribute to flag whether the widget value has # been set by the user. if input.getDefault() is not None: widget._is_set = True widget._button.tooltip = "The input requirement is set." widget._button.button_style = "success" widget._button.icon = "fa-check" # Store the requirement name. widget._name = name # Bind the callback function. widget.observe(_on_value_change, names="value") # Store the widget. self._widgets[name] = widget # File / File set. elif type(input) is _File or type(input) is _FileSet: # Create a fileupload widget. if type(input) is _FileSet: widget = _widgets.FileUpload(multiple=True) else: widget = _widgets.FileUpload(multiple=False) # Make the widget dynamically resize to the content. widget.layout = {"width": "max-content"} # Add the 'set' indicator button to the widget. widget._button = button # Flag that the widget is unset. widget._is_set = False # Flag that this widget references files. widget._is_file = True # Store the requirement name. widget._name = name # Bind the callback function. widget.observe(_on_file_upload, names="data") # Store the widget. self._widgets[name] = widget # Unsupported input. else: raise ValueError("Unsupported requirement type '%s'" % type(input))
def __init__(self, machine=None, examples=False): # added to force using font-family monospace for user input Textarea and Text widgets display(HTML("<style>textarea, input { font-family: monospace; }</style>")) # Editing textboxes and toggle buttons text_area_sytle = Layout(width='100%', height='500px') self.dfa_editor = widgets.Textarea(value=dfa_example.strip() if examples else '', placeholder=dfa_placeholder.strip(), disabled=False, layout=text_area_sytle ) self.nfa_editor = widgets.Textarea(value=nfa_example.strip() if examples else '', placeholder=nfa_placeholder.strip(), disabled=False, layout=text_area_sytle ) self.pda_editor = widgets.Textarea(value=pda_example.strip() if examples else '', placeholder=pda_placeholder.strip(), disabled=False, layout=text_area_sytle ) self.tm_editor = widgets.Textarea(value=tm_example.strip() if examples else '', placeholder=tm_placeholder.strip(), disabled=False, layout=text_area_sytle ) self.translate_editor = widgets.Textarea(value='', placeholder=translate_placeholder.strip(), disabled=False, layout=text_area_sytle ) self.machine_toggle = widgets.ToggleButtons(options=['DFA', 'NFA', 'PDA', 'TM', 'Translate'], value='DFA', description='', disabled=False, style={'button_width': '120px'}, button_style='info', tooltips=['Deterministic Finite Automata', 'Non-deterministic Finite Automata', 'Pushdown Automata', 'Turing Machine', 'Translation'] ) self.machine_toggle.observe(self.on_machine_select, names='value') self.text_editor_display = widgets.Output() with self.text_editor_display: display(self.dfa_editor) # save and upload self.save_name_text = widgets.Text(value='', placeholder='filename', disabled=False) self.save_name_text.observe(self.save_text_changed, names='value') self.postfix_text = widgets.HTML(value='<p style="font-family:monospace">.dfa</p>') self.save_button = widgets.Button(description="Save", button_style='info', disabled=True, icon='download') self.save_button.on_click(self.save_machine) self.save_load_messages = widgets.HTML(value='<p style="font-size:small"></br></br></p>') self.upload_button = widgets.FileUpload(accept='.txt,.jff,.dfa,.nfa,.pda,.tm', button_style='info', description='Load', disabled=False) self.upload_button.observe(self.on_file_upload, names='value') self.save_load_collapse = widgets.Accordion(children=[widgets.VBox([widgets.HBox([self.save_name_text, self.postfix_text]), self.save_button, self.save_load_messages, self.upload_button])], selected_index=None) self.save_load_collapse.set_title(0, 'Save/Load') # Options Controls self.max_draw_size = widgets.BoundedFloatText(value=9.5, min=1.0, max=1000.0, step=0.1, description='Max Draw Size', disabled=False, style={'description_width': 'initial'}, layout=Layout(width='200px') ) self.fuse_option = widgets.ToggleButton(value=True, description='Fuse Edges', disabled=False, button_style='info', tooltip='Fuse machine edges', ) self.alt_start_option = widgets.ToggleButton(value=False, description='Alternate Start', disabled=False, button_style='info', tooltip='Pick the starting state (DFA and NFA only)', ) self.show_reject_option = widgets.ToggleButton(value=False, description='Show Rejected', disabled=False, button_style='info', tooltip='Show rejected paths (TM only)', ) self.max_stack_size = widgets.BoundedIntText(value=30, min=0, max=1000, step=1, description='Max Stack Size', disabled=False, style={'description_width': 'initial'}, layout=Layout(width='200px') ) # color pickers self.accept_colorpicker = widgets.ColorPicker(concise=True, description='Acceptance', value='#66cd00', disabled=False, style={'description_width': 'initial'} ) self.reject_colorpicker = widgets.ColorPicker(concise=True, description='Rejection', value='#ff0000', disabled=False, style={'description_width': 'initial'} ) self.transit_colorpicker = widgets.ColorPicker(concise=True, description='Transition', value='#1c86ee', disabled=False, style={'description_width': 'initial'} ) self.colors = widgets.HBox([self.accept_colorpicker, self.reject_colorpicker, self.transit_colorpicker]) options_layout = GridspecLayout(4, 3, grid_gap='5px', overflow='scroll hidden') options_layout[0, 0] = widgets.Label(value='Animation Colors:') options_layout[1, 0] = self.accept_colorpicker options_layout[2, 0] = self.reject_colorpicker options_layout[3, 0] = self.transit_colorpicker options_layout[0, 1] = self.fuse_option options_layout[1, 1] = self.max_draw_size options_layout[2, 1] = widgets.Label(value='Finite Automata:') options_layout[3, 1] = self.alt_start_option options_layout[0, 2] = widgets.Label(value='Turing Machine:') options_layout[1, 2] = self.show_reject_option options_layout[2, 2] = widgets.Label(value='Pushdown Automata:') options_layout[3, 2] = self.max_stack_size accordion = widgets.Accordion(children=[options_layout], layout=Layout(overflow='hidden'), selected_index=None) accordion.set_title(0, 'Options') # Pack the text editor and options into a VBOX self.edit_tab = widgets.VBox([widgets.HBox([self.save_load_collapse, self.machine_toggle], layout=Layout(width='100%', align_content='center')), self.text_editor_display, accordion]) # Animated Machine self.animated_machine_display = widgets.Output() self.machine_failure_display = widgets.Output() self.machine_messages_display = widgets.Output() self.machine_messages_text = widgets.HTML(value='<p style="font-family:monospace;font-size:24px;text-align:center">Generating animation widget ...</p>') self.machine_tab = widgets.VBox([self.machine_messages_display, self.animated_machine_display, self.machine_failure_display]) # Help Tab help_tab_label = widgets.HTML(value='<H2>Help</H2>') markdown_help = widgets.HTML(value=machine_markdown_help_text.strip()) options_help = widgets.HTML(value=options_help_text.strip()) animation_help = widgets.HTML(value=animation_help_text.strip()) play_help = widgets.HTML(value=play_help_text.strip()) translate_help = widgets.HTML(value=translate_help_text.strip()) help_topics = widgets.Accordion(children=[markdown_help, options_help, animation_help, play_help, translate_help], selected_index=None) help_topics.set_title(0, 'Machine Markdown') help_topics.set_title(1, 'Options') help_topics.set_title(2, 'Animations') help_topics.set_title(3, 'Play Controls') help_topics.set_title(4, 'Translation from JFlap') help_tab = widgets.VBox([help_tab_label, help_topics]) # Pack the Tabs self.editor_tabs = widgets.Tab(children=[self.edit_tab, self.machine_tab, help_tab]) self.editor_tabs.set_title(0, 'Edit') self.editor_tabs.set_title(1, 'Animate') self.editor_tabs.set_title(2, 'Help') self.editor_tabs.observe(self.on_tab_switch, names='selected_index') # If a machine was passed in handle differently if machine is not None: editor_string = '{}'.format(pprint.pformat(machine)) if {'Q', 'Sigma', 'Delta', 'q0', 'F'} == machine.keys(): self.dfa_editor.value = editor_string self.machine_toggle.value = 'DFA' self.editor_tabs.selected_index = 1 elif {'Q', 'Sigma', 'Delta', 'Q0', 'F'} == machine.keys(): self.nfa_editor.value = editor_string self.machine_toggle.value = 'NFA' self.editor_tabs.selected_index = 1 elif {'Q', 'Sigma', 'Gamma', 'Delta', 'q0', 'z0', 'F'} == machine.keys(): self.pda_editor.value = editor_string self.machine_toggle.value = 'PDA' self.editor_tabs.selected_index = 1 elif {'Q', 'Sigma', 'Gamma', 'Delta', 'q0', 'B', 'F'} == machine.keys(): self.tm_editor.value = editor_string self.machine_toggle.value = 'TM' self.editor_tabs.selected_index = 1 else: self.translate_editor.value = '!! The provided dictionary does not match any known Jove machine type\n{}'.format(editor_string) self.machine_toggle.value = 'Translate' self.editor_tabs.selected_index = 0 display(self.editor_tabs)
def __init__(self, **kwargs): computer_image = ipw.HTML( '<img width="200px" src="./miscellaneous/images/computer.png">') # Username. inp_username = ipw.Text(description="SSH username:"******"350px"), style=STYLE) link((inp_username, 'value'), (self, 'username')) # Port. inp_port = ipw.IntText(description="SSH port:", value=22, layout=ipw.Layout(width="350px"), style=STYLE) link((inp_port, 'value'), (self, 'port')) # Hostname. inp_computer_hostname = ipw.Text(description="Computer hostname:", layout=ipw.Layout(width="350px"), style=STYLE) link((inp_computer_hostname, 'value'), (self, 'hostname')) # Upload private key directly. self._inp_password = ipw.Password(description="SSH password:"******"150px"), style=STYLE, disabled=False) self._inp_private_key = ipw.FileUpload( accept='', layout=ipw.Layout(width="350px"), style=STYLE, description='Private key', multiple=False, disabled=True) self._verification_mode = ipw.Dropdown( options=['password', 'private_key'], layout=ipw.Layout(width="350px"), style=STYLE, value='password', description='verification mode:', disabled=False) self._verification_mode.observe(self.on_use_verification_mode_change, names='value') # Proxy ssh settings. inp_use_proxy = ipw.Checkbox(value=False, description='Use proxy') inp_use_proxy.observe(self.on_use_proxy_change, names='value') link((inp_use_proxy, 'value'), (self, 'use_proxy')) inp_proxy_hostname = ipw.Text(description="Proxy server address:", layout=ipw.Layout(width="350px"), style=STYLE) link((inp_proxy_hostname, 'value'), (self, 'proxy_hostname')) self._use_diff_proxy_username = ipw.Checkbox( value=False, description='Use different username and password', layout={'width': 'initial'}) self._use_diff_proxy_username.observe( self.on_use_diff_proxy_username_change, names='value') inp_proxy_username = ipw.Text(value='', description="Proxy server username:"******"350px"), style=STYLE) link((inp_proxy_username, 'value'), (self, 'proxy_username')) self._inp_proxy_password = ipw.Password( value='', description="Proxy server password:"******"138px"), style=STYLE) # Setup ssh button and output. btn_setup_ssh = ipw.Button(description="Setup ssh") btn_setup_ssh.on_click(self.on_setup_ssh) self._setup_ssh_out = ipw.Output() # Defining widgets positions. computer_ssh_box = ipw.VBox([ inp_computer_hostname, inp_port, inp_username, self._verification_mode, self._inp_password, self._inp_private_key, inp_use_proxy ], layout=ipw.Layout(width="400px")) self._proxy_user_password_box = ipw.VBox( [inp_proxy_username, self._inp_proxy_password], layout={'visibility': 'hidden'}) self._proxy_ssh_box = ipw.VBox([ inp_proxy_hostname, self._use_diff_proxy_username, self._proxy_user_password_box ], layout={ 'visibility': 'hidden', 'width': '400px' }) children = [ ipw.HBox([computer_image, computer_ssh_box, self._proxy_ssh_box]), btn_setup_ssh, self._setup_ssh_out ] super(SshComputerSetup, self).__init__(children, **kwargs)
widgets.DatetimePicker(description='Pick a Time', disabled=False) # ## Color picker widgets.ColorPicker(concise=False, description='Pick a color', value='blue', disabled=False) # ## File Upload # # The `FileUpload` allows to upload any type of file(s) into memory in the kernel. widgets.FileUpload( accept= '', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=False # True to accept multiple files upload else False ) # The upload widget exposes a `value` attribute that contains the files uploaded. The value attribute is a tuple with a dictionary for each uploaded file. For instance: # # ```python # uploader = widgets.FileUpload() # display(uploader) # # # upload something... # # # once a file is uploaded, use the `.value` attribute to retrieve the content: # uploader.value # #=> ( # #=> {