Python IPython.display.display() Examples
The following are 30
code examples of IPython.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.display
, or try the search function
.
Example #1
Source File: __init__.py From paramnb with BSD 3-Clause "New" or "Revised" License | 7 votes |
def run_next_cells(n): if n=='all': n = 'NaN' elif n<1: return js_code = """ var num = {0}; var run = false; var current = $(this)[0]; $.each(IPython.notebook.get_cells(), function (idx, cell) {{ if ((cell.output_area === current) && !run) {{ run = true; }} else if ((cell.cell_type == 'code') && !(num < 1) && run) {{ cell.execute(); num = num - 1; }} }}); """.format(n) display(Javascript(js_code))
Example #2
Source File: drawTopicModel.py From CheTo with BSD 3-Clause "New" or "Revised" License | 7 votes |
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
Example #3
Source File: test_display.py From altair with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_render_options(**options): """ Context manager that will assert that alt.renderers.options are equivalent to the given options in the IPython.display.display call """ import IPython.display def check_options(obj): assert alt.renderers.options == options _display = IPython.display.display IPython.display.display = check_options try: yield finally: IPython.display.display = _display
Example #4
Source File: state.py From evo-pawness with GNU General Public License v3.0 | 6 votes |
def print_board(self): """ Print the board with the help of pandas DataFrame.. Well it sounds stupid.. anyway, it has a nice display, right? :return: """ df_pr = [[None for i in range(self.board_size)] for j in range(self.board_size)] pd.options.display.max_columns = 10 pd.options.display.max_rows = 1000 pd.options.display.width = 1000 for i in range(self.board_size): for j in range(self.board_size): need_to_pass = False for rune in self.rune_list: # Print the rune if present if j == rune.x and i == rune.y: # print(rune, end=' ') df_pr[i][j] = "Rune" need_to_pass = True pass if not need_to_pass: if self.board[j][i] is not None and self.board[j][i].dead == False: df_pr[i][j] = self.board[j][i].__repr__() else: df_pr[i][j] = "Nones" display(pd.DataFrame(df_pr))
Example #5
Source File: display_util.py From data-validation with Apache License 2.0 | 6 votes |
def visualize_statistics( lhs_statistics: statistics_pb2.DatasetFeatureStatisticsList, rhs_statistics: Optional[ statistics_pb2.DatasetFeatureStatisticsList] = None, lhs_name: Text = 'lhs_statistics', rhs_name: Text = 'rhs_statistics') -> None: """Visualize the input statistics using Facets. Args: lhs_statistics: A DatasetFeatureStatisticsList protocol buffer. rhs_statistics: An optional DatasetFeatureStatisticsList protocol buffer to compare with lhs_statistics. lhs_name: Name of the lhs_statistics dataset. rhs_name: Name of the rhs_statistics dataset. Raises: TypeError: If the input argument is not of the expected type. ValueError: If the input statistics protos does not have only one dataset. """ html = get_statistics_html(lhs_statistics, rhs_statistics, lhs_name, rhs_name) display(HTML(html))
Example #6
Source File: zmqshell.py From Computable with MIT License | 6 votes |
def autosave(self, arg_s): """Set the autosave interval in the notebook (in seconds). The default value is 120, or two minutes. ``%autosave 0`` will disable autosave. This magic only has an effect when called from the notebook interface. It has no effect when called in a startup file. """ try: interval = int(arg_s) except ValueError: raise UsageError("%%autosave requires an integer, got %r" % arg_s) # javascript wants milliseconds milliseconds = 1000 * interval display(Javascript("IPython.notebook.set_autosave_interval(%i)" % milliseconds), include=['application/javascript'] ) if interval: print("Autosaving every %i seconds" % interval) else: print("Autosave disabled")
Example #7
Source File: nbinit.py From msticpy with MIT License | 6 votes |
def _imp_from_package( nm_spc: Dict[str, Any], pkg: str, tgt: str = None, alias: str = None ): """Import object or submodule from `pkg`.""" if not tgt: return _imp_module(nm_spc=nm_spc, module_name=pkg, alias=alias) try: # target could be a module obj = importlib.import_module(f".{tgt}", pkg) except (ImportError, ModuleNotFoundError): # if not, it must be an attribute (class, func, etc.) try: mod = importlib.import_module(pkg) except ImportError: display(HTML(_IMPORT_MODULE_MSSG.format(module=pkg))) raise obj = getattr(mod, tgt) if alias: nm_spc[alias] = obj else: nm_spc[tgt] = obj if _VERBOSE(): # type: ignore print(f"{tgt} imported from {pkg} (alias={alias})") return obj
Example #8
Source File: Reinforcement Learning DQN.py From ML_CIA with MIT License | 6 votes |
def plot_durations(): plt.figure(2) plt.clf() durations_t = torch.tensor(episode_durations, dtype=torch.float) plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(durations_t.numpy()) # Take 100 episode averages and plot them too if len(durations_t) >= 100: means = durations_t.unfold(0, 100, 1).mean(1).view(-1) means = torch.cat((torch.zeros(99), means)) plt.plot(means.numpy()) plt.pause(0.001) if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) #%% Training loop
Example #9
Source File: drawTopicModel.py From CheTo with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #10
Source File: nbinit.py From msticpy with MIT License | 6 votes |
def _check_config() -> Tuple[bool, Optional[Tuple[List[str], List[str]]]]: config_ok = True err_warn = None mp_path = os.environ.get("MSTICPYCONFIG", "./msticpyconfig.yaml") if not Path(mp_path).exists(): display(HTML(_MISSING_MPCONFIG_ERR)) else: err_warn = validate_config(config_file=mp_path) if err_warn and err_warn[0]: config_ok = False ws_config = WorkspaceConfig() if not ws_config.config_loaded: print("No valid configuration for Azure Sentinel found.") config_ok = False return config_ok, err_warn
Example #11
Source File: gui.py From pyiron with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, project): self._ref_path = project.path self.project = project.copy() self.project._inspect_mode = True self.parent = None self.name = None self.fig, self.ax = None, None self.w_group = None self.w_node = None self.w_file = None self.w_text = None self.w_tab = None self.w_path = None self.w_type = None # self.fig, self.ax = plt.subplots() self.create_widgets() self.connect_widgets() self.display()
Example #12
Source File: nbwidgets.py From msticpy with MIT License | 6 votes |
def _run_action(self): """Run any action function and display details, if any.""" output_objs = self.item_action(self.value) if output_objs is None: return if not isinstance(output_objs, (tuple, list)): output_objs = [output_objs] display_objs = bool(self._disp_elems) for idx, out_obj in enumerate(output_objs): if not display_objs: self._disp_elems.append( display(out_obj, display_id=f"{self._output_id}_{idx}") ) else: if idx == len(self._disp_elems): break self._disp_elems[idx].update(out_obj)
Example #13
Source File: notebook.py From rsmtool with Apache License 2.0 | 5 votes |
def bold_highlighter(num, low=0, high=1, prec=3, absolute=False): """ Instantiating ``custom_highlighter()`` with the ``bold`` class as the default. Parameters: ----------- num : float The floating point number to format. low : float The number will be displayed as an HTML span it is below this value. Defaults to 0. high : float The number will be displayed as an HTML span it is above this value. Defaults to 1. prec : int The number of decimal places to display for x. Defaults to 3. absolute: bool If True, use the absolute value of x for comparison. Defaults to False. Returns: -------- ans : str The formatted highlighter with bold class as default. """ ans = custom_highlighter(num, low, high, prec, absolute, 'bold') return ans
Example #14
Source File: notebook.py From rsmtool with Apache License 2.0 | 5 votes |
def show_thumbnail(path_to_image, image_id, path_to_thumbnail=None): """ Given an path to an image file, display a click-able thumbnail version of the image. On click, open the full-sized version of the image in a new window. Parameters ---------- path_to_image : str The absolute or relative path to the image. If an absolute path is provided, it will be converted to a relative path. image_id : int The id of the <img> tag in the HTML. This must be unique for each <img> tag. path_to_thumbnail : str or None, optional If you would like to use a different thumbnail image, specify the path to the thumbnail. Defaults to None. Displays -------- display : IPython.core.display.HTML The HTML display of the thumbnail image. """ display(HTML(get_thumbnail_as_html(path_to_image, image_id, path_to_thumbnail)))
Example #15
Source File: notebook.py From rsmtool with Apache License 2.0 | 5 votes |
def color_highlighter(num, low=0, high=1, prec=3, absolute=False): """ Instantiating ``custom_highlighter()`` with the ``color`` class as the default. Parameters: ----------- num : float The floating point number to format. low : float The number will be displayed as an HTML span it is below this value. Defaults to 0. high : float The number will be displayed as an HTML span it is above this value. Defaults to 1. prec : int The number of decimal places to display for x. Defaults to 3. absolute: bool If True, use the absolute value of x for comparison. Defaults to False. Returns: -------- ans : str The formatted highlighter with color class as default. """ ans = custom_highlighter(num, low, high, prec, absolute, 'color') return ans
Example #16
Source File: gui.py From pyiron with BSD 3-Clause "New" or "Revised" License | 5 votes |
def display(self): """ Returns: """ w_txt = widgets.HBox([self.w_path, self.w_type]) display(widgets.VBox([self.w_tab, w_txt]))
Example #17
Source File: nbwidgets.py From msticpy with MIT License | 5 votes |
def _ipython_display_(self): """Display in IPython.""" self.display()
Example #18
Source File: notebook.py From rsmtool with Apache License 2.0 | 5 votes |
def custom_highlighter(num, low=0, high=1, prec=3, absolute=False, span_class='bold'): """ Return the supplied float as an HTML <span> element with the specified class if its value is below ``low`` or above ``high``. If its value does not meet those constraints, then return as a plain string with the specified number of decimal places. Parameters: ----------- num : float The floating point number to format. low : float The number will be displayed as an HTML span it is below this value. Defaults to 0. high : float The number will be displayed as an HTML span it is above this value. Defaults to 1. prec : int The number of decimal places to display for x. Defaults to 3. absolute: bool If True, use the absolute value of x for comparison. Defaults to False. span_class: str One of ``bold`` or ``color``. These are the two classes available for the HTML span tag. Returns: -------- ans : str The formatted (plain or HTML) string representing the given number. """ abs_num = abs(num) if absolute else num val = float_format_func(num, prec=prec) ans = ('<span class="highlight_{}">{}</span>'.format(span_class, val) if abs_num < low or abs_num > high else val) return ans
Example #19
Source File: display_util.py From data-validation with Apache License 2.0 | 5 votes |
def display_anomalies(anomalies: anomalies_pb2.Anomalies) -> None: """Displays the input anomalies. Args: anomalies: An Anomalies protocol buffer. """ if not isinstance(anomalies, anomalies_pb2.Anomalies): raise TypeError('anomalies is of type %s, should be an Anomalies proto.' % type(anomalies).__name__) anomaly_rows = [] for feature_name, anomaly_info in anomalies.anomaly_info.items(): anomaly_rows.append([ _add_quotes(feature_name), anomaly_info.short_description, anomaly_info.description ]) if anomalies.HasField('dataset_anomaly_info'): anomaly_rows.append([ '[dataset anomaly]', anomalies.dataset_anomaly_info.short_description, anomalies.dataset_anomaly_info.description ]) if not anomaly_rows: display(HTML('<h4 style="color:green;">No anomalies found.</h4>')) else: # Construct a DataFrame consisting of the anomalies and display it. anomalies_df = pd.DataFrame( anomaly_rows, columns=['Feature name', 'Anomaly short description', 'Anomaly long description']).set_index('Feature name') # Do not truncate columns. pd.set_option('max_colwidth', -1) display(anomalies_df)
Example #20
Source File: labeled_trees.py From pytreebank with MIT License | 5 votes |
def display(self): from IPython.display import Javascript, display display(Javascript("createTrees(["+self.to_json()+"])")) display(Javascript("updateTrees()"))
Example #21
Source File: labeled_trees.py From pytreebank with MIT License | 5 votes |
def to_dict(self, index=0): """ Dict format for use in Javascript / Jason Chuang's display technology. """ index += 1 rep = {} rep["index"] = index rep["leaf"] = len(self.children) == 0 rep["depth"] = self.udepth rep["scoreDistr"] = [0.0] * len(LabeledTree.SCORE_MAPPING) # dirac distribution at correct label if self.label is not None: rep["scoreDistr"][self.label] = 1.0 mapping = LabeledTree.SCORE_MAPPING[:] rep["rating"] = mapping[self.label] - min(mapping) # if you are using this method for printing predictions # from a model, the the dot product with the model's output # distribution should be taken with this list: rep["numChildren"] = len(self.children) text = self.text if self.text != None else "" seen_tokens = 0 witnessed_pixels = 0 for i, child in enumerate(self.children): if i > 0: text += " " child_key = "child%d" % (i) (rep[child_key], index) = child.to_dict(index) text += rep[child_key]["text"] seen_tokens += rep[child_key]["tokens"] witnessed_pixels += rep[child_key]["pixels"] rep["text"] = text rep["tokens"] = 1 if (self.text != None and len(self.text) > 0) else seen_tokens rep["pixels"] = witnessed_pixels + 3 if len(self.children) > 0 else text_size(self.text) return (rep, index)
Example #22
Source File: TreeVisualizer.py From pdftotree with MIT License | 5 votes |
def display_candidates(self, tree, html_path, filename_prefix): """ Displays the bounding boxes corresponding to candidates on an image of the pdf boxes is a list of 5-tuples (page, top, left, bottom, right) """ imgs = self.display_boxes( tree, html_path, filename_prefix, alternate_colors=True ) return display(*imgs)
Example #23
Source File: observationlist.py From msticpy with MIT License | 5 votes |
def display_observations(self): """Display the current observations using IPython.display.""" for observation in self.observation_list.values(): display(Markdown(f"### {observation.caption}")) display(Markdown(observation.description)) display(Markdown(f"Score: {observation.score}")) if observation.link: display(Markdown(f"[Go to details](#{observation.link})")) if observation.tags: display(Markdown(f'tags: {", ".join(observation.tags)}')) display(observation.data) if observation.additional_properties: display(Markdown("### Additional Properties")) for key, val in observation.additional_properties.items(): display(Markdown(f"**{key}**: {val}"))
Example #24
Source File: nbinit.py From msticpy with MIT License | 5 votes |
def _imp_module_all(nm_spc: Dict[str, Any], module_name): """Import all from named module add to globals.""" try: imported_mod = importlib.import_module(module_name) except ImportError: display(HTML(_IMPORT_MODULE_MSSG.format(module=module_name))) raise for item in dir(imported_mod): if item.startswith("_"): continue nm_spc[item] = getattr(imported_mod, item) if _VERBOSE(): # type: ignore print(f"All items imported from {module_name}")
Example #25
Source File: nbinit.py From msticpy with MIT License | 5 votes |
def _imp_module(nm_spc: Dict[str, Any], module_name: str, alias: str = None): """Import named module and assign to global alias.""" try: mod = importlib.import_module(module_name) except ImportError: display(HTML(_IMPORT_MODULE_MSSG.format(module=module_name))) raise if alias: nm_spc[alias] = mod else: nm_spc[module_name] = mod if _VERBOSE(): # type: ignore print(f"{module_name} imported (alias={alias})") return mod
Example #26
Source File: nbinit.py From msticpy with MIT License | 5 votes |
def _set_nb_options(namespace): namespace["WIDGET_DEFAULTS"] = { "layout": widgets.Layout(width="95%"), "style": {"description_width": "initial"}, } # Some of our dependencies (networkx) still use deprecated Matplotlib # APIs - we can't do anything about it, so suppress them from view warnings.simplefilter("ignore", category=MatplotlibDeprecationWarning) warnings.filterwarnings("ignore", category=DeprecationWarning) sns.set() pd.set_option("display.max_rows", 100) pd.set_option("display.max_columns", 50) pd.set_option("display.max_colwidth", 100) os.environ["KQLMAGIC_LOAD_MODE"] = "silent"
Example #27
Source File: nbwidgets.py From msticpy with MIT License | 5 votes |
def _ipython_display_(self): """Display in IPython.""" self.display()
Example #28
Source File: nbwidgets.py From msticpy with MIT License | 5 votes |
def display(self): """Display the control.""" display(self.layout)
Example #29
Source File: nbwidgets.py From msticpy with MIT License | 5 votes |
def __init__(self, completed_len: int, visible: bool = True): """ Instantiate new _Progress UI. Parameters ---------- completed_len : int The expected value that indicates 100% done. visible : bool If True start the progress UI visible, by default True. """ self._completed = 0 self._total = completed_len self._progress = widgets.IntProgress( value=0, max=100, step=1, description="Progress:", bar_style="info", orientation="horizontal", ) self._done_label = widgets.Label(value="0%") self._progress.visible = visible self._done_label.visible = visible self.layout = widgets.HBox([self._progress, self._done_label]) self.display()
Example #30
Source File: nbwidgets.py From msticpy with MIT License | 5 votes |
def _ipython_display_(self): """Display in IPython.""" self.display()