Find the values of the local variables within the traceback scope.

    :param tb: traceback
    :return: list of tuples containing (variable name, value)
169301
def get_local_references(tb, max_string_length=1000):
    
    if 'self' in tb.tb_frame.f_locals:
        _locals = [('self', repr(tb.tb_frame.f_locals['self']))]
    else:
        _locals = []
    for k, v in tb.tb_frame.f_locals.iteritems():
        if k == 'self':
            continue
        try:
            vstr = format_reference(v, max_string_length=max_string_length)
            _locals.append((k, vstr))
        except TypeError:
            pass
    return _locals
417761
def debug_on_error(type, value, tb):
    """"""
    traceback.print_exc(type, value, tb)
    print()
    pdb.pm()
634866
def asString(self, strict=False):
        
        if len(self.keys())==0:
            return "origin"
        v = []
        n = []
        try:
            for name, value in self.asTuple():
                s = ''
                if value is None:
                    s = "None"
                elif type(value) == tuple or type(value) == list:
                    s = "(%.3f,%.3f)"%(value[0], value[1])
                elif int(value) == value:
                    s = "%d"%(int(value))
                else:
                    s = "%.3f"%(value)
                if s != '':
                    n.append("%s:%s"%(name, s))
            return ", ".join(n)
        except TypeError:
            import traceback
            print("Location value error:", name, value)
            for key, value in self.items():
                print("\t\tkey:", key)
                print("\t\tvalue:", value)
            traceback.print_exc()
            return "error"
562121
def trace(self, trace_obj):
        
        tracer = self
        tracer.writeln(u'%s = ' % trace_obj.__class__.__name__)
        tracer.incr('{')
        for attr_name in trace_obj.__tracing_attrs__:
            attr = getattr(trace_obj, attr_name)
            if isinstance(attr, tuple) and hasattr(attr, '_fields'):
                # probably a namedtuple instance
                tracer.writeln(u'%s = ' % (attr_name,))
                tracer.incr('[')
                for k, v in attr._asdict().items():
                    # _asdict() creates an OrderedDict, so elements are still in order
                    tracer.writeln(u'%s = %s' % (k, v))
                tracer.decr(']')
            elif isinstance(attr, (list, tuple)):
                if attr:
                    tracer.writeln(u'%s = ' % (attr_name,))
                    tracer.incr('[')
                    for elem in attr:
                        if hasattr(elem, '__tracing_attrs__'):
                            self.trace(elem)
                        else:
                            # some other plain list element, just print it as it is:
                            tracer.writeln(u'%s' % repr(elem))
                    tracer.decr(']')
                else:
                    tracer.writeln(u'%s = []' % (attr_name,))
            else:
                # a plain attribute object, just print it as it is
                tracer.writeln(u'%s = %s' % (attr_name, repr(attr)))
        tracer.decr('}')
        return self.getvalue()
491603
def analyze_traceback(tb, inspection_level=None, limit=None):
    
    info = []
    tb_level = tb
    extracted_tb = traceback.extract_tb(tb, limit=limit)
    for ii, (filepath, line, module, code) in enumerate(extracted_tb):
        func_source, func_lineno = inspect.getsourcelines(tb_level.tb_frame)

        d = {"File": filepath,
             "Error Line Number": line,
             "Module": module,
             "Error Line": code,
             "Module Line Number": func_lineno,
             "Custom Inspection": {},
             "Source Code": ''}
        if inspection_level is None or len(extracted_tb) - ii <= inspection_level:
            # Perform advanced inspection on the last `inspection_level` tracebacks.
            d['Source Code'] = ''.join(func_source)
            d['Local Variables'] = get_local_references(tb_level)
            d['Object Variables'] = get_object_references(tb_level, d['Source Code'])
        tb_level = getattr(tb_level, 'tb_next', None)
        info.append(d)

    return info
818990
def __get_values(self):
        
        array = self._get_target().getDataArray()
        return tuple(itertools.chain.from_iterable(array))
693608
def from_traceback(cls, tb):
        
        while tb.tb_next:
            tb = tb.tb_next
        return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti)
231958
def get_localvariabletable(self):
          # noqa

        buff = self.get_attribute("LocalVariableTable")
        if buff is None:
            return tuple()

        with unpack(buff) as up:
            return tuple(up.unpack_struct_array(_HHHHH))
929407
def check_variable_names(self, ds):
        
        msgs = []
        count = 0

        for k, v in ds.variables.items():
            if 'standard_name' in v.ncattrs():
                count += 1
            else:
                msgs.append("Variable '{}' missing standard_name attr".format(k))

        return Result(BaseCheck.MEDIUM, (count, len(ds.variables)), 'Variable Names', msgs)
