我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用IPython.display.HTML。
def view_live(live, lang='EN'): df_head = pd.DataFrame({'Cover': ['<img src="{0}" width=100 />'.format(live.cover)]}) df_head['Song Name'] = '<p style="color:{0};">{1}</p>'.format(attr_color[live.attr], live.name) df_head['Group'] = live.group df_head['Difficulty'] = live.difficulty df_head['Total Note'] = live.note_number df_head['Duration'] = live.duration df_head.columns = ['<p>{0}</p>'.format(x) for x in list(df_head.columns)] df = live.summary.copy() pos_name = ['<p>{0}</p>'.format(x) for x in ['L1', 'L2', 'L3', 'L4', 'C', 'R4', 'R3', 'R2', 'R1']] df.index = [pos_name[9-x] if type(x)==int else x for x in list(df.index)] df = df.loc[pos_name+['total']] df = df.applymap(lambda x: '<p>{0}</p>'.format(str(int(x)) if np.isclose(2*x,round(2*x)) else '{0:.3f}'.format(x))).transpose() if lang=='CN': df_head.columns = ['<p>{0}</p>'.format(x) for x in ['????', '????', '??', '??', 'Note??', '??']] df.columns = list(df.columns)[:-1] + ['<p>??</p>'] df.index = ['<p>{0}</p>'.format(x) for x in ['??', '??', '??', '??', '??', '????', '????', '??????']] elif lang=='EN': df.index = ['<p>{0}</p>'.format(x) for x in ['tap', 'hold', 'swing', 'star', 'token', 'type weight', 'combo weight', 'weight fraction']] return HTML(html_template.format(df_head.to_html(escape=False, index=False) + df.to_html(escape=False)))
def print_frames(dataframes): if not isinstance(dataframes, tuple): return dataframes border_style = u'\"border: none\"' cells = [u'<td style={}> {} </td>'.format(border_style, df._repr_html_()) for df in dataframes] table = '''<table style={}> <tr style={}>'''.format(border_style, border_style) +\ '\n'.join(cells)+\ ''' </tr> </table>''' return HTML(table) # from http://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/#
def idv_help(line, cell=None): DrilsdownUI.status("") html = "<pre>idv_help Show this help message<br>" \ + "run_idv<br>" \ + "make_ui<br>" \ + "load_bundle <bundle url or file path><br>" \ + " If no bundle given and if set_ramadda has been called the bundle will be fetched from RAMADDA<br>" \ + "load_bundle_make_image <bundle url or file path><br>" \ + "load_catalog Load the case study catalog into the IDV<br>" \ + "make_image <-publish> <-caption ImageName> <-capture (legend|window)> Capture an IDV image and optionally publish it to RAMADDA<br>" \ + "make_movie <-publish> <-caption MovieName> <-capture (legend|window)> Capture an IDV movie and optionally publish it to RAMADDA<br>" \ + "save_bundle <xidv or zidv filename> <-publish> <-embed> - write out the bundle and optionally publish to RAMADDA. If embed then embed the bundle xml into the notebook as a link<br>" \ + "publish_bundle <xidv or zidv filename> - write out the bundle and publish it to RAMADDA<br>" \ + "publish_notebook <notebook file name> - publish the current notebook to RAMADDA via the IDV<br>" \ + "set_ramadda <ramadda url to a Drilsdown case study><br>" \ + "create_case_study <case study name><br>" \ + "set_bbox <north west south east> No arguments to clear the bbox<br></pre>" DrilsdownUI.do_display(HTML(html))
def view_url_clicked(b): DrilsdownUI.do_display(HTML("<a target=ramadda href=" + b.url + ">" + b.name + "</a>")) display(IFrame(src=b.url, width=800, height=400))
def save_bundle(filename, publish=False, embed = False): extra = "" if filename is None: filename = "idv.xidv" if publish: extra += ' publish="true" ' if not os.path.isabs(filename): filename = os.path.join(os.getcwd() ,filename); isl = '<isl><save file="' + filename + '"' + extra + '/></isl>' result = Idv.run_isl(isl); if not result.ok(): print("save failed") return if os.path.isfile(filename): DrilsdownUI.status("Bundle saved:" + filename) if embed: bundle = open(filename, "rb").read() bundle = b64encode(bundle).decode('ascii') name = os.path.basename(filename); html = '<a target=_bundle download="' + name +'" href="data:text/xidv;name=' + name +';base64,' + bundle +'">' + name +'</a>'; DrilsdownUI.do_display(HTML(html)) else: DrilsdownUI.do_display(FileLink(filename)) return; DrilsdownUI.status("Bundle not saved")
def publish(self, name, file=None, parent=None): if "RAMADDA_USER" not in os.environ: print("No RAMADDA_USER environment variable set") return if "RAMADDA_PASSWORD" not in os.environ: print("No RAMADDA_PASSWORD environment variable set") return user = os.environ['RAMADDA_USER'] password = os.environ['RAMADDA_PASSWORD'] if parent is None: parent = self.entryId extra = "" if file is not None: extra += ' file="' + os.path.basename(file) + '" ' entry_xml = '<entry name="' + name + '" ' + extra + '/>' with NamedTemporaryFile(suffix='.zip') as tmpZip: with ZipFile(tmpZip.name, 'w') as myzip: with NamedTemporaryFile(suffix='.xml') as tmpFile: entries_file = open(tmpFile.name, 'w') entries_file.write(entry_xml) entries_file.close() myzip.write(tmpFile.name, arcname='entries.xml') if file is not None: myzip.write(file) files = {'file': open(tmpZip.name, 'rb')} # TODO: change http to https url = self.make_url("/entry/xmlcreate") r = requests.post(url, files=files, data={'group': parent, 'auth.user': user, 'auth.password': password, 'response': 'xml'}) root = ET.fromstring(r.text) if root.attrib['code'] == 'ok': for child in root: display(HTML("Published file: " + self.make_entry_href(child.attrib['id'], name))) else: print('Error publishing file') print(r.text)
def add_display_widget(self, row): b = DrilsdownUI.make_button("Set URL", DrilsdownUI.set_url_clicked) b.entry = self row.append(b) link = self.get_repository().make_url("/entry/show/?output=idv.islform&entryid=" + self.get_id()) row.append(HTML('<a target=ramadda href="' + link + '">Subset Bundle</a>')) # Make the REPOSITORIES
def plot_state(self, **options): """Plot the current state of the inference algorithm. This feature is still experimental and only supports 1d or 2d cases. """ displays = [] if options.get('interactive'): from IPython import display displays.append( display.HTML('<span>Threshold: {}</span>'.format(self.state['threshold']))) visin.plot_sample( self.state['samples'], nodes=self.parameter_names, n=self.objective['n_samples'], displays=displays, **options)
def slider(self, div_id) : #div_id = self.show(*args, **kwargs) def change_frame(w) : (updates, indices) = self.get_frame(w-1) script = '' for i in range(len(updates)) : jupdate = json.dumps(updates[i], cls=utils.PlotlyJSONEncoder) #pprint(jupdate) script = script \ + 'Plotly.restyle("{id}", {update}, [{index}]);'.format( id=div_id, update=jupdate, index = indices[i][1:-1]) #print(script) update_str = ( '' '<script type="text/javascript">' + 'window.PLOTLYENV=window.PLOTLYENV || {{}};' 'window.PLOTLYENV.BASE_URL="' + 'https://plot.ly' + '";' '{script}' + '</script>' '').format(script=script) display(HTML(update_str)) interact((lambda frame : change_frame(frame)), frame=(1,len(self.frames)))
def __init__(self, shell): super(PixiedustNodeMagics,self).__init__(shell=shell) display(HTML( """ <div style="margin:10px"> <a href="https://github.com/ibm-cds-labs/pixiedust_node" target="_new"> <img src="https://github.com/ibm-cds-labs/pixiedust_node/raw/master/docs/_images/pdn_icon32.png" style="float:left;margin-right:10px"/> </a> <span>Pixiedust Node.js</span> </div> """ )) # create Node.js sub-process path = os.path.join(__path__[0], 'pixiedustNodeRepl.js') self.n = Node(path) ShellAccess.npm = Npm() ShellAccess.node = self.n
def show_site(self, article, nwork, info): """Display site citation""" text = "# Temp\n" text += "insert('''" text += citation_text( self.citation_var, info, ref=article.get('citation_id', ''), backward=self.backward ) + "\n" text += "''', citations='{}');".format(self.citation_file) display_cell(text) self.output_widget.clear_output() with self.output_widget: if self.to_display: display("\n".join(self.to_display)) if 'div' in article: display(HTML(repr(article['div']))) elif 'name' in article: print(article['name']) self.to_display = []
def add_input_toggle(): from IPython.display import HTML, display r = HTML(''' <script> $( document ).ready(function () { IPython.CodeCell.options_default['cm_config']['lineWrapping'] = true; IPython.notebook.get_selected_cell() IPython.toolbar.add_buttons_group([ { 'label' : 'toggle all input cells', 'icon' : 'fa-eye-slash', 'callback': function(){ $('div.input').slideToggle(); } } ]); }); </script> ''') display(r) return r
def toggle(): html = HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <a href="javascript:code_toggle()">toggle code cells</a>''') return html
def display_source_ipython(self): """ Convenience method to print the loaded source file as syntax highlighted HTML within IPython. """ from pygments import highlight from pygments.lexers import SLexer from pygments.formatters import HtmlFormatter import IPython.display as display with open(self.source_file) as f: code = f.read() formatter = HtmlFormatter() return display.HTML('<style type="text/css">{}</style>{}'.format( formatter.get_style_defs('.highlight'), highlight(code, SLexer(), formatter)))
def show_graph(graph_def, max_const_size=32): """Visualize TensorFlow graph.""" if hasattr(graph_def, 'as_graph_def'): graph_def = graph_def.as_graph_def() strip_def = strip_consts(graph_def, max_const_size=max_const_size) code = """ <script> function load() {{ document.getElementById("{id}").pbtxt = {data}; }} </script> <link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()> <div style="height:600px"> <tf-graph-basic id="{id}"></tf-graph-basic> </div> """.format(data=repr(str(strip_def)), id='graph'+str(np.random.rand())) iframe = """ <iframe seamless style="width:1200px;height:620px;border:0" srcdoc="{}"></iframe> """.format(code.replace('"', '"')) display(HTML(iframe))
def __init__(self, names, initial_size, width=900, height=480): # Call this once to raise an error early if necessary: self._colors = colors.colors(len(names)) self._start = time.perf_counter() self._initial_size = initial_size self._sources = collections.OrderedDict([ (name, { 'hist': bm.ColumnDataSource( data={'top': [], 'left': [], 'right': []}), 'pdf': bm.ColumnDataSource( data={'x': [], 'y': []}), 'stddev': bm.ColumnDataSource( data={'base': [], 'lower': [], 'upper': []}), 'median': bm.ColumnDataSource( data={'x': [], 'y': []}) }) for name in names ]) self._width = width self._height = height self._plot = None self._elapsed_rendering_seconds = 0.0 self._describe_widget = ipdisplay.HTML('')
def drawMolsByLabel(topicModel, label, idLabelToMatch=0, baseRad=0.5, molSize=(250,150),\ numRowsShown=3, tableHeader='', maxMols=100): result = generateMoleculeSVGsbyLabel(topicModel, label, idLabelToMatch=idLabelToMatch,baseRad=baseRad,\ molSize=molSize, maxMols=maxMols) if len(result) == 1: print(result) return svgs, namesSVGs = result finalsvgs = [] for svg in svgs: # make the svg scalable finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\ +' '+str(molSize[1])+'"')) return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader='Molecules of '+str(label), namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4))) # produces a svg grid of the molecules of a certain label and highlights the most probable topic
def drawMolsByTopic(topicModel, topicIdx, idsLabelToShow=[0], topicProbThreshold = 0.5, baseRad=0.5, molSize=(250,150),\ numRowsShown=3, color=(.0,.0, 1.), maxMols=100): result = generateMoleculeSVGsbyTopicIdx(topicModel, topicIdx, idsLabelToShow=idsLabelToShow, \ topicProbThreshold = topicProbThreshold, baseRad=baseRad,\ molSize=molSize,color=color, maxMols=maxMols) if len(result) == 1: print(result) return svgs, namesSVGs = result finalsvgs = [] for svg in svgs: # make the svg scalable finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\ +' '+str(molSize[1])+'"')) tableHeader = 'Molecules in topic '+str(topicIdx)+' (sorted by decending probability)' return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader=tableHeader,\ namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4))) # produces a svg grid of the molecules belonging to a certain topic and highlights this topic within the molecules
def interactive_html(self): from IPython.display import display, HTML uid = str(uuid.uuid4()) display(HTML(''.join(self.empty_table_generator(uid)))) internal_columns = self.get_internal_columns() for key, report in self.get_reports(): js = ''' (function(){ var node = document.getElementById('diligent-%(uid)s-%(check_no)s-%(column_no)s'); var data = '%(data)s'; node.innerHTML = data; if (!data) { node.style.backgroundColor = '#eee'; } }()); ''' % { 'uid': uid, 'check_no': key[1], 'column_no': internal_columns.index(key[0]), # FIXME 'data': escape_js(''.join(self.render_messages(report))) } display({'application/javascript': js}, raw=True) return ''
def _gen_summary(self, col_width=50): pd.set_option('display.max_colwidth', -1) song_name = '<p style="color:{0};">{1}</p>'.format(attr_color[self.live.attr], self.live.name) df_head = pd.DataFrame({'Song Name': [song_name]}) df_head['Difficulty'] = self.live.difficulty df_head['Score'] = int(self.global_status['cum_score']) df_head['Cover Rate'] = '{0:.2f}%'.format(100*(self.simul_result['timing_sec'] <= self.simul_result['judge_end_time']).mean()) df_head['Max Combo'] = self.simul_result['combo'].max() for accr in accuracy_list: df_head[accr] = self.global_status['note_stat'][accr] card = ['<img src="{0}" width={1} />'.format(icon_path(card.card_id, card.idolized), col_width) for card in self.card_list] summary, keys = [], ['base_score', 'score', 'hp', 'judge', 'weak_judge'] for i in range(len(card)): temp = {k:getattr(self.skill_tracker[i], 'cum_'+k) for k in keys} temp['card'] = card[i] summary.append(temp) df = pd.DataFrame(summary, columns=['card']+keys) df = df.append(pd.DataFrame(df.sum()).transpose()) df['base_score'] = df['base_score'].apply(lambda x: '<p>{0}</p>'.format(int(x))) df['score'] = df['score'].apply(lambda x: '<p>{0}</p>'.format(int(x))) df['hp'] = df['hp'].apply(lambda x: '<p>{0}</p>'.format(int(x))) df['judge'] = df['judge'].apply(lambda x: '<p>{0}</p>'.format(round(x,1))) df['weak_judge'] = df['weak_judge'].apply(lambda x: '<p>{0}</p>'.format(round(x,1))) df.index = ['<p>{0}</p>'.format(x) for x in ['L1', 'L2', 'L3', 'L4', 'C', 'R4', 'R3', 'R2', 'R1', 'Total']] df.loc['<p>Total</p>', 'card'] = '' html_code = df_head.to_html(escape=False, index=False) + df.transpose().to_html(escape=False) return HTML(html_code)
def show_live_list(group=None, attr=None, diff_level=None): def match_func(x): res = True if group is not None: res &= x.group==group if attr is not None: res &= x.attr==attr if diff_level is not None: res &= x.diff_level==diff_level return res df = live_basic_data[live_basic_data.apply(lambda x: match_func(x), axis=1)].copy() df['cover'] = df['cover'].apply(lambda x: '<img src="{0}" width=100 />'.format(x)) df['name'] = df.apply(lambda x: '<p style="color:{0};">{1}</p>'.format(global_var.attr_color[x['attr']], x['name']), axis=1) df = df[['cover', 'name', 'diff_level', 'note_number', 'diff_star']] df.columns = ['<p>{0}</p>'.format(x) for x in df.columns] return HTML(df.to_html(escape=False, index=False))
def show_markup(text, spans, index=False): from IPython.display import HTML, display html = ''.join(format_markup(text, spans, index=index)) display(HTML(html))
def display(self, columns=[], msg=None): data = self.data if len(self.data) <= 100 else self.data[:49] + [['...'] * (len(self.data[0]))] + self.data[-49:] table_str = HTMLTable([columns] + data, self.id_)._repr_html_(n_rows=100, length=len(self.data)) table_str = table_str.replace('<table', '<table class="table-striped table-hover table-bordered"').replace("'", "\\'").replace('\n','') display( HTML( """ <script type="text/Javascript"> $('#dbinfo{id}').append('{msg}'); $('#table{id}').append('{table}'); </script> """.format(msg=str(msg), table=table_str, id=self.id_) ) )
def print_html(html): display(HTML(html))
def notebook_to_nbviewer(): js = _js_callback_open + _js html = '<script type="text/javascript">' html += js html += '</script>' html += '<b>nbviewer will open in a new tab in 20 seconds .....</b>' return display(HTML(html))
def get_sys_info(): """Display info on system and output as nice HTML""" spacer = "<tr><td> </td><td> </td></tr>" html = '<h3>System Information for {}</h3>'.format(platform.node()) html += '<table>' html += '<tr><td align="left">Python Executable</td>' html += '<td>{}</td></tr>'.format(sys.executable) html += '<tr><td>Kernel PID</td><td>{}</td></tr>'.format( psutil.Process().pid) mem = psutil.virtual_memory() html += '<tr><td>Total System Memory</td>' html += '<td>{:.4} Mb</td></td>'.format(mem.total/1024**3) html += '<tr><td>Total Memory Used</td>' html += '<td>{:.4} Mb</td></td>'.format(mem.used/1024**3) html += '<tr><td>Total Memory Free</td>' html += '<td>{:.4} Mb</td></td>'.format(mem.free/1024**3) html += '<tr><td>Number of CPU Cores</td><td>{}</td></tr>'.format( psutil.cpu_count()) html += '<tr><td>Current CPU Load</td><td>{} %</td></tr>'.format( psutil.cpu_percent(1, False)) html += '</table>' return HTML(html)
def show_kernels(): """Show all IPython Kernels on System""" total_mem = psutil.virtual_memory().total html = ('<h3>IPython Notebook Processes on {}</h3>' '<table><tr>' '<th>Username</th><th>PID</th><th>CPU Usage</th>' '<th>Process Memory</th><th>System Memory Used</th><th>Status</th>' '</tr>').format(platform.node()) for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'username', 'cmdline', 'memory_info', 'status']) except psutil.NoSuchProcess: pass else: if any(x in pinfo['cmdline'] for x in ['IPython.kernel', 'ipykernel_launcher']): html += '<tr>' html += '<td>{username}</td><td>{pid}</td>'.format(**pinfo) p = psutil.Process(pinfo['pid']).cpu_percent(0.1) html += '<td>{}%</td>'.format(p) html += '<td>{:.4} Mb</td>'.format(pinfo['memory_info'].vms / 1024**3) html += '<td>{:.3}%</td>'.format(100 *pinfo['memory_info'].vms / total_mem) html += '<td>{}</td>'.format(pinfo['status']) html += '</tr>' html += '</table>' return HTML(html)
def async_run(self, line, cell=None): """Run code into cell asynchronously Usage:\\ %async_run <source> (cell content) """ if cell is None: code_to_run = line else: code_to_run = cell session_id = str(uuid4()) connection_id = format_ws_connection_id(PY_ROLE, session_id) try: _ = urlopen(connection_string(web_socket=False, extra='ping')) except URLError: print("Connection to server refused!", end=' ') print("Use %async_run_server first!") else: connector = WSConnector(connection_id, code_to_run, self.shell) connector.connect() html_output = LIGHT_HTML_OUTPUT_CELL.format(session_id=session_id) js_code = JS_WEBSOCKET_CODE.replace('__sessionid__', session_id) js_code = js_code.replace('__connection_id__', format_ws_connection_id(JS_ROLE, session_id)) html_output += js_code return HTML(html_output)
def show(self): """Show the viewer. """ viewer_url = self.get_server_url() + '/neuroglancer' + '#!' + self.get_encoded_state() large_html = "<style>.container { width:100% !important; }</style>" if self.large else "" return HTML(large_html + "<iframe src=\"" + viewer_url + "\" width=\"100%\" height=\"1024px\"><\iframe>")
def enable_mpl_offline(resize=False, strip_style=False, verbose=False, show_link=True, link_text='Export to plot.ly', validate=True): """ Convert mpl plots to locally hosted HTML documents. This function should be used with the inline matplotlib backend that ships with IPython that can be enabled with `%pylab inline` or `%matplotlib inline`. This works by adding an HTML formatter for Figure objects; the existing SVG/PNG formatters will remain enabled. (idea taken from `mpld3._display.enable_notebook`) Example:
from plotly.offline import enable_mpl_offline import matplotlib.pyplot as plt enable_mpl_offline() fig = plt.figure() x = [10, 15, 20, 25, 30] y = [100, 250, 200, 150, 300] plt.plot(x, y, "o") fig ``` """ init_notebook_mode() ip = IPython.core.getipython.get_ipython() formatter = ip.display_formatter.formatters['text/html'] formatter.for_type(matplotlib.figure.Figure, lambda fig: iplot_mpl(fig, resize, strip_style, verbose, show_link, link_text, validate))
```
def show_training(self, div_id, div_costs_curve, cost_values) : #div_id = self.show(*args, **kwargs) def change_frame(w) : #print(w) updates = self.get_frame(w-1) script = '' for i in range(len(updates[0])) : jupdate = json.dumps(updates[0][i], cls=utils.PlotlyJSONEncoder) jupdate_cost = json.dumps(dict(x = [[w]], y = [[cost_values[w-1]]]), cls=utils.PlotlyJSONEncoder) script = script \ + 'Plotly.restyle("{id}", {update}, [{index}]);'.format( id=div_id, update=jupdate, index = updates[1][i]) \ + 'Plotly.restyle("{id}", {update}, [{index}]);'.format( id=div_costs_curve, update=jupdate_cost, index = 1) update_str = ( '<script type="text/javascript">' + 'window.PLOTLYENV=window.PLOTLYENV || {{}};' + 'window.PLOTLYENV.BASE_URL="' + 'https://plot.ly' + '";' + '{script}' + '</script>').format(script=script) #print(script) display(HTML(update_str)) #print(self.frames) maxframe = len(self.frames) - 1 play = Play(value=maxframe) slider = IntSlider(min=1, max=maxframe, step=1, value=maxframe,continuous_update=False) slider.layout.width = '100%' #jslink((play, 'value'), (slider, 'value')) traitlets.link((play, 'value'), (slider, 'value')) hb = HBox([play, slider]) slider.observe((lambda iteration : change_frame(iteration['new'])), names='value') change_frame(maxframe) #play.observe((lambda iteration : print(iteration['new'])), names='value') #display(hb) return hb
def my_iplot(figure_or_data, show_link=False, link_text='Export to plot.ly', validate=True, image=None, filename='plot_image', image_width=800, image_height=600) : plot_html, plotdivid, width, height = _plot_html( figure_or_data, show_link, link_text, validate, '100%', 525, global_requirejs=True) #display(HTML(plot_html)) wid = widgets.HTML( value=plot_html, placeholder='Some HTML', description='Some HTML', disabled=False ) return (wid, plotdivid)
def wrap_animation(anim): if not is_html_setup: setup_html() return HTML(anim.to_html5_video())
def show_image(image_path): display(Image(image_path)) image_rel = image_path.replace(root,'') caption = "Image " + ' - '.join(attributions[image_rel].split(' - ')[:-1]) display(HTML("<div>%s</div>" % caption))
def show_article(self, article, nwork, info): """Display article""" citations = "" text = "# Temp\n" text += "insert('''" if nwork is None: text += info_to_code(info) + "\n" if self.citation_var: text += citation_text( self.citation_var, info, ref=article.get('citation_id', ''), backward=self.backward ) + "\n" citations = ", citations='{}'".format(self.citation_file) text += "'''{});".format(citations) if nwork: for key, value in info.items(): if key in {'pyref', 'place1', '_work_type'}: continue if not hasattr(nwork, key): text += "\nset_attribute('{}', '{}', '{}');".format( info['pyref'], key, value ) display_cell(text) self.output_widget.clear_output() with self.output_widget: if self.to_display: display("\n".join(self.to_display)) if 'div' in article: display(HTML(repr(article['div']))) elif 'name' in article: print(article['name']) display(HTML("<input value='{}.pdf' style='width: 100%'></input>".format(info['pyref']))) if not 'place' in info: display(HTML("<input value='{}' style='width: 100%'></input>".format(info['place1']))) self.to_display = []
def show(self, b=None, clear=True): """Generic display""" _up = self.update_info reload() self.next_article_widget.disabled = self.selector_widget.value == self.selector_widget.max self.previous_article_widget.disabled = self.selector_widget.value == 0 if clear: self.clear() if self.disable_show or not self.articles: return article, _, _ = self.articles[self.selector_widget.value] with self.output_widget: if 'div' in article: display(HTML(repr(article['div']))) else: print(article['name']) for article, nwork, info in self.valid_articles([article], show=True): if info.get("_work_type") == "Site": self.show_site(article, nwork, info) continue if info.get("place", "") == "Lang": self.work_type_widget.value = "WorkLang" _up(info, 'due', self.due_widget) _up(info, 'place', self.place_widget) _up(info, "_work_type", self.work_type_widget, default="Work") if _up(info, 'year', self.year_widget) or _up(info, 'display', self.prefix_widget): set_pyref(info) _up(info, 'file', self.file_field_widget, info["pyref"] + ".pdf", default=False) _up(info, 'file', self.pdfpage_widget, info.get("file", "") + "#page={}".format(self.pdfpage_widget.value)) for widget in self.custom_widgets: _up(info, widget._workattr, widget) self.show_article(article, nwork, info)
def notify(self): return display(HTML(self.template.format(self.message)))
def notify(self): display(Audio(self.audio, autoplay=True)) time.sleep(3) display(HTML(self.template.format(self.message)))
def print_frames(dataframes): if not isinstance(dataframes, tuple): return dataframes border_style = u'\"border: none\"' cells = [u'<td style={}> {} </td>'.format(border_style, df._repr_html_()) for df in dataframes] table = '''<table style={}> <tr style={}>'''.format(border_style, border_style) +\ '\n'.join(cells)+\ ''' </tr> </table>''' return HTML(table)
def publish_to_baas(self, url, study_name=None, username=None): """ Publishes a tree on a Boris as a Service instance. :param url: url to a instance (e.g. http://transmart-arborist.thehyve.nl/). :param study_name: a nice name. :param username: if no username is given, you will be prompted for one. :return: the url that points to the study you've just uploaded. """ study_name = study_name or self.study_name or input('Enter study name:') json_data = self.concept_tree.jstree.json_data_string new_url = arborist.publish_to_baas(url, json_data, study_name, username) return HTML('<a target="_blank" href="{l}">{l}</a>'.format(l=new_url))
def display_styler_as_html(styler): display(HTML(styler.render()))
def tableau(quadkeys, solution = None): retVal = "<table>" for row in grouper(quadkeys, 3): html_row = "<tr>" for quadkey in row: html_row += "<td align=\"center\" style=\"text-align: center\">" if quadkey is not None: html_row += cell_renderer(quadkey, solution) html_row += "</td>" html_row += "</tr>" retVal += html_row retVal += "</table>" display(HTML(retVal))
def __init__(self, **kwargs): super(D3Magics, self).__init__(**kwargs) self.max_id = 0 # Used to ensure that the current group selection is unique. # self.initialized = True # Used to ensure that d3.js is only imported once. # # The necessary substitutions to get a block working are theoretically possible, but too quirky for the moment # to consider. # @line_magic # def block(self, line): # user, gist_id = line.split("/")[-2:] # r = requests.get("https://gist.github.com/{0}/{1}/download".format(user, gist_id)) # with zipfile.ZipFile(io.BytesIO(r.content)) as ar: # ar.extractall(".blocks/{0}/".format(user, gist_id)) # # This creates e.g. ".blocks/mbostock/3885304-master" in the root directory. # # The appended "-master" is due to the format of the zipped file. # # It's a little unideal, but unsure about whether or not removing it would cause any issues I've kept it # # for the time being (you could easily rename the folder). # with open(".blocks/{0}/{1}-master/index.html".format(user, gist_id), "r") as f: # source = f.read() # # We need to perform a few substutions to make the figure work within a Jupyter Notebook file. # # 1. <body> tags are not allowed within a D3 notebook (one has already been defined and HTML documents only # # allow one <body> and one <head>), but are probably the most common initial selector of all for defining # # the initial D3 frame. To fix: # # >>> <body> --> <g> # # >>> d3.select("body") --> d3.select("g") # # >>> <body id="foo"> --> ??? # # >>> <body class="foo"> --> ??? # source = source.replace('<body', '<g') # source = source.replace("select('body", "select(g") # source = source.replace('d3.tsv("', 'd3.tsv("./.blocks/{0}/{1}-master/'.format(user, gist_id)) # print(HTML(source).data) # display(HTML(source))
def d3(self, line, cell): src = line if len(line) > 0 else "3.5.17" s = """ <script> requirejs.config({ paths: { d3: "//cdnjs.cloudflare.com/ajax/libs/d3/""" + src + """/d3" } }); require(['d3'], function(d3) { window.d3 = d3; }); </script> <script> _select = d3.select; d3.select""" + str(self.max_id) + """ = function(selection) { return _select("#d3-cell-""" + str(self.max_id) + """").select(selection); } d3.selectAll""" + str(self.max_id) + """ = function(selection) { return _select("#d3-cell-""" + str(self.max_id) + """").selectAll(selection); } </script> <g id="d3-cell-""" + str(self.max_id) + """"> """ cell = re.sub('d3.select\((?!this)', "d3.select" + str(self.max_id) + "(", cell) cell = re.sub('d3.selectAll\((?!this)', "d3.selectAll" + str(self.max_id) + "(", cell) s += cell + "\n</g>" # print(s) # Useful for debugging. h = HTML(s) self.max_id += 1 display(h)
def drawFragmentsbyTopic(topicModel, topicIdx, n_top_frags=10, numRowsShown=4, cssTableName='fragTab', \ prior=-1.0, numColumns=4, tableHeader=''): scores = topicModel.getTopicFragmentProbabilities() numTopics, numFragments = scores.shape if prior < 0: prior = 1./numFragments svgs=generateTopicRelatedFragmentSVGs(topicModel, topicIdx, n_top_frags=n_top_frags, prior=prior) namesSVGs = list(map(lambda x: "Score %.2f" % x, \ filter(lambda y: y > prior, sorted(scores[topicIdx,:], reverse=True)[:n_top_frags]))) if tableHeader == '': tableHeader = "Topic "+str(topicIdx) return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(svgs,tableHeader=tableHeader,cssTableName=cssTableName,\ namesSVGs=namesSVGs,size=(120,100),numRowsShown=numRowsShown,\ numColumns=numColumns)))
def play_video(path): video = io.open(path, 'r+b').read() encoded = base64.b64encode(video) return HTML(data='''<video alt="test" controls> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))
def animation2HTML(anim, frame_rate): print("animaiton to video...") if not hasattr(anim, '_encoded_video'): with NamedTemporaryFile(suffix='.mp4') as f: anim.save(f.name, fps=frame_rate, extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '28', '-preset', 'veryfast']) video = io.open(f.name, 'r+b').read() encoded = base64.b64encode(video) return HTML(data='''<video alt="test" controls> <source src="data:video/mp4;base64,{0}" type="video/mp4" /> </video>'''.format(encoded.decode('ascii')))
def image_stack_to_movie(images, frames=None, vmin=None, vmax=None, figsize=(6, 5), cmap='CMRmap', fps=10): """Convert image stack to movie and show in notebook. Parameters ---------- images : array_like Stack of images to show as a movie of shape (N, y, x). frames : int Number of frames to process vmin : number Minimum value to display for ``imshow`` vmax : number Maximum value to display for ``imshow`` figsize : tuple Figure size for each frame cmap : string Colormap to use for plotting image fps : int Framerate for created movie """ if frames is None: frames = images.shape[0] fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) im = plt.imshow(images[1], vmin=vmin, vmax=vmax, cmap=cmap, interpolation='none') cbar = fig.colorbar(im) cbar.ax.tick_params(labelsize=14) cbar.set_label(r"Intensity [ADU]", size=14,) for item in ([ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(14) item.set_fontweight('bold') def animate(i): im.set_array(images[i]) ax.set_title('Frame {}'.format(i), fontsize=16, fontweight='bold') return im, anim = animation.FuncAnimation(fig, animate, frames=frames, interval=1, blit=True) plt.close(anim._fig) # return anim.to_html5_video() return HTML(_anim_to_html(anim, fps))
def plot_state(self, **options): """Plot the GP surface. This feature is still experimental and currently supports only 2D cases. """ f = plt.gcf() if len(f.axes) < 2: f, _ = plt.subplots(1, 2, figsize=(13, 6), sharex='row', sharey='row') gp = self.target_model # Draw the GP surface visin.draw_contour( gp.predict_mean, gp.bounds, self.parameter_names, title='GP target surface', points=gp.X, axes=f.axes[0], **options) # Draw the latest acquisitions if options.get('interactive'): point = gp.X[-1, :] if len(gp.X) > 1: f.axes[1].scatter(*point, color='red') displays = [gp._gp] if options.get('interactive'): from IPython import display displays.insert( 0, display.HTML('<span><b>Iteration {}:</b> Acquired {} at {}</span>'.format( len(gp.Y), gp.Y[-1][0], point))) # Update visin._update_interactive(displays, options) def acq(x): return self.acquisition_method.evaluate(x, len(gp.X)) # Draw the acquisition surface visin.draw_contour( acq, gp.bounds, self.parameter_names, title='Acquisition surface', points=None, axes=f.axes[1], **options) if options.get('close'): plt.close()
def _plot_in_notebook(profiler): """Generate interactive (notebook) visualization of the current profile statistics in `profiler`.""" from .pstats import Stats import snakeviz import snakeviz.stats stats = Stats(profiler) table_rows=snakeviz.stats.table_rows(stats) callees=snakeviz.stats.json_stats(stats) base = join(dirname(__file__), 'snakeviz') template = join(base, 'template.jinja') resources={} resources['style_css'] = join(base, 'style.css') base = join(dirname(snakeviz.__file__), 'static') resources['snakeviz_js'] = join(base, 'snakeviz.js') resources['drawsvg_js'] = join(base, 'drawsvg.js') resources['datatables_css'] = join(base, 'vendor/jquery.dataTables.min.css') resources['jquery_min_js'] = join(base, 'vendor/jquery-1.11.1.min.js') resources['d3_min_js'] = join(base, 'vendor/d3.min.js') resources['jquery_dt_js'] = join(base, 'vendor/jquery.dataTables.min.js') resources['lodash_js'] = join(base, 'vendor/lodash.compat.min.js') resources['immutable_js'] = join(base, 'vendor/immutable.min.js') for r in resources: with open(resources[r], 'r', encoding='utf-8') as f: resources[r] = f.read() with open(template, 'r', encoding='utf-8') as f: template = Template(f.read()) html = template.render(table_rows=table_rows, callees=callees, **resources) # We can't embed the snakeviz html because its js isn't (yet) compatible # with the notebook's use of RequireJS, so we fall back to using an iframe # until that's fixed. with open("snakeviz.html", 'w', encoding='utf-8') as f: f.write(html) return HTML(data="""<div class="resizable" style="height:500px;"> <iframe src="./snakeviz.html" width="100%" height="100%"/> </div> <script type="text/javascript"> $(function() { $('.resizable').resizable({ handles: 'n,s', start: function(event, ui) { $('iframe').css('pointer-events','none'); }, stop: function(event, ui) { $('iframe').css('pointer-events','auto'); } }); }); </script> """)