def overlayViewer(im4d, overlay3d, zz=0, tt=0, th=0, oa=1, im_range=None, o_range=None): tt_enable = True if im4d.ndim == 3: im4d = im4d[:,:,:,np.newaxis] tt_enable = False out = widgets.Output() zz_slider = widgets.IntSlider(min=0, max=im4d.shape[2]-1, step=1, value=zz) tt_slider = widgets.IntSlider(min=0, max=im4d.shape[3]-1, step=1, value=tt) oa_slider = widgets.FloatSlider(min=0, max=1, step=0.1, value=oa) if issubclass(overlay3d.dtype.type, np.integer) or overlay3d.dtype == np.bool: th = 1 th_slider = widgets.IntSlider(min=np.amin(overlay3d), max=np.amax(overlay3d), step=1, value=th) th_slider.visible = False oa_slider.visible = True else: th_slider = widgets.FloatSlider(min=np.amin(overlay3d), max=np.amax(overlay3d), step=0.01, value=th) oa_slider.visible = False overlay_button = widgets.ToggleButton(description='Overlay', value=True) if not tt_enable: tt_slider.visible = False with warnings.catch_warnings(): warnings.simplefilter('ignore') w = widgets.interactive(overlayShow, recon=widgets.fixed(im4d), overlay3d=widgets.fixed(overlay3d), zz=zz_slider, tt=tt_slider, th=th_slider, oa=oa_slider, oe=overlay_button, im_range=widgets.fixed(im_range), o_range=widgets.fixed(o_range), out=widgets.fixed(out)) wo = widgets.HBox(children=(w,out)) display(wo)
def preview(self): #figure, axis = plt.subplots() [height, width] = np.shape(self.images_array[0]) text_y = 0.1 * height text_x = 0.6 * width def display_selected_image(index, text_x, text_y, pre_text, post_text, color): 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.show() return { 'text_x': text_x, 'text_y': text_y, 'pre_text': pre_text, 'post_text': post_text, 'color': color } self.preview = interact( display_selected_image, index=widgets.IntSlider(min=0, max=len(self.list_files), continuous_update=False), text_x=widgets.IntSlider(min=0, max=width, value=text_x, description='Text x_offset', continuous_update=False), text_y=widgets.IntSlider(min=0, max=height, value=text_y, description='Text y_offset', continuous_upadte=False), pre_text=widgets.Text(value='Time Offset', description='Pre text'), post_text=widgets.Text(value='(s)', description='Post text'), color=widgets.RadioButtons( options=['red', 'blue', 'white', 'black', 'yellow'], value='red', description='Text Color'))
def plot_bounds_2d(top, bottom, x=None, y=None, figsize=None): """Plot top and bottom lines in x and y projections.""" nans = np.isnan(top) ylim = (bottom[~nans].max(), top[~nans].min()) def update(x=0, y=0): _, axes = plt.subplots(1, 2, figsize=figsize) axes[0].plot(top[x], label='top') axes[0].plot(bottom[x], label='bottom') axes[0].axvline(y, c='r') axes[0].set_xlim((0, top.shape[1])) axes[0].set_title('x') axes[1].plot(top[:, y], label='top') axes[1].plot(bottom[:, y], label='bottom') axes[1].axvline(x, c='r') axes[1].set_xlim((0, top.shape[0])) axes[1].set_title('y') for ax in axes: ax.legend() ax.set_ylim(*ylim) if (x is None) and (y is None): interact(update, x=widgets.IntSlider(0, 0, top.shape[0] - 1, step=1), y=widgets.IntSlider(0, 0, top.shape[1] - 1, step=1)) else: x = 0 if x is None else x y = 0 if y is None else y update(x, y) plt.show()
def select_profile(self, roi_left=0, roi_top=0, roi_height=-1, roi_width=-1): self.integrated_data = self.__calculate_integrated_data() self.image_dimension = np.shape(self.integrated_data) [self.height, self.width] = self.image_dimension if roi_height == -1: roi_height = self.height - 1 if roi_width == -1: roi_width = self.width - 1 def plot_images_with_roi(x_left, y_top, width, height, contrast_min, contrast_max): plt.figure(figsize=(5, 5)) ax_img = plt.subplot(111) ax_img.imshow(self.integrated_data, cmap='rainbow', interpolation=None, vmin = contrast_min, vmax = contrast_max) ax_img.add_patch(patches.Rectangle((x_left, y_top), width, height, fill=False)) return [x_left, y_top, width, height] self.profile = interact(plot_images_with_roi, x_left=widgets.IntSlider(min=0, max=self.width - 1, step=1, value=roi_left, continuous_update=False), y_top=widgets.IntSlider(min=0, max=self.height - 1, step=1, value=roi_top, continuous_update=False), width=widgets.IntSlider(min=0, max=self.width - 1, step=1, value=roi_width, continuous_update=False), height=widgets.IntSlider(min=0, max=self.height - 1, step=1, value=roi_height, continuous_update=False), contrast_min=widgets.FloatSlider(min=0, max=1, step=0.1, value=0, continuous_update=False), contrast_max=widgets.FloatSlider(min=0, max=2, value=1, step=0.1, continuous_update=False))
def create_search_params(self): start_date = widgets.DatePicker(description="Pick a start date", style={"description_width": "initial"}) end_date = widgets.DatePicker(description="Pick an end date", style={"description_width": "initial"}) sensors = widgets.RadioButtons( options=["pleiades", "spot"], value="pleiades", description="Sensor", # ) max_cloudcover = widgets.IntSlider( value=20, min=0, max=100, step=1, description="Max Cloud Cover (%)", style={"description_width": "initial"}, ) limit = widgets.IntSlider( value=10, min=1, max=500, step=1, description="Limit", ) button = widgets.Button(description="Save search params!") def create_search_params(start_date, end_date, sensors, max_cloudcover, limit): assert self.ensure_variables( (self.catalog, self.aoi)), "Please select an AOI and/or authenticate!" search_parameters = self.catalog.construct_parameters( geometry=self.aoi, start_date=start_date.value, end_date=end_date.value, sensors=[sensors.value], max_cloudcover=max_cloudcover.value, sortby="cloudCoverage", limit=limit.value, ) search_parameters["query"]["deliveryTime"] = {"in": ["MINUTES"]} display(search_parameters) self.search_parameters = search_parameters self.sensors = sensors.value self.process_template( [start_date, end_date, sensors, max_cloudcover, limit], button, create_search_params, start_date=start_date, end_date=end_date, sensors=sensors, max_cloudcover=max_cloudcover, limit=limit, )
def plot_top_words(): global bok_tweets interact(top_words, num_word_instances=widgets.IntSlider(min=1, value=50, continuous_update=False), top_words=widgets.IntSlider(min=1, value=30, continuous_update=False))
def x(self): interact_manual(self.X, day=widgets.IntSlider(min=1, max=365, step=1, value=180), hour=widgets.IntSlider(min=0, max=23, step=1, value=12), jj=widgets.IntSlider(min=0, max=self.ny - 1, step=1, value=0))
def y(self): interact_manual(self.Y, day=widgets.IntSlider(min=1, max=365, step=1, value=180), hour=widgets.IntSlider(min=0, max=23, step=1, value=12), ii=widgets.IntSlider(min=0, max=self.nx - 1, step=1, value=0))
def map(self): interact_manual(self.MAP, day=widgets.IntSlider(min=1, max=365, step=1, value=180), hour=widgets.IntSlider(min=6, max=20, step=1, value=12), Lmax=widgets.IntSlider(min=0, max=35000, step=100, value=5000))
def track_menu(): input = widgets.Dropdown(description='Input data', options=['Dictionary', 'Pickle', 'Text file'], value='Dictionary') max_disp = widgets.FloatSlider(min=0.1, max=11.0, description='Max disp', value=0.5) memory = widgets.IntSlider(description='Memory', min=0, max=5, value=2) predict = widgets.Checkbox(description='Trajectory predictor', value=False) rn1 = widgets.IntSlider(description='Range 1', min=0, max=11, value=3) rn2 = widgets.IntSlider(description='Range 2', min=0, max=11, value=3) return widgets.VBox([input, predict, max_disp, memory, rn1, rn2])
def update(self): xl, xh = (widgets.IntSlider(description="Lower Bound Scaling", min=0, max=len(self.txs) - 1, value=0, step=1.0), widgets.IntSlider(description="Upper Bound Scaling", min=0, max=len(self.txs) - 1, value=len(self.txs) - 1, step=1.0)) dl = widgets.jsdlink((xl, 'value'), (xh, 'min')) w = widgets.interact(self.plotting, xl=xl, xh=xh)
def plot_top_words_with_custom_stopwords(): global bok_tweets def create_term_document_matrix2(corpus, min_df=1): cvec = CountVectorizer(min_df=min_df, stop_words=stopwords) tfmatrix = cvec.fit_transform(corpus) return pd.DataFrame(data=tfmatrix.toarray(), columns=cvec.get_feature_names()) def plot_top_words_with_filters(num_word_instances, top_words, stop_words, small_words, lower, more_stop_words): tweets = bok_tweets.text if lower: tweets = tweets.str.lower() if stop_words: tweets = tweets.apply(remove_stopwords) if small_words: tweets = tweets.str.findall('\w{3,}').str.join(' ') if len(more_stop_words) > 0: remove_more_stopwords = lambda x: ' '.join(y for y in x.split( ) if y not in (x.strip() for x in more_stop_words.split(','))) tweets = tweets.apply(remove_more_stopwords) tdm_df = create_term_document_matrix2(tweets, min_df=2) word_frequencies = tdm_df[[x for x in tdm_df.columns if len(x) > 1]].sum() sorted_words = word_frequencies.sort_values(ascending=False) top_sorted_words = sorted_words[:num_word_instances] top_sorted_words[:top_words].plot.bar() return top_sorted_words interact(plot_top_words_with_filters, num_word_instances=widgets.IntSlider(min=1, value=50, continuous_update=False), top_words=widgets.IntSlider(min=1, value=30, continuous_update=False), stop_words=widgets.Checkbox(value=False, description='Filter stop words', continuous_update=False), small_words=widgets.Checkbox(value=False, description='Filter small words', continuous_update=False), lower=widgets.Checkbox(value=False, description='Apply lowercase', continuous_update=False), more_stop_words=widgets.Text(value='aar,år', description='Additional stop words:', continuous_update=False))
def browse_tree_fit(self): def show_fit(num_elements): # plot our points self.plot_target() # load in gradient booster clf = GradientBoostingRegressor(n_estimators=num_elements, learning_rate=1, max_depth=2, random_state=0, loss='ls') # fit classifier self.y.shape = (len(self.y), ) clf.fit(self.x, self.y) # plot classification boundary and color regions appropriately r = np.linspace(-0.1, 1.1, 300)[:, np.newaxis] # plot approximation self.plot_approx(clf, r, r) interact(show_fit, num_elements=widgets.IntSlider(min=1, max=50, step=1, value=1))
def __init__(self, list_videos, numRows, numColumns, list_titles=None, imgSizex=20, imgSizey=20, IntSlider_width='500px', median_filter_flag=False, color='gray', step=1, value=0): """ This class interactively displays several videos (with the same number of frames) in a Jupyter notebook. Parameters ---------- list_videos: list of NDArray List of videos numRows: int It defines number of rows in sub-display numColumns: int It defines number of columns in sub-display list_titles: list str List of titles for each sub plot median_filter_flag: bool In case it defines as True, a median filter is applied with size 3 to remove hot pixel effect. color: str It defines the colormap for visualization. imgSizex: int Image length size. imgSizey: int Image width size. IntSlider_width: str Size of slider step: int Stride between visualization frames. value: int Initial frame value for visualization """ self.color = color self.video = list_videos self.median_filter_flag = median_filter_flag self.numRows = numRows self.numColumns = numColumns self.numVideos = len(list_videos) self.imgSizex = imgSizex self.imgSizey = imgSizey if list_titles is None: self.list_titles = [None for _ in range(self.numVideos)] else: self.list_titles = list_titles max_numberFrames = np.max([vid_.shape[0] for vid_ in list_videos]) interact(self.display, frame=widgets.IntSlider(min=0, max=max_numberFrames-1, step=step, value=value, layout=Layout(width=IntSlider_width), readout_format='100', continuous_update=False, description='Frame:'))
def display_images_pretty(self): _data = self.data _clean_data = self.clean_data _files = self.list_files _full_statistics = self.full_statistics [height, width] = np.shape(self.data[0]) def _plot_images(index): _file_name = _files[index] fig = plt.figure(figsize=(7,7)) ax0 = plt.subplot(111) ax0.set_title(os.path.basename(_file_name)) cax0 = ax0.imshow(_clean_data[index], cmap='viridis', interpolation=None) tmp2 = fig.colorbar(cax0, ax=ax0) # colorbar fig.tight_layout() tmp3 = widgets.interact(_plot_images, index=widgets.IntSlider(min=0, max=len(self.list_files) - 1, step=1, value=0, description='File Index', continuous_update=False), )
def ui_prepare(self, k): for typ in k: if typ in ['always_apply', 'p']: continue if type(k[typ]) == float: tmp = widgets.FloatSlider(min=0, max=1, step=0.05, continuous_update=False) self.interact_wds[typ] = tmp if type(k[typ]) == bool: tmp = widgets.ToggleButton() self.interact_wds[typ] = tmp if type(k[typ]) == int: tmp = widgets.IntSlider(min=1, max=50, step=1, continuous_update=False) self.interact_wds[typ] = tmp if type(k[typ]) == tuple: tmp = widgets.IntRangeSlider(value=[50, 70], min=5, max=200, step=1, continuous_update=False) self.interact_wds[typ] = tmp ui_lists = [] for w in self.interact_wds: ui_tmp = widgets.VBox([widgets.Label(w), self.interact_wds[w]]) ui_lists.append(ui_tmp) ui = widgets.HBox(ui_lists) return ui
def InteractivePlanes(planevalue="XZ", offsetvalue=0.0): def foo(Plane, Offset, nRx): X0, Y0, Z0 = -20, -50, -50 X2, Y2, Z2 = X0 + 100.0, Y0 + 100.0, Z0 + 100.0 return plotObj3D( offset_plane=Offset, X1=X0, X2=X2, Y1=Y0, Y2=Y2, Z1=Z0, Z2=Z2, nRx=nRx, plane=Plane, ) out = widgetify( foo, Offset=widgets.FloatSlider(min=-100, max=100, step=5.0, value=offsetvalue, continuous_update=False), # ,X0=widgets.FloatText(value=-20) \ # ,Y0=widgets.FloatText(value=-50.) \ # ,Z0=widgets.FloatText(value=-50.) \ nRx=widgets.IntSlider(min=4, max=200, step=2, value=40, continuous_update=False), Plane=widgets.ToggleButtons(options=["XZ", "YZ"], value=planevalue), ) return out
def build_panel_item(self, cv_value, description, min_val, max_val, value=0, step=1): brightness_w = widgets.IntSlider(min=min_val, max=max_val, value=value, step=step, description=description) def on_value_change(change): self.camera.cap.set(cv_value, change['new']) brightness_w.observe(on_value_change, names='value') display(brightness_w)
def build_rotate_panel(self): brightness_w = widgets.IntSlider(min=0, max=270, value=0, step=90, description="Rotate:") def on_value_change(change): self._rotate_angle = -1 * change['new'] brightness_w.observe(on_value_change, names='value') display(brightness_w)
def get_line(m_slope=1, c_intercept=0, initial_b=0, initial_m=0, learning_rate=0.001, num_pts=150, num_itr=200): num_pts = min(200, num_pts) fig = figure() plotdata = [] x = np.linspace(1, 50, num_pts) points = np.array([ x, Polynomial_Fit.get_noisy_func(x, 1, lambda x: m_slope * x + c_intercept, num_pts=num_pts), ]).T # initial_b = 0 # initial y-intercept guess # initial_m = 0 # initial slope guess num_iterations = num_itr print( "Starting gradient descent at:\n b = {0}, m = {1}, error = {2}".format( initial_b, initial_m, compute_error(initial_b, initial_m, points))) [b, m], plotdata = gradient_descent_runner(points, initial_b, initial_m, learning_rate, num_iterations, plotdata) print("After {0} iterations:\n b = {1}, m = {2}, error = {3}".format( num_iterations, b, m, compute_error(b, m, points))) fig.tight_layout() np_plotdata = np.array(plotdata) l1 = subplot2grid((2, 2), (0, 0), rowspan=2) xlabel("iterations (10x)") ylabel("cost") fig1 = plot(np_plotdata[:, 2]) # l2 = subplot2grid((2, 2), (1, 0)) # xlabel("iterations (10x)") # ylabel("cost") # fig2 = plot(np_plotdata[:, 2]) l3 = subplot2grid((2, 2), (0, 1), rowspan=2) xlabel("x") ylabel("y") print(np_plotdata.shape) fig3 = scatter(points[:, 0], points[:, 1], alpha=0.6) fig4 = plot(points[:, 0], m * points[:, 0] + b, c="r") interact( # lambda iterations: update_plot(iterations, fig, plotdata, [initial_b, initial_m, learning_rate,points], (fig1[0], fig2[0], fig4[0])), lambda iterations: update_plot( iterations, fig, plotdata, [initial_b, initial_m, learning_rate, points], (fig4[0]), ), iterations=widgets.IntSlider(value=num_iterations, min=0, max=num_iterations, step=1), ) show()
def interactive_from_traj(trajectories, traj_idx=0): """ Displays ith trajectory of trajectories (in standard format) interactively in a Jupyter notebook. """ from ipywidgets import widgets, interactive_output states = trajectories["ep_observations"][traj_idx] joint_actions = trajectories["ep_actions"][traj_idx] cumulative_rewards = cumulative_rewards_from_rew_list( trajectories["ep_rewards"][traj_idx]) mdp_params = trajectories["mdp_params"][traj_idx] env_params = trajectories["env_params"][traj_idx] env = AgentEvaluator(mdp_params, env_params=env_params).env def update(t=1.0): env.state = states[int(t)] joint_action = joint_actions[int(t - 1)] if t > 0 else (Action.STAY, Action.STAY) print(env) print("Joint Action: {} \t Score: {}".format( Action.joint_action_to_char(joint_action), cumulative_rewards[t])) t = widgets.IntSlider(min=0, max=len(states) - 1, step=1, value=0) out = interactive_output(update, {'t': t}) display(out, t)
def show_image_series(image_series: ImageSeries, neurodata_vis_spec: dict): if len(image_series.data.shape) == 3: return show_grayscale_image_series(image_series, neurodata_vis_spec) def show_image(index=0, mode='rgb'): fig, ax = plt.subplots(subplot_kw={'xticks': [], 'yticks': []}) image = image_series.data[index] if mode == 'bgr': image = image[:, :, ::-1] ax.imshow(image, cmap='gray', aspect='auto') fig.show() return fig2widget(fig) slider = widgets.IntSlider(value=0, min=0, max=image_series.data.shape[0] - 1, orientation='horizontal', continuous_update=False, description='index') mode = widgets.Dropdown(options=('rgb', 'bgr'), layout=Layout(width='200px'), description='mode') controls = {'index': slider, 'mode': mode} out_fig = widgets.interactive_output(show_image, controls) vbox = widgets.VBox(children=[out_fig, slider, mode]) return vbox
def display_profile(self): [roi_left, roi_top, roi_width, roi_height] = self.roi _rebin = self.rebin pixel_range = np.arange(roi_top, roi_height-roi_top, _rebin) def plot_profile(file_index): data_1d = self.profile_1d[file_index] data_2d = self.sample_data[file_index] fig = plt.figure(figsize=(5, 5)) ax_plt = plt.subplot(211) ax_plt.plot(pixel_range, data_1d) plt.xlabel("Pixel") plt.ylabel("Transmission") ax_plt.set_title(os.path.basename(self.list_data_files[file_index])) ax_img = plt.subplot(212) ax_img.imshow(data_2d, cmap='rainbow', interpolation=None) ax_img.add_patch(patches.Rectangle((roi_left, roi_top), roi_width, roi_height, fill=False)) number_of_files = len(self.sample_data) _ = interact(plot_profile, file_index=widgets.IntSlider(min=0, max=number_of_files - 1, value=0, step=1, description="Image Index", continuous_update=False))
def _stack(self, network: str, node: str): """ Display stack graphics. Manage user interaction with scn slider and prod, cons choices. :param network: network name :param node: node name :return: """ def changes(scn, prod, cons): display( go.FigureWidget( self.plotting.network(network).node(node).stack( scn=scn, prod_kind=prod, cons_kind=cons))) scn = widgets.IntSlider(value=0, min=0, description='scn', max=self.plotting.agg.nb_scn - 1, continuous_update=False, disabled=False) cons = widgets.RadioButtons(options=['asked', 'given'], value='asked', description='Consumption') prod = widgets.RadioButtons(options=['avail', 'used'], value='used', description='Production') hbox = widgets.HBox([scn, cons, prod]) inter = interactive_output(changes, { 'scn': scn, 'prod': prod, 'cons': cons }) return widgets.VBox([hbox, inter])
def create_kmeans_clustering_widgets(dict): """ instiantate the widgets for k-means clustering algorithm :param dict: name of _parameters and its default value :return: list with HBox's of widgets """ widget_initMode = widgets.Dropdown(value=dict.get( "initMode", "k-means||"), options=["k-means||", "random"], description="Initial mode") setattr(widget_initMode, 'name', 'initMode') widget_initSteps = widgets.IntSlider( value=dict.get("initSteps", 10), min=1, max=100, step=1, description="Number of Initial steps") setattr(widget_initSteps, 'name', 'initSteps') widgets_gaussian_mix = ParamsCleaning.create_gaussian_mixture_widgets( dict) widgets_kmeans = widgets.HBox([widget_initSteps, widget_initMode]) return widgets_gaussian_mix + [widgets_kmeans]
def show_in_notebook(self, fps=5, figsize=(8, 8), cmap="viridis"): # Prepare widgets play = widgets.Play(value=0, min=0, max=len(self.states) - 1, step=1, interval=int(1000 / fps), description="Press play", disabled=False) slider = widgets.IntSlider(min=0, value=0, max=len(self.states) - 1, step=1) widgets.jslink((play, 'value'), (slider, 'value')) # Visualize frames and widgets @interact(i=play) def show(i): plt.figure(figsize=figsize) plt.axis('off') plt.imshow(self.states[i], cmap=cmap) # Display on the notebook display(slider)
def plot(self, show_quadrature="", x_unit="ns"): """ Plots the sequences stored in channel. A slider provides the option to sweep through different time values. Readout pulse is fixed at t = 0, where is t>0 before the readout tone. Args: x_unit: unit of the x-axis in the plot. Options are "s", "ms", "us", "ns". """ show_iq = False if show_quadrature in ["I", "Q"]: show_iq = True sequences, readout_indices = self._get_sequences(IQ_mixing=show_iq) seq_max = len(readout_indices) - 1 if show_quadrature is "I": sequences = [np.real(seq) for seq in sequences] elif show_quadrature is "Q": sequences = [np.imag(seq) for seq in sequences] bounds = self._get_boundaries(sequences, readout_indices, x_unit) interact(lambda sequence: self._plot_sequence( sequences[sequence], readout_indices[sequence], x_unit, bounds), sequence=widgets.IntSlider(value=0, min=0, max=seq_max, layout=Layout(width="98%", height="50px"))) return True
def browse_net_fit(self): def show_fit(num_elements): # plot our points self.plot_all() # create the decision tree classifier with appropriate clf = MLPRegressor(solver='lbfgs', alpha=0, activation='tanh', random_state=1, hidden_layer_sizes=(num_elements, num_elements)) # fit classifier self.y.shape = (len(self.y), ) clf.fit(self.x, self.y) # plot classification boundary and color regions appropriately r = np.linspace(min(self.x), max(self.x), 300)[:, np.newaxis] # plot approximation self.plot_approx(clf, r, r) interact(show_fit, num_elements=widgets.IntSlider(min=1, max=100, step=1, value=1))
def show_obs_plot_widget(data, display_fn): from IPython import display from ipywidgets import widgets text_wid = widgets.IntText(value=0, placeholder='Frame number', description='Frame number:', disabled=False) slider_wid = widgets.IntSlider(value=0, min=0, max=len(data), step=1, description='Frames:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') widgets.jslink((text_wid, 'value'), (slider_wid, 'value')) output_widget = widgets.Output(layout={'height': '250px'}) def on_value_change(change): frame_idx = change['new'] display_fn(frame_idx) slider_wid.observe(on_value_change, names='value') frame_box = widgets.HBox([output_widget]) control_box = widgets.HBox([text_wid, slider_wid]) # Controls main_box = widgets.VBox([frame_box, control_box]) display.display(main_box) display_fn(0)
def __init__(self): super(PassGenGUI, self).__init__() self._helpful_title = widgets.HTML('Generated password is:') self._password_text = widgets.HTML('', placeholder='No password generated yet') self._password_text.layout.margin = '0 0 0 20px' self._password_length = widgets.IntSlider(description='Length of password', min=8, max=20, style={'description_width': 'initial'}) self._numbers = widgets.Checkbox(description='Include numbers in password', style={'description_width': 'initial'}) self._label = widgets.Label('Choose special characters to include') self._toggles = widgets.ToggleButtons(description='', options=[',./;[', '!@#~%', '^&*()'], style={'description_width': 'initial'}) # Set the margins to control the indentation. # The order is top right bottom left self._toggles.layout.margin = '0 0 0 20px' children = [self._helpful_title, self._password_text, self._password_length, self._label, self._toggles, self._numbers] self.children = children self.model = PassGen() traitlets.link((self.model, 'password'), (self._password_text, 'value')) traitlets.link((self.model, 'length'), (self._password_length, 'value')) traitlets.link((self.model, 'special_character_groups'), (self._toggles, 'value')) traitlets.link((self.model, 'include_numbers'), (self._numbers, 'value'))