893615
def _shadow_model_variables(shadow_vars):
        
        G = tf.get_default_graph()
        curr_shadow_vars = set([v.name for v in shadow_vars])
        model_vars = tf.model_variables()
        shadow_model_vars = []
        for v in model_vars:
            assert v.name.startswith('tower'), "Found some MODEL_VARIABLES created outside of the tower function!"
            stripped_op_name, stripped_var_name = get_op_tensor_name(re.sub('^tower[0-9]+/', '', v.name))
            if stripped_op_name in curr_shadow_vars:
                continue
            try:
                G.get_tensor_by_name(stripped_var_name)
                logger.warn("Model Variable {} also appears in other collections.".format(stripped_var_name))
                continue
            except KeyError:
                pass
            new_v = tf.get_variable(stripped_op_name, dtype=v.dtype.base_dtype,
                                    initializer=v.initial_value,
                                    trainable=False)

            curr_shadow_vars.add(stripped_op_name)  # avoid duplicated shadow_model_vars
            shadow_vars.append(new_v)
            shadow_model_vars.append((new_v, v))  # only need to sync model_var from one tower
        return shadow_model_vars
1116966
def _read_var_data(self):
        

        var_bundles = OrderedDict()
        var_attrs = OrderedDict()

        n_vars = 0

        while self.fp.tell() < self.fsize:

            var_attr = OrderedDict()

            # read first and second header lines
            line = self.fp.readline('20sffii')
            modelname, res0, res1, halfpolar, center180 = line

            line = self.fp.readline('40si40sdd40s7i')
            category_name, number, unit, tau0, tau1, reserved = line[:6]
            dim0, dim1, dim2, dim3, dim4, dim5, skip = line[6:]
            var_attr['number'] = number

            # Decode byte-strings to utf-8
            category_name = str(category_name, 'utf-8')
            var_attr['category'] = category_name.strip()
            unit = str(unit, 'utf-8')

            # get additional metadata from tracerinfo / diaginfo
            try:
                cat_df = self.diaginfo_df[
                    self.diaginfo_df.name == category_name.strip()
                ]
                # TODO: Safer logic for handling case where more than one
                #       tracer metadata match was made
                # if len(cat_df > 1):
                #     raise ValueError(
                #         "More than one category matching {} found in "
                #         "diaginfo.dat".format(
                #             category_name.strip()
                #         )
                #     )
                # Safe now to select the only row in the DataFrame
                cat = cat_df.T.squeeze()

                tracer_num = int(cat.offset) + int(number)
                diag_df = self.tracerinfo_df[
                    self.tracerinfo_df.tracer == tracer_num
                ]
                # TODO: Safer logic for handling case where more than one
                #       tracer metadata match was made
                # if len(diag_df > 1):
                #     raise ValueError(
                #         "More than one tracer matching {:d} found in "
                #         "tracerinfo.dat".format(tracer_num)
                #     )
                # Safe now to select only row in the DataFrame
                diag = diag_df.T.squeeze()
                diag_attr = diag.to_dict()

                if not unit.strip():  # unit may be empty in bpch
                    unit = diag_attr['unit']  # but not in tracerinfo
                var_attr.update(diag_attr)
            except:
                diag = {'name': '', 'scale': 1}
                var_attr.update(diag)
            var_attr['unit'] = unit

            vname = diag['name']
            fullname = category_name.strip() + "_" + vname

            # parse metadata, get data or set a data proxy
            if dim2 == 1:
                data_shape = (dim0, dim1)         # 2D field
            else:
                data_shape = (dim0, dim1, dim2)
            var_attr['original_shape'] = data_shape

            # Add proxy time dimension to shape
            data_shape = tuple([1, ] + list(data_shape))
            origin = (dim3, dim4, dim5)
            var_attr['origin'] = origin

            timelo, timehi = cf.tau2time(tau0), cf.tau2time(tau1)

            pos = self.fp.tell()
            # Note that we don't pass a dtype, and assume everything is
            # single-fp floats with the correct endian, as hard-coded
            var_bundle = BPCHDataBundle(
                data_shape, self.endian, self.filename, pos, [timelo, timehi],
                metadata=var_attr,
                use_mmap=self.use_mmap, dask_delayed=self.dask_delayed
            )
            self.fp.skipline()

            # Save the data as a "bundle" for concatenating in the final step
            if fullname in var_bundles:
                var_bundles[fullname].append(var_bundle)
            else:
                var_bundles[fullname] = [var_bundle, ]
                var_attrs[fullname] = var_attr
                n_vars += 1

        self.var_data = var_bundles
        self.var_attrs = var_attrs
