def hide_code() : import IPython.core.display as di # This line will hide code by default # when the notebook is exported as HTML di.display_html(''' <script>jQuery( function() { if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle(); } }); </script> ''', raw=True) # This will add a button to toggle visibility of code blocks, # for use with the HTML export version di.display_html(''' <button onclick=" jQuery('.input_area').toggle(); jQuery('.prompt').toggle(); ">Toggle code</button> ''', raw=True)
def hidecode(showbutton=False): if (showbutton == True): javascript_functions = {False: "hide()", True: "show()"} button_descriptions = {False: "Show code", True: "Hide code"} def toggle_code(state): output_string = "<script>$(\"div.input\").{}</script>" output_args = (javascript_functions[state], ) output = output_string.format(*output_args) display(HTML(output)) def button_action(value): state = value.new toggle_code(state) value.owner.description = button_descriptions[state] state = False toggle_code(state) button = widgets.ToggleButton(state, description=button_descriptions[state]) button.observe(button_action, "value") display(button) else: di.display_html( '<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True) CSS = """#notebook div.output_subarea {max-width:100%;}""" # changes output_subarea width to 100% (from 100% - 14ex) HTML('<style>{}</style>'.format(CSS))
def problog(self, line, cell=None): """problog line/cell magic""" args = parse_argstring(self.problog, line) if args.knowledge == 'nnf': knowledge = DDNNF elif args.knowledge == 'sdd': knowledge = SDD elif args.knowledge is None: if SDD.is_available(): knowledge = SDD else: knowledge = DDNNF else: error("Unknown option for --knowledge: '%s'" % args.knowledge) if args.logspace: semiring = SemiringLogProbability() else: semiring = None s = cell data = runproblog(s, knowledge=knowledge, semiring=semiring, output='html') if data: display_html(data, raw=True)
def display(table, limit=0, vrepr=None, index_header=None, caption=None, tr_style=None, td_styles=None, encoding=None, truncate=None): """ Display a table inline within an IPython notebook. """ from IPython.core.display import display_html html = _display_html(table, limit=limit, vrepr=vrepr, index_header=index_header, caption=caption, tr_style=tr_style, td_styles=td_styles, encoding=encoding, truncate=truncate) display_html(html, raw=True)
def textdiff(self, line): """ .. nbref:: :title: %textdiff :tag: nb It displays differences between two text files, two strings, two urls, it is based on :func:`create_visual_diff_through_html_files <pyquickhelper.filehelper.visual_sync.create_visual_diff_through_html_files>`. Check blog post :ref:`Visualize differences between two files in a notebook <b-diffview>` to see an example. See also `A magic command to visualize differences between two files in a notebook <http://www.xavierdupre.fr/app/pyensae/helpsphinx/blog/2015/2015-04-23_textdiff.html>`_. The magic command is equivalent to:: from IPython.core.display import display_html, display_javascript from pyquickhelper import docstring2html, create_visual_diff_through_html_files html, js = create_visual_diff_through_html_files(<f1>, <f2>, encoding=<encoding>, notebook=True, context_size=None if <context> in [None, ""] else int(<context>), inline_view=<inline>) display_html(html) display_javascript(js) """ parser = self.get_parser(MagicDiff.textdiff_parser, "textdiff") args = self.get_args(line, parser) if args is not None: html, js = create_visual_diff_through_html_files(args.f1, args.f2, encoding=args.encoding, notebook=True, context_size=None if args.context in [ None, ""] else int(args.context), inline_view=args.inline) display_html(html) return js
def HTML(string): try: from IPython.core.display import publish_html publish_html(string) except ImportError: from IPython.core.display import display_html display_html(string,raw=True)
def display(tbl, limit=None, **kwargs): """ Display a table inline within an iPython notebook. E.g.:: In [0]: from petlx.ipython import display tbl = [['foo', 'bar'], ['a', 1], ['b', 2]] display(tbl) Alternatively, using the fluent style:: In [0]: import petl.interactive as etl import petlx.ipython tbl = etl.wrap([['foo', 'bar'], ['a', 1], ['b', 2]]) tbl.display() .. versionadded:: 0.5 """ try: from IPython.core.display import display_html except ImportError as e: raise UnsatisfiedDependency(e, dep_message) else: html = repr_html(tbl, limit=limit, **kwargs) display_html(html, raw=True)
def print_param(self, mps, merr=None, float_format='%5.3e', smart_latex=True, latex_map=None): """print list of parameters Arguments: *mps* : minuit parameters struct *merr* : minos error *float_format* : control the format of latex floating point output default '%5.3e' *smart_latex* : convert greek symbols and underscores to latex symbol. default True """ to_print = "" uid = randid() header = """ <table> <tr> <td><a href="#" onclick="$('#{uid}').toggle()">+</a></td> <td title="Variable name">Name</td> <td title="Value of parameter">Value</td> <td title="Parabolic error">Parab Error</td> <td title="Minos lower error">Minos Error-</td> <td title="Minos upper error">Minos Error+</td> <td title="Lower limit of the parameter">Limit-</td> <td title="Upper limit of the parameter">Limit+</td> <td title="Is the parameter fixed in the fit">FIXED</td> </tr> """.format(**locals()) to_print += header for i, mp in enumerate(mps): minos_p, minos_m = (0., 0.) if merr is None or mp.name not in merr else\ (merr[mp.name].upper, merr[mp.name].lower) limit_p = '' if not mp.has_upper_limit else mp.upper_limit limit_m = '' if not mp.has_lower_limit else mp.lower_limit fixed = 'FIXED' if mp.is_fixed else '' j = i+1 content = """ <tr> <td>{j}</td> <td>{mp.name}</td> <td>{mp.value:e}</td> <td>{mp.error:e}</td> <td>{minos_m:e}</td> <td>{minos_p:e}</td> <td>{limit_m!s}</td> <td>{limit_p!s}</td> <td>{fixed}</td> </tr> """.format(**locals()) to_print += content to_print += """ </table> """ ltable = LatexFactory.build_param_table(mps, merr, float_format=float_format, smart_latex=smart_latex, latex_map=latex_map) #rows = str(ltable).count('\n')+1 to_print += self.hidden_table(str(ltable), uid) display_html(to_print, raw=True)
def nbsample(draws, step, start=None, trace=None, chain=0, tune=None, model=None, random_seed=None): try: assert(hasattr(IPython.get_ipython(), 'comm_manager')) except (AssertionError, NameError, KeyError) as e: raise NotImplementedError(_no_notebook_error_message) display.display_html(_javascript, raw=True) w = ISampleWidget() display.display(w) t_start = time.time() t_last = time.time() w.max_samples = draws w.current_samples = 0 sampling = _iter_sample(draws, step, start=start, trace=trace, chain=chain, tune=tune, model=model, random_seed=random_seed) for i, trace in enumerate(sampling, 1): elapsed = time.time() - t_start elapsed_last = time.time() - t_last if elapsed_last > 0.1: t_last = time.time() w.current_samples = i w.clock = "%02i:%02i:%02i" % (elapsed / 60 / 60, elapsed / 60 % 60, elapsed % 60) get_ipython().kernel.do_one_iteration() if w.stopped: trace.close() break w.current_samples = i return MultiTrace([trace])
def print_merror(self, vname, smerr): stat = 'VALID' if smerr.is_valid else 'PROBLEM' style = minos_style(smerr) to_print = """ <span>Minos status for {vname}: <span style="{style.is_valid}">{stat}</span></span> <table> <tr> <td title="lower and upper minos error of the parameter">Error</td> <td>{smerr.lower}</td> <td>{smerr.upper}</td> </tr> <tr> <td title="Validity of minos error">Valid</td> <td style="{style.lower_valid}">{smerr.lower_valid}</td> <td style="{style.upper_valid}">{smerr.upper_valid}</td> </tr> <tr> <td title="Did minos error search hit limit of any paramter?">At Limit</td> <td style="{style.at_lower_limit}">{smerr.at_lower_limit}</td> <td style="{style.at_upper_limit}">{smerr.at_upper_limit}</td> </tr> <tr> <td title="I don't really know what this one means... Post it in issue if you know">Max FCN</td> <td style="{style.at_lower_max_fcn}">{smerr.at_lower_max_fcn}</td> <td style="{style.at_upper_max_fcn}">{smerr.at_upper_max_fcn}</td> </tr> <tr> <td title="New minimum found when doing minos scan.">New Min</td> <td style="{style.lower_new_min}">{smerr.lower_new_min}</td> <td style="{style.upper_new_min}">{smerr.upper_new_min}</td> </tr> </table> """.format(**locals()) display_html(to_print, raw=True)
def hide_code(): import IPython.core.display as di # This line will hide code by default # when the notebook is exported as HTML di.display_html(''' <script>jQuery( function() { if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle(); } }); </script> ''', raw=True) # This will add a button to toggle visibility of code blocks, # for use with the HTML export version di.display_html(''' <button onclick=" jQuery('.input_area').toggle(); jQuery('.prompt').toggle(); ">Toggle code</button> ''', raw=True)
def print_merror(self, vname, smerr): stat = 'VALID' if smerr.is_valid else 'PROBLEM' style = minos_style(smerr) to_print = """ <span>Minos status for {vname}: <span style="{style.is_valid}">{stat}</span></span> <table> <tr> <td>Error</td> <td>{smerr.lower}</td> <td>{smerr.upper}</td> </tr> <tr> <td>Valid</td> <td style="{style.lower_valid}">{smerr.lower_valid}</td> <td style="{style.upper_valid}">{smerr.upper_valid}</td> </tr> <tr> <td>At Limit</td> <td style="{style.at_lower_limit}">{smerr.at_lower_limit}</td> <td style="{style.at_upper_limit}">{smerr.at_upper_limit}</td> </tr> <tr> <td>Max FCN</td> <td style="{style.at_lower_max_fcn}">{smerr.at_lower_max_fcn}</td> <td style="{style.at_upper_max_fcn}">{smerr.at_upper_max_fcn}</td> </tr> <tr> <td>New Min</td> <td style="{style.lower_new_min}">{smerr.lower_new_min}</td> <td style="{style.upper_new_min}">{smerr.upper_new_min}</td> </tr> </table> """.format(**locals()) display_html(to_print, raw=True)
def nbsample(draws, step, start=None, trace=None, chain=0, tune=None, model=None, random_seed=None): try: assert(hasattr(IPython.get_ipython(), 'comm_manager')) except (AssertionError, NameError, KeyError) as e: raise NotImplementedError(_no_notebook_error_message) display.display_html(_javascript, raw=True) w = ISampleWidget() display.display(w) t_start = time.time() t_last = time.time() w.max_samples = draws w.current_samples = 0 for i,backend in enumerate(iter_sample(draws, step, start=start, trace=trace, chain=chain, tune=tune, model=model, random_seed=None), 1): elapsed = time.time() - t_start elapsed_last = time.time() - t_last if elapsed_last > 0.1: t_last = time.time() w.current_samples = i w.clock = "%02i:%02i:%02i" % (elapsed / 60 / 60, elapsed / 60 % 60, elapsed % 60) get_ipython().kernel.do_one_iteration() if w.stopped: break w.current_samples = i return backend
def print_matrix(self, vnames, matrix, varno=None): to_print = """ <table> <tr> <td></td> """ for v in vnames: to_print += """ <td> <span style="-webkit-writing-mode:vertical-rl;-moz-writing-mode: vertical-rl;writing-mode: vertical-rl;"> {v} </span> </td> """.format(**locals()) to_print += """ </tr> """ for i, v1 in enumerate(vnames): to_print += """ <tr> <td>{v1}</td> """.format(**locals()) for j, v2 in enumerate(vnames): val = matrix[i][j] color = Gradient.rgb_color_for(val) to_print += """ <td style="background-color:{color}"> {val:3.2f} </td> """.format(**locals()) to_print += """ </tr> """ to_print += '</table>' display_html(to_print, raw=True)
def toHTML(divId,zoom,type,baseMapType,redraw=False): # HTML html = "" if not redraw: html ="<div id='" + divId html += """' style="width: 1000px; height: 400px"></div>""" html += """ <link rel="stylesheet" href="tools/leaflet.css"> <link rel="stylesheet" href="tools/map.css"> <script src="tools/d3.min.js" type="text/javascript"></script> <script src="tools/leaflet.js" type="text/javascript"></script> <script src="tools/leaflet-heat.js" type="text/javascript"></script> <script src="tools/jquery-3.1.1.js" type="text/javascript"></script> <script src="tools/L.D3SvgOverlay.js" type="text/javascript"></script> <script src="jsonData/""" +divId + """.json" type="text/javascript"></script> <script src="tools/wkx.js" type="text/javascript"></script> <script src="tools/underscore.js" type="text/javascript"></script> <script src="tools/baseMap.js" type="text/javascript"></script> <script src="tools/geoMap.js" type="text/javascript"></script> <script src="tools/choroplethMap.js" type="text/javascript"></script> <script src="tools/heatMap.js" type="text/javascript"></script> <script type="text/javascript"> """ if type=='': html += "(new GeoMap('" + divId + "' ," + str(zoom) +","+str(baseMapType)+")).display();</script>"; elif type=='heatMap': html += "(new HeatMap('" + divId + "' ," + str(zoom) +","+str(baseMapType)+")).display();</script>"; elif type=='choroplethMap': html += "(new ChoroplethMap('" + divId + "' ," + str(zoom) +","+str(baseMapType)+")).display();</script>"; html = html.format('') # Display in Jupyter Notebook display_html(HTML(data=html))
def print_merror(vname, smerr): stat = 'VALID' if smerr.is_valid else 'PROBLEM' style = minos_style(smerr) to_print = """ <span>Minos status for {vname}: <span style="{style.is_valid}">{stat}</span></span> <table> <tr> <td title="lower and upper minos error of the parameter">Error</td> <td>{smerr.lower}</td> <td>{smerr.upper}</td> </tr> <tr> <td title="Validity of minos error">Valid</td> <td style="{style.lower_valid}">{smerr.lower_valid}</td> <td style="{style.upper_valid}">{smerr.upper_valid}</td> </tr> <tr> <td title="Did minos error search hit limit of any paramter?">At Limit</td> <td style="{style.at_lower_limit}">{smerr.at_lower_limit}</td> <td style="{style.at_upper_limit}">{smerr.at_upper_limit}</td> </tr> <tr> <td title="I don't really know what this one means... Post it in issue if you know">Max FCN</td> <td style="{style.at_lower_max_fcn}">{smerr.at_lower_max_fcn}</td> <td style="{style.at_upper_max_fcn}">{smerr.at_upper_max_fcn}</td> </tr> <tr> <td title="New minimum found when doing minos scan.">New Min</td> <td style="{style.lower_new_min}">{smerr.lower_new_min}</td> <td style="{style.upper_new_min}">{smerr.upper_new_min}</td> </tr> </table> """.format(**locals()) display_html(to_print, raw=True)
def print_param(self, mps, merr=None, float_format='%5.3e', smart_latex=True, latex_map=None): """print list of parameters Arguments: *mps* : minuit parameters struct *merr* : minos error *float_format* : control the format of latex floating point output default '%5.3e' *smart_latex* : convert greek symbols and underscores to latex symbol. default True """ to_print = "" uid = randid() header = """ <table> <tr> <td><a href="#" onclick="$('#{uid}').toggle()">+</a></td> <td title="Variable name">Name</td> <td title="Value of parameter">Value</td> <td title="Parabolic error">Parab Error</td> <td title="Minos lower error">Minos Error-</td> <td title="Minos upper error">Minos Error+</td> <td title="Lower limit of the parameter">Limit-</td> <td title="Upper limit of the parameter">Limit+</td> <td title="Is the parameter fixed in the fit">FIXED</td> </tr> """.format(**locals()) to_print += header for i, mp in enumerate(mps): minos_p, minos_m = (0., 0.) if merr is None or mp.name not in merr else \ (merr[mp.name].upper, merr[mp.name].lower) limit_p = '' if not mp.has_upper_limit else mp.upper_limit limit_m = '' if not mp.has_lower_limit else mp.lower_limit fixed = 'FIXED' if mp.is_fixed else '' j = i + 1 content = """ <tr> <td>{j}</td> <td>{mp.name}</td> <td>{mp.value:e}</td> <td>{mp.error:e}</td> <td>{minos_m:e}</td> <td>{minos_p:e}</td> <td>{limit_m!s}</td> <td>{limit_p!s}</td> <td>{fixed}</td> </tr> """.format(**locals()) to_print += content to_print += """ </table> """ ltable = LatexFactory.build_param_table(mps, merr, float_format=float_format, smart_latex=smart_latex, latex_map=latex_map) # rows = str(ltable).count('\n')+1 to_print += self.hidden_table(str(ltable), uid) display_html(to_print, raw=True)
def _display_ogg( self, midi_bank, midi_file_path, ogg_file_path, sound_font, ): from abjad.tools import systemtools fluidsynth_command = ( 'fluidsynth', '-T oga', '-nli', '-r 44100', '-o synth.midi-bank-select={}'.format(midi_bank), '-F', ogg_file_path, sound_font, midi_file_path, ) fluidsynth_command = ' '.join(fluidsynth_command) print(fluidsynth_command) result = systemtools.IOManager.spawn_subprocess(fluidsynth_command) if result == 0: encoded_audio = self._get_base64_from_file(ogg_file_path) audio_tag = '<audio controls type="audio/ogg" ' audio_tag += 'src="data:audio/ogg;base64,{}">' audio_tag = audio_tag.format(encoded_audio) display_html(audio_tag, raw=True) return True message = 'fluidsynth failed to render MIDI as OGG, result: {}' message = message.format(result) print(message) return False
def init_django_forms(): """ Initializes the django environment if necessary and renders the javascript and css code.""" try: settings.configure() except RuntimeError: pass display.display_html(widget_css, raw=True) display.display_html(widget_javascript, raw=True)
def print_fmin(self, sfmin, tolerance=None, ncalls=0): """Display FunctionMinum in html representation. .. note: Would appreciate if someone would make jquery hover description for each item.""" goaledm = 0.0001 * tolerance * sfmin.up style = fmin_style(sfmin) header = u""" <table> <tr> <td>FCN = {sfmin.fval}</td> <td>NFCN = {sfmin.nfcn}</td> <td>NCALLS = {ncalls}</td> </tr> <tr> <td>EDM = {sfmin.edm}</td> <td>GOAL EDM = {goaledm}</td> <td>UP = {sfmin.up}</td> </tr> </table> """.format( **locals() ) status = u""" <table> <tr> <td align="center">Valid</td> <td align="center">Valid Param</td> <td align="center">Accurate Covar</td> <td align="center">PosDef</td> <td align="center">Made PosDef</td> </tr> <tr> <td align="center" style="{style.is_valid}">{sfmin.is_valid!r}</td> <td align="center" style="{style.has_valid_parameters}">{sfmin.has_valid_parameters!r}</td> <td align="center" style="{style.has_accurate_covar}">{sfmin.has_accurate_covar!r}</td> <td align="center" style="{style.has_posdef_covar}">{sfmin.has_posdef_covar!r}</td> <td align="center" style="{style.has_made_posdef_covar}">{sfmin.has_made_posdef_covar!r}</td> </tr> <tr> <td align="center">Hesse Fail</td> <td align="center">HasCov</td> <td align="center">Above EDM</td> <td align="center"></td> <td align="center">Reach calllim</td> </tr> <tr> <td align="center" style="{style.hesse_failed}">{sfmin.hesse_failed!r}</td> <td align="center" style="{style.has_covariance}">{sfmin.has_covariance!r}</td> <td align="center" style="{style.is_above_max_edm}">{sfmin.is_above_max_edm!r}</td> <td align="center"></td> <td align="center" style="{style.has_reached_call_limit}">{sfmin.has_reached_call_limit!r}</td> </tr> </table> """.format( **locals() ) display_html(header + status, raw=True)
def display(self, speed=1000, from_start=False, reset_io=False, buffer_num=0): """ Display an animation, based on a starting state & the logged diff Once this is called, the starting state & log mark are advanced """ self.log_buffer_data_diffs() # Create a new html pane with unique id chart_id = '%s-%s' % (buffer_num, self._chart_num) html = """ <table> <tr><th><i>IO Counts</i></th><th>R</th><th>W</th></tr> <tr> <td><i>To/from Buffer</i></td> <td id="chart-{0}-bufferReads">0</td> <td id="chart-{0}-bufferWrites">0</td> </tr> <tr> <td><b>To/from Disk</b></td> <td id="chart-{0}-diskReads">0</td> <td id="chart-{0}-diskWrites">0</td> </tr> </table> <br /> <div class="tooltip" id="chart-{0}-tooltip" style="position:absolute; z-index:100; color:white; background:black; opacity:0.7; padding:3px; border-radius:5px; display:none;">TOOLTIP!</div> <div class="tooltip" id="chart-{0}-tooltip-2" style="position:absolute; z-index:100; color:white; background:black; opacity:0.7; padding:3px; border-radius:5px; display:none;">TOOLTIP!</div> <div id="chart-{0}"></div> """.format(chart_id) # Dump log to json file with open('pagesLog.json', 'w') as f: json.dump(self._log, f) # Create animation in js/d3 js_configs = { 'DURATION': speed, 'chartNum': chart_id, 'numBufferPages': self.buffer_size, 'pageSize': self.page_size, 'numDiskPages': 5, 'logStart': self._diff_log_start if not from_start else 0 } js = js_file_with_configs('compModel.js', js_configs) js_libs = [ 'https://d3js.org/d3.v3.min.js', 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js' ] display_html(HTML(data=html)) display_javascript(Javascript(data=js, lib=js_libs)) self._chart_num += 1 # Advance current animation state in log self.display_set_mark(reset_io=reset_io)
def problogobj(self, line): """problog object magic""" obj = self.shell.ev(line) if not isinstance(obj, LogicProgram): error("expected object to be of type LogicProgram") else: data = runproblog(s, output='html') if data: display_html(data, raw=True)
def _display(tbl, sliceargs, **kwargs): try: from IPython.core.display import display_html except ImportError as e: raise UnsatisfiedDependency(e, dep_message) if sliceargs is not None: tbl = rowslice(tbl, *sliceargs) html = repr_html(tbl, **kwargs) display_html(html, raw=True)
def print_fmin(sfmin, tolerance=None, ncalls=0): """Display FunctionMinum in html representation. .. note: Would appreciate if someone would make jquery hover description for each item.""" from IPython.core.display import display_html goaledm = 0.0001 * tolerance * sfmin.up style = fmin_style(sfmin) header = u""" <table> <tr> <td title="Minimum value of function">FCN = {sfmin.fval}</td> <td title="Total number of call to FCN so far">TOTAL NCALL = {ncalls}</td> <td title="Number of call in last migrad">NCALLS = {sfmin.nfcn}</td> </tr> <tr> <td title="Estimated distance to minimum">EDM = {sfmin.edm}</td> <td title="Maximum EDM definition of convergence">GOAL EDM = {goaledm}</td> <td title="Error def. Amount of increase in FCN to be defined as 1 standard deviation"> UP = {sfmin.up}</td> </tr> </table> """.format(**locals()) status = u""" <table> <tr> <td align="center" title="Validity of the migrad call">Valid</td> <td align="center" title="Validity of parameters">Valid Param</td> <td align="center" title="Is Covariance matrix accurate?">Accurate Covar</td> <td align="center" title="Positive definiteness of covariance matrix">PosDef</td> <td align="center" title="Was covariance matrix made posdef by adding diagonal element">Made PosDef</td> </tr> <tr> <td align="center" style="{style.is_valid}">{sfmin.is_valid!r}</td> <td align="center" style="{style.has_valid_parameters}">{sfmin.has_valid_parameters!r}</td> <td align="center" style="{style.has_accurate_covar}">{sfmin.has_accurate_covar!r}</td> <td align="center" style="{style.has_posdef_covar}">{sfmin.has_posdef_covar!r}</td> <td align="center" style="{style.has_made_posdef_covar}">{sfmin.has_made_posdef_covar!r}</td> </tr> <tr> <td align="center" title="Was last hesse call fail?">Hesse Fail</td> <td align="center" title="Validity of covariance">HasCov</td> <td align="center" title="Is EDM above goal EDM?">Above EDM</td> <td align="center"></td> <td align="center" title="Did last migrad call reach max call limit?">Reach calllim</td> </tr> <tr> <td align="center" style="{style.hesse_failed}">{sfmin.hesse_failed!r}</td> <td align="center" style="{style.has_covariance}">{sfmin.has_covariance!r}</td> <td align="center" style="{style.is_above_max_edm}">{sfmin.is_above_max_edm!r}</td> <td align="center"></td> <td align="center" style="{style.has_reached_call_limit}">{sfmin.has_reached_call_limit!r}</td> </tr> </table> """.format(**locals()) display_html(header + status, raw=True)
def display(self, speed=1000, from_start=False, reset_io=False, buffer_num=0): """ Display an animation, based on a starting state & the logged diff Once this is called, the starting state & log mark are advanced """ self.log_buffer_data_diffs() # Create a new html pane with unique id chart_id = "%s-%s" % (buffer_num, self._chart_num) html = """ <table> <tr><th><i>IO Counts</i></th><th>R</th><th>W</th></tr> <tr> <td><i>To/from Buffer</i></td> <td id="chart-{0}-bufferReads">0</td> <td id="chart-{0}-bufferWrites">0</td> </tr> <tr> <td><b>To/from Disk</b></td> <td id="chart-{0}-diskReads">0</td> <td id="chart-{0}-diskWrites">0</td> </tr> </table> <br /> <div class="tooltip" id="chart-{0}-tooltip" style="position:absolute; z-index:100; color:white; background:black; opacity:0.7; padding:3px; border-radius:5px; display:none;">TOOLTIP!</div> <div class="tooltip" id="chart-{0}-tooltip-2" style="position:absolute; z-index:100; color:white; background:black; opacity:0.7; padding:3px; border-radius:5px; display:none;">TOOLTIP!</div> <div id="chart-{0}"></div> """.format( chart_id ) # Dump log to json file with open("pagesLog.json", "wb") as f: json.dump(self._log, f) # Create animation in js/d3 js_configs = { "DURATION": speed, "chartNum": chart_id, "numBufferPages": self.buffer_size, "pageSize": self.page_size, "numDiskPages": 5, "logStart": self._diff_log_start if not from_start else 0, } js = js_file_with_configs("compModel.js", js_configs) js_libs = [ "http://rawgithub.com/mbostock/d3/master/d3.min.js", "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js", ] display_html(HTML(data=html)) display_javascript(Javascript(data=js, lib=js_libs)) self._chart_num += 1 # Advance current animation state in log self.display_set_mark(reset_io=reset_io)
def _display_audio_tag(self, encoded_audio, has_vorbis): from IPython.core.display import display_html if has_vorbis: mime_type = 'audio/ogg' else: mime_type = 'audio/aiff' audio_tag = '<audio controls type="{}" ' audio_tag += 'src="data:{};base64,{}">' audio_tag = audio_tag.format(mime_type, mime_type, encoded_audio) display_html(audio_tag, raw=True)
def hide_code(button=False): display.display_html( '<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(' '".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True) if button: display.display_html( '''<button onclick="jQuery('.input_area').toggle(); jQuery('.prompt').toggle();">Toggle code</button>''', raw=True)
def problogsample(self, line, cell=None): """problog line/cell magic""" args = parse_argstring(self.problogsample, line) n = 5 if args.N is not None: n = int(args.N) s = cell data = runproblogsampling(s, n=n, output='html') if data: display_html(data, raw=True)
def display_side_by_side(*args): html_str = "" for df in args: if isinstance(df, pd.DataFrame): html_str += df.to_html() elif isinstance(df, pd.Series): html_str += df.to_frame().to_html() display_html(html_str.replace("table", 'table style="display:inline"'), raw=True) return None
def display_canvas_point(html_id, width=800, heigth=400, var_name="points"): """ Adds a canvas to draw from a notebook, the code use javascript. @param height height @param width width @param html_id the function adds a div section, it should be different for every canevas @param var_name the function adds this variable to the kernel workspace @return the list of points """ js_libs = local_d3js() # http://jsfiddle.net/yonester/9tr7w/2/ html_src = """ <div id="{0}"></div> """.format(html_id) points = [] test_d3_js = """ var r; var command0 ="__VARNAME__=[]"; var kernel = IPython.notebook.kernel; kernel.execute(command0); var vis = d3.select("#__ID__").append("svg") .attr("width", __WIDTH__) .attr("height", __HEIGHT__) .style('border', '1px solid black') .on("mousedown", mousedown) ; function mousedown() { var m = d3.mouse(this); r = vis.append("rect") .attr("class", "myrect") .attr("style", "fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,255);") .attr("x", m[0]) .attr("y", m[1]) .attr("width", 5) .attr("height", 5); var command = "__VARNAME__.append( (" + m[0] + ", -" + m[1] + ") )"; kernel.execute(command); } """ .replace("__WIDTH__", str(width)) \ .replace("__HEIGHT__", str(heigth)) \ .replace("__ID__", html_id)\ .replace("__VARNAME__", var_name) js_libs = [js_libs] display_html(IPython.core.display.HTML(data=html_src)) display_javascript(Javascript(data=test_d3_js, lib=js_libs)) return points
def problogobjs(self, line): """problog objects magic""" objs = self.shell.ev(line) for i, obj in enumerate(objs): if not isinstance(obj, LogicProgram): warnings.warn("expected object {} to be of type LogicProgram".format(i)) else: data = runproblog(obj, output="html") if data: warnings.warn("object {}:".format(i)) display_html(data, raw=True)
def print_fmin(self, sfmin, tolerance=None, ncalls=0): """Display FunctionMinum in html representation. .. note: Would appreciate if someone would make jquery hover description for each item.""" goaledm = 0.0001 * tolerance * sfmin.up style = fmin_style(sfmin) header = u""" <table> <tr> <td>FCN = {sfmin.fval}</td> <td>NFCN = {sfmin.nfcn}</td> <td>NCALLS = {ncalls}</td> </tr> <tr> <td>EDM = {sfmin.edm}</td> <td>GOAL EDM = {goaledm}</td> <td>UP = {sfmin.up}</td> </tr> </table> """.format(**locals()) status = u""" <table> <tr> <td align="center">Valid</td> <td align="center">Valid Param</td> <td align="center">Accurate Covar</td> <td align="center">PosDef</td> <td align="center">Made PosDef</td> </tr> <tr> <td align="center" style="{style.is_valid}">{sfmin.is_valid!r}</td> <td align="center" style="{style.has_valid_parameters}">{sfmin.has_valid_parameters!r}</td> <td align="center" style="{style.has_accurate_covar}">{sfmin.has_accurate_covar!r}</td> <td align="center" style="{style.has_posdef_covar}">{sfmin.has_posdef_covar!r}</td> <td align="center" style="{style.has_made_posdef_covar}">{sfmin.has_made_posdef_covar!r}</td> </tr> <tr> <td align="center">Hesse Fail</td> <td align="center">HasCov</td> <td align="center">Above EDM</td> <td align="center"></td> <td align="center">Reach calllim</td> </tr> <tr> <td align="center" style="{style.hesse_failed}">{sfmin.hesse_failed!r}</td> <td align="center" style="{style.has_covariance}">{sfmin.has_covariance!r}</td> <td align="center" style="{style.is_above_max_edm}">{sfmin.is_above_max_edm!r}</td> <td align="center"></td> <td align="center" style="{style.has_reached_call_limit}">{sfmin.has_reached_call_limit!r}</td> </tr> </table> """.format(**locals()) display_html(header + status, raw=True)
def display_raw_html(html, hide_input_cell=True): """ Execute raw HTML. :param html: str; HTML :param hide_input_cell: bool; :return: None """ if hide_input_cell: html += """<script> $('div .input').hide()""" display_html(html, raw=True)
def load_ipython_extension(ip): """Load the extension in IPython.""" ip.register_magics(PigMagics) # enable Pig highlight js = display.Javascript(data=js_string) display.display_javascript(js) # some custom CSS to augment the syntax highlighting css = display.HTML(css_string) display.display_html(css)
def print_coeffcorr(X): ## Correlation confusion matrix corr = X.corr() sns.heatmap(corr, xticklabels=corr.columns.values, yticklabels=corr.columns.values) plt.show() # Correlation matrix with values display_html(X.corr().style.background_gradient())
def show(plot, output=Output.pweave_md): """ Include an Altair (vega) figure in Pweave document. Generates html output. """ html = to_html(plot) if output == Output.pweave_md: display_html(html, raw=True) else: print(html)
def problogobjs(self, line): """problog objects magic""" objs = self.shell.ev(line) for i, obj in enumerate(objs): if not isinstance(obj, LogicProgram): error( "expected object {} to be of type LogicProgram".format(i)) else: data = runproblog(s, output='html') if data: info('object {}:'.format(i)) display_html(data, raw=True)
def _hack_style_jupyter_lab(): """Hack style format the jupyter notebook. This is a hack for formatting the jupyter notebook. It adds some utilities to the jupyter lab. Eventually these should be turned into some sort of jupyter lab extension. """ from IPython.core.display import ( # pylint: disable=import-outside-toplevel display_html, ) display_html(EXTRA_JUPYTER_HTML, raw=True)
def display(self, chart_num=0, configs_in={}): """Display the TXN viewer based on full current log""" # dump input txns to jsonfor transfer to js with open('txnLog.json', 'wb') as f: json.dump(self._log, f) # merge default configs config = { 'chartNum': chart_num, 'numThreads': self.n_threads } config.update(configs_in) js = ''.join('var %s = %s\n' % (k,v) for k,v in config.iteritems()) # JS js += open('txnViewer.js', 'rb').read() js_libs = [ 'http://rawgithub.com/mbostock/d3/master/d3.min.js', 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js' ] # HTML html_scripts = [ '<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">' ] html=""" <head>{0}</head> <h3>TXN VIEWER</h3> <table style="border: none; border-collapse: collapse;"> <tr style="border: none;"> <td style="border: none;"> <div id="top-spacer-{1}"></div> <div id="chart-{1}"></div> <div id="slider-{1}"></div> </td> <td style="vertical-align:top; border: none;"> <table id="vals-{1}"></table> </td> </tr> <tr style="border: none;"> <td colspan="2" style="border: none;"><h4>The Log</h4></td> </tr> <tr><td colspan="2"><div id="log-{1}"></td></tr> </table> """.format(''.join(html_scripts), chart_num) # Display in IPython notebook display_html(HTML(data=html)) display_javascript(Javascript(data=js, lib=js_libs))
def render_tree(self): """ Renders d3 visualization of the d3 tree, for IPython notebook display Depends on html/js files in vis/ directory, which is assumed to be in same dir... :return: """ # TODO: Make better control over what format / what attributes displayed @ nodes! html = open('lib/vis/tree-chart.html').read() % self.id display_html(HTML(data=html)) # JS JS_LIBS = ["https://d3js.org/d3.v3.min.js"] js = open('lib/vis/tree-chart.js').read() % (json.dumps(self.json), self.id) display_javascript(Javascript(data=js, lib=JS_LIBS))
def hide_code_on_export(): """ Use before any code cells to hide code on export to HTML There will be a toggle button to show or hide the code Markdown cells will still be shown From: https://stackoverflow.com/questions/27934885/how-to-hide-code-from-cells-in-ipython-notebook-visualized-with-nbviewer """ import IPython.core.display as di # This line will hide code by default when the notebook is exported as HTML di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True) # This line will add a button to toggle visibility of code blocks, for use with the HTML export version di.display_html('''<button onclick="jQuery('.input_area').toggle(); jQuery('.prompt').toggle();">Toggle code</button>''', raw=True)
def render_tree(self, highlight=[]): """ Renders d3 visualization of the d3 tree, for IPython notebook display Depends on html/js files in vis/ directory, which is assumed to be in same dir... """ # HTML WORD = '<span class="word-' + self.id + '-%s">%s</span>' words = ' '.join(WORD % (i,w) for i,w in enumerate(corenlp_cleaner(self.words))) if self.words else '' html = open('%s/vis/tree-chart.html' % APP_HOME).read() % (self.id, self.id, words) display_html(HTML(data=html)) # JS JS_LIBS = ["http://d3js.org/d3.v3.min.js"] js = open('%s/vis/tree-chart.js' % APP_HOME).read() % (self.id, json.dumps(self.to_json()), str(highlight)) display_javascript(Javascript(data=js, lib=JS_LIBS))
def print_param(self, mps, merr=None): """print list of parameters""" # todo: how to make it right clickable to export to latex to_print = "" header = """ <table> <tr> <td></td> <td>Name</td> <td>Value</td> <td>Parab Error</td> <td>Minos Error-</td> <td>Minos Error+</td> <td>Limit-</td> <td>Limit+</td> <td>FIXED</td> </tr> """.format( **locals() ) to_print += header for i, mp in enumerate(mps): minos_p, minos_m = ( (0.0, 0.0) if merr is None or mp.name not in merr else (merr[mp.name].upper, merr[mp.name].lower) ) limit_p, limit_m = ("", "") if not mp.has_limits else (mp.upper_limit, mp.lower_limit) fixed = "FIXED" if mp.is_fixed else "" j = i + 1 content = """ <tr> <td>{j}</td> <td>{mp.name}</td> <td>{mp.value:e}</td> <td>{mp.error:e}</td> <td>{minos_m:e}</td> <td>{minos_p:e}</td> <td>{limit_m!s}</td> <td>{limit_p!s}</td> <td>{fixed}</td> </tr> """.format( **locals() ) to_print += content to_print += """ </table> """ display_html(to_print, raw=True)
def _display_mp3(self, mp3_file_path, ogg_file_path): from abjad.tools import systemtools ffmpeg_command = 'ffmpeg -i {} {}'.format(ogg_file_path, mp3_file_path) print(ffmpeg_command) result = systemtools.IOManager.spawn_subprocess(ffmpeg_command) if result == 0: encoded_audio = self._get_base64_from_file(mp3_file_path) audio_tag = '<audio controls type="audio/mpeg" ' audio_tag += 'src="data:audio/mpeg;base64,{}">' audio_tag = audio_tag.format(encoded_audio) display_html(audio_tag, raw=True) return True message = 'ffmpeg failed to render OGG as MP3, result: {}' message = message.format(result) print(message) return False
def html_cursor(cursor): """Pretty prints a generic database API cursor.""" if cursor.description is None: ipdisp.display_html(ipdisp.HTML("<i>No data returned</i>")) return headers = [x[0] for x in cursor.description] header_line = "<tr><th>" + ("</th><th>".join(headers)) + "</th></tr>" def getrow(row): rendered = ["<tr>"] + ["<td>%s</td>" % enc(row[col]) for col in range(0, len(headers))] + ["</tr>"] return "".join(rendered) rows = [header_line] + [getrow(row) for row in cursor] body = '\n'.join(rows) table = '<table class="nowrap">\n%s\n</table>' % body return ipdisp.HTML(table)
def show_image(arr): resized = imutils.resize(arr, width=800) png_to_show = cv2.imencode('.png', resized)[1].tostring() display_png(png_to_show, raw=True) png_to_save = cv2.imencode('.png', arr)[1].tostring() try: os.makedirs(temp_images_dir) except OSError as exception: if exception.errno != errno.EEXIST: raise file_name = datetime.datetime.now().isoformat().replace(':', '_') + '.png' file_path = os.path.join(temp_images_dir, file_name) with open(file_path, 'w') as f: f.write(png_to_save) url = 'http://localhost:8888/files/%s' % file_path display_html('<a href="%s" target="_blank">%s</a>' % (url, file_name), raw=True)
def textdiff(self, line): """ defines ``%textdiff`` which displays differences between two text files, two strings, two urls, it is based on `create_visual_diff_through_html_files <http://www.xavierdupre.fr/app/pyquickhelper/helpsphinx/pyquickhelper/filehelper/visual_sync.html?highlight=create#pyquickhelper.filehelper.visual_sync.create_visual_diff_through_html_files>`_ Check blog post :ref:`b-textdiff` to see an example. """ parser = self.get_parser(MagicFile.textdiff_parser, "textdiff") args = self.get_args(line, parser) if args is not None: html, js = create_visual_diff_through_html_files(args.f1, args.f2, encoding=args.encoding, notebook=True, context_size=None if args.context in [ None, ""] else int(args.context), inline_view=args.inline) display_html(html) return js
def dict2html(dic, keys=None, border="", prec=4): dcont = """ <tr> <td><b>{key}</b></td> <td>{value}</td> </tr>""" keys = keys if keys else sorted(dic.keys()) header = "<table border=%r>" % border if border else "<table>" content = [dcont.format(key=k, value=(round(dic[k][0], prec), round(dic[k][1], prec))) for k in keys] return display_html(HTML("\n".join([header] + content + ["</table>"])))
def print_matrix(self, vnames, matrix, latex_map=None): from IPython.core.display import display_html latexuid = randid() latextable = LatexFactory.build_matrix(vnames, matrix, latex_map=latex_map) to_print = """ <table> <tr> <td>%s</td> """ % self.toggle_sign(latexuid) for v in vnames: to_print += """ <td> <div style="width:20px;position:relative; width: -moz-fit-content;"> <div style="display:inline-block;-webkit-writing-mode:vertical-rl;-moz-writing-mode: vertical-rl;writing-mode: vertical-rl;"> {v} </div> </div> </td> """.format(**locals()) to_print += """ </tr> """ for i, v1 in enumerate(vnames): to_print += """ <tr> <td>{v1}</td> """.format(**locals()) for j, v2 in enumerate(vnames): val = matrix[i][j] color = Gradient.rgb_color_for(val) to_print += """ <td style="background-color:{color}"> {val:3.2f} </td> """.format(**locals()) to_print += """ </tr> """ to_print += '</table>\n' to_print += self.hidden_table(str(latextable), latexuid) display_html(to_print, raw=True)
def print_matrix(self, vnames, matrix, varno=None): to_print = """ <table> <tr> <td></td> """ for v in vnames: to_print += """ <td> <span style="-webkit-writing-mode:vertical-rl;-moz-writing-mode: vertical-rl;writing-mode: vertical-rl;"> {v} </span> </td> """.format( **locals() ) to_print += """ </tr> """ for i, v1 in enumerate(vnames): to_print += """ <tr> <td>{v1}</td> """.format( **locals() ) for j, v2 in enumerate(vnames): val = matrix[i][j] color = Gradient.rgb_color_for(val) to_print += """ <td style="background-color:{color}"> {val:3.2f} </td> """.format( **locals() ) to_print += """ </tr> """ to_print += "</table>" display_html(to_print, raw=True)
def display_list(l, list_type='ul'): """Convert a list of strings into an HTML list.""" from IPython.core.display import display_html o = ["<{}>".format(list_type)] for i in l: o.append("<li>{}</li>".format(str(i))) o.append("</{}>".format(list_type)) return display_html('\n'.join(o), raw=True)
def nbsample(draws, step, start=None, trace=None, chain=0, tune=None, model=None, random_seed=None): display.display_html(_javascript, raw=True) w = ISampleWidget() display.display(w) t_start = time.time() t_last = time.time() w.max_samples = draws w.current_samples = 0 for i,backend in enumerate(iter_sample(draws, step, start=start, trace=trace, chain=chain, tune=tune, model=model, random_seed=None), 1): elapsed = time.time() - t_start elapsed_last = time.time() - t_last if elapsed_last > 0.1: t_last = time.time() w.current_samples = i w.clock = "%02i:%02i:%02i" % (elapsed / 60 / 60, elapsed / 60 % 60, elapsed % 60) get_ipython().kernel.do_one_iteration() if w.stopped: break w.current_samples = i return backend
def print_merror(self, vname, smerr): stat = "VALID" if smerr.is_valid else "PROBLEM" style = minos_style(smerr) to_print = """ <span>Minos status for {vname}: <span style="{style.is_valid}">{stat}</span></span> <table> <tr> <td>Error</td> <td>{smerr.lower}</td> <td>{smerr.upper}</td> </tr> <tr> <td>Valid</td> <td style="{style.lower_valid}">{smerr.lower_valid}</td> <td style="{style.upper_valid}">{smerr.upper_valid}</td> </tr> <tr> <td>At Limit</td> <td style="{style.at_lower_limit}">{smerr.at_lower_limit}</td> <td style="{style.at_upper_limit}">{smerr.at_upper_limit}</td> </tr> <tr> <td>Max FCN</td> <td style="{style.at_lower_max_fcn}">{smerr.at_lower_max_fcn}</td> <td style="{style.at_upper_max_fcn}">{smerr.at_upper_max_fcn}</td> </tr> <tr> <td>New Min</td> <td style="{style.lower_new_min}">{smerr.lower_new_min}</td> <td style="{style.upper_new_min}">{smerr.upper_new_min}</td> </tr> </table> """.format( **locals() ) display_html(to_print, raw=True)