Disassemble a code object.
334838
def disassemble(co, lasti=-1):
    """"""
    # Taken from dis.disassemble, returns disassembled code instead of printing
    # it (the fuck python ?).
    # Also, unicodified.
    # Also, use % operator instead of string operations.
    # Also, one statement per line.
    out = StringIO()
    code = co.co_code
    labels = dis.findlabels(code)
    linestarts = dict(dis.findlinestarts(co))
    n = len(code)
    i = 0
    extended_arg = 0
    free = None
    while i < n:
        c = code[i]
        op = ord(c)
        if i in linestarts:
            if i > 0:
                print(end=u'\n', file=out)
            print(u'%3d' % linestarts[i], end=u' ', file=out)
        else:
            print(u'   ', end=u' ', file=out)

        if i == lasti:
            print(u'-->', end=u' ', file=out)
        else:
            print(u'   ', end=u' ', file=out)
        if i in labels:
            print(u'>>', end=u' ', file=out)
        else:
            print(u'  ', end=u' ', file=out)
        print(u'%4i' % i, end=u' ', file=out)
        print(u'%-20s' % dis.opname[op], end=u' ', file=out)
        i = i + 1
        if op >= dis.HAVE_ARGUMENT:
            oparg = ord(code[i]) + ord(code[i + 1]) * 256 + extended_arg
            extended_arg = 0
            i = i + 2
            if op == dis.EXTENDED_ARG:
                extended_arg = oparg * 65536
            print(u'%5i' % oparg, end=u' ', file=out)
            if op in dis.hasconst:
                print(u'(%r)' % co.co_consts[oparg], end=u' ', file=out)
            elif op in dis.hasname:
                print(u'(%s)' % co.co_names[oparg], end=u' ', file=out)
            elif op in dis.hasjrel:
                print(u'(to %r)' % (i + oparg), end=u' ', file=out)
            elif op in dis.haslocal:
                print(u'(%s)' % co.co_varnames[oparg], end=u' ', file=out)
            elif op in dis.hascompare:
                print(u'(%s)' % dis.cmp_op[oparg], end=u' ', file=out)
            elif op in dis.hasfree:
                if free is None:
                    free = co.co_cellvars + co.co_freevars
                print(u'(%s)' % free[oparg], end=u' ', file=out)
        print(end=u'\n', file=out)
    return out.getvalue()
398203
def clear_code(code)
      if url_obj = url_object(code)
        @url_bucket.delete url_key(url_obj.data)
        @code_bucket.delete url_obj.key
      end
    end
