Python IPython.core.display.HTML Examples
The following are 30
code examples of IPython.core.display.HTML().
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: gpcharts.py From GooPyCharts with Apache License 2.0 | 6 votes |
def __init__(self,title="Fig",xlabel='',ylabel='',height=600,width=1000): #set figure number, and increment for each instance self.figNum = figure.numFig figure.numFig = figure.numFig + 1 #if title has not been changed, add figure number if title=="Fig": self.title = title+str(self.figNum) else: self.title = title self.fname = self.title+'.html' self.xlabel = xlabel self.ylabel = ylabel #for sizing plot self.height = height self.width = width #Set by the chart methods, can be printed out or exported to file. self.javascript = 'No chart created yet. Use a chart method' # Get the full HTML of the file.
Example #2
Source File: workspace.py From pyGSTi with Apache License 2.0 | 6 votes |
def render(self, typ="html"): """ Renders this object into the specifed format, specifically for embedding it within a larger document. Parameters ---------- typ : str The format to render as. Currently `"html"` is widely supported and `"latex"` is supported for tables. Returns ------- dict A dictionary of strings whose keys indicate which portion of the embeddable output the value is. Keys will vary for different `typ`. For `"html"`, keys are `"html"` and `"js"` for HTML and and Javascript code, respectively. """ raise NotImplementedError("Derived classes must implement their own render()")
Example #3
Source File: workspace.py From pyGSTi with Apache License 2.0 | 6 votes |
def render(self, typ="html"): """ Render this Switchboard into the requested format. The returned string(s) are intended to be used to embedded a visualization of this object within a larger document. Parameters ---------- typ : {"html"} The format to render as. Currently only HTML is supported. Returns ------- dict A dictionary of strings whose keys indicate which portion of the embeddable output the value is. Keys will vary for different `typ`. For `"html"`, keys are `"html"` and `"js"` for HTML and and Javascript code, respectively. """ return self._render_base(typ, None, self.show)
Example #4
Source File: metadata.py From dcase_util with MIT License | 6 votes |
def to_html(self, indent=0): """Get container information in a HTML formatted string Parameters ---------- indent : int Amount of indent Default value 0 Returns ------- str """ return self.to_string(ui=FancyHTMLStringifier(), indent=indent)
Example #5
Source File: workspace.py From pyGSTi with Apache License 2.0 | 6 votes |
def render(self, typ="html"): """ Render this Switchboard into the requested format. The returned string(s) are intended to be used to embedded a visualization of this object within a larger document. Parameters ---------- typ : {"html"} The format to render as. Currently only HTML is supported. Returns ------- dict A dictionary of strings whose keys indicate which portion of the embeddable output the value is. Keys will vary for different `typ`. For `"html"`, keys are `"html"` and `"js"` for HTML and and Javascript code, respectively. """ return self.switchboard._render_base(typ, self.idsuffix, self.show)
Example #6
Source File: ui.py From dcase_util with MIT License | 6 votes |
def sub_header(self, text='', indent=0, tag='h3'): """Sub header Parameters ---------- text : str, optional Footer text indent : int Amount of indention used for the line Default value 0 tag : str HTML tag used for the title Default value "h3" Returns ------- str """ return '<' + tag + self.get_margin(indent=indent) + '>' + text + '</' + tag + '>' + '\n'
Example #7
Source File: mixins.py From dcase_util with MIT License | 6 votes |
def to_html(self, indent=0): """Get container information in a HTML formatted string Parameters ---------- indent : int Amount of indent Default value 0 Returns ------- str """ return self.to_string(ui=FancyHTMLStringifier(), indent=indent)
Example #8
Source File: callbacks.py From dcase_util with MIT License | 6 votes |
def to_html(self, indent=0): """Get information in a HTML formatted string Parameters ---------- indent : int Amount of indent Default value 0 Returns ------- str """ return self.to_string(ui=FancyHTMLStringifier(), indent=indent)
Example #9
Source File: plotting.py From rnn_agreement with MIT License | 6 votes |
def highlight_dep(dep, show_pos=False): s = [] s2 = [] z = zip(dep.orig_sentence.split(), dep.sentence.split(), dep.pos_sentence.split()) for i, (tok, mixed, pos) in enumerate(z): color = 'black' if i == dep.subj_index - 1 or i == dep.verb_index - 1: color = 'blue' elif (dep.subj_index - 1 < i < dep.verb_index - 1 and pos in ['NN', 'NNS']): color = 'red' if pos != dep.subj_pos else 'green' s.append('<span style="color: %s">%s</span>' % (color, tok)) if show_pos: s2.append('<span style="color: %s">%s</span>' % (color, pos)) res = ' '.join(s) if show_pos: res += '<br>' + ' '.join(s2) display(HTML(res))
Example #10
Source File: clienttest.py From Computable with MIT License | 6 votes |
def generate_output(): """function for testing output publishes two outputs of each type, and returns a rich displayable object. """ import sys from IPython.core.display import display, HTML, Math print("stdout") print("stderr", file=sys.stderr) display(HTML("<b>HTML</b>")) print("stdout2") print("stderr2", file=sys.stderr) display(Math(r"\alpha=\beta")) return Math("42") # test decorator for skipping tests when libraries are unavailable
Example #11
Source File: JPyInterface.py From parliament2 with Apache License 2.0 | 6 votes |
def Draw(obj, jsDrawMethod='draw', objIsJSON=False): if objIsJSON: dat = obj else: dat = ROOT.TBufferJSON.ConvertToJSON(obj) dat = str(dat).replace("\n", "") JsDraw.__divUID += 1 display(HTML(JsDraw.__jsCode.substitute({ 'funcName': jsDrawMethod, 'divid':'jstmva_'+str(JsDraw.__divUID), 'dat': dat, 'width': JsDraw.jsCanvasWidth, 'height': JsDraw.jsCanvasHeight }))) ## Inserts CSS file # @param cssName The CSS file name. File must be in jsMVACSSDir!
Example #12
Source File: JPyInterface.py From parliament2 with Apache License 2.0 | 6 votes |
def InsertData(obj, dataInserterMethod="updateTrainingTestingErrors", objIsJSON=False, divID=""): if objIsJSON: dat = obj else: dat = ROOT.TBufferJSON.ConvertToJSON(obj) dat = str(dat).replace("\n", "") if len(divID)>1: divid = divID jsCode = JsDraw.__jsCodeForDataInsertNoRemove else: divid = str(JsDraw.__divUID) jsCode = JsDraw.__jsCodeForDataInsert display(HTML(jsCode.substitute({ 'funcName': dataInserterMethod, 'divid': 'jstmva_'+divid, 'dat': dat }))) ## Draws a signal and background histogram to a newly created TCanvas # @param sig signal histogram # @param bkg background histogram # @param title all labels
Example #13
Source File: analysis.py From ParlAI with MIT License | 6 votes |
def get_num_hits_per_matchup(self): """ Return the number of hits per matchup. """ matchup_total_1_df = self.matchup_total_df.reset_index() matchup_total_2_df = matchup_total_1_df.rename( columns={'eval_choice_0': 'eval_choice_1', 'eval_choice_1': 'eval_choice_0'} ) self.num_hits_per_matchup_df = ( pd.concat([matchup_total_1_df, matchup_total_2_df], axis=0) .pivot( index='eval_choice_0', columns='eval_choice_1', values='matchup_total' ) .reindex(index=self.models_by_win_frac, columns=self.models_by_win_frac) ) return self.num_hits_per_matchup_df ################## # Rendering HTML # ##################
Example #14
Source File: bokeh.py From backtrader_plotting with GNU General Public License v3.0 | 6 votes |
def show(self): """Display a figure (called by backtrader).""" # as the plot() function only created the figures and the columndatasources with no data -> now we fill it for idx in range(len(self.figurepages)): model = self.generate_model(idx) if self.p.output_mode in ['show', 'save']: if self._iplot: css = self._output_stylesheet() display(HTML(css)) show(model) else: filename = self._output_plot_file(model, idx, self.p.filename) if self.p.output_mode == 'show': view(filename) elif self.p.output_mode == 'memory': pass else: raise RuntimeError(f'Invalid parameter "output_mode" with value: {self.p.output_mode}') self._reset()
Example #15
Source File: commands.py From Xpedite with Apache License 2.0 | 6 votes |
def diff(lhs, rhs, profiles=None): """ Compares statistics for a pair or a group of transactions :param lhs: Transaction ID or A list of transaction ids (lhs value of comparison) :param rhs: Transaction ID or A list of transaction ids (rhs value of comparison) :param profiles: Transactions from the current profile session :type profiles: xpedite.report.profile.Profiles """ profiles = profiles if profiles else globalProfile() if isinstance(lhs, int) and isinstance(rhs, int): diffTxn(lhs, rhs, profiles) elif isinstance(lhs, list) or isinstance(rhs, list): diffTxns(lhs, rhs, profiles) else: display(HTML(ERROR_TEXT.format( """ Invalid arguments:<br> diff expects either a pair of txns or a pair of list of txns<br> usage 1: diff(<txnId1>, <txnId2>) - compares two transactions with id txnId1 vs txnId2<br> usage 2: diff(<List of txns>, <List of txns>) - compares stats for the first list of txns vs the second.<br> """ )))
Example #16
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 #17
Source File: log.py From lang2program with Apache License 2.0 | 5 votes |
def print_with_fonts(tokens, sizes, colors, background=None): def style(text, size=12, color='black'): return u'<span style="font-size: {}px; color: {};">{}</span>'.format(size, color, text) styled = [style(token, size, color) for token, size, color in zip(tokens, sizes, colors)] text = u' '.join(styled) if background: text = u'<span style="background-color: {};">{}</span>'.format(background, text) display(HTML(text))
Example #18
Source File: log.py From lang2program with Apache License 2.0 | 5 votes |
def print_with_fonts(tokens, sizes, colors, background=None): def style(text, size=12, color='black'): return u'<span style="font-size: {}px; color: {};">{}</span>'.format(size, color, text) styled = [style(token, size, color) for token, size, color in zip(tokens, sizes, colors)] text = u' '.join(styled) if background: text = u'<span style="background-color: {};">{}</span>'.format(background, text) display(HTML(text))
Example #19
Source File: roughviz.py From roughviz with MIT License | 5 votes |
def generate_template(data, labels, values, plot_svg, **kwargs): template = Template(data.decode("utf-8")) id_name = ''.join(random.choice(string.ascii_lowercase) for i in range(10)) output = template.render(id_name = id_name, labels = labels, values = values, kwargs = kwargs) if(plot_svg): svg_id = "svg"+id_name script = """ <style> div.output_area img, div.output_area svg{ height: 100%!important; } </style> <script> var e = document.getElementById('"""+id_name+"""'); var divCheckingInterval = setInterval(function(){ if(e.getElementsByTagName('svg').length){ clearInterval(divCheckingInterval); e.getElementsByTagName('svg')[0].setAttribute("id", '"""+svg_id+"""'); var svgElement = document.getElementById('"""+svg_id+"""'); var svgString = new XMLSerializer().serializeToString(svgElement); var decoded = unescape(encodeURIComponent(svgString)); var base64 = btoa(decoded); var imgSource = `data:image/svg+xml;base64,${base64}`; e.innerHTML = "<img id='svgplot'>"; document.getElementById('svgplot').src = imgSource; }}, 1); </script> """ display(HTML(output)) display(HTML(script)) else: display(HTML(output))
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: 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 #22
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 #23
Source File: quickplot.py From qkit with GNU General Public License v2.0 | 5 votes |
def __init__(self, maximize=True): """ Quickplot routine to scan through your measurement data. The maximize switch can be used to increase the width of the notebook view, giving you more space for the database table. """ self.fig, self.ax = plt.subplots(2, num="Quickplot", clear=True) self.args, self.kwargs = (), {} self.m_type, self.ds_type, self.num_plots = None, None, None self.remove_offset_x_avg = False self.remove_offset_y_avg = False self.unwrap_phase = False if maximize: display(HTML("<style>.container { width:100% !important; }</style>"))
Example #24
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 #25
Source File: viz.py From mapboxgl-jupyter with MIT License | 5 votes |
def as_iframe(self, html_data): """Build the HTML representation for the mapviz.""" srcdoc = html_data.replace('"', "'") return ('<iframe id="{div_id}", srcdoc="{srcdoc}" style="width: {width}; ' 'height: {height};"></iframe>'.format( div_id=self.div_id, srcdoc=srcdoc, width=self.width, height=self.height))
Example #26
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 #27
Source File: Auto_NLP.py From Auto_ViML with Apache License 2.0 | 5 votes |
def plot_confusion_matrix(y_test,y_pred, model_name='Model'): """ This plots a beautiful confusion matrix based on input: ground truths and predictions """ #Confusion Matrix '''Plotting CONFUSION MATRIX''' import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') '''Display''' from IPython.core.display import display, HTML display(HTML("<style>.container { width:95% !important; }</style>")) pd.options.display.float_format = '{:,.2f}'.format #Get the confusion matrix and put it into a df from sklearn.metrics import confusion_matrix, f1_score cm = confusion_matrix(y_test, y_pred) cm_df = pd.DataFrame(cm, index = np.unique(y_test).tolist(), columns = np.unique(y_test).tolist(), ) #Plot the heatmap plt.figure(figsize=(12, 8)) sns.heatmap(cm_df, center=0, cmap=sns.diverging_palette(220, 15, as_cmap=True), annot=True, fmt='g') plt.title(' %s \nF1 Score(avg = micro): %0.2f \nF1 Score(avg = macro): %0.2f' %( model_name,f1_score(y_test, y_pred, average='micro'),f1_score(y_test, y_pred, average='macro')), fontsize = 13) plt.ylabel('True label', fontsize = 13) plt.xlabel('Predicted label', fontsize = 13) plt.show(); ##############################################################################################
Example #28
Source File: Auto_NLP.py From Auto_ViML with Apache License 2.0 | 5 votes |
def plot_confusion_matrix(y_test,y_pred, model_name='Model'): """ This plots a beautiful confusion matrix based on input: ground truths and predictions """ #Confusion Matrix '''Plotting CONFUSION MATRIX''' import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') '''Display''' from IPython.core.display import display, HTML display(HTML("<style>.container { width:95% !important; }</style>")) pd.options.display.float_format = '{:,.2f}'.format #Get the confusion matrix and put it into a df from sklearn.metrics import confusion_matrix, f1_score cm = confusion_matrix(y_test, y_pred) cm_df = pd.DataFrame(cm, index = np.unique(y_test).tolist(), columns = np.unique(y_test).tolist(), ) #Plot the heatmap plt.figure(figsize=(12, 8)) sns.heatmap(cm_df, center=0, cmap=sns.diverging_palette(220, 15, as_cmap=True), annot=True, fmt='g') plt.title(' %s \nF1 Score(avg = micro): %0.2f \nF1 Score(avg = macro): %0.2f' %( model_name,f1_score(y_test, y_pred, average='micro'),f1_score(y_test, y_pred, average='macro')), fontsize = 13) plt.ylabel('True label', fontsize = 13) plt.xlabel('Predicted label', fontsize = 13) plt.show(); ##############################################################################################
Example #29
Source File: local_parameter_importance.py From CAVE with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_jupyter(self): from IPython.core.display import HTML, display display(HTML(figure_to_html(self.get_plots(), max_in_a_row=3, true_break_between_rows=True))) if self.runscontainer.analyzing_options['Parameter Importance'].getboolean('whisker_quantiles_plot'): output_notebook() show(self.plot_whiskers())
Example #30
Source File: ipython.py From executing with MIT License | 5 votes |
def eye(self, _line, cell): if not self.server_url: server.db = Database(self.db_url) server.Function = server.db.Function server.Call = server.db.Call server.Session = server.db.Session Thread( target=run_server, args=( self.port, self.bind_host, self.show_server_output, ), ).start() eye.db = Database(self.db_url) def callback(call_id): """ Always executes after the cell, whether or not an exception is raised in the user code. """ if call_id is None: # probably means a bug return html = HTML(templates_env.get_template('ipython_iframe.html').render( call_id=call_id, url=self.server_url.rstrip('/'), port=self.port, container_id=uuid4().hex, )) # noinspection PyTypeChecker display(html) value = eye.exec_ipython_cell(cell, callback) # Display the value as would happen if the %eye magic wasn't there return value