Python IPython.core.display.display() Examples
The following are 30
code examples of IPython.core.display.display().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
IPython.core.display
, or try the search function
.
Example #1
Source File: ITM.py From pySPM with Apache License 2.0 | 6 votes |
def show_values(self, pb=False, gui=False, **kargs): from .utils import html_table, aa_table html = True if 'html' in kargs: html = kargs['html'] del kargs['html'] if gui: from pySPM.tools import values_display Vals = self.get_values(pb, nest=True, **kargs) values_display.show_values(Vals) else: Vals = self.get_values(pb, **kargs) Table = [["Parameter Name", "Value @start", "Value @end"]] for x in Vals: Table.append(tuple([x]+Vals[x])) if not html: print(aa_table(Table, header=True)) else: from IPython.core.display import display, HTML res = html_table(Table, header=True) display(HTML(res))
Example #2
Source File: pylabtools.py From Computable with MIT License | 6 votes |
def print_figure(fig, fmt='png'): """Convert a figure to svg or png for inline display.""" from matplotlib import rcParams # When there's an empty figure, we shouldn't return anything, otherwise we # get big blank areas in the qt console. if not fig.axes and not fig.lines: return fc = fig.get_facecolor() ec = fig.get_edgecolor() bytes_io = BytesIO() dpi = rcParams['savefig.dpi'] if fmt == 'retina': dpi = dpi * 2 fmt = 'png' fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight', facecolor=fc, edgecolor=ec, dpi=dpi) data = bytes_io.getvalue() return data
Example #3
Source File: fanova.py From CAVE with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_jupyter(self): from IPython.core.display import HTML, Image, display for b, result in self.result.items(): error = self.result[b]['else'] if 'else' in self.result[b] else None if error: display(HTML(error)) else: # Show table display(HTML(self.result[b]["Importance"]["table"])) # Show plots display(*list([Image(filename=d["figure"]) for d in self.result[b]['Marginals'].values()])) display(*list([Image(filename=d["figure"]) for d in self.result[b]['Pairwise Marginals'].values()])) # While working for a prettier solution, this might be an option: # display(HTML(figure_to_html([d["figure"] for d in self.result[b]['Marginals'].values()] + # [d["figure"] for d in self.result[b]['Pairwise Marginals'].values()], # max_in_a_row=3, true_break_between_rows=True)))
Example #4
Source File: shell_magics.py From coastermelt with MIT License | 6 votes |
def ecc(self, line, cell='', address=target_memory.shell_code): """Evaluate a 32-bit C++ expression on the target, and immediately start a console To ensure we only display output that was generated during the command execution, the console is sync'ed and unread output is discarded prior to running the command. """ d = self.shell.user_ns['d'] ConsoleBuffer(d).discard() try: return_value = evalc(d, line + cell, defines=all_defines(), includes=all_includes(), address=address, verbose=True) except CodeError as e: raise UsageError(str(e)) if return_value is not None: display(return_value) console_mainloop(d)
Example #5
Source File: workspace.py From pyGSTi with Apache License 2.0 | 6 votes |
def display(self): """ Display this switchboard within an iPython notebook. Calling this function requires that you are in an iPython environment, and really only makes sense within a notebook. Returns ------- None """ if not in_ipython_notebook(): raise ValueError('Only run `display` from inside an IPython Notebook.') out = self.render("html") content = "<script>\n" + \ "require(['jquery','jquery-UI'],function($,ui) {" + \ out['js'] + " });</script>" + out['html'] display_ipynb(content)
Example #6
Source File: ui.py From dcase_util with MIT License | 6 votes |
def class_name(self, class_name, indent=0): """Class name Parameters ---------- class_name : str Class name indent : int Amount of indention used for the line Default value 0 Returns ------- str """ return '<div class="label label-primary" ' \ 'style="margin-bottom:5px;margin-top:5px;display:inline-block;' + self.get_margin( indent=indent, include_style_attribute=False) + '">' + class_name + '</div>'
Example #7
Source File: backend_inline.py From Computable with MIT License | 6 votes |
def show(close=None): """Show all figures as SVG/PNG payloads sent to the IPython clients. Parameters ---------- close : bool, optional If true, a ``plt.close('all')`` call is automatically issued after sending all the figures. If this is set, the figures will entirely removed from the internal list of figures. """ if close is None: close = InlineBackend.instance().close_figures try: for figure_manager in Gcf.get_all_fig_managers(): display(figure_manager.canvas.figure) finally: show._to_draw = [] if close: matplotlib.pyplot.close('all') # This flag will be reset by draw_if_interactive when called
Example #8
Source File: nbdisplay.py From msticpy with MIT License | 6 votes |
def display_alert( alert: Union[Mapping[str, Any], SecurityAlert], show_entities: bool = False ): """ Display a Security Alert. Parameters ---------- alert : Union[Mapping[str, Any], SecurityAlert] The alert to display as Mapping (e.g. pd.Series) or SecurityAlert show_entities : bool, optional Whether to display entities (the default is False) """ output = format_alert(alert, show_entities) if not isinstance(output, tuple): output = [output] for disp_obj in output: display(disp_obj)
Example #9
Source File: nbdisplay.py From msticpy with MIT License | 6 votes |
def display_process_tree(process_tree: pd.DataFrame): """ Display process tree data frame. (Deprecated). Parameters ---------- process_tree : pd.DataFrame Process tree DataFrame The display module expects the columns NodeRole and Level to be populated. NoteRole is one of: 'source', 'parent', 'child' or 'sibling'. Level indicates the 'hop' distance from the 'source' node. """ build_and_show_process_tree(process_tree)
Example #10
Source File: common.py From pycoQC with GNU General Public License v3.0 | 5 votes |
def jhelp (f:"python function or method"): """ Display a Markdown pretty help message for functions and class methods (default __init__ is a class is passed) jhelp also display default values and type annotations if available. The docstring synthax should follow the same synthax as the one used for this function * f Function or method to display the help message for """ # Private import as this is only needed if using jupyter from IPython.core.display import display, Markdown f_doc = doc_func(f) arg_doc = make_arg_dict(f) # Signature and function documentation s = "**{}** ({})\n\n{}\n\n---\n\n".format(f.__name__, ", ".join(arg_doc.keys()), f_doc) # Args doc for arg_name, arg_val in arg_doc.items(): # Arg signature section s+= "* **{}**".format(arg_name) if "default" in arg_val: if arg_val["default"] == "": arg_val["default"] = "\"\"" s+= " (default: {})".format(arg_val["default"]) if "required" in arg_val: s+= " (required)" if "type" in arg_val: if type(list) == type: s+= " [{}]".format(arg_val["type"].__name__) else: s+= " [{}]".format(arg_val["type"]) s+="\n\n" # Arg doc section if "help" in arg_val: s+= "{}\n\n".format(arg_val["help"]) # Display in Jupyter display (Markdown(s))
Example #11
Source File: gpcharts.py From GooPyCharts with Apache License 2.0 | 5 votes |
def write(self): with open(self.fname,'w') as f: f.write(self.javascript) #display HTML helper method. Trys nb() first, falls back on wb() if no notebook #the nb parameter has been deprecated and does nothing.
Example #12
Source File: viz.py From mapboxgl-jupyter with MIT License | 5 votes |
def show(self, **kwargs): # Load the HTML iframe html = self.create_html(**kwargs) map_html = self.as_iframe(html) # Display the iframe in the current jupyter notebook view display(HTML(map_html))
Example #13
Source File: display.py From Computable with MIT License | 5 votes |
def html(self, line, cell): """Render the cell as a block of HTML""" display(HTML(cell))
Example #14
Source File: display.py From Computable with MIT License | 5 votes |
def svg(self, line, cell): """Render the cell as an SVG literal""" display(SVG(cell))
Example #15
Source File: display.py From Computable with MIT License | 5 votes |
def latex(self, line, cell): """Render the cell as a block of latex""" display(Latex(cell))
Example #16
Source File: display.py From Computable with MIT License | 5 votes |
def javascript(self, line, cell): """Run the cell block of Javascript code""" display(Javascript(cell))
Example #17
Source File: pylabtools.py From Computable with MIT License | 5 votes |
def import_pylab(user_ns, import_all=True): """Populate the namespace with pylab-related values. Imports matplotlib, pylab, numpy, and everything from pylab and numpy. Also imports a few names from IPython (figsize, display, getfigs) """ # Import numpy as np/pyplot as plt are conventions we're trying to # somewhat standardize on. Making them available to users by default # will greatly help this. s = ("import numpy\n" "import matplotlib\n" "from matplotlib import pylab, mlab, pyplot\n" "np = numpy\n" "plt = pyplot\n" ) exec s in user_ns if import_all: s = ("from matplotlib.pylab import *\n" "from numpy import *\n") exec s in user_ns # IPython symbols to add user_ns['figsize'] = figsize from IPython.core.display import display # Add display and getfigs to the user's namespace user_ns['display'] = display user_ns['getfigs'] = getfigs
Example #18
Source File: utility.py From msticpy with MIT License | 5 votes |
def toggle_code(): """Display a toggle button to hide/reveal code cell.""" display(HTML(_TOGGLE_CODE_STR)) # String escapes
Example #19
Source File: miner.py From minetorch with MIT License | 5 votes |
def notebook_divide(self, message): if self.in_notebook: display(HTML( '<div style="display: flex; justify-content: center;">' f'<h3 style="color: #7cb305; border-bottom: 4px dashed #91d5ff; padding-bottom: 6px;">{message}</h3>' '</div>' ))
Example #20
Source File: jupyter.py From axcell with Apache License 2.0 | 5 votes |
def display_html(s): return display(HTML(s))
Example #21
Source File: progress_reporter.py From ray with Apache License 2.0 | 5 votes |
def report(self, trials, done, *sys_info): from IPython.display import clear_output from IPython.core.display import display, HTML if self._overwrite: clear_output(wait=True) progress_str = self._progress_str( trials, done, *sys_info, fmt="html", delim="<br>") display(HTML(progress_str))
Example #22
Source File: __init__.py From pywr with GNU General Public License v3.0 | 5 votes |
def draw_graph(self): """Draw pywr schematic graph in a jupyter notebook""" js = draw_graph_template.render( graph=self.graph, width=self.width, height=self.height, element="element", labels=self.labels, attributes=self.attributes, css=self.css.replace("\n", "") ) display(Javascript(data=js))
Example #23
Source File: gpcharts.py From GooPyCharts with Apache License 2.0 | 5 votes |
def nb(self): self.write() display(HTML(self.fname)) #Displays in a web browser. Writes current data first.
Example #24
Source File: gpcharts.py From GooPyCharts with Apache License 2.0 | 5 votes |
def bar(self,xdata,ydata,disp=True,**kwargs): '''Displays a bar graph. xdata: list of bar graph categories/bins. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example. ydata: list of values associated with categories in xdata. If xdata includes a header, include a header list on ydata as well. disp: for displaying plots immediately. Set to True by default. Set to False for other operations, then use show() to display the plot. **kwargs: Access to other Google Charts API options. The key is the option name, the value is the option's full JS code. ''' #combine data into proper format data = combineData(xdata,ydata,self.xlabel) #Include other options, supplied by **kwargs other = '' for option in kwargs: other += option + ': ' + kwargs[option] + ',\n' #input argument format to template is in dictionary format (see template for where variables are inserted) argDict = { 'data':str(data), 'title':self.title, 'functionName':slugify(self.title), 'height':self.height, 'width':self.width, 'logScaleFlag':'false', 'ylabel':self.ylabel, 'plotType':'BarChart', 'numFig':self.numFig, 'other':other} self.javascript = templateType(xdata) % argDict if disp: self.dispFile() #column chart
Example #25
Source File: gpcharts.py From GooPyCharts with Apache License 2.0 | 5 votes |
def hist(self,xdata,disp=True,**kwargs): '''Graphs a histogram. xdata: List of values to bin. Can optionally include a header, see testGraph_barAndHist.py in https://github.com/Dfenestrator/GooPyCharts for an example. disp: for displaying plots immediately. Set to True by default. Set to False for other operations, then use show() to display the plot. **kwargs: Access to other Google Charts API options. The key is the option name, the value is the option's full JS code. ''' #combine data into proper format data = [self.xlabel]+xdata #Include other options, supplied by **kwargs other = '' for option in kwargs: other += option + ': ' + kwargs[option] + ',\n' #input argument format to template is in dictionary format (see template for where variables are inserted) argDict = { 'data':str(data), 'title':self.title, 'functionName':slugify(self.title), 'height':self.height, 'width':self.width, 'logScaleFlag':'false', 'ylabel':self.ylabel, 'plotType':'Histogram', 'numFig':self.numFig, 'other':other} self.javascript = (graphPgTemplateStart+graphPgTemplate_hist+graphPgTemplateEnd) % argDict if disp: self.dispFile() #Jupyter plotting methods (depricated; keeping for now for backwards compatibility)
Example #26
Source File: ui.py From dcase_util with MIT License | 5 votes |
def row_sep(self, **kwargs): """Table separator row Returns ------- str """ html = '' grid_template_columns = [] for column_id in range(0, self.row_column_count): if column_id < len(self.row_column_widths): column_width = int(self.row_column_widths[column_id] * self.row_item_width_factor) else: column_width = int(15 * self.row_item_width_factor) grid_template_columns.append(str(column_width) + 'px') grid_template_columns = ' '.join(grid_template_columns) html += '<div style="' html += 'display:grid;grid-template-columns:' + grid_template_columns + ';grid-gap:0px;' html += 'margin-top:-4px;margin-bottom:-3px;height:2px;' + self.get_margin( indent=self.row_indent, include_style_attribute=False ) html += '">' for i in range(0, self.row_column_count): html += '<div style="padding:0px;margin:0px;background-color:#333;">' html += '</div>' html += '</div>' # Container return html
Example #27
Source File: engine.py From py-roughviz with MIT License | 5 votes |
def render_notebook(self): if hasattr(self, "render_to_tmpl"): self.render_to_tmpl() with open(self.tmpl_file) as f: tmpl_file = f.read() tmpl = Template(tmpl_file) output = tmpl.render(chart=self) return display(HTML(output))
Example #28
Source File: base_analyzer.py From CAVE with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_jupyter(self): """Depending on analysis, this creates jupyter-notebook compatible output.""" bokeh_plots = self.check_for_bokeh(self.result) if bokeh_plots: self.logger.warning("Bokeh plots cannot be re-used for notebook if they've already been \"components\"'ed. " "To be sure, get_jupyter should be overwritten for bokeh-producing analyzers.") output_notebook() for bokeh_plot in bokeh_plots: show(bokeh_plot) else: from IPython.core.display import HTML, display display(HTML(self.get_html()))
Example #29
Source File: visualization.py From captum with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visualize_text(datarecords: Iterable[VisualizationDataRecord]) -> None: assert HAS_IPYTHON, ( "IPython must be available to visualize text. " "Please run 'pip install ipython'." ) dom = ["<table width: 100%>"] rows = [ "<tr><th>True Label</th>" "<th>Predicted Label</th>" "<th>Attribution Label</th>" "<th>Attribution Score</th>" "<th>Word Importance</th>" ] for datarecord in datarecords: rows.append( "".join( [ "<tr>", format_classname(datarecord.true_class), format_classname( "{0} ({1:.2f})".format( datarecord.pred_class, datarecord.pred_prob ) ), format_classname(datarecord.attr_class), format_classname("{0:.2f}".format(datarecord.attr_score)), format_word_importances( datarecord.raw_input, datarecord.word_attributions ), "<tr>", ] ) ) dom.append("".join(rows)) dom.append("</table>") display(HTML("".join(dom)))
Example #30
Source File: ITM.py From pySPM with Apache License 2.0 | 5 votes |
def reconstruct(self, channels, scans=None, sf=None, k0=None, prog=False, time=False): """ Reconstruct an Image from a raw spectra by defining the lower and upper mass channels: list of (lower_mass, upper_mass) upper_mass: upper mass of the peak scans: The list of the scans to take into account (if None, all scans are taken) sf/k0: mass calibration. If none take the saved values time: If true the upper/lower_mass will be understood as time value prog: If True display a progressbar with tqdm """ from .utils import mass2time from . import SPM_image assert hasattr(channels, '__iter__') if not hasattr(channels[0], '__iter__'): channels = [channels] for c in channels: assert len(c)==2 if scans is None: scans = range(self.Nscan) if prog: scans = PB(scans) left = np.array([x[0] for x in channels]) right = np.array([x[1] for x in channels]) if not time: if sf is None or k0 is None: sf, k0 = self.get_mass_cal() left = mass2time(left, sf=sf, k0=k0) right = mass2time(right, sf=sf, k0=k0) Counts = [np.zeros((self.size['pixels']['x'], self.size['pixels']['y'])) for x in channels] for s in scans: Data = self.get_raw_data(s) for xy in Data: for i,ch in enumerate(channels): Counts[i][xy[1],xy[0]] += np.sum((Data[xy]>=left[i])*(Data[xy]<=right[i])) res = [SPM_image(C, real=self.size['real'], _type='TOF', channel="{0[0]:.2f}{unit}-{0[1]:.2f}{unit}".format(channels[i],unit=["u", "s"][time]), zscale="Counts") for i,C in enumerate(Counts)] if len(res) == 1: return res[0] return res[0] return res