the heart of api translation dsl

        function or <z>(<arg>, ..) can be expanded, <z> can be just a name for a global function, or #name for method, <arg> can be %{self} for self or %{n} for nth arg
190725
def _expand_api(self, api, receiver, args, pseudo_type, equivalent):
        '''
        
        '''

        if callable(api):
            if receiver:
                return api(receiver, *(args + [pseudo_type]))
            else:
                return api(*(args + [pseudo_type]))
        elif isinstance(api, str):
            if '(' in api:
                call_api, arg_code = api[:-1].split('(')
                new_args = [self._parse_part(
                    a.strip(), receiver, args, equivalent) for a in arg_code.split(',')]
            else:
                call_api, arg_code = api, ''
                new_args = args
            if '#' in call_api:
                a, b = call_api.split('#')
                method_receiver = self._parse_part(
                    a, receiver, args, equivalent) if a else receiver
                return method_call(method_receiver, b, new_args, pseudo_type=pseudo_type)
            elif '.' in call_api:
                a, b = call_api.split('.')
                static_receiver = self._parse_part(
                    a, receiver, args, equivalent) if a else receiver
                if b[-1] != '!':
                    return Node('static_call', receiver=static_receiver, message=b, args=new_args, pseudo_type=pseudo_type)
                else:
                    return Node('attr', object=static_receiver, attr=b[:-1], pseudo_type=pseudo_type)
            else:
                if receiver:
                    return call(call_api, [receiver] + new_args, pseudo_type=pseudo_type)
                else:
                    return call(call_api, new_args, pseudo_type=pseudo_type)
        else:
            raise PseudoDSLError('%s not supported by api dsl' % str(api))
1021564
def output_methods(dsl)
      dsl.target_methods.each do |m|
        snippet = get_snippet(
          m.method_name ,
          get_args_names(m) ,
          get_do_block(m).chop,
          get_brace_block(m),
          dsl.scope_value
        )
        File.open(method_file_path(dsl, m), 'w:UTF-8') { |f|f.puts snippet }
      end
    end
1274577
public static <T> DslTemplate<T> dslTemplate(Class<? extends T> cl, String template, Object... args) {
        return dslTemplate(cl, createTemplate(template), ImmutableList.copyOf(args));
    }
738017
function (tpl) {
            var func = this.compile(tpl);
            return 'function(' + func.params.join(',') + '){\n' +
                func.source.join('\n') +
                '}';
        }
83570
function methodCall( $elems, methodName, args ) {
    var returnValue;
    var pluginMethodStr = '$().' + namespace + '("' + methodName + '")';

    $elems.each( function( i, elem ) {
      // get instance
      var instance = $.data( elem, namespace );
      if ( !instance ) {
        logError( namespace + ' not initialized. Cannot call methods, i.e. ' +
          pluginMethodStr );
        return;
      }

      var method = instance[ methodName ];
      if ( !method || methodName.charAt(0) == '_' ) {
        logError( pluginMethodStr + ' is not a valid method' );
        return;
      }

      // apply method, get return value
      var value = method.apply( instance, args );
      // set return value if value is returned, use only first value
      returnValue = returnValue === undefined ? value : returnValue;
    });

    return returnValue !== undefined ? returnValue : $elems;
  }
783851
def split_func_name_args_params_handle(tokens):
    """"""
    internal_assert(len(tokens) == 2, "invalid function definition splitting tokens", tokens)
    func_name = tokens[0]
    func_args = []
    func_params = []
    for arg in tokens[1]:
        if len(arg) > 1 and arg[0] in ("*", "**"):
            func_args.append(arg[1])
        elif arg[0] != "*":
            func_args.append(arg[0])
        func_params.append("".join(arg))
    return [
        func_name,
        ", ".join(func_args),
        "(" + ", ".join(func_params) + ")",
    ]
855942
function Arguable (usage, argv, options) {
    this._usage = usage

    // These are the merged defintion and invocation options provided by the
    // user.
    this.options = options.options

    // The key used to create the `Destructible`.
    this.identifier = options.identifier

    // We'll use this for an exit code if it is set and if we exit normally.
    this.exitCode = null

    // Are we running as a main module?
    this.isMainModule = options.isMainModule

    // Use environment `LANG` or else language of first usage definition.
    this.lang = coalesce(options.lang, this._usage.language)

    // Extract argument patterns from usage.
    var patterns = this._usage.getPattern()

    // Extract the arguments that accept values, TODO maybe call `valuable`.
    this.arguable = patterns.filter(function (pattern) {
        return pattern.arguable
    }).map(function (pattern) {
        return pattern.verbose
    })

    // Parse arguments and save the remaining arguments.
    try {
        var gotopts = getopt(patterns, argv)
    } catch (error) {
        this.abend(error.abend, error.context)
    }

    // Extract an argument end sigil and note that it was there.
    if (this.terminal = argv[0] == '--')  {
        argv.shift()
    }

    // Slice and dice results into convenience structures.
    this._setParameters(gotopts)

    // Remaining arguments.
    this.argv = argv

    // Assign standard I/O provide in `options`.
    this.stdout = options.stdout
    this.stderr = options.stderr
    this.stdin = options.stdin

    // Assign pipes open to our parent.
    this.pipes = options.pipes

    // Set after we get our arguments.
    this.scram = 0

    // Called when we exit with no arguments.
    this.exited = new Signal
}
573388
function buildArguments (argz) {
  var args = argz.cmd.split(' ')
  argz.cmd = args.shift()
  argz.args = union([], args || [], argz.args || [])
  return argz
}
745074
def data_structure_builder(func):
    
    @wraps(func)
    def ds_builder_wrapper(function, *args, **kwargs):
        try:
            function = DSBuilder(function)
        except NoBuilder:
            pass
        return func(function, *args, **kwargs)

    return ds_builder_wrapper