358057
def _extract_traceback(start):
    
    tb = sys.exc_info()[2]
    for i in range(start):
        tb = tb.tb_next
    return _parse_traceback(tb)
912658
def extract_relevant_tb(tb, exctype, is_test_failure):
    
    # Skip test runner traceback levels:
    while tb and _is_unittest_frame(tb):
        tb = tb.tb_next
    if is_test_failure:
        # Skip assert*() traceback levels:
        length = _count_relevant_tb_levels(tb)
        return extract_tb(tb, length)
    return extract_tb(tb)
1150043
def find_loopbacks(self):
        

        for dev, source in self.loopbacks.items():
            if re.match(self.orig_re_pattern, source):
                yield dev
1092936
def get_trace(self, frame, tb):
        """"""
        import linecache
        frames = []
        stack, _ = self.get_stack(frame, tb)
        current = 0

        for i, (stack_frame, lno) in enumerate(stack):
            code = stack_frame.f_code
            filename = code.co_filename or '<unspecified>'
            line = None
            if filename[0] == '<' and filename[-1] == '>':
                line = get_source_from_byte_code(code)
                fn = filename
            else:
                fn = os.path.abspath(filename)
            if not line:
                linecache.checkcache(filename)
                line = linecache.getline(filename, lno, stack_frame.f_globals)
                if not line:
                    line = self.compile_cache.get(id(code), '')
                line = to_unicode_string(line, filename)
                line = line and line.strip()
            startlnos = dis.findlinestarts(code)
            lastlineno = list(startlnos)[-1][1]
            if frame == stack_frame:
                current = i
            frames.append({
                'file': fn,
                'function': code.co_name,
                'flno': code.co_firstlineno,
                'llno': lastlineno,
                'lno': lno,
                'code': line,
                'level': i,
                'current': frame == stack_frame
            })

        # While in exception always put the context to the top
        return stack, frames, current
849743
def find_program_variables(code):
    
    vars = {}
    lines = code.split('\n')
    for line in lines:
        m = re.match(r"\s*" + re_prog_var_declaration + r"\s*(=|;)", line)
        if m is not None:
            vtype, dtype, names = m.groups()[:3]
            for name in names.split(','):
                vars[name.strip()] = (vtype, dtype)
    return vars
441103
def get_frame_info(tb, context_lines=7, simple=False):
    
    # line numbers / function / variables
    lineno = tb.tb_lineno
    function = tb.tb_frame.f_code.co_name
    variables = tb.tb_frame.f_locals

    files = {}

    # get filename
    if simple:
        fn = tb.tb_frame.f_code.co_filename
    else:
        fn = tb.tb_frame.f_globals.get('__file__')
        if not fn:
            fn = os.path.realpath(inspect.getsourcefile(tb) or
                                  inspect.getfile(tb))
        if fn[-4:] in ('.pyc', '.pyo'):
            fn = fn[:-1]

    #if filename is existed, then just read the file
    # get loader
    loader = None
    if not os.path.exists(fn):
        loader = tb.tb_frame.f_globals.get('__loader__')
        while not loader and tb.tb_next:
            tb = tb.tb_next
            loader = tb.tb_frame.f_globals.get('__loader__')


    # sourcecode
    source = ''
    pre_context, post_context = [], []
    context_line = raw_context_line = context_lineno = None
    try:
        if loader:
            source = loader.get_source(fn)
        else:
            if not fn in files:
                source = open(fn).read()
                files[fn] = source
            else:
                source = files[fn]
    except:
        pass
    else:
        try:
            raw_context_line = source.splitlines()[lineno - 1].strip()
        except IndexError:
            pass
        if not simple:
            parsed_source = highlight_python(source)
            lbound = max(0, lineno - context_lines - 1)
            ubound = lineno + context_lines
            try:
                context_line = parsed_source[lineno - 1]
                pre_context = parsed_source[lbound:lineno - 1]
                post_context = parsed_source[lineno:ubound]
            except IndexError as e:
                pass
            context_lineno = lbound

    if isinstance(fn, unicode):
        fn = fn.encode('utf-8')
    return {
        'tb':               tb,
        'filename':         fn,
        'basename':         os.path.basename(fn),
        'loader':           loader,
        'function':         function,
        'lineno':           lineno,
        'vars':             variables,
        'pre_context':      pre_context,
        'context_line':     context_line,
        'raw_context_line': raw_context_line,
        'post_context':     post_context,
        'context_lineno':   context_lineno,
        'source':           source
    }