def custom_exc(shell, etype, evalue, tb, tb_offset=None): '''this function will be called on exceptions in any cell ''' # still show the error within the notebook, don't just swallow it shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset) # initialize the formatter for making the tracebacks into strings itb = AutoFormattedTB(mode='Plain', tb_offset=1, color_scheme='NoColor') # grab the traceback and make it into a list of strings stb = itb.structured_traceback(etype, evalue, tb) sstb = itb.stb2text(stb) notify(sstb)
def _init(self): """Common initialization for all BackgroundJob objects""" for attr in ['call', 'strform']: assert hasattr(self, attr), "Missing attribute <%s>" % attr # The num tag can be set by an external job manager self.num = None self.status = BackgroundJobBase.stat_created self.stat_code = BackgroundJobBase.stat_created_c self.finished = False self.result = '<BackgroundJob has not completed>' # reuse the ipython traceback handler if we can get to it, otherwise # make a new one try: make_tb = get_ipython().InteractiveTB.text except: make_tb = AutoFormattedTB(mode='Context', color_scheme='NoColor', tb_offset=1).text # Note that the actual API for text() requires the three args to be # passed in, so we wrap it in a simple lambda. self._make_tb = lambda: make_tb(None, None, None) # Hold a formatted traceback if one is generated. self._tb = None threading.Thread.__init__(self)
def _init(self): """Common initialization for all BackgroundJob objects""" for attr in ['call', 'strform']: assert hasattr(self, attr), "Missing attribute <%s>" % attr # The num tag can be set by an external job manager self.num = None self.status = BackgroundJobBase.stat_created self.stat_code = BackgroundJobBase.stat_created_c self.finished = False self.result = '<BackgroundJob has not completed>' # reuse the ipython traceback handler if we can get to it, otherwise # make a new one try: self._make_tb = __IPYTHON__.InteractiveTB.text except: self._make_tb = AutoFormattedTB(mode='Context', color_scheme='NoColor', tb_offset=1).text # Hold a formatted traceback if one is generated. self._tb = None threading.Thread.__init__(self)
def _render_traceback_(self): # pragma: no cover """Render a minimized version of the `StateError` traceback. The default Jupyter/IPython traceback includes a lot of context from within `State` where the `StateError` is raised. This context isn't really needed, since the problem is almost certainly in the user code. This function removes the additional context. """ if AutoFormattedTB is not None: a = AutoFormattedTB(mode="Context", color_scheme="Neutral", tb_offset=1) etype, evalue, tb = sys.exc_info() stb = a.structured_traceback(etype, evalue, tb, tb_offset=1) for i, line in enumerate(stb): if "site-packages" in line: first_line = i break return stb[:first_line] + stb[-1:]
def render_traceback(self): """Render a minimized version of the DimensionalityError traceback. The default Jupyter/IPython traceback includes a lot of context from within pint that actually raises the DimensionalityError. This context isn't really needed for this particular error, since the problem is almost certainly in the user code. This function removes the additional context. """ a = AutoFormattedTB(mode="Context", color_scheme="Neutral", tb_offset=1) etype, evalue, tb = sys.exc_info() stb = a.structured_traceback(etype, evalue, tb, tb_offset=1) for i, line in enumerate(stb): if "site-packages" in line: first_line = i break return stb[:first_line] + stb[-1:]
def setup_exceptions(): scheme = terminal_bg('LightBG', 'Linux', 'Neutral') mode = 'Plain' if 'DEBUG' in os.environ: mode = 'Verbose' try: from IPython.core.ultratb import AutoFormattedTB sys.excepthook = AutoFormattedTB(mode=mode, color_scheme=scheme) except ImportError: pass
def setup_exceptions(): switch = { BGColor.LIGHT: 'LightBG', BGColor.DARK: 'Linux', BGColor.UNKNOWN: 'Neutral' } scheme = switch[terminal_bg()] mode = 'Plain' if 'DEBUG' in os.environ: mode = 'Verbose' try: from IPython.core.ultratb import AutoFormattedTB sys.excepthook = AutoFormattedTB(mode=mode, color_scheme=scheme) except ImportError: pass
def wrapped(element): global FULL_TRACEBACK optstate = StoreOptions.state(element) try: html = fn(element, max_frames=OutputMagic.options['max_frames'], max_branches=OutputMagic.options['max_branches']) # Only want to add to the archive for one display hook... disabled_suffixes = ['png_display', 'svg_display'] if not any( fn.__name__.endswith(suffix) for suffix in disabled_suffixes): holoviews.archive.add(element, html=html) filename = OutputMagic.options['filename'] if filename: Store.renderers[Store.current_backend].save(element, filename) return html except SkipRendering as e: sys.stderr.write("Rendering process skipped: %s" % str(e)) return None except Exception as e: try: StoreOptions.state(element, state=optstate) frame = inspect.trace()[-1] mod = inspect.getmodule(frame[0]) module = (mod.__name__ if mod else frame[1]).split('.')[0] backends = Store.renderers.keys() abbreviate = isinstance(e, BackendError) or module in backends if ABBREVIATE_TRACEBACKS and abbreviate: AutoTB = AutoFormattedTB(mode='Verbose', color_scheme='Linux') buff = io.StringIO() AutoTB(out=buff) buff.seek(0) FULL_TRACEBACK = buff.read() info = dict(name=type(e).__name__, message=str(e).replace('\n', '<br>')) msg = '<i> [Call ipython.show_traceback() for details]</i>' return "<b>{name}</b>{msg}<br>{message}".format(msg=msg, **info) except: FULL_TRACEBACK = traceback.format_exc() msg = ('<i>Error catching exception:</i> %r <br>' 'Call ipython.show_traceback() for details') return msg % e raise e
def structured_traceback(self, type, value, tb, tb_offset=None, *args, **kwargs): # If an offset is given, use it, else use the default offset = tb_offset if tb_offset else self.tb_offset ftb = AutoFormattedTB.structured_traceback(self, type, value, tb, offset, *args, **kwargs) if _traceback_verbose: return ftb else: length = vcsn_traceback_levels(tb) # Display the 2 header entries plus `length` entries # minus the entries that were offset, and the footer entry. return ftb[:2 + length - offset] + ftb[-1:]
if return_hexdigest: return file_hash.hexdigest() else: return file_hash # ###################################################################### # Handy things to print the traceback of exceptions # ###################################################################### # initialize the formatter for making the tracebacks into strings # mode = 'Plain' # for printing like in the interactive python traceback # TODO: Not sure if this line needs to be run in the highest level # python file in order to get a full traceback itb = AutoFormattedTB(mode="Verbose", tb_offset=None) def print_exception(): """ Prints the output of get_formatted_exception() """ # This should print the same output, not sure when nesting code # itb() print(get_formatted_exception()) def get_formatted_exception(): """ Retunr the last exception in a beautiful rainbow with extra sugar and a cherry on top
"""Benchmarks different optimization methods for gamut mapping.""" from functools import partial import time import numpy as np from scipy import optimize import cam try: import sys from IPython.core.ultratb import AutoFormattedTB sys.excepthook = AutoFormattedTB('Plain', 'Neutral') except ImportError: pass def proj(x): """Projects x onto the feasible set.""" return np.clip(x, 0, 1) def grad(loss, x): """Computes the gradient of loss at x using finite differences.""" return optimize.approx_fprime(x, loss, 1e-8) def method_lbfgsb(rgb, loss):
state0_i=pl[0].name, state1_i=pl[1].name, byte_i=pl[0].name, byte_o=pl[-1].name, byte0_i=pl[0].name, byte1_i=pl[1].name, s=max(map(lambda p:len(p.name), pl)), ) bench_file = Bench( path=bench_path, template=template_path.read_text(), format_param=format_param ) bench_file.write() if __name__ == "__main__": try: main() except Exception: # import traceback # traceback.print_exc() from IPython.core.ultratb import AutoFormattedTB AutoFormattedTB(mode="Verbose")() import pdb pdb.post_mortem()
if key not in keys_set: if isinstance(value, MutableMapping): modified_dict[key] = delete_keys_from_dict(value, keys_set) else: modified_dict[key] = value return modified_dict # Handy things to print the traceback of exceptions # initialize the formatter for making the tracebacks into strings # mode = 'Plain' # for printing like in the interactive python traceback # TODO: Not sure if this line needs to be run in the highest level # python file in order to get a full traceback itb = AutoFormattedTB(mode='Verbose', tb_offset=None) def print_exception(): """ Prints the output of get_formatted_exception() """ # This should print the same output, not sure when nesting code # itb() print(get_formatted_exception()) def get_formatted_exception(): """ Retunr the last exception in a beautiful rainbow with extra sugar and a cherry on top
import torch.nn as nn from torch import Tensor import torch import time from IPython import get_ipython from typing import * # Live plotting stuff import seaborn as sns sns.set_style('whitegrid') custom = sns.color_palette("Paired", 9) sns.set_palette(custom) sns.set() plt.ion() __ITB__ = AutoFormattedTB(mode='Verbose', color_scheme='LightBg', tb_offset=1) assert torch.cuda.is_available( ), "You need to request a GPU from Runtime > Change Runtime" # %% """ ########################### DOWNLOAD DATASET ##################################### """ class CancerDataset(Dataset): def __init__(self, root, download=True, size=512, train=True): if download and not os.path.exists(os.path.join(root, 'cancer_data')): datasets.utils.download_url( 'http://liftothers.org/cancer_data.tar.gz', root,
parser.add_argument("-r", "--rate", type = float, default = 5., help = 'Playback speed') parser.add_argument("-s", "--qsize", type = int, default = 100, help = 'Queue size') parser.add_argument("-b", "--backend", choices = ["qt", "tk", "mp4", "qt+vlc", 'template'], default = "qt+vlc", help = 'GUI backend') parser.add_argument("-o", "--output", default = None, help = 'Output file name. <BACKEND> will be set to mp4 if not None.') parser.add_argument("f", nargs = "+", type = str, help = 'Input file name.') parser.add_argument("-a", "--aspect", default = '4X3', help = "Aspect ratio. Only affect when outputing mp4")#, choices = ['16X9', '4X3', '9X16']) parser.add_argument('--dpi', type = int, default = 300, help = 'DPI. Only affect when outputing mp4') try: import argcomplete argcomplete.autocomplete(parser) except ImportError: pass try: import sys from IPython.core.ultratb import AutoFormattedTB sys.excepthook = AutoFormattedTB() except ImportError: print ('IPython is not installed. Colored Traceback will not be populated.') args = parser.parse_args() # upper left corner coordinates of app window if args.output is not None: args.backend = 'mp4' if args.backend in ("qt", "qt+vlc"): import GUIPyQt GUIPyQt.__VLC__ = 'vlc' in args.backend from PyQt5.QtWidgets import QApplication a = QApplication([]) app = GUIPyQt.App(args.f, args.delay, rate = args.rate, qsize = args.qsize) app.setGeometry(20, 20, 1024, 768) app.show_slides()
""" Huge kudos to https://stackoverflow.com/a/40135960 """ import socket from IPython.core.ultratb import AutoFormattedTB from tomo2seg import slack # formatter for making the tracebacks into strings itb = AutoFormattedTB(mode='Plain', tb_offset=1) # this function will be called on exceptions in any cell def custom_exc(shell, etype, evalue, tb, tb_offset=None): # still show the error within the notebook, don't just swallow it shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset) # grab the traceback and make it into a list of strings stb = itb.structured_traceback(etype, evalue, tb) sstb = itb.stb2text(stb) hostname = socket.gethostname() sstb = f"An exception occurred in {hostname=}\n\n" + sstb slack.notify(sstb)