655396
def _generate_route_method_decl(
            self, namespace, route, arg_data_type, request_binary_body,
            method_name_suffix='', extra_args=None):
        """"""
        args = ['self']
        if extra_args:
            args += extra_args
        if request_binary_body:
            args.append('f')
        if is_struct_type(arg_data_type):
            for field in arg_data_type.all_fields:
                if is_nullable_type(field.data_type):
                    args.append('{}=None'.format(field.name))
                elif field.has_default:
                    # TODO(kelkabany): Decide whether we really want to set the
                    # default in the argument list. This will send the default
                    # over the wire even if it isn't overridden. The benefit is
                    # it locks in a default even if it is changed server-side.
                    if is_user_defined_type(field.data_type):
                        ns = field.data_type.namespace
                    else:
                        ns = None
                    arg = '{}={}'.format(
                        field.name,
                        self._generate_python_value(ns, field.default))
                    args.append(arg)
                else:
                    args.append(field.name)
        elif is_union_type(arg_data_type):
            args.append('arg')
        elif not is_void_type(arg_data_type):
            raise AssertionError('Unhandled request type: %r' %
                                 arg_data_type)

        method_name = fmt_func(route.name + method_name_suffix, version=route.version)
        namespace_name = fmt_underscores(namespace.name)
        self.generate_multiline_list(args, 'def {}_{}'.format(namespace_name, method_name), ':')
298040
public static List<String> getArgumentNames(MethodCallExpression methodCall) {
        ArrayList<String> result = new ArrayList<String>();

        Expression arguments = methodCall.getArguments();
        List<Expression> argExpressions = null;
        if (arguments instanceof ArrayExpression) {
            argExpressions = ((ArrayExpression) arguments).getExpressions();
        } else if (arguments instanceof ListExpression) {
            argExpressions = ((ListExpression) arguments).getExpressions();
        } else if (arguments instanceof TupleExpression) {
            argExpressions = ((TupleExpression) arguments).getExpressions();
        } else {
            LOG.warn("getArgumentNames arguments is not an expected type");
        }

        if (argExpressions != null) {
            for (Expression exp : argExpressions) {
                if (exp instanceof VariableExpression) {
                    result.add(((VariableExpression) exp).getName());
                }
            }
        }
        return result;
    }
1304996
function wrapArguments(trace, clientState, hooks) {
  //wrap any callbacks found in the arguments
  var args = trace.args;
  var handler = clientState.rules.handleArgs(trace.funInfo.name);
  if (handler) {
    handler(trace, clientState);
  }
  for (var i = args.length - 1; i >= 0; i--) {
    var a = args[i];
    if (util.isFunction(a) && !a.__concurix_blacklisted) {
      var callbackState = {
        modInfo: clientState.modInfo,
        rules: clientState.rules,
        callbackOf: trace
      };

      if (wrap.isWrapper(args[i])) {
        args[i].__concurix_proxy_state__
          .module((trace.calledBy && trace.calledBy.moduleName) || 'root')
          .state(callbackState)
          .nameIfNeeded(trace.funInfo.name + ' callback')
          .getProxy();
      }
      else {
        args[i] = wrap(a)
          .before(hooks.beforeHook)
          .after(hooks.afterHook)
          .module((trace.calledBy && trace.calledBy.moduleName) || 'root')
          .state(callbackState)
          .nameIfNeeded(trace.funInfo.name + ' callback')
          .getProxy();
      }
      trace.origFunctionArguments = trace.origFunctionArguments || [];
      trace.origFunctionArguments.push(a);
    }
  }
}
574205
def ExpandArg(self, **_):
    """"""
    # This function is called when we see close ) and the stack depth has to
    # exactly match the number of (.
    if len(self.stack) <= 1:
      raise lexer.ParseError(
          "Unbalanced parenthesis: Can not expand '%s'" % self.processed_buffer)

    # This is the full parameter name: e.g. Logging.path
    parameter_name = self.stack.pop(-1)
    if "." not in parameter_name:
      parameter_name = "%s.%s" % (self.default_section, parameter_name)

    final_value = self.config.Get(parameter_name, context=self.context)
    if final_value is None:
      final_value = ""

    type_info_obj = (
        self.config.FindTypeInfo(parameter_name) or type_info.String())

    # Encode the interpolated string according to its type.
    self.stack[-1] += type_info_obj.ToString(final_value)