1214952
function clean(code) {

    try {
        const ast = babylon.parse(code, {
            // parse in strict mode and allow module declarations
            sourceType: 'module',
            plugins: [
                // enable jsx and flow syntax
                'jsx',
                'flow'
            ]
        });

        const cleanAst = strip(ast).program;

        const resultCode = generate(cleanAst, {}).code;

        return resultCode.replace(/(\/\*\$ | \#\*\/)/g, '');

    } catch (e) {
        console.log(code);
        throw e;
    }
}
255044
def _unwrap_obj(self, fobj, fun):
        """"""
        try:
            prev_func_obj, next_func_obj = (
                fobj.f_globals[fun],
                getattr(fobj.f_globals[fun], "__wrapped__", None),
            )
            while next_func_obj:
                prev_func_obj, next_func_obj = (
                    next_func_obj,
                    getattr(next_func_obj, "__wrapped__", None),
                )
            return (prev_func_obj, inspect.getfile(prev_func_obj).replace(".pyc", "py"))
        except (KeyError, AttributeError, TypeError):
            # KeyErrror: fun not in fobj.f_globals
            # AttributeError: fobj.f_globals does not have
            #                 a __wrapped__ attribute
            # TypeError: pref_func_obj does not have a file associated with it
            return None, None
1044542
function prune(code) {
  var ast = esprima.parse(code);

  estraverse.replace(ast, {
    leave: function leave(node, parent) {
      var ret;

      if ('IfStatement' === node.type) {
        if ('BinaryExpression' !== node.test.type) return;

        if ('self' === node.test.left.argument.name) {
          node.alternate = null;
        } else if ('global' === node.test.left.argument.name) {
          ret = node.alternate;
        }

        return ret;
      }

      if (
          'BlockStatement' === node.type
        && 'FunctionExpression' === parent.type
      ) {
        return node.body[0].alternate.alternate;
      }
    }
  });

  return escodegen.generate(ast, {
    format: {
      indent: { style: '  ' },
      semicolons: false,
      compact: true
    }
  });
}
219537
def code(self, text, lang=None):
        """"""
        # WARNING: lang is discarded currently.
        with self.paragraph(stylename='code'):
            lines = text.splitlines()
            for line in lines[:-1]:
                self._code_line(line)
                self.linebreak()
            self._code_line(lines[-1])
874397
def delete_cell(self,  key):
        """"""

        try:
            self.code_array.pop(key)

        except KeyError:
            pass

        self.grid.code_array.result_cache.clear()
971859
function () {
    this.objectPool.recycle(this.attrValue);
    this.objectPool.recycle(this.oldData);
    this.objectPool.recycle(this.parsingAttrValue);
    this.attrValue = this.oldData = this.parsingAttrValue = undefined;
  }
961583
def recompile(filename):
    """"""
    # Most of the code here based on the compile.py module.
    import os
    import imp
    import marshal
    import struct

    f = open(filename, 'U')
    try:
        timestamp = long(os.fstat(f.fileno()).st_mtime)
    except AttributeError:
        timestamp = long(os.stat(filename).st_mtime)
    codestring = f.read()
    f.close()
    if codestring and codestring[-1] != '\n':
        codestring = codestring + '\n'
    try:
        codeobject = compile(codestring, filename, 'exec')
    except SyntaxError:
        print >> sys.stderr, "Skipping %s - syntax error." % filename
        return
    cod = Code.from_code(codeobject)
    message = "reassembled %r imported.\n" % filename
    cod.code[:0] = [ # __import__('sys').stderr.write(message)
        (LOAD_GLOBAL, '__import__'),
        (LOAD_CONST, 'sys'),
        (CALL_FUNCTION, 1),
        (LOAD_ATTR, 'stderr'),
        (LOAD_ATTR, 'write'),
        (LOAD_CONST, message),
        (CALL_FUNCTION, 1),
        (POP_TOP, None),
        ]
    codeobject2 = cod.to_code()
    fc = open(filename+'c', 'wb')
    fc.write('\0\0\0\0')
    fc.write(struct.pack('<l', timestamp))
    marshal.dump(codeobject2, fc)
    fc.flush()
    fc.seek(0, 0)
    fc.write(imp.get_magic())
    fc.close()
647579
def disassemble(nex):
    
    rev_opcodes = {}
    for op in interpreter.opcodes:
        rev_opcodes[interpreter.opcodes[op]] = op
    r_constants = 1 + len(nex.signature)
    r_temps = r_constants + len(nex.constants)

    def getArg(pc, offset):
        if sys.version_info[0] < 3:
            arg = ord(nex.program[pc + offset])
            op = rev_opcodes.get(ord(nex.program[pc]))
        else:
            arg = nex.program[pc + offset]
            op = rev_opcodes.get(nex.program[pc])
        try:
            code = op.split(b'_')[1][offset - 1]
        except IndexError:
            return None
        if sys.version_info[0] > 2:
            # int.to_bytes is not available in Python < 3.2
            #code = code.to_bytes(1, sys.byteorder)
            code = bytes([code])
        if arg == 255:
            return None
        if code != b'n':
            if arg == 0:
                return b'r0'
            elif arg < r_constants:
                return ('r%d[%s]' % (arg, nex.input_names[arg - 1])).encode('ascii')
            elif arg < r_temps:
                return ('c%d[%s]' % (arg, nex.constants[arg - r_constants])).encode('ascii')
            else:
                return ('t%d' % (arg,)).encode('ascii')
        else:
            return arg

    source = []
    for pc in range(0, len(nex.program), 4):
        if sys.version_info[0] < 3:
            op = rev_opcodes.get(ord(nex.program[pc]))
        else:
            op = rev_opcodes.get(nex.program[pc])
        dest = getArg(pc, 1)
        arg1 = getArg(pc, 2)
        arg2 = getArg(pc, 3)
        source.append((op, dest, arg1, arg2))
    return source
1342556
def _pys2code(self, line):
        """"""

        row, col, tab, code = self._split_tidy(line, maxsplit=3)
        key = self._get_key(row, col, tab)

        self.code_array.dict_grid[key] = unicode(code, encoding='utf-8')
1194747
def replace(self, old, new):
        """"""
        if old.type != new.type:
            raise TypeError("new instruction has a different type")
        pos = self.instructions.index(old)
        self.instructions.remove(old)
        self.instructions.insert(pos, new)

        for bb in self.parent.basic_blocks:
            for instr in bb.instructions:
                instr.replace_usage(old, new)
143200
def disasm(raw, arch: nil)
      codes = to_bpf(raw, arch)
      contexts = Array.new(codes.size) { Set.new }
      contexts[0].add(Context.new)
      # all we care is if A is exactly one of data[*]
      dis = codes.zip(contexts).map do |code, ctxs|
        ctxs.each do |ctx|
          code.branch(ctx) do |pc, c|
            contexts[pc].add(c) unless pc >= contexts.size
          end
        end
        code.contexts = ctxs
        code.disasm
      end.join("\n")
      <<EOS + dis + "\n"
 line  CODE  JT   JF      K
=================================
EOS
    end
580796
def teardown(self, np=np):
    """"""

    if self.old_err is not None:
        np.seterr(**self.old_err)

    if self.old_opts is not None:
        np.set_printoptions(**self.old_opts)
206726
def disasm_app(_parser, cmd, args):  # pragma: no cover
    

    parser = argparse.ArgumentParser(
        prog=_parser.prog,
        description=_parser.description,
    )
    parser.add_argument('code', help='the code to disassemble, read from stdin if omitted', nargs='?')
    pwnypack.main.add_target_arguments(parser)
    parser.add_argument(
        '--syntax', '-s',
        choices=AsmSyntax.__members__.keys(),
        default=None,
    )
    parser.add_argument(
        '--address', '-o',
        type=lambda v: int(v, 0),
        default=0,
        help='the address of the disassembled code',
    )
    parser.add_argument(
        '--format', '-f',
        choices=['hex', 'bin'],
        help='the input format (defaults to hex for commandline, bin for stdin)',
    )

    args = parser.parse_args(args)
    target = pwnypack.main.target_from_arguments(args)
    if args.syntax is not None:
        syntax = AsmSyntax.__members__[args.syntax]
    else:
        syntax = None

    if args.format is None:
        if args.code is None:
            args.format = 'bin'
        else:
            args.format = 'hex'

    if args.format == 'hex':
        code = pwnypack.codec.dehex(pwnypack.main.string_value_or_stdin(args.code))
    else:
        code = pwnypack.main.binary_value_or_stdin(args.code)

    print('\n'.join(disasm(code, args.address, syntax=syntax, target=target)))
774867
def extract_code(obj, compile_mode):
    
    try:
        code = obj.__code__
        if isinstance(code, CodeType):
            return code
        raise ValueError(
            "{obj} has a `__code__` attribute, "
            "but it's an instance of {notcode!r}, not CodeType.".format(
                obj=obj,
                notcode=type(code).__name__,
            )
        )
    except AttributeError:
        raise ValueError("Don't know how to extract code from %s." % obj)
464607
def disassemble(self, lineno_width=3,
                    mark_as_current=False,
                    asm_format=False,
                    show_bytes=False):
        
        fields = []
        if asm_format:
            indexed_operand = set(['name', 'local', 'compare', 'free'])
        # Column: Source code line number
        if lineno_width:
            if self.starts_line is not None:
                if asm_format:
                    lineno_fmt = "%%%dd:\n" % lineno_width
                    fields.append(lineno_fmt % self.starts_line)
                    fields.append(' ' * (lineno_width))
                    if self.is_jump_target:
                        fields.append(' ' * (lineno_width-1))
                else:
                    lineno_fmt = "%%%dd:" % lineno_width
                    fields.append(lineno_fmt % self.starts_line)
            else:
                fields.append(' ' * (lineno_width+1))
        # Column: Current instruction indicator
        if mark_as_current and not asm_format:
            fields.append('-->')
        else:
            fields.append('   ')
        # Column: Jump target marker
        if self.is_jump_target:
            if not asm_format:
                fields.append('>>')
            else:
                fields = ["L%d:\n" % self.offset] + fields
                if not self.starts_line:
                    fields.append(' ')
        else:
            fields.append('  ')
        # Column: Instruction offset from start of code sequence
        if not asm_format:
            fields.append(repr(self.offset).rjust(4))

        if show_bytes:
            hex_bytecode = "|%02x" % self.opcode
            if self.inst_size == 1:
                # Not 3.6 or later
                hex_bytecode += ' ' * (2*3)
            if self.inst_size == 2:
                # Must by Python 3.6 or later
                if self.has_arg:
                    hex_bytecode += " %02x" % (self.arg % 256)
                else :
                    hex_bytecode += ' 00'
            elif self.inst_size == 3:
                # Not 3.6 or later
                hex_bytecode += " %02x %02x" % (
                    (self.arg >> 8, self.arg % 256))

            fields.append(hex_bytecode + '|')

        # Column: Opcode name
        fields.append(self.opname.ljust(20))

        # Column: Opcode argument
        if self.arg is not None:
            argrepr = self.argrepr
            if asm_format:
                if self.optype == 'jabs':
                    fields.append('L' + str(self.arg))
                elif self.optype == 'jrel':
                    argval = self.offset + self.arg + self.inst_size
                    fields.append('L' + str(argval))
                elif self.optype in indexed_operand:
                    fields.append('(%s)' % argrepr)
                    argrepr = None
                elif (self.optype == 'const'
                      and not re.search('\s', argrepr)):
                    fields.append('(%s)' % argrepr)
                    argrepr = None
                else:
                    fields.append(repr(self.arg))
            elif not (show_bytes and argrepr):
                fields.append(repr(self.arg).rjust(6))
            # Column: Opcode argument details
            if argrepr:
                fields.append('(%s)' % argrepr)
                pass
            pass
        return ' '.join(fields).rstrip()