def __init__(self, lp, filename='', **kwargs): self.__lp = lp self.filename = filename self.__accordion = Accordion() self.__auto_apply_cbx = Checkbox(description='Auto apply') self.__auto_save_cbx = Checkbox(description='Auto save') self.__apply_btn = Button(description='Apply changes') self.__save_btn = Button(description='Save changes') self.__add_category_btn = Button(description='Add category') self.__add_category_txt = Text(placeholder='category name') self.__initialize() super().__init__([ VBox([ HBox([ HBox((self.__apply_btn, self.__auto_apply_cbx)), HBox((self.__save_btn, self.__auto_save_cbx)), HBox((self.__add_category_btn, self.__add_category_txt)) ], layout=Layout(flex_flow='row wrap', margin='5px')), self.__accordion ], layout=Layout(margin='5px')) ], **kwargs)
def __init__(self): plt.close("all") self.backend = TextInputLoop(use_widget=True) self.highlighter = SentimentHighlighter(self.backend) self.backend.add_interface(self.highlighter) self.backend.start() self.cwd_label = Label( value="Working directory: {}".format(Path.cwd()), layout=dict(margin="2px 0px 0px 20px"), ) self.save_path = Text( value=str(Path("saved_html.html")), description='Save path:', disabled=False, layout=dict(width="50%"), ) self.save_button = Button( value=False, description='Save to HTML', disabled=False, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='', icon='', layout=Layout(width='18%', margin="2px 0px 0px 20px"), ) self.progress_label = Label( value="", layout=dict(margin="2px 0px 0px 20px"), ) self.full_contrast = Checkbox(value=False, description='Full Contrast', disabled=False) self.do_highlighting = Checkbox(value=True, description='Do Highlighting', disabled=False) box1 = HBox( (self.do_highlighting, self.full_contrast), layout=Layout(align_content="flex-start"), ) box2 = HBox( (self.save_path, self.save_button), layout=Layout(align_content="flex-start"), ) self.storage_dashboard = VBox( (box1, self.cwd_label, box2, self.progress_label)) # Set observers self.save_button.on_click(self._save) self.full_contrast.observe(self._special_options) self.do_highlighting.observe(self._special_options) # noinspection PyTypeChecker display(self.storage_dashboard)
def __init__(self, fig_size=(10, 6)): self.fig_size = fig_size files = list(sorted(list(storage_dir.glob("*.npy")))) file_names = [val.name for val in files] self.start_button = Button( value=False, description='Show!', disabled=False, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' icon='') self.w_dropdown = Dropdown(options=file_names, value=file_names[0], description='File:', disabled=False, layout={"margin": "10px"}) style = {'description_width': 'initial'} self.w_camera_position = RadioButtons( options=['xyz', 'x', 'y', "z"], description='Camera viewpoint:', disabled=False, style=style, ) self.w_show_mean = Checkbox( value=False, description='Show Averages', disabled=False, # button_style='', # 'success', 'info', 'warning', 'danger' or '' # icon='check', layout={ "justify_content": "space-around", 'width': '250px', "margin": "10px" }) self.fig = None self.ax = None self.container = VBox(( HBox([self.w_dropdown, self.start_button]), HBox( [self.w_show_mean, self.w_camera_position], layout=Layout(justify_content="space-around", width="100%"), ), ), ) # Assign viewer to events self.start_button.on_click(self.update)
def _update_clusters(self) -> None: """ Updates the clusters currently being displayed. """ line = HBox( children=[Label("-" * 186, layout=Layout(margin="0 0 0 18px"))]) self._sel_all.value = False cluster_page = self._clusterer.get_page( self._page_pos, self._page_pos + self._page_size) label_layout = Layout(height="22px", width="360px") box_children = [line] for idx, cluster in enumerate(cluster_page): labels = [] for cluster_val, cnt in cluster: if cnt > 1: cluster_val += f" ({cnt} rows)" labels.append(Label(cluster_val, layout=label_layout)) totals_vals = sum(cnt for _, cnt in cluster) distinct_vals = len(cluster) self._reprs[idx].value = cluster[0][0] self._checks[idx].value = False box_children.append( HBox([ Label(str(distinct_vals), layout=Layout(width="60px", margin="0 0 0 60px")), Label(str(totals_vals), layout=Layout(width="60px", margin="0 0 0 50px")), VBox(children=labels, layout=Layout(margin="0 0 0 80px")), self._checks[idx], self._reprs[idx], ])) box_children.append(line) # no clusters to display if len(cluster_page) == 0: box_children = [ Label( "No clusters, try a different clustering method", layout=Layout(margin="170px 0 0 360px"), ) ] self._cluster_vbox.children = box_children cluster_and_next_prev = [self._cluster_vbox] self._add_next_prev_button_row(cluster_and_next_prev) self._cluster_and_next_prev.children = cluster_and_next_prev
def __init__(self): self.currentConnection = None self.currentDB = '' self.tableOut = Output(layout=Layout(max_width='30%')) self.schemaOut = Output() self.tableSelect = Dropdown( options=[''], value='', description='Table:', disabled=False, ) self.databaseSelect = Dropdown( options=['sqlite-sakila', 'chinook'], value='sqlite-sakila', description='Database:', disabled=False, ) self.tableSelect.observe(self.tableChange, names='value') self.databaseSelect.observe(self.databaseChange, names='value') self.displayDatabases = VBox([ HBox( [self.tableOut, VBox([self.databaseSelect, self.tableSelect])]), self.schemaOut ]) self.changeDatabase()
def __build_gui(self): children = [] titles = ['materials'] item_layout = Layout(margin='20px', flex_flow='row wrap') if self.__lp: box_materials = HBox(layout=item_layout) for index, color in self.__lp.get_colors().items(): editor = make_color_editor(color, index, no_name=True) if editor: editor.observe(self.__on_editor_changed(color)) box_materials.children = (*box_materials.children, editor) children.append( VBox([self.__menu('materials', box_materials), box_materials])) for category_name in self.__lp.get_category_names(): box_scalars = HBox(layout=item_layout) box_curves = HBox(layout=item_layout) for scalar in self.__lp.get_category_scalars(category_name): editor = make_scalar_editor(scalar, False) if editor: editor.observe(self.__on_editor_changed(scalar)) box_scalars.children = (*box_scalars.children, editor) for param in self.__lp.get_category_graphicalparameters( category_name): editor = make_curve_editor(param, False) if editor: editor.observe(self.__on_editor_changed(param)) box_curves.children = (*box_curves.children, editor) children.append( VBox([ self.__menu('scalars', box_scalars, category_name), box_scalars, self.__menu('curves', box_curves, category_name), box_curves ])) titles.append(category_name) return (children, titles)
def __add_category(self, name): if not name or name in self.__lp.get_category_names(): return item_layout = Layout(margin='20px', flex_flow='row wrap') acc = self.__accordion box_scalars = HBox(layout=item_layout) box_curves = HBox(layout=item_layout) acc.children = (*self.__accordion.children, VBox([ self.__menu('scalars', box_scalars, name), box_scalars, self.__menu('curves', box_curves, name), box_curves ])) acc.set_title(len(acc.children) - 1, name) self.__lp.add_category(name) if self.__auto_save: self.__save()
def __init__(self): self.dashboard = HBox([]) self.tab = Tab(layout=layout) self.titles = [ 'Glimpse', 'Columns', 'Cross filters', 'Pairwise Patterns' ] # set titles for tab cell for i, title in enumerate(self.titles): self.tab.set_title(i, title)
def history_ui(): date_wid = widgets.DatePicker(description='Pick a Date', value=dt.datetime.today(), disabled=False) def filter_data(date): d = read(dr['MAT']+'Timesheet.pkl') date=dt.datetime(date.year,date.month,date.day) c1=(d['From']>date)*(d['To']<=date+pd.to_timedelta('23:59:59')) c11=d[c1] idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1] c12=d.loc[idx] c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))] for j in ['From','To']: c11[j]=[c11[j].iloc[i].strftime('%H:%M:%S') for i in range(len(c11[j]))] c13=pd.concat((c10,c11)) display(c13) def total_df(date): d = read(dr['MAT']+'Timesheet.pkl') date=dt.datetime(date.year,date.month,date.day) c1=(d['From']>pd.to_datetime(date))*(d['To']<=pd.to_datetime(date)+pd.to_timedelta('23:59:59')) c11=d[c1] idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1] c12=d.loc[idx] c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))] c13=pd.concat((c10,c11)) acts=sorted(list(set(c13['Activity']))) act1=pd.Series(acts) tot=[c13[c13['Activity']==j]['Duration'].sum() for j in act1] tot1=pd.Series(tot) tot2=pd.DataFrame({'Activity': act1,'Total Duration':tot1}) tot2 = tot2.sort_values(by='Total Duration',ascending=False) tot2 = tot2.reset_index(drop=True) display(tot2) out1 = widgets.interactive_output(filter_data, {'date': date_wid}) out2 = widgets.interactive_output(total_df, {'date': date_wid}) ui = VBox([date_wid,HBox([out1,out2])]) return ui
def predictors_widget(preds, target): # plen = len(preds) logger.debug("inside predictors_widget") preds_btn = [] for key, val in preds: btn = Button(description='%s : %s' % (key, val), disabled=False, button_style='', tooltip=str(val), layout=predbtn_layout, display='flex', flex_flow='column', align_items='stretch') # , icon='check') # set btn color btn.style.button_color = 'lightgreen' preds_btn.append(btn) logger.info("Done creating predictor buttons") head_out = HTML( "<h3> Predictors of `%s` with their predictive power </h3>" % (target)) preds_btn.insert(0, head_out) children = preds_btn preds_widget = VBox(children, layout=pred_wiget_layout) bar_w = pp_barplot_widget(preds) # set width of bar plot bar_w.layout.width = 450 rightside_vis = HBox([bar_w], display='flex', align_items="stretch") #rightside_vis.layout.align_items = 'center' rightside_vis.layout.flex = "1.5 1 auto" rightside_vis.layout.width = "60%" rightside_vis.layout.border = '1px solid black' preds_widget.layout.flex = "1 1 auto" preds_widget = HBox([preds_widget, rightside_vis], layout=layout, display='flex') return preds_widget
def __init__(self): self.start_button = Button( value=False, description='Start Camera', disabled=False, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Start the camera and the recognition algorithm.', icon='') self.select_network = Dropdown( options=KerasDetector.available_models, value=KerasDetector.available_models[0], description='Algorithm:', disabled=False, ) self.label_names = Text( value='', placeholder='separated by commas', description='Labels', disabled=False, ) self.num_pictures = IntText(value=2.0, description='#pictures', disabled=False, layout=Layout(width='18%')) self.text = Label(value='', layout=Layout(justify_content='space-around', )) self.widget_box = VBox((HBox( (self.start_button, self.label_names, self.num_pictures, self.select_network), layout=Layout(justify_content="space-around")), self.text)) # Initialize field self.collector = None self.start_button.on_click(self._start_video)
def __init__(self, qNo): self.qNo = qNo self.qOut = Output() self.queryArea = Textarea( value='', placeholder='Type your Query here', description='', disabled=False, #layout = Layout(max_width='30%') ) self.execute = Button( description='Execute', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Execute', #layout = Layout(max_width='20%') ) self.resultMessage = Output() self.execute.on_click(self.executeQuery) self.yourOutput = Output(layout=Layout()) self.expectedOutput = Output(layout=Layout()) self.yourOut = Output() self.expectOut = Output() with self.yourOut: display(HTML('<b>Your Ouput:</b>')) with self.expectOut: display(HTML('<b>Expected Ouput:</b>')) self.disPlayWindow = VBox([HBox([self.qOut,self.queryArea,self.execute,self.resultMessage]),\ VBox([VBox([self.expectOut,self.expectedOutput]\ ),VBox([self.yourOut,self.yourOutput])])]\ ,layout = Layout(width='80%')) self.qset = pd.read_csv('questions.csv') self.questionData = self.qset.loc[self.qset.qNo == self.qNo] expected = self.getExpected() with self.expectedOutput: display(expected) with self.qOut: print(self.questionData.question.values[0])
def _add_next_prev_button_row( self, box_children: List[Union[HBox, VBox]]) -> None: """ Adds a next page or previous page button, if the operation is valid. """ next_prev = [] prev_is_valid = self._page_pos - self._page_size >= 0 next_is_valid = self._page_pos + self._page_size < len( self._clusterer.clusters) if prev_is_valid and next_is_valid: self._next_button.layout.margin = "0 0 0 628px" next_prev.append(self._prev_button) next_prev.append(self._next_button) elif prev_is_valid: next_prev.append(self._prev_button) elif next_is_valid: self._next_button.layout.margin = "0 0 0 795px" next_prev.append(self._next_button) if next_is_valid or prev_is_valid: box_children.append(HBox(next_prev, layout={"height": "50px"}))
def DataApp(): frequency = FloatText(value=0.5, description='f (Hz)') zsrc = FloatText(value=-950., description='src height (m)') zrx = FloatText(value=-1000., description='rx height (m)') rho0 = FloatText(value=1e8, description='$\\rho_{0} \ (\Omega m)$') rho1 = FloatText(value=0.3, description='$\\rho_{1} \ (\Omega m)$') rho2 = FloatText(value=1., description='$\\rho_{2} \ (\Omega m)$') rho3 = FloatText(value=100., description='$\\rho_{3} \ (\Omega m)$') rho4 = FloatText(value=1., description='$\\rho_{4} \ (\Omega m)$') rv_rh = FloatText(value=1., description='$\\rho_{2 \ v} / \\rho_{2 \ h}$') dz1 = FloatText(value=1000., description="dz1 (m)") dz2 = FloatText(value=1000., description="dz2 (m)") dz3 = FloatText(value=200., description="dz3 (m)") frequency_bg = FloatText(value=0.5, description='f$^{BG}$ (Hz)') zsrc_bg = FloatText(value=-950., description='src height$^{BG}$ (m)') zrx_bg = FloatText(value=-1000., description='rx height$^{BG}$ (m)') rho0_bg = FloatText(value=1e8, description='$\\rho_{0}^{BG} \ (\Omega m)$') rho1_bg = FloatText(value=0.3, description='$\\rho_{1}^{BG} \ (\Omega m)$') rho2_bg = FloatText(value=1., description='$\\rho_{2}^{BG} \ (\Omega m)$') rho3_bg = FloatText(value=1., description='$\\rho_{3}^{BG} \ (\Omega m)$') rho4_bg = FloatText(value=1., description='$\\rho_{4}^{BG} \ (\Omega m)$') rv_rh_bg = FloatText( value=1., description='$\\rho_{2 \ v}^{BG} / \\rho_{2 \ h}^{BG}$') dz1_bg = FloatText(value=1000., description="dz1$^{BG}$ (m)") dz2_bg = FloatText(value=1000., description="dz2$^{BG}$ (m)") dz3_bg = FloatText(value=200., description="dz3$^{BG}$ (m)") Field = ToggleButtons(options=['E', 'H', 'Zxy'], value='E', description="Field") Plane = ToggleButtons(options=['XZ', 'YZ'], value='XZ', description="Plane") Component = ToggleButtons(options=['x', 'y', 'z'], value='x', description="rx direction") Complex = ToggleButtons(options=['Real', 'Imag', "Amp", "Phase"], value='Amp', description="Complex") scale = ToggleButtons(options=['log', 'linear'], value='log', description="Scale") Fixed = widgets.widget_bool.Checkbox(value=False, description="Fixed") vmin = FloatText(value=None, description='vmin') vmax = FloatText(value=None, description='vmax') __manual = True out = widgets.interactive_output( csem_data_app, { "frequency": frequency, "zsrc": zsrc, "zrx": zrx, "rho0": rho0, "rho1": rho1, "rho2": rho2, "rho3": rho3, "rho4": rho4, "rv_rh": rv_rh, "dz1": dz1, "dz2": dz2, "dz3": dz3, "frequency_bg": frequency_bg, "zsrc_bg": zsrc_bg, "zrx_bg": zrx_bg, "rho0_bg": rho0_bg, "rho1_bg": rho1_bg, "rho2_bg": rho2_bg, "rho3_bg": rho3_bg, "rho4_bg": rho4_bg, "rv_rh_bg": rv_rh_bg, "dz1_bg": dz1_bg, "dz2_bg": dz2_bg, "dz3_bg": dz3_bg, "Field": Field, "Plane": Plane, "Component": Component, "Complex": Complex, "scale": scale, "Fixed": Fixed, "vmin": vmin, "vmax": vmax, }) panel = VBox([ frequency, zsrc, zrx, rho0, rho1, rho2, rho3, rho4, rv_rh, dz1, dz2, dz3 ]) panel_bg = VBox([ frequency_bg, zsrc_bg, zrx_bg, rho0_bg, rho1_bg, rho2_bg, rho3_bg, rho4_bg, rv_rh_bg, dz1_bg, dz2_bg, dz3_bg ]) panel_type = VBox( [Field, Plane, Component, Complex, scale, Fixed, vmin, vmax]) return VBox([HBox([panel, panel_bg]), panel_type, out])
def ana_ui(): out_0 = widgets.Output() out_1 = widgets.Output() out_2 = widgets.Output() out_3 = widgets.Output() def filter_data(k,date): date=dt.datetime(date.year,date.month,date.day) c1=(d['From']>pd.to_datetime(date))*(d['To']<=pd.to_datetime(date)+pd.to_timedelta('23:59:59')) c11=d[c1] idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1] c12=d.loc[idx] c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))] c13=pd.concat((c10,c11)) c2=c13[c13['Activity']==k] return c2 def update_mat(k,mat,tot,date): c11=filter_data(k,date) tot[date]=c11['Duration'].sum() mat[date]=np.zeros(1440) ix=[int(np.round(i.total_seconds()/60)) for i in (c11['From']-date)] iy=[int(np.round(i.total_seconds()/60)) for i in (c11['To']-date)] for i,j in zip(ix,iy): if i<0: mat[date][0:j]=1 date1=date-dt.timedelta(1) date1=dt.datetime(date1.year,date1.month,date1.day) if date1 >= dt.datetime(date_from.value.year,date_from.value.month,date_from.value.day): ii=i+1440 mat[date1][ii:]=1 else: mat[date][i:j]=1 def gen_mat(k,from_date,to_date): dates = pd.date_range(from_date,to_date) mat={} tot={} for date in dates: date=dt.datetime(date.year,date.month,date.day) update_mat(k,mat,tot,date) return mat,tot def plot_ts(k,tot): nmin={i.strftime('%a, %d %b'):tot[i].total_seconds()/60. for i in tot} a1=pd.Series(tot) a33 = pd.Series(nmin) a33 = a33.fillna(0) v=[str(tot[i])[7:] for i in tot] try: title = '%s\nMean = %s\n Regularity = %4.1f %% \n Maximum = %s on %s\n Minimum = %s on %s ' % ( k, str(a1.mean())[7:15], 100 * len(a33[a33 > 0]) / len(a33), str(a1[a1 > dt.timedelta(0)].max())[7:15], a33[a33 > 0].argmax(), str(a1[a1 > dt.timedelta(0)].min())[7:15], a33[a33 > 0].argmin()) except ValueError: title = 'No \n %s \n Activitiy ' %(k) fig, ax = plt.subplots(figsize=(16, 8)) plt.subplots_adjust(top=0.8, bottom=0.25) a33.plot.bar(width=1, ax=ax, color='g') ax.set_ylabel('Minutes', fontweight='bold') for j, i in enumerate(ax.patches): if v[j] != '00:00:00': if a33[j] < 0.2 * a33[a33 > 0].max(): ax.text(i.get_x() + 0.45, 1.5 * a33[j], v[j], fontsize=10, color='blue', rotation=90) else: ax.text(i.get_x() + 0.45, 0.1 * a33[j], v[j], fontsize=10, color='yellow', rotation=90) fig.suptitle(title, fontsize=18, fontweight='bold') fig.savefig(dr['FIG']+'ts.jpg',dpi=72) plt.close() return dr['FIG']+'ts.jpg' def plot_matrix(mat): dd1=np.zeros((len(mat),1440)) for i,j in enumerate(mat): dd1[i,:]=mat[j] freq=100*(len(np.where(dd1.sum(axis=1)>0)[0])/dd1.shape[0]) fig,ax=plt.subplots(figsize=(15,6)) ax.imshow(dd1,aspect='auto',cmap=mpl.colors.ListedColormap(['white','g'])) labels=[j.strftime('%a %d %b') for j in mat] plt.yticks(range(len(mat)),labels); xticks=np.arange(60,1440,60) xticklabels=np.arange(1,24) ax.set_xlabel('Time(hours)',fontweight='bold') ax.set_ylabel('Day',fontweight='bold') plt.xticks(xticks,xticklabels); ax.grid(color='y') ax.grid('off') fig.suptitle('Time Matrix of %s\nDaily frequency(Percent) = %4.1f' %(act_w.value,freq),fontsize=21,fontweight='bold') fig.savefig(dr['FIG']+'matrix.jpg',dpi=72) plt.close() return dr['FIG']+'matrix.jpg' @out_3.capture(clear_output=True, wait=True) def plot_act(b): d = read(dr['MAT']+'Timesheet.pkl') mat,tot=gen_mat(act_w.value,date_from.value,date_to.value) display(Image(plot_matrix(mat))) display(Image(plot_ts(act_w.value,tot))) d = read(dr['MAT']+'Timesheet.pkl') acts=set(d['Activity']) random_act = np.random.choice(list(acts), 1, replace=False) act_w=widgets.Dropdown(options=acts, value=random_act, description='Activity', disabled=False, ) date_from = widgets.DatePicker(description='From', value=dt.date.today()-dt.timedelta(21), disabled=False) date_to = widgets.DatePicker(description='Upto', value=dt.date.today(), disabled=False) b_mat = widgets.Button(description='Show Matrix', icon='play', button_style='warning', ) b_mat.on_click(plot_act) matrix_ui=VBox([HBox([act_w,date_from,date_to,b_mat]),out_3]) return matrix_ui
def track(): import os import sys import socket import platform import datetime as dt import glob import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns import ipywidgets as widgets import imp import time import pickle import threading import warnings from IPython.display import display, HTML, Image, Video from ipywidgets import interact, interact_manual, fixed from ipywidgets import Label, FloatProgress, FloatSlider, Button from ipywidgets.widgets import Layout, HBox, VBox warnings.filterwarnings('ignore') sns.set() plt.rcParams.update({'font.family': 'serif', 'font.weight': 'bold'}) info = { 'System ': socket.gethostname(), 'Platform': platform.platform(), 'Python Version': sys.version, 'Python Directory': sys.executable, 'Current Directory': os.getcwd(), 'Last Run': dt.datetime.now().strftime('%d %b %Y, %H:%M:%S'), } dr = {} cwd = os.getcwd() keys = ['DOC', 'EXT', 'FIG', 'MAT', 'RAW', 'REP', 'STC', 'VID'] dr.update({k: '%s/%s/' % (cwd, k) for k in keys}) for k in dr: os.makedirs(dr[k], exist_ok=True) dpi = 72 Activity = [ 'Sleeping', 'Drinks', 'Refresh', 'Walk', 'Yoga', 'Gym', 'Breakfast', 'Driving', 'Management', 'Python', 'Tea', 'Study', 'Lunch', 'Table Tennis', 'Discussions', 'Report Writing', 'Meetings', 'Presentations', 'Snacks', 'Stairs', 'Writing', 'Dinner','Housework', 'Family', 'Friends', 'Meetups', 'Volleyball', 'Housework', 'Reading non fiction', 'Reading fiction', 'Singing', 'Movie', 'TV Series', 'YouTube', 'Music', 'Web Surfing', 'Coursera', 'Volleyball', 'Cycling', 'Traveling', 'Shopping', 'Social Media', 'Entertainment', 'Vocabulary', 'Thinking','News', 'Video Shooting','Video Editing','Creative Works','Chatting' ] msg = "Welcome to Time Management !\nSince this is your first time.\nYou have to manually enter your first entry and rerun the cell again to access all features." out_0 = widgets.Output() out_1 = widgets.Output() out_2 = widgets.Output() out_3 = widgets.Output() out_4 = widgets.Output() out_5 = widgets.Output() def sync(): ''' Sync the timesheets between your local and external sources. It will take no inputs, just run the function. It will save 2 minutes of everyday and possible mistakes ''' import shutil import time if info['Platform'][:7] == 'Windows': ep = 'I:/Timesheet.pkl' elif info['System ']=='kali': ep = '/media/root/UUI/Timesheet.pkl' else: ep = '/media/prateek/UUI/Timesheet.pkl' if not os.path.exists(ep): print('%s does not exists ' % (ep)) return lp = dr['MAT'] + 'Timesheet.pkl' ext = os.path.getmtime(ep) lcl = os.path.getmtime(lp) extsz=os.path.getsize(ep) lclsz=os.path.getsize(lp) print('Local : %s %6.2f KB' % (time.ctime(lcl),lclsz/1024.)) print('External : %s %6.2f KB' % (time.ctime(ext),extsz/1024.)) if (lcl > ext) and (lclsz>extsz) : shutil.copy(lp, ep) print('Copied to external') elif (lcl < ext) and (lclsz<extsz) : shutil.copy(ep, lp) print('Copied to local') else: print('Already in Sync. Do manually if you do not believe so') def update(): ''' Update the timesheet from reading the atime logger csv report. Benefits :- Save the time spent on manual entries. Easily get the time spent upto the second's precision This process will always be performed on a local system ''' fn_csv = dr['RAW'] + dt.datetime.today().strftime('report-%d-%m-%Y.csv') if not os.path.exists(fn_csv): print('%s does not exists' % (fn_csv)) return aa = pd.read_csv(fn_csv) idx = aa[aa[aa.columns[0]] == aa.columns[0]].index[0] - 1 aa1 = aa.loc[0:idx] d = read(dr['MAT'] + 'Timesheet.pkl') d.iloc[-1]['To'] b = aa1[pd.to_datetime(aa1['From']) > d.iloc[-1]['To']] b1 = { 'Activity': [i.rstrip() for i in b['Activity type']], 'From': pd.to_datetime(b['From']), 'To': pd.to_datetime(b['To']), 'Notes': b['Comment'] } b11 = pd.DataFrame(b1) b12 = b11.reindex(index=b11.index[::-1]) b12['Duration'] = b12['To'] - b12['From'] if len(b12) == 0: print('Data is already updated') else: print('%d entries added' % (len(b12))) d = pd.concat((d, b12), ignore_index=True) d = d.fillna('') d.to_pickle(dr['MAT'] + 'Timesheet.pkl') d.to_pickle(dr['EXT'] + dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl')) @out_5.capture(clear_output=True, wait=True) def sync_update(): ''' It will sync and update ( from csv) the timesheet ''' sync() update() sync() display(read(dr['MAT'] + 'Timesheet.pkl').tail()) @out_5.capture(clear_output=True, wait=True) def sync_update1(b): ''' It will sync and update ( from csv) the timesheet ''' sync() update() sync() display(read(dr['MAT'] + 'Timesheet.pkl').tail()) def make_df(lst): columns = 'Activity', 'From', 'To', 'Notes' a = pd.DataFrame(lst, columns=columns) a['Duration'] = a['To'] - a['From'] return a def make_df_id(lst, idx): columns = 'Activity', 'From', 'To', 'Notes' a = pd.DataFrame(lst, columns=columns, index=[idx - 0.5]) a['Duration'] = a['To'] - a['From'] return a def read(fn): ''' read the saved variable using pickle library of python. ''' with open(fn, 'rb') as f: data = pickle.load(f) return data def save(dct, fn): ''' It will save the variable using pickle library fn : will be the output file name ( can be any .pkl is convention) ''' with open(fn, 'wb') as f: pickle.dump(dct, f) def loop_1(): while b_start[1].icon == 'stop': To[1].value = str(dt.datetime.today() - pd.to_datetime(From[1].value))[7:-7] time.sleep(1) def loop_2(): while b_start[2].icon == 'stop': To[2].value = str(dt.datetime.today() - pd.to_datetime(From[2].value))[7:-7] time.sleep(1) def loop_3(): while b_start[3].icon == 'stop': To[3].value = str(dt.datetime.today() - pd.to_datetime(From[3].value))[7:-7] time.sleep(1) @out_0.capture(clear_output=True, wait=True) def stop_click(b): ''' Function for Manual Time Logging ''' A = Act[0].value From_str = From[0].value To_str = To[0].value N = Notes[0].value if os.path.exists(dr['MAT'] + 'Timesheet.pkl'): d = read(dr['MAT'] + 'Timesheet.pkl') else: d = pd.DataFrame( columns=['Activity', 'From', 'To', 'Notes', 'Duration']) F = pd.to_datetime(From_str) T = pd.to_datetime(To_str) aa = make_df([[A, F, T, N]]) d = pd.concat((d, aa), ignore_index=True) d.to_pickle(dr['MAT'] + 'Timesheet.pkl') d.to_pickle(dr['EXT'] + dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl')) display(d.tail()) @out_1.capture(clear_output=True, wait=True) def start_click_1(b): ''' Function for automatic time logging ''' if b_start[1].icon == 'play': From[1].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') To[1].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') To[1].description = 'Elapsed Time' b_start[1].icon = 'stop' b_start[1].button_style = 'danger' display(read(dr['MAT'] + 'Timesheet.pkl').tail()) threading.Thread(target=loop_1).start() else: To[1].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') To[1].description = 'To' b_start[1].icon = 'play' b_start[1].button_style = 'success' fnn = dr['MAT'] + 'Timesheet.pkl' if os.path.exists(fnn): d = read(fnn) else: d = pd.DataFrame( columns=['Activity', 'From', 'To', 'Notes', 'Duration']) F = pd.to_datetime(From[1].value) T = pd.to_datetime(To[1].value) aa = make_df([[Act[1].value, F, T, Notes[1].value]]) d = pd.concat((d, aa), ignore_index=True) d.to_pickle(fnn) d.to_pickle(dr['EXT'] + dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl')) display(d.tail()) @out_1.capture(clear_output=True, wait=True) def start_click_2(b): ''' Function for automatic time logging ''' if b_start[2].icon == 'play': From[2].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') To[2].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') To[2].description = 'Elapsed Time' b_start[2].icon = 'stop' b_start[2].button_style = 'danger' threading.Thread(target=loop_2).start() display(read(dr['MAT'] + 'Timesheet.pkl').tail()) else: To[2].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') To[2].description = 'To' b_start[2].icon = 'play' b_start[2].button_style = 'success' fnn = dr['MAT'] + 'Timesheet.pkl' if os.path.exists(fnn): d = read(fnn) else: d = pd.DataFrame( columns=['Activity', 'From', 'To', 'Notes', 'Duration']) F = pd.to_datetime(From[2].value) T = pd.to_datetime(To[2].value) aa = make_df([[Act[2].value, F, T, Notes[2].value]]) d = pd.concat((d, aa), ignore_index=True) d.to_pickle(fnn) d.to_pickle(dr['EXT'] + dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl')) display(d.tail()) @out_1.capture(clear_output=True, wait=True) def start_click_3(b): ''' Function for automatic time logging ''' if b_start[3].icon == 'play': From[3].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') To[3].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') To[3].description = 'Elapsed Time' b_start[3].icon = 'stop' b_start[3].button_style = 'danger' threading.Thread(target=loop_3).start() display(read(dr['MAT'] + 'Timesheet.pkl').tail()) else: To[3].value = dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S') To[3].description = 'To' b_start[3].icon = 'play' b_start[3].button_style = 'success' fnn = dr['MAT'] + 'Timesheet.pkl' if os.path.exists(fnn): d = read(fnn) else: d = pd.DataFrame( columns=['Activity', 'From', 'To', 'Notes', 'Duration']) F = pd.to_datetime(From[3].value) T = pd.to_datetime(To[3].value) aa = make_df([[Act[3].value, F, T, Notes[3].value]]) d = pd.concat((d, aa), ignore_index=True) d.to_pickle(fnn) d.to_pickle(dr['EXT'] + dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl')) display(d.tail()) @out_2.capture(clear_output=True, wait=True) def edit_data_click(b): index = IND.value col = COL.value value = VAL.value d = read(dr['MAT'] + 'Timesheet.pkl') print('Old Value : %s New Value : %s' % (d.loc[index, col], value)) if col == 'Activity': if value in Activity: d.loc[index, col] = value else: print( '%s is not in any activity. Please include %s in activity list first' % (value, value)) elif col in ['From', 'To']: value = pd.to_datetime(value) d.loc[index, col] = value else: d.loc[index, col] = value d['Duration'] = d['To'] - d['From'] d.to_pickle(dr['MAT'] + 'Timesheet.pkl') d.to_pickle(dr['EXT'] + dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl')) print('Here is the new data') display(d.loc[index - 2:index + 2]) @out_2.capture(clear_output=True, wait=True) def delete_entry(b): idx = IND.value d = read(dr['MAT']+'Timesheet.pkl') d1=d.drop(idx) d1=d1.reset_index(drop=True) d1.to_pickle(dr['MAT']+'Timesheet.pkl') display(read(dr['MAT']+'Timesheet.pkl').loc[idx-2:idx+2]) @out_3.capture(clear_output=True, wait=True) def stop_click1(b): A = Act[4].value From_str = From[4].value To_str = To[4].value N = Notes[4].value idx = IND1.value F = pd.to_datetime(From_str) T = pd.to_datetime(To_str) val = make_df_id([[A, F, T, N]], idx) d = read(dr['MAT'] + 'Timesheet.pkl') d = d.append(val, ignore_index=False) d = d.sort_index().reset_index(drop=True) d.to_pickle(dr['MAT'] + 'Timesheet.pkl') d.to_pickle(dr['EXT'] + dt.datetime.now().strftime('Timesheet-%y%m%d-%H%M%S.pkl')) display(d.loc[idx - 2:idx + 2]) def ana_ui(): out_0 = widgets.Output() out_1 = widgets.Output() out_2 = widgets.Output() out_3 = widgets.Output() def filter_data(k,date): date=dt.datetime(date.year,date.month,date.day) c1=(d['From']>pd.to_datetime(date))*(d['To']<=pd.to_datetime(date)+pd.to_timedelta('23:59:59')) c11=d[c1] idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1] c12=d.loc[idx] c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))] c13=pd.concat((c10,c11)) c2=c13[c13['Activity']==k] return c2 def update_mat(k,mat,tot,date): c11=filter_data(k,date) tot[date]=c11['Duration'].sum() mat[date]=np.zeros(1440) ix=[int(np.round(i.total_seconds()/60)) for i in (c11['From']-date)] iy=[int(np.round(i.total_seconds()/60)) for i in (c11['To']-date)] for i,j in zip(ix,iy): if i<0: mat[date][0:j]=1 date1=date-dt.timedelta(1) date1=dt.datetime(date1.year,date1.month,date1.day) if date1 >= dt.datetime(date_from.value.year,date_from.value.month,date_from.value.day): ii=i+1440 mat[date1][ii:]=1 else: mat[date][i:j]=1 def gen_mat(k,from_date,to_date): dates = pd.date_range(from_date,to_date) mat={} tot={} for date in dates: date=dt.datetime(date.year,date.month,date.day) update_mat(k,mat,tot,date) return mat,tot def plot_ts(k,tot): nmin={i.strftime('%a, %d %b'):tot[i].total_seconds()/60. for i in tot} a1=pd.Series(tot) a33 = pd.Series(nmin) a33 = a33.fillna(0) v=[str(tot[i])[7:] for i in tot] try: title = '%s\nMean = %s\n Regularity = %4.1f %% \n Maximum = %s on %s\n Minimum = %s on %s ' % ( k, str(a1.mean())[7:15], 100 * len(a33[a33 > 0]) / len(a33), str(a1[a1 > dt.timedelta(0)].max())[7:15], a33[a33 > 0].argmax(), str(a1[a1 > dt.timedelta(0)].min())[7:15], a33[a33 > 0].argmin()) except ValueError: title = 'No \n %s \n Activitiy ' %(k) fig, ax = plt.subplots(figsize=(16, 8)) plt.subplots_adjust(top=0.8, bottom=0.25) a33.plot.bar(width=1, ax=ax, color='g') ax.set_ylabel('Minutes', fontweight='bold') for j, i in enumerate(ax.patches): if v[j] != '00:00:00': if a33[j] < 0.2 * a33[a33 > 0].max(): ax.text(i.get_x() + 0.45, 1.5 * a33[j], v[j], fontsize=10, color='blue', rotation=90) else: ax.text(i.get_x() + 0.45, 0.1 * a33[j], v[j], fontsize=10, color='yellow', rotation=90) fig.suptitle(title, fontsize=18, fontweight='bold') fig.savefig(dr['FIG']+'ts.jpg',dpi=72) plt.close() return dr['FIG']+'ts.jpg' def plot_matrix(mat): dd1=np.zeros((len(mat),1440)) for i,j in enumerate(mat): dd1[i,:]=mat[j] freq=100*(len(np.where(dd1.sum(axis=1)>0)[0])/dd1.shape[0]) fig,ax=plt.subplots(figsize=(15,6)) ax.imshow(dd1,aspect='auto',cmap=mpl.colors.ListedColormap(['white','g'])) labels=[j.strftime('%a %d %b') for j in mat] plt.yticks(range(len(mat)),labels); xticks=np.arange(60,1440,60) xticklabels=np.arange(1,24) ax.set_xlabel('Time(hours)',fontweight='bold') ax.set_ylabel('Day',fontweight='bold') plt.xticks(xticks,xticklabels); ax.grid(color='y') ax.grid('off') fig.suptitle('Time Matrix of %s\nDaily frequency(Percent) = %4.1f' %(act_w.value,freq),fontsize=21,fontweight='bold') fig.savefig(dr['FIG']+'matrix.jpg',dpi=72) plt.close() return dr['FIG']+'matrix.jpg' @out_3.capture(clear_output=True, wait=True) def plot_act(b): d = read(dr['MAT']+'Timesheet.pkl') mat,tot=gen_mat(act_w.value,date_from.value,date_to.value) display(Image(plot_matrix(mat))) display(Image(plot_ts(act_w.value,tot))) d = read(dr['MAT']+'Timesheet.pkl') acts=set(d['Activity']) random_act = np.random.choice(list(acts), 1, replace=False) act_w=widgets.Dropdown(options=acts, value=random_act, description='Activity', disabled=False, ) date_from = widgets.DatePicker(description='From', value=dt.date.today()-dt.timedelta(21), disabled=False) date_to = widgets.DatePicker(description='Upto', value=dt.date.today(), disabled=False) b_mat = widgets.Button(description='Show Matrix', icon='play', button_style='warning', ) b_mat.on_click(plot_act) matrix_ui=VBox([HBox([act_w,date_from,date_to,b_mat]),out_3]) return matrix_ui def history_ui(): date_wid = widgets.DatePicker(description='Pick a Date', value=dt.datetime.today(), disabled=False) def filter_data(date): d = read(dr['MAT']+'Timesheet.pkl') date=dt.datetime(date.year,date.month,date.day) c1=(d['From']>date)*(d['To']<=date+pd.to_timedelta('23:59:59')) c11=d[c1] idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1] c12=d.loc[idx] c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))] for j in ['From','To']: c11[j]=[c11[j].iloc[i].strftime('%H:%M:%S') for i in range(len(c11[j]))] c13=pd.concat((c10,c11)) display(c13) def total_df(date): d = read(dr['MAT']+'Timesheet.pkl') date=dt.datetime(date.year,date.month,date.day) c1=(d['From']>pd.to_datetime(date))*(d['To']<=pd.to_datetime(date)+pd.to_timedelta('23:59:59')) c11=d[c1] idx=[i for i in d.index if d['To'][i].day==d['From'][i].day+1] c12=d.loc[idx] c10=c12[(c12['To']>=date)*(c12['To']<=date+pd.to_timedelta('23:59:59'))] c13=pd.concat((c10,c11)) acts=sorted(list(set(c13['Activity']))) act1=pd.Series(acts) tot=[c13[c13['Activity']==j]['Duration'].sum() for j in act1] tot1=pd.Series(tot) tot2=pd.DataFrame({'Activity': act1,'Total Duration':tot1}) tot2 = tot2.sort_values(by='Total Duration',ascending=False) tot2 = tot2.reset_index(drop=True) display(tot2) out1 = widgets.interactive_output(filter_data, {'date': date_wid}) out2 = widgets.interactive_output(total_df, {'date': date_wid}) ui = VBox([date_wid,HBox([out1,out2])]) return ui Act = {} From = {} To = {} Notes = {} Duration = {} random_act = np.random.choice(Activity, 5, replace=False) for i in range(5): Act[i] = widgets.Dropdown(options=Activity, value=random_act[i], description='Activity', disabled=False, layout=Layout(width='200px')) From[i] = widgets.Text(value='%s' % (dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')), placeholder='Start time', description='From', disabled=False, layout=Layout(width='230px')) To[i] = widgets.Text(value='%s' % (dt.datetime.today().strftime('%Y-%m-%d %H:%M:%S')), placeholder='Start time', description='To', disabled=False, layout=Layout(width='230px')) Notes[i] = widgets.Text(value='', placeholder='Type something', description='Notes', disabled=False, layout=Layout(width='220px')) b_stop = Button(description='', icon='play', button_style='info', layout=Layout(width='100px')) b_stop1 = Button(description='', icon='play', button_style='info', layout=Layout(width='100px')) b_stop.on_click(stop_click) b_stop1.on_click(stop_click1) add_row_ui = VBox([ HBox([Act[0], From[0], To[0], Notes[0], b_stop], layout=Layout(margin='00000')), out_0 ]) b_start = {} timer_ui = {} for i in range(1, 4): b_start[i] = Button(description='', icon='play', button_style='success', layout=Layout(width='100px')) timer_ui[i] = HBox([Act[i], b_start[i], From[i], To[i], Notes[i]], layout=Layout(margin='00000')) b_start[1].on_click(start_click_1) b_start[2].on_click(start_click_2) b_start[3].on_click(start_click_3) COL = widgets.Dropdown(options=['Activity', 'From', 'To', 'Notes'], value='Activity', description='Columns', disabled=False, layout=Layout(width='200px')) app1 = VBox([timer_ui[1], timer_ui[2], timer_ui[3], out_1]) if os.path.exists(dr['MAT'] + 'Timesheet.pkl'): sync_update() IND = widgets.Dropdown(options=read(dr['MAT'] + 'Timesheet.pkl').index[:], value=read(dr['MAT'] + 'Timesheet.pkl').index[-1], description='Index', disabled=False, layout=Layout(width='200px')) IND1 = widgets.Dropdown(options=read(dr['MAT'] + 'Timesheet.pkl').index[:], value=read(dr['MAT'] + 'Timesheet.pkl').index[-1], description='Index', disabled=False, layout=Layout(width='200px')) VAL = widgets.Text(value='', placeholder='Type something', description='Value', disabled=False, layout=Layout(width='300px')) b_edit = Button(description='Edit', icon='play', button_style='warning', layout=Layout(width='100px')) b_del = Button(description='DELETE', icon='play', button_style='Danger', layout=Layout(width='150px')) b_update=Button(description='Refresh', icon='play', button_style='warning', layout=Layout(width='150px')) b_update.on_click(sync_update1) b_edit.on_click(edit_data_click) b_del.on_click(delete_entry) update_ui=VBox([b_update,out_5]) edit_row_ui = VBox( [HBox([IND, COL, VAL, b_edit, b_del], layout=Layout(margin='00000')), out_2]) insert_row_ui = VBox([ HBox([IND1, Act[4], b_stop1]), HBox([From[4], To[4], Notes[4]]), out_3 ]) analysis_ui=ana_ui() hist=history_ui() tab = widgets.Tab() tab.children = [update_ui, add_row_ui, edit_row_ui, insert_row_ui, app1, analysis_ui,hist] tab.set_title(0, 'Updated Timesheet') tab.set_title(1, 'Manual Entry') tab.set_title(2, 'Edit Entry') tab.set_title(3, 'Insert Row') tab.set_title(4, 'Timer') tab.set_title(5, 'Analysis') tab.set_title(6, 'History') tab.box_style = 'danger' else: print(msg) tab = widgets.Tab() tab.children = [add_row_ui] tab.set_title(0, 'Manual Entry') return tab
def get_widget(): self.refresh() return VBox([ HBox([refresh_button,commit_button]), grid_widget ])
def __init__(self): self.scaling_type = Select(options=[r'diffusive (fixed relaxation rate)', r'acoustic (fixed dt)', r'fixed lattice velocity']) self.physical_length = FloatText(value=0.1) self.cells_per_length = FloatText(value=256.0) self.max_physical_velocity = FloatText(value=0.01) self.dx = FloatText(value=self._get_dx()) self.kinematic_viscosity = BoundedFloatText(value=1.0, min=0, max=1e12) self.omega = BoundedFloatText(min=0, max=2, value=1.9) self.dt = FloatText(value=0) self.max_lattice_velocity = FloatText(disabled=True) self.re = FloatText(disabled=True) self.processing_update = False def make_label(text): label_layout = {'width': '200px'} return Label(value=text, layout=label_layout) def make_buttons(input_widget, inverse=False): button_layout = {'width': '20px'} factor = 0.5 if inverse else 2.0 double_btn = Button(description="", button_style='warning', layout=button_layout) half_btn = Button(description="", button_style='success', layout=button_layout) def double_value(_): input_widget.value *= factor def half_value(_): input_widget.value /= factor widgets.jslink((double_btn, 'disabled'), (input_widget, 'disabled')) widgets.jslink((half_btn, 'disabled'), (input_widget, 'disabled')) double_btn.on_click(double_value) half_btn.on_click(half_value) return [half_btn, double_btn] self.form = VBox([ HBox([make_label(r'Scaling'), self.scaling_type]), HBox([make_label(r"Physical Length $[m]$"), self.physical_length]), HBox([make_label(r"Max. velocity $[m/s]$"), self.max_physical_velocity]), HBox([make_label(r"Cells per length"), self.cells_per_length] + make_buttons(self.cells_per_length, True)), HBox([make_label(r"dx"), self.dx] + make_buttons(self.dx)), HBox([make_label(r"Kinematic viscosity $10^{-6}[m^2/s]$"), self.kinematic_viscosity]), HBox([make_label(r"Relaxation rate $\omega$"), self.omega]), HBox([make_label(r"dt"), self.dt] + make_buttons(self.dt)), HBox([make_label(r"Max. lattice velocity"), self.max_lattice_velocity]), HBox([make_label(r"Re"), self.re]), ]) # Change listeners self.physical_length.observe(self._on_physical_length_change, names='value') self.cells_per_length.observe(self._on_cells_per_length_change, names='value') self.dx.observe(self._on_dx_change, names='value') self.physical_length.observe(self._update_re) self.kinematic_viscosity.observe(self._update_re) self.max_physical_velocity.observe(self._update_re) for obj in [self.scaling_type, self.kinematic_viscosity, self.omega, self.dt, self.max_lattice_velocity]: obj.observe(self._update_free_parameter, names='value') self._update_free_parameter() self._update_re()
def __init__(self, model, *args, **kwargs): self.model = model self._fields = {field: Text() for field in self.model.fields} self.radio_button_group = RadioButtons( description="When:", options=[ "All", "30 Days", "24 Hours", "1 Year", "1 Week", "1 Hour" ], ) self.refresh_button = Button(description="Refresh") date_buttons = VBox([self.radio_button_group, self.refresh_button]) self.since_widget = DatetimePicker() self.until_widget = DatetimePicker() date_range = HBox([ Label(value="Date range:"), self.since_widget, Label(value="-"), self.until_widget, ]) grid_children = [] for field, text in self._fields.items(): grid_children.append(Label(value=f"{field}:")) grid_children.append(text) text_grid = GridBox(children=grid_children, layout=Layout(grid_template_columns="30% 70%")) text_input = VBox([date_range, text_grid]) children = (date_buttons, text_input) if self.model.text_search_supported: full_text_label = Label("Full Text Search:") self.text_search_input = Text() text_grid.children += (full_text_label, self.text_search_input) self.text_search_input.observe(self._on_text_view_changed, "value") self.model.events.text.connect(self._on_text_model_changed) super().__init__(children, **kwargs) self.radio_button_group.observe(self._on_radio_button_changed, "value") self.refresh_button.on_click(self._on_reload_request) self.model.events.reload.connect(self._on_reload) self.model.events.query.connect(self._on_reload) self.since_widget.observe(self._on_since_view_changed, "value") self.model.events.since.connect(self._on_since_model_changed) self.until_widget.observe(self._on_until_view_changed, "value") self.model.events.until.connect(self._on_until_model_changed) # Set these values here so the model picks the values up self.model.since = GRACE_HOPPER_BIRTHDAY self.model.until = timedelta() self.radio_button_group.index = self.radio_button_group.options.index( "All") for field, text in zip(self.model.fields, self._fields.values()): def on_field_text_changed(change, field=field): self.model.field_search.update({field: change["new"]}) text.observe(on_field_text_changed, "value") self.model.events.field_search_updated.connect( self._on_field_search_updated)
def RGB_colourspace_models_chromatically_adapted_primaries_widget(): title_Label = Label( 'RGB Colourspace Models Chromatically Adapted Primaries') title_Label.add_class('widget-title') default_layout = {'flex': '1 1 auto', 'width': 'auto'} input_colourspace_Dropdown = Dropdown( options=sorted(colour.RGB_COLOURSPACES), layout=default_layout) illuminant_Dropdown = Dropdown( options=sorted( colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']), layout=default_layout) chromatic_adaptation_transforms_Dropdown = Dropdown( options=sorted(colour.CHROMATIC_ADAPTATION_TRANSFORMS), layout=default_layout) formatter_Dropdown = Dropdown( options=['str', 'repr'], layout=default_layout) decimals_IntSlider = IntSlider(value=10, max=15, layout=default_layout) primaries_Textarea = Textarea(rows=3, layout=default_layout) primaries_Textarea.add_class('widget-output-textarea') def set_primaries_Textarea(): input_colourspace = colour.RGB_COLOURSPACES[ input_colourspace_Dropdown.value] P = colour.chromatically_adapted_primaries( input_colourspace.primaries, input_colourspace.whitepoint, colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer'][ illuminant_Dropdown.value], chromatic_adaptation_transforms_Dropdown.value) with colour.utilities.numpy_print_options( formatter={ 'float': ('{{:0.{0}f}}'.format(decimals_IntSlider.value)).format }, threshold=np.nan): if formatter_Dropdown.value == 'str': P = str(P) elif formatter_Dropdown.value == 'repr': P = repr(P) primaries_Textarea.rows = len(P.split('\n')) primaries_Textarea.value = P def on_input_change(change): if change['type'] == 'change' and change['name'] == 'value': set_primaries_Textarea() input_colourspace_Dropdown.observe(on_input_change) illuminant_Dropdown.observe(on_input_change) chromatic_adaptation_transforms_Dropdown.observe(on_input_change) formatter_Dropdown.observe(on_input_change) decimals_IntSlider.observe(on_input_change) set_primaries_Textarea() widget = Box([ VBox( [ title_Label, Textarea( 'This widget computes the Chromatically Adapted Primaries ' 'of the given RGB Colourspace Model to the given ' 'Illuminant using the ' 'given Chromatic Adaptation Transform.', rows=3, layout=default_layout), Label('Input RGB Colourspace'), input_colourspace_Dropdown, Label('Illuminant'), illuminant_Dropdown, Label('Chromatic Adaptation Transform'), chromatic_adaptation_transforms_Dropdown, Label('Formatter'), formatter_Dropdown, HBox([Label('Decimals:'), decimals_IntSlider]), Label('RGB Transformation Matrix'), primaries_Textarea, ], layout={ 'border': 'solid 2px', 'width': '55%' }) ]) return widget
def __init__(self): self.start_button = Button( value=False, description='Start Camera', disabled=False, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Start the camera to take pictures for classifier ', icon='', layout=Layout(width='25%'), ) self.save_button = Button( value=False, description='Save images', disabled=True, button_style= 'danger', # 'success', 'info', 'warning', 'danger' or '' tooltip='Save images to folder ', icon='', layout=Layout(width='18%', margin="2px 0px 0px 20px"), ) self.load_button = Button( value=False, description='Load images', disabled=False, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Load images from folder ', icon='', layout=Layout(width='18%', margin="2px 0px 0px 20px"), ) self.save_path = Text( value=str(Path("path", "to", "directory")), description='Save path:', disabled=False, ) self.num_pictures = FloatText( value=12, description='#pictures:', disabled=False, layout=Layout(width='20%'), ) self.use_augmentation = Checkbox( value=False, description='Augmentation', disabled=False, tooltip='Use Augmentation', icon='check', ) self.progress_text = Label( value='', layout=Layout(margin="5px 0px 5px 20px"), ) self.widget_box = VBox(( HBox( (self.num_pictures, self.use_augmentation, self.start_button), layout=Layout(align_content="flex-start"), ), HBox( (self.progress_text, ), layout=Layout(align_content="flex-start"), ), HBox( (self.save_path, self.save_button, self.load_button), layout=Layout(align_content="flex-start"), ), )) self.start_button.on_click(self._start_video) self.save_button.on_click(self._save_images) self.load_button.on_click(self._load_images) self.collector = ImageCollector()
def __init__(self): """ :param int i: """ self.test_sound = None self.test_data = None self.select_test_data_options = None self.select_test_data = Dropdown( options={'Record test data': 0, 'Load test data files': 1 }, value=0, description='Choose training data:', disabled=False, layout=Layout(width='400px'), style={'description_width': '160px'}, ) self.select_test_data.observe(self.on_change) self.select_nseconds = Dropdown( options={ '2s': 2, '3s': 3, '5s': 5 }, value=2, description='Choose recording length:', disabled=False, layout=Layout(width='400px', display='block'), style={'description_width': '160px'}, ) self.container = Output( value="", ) self.submit_button = Button( value=False, description='Get test data', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='TEST: use recorded sounds or record new', icon='' ) self.play_button = Button( value=False, description='Play the recording', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltip='TEST: play recorded or loaded sounds', icon='' ) self.widget_box = VBox( ( HBox( ( VBox(( self.select_test_data, self.select_nseconds ), ), VBox(( self.submit_button, self.play_button ), ) ), ), self.container ), ) self.submit_button.on_click(self._run) self.play_button.on_click(self._playback)
def __init__(self, df: pd.DataFrame, col_name: str, df_name: str, page_size: int): self._clusterer = Clusterer(df, col_name, df_name) self._clusterer.cluster("fingerprint") self._page_size = page_size # clustering dropdown and export code checkbox, used in the top row self._clustering_method_label = Label( " Clustering Method: ", layout=Layout(margin="2px 0 0 20px")) self._clustering_method_drop = Dropdown( options=[ "fingerprint", "ngram-fingerprint", "phonetic-fingerprint", "levenshtein" ], layout=Layout(width="150px", margin="0 0 0 10px"), ) self._clustering_method_drop.observe(self._cluster_method_change, names="value") self._export_code = Checkbox( value=True, description="export code", layout=Layout(width="165px", margin="0 0 0 482px"), style={"description_width": "initial"}, ) self._dropds = HBox( [ self._clustering_method_label, self._clustering_method_drop, self._export_code, ], layout=Layout(height="35px", margin="10px 0 0 0"), ) # text boxes for clustering parameters used in the top row self._ngram_text = Text( value=DEFAULT_NGRAM, description="n-gram", layout=Layout(width="130px"), continuous_update=False, ) self._radius_text = Text( value=DEFAULT_RADIUS, description="Radius", layout=Layout(width="130px"), continuous_update=False, ) self._block_chars_text = Text( value=DEFAULT_BLOCK_SIZE, description="Block Chars", layout=Layout(width="130px"), continuous_update=False, ) self._ngram_text.observe(self._param_recluster, names="value") self._radius_text.observe(self._param_recluster, names="value") self._block_chars_text.observe(self._param_recluster, names="value") # create header labels, second row headers = HBox( [ Label("Distinct values", layout=Layout(margin="0 0 0 10px")), Label("Total values", layout=Layout(margin="0 0 0 35px")), Label("Cluster values", layout=Layout(margin="0 0 0 95px")), Label("Merge?", layout=Layout(margin="0 0 0 295px")), Label("Representative value", layout=Layout(margin="0 0 0 50px")), ], layout=Layout(margin="10px"), ) # create buttons for bottom row self._sel_all = Checkbox(description="Select all", layout=Layout(width="165px")) self._sel_all.observe(self._select_all, names="value") merge_and_recluster = Button(description="Merge and Re-Cluster", layout=Layout(margin="0 0 0 466px", width="150px")) merge_and_recluster.on_click(self._execute_merge) finish = Button(description="Finish", layout=Layout(margin="0 0 0 10px")) finish.on_click(self._close) # next and previous page buttons self._next_button = Button(description="Next") self._next_button.on_click(self._next_page) self._prev_button = Button(description="Previous", layout=Layout(margin="0 0 0 20px")) self._prev_button.on_click(self._prev_page) # an index in the clusters Series indicating the start of the current page self._page_pos = 0 # loading label, displayed when re-clustering or next page load self._loading_label = Label("Loading...", layout=Layout(margin="170px 0 0 440px")) # displayed when the user enters a non integer value into a clustering parameter text box self._invalid_param_label = Label( "Invalid clustering parameter, please enter an integer", layout=Layout(margin="170px 0 0 350px"), ) self._reprs = [ Text(layout=Layout(width="200px", margin="0 10px 0 40px")) for _ in range(self._page_size) ] self._checks = [ Checkbox(indent=False, layout=Layout(width="auto", margin="0 0 0 20px")) for _ in range(self._page_size) ] # VBox containing a VBox with all the clusters in the first row and an optional # second row containing next and previous page buttons self._cluster_and_next_prev = VBox() self._cluster_vbox = VBox( layout=Layout(height="450px", flex_flow="row wrap")) footer = HBox([self._sel_all, merge_and_recluster, finish]) box_children = [ self._dropds, headers, self._cluster_and_next_prev, footer ] box_layout = Layout(display="flex", flex_flow="column", align_items="stretch", border="solid") self._box = Box(children=box_children, layout=box_layout) self._update_clusters()
def __menu(self, parameter_type, box, category_name=None): btn_add = Button(description='Add') ddn_add = Dropdown() if parameter_type == 'scalars': def fn_add(self): value = None if ddn_add.value == 'Integer': value = 1 elif ddn_add.value == 'Float': value = 1.0 elif ddn_add.value == 'Bool': value = True name = f'{ddn_add.value}_{len(box.children)}' scalar = self.__lp.add_scalar(name, value, category=category_name) editor = make_scalar_editor(scalar) editor.observe(self.__on_editor_changed(scalar)) box.children = (*box.children, editor) if self.__auto_save: self.__save() if self.__auto_apply: self.on_lpy_context_change(self.__lp.dumps()) ddn_add.options = ['Integer', 'Float', 'Bool'] elif parameter_type == 'materials': def fn_add(self): index = max(self.__lp.get_colors().keys()) + 1 if len( self.__lp.get_colors().keys()) else 0 self.__lp.set_color( index, pgl.Material(ambient=(80, 80, 80), diffuse=1)) editor = make_color_editor(self.__lp.get_color(index), index, no_name=True) editor.observe( self.__on_editor_changed(self.__lp.get_color(index))) box.children = (*box.children, editor) if self.__auto_save: self.__save() if self.__auto_apply: self.on_lpy_context_change(self.__lp.dumps()) ddn_add.options = ['Color'] elif parameter_type == 'curves': def fn_add(self): name = f'{ddn_add.value}_{len(box.children)}' if ddn_add.value == 'Function': curve = self.__lp.add_function(name, category=category_name) else: curve = self.__lp.add_curve(name, category=category_name) editor = make_curve_editor(curve) editor.observe(self.__on_editor_changed(curve)) box.children = (*box.children, editor) if self.__auto_save: self.__save() if self.__auto_apply: self.on_lpy_context_change(self.__lp.dumps()) ddn_add.options = ['Curve', 'Function'] btn_add.on_click(lambda x: fn_add(self)) return HBox((btn_add, ddn_add))
def servers(self, line='', cell=None): display(HBox([ServerWidget(l) for l in cell.splitlines()]))
layout={'width': 'max-content'}, # If the items' names are long ) # Export single date images export_summary_images = Checkbox( value=False, description='Export to Drive', disabled=False, indent=False, layout={'width': 'max-content'} # If the items' names are long ) lbl = Label(value=('Select parameters for exporting single date images - ' 'WARNING can be hundreds of images:'), style={'description_width': 'initial'}) single_date_export_label = HBox([lbl]) lbl = Label( value=('Select parameters for exporting summary date images - i.e. ' 'the percentage (%) of inundation:'), style={'description_width': 'initial'}) summary_date_export_label = HBox([lbl]) export_variables = Accordion(children=[ VBox([ single_date_export_label, band_option, export_images, summary_date_export_label, summary_band_option, water_threshold, export_summary_images ]) ])
def DataApp(): frequency = FloatText(value=0.5, description="f (Hz)") zsrc = FloatText(value=-950.0, description="src height (m)") zrx = FloatText(value=-1000.0, description="rx height (m)") rho0 = FloatText(value=1e8, description="$\\rho_{0} \ (\Omega m)$") rho1 = FloatText(value=0.3, description="$\\rho_{1} \ (\Omega m)$") rho2 = FloatText(value=1.0, description="$\\rho_{2} \ (\Omega m)$") rho3 = FloatText(value=100.0, description="$\\rho_{3} \ (\Omega m)$") rho4 = FloatText(value=1.0, description="$\\rho_{4} \ (\Omega m)$") rv_rh = FloatText(value=1.0, description="$\\rho_{2 \ v} / \\rho_{2 \ h}$") dz1 = FloatText(value=1000.0, description="dz1 (m)") dz2 = FloatText(value=1000.0, description="dz2 (m)") dz3 = FloatText(value=200.0, description="dz3 (m)") frequency_bg = FloatText(value=0.5, description="f$^{BG}$ (Hz)") zsrc_bg = FloatText(value=-950.0, description="src height$^{BG}$ (m)") zrx_bg = FloatText(value=-1000.0, description="rx height$^{BG}$ (m)") rho0_bg = FloatText(value=1e8, description="$\\rho_{0}^{BG} \ (\Omega m)$") rho1_bg = FloatText(value=0.3, description="$\\rho_{1}^{BG} \ (\Omega m)$") rho2_bg = FloatText(value=1.0, description="$\\rho_{2}^{BG} \ (\Omega m)$") rho3_bg = FloatText(value=1.0, description="$\\rho_{3}^{BG} \ (\Omega m)$") rho4_bg = FloatText(value=1.0, description="$\\rho_{4}^{BG} \ (\Omega m)$") rv_rh_bg = FloatText( value=1.0, description="$\\rho_{2 \ v}^{BG} / \\rho_{2 \ h}^{BG}$") dz1_bg = FloatText(value=1000.0, description="dz1$^{BG}$ (m)") dz2_bg = FloatText(value=1000.0, description="dz2$^{BG}$ (m)") dz3_bg = FloatText(value=200.0, description="dz3$^{BG}$ (m)") Field = ToggleButtons(options=["E", "H", "Zxy"], value="E", description="Field") Plane = ToggleButtons(options=["XZ", "YZ"], value="XZ", description="Plane") Component = ToggleButtons(options=["x", "y", "z"], value="x", description="rx direction") Complex = ToggleButtons(options=["Real", "Imag", "Amp", "Phase"], value="Amp", description="Complex") scale = ToggleButtons(options=["log", "linear"], value="log", description="Scale") Fixed = widgets.widget_bool.Checkbox(value=False, description="Fixed") vmin = FloatText(value=None, description="vmin") vmax = FloatText(value=None, description="vmax") # __manual = True out = widgets.interactive_output( csem_data_app, { "frequency": frequency, "zsrc": zsrc, "zrx": zrx, "rho0": rho0, "rho1": rho1, "rho2": rho2, "rho3": rho3, "rho4": rho4, "rv_rh": rv_rh, "dz1": dz1, "dz2": dz2, "dz3": dz3, "frequency_bg": frequency_bg, "zsrc_bg": zsrc_bg, "zrx_bg": zrx_bg, "rho0_bg": rho0_bg, "rho1_bg": rho1_bg, "rho2_bg": rho2_bg, "rho3_bg": rho3_bg, "rho4_bg": rho4_bg, "rv_rh_bg": rv_rh_bg, "dz1_bg": dz1_bg, "dz2_bg": dz2_bg, "dz3_bg": dz3_bg, "Field": Field, "Plane": Plane, "Component": Component, "Complex": Complex, "scale": scale, "Fixed": Fixed, "vmin": vmin, "vmax": vmax, }, ) panel = VBox([ frequency, zsrc, zrx, rho0, rho1, rho2, rho3, rho4, rv_rh, dz1, dz2, dz3 ]) panel_bg = VBox([ frequency_bg, zsrc_bg, zrx_bg, rho0_bg, rho1_bg, rho2_bg, rho3_bg, rho4_bg, rv_rh_bg, dz1_bg, dz2_bg, dz3_bg, ]) panel_type = VBox( [Field, Plane, Component, Complex, scale, Fixed, vmin, vmax]) return VBox([HBox([panel, panel_bg]), panel_type, out])
def RGB_colourspace_models_transformation_matrix_widget(): title_Label = Label('RGB Colourspace Models Transformation Matrix') title_Label.add_class('widget-title') default_layout = {'flex': '1 1 auto', 'width': 'auto'} input_colourspace_Dropdown = Dropdown( options=sorted(colour.RGB_COLOURSPACES), layout=default_layout) output_colourspace_Dropdown = Dropdown( options=sorted(colour.RGB_COLOURSPACES), layout=default_layout) chromatic_adaptation_transforms_Dropdown = Dropdown( options=sorted(colour.CHROMATIC_ADAPTATION_TRANSFORMS), layout=default_layout) formatter_Dropdown = Dropdown( options=['str', 'repr', 'Nuke'], layout=default_layout) decimals_IntSlider = IntSlider(value=10, max=15, layout=default_layout) RGB_to_RGB_matrix_Textarea = Textarea(rows=3, layout=default_layout) RGB_to_RGB_matrix_Textarea.add_class('widget-output-textarea') def set_RGB_to_RGB_matrix_Textarea(): M = colour.RGB_to_RGB_matrix( colour.RGB_COLOURSPACES[input_colourspace_Dropdown.value], colour.RGB_COLOURSPACES[output_colourspace_Dropdown.value], chromatic_adaptation_transforms_Dropdown.value) with colour.utilities.numpy_print_options( formatter={ 'float': ('{{:0.{0}f}}'.format(decimals_IntSlider.value)).format }, threshold=np.nan): if formatter_Dropdown.value == 'str': M = str(M) elif formatter_Dropdown.value == 'repr': M = repr(M) else: M = NUKE_COLORMATRIX_NODE_TEMPLATE.format( nuke_format_matrix(M, decimals_IntSlider.value), '{0}_to_{1}'.format( input_colourspace_Dropdown.value.replace(' ', '_'), output_colourspace_Dropdown.value.replace(' ', '_'))) RGB_to_RGB_matrix_Textarea.rows = len(M.split('\n')) RGB_to_RGB_matrix_Textarea.value = M def on_input_change(change): if change['type'] == 'change' and change['name'] == 'value': set_RGB_to_RGB_matrix_Textarea() input_colourspace_Dropdown.observe(on_input_change) output_colourspace_Dropdown.observe(on_input_change) chromatic_adaptation_transforms_Dropdown.observe(on_input_change) formatter_Dropdown.observe(on_input_change) decimals_IntSlider.observe(on_input_change) set_RGB_to_RGB_matrix_Textarea() widget = Box([ VBox( [ title_Label, Textarea( 'This widget computes the colour transformation ' 'matrix from the Input RGB Colourspace to the ' 'Output RGB Colourspace using the given ' 'Chromatic Adaptation Transform.', rows=2, layout=default_layout), Label('Input RGB Colourspace'), input_colourspace_Dropdown, Label('Output RGB Colourspace'), output_colourspace_Dropdown, Label('Chromatic Adaptation Transform'), chromatic_adaptation_transforms_Dropdown, Label('Formatter'), formatter_Dropdown, HBox([Label('Decimals:'), decimals_IntSlider]), Label('RGB Transformation Matrix'), RGB_to_RGB_matrix_Textarea, ], layout={ 'border': 'solid 2px', 'width': '55%' }) ]) return widget
def __init__(self): self.start_button = Button( value=False, description='Start Camera', disabled=False, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Start the camera and the recognition algorithm.', icon='') self.use_recorded = RadioButtons( options=['Webcam', 'MP4'], value='Webcam', description='Input', disabled=False, layout=Layout(width='320px'), style={'description_width': '150px'}, ) self.video_path = Text( value='', placeholder=str(Path("path", "to", "video.mp4")), description='Video path:', disabled=True, layout=Layout(width='320px'), style={'description_width': '150px'}, ) self.select_network = Dropdown( options=KerasDetector.available_models, value=KerasDetector.available_models[0], description='Algorithm:', disabled=False, layout=Layout(width='220px'), style={'description_width': '100px'}, ) self.select_frontend = Dropdown( options=["opencv", "matplotlib"], value="opencv", description='Frontend:', disabled=False, layout=Layout(width='220px', padding='8px 0 0 0'), style={'description_width': '100px'}, ) self.video_length = FloatText( value=12.0, description='Video length [s]:', disabled=False, layout=Layout(width='250px'), style={'description_width': '130px'}, ) self.select_framerate = Dropdown( options=[3, 5, 10, 15, 24], value=15, description='Frame rate:', disabled=False, layout=Layout(width='250px', padding='8px 0 0 0'), style={'description_width': '130px'}, ) self.static_text = Label( value="Working directory: {}".format(Path.cwd()), layout=Layout(margin='30px 0 0 0'), ) self.progress_text = Label(value='', ) self.text_box = VBox((self.static_text, self.progress_text), layout=Layout(justify_content="flex-start")) self.widget_box = VBox( (HBox((VBox((self.start_button, ), layout=Layout(justify_content="space-around")), VBox((self.use_recorded, self.video_path), layout=Layout(justify_content="space-around")), VBox((self.video_length, self.select_framerate), layout=Layout(justify_content="space-around")), VBox((self.select_network, self.select_frontend), layout=Layout(justify_content="space-around"))), ), HBox((self.text_box, ), layout=Layout(justify_content="flex-start"))), ) self.start_button.on_click(self._start_video) self.use_recorded.observe(self.refresh_state)