process automatic context variable capturing.
    return the transformed function and its ast.
198666
def process(fn, bound_names):
    
    if isinstance(fn, _AutoContext):
        fn = fn.fn

    # noinspection PyArgumentList,PyArgumentList
    if isinstance(fn, _FnCodeStr):

        if bound_names:
            assign_code_str = '{syms} = map(state.ctx.get, {names})'.format(
                syms=', '.join(bound_names) + ',', names=repr(bound_names))
        else:
             assign_code_str = ''

        code = "def {0}({1}):\n{2}".format(
            fn.fn_name, ", ".join(fn.fn_args),
            textwrap.indent(assign_code_str + '\n' + fn.code, "    "))

        module_ast = ast.parse(code, fn.filename)

        bound_name_line_inc = int(bool(bound_names)) + 1

        module_ast: ast.Module = ast.increment_lineno(
            module_ast, fn.lineno - bound_name_line_inc)

        fn_ast = module_ast.body[0]

        if isinstance(fn_ast.body[-1], ast.Expr):
            # auto addition of tail expr return
            # in rbnf you don't need to write return if the last statement in the end is an expression.
            it: ast.Expr = fn_ast.body[-1]

            fn_ast.body[-1] = ast.Return(
                lineno=it.lineno, col_offset=it.col_offset, value=it.value)

        filename = fn.filename
        name = fn.fn_name

        code_object = compile(module_ast, filename, "exec")

        local = {}
        # TODO: using types.MethodType here to create the function object leads to various problems.
        # Actually I don't really known why util now.
        exec(code_object, fn.namespace, local)
        ret = local[name]

    else:
        if not bound_names:
            return fn, get_ast(fn)

        code = fn.__code__
        assigns = ast.parse("ctx = state.ctx\n" + "\n".join(
            "{0} = ctx.get({0!r})".format(name) for name in bound_names))

        module_ast = get_ast(fn)
        fn_ast: ast.FunctionDef = module_ast.body[0]
        fn_ast.body = assigns.body + fn_ast.body
        module_ast = ast.Module([fn_ast])

        filename = code.co_filename
        name = code.co_name
        __defaults__ = fn.__defaults__
        __closure__ = fn.__closure__
        __globals__ = fn.__globals__

        code_object = compile(module_ast, filename, "exec")

        code_object = next(
            each for each in code_object.co_consts
            if isinstance(each, types.CodeType) and each.co_name == name)

        # noinspection PyArgumentList,PyUnboundLocalVariable
        ret = types.FunctionType(code_object, __globals__, name, __defaults__,
                                 __closure__)
    return ret, module_ast
1055548
def _process_value(self, d, from_where):
        
        if len(d.annotations):
            l.debug("Blocking annotated AST.")
            return None
        elif not d.symbolic:
            return d
        else:
            l.debug("Processing AST with variables %s.", d.variables)

        dd = self._symbolic_passthrough(d)

        if not dd.symbolic:
            if d.symbolic:
                l.debug("... concretized")
            return dd
        elif from_where == 'reg' and options.UNICORN_SYM_REGS_SUPPORT in self.state.options:
            l.debug("... allowing symbolic register")
            return dd
        else:
            l.debug("... denied")
            return None
