Call a remote method

        Arguments:
        method - remote method name
        params - remote method parameters

        Keyword Arguments:
        callback - callback function containing return data
436632
def call(self, method, params, callback=None):
        """"""
        self._wait_for_connect()
        self.ddp_client.call(method, params, callback=callback)
406856
def json_call(cls, method, url, **kwargs):
        
        # retrieve api key if needed
        empty_key = kwargs.pop('empty_key', False)
        send_key = kwargs.pop('send_key', True)
        return_header = kwargs.pop('return_header', False)
        try:
            apikey = cls.get('apirest.key')
            if not apikey and not empty_key:
                cls.echo("No apikey found for REST API, please use "
                         "'gandi setup' command")
                sys.exit(1)
            if send_key:
                if 'headers' in kwargs:
                    kwargs['headers'].update({'X-Api-Key': apikey})
                else:
                    kwargs['headers'] = {'X-Api-Key': apikey}
        except MissingConfiguration:
            if not empty_key:
                return []
        # make the call
        cls.debug('calling url: %s %s' % (method, url))
        cls.debug('with params: %r' % kwargs)
        try:
            resp, resp_headers = JsonClient.request(method, url, **kwargs)
            cls.dump('responded: %r' % resp)
            if return_header:
                return resp, resp_headers
            return resp
        except APICallFailed as err:
            cls.echo('An error occured during call: %s' % err.errors)
            sys.exit(1)
967363
def callback(params, returns, &block)
      Win32::API::Callback.new(params, returns, &block)
    end
810818
def call(self, method, *args):
        

        payload = self.build_payload(method, args)
        logging.debug('* Client will send payload: {}'.format(payload))
        self.send(payload)

        res = self.receive()
        assert payload[2] == res['ref']
        return res['result'], res['error']
68645
def call_method_with_optional_parameters(object, method_name, parameters)
        if object.respond_to?(method_name)
          if object.method(method_name).arity == -1
            object.send(method_name, parameters)
          else
            object.send(method_name)
          end
        end
      end
1087072
def _call(self, method, path, data=None):
    
    if is_python3():
      conn = http.client.HTTPConnection(API_HOST)
    else:
      conn = httplib.HTTPConnection(API_HOST)

    headers = {'User-Agent' : USER_AGENT}

    if data:
      headers.update( {'Content-type': 'application/x-www-form-urlencoded'} )
      conn.request(method, path, self._urlencode(data), headers)

    else:
      conn.request(method, path, None, headers)

    response = conn.getresponse()
    result   =  [response.status, self._parse_body(response.read())]
    conn.close()
    return result
888027
def remote_call(request, cls, method, args, kw):
    '''
    '''
    actor = request.actor
    name = 'remote_%s' % cls.__name__
    if not hasattr(actor, name):
        object = cls(actor)
        setattr(actor, name, object)
    else:
        object = getattr(actor, name)
    method_name = '%s%s' % (PREFIX, method)
    return getattr(object, method_name)(request, *args, **kw)