1349835
function (parameters, argumentsToParse) {
                var
                    result = {},
                    len,
                    idx,
                    argument,
                    parameter,
                    name,
                    lastNonPrefixIdx = 0;
                parameters = gpf.Parameter.create(parameters);
                len = argumentsToParse.length;
                for (idx = 0; idx < len; ++idx) {
                    // Check if a prefix was used and find parameter
                    argument = this.getPrefixValuePair(argumentsToParse[idx]);
                    if (argument instanceof Array) {
                        parameter = this.getOnPrefix(parameters, argument[0]);
                        argument = argument[1];
                    } else {
                        parameter = this.getOnPrefix(parameters,
                            lastNonPrefixIdx);
                        lastNonPrefixIdx = parameters.indexOf(parameter) + 1;
                    }
                    // If no parameter corresponds, ignore
                    if (!parameter) {
                        // TODO maybe an error might be more appropriate
                        continue;
                    }
                    // Sometimes, the prefix might be used without value
                    if (undefined === argument) {
                        if ("boolean" === parameter._type) {
                            argument = !parameter._defaultValue;
                        } else {
                            // Nothing to do with it
                            // TODO maybe an error might be more appropriate
                            continue;
                        }
                    }
                    // Convert the value to match the type
                    // TODO change when type will be an object
                    argument = gpf.value(argument, parameter._defaultValue,
                        parameter._type);
                    // Assign the corresponding member of the result object
                    name = parameter._name;
                    if (parameter._multiple) {
                        if (undefined === result[name]) {
                            result[name] = [];
                        }
                        result[name].push(argument);
                        if (parameter._prefix === "") {
                            --lastNonPrefixIdx;
                        }

                    } else {
                        // The last one wins
                        result[name] = argument;
                    }
                }
                this._finalizeParse(parameters, result);
                return result;
            }
239268
def tzname_in_python2(myfunc):
    
    def inner_func(*args, **kwargs):
        if PY3:
            return myfunc(*args, **kwargs)
        else:
            return myfunc(*args, **kwargs).encode()
    return inner_func
1152762
function define () {
  var args = Array.prototype.slice.call(arguments)
  var i, l

  var name = args.shift()
  if (is.array(name)) {
    name = args.shift()
    for (i = 0, l = name.length; i < l; i++) {
      define.apply(this, [name[i]].concat(args))
    }
    return this
  }

  if (!is.string(name)) throw new Error('Method name is not defined')

  var invoke = is.function(args[args.length - 1]) ? wrapFn(args.pop()) : null
  var pre = args.map(wrapFn)

  // define scope method
  this[name] = function () {
    var args = Array.prototype.slice.call(arguments)
    var self = this
    var callback

    if (is.function(args[args.length - 1])) callback = args.pop()

    // init pipeline
    var pipe = []
    var obj = this

    // prototype chain
    while (obj) {
      if (obj.hasOwnProperty('_hooks') && obj._hooks[name]) {
        pipe.unshift(obj._hooks[name])
      }
      obj = Object.getPrototypeOf(obj)
    }
    // pre middlewares
    pipe.unshift(pre)

    // invoke middleware
    if (invoke) pipe.push(invoke)

    pipe = flatten(pipe)

    // context object and next triggerer
    var ctx = new EventEmitter()
    ctx.method = name
    ctx.args = args
    var index = 0
    var size = pipe.length

    function next (err, res) {
      if (err || index === size) {
        var args = Array.prototype.slice.call(arguments)
        // callback when err or end of pipeline
        if (callback) callback.apply(self, args)
        args.unshift('end')
        ctx.emit.apply(ctx, args)
      } else if (index < size) {
        var fn = pipe[index]
        index++
        var val = fn.call(self, ctx, next)
        if (is.promise(val)) {
          val.then(function (res) {
            next(null, res)
          }, function (err) {
            next(err || new Error())
          })
        } else if (fn.length < 2) {
          // args without next() & not promise, sync func
          next(null, val)
        }
      }
    }

    if (callback) {
      next()
    } else {
      // use promise if no callback
      return new Promise(function (resolve, reject) {
        callback = function (err, result) {
          if (err) return reject(err)
          resolve(result)
        }
        next()
      })
    }
  }
  return this
}
1101395
function _nom(fun) {
    var src = fun.toString();
    src = src.substr('function '.length);
    var n = src.substr(0, src.indexOf('('));

    if (!L.isFunction(fun)) fail("Cannot derive the name of a non-function.");
    if (fun.name && (fun.name === n)) return fun.name;
    if (n) return n;
    fail("Anonymous function has no name.");
  }