866225
def format_context(
    context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
    """"""
    if not context:
        return ""

    if callable(formatter):
        formatter_func = formatter
    else:
        if formatter in CONTEXT_FORMATTERS:
            formatter_func = CONTEXT_FORMATTERS[formatter]
        else:
            raise ValueError(f'Invalid context format: "{formatter}"')
    return formatter_func(context)
1147776
def from_dict(cls, ctx):
        ''
        ctx = Context(ctx)
        s = cls()
        ContextFlags = ctx['ContextFlags']
        setattr(s, 'ContextFlags', ContextFlags)
        if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
            for key in s._ctx_debug:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT:
            fsa = ctx['FloatSave']
            s.FloatSave = FLOATING_SAVE_AREA.from_dict(fsa)
        if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS:
            for key in s._ctx_segs:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER:
            for key in s._ctx_int:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL:
            for key in s._ctx_ctrl:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS:
            er = ctx['ExtendedRegisters']
            for index in compat.xrange(0, MAXIMUM_SUPPORTED_EXTENSION):
                s.ExtendedRegisters[index] = er[index]
        return s
1229261
function captureOrMatch(params, response, context, done) {
  let result = {
    captures: {},
    matches: {}
  };

  if (!params.capture && !params.match) {
    return done(null, result);
  }

  let specs = L.concat(
    L.get(params, 'capture', []),
    L.get(params, 'match', []));


  async.eachSeries(
    specs,
    function(spec, next) {
      let parsedSpec = parseSpec(spec, response);
      let parser = parsedSpec.parser;
      let extractor = parsedSpec.extractor;
      let expr = parsedSpec.expr;

      // are we looking at body or headers:
      var content = response.body;
      if (spec.header) {
        content = response.headers;
      }

      parser(content, function(err, doc) {
        if (err) {
          // TODO: The message could be improved still
          if (spec.strict) {
            return next(new Error(`Couldn't parse response for '${expr}'`), null);
          }
        }

        let extractedValue = extractor(doc, template(expr, context), spec);

        if (spec.value) {
          // this is a match spec
          let expected = template(spec.value, context);
          debug('match: %s, expected: %s, got: %s', expr, expected, extractedValue);
          if (extractedValue !== expected) {
            result.matches[expr] = {
              success: false,
              expected: expected,
              got: extractedValue,
              expression: expr,
              strict: spec.strict
            };
          } else {
            result.matches.expr = {
              success: true,
              expected: expected,
              expression: expr
            };
          }
          return next(null);
        }


        if (spec.as) {
          // this is a capture
          debug('capture: %s = %s', spec.as, extractedValue);
          result.captures[spec.as] = extractedValue;
          if (spec.transform) {
            let transformedValue = evil(
              result.captures,
              spec.transform);

            debug('transform: %s = %s', spec.as, result.captures[spec.as]);
            result.captures[spec.as] = transformedValue !== null ? transformedValue : extractedValue;
          }
        }

        return next(null);
      });
    },
    function(err) {
      if (err) {
        return done(err, null);
      } else {
        return done(null, result);
      }
    });
}
633378
def process(self):
        """"""
        var_name = self.name_edt.text()
        try:
            self.var_name = str(var_name)
        except UnicodeEncodeError:
            self.var_name = to_text_string(var_name)
        if self.text_widget.get_as_data():
            self.clip_data = self._get_table_data()
        elif self.text_widget.get_as_code():
            self.clip_data = try_to_eval(
                to_text_string(self._get_plain_text()))
        else:
            self.clip_data = to_text_string(self._get_plain_text())
        self.accept()
372935
def capture(context, callable_, *args, **kwargs):
    

    if not compat.callable(callable_):
        raise exceptions.RuntimeException(
                        "capture() function expects a callable as "
                        "its argument (i.e. capture(func, *args, **kwargs))"
                        )
    context._push_buffer()
    try:
        callable_(*args, **kwargs)
    finally:
        buf = context._pop_buffer()
    return buf.getvalue()
896134
def ast2expr(ast):
    """"""
    if ast[0] == 'const':
        return _CONSTS[ast[1]]
    elif ast[0] == 'var':
        return exprvar(ast[1], ast[2])
    else:
        xs = [ast2expr(x) for x in ast[1:]]
        return ASTOPS[ast[0]](*xs, simplify=False)
742499
def _get_callback_context(env):
    """"""
    if env.model is not None and env.cvfolds is None:
        context = 'train'
    elif env.model is None and env.cvfolds is not None:
        context = 'cv'
    return context
1147020
def evaluate(self, expr, context):
        
        if isinstance(expr, string_types):
            if expr[0] in '\'"':
                result = expr[1:-1]
            else:
                if expr not in context:
                    raise SyntaxError('unknown variable: %s' % expr)
                result = context[expr]
        else:
            assert isinstance(expr, dict)
            op = expr['op']
            if op not in self.operations:
                raise NotImplementedError('op not implemented: %s' % op)
            elhs = expr['lhs']
            erhs = expr['rhs']
            if _is_literal(expr['lhs']) and _is_literal(expr['rhs']):
                raise SyntaxError('invalid comparison: %s %s %s' % (elhs, op, erhs))

            lhs = self.evaluate(elhs, context)
            rhs = self.evaluate(erhs, context)
            result = self.operations[op](lhs, rhs)
        return result
414589
private Context translateVariableDeclaration(WyilFile.Decl.Variable stmt, Context context) {
		if (stmt.hasInitialiser()) {
			Pair<Expr, Context> p = translateExpressionWithChecks(stmt.getInitialiser(), null, context);
			context = p.second();
			generateTypeInvariantCheck(stmt.getType(), p.first(), context);
			context = context.write(stmt, p.first());
		}
		//
		return context;
	}
935281
function extractImportedVariables(context) {
  if (!context.importedVariables) {
    return {};
  }
  const importedVariables = {};
  Object.entries(context.importedVariables).forEach(([src, variables]) => {
    variables.forEach((variableName) => {
      const actualFilePath = utils.isUrl()
        ? src
        : path.resolve(path.dirname(context.cwf), decodeURIComponent(url.parse(src).path));
      if (!VARIABLE_LOOKUP[actualFilePath] || !VARIABLE_LOOKUP[actualFilePath][variableName]) {
        // eslint-disable-next-line no-console
        console.warn(`Missing variable ${variableName} in ${src} referenced by ${context.cwf}\n`);
        return;
      }
      const variableValue = VARIABLE_LOOKUP[actualFilePath][variableName];
      if (!importedVariables[variableName]) {
        importedVariables[variableName] = variableValue;
      }
    });
  });
  return importedVariables;
}
997881
function transform(str) {
  str = str.split(/^lazy\(/gm).join('require(');
  var lines = str.split(/\r\n|\n/);
  var len = lines.length;
  var re = regex();
  var idx = 0;

  var start = false;
  var isExported = false;
  var namespace;
  var res = '';

  while (idx < len) {
    var line = lines[idx++];
    res += '\n';

    if (/(?:var fn = require|require = utils)/.test(line)) {
      continue;
    }
    if (/^require = fn/.test(line)) {
      continue;
    }
    // adding this line to catch other variable names than the more specific cases above
    if (/^require = (?:.*)/.test(line)) {
      continue;
    }

    var match = re.exec(line);
    if (!match) {
      res += line;
      continue;
    }

    if (match && (match[2] === 'lazy-cache' || match[3] === 'lazy-cache')) {
      namespace = toNamespace(match[1]);
      if (/module\.exports/.test(match[1])) {
        isExported = true;
      }
      line = 'var ' + namespace + ' = {};';
      start = true;
      res += line;
      continue;
    }

    if (!start) {
      res += line;
      continue;
    }

    var variable = toVariable(match);
    var prefix = toProperty(namespace, variable, match[2]);
    line = line.split(match[0]).join(prefix);
    res += line;
  }

  if (isExported) {
    res += '\nmodule.exports = ' + namespace + ';';
  }
  return res.replace(/^\s+/, '');
}
933035
def _preprocess(self, data):
        
        transformed_data = _copy(data)
        for name, step in self._transformers[:-1]:
            transformed_data = step.fit_transform(transformed_data)
            if type(transformed_data) != _tc.SFrame:
                raise RuntimeError("The transform function in step '%s' did not"
                    " return an SFrame (got %s instead)." % (name,
                                            type(transformed_data).__name__))
        return transformed_data
728295
def context_processor(self, fn):
        
        self._defer(lambda app: app.context_processor(fn))
        return fn
350253
def func_reconstruct_closure(values):
    
    nums = range(len(values))
    src = ["def func(arg):"]
    src += ["  _%d = arg[%d]" % (n, n) for n in nums]
    src += ["  return lambda:(%s)" % ','.join(["_%d" % n for n in nums]), ""]
    src = '\n'.join(src)
    try:
        exec(src, globals())
    except:
        raise SyntaxError(src)
    return func(values).__closure__
1146031
def _encode(self, obj, context):
        
        func = getattr(obj, 'to_construct', None)
        if callable(func):
            return func(context)
        else:
            return obj