724024
@Override
    public <R, T extends Object> R callMethod(final String methodName, final T argument, final long timeout) throws CouldNotPerformException, InterruptedException {

        final String shortArgument = RPCHelper.argumentToString(argument);
        validateMiddleware();
        long retryTimeout = METHOD_CALL_START_TIMEOUT;
        long validTimeout = timeout;

        try {
            logger.debug("Calling method [" + methodName + "(" + shortArgument + ")] on scope: " + remoteServer.getScope().toString());
            if (!isConnected()) {
                waitForConnectionState(CONNECTED, timeout);
            }

            if (timeout > -1) {
                retryTimeout = Math.min(METHOD_CALL_START_TIMEOUT, validTimeout);
            }

            while (true) {

                if (!isActive()) {
                    throw new InvalidStateException("Remote service is not active!");
                }

                try {
                    logger.debug("Calling method [" + methodName + "(" + shortArgument + ")] on scope: " + remoteServer.getScope().toString());
                    remoteServerWatchDog.waitForServiceActivation(timeout, TimeUnit.MILLISECONDS);
                    final R returnValue = remoteServer.call(methodName, argument, retryTimeout);

                    if (retryTimeout != METHOD_CALL_START_TIMEOUT && retryTimeout > 15000) {
                        logger.info("Method[" + methodName + "(" + shortArgument + ")] returned! Continue processing...");
                    }
                    return returnValue;

                } catch (TimeoutException ex) {

                    // check if timeout is set and handle
                    if (timeout != -1) {
                        validTimeout -= retryTimeout;
                        if (validTimeout <= 0) {
                            ExceptionPrinter.printHistory(ex, logger, LogLevel.WARN);
                            throw new TimeoutException("Could not call remote Method[" + methodName + "(" + shortArgument + ")] on Scope[" + remoteServer.getScope() + "] in Time[" + timeout + "ms].");
                        }
                        retryTimeout = Math.min(generateTimeout(retryTimeout), validTimeout);
                    } else {
                        retryTimeout = generateTimeout(retryTimeout);
                    }

                    // only print warning if timeout is too long.
                    if (retryTimeout > 15000) {
                        ExceptionPrinter.printHistory(ex, logger, LogLevel.WARN);
                        logger.warn("Waiting for RPCServer[" + remoteServer.getScope() + "] to call method [" + methodName + "(" + shortArgument + ")]. Next retry timeout in " + (int) (Math.floor(retryTimeout / 1000)) + " sec.");
                    } else {
                        ExceptionPrinter.printHistory(ex, logger, LogLevel.DEBUG);
                        logger.debug("Waiting for RPCServer[" + remoteServer.getScope() + "] to call method [" + methodName + "(" + shortArgument + ")]. Next retry timeout in " + (int) (Math.floor(retryTimeout / 1000)) + " sec.");
                    }

                    Thread.yield();
                }
            }
        } catch (TimeoutException ex) {
            throw ex;
        } catch (CouldNotPerformException ex) {
            throw new CouldNotPerformException("Could not call remote Method[" + methodName + "(" + shortArgument + ")] on Scope[" + remoteServer.getScope() + "].", ex);
        }
    }
149059
def callm(method, param_dict, POST=False, socket_timeout=None, data=None):
    
    try:
        param_dict['api_key'] = config.ECHO_NEST_API_KEY
        param_list = []
        if not socket_timeout:
            socket_timeout = config.CALL_TIMEOUT

        for key,val in param_dict.iteritems():
            if isinstance(val, list):
                param_list.extend( [(key,subval) for subval in val] )
            elif val is not None:
                if isinstance(val, unicode):
                    val = val.encode('utf-8')
                param_list.append( (key,val) )

        params = urllib.urlencode(param_list)

        orig_timeout = socket.getdefaulttimeout()
        socket.setdefaulttimeout(socket_timeout)

        if(POST):
            if (not method == 'track/upload') or ((method == 'track/upload') and 'url' in param_dict):
                """
                this is a normal POST call
                """
                url = 'http://%s/%s/%s/%s' % (config.API_HOST, config.API_SELECTOR,
                                            config.API_VERSION, method)

                if data is None:
                    data = ''
                data = urllib.urlencode(data)
                data = "&".join([data, params])

                f = opener.open(url, data=data)
            else:
                """
                upload with a local file is special, as the body of the request is the content of the file,
                and the other parameters stay on the URL
                """
                url = '/%s/%s/%s?%s' % (config.API_SELECTOR, config.API_VERSION,
                                            method, params)

                if ':' in config.API_HOST:
                    host, port = config.API_HOST.split(':')
                else:
                    host = config.API_HOST
                    port = 80

                if config.TRACE_API_CALLS:
                    logger.info("%s/%s" % (host+':'+str(port), url,))
                conn = httplib.HTTPConnection(host, port = port)
                conn.request('POST', url, body = data, headers = dict([('Content-Type', 'application/octet-stream')]+headers))
                f = conn.getresponse()

        else:
            """
            just a normal GET call
            """
            url = 'http://%s/%s/%s/%s?%s' % (config.API_HOST, config.API_SELECTOR, config.API_VERSION,
                                            method, params)

            f = opener.open(url)

        socket.setdefaulttimeout(orig_timeout)

        # try/except
        response_dict = get_successful_response(f)
        return response_dict

    except IOError, e:
        if hasattr(e, 'reason'):
            raise EchoNestIOError(error=e.reason)
        elif hasattr(e, 'code'):
            raise EchoNestIOError(code=e.code)
        else:
            raise
1305785
public static Object callMethod(Scriptable obj, String methodName,
                                    Object[] args)
    {
        return callMethod(null, obj, methodName, args);
    }
991878
def _call_function(name, returner=None, **kwargs):
    '''
    
    '''
    argspec = salt.utils.args.get_function_argspec(__salt__[name])

    # func_kw is initialized to a dictionary of keyword arguments the function to be run accepts
    func_kw = dict(zip(argspec.args[-len(argspec.defaults or []):],  # pylint: disable=incompatible-py3-code
                   argspec.defaults or []))

    # func_args is initialized to a list of positional arguments that the function to be run accepts
    func_args = argspec.args[:len(argspec.args or []) - len(argspec.defaults or [])]
    arg_type, kw_to_arg_type, na_type, kw_type = [], {}, {}, False
    for funcset in reversed(kwargs.get('func_args') or []):
        if not isinstance(funcset, dict):
            # We are just receiving a list of args to the function to be run, so just append
            # those to the arg list that we will pass to the func.
            arg_type.append(funcset)
        else:
            for kwarg_key in six.iterkeys(funcset):
                # We are going to pass in a keyword argument. The trick here is to make certain
                # that if we find that in the *args* list that we pass it there and not as a kwarg
                if kwarg_key in func_args:
                    kw_to_arg_type[kwarg_key] = funcset[kwarg_key]
                    continue
                else:
                    # Otherwise, we're good and just go ahead and pass the keyword/value pair into
                    # the kwargs list to be run.
                    func_kw.update(funcset)
    arg_type.reverse()
    for arg in func_args:
        if arg in kw_to_arg_type:
            arg_type.append(kw_to_arg_type[arg])
    _exp_prm = len(argspec.args or []) - len(argspec.defaults or [])
    _passed_prm = len(arg_type)
    missing = []
    if na_type and _exp_prm > _passed_prm:
        for arg in argspec.args:
            if arg not in func_kw:
                missing.append(arg)
    if missing:
        raise SaltInvocationError('Missing arguments: {0}'.format(', '.join(missing)))
    elif _exp_prm > _passed_prm:
        raise SaltInvocationError('Function expects {0} parameters, got only {1}'.format(
            _exp_prm, _passed_prm))

    mret = __salt__[name](*arg_type, **func_kw)
    if returner is not None:
        returners = salt.loader.returners(__opts__, __salt__)
        if returner in returners:
            returners[returner]({'id': __opts__['id'], 'ret': mret,
                                 'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)})

    return mret
1091160
def _get_remote_method(self, funcname):
        

        func = getattr(self, funcname)
        if not callable(func) or not getattr(func, '_remote', False):
            raise AttributeError("%r object has no attribute %r" %
                                 (self.__class__.__name__, funcname))

        return func
488109
def callback(name, params, returns)
      params, returns = generate_signature(params, returns)
      super name.to_sym, params, returns
    end
236182
def method_missing(method, *args, &block)
      if main_app_url_helper?(method)
        main_app.send(method, *args)
      else
        super
      end
    end
355164
def method_call(receiver, message, args, pseudo_type=None):
    ''''''

    if not isinstance(receiver, Node):
        receiver = local(receiver)
    return Node('method_call', receiver=receiver, message=message, args=args, pseudo_type=pseudo_type)
1238857
private function callMethod($method, $params)
    {
        $params['chat_id'] = Conversation::get('lead_id');

        return giga_remote_post($this->getResource($method), $params);
    }
943485
function methodCall(method, args, callback) {
      this.debug('methodCall', method);
      var self = this;

      /**
       * Handle RPC Method Callback.
       *
       * @param {Error} error
       * @param {string} response
       * @returns {*}
       */
      function callbackWrapper(error, response) {
        self.debug('methodCall->callbackWrapper', error, response);
        // TODO: error should be customized to handle more error types
        if (error /*&& error.code === "ENOTFOUND" && error.syscall === "getaddrinfo"*/) {
          error.message = "Unable to connect to WordPress.";
          return callback.call(self, error);
        }

        // Parse Response.
        if (_.isString(response) && self.common.is_numeric(response)) {
          response = parseInt(response);
        }
        callback.call(self, error, response);
      }

      this.__client.rpc.methodCall(
        method,
        args || [],
        callbackWrapper
      );

      // @chainable
      return this;
    }