Method for making requests to the Optimizely API
19987
def request(self, method, url_parts, headers=None, data=None):
        
        if method in self.ALLOWED_REQUESTS:
            # add request token header
            headers = headers or {}

            # test if Oauth token
            if self.token_type == 'legacy':
                headers.update(
                    {'Token': self.api_key,
                     'User-Agent': 'optimizely-client-python/0.1.1'})
            elif self.token_type == 'oauth':
                headers.update(
                    {'Authorization': 'Bearer ' + self.api_key,
                     'User-Agent': 'optimizely-client-python/0.1.1'})
            else:
                raise ValueError(
                    '{} is not a valid token type.'.format(self.token_type))
            # make request and return parsed response
            url = urlparse.urljoin(
                self.api_base,
                '/'.join([str(url_part) for url_part in url_parts])
            )
            return self.parse_response(
                getattr(requests, method)(url, headers=headers, data=data)
            )
        else:
            raise error.BadRequestError(
                '%s is not a valid request type.' % method)
1178982
def do_request_async(self, url, method='GET', headers=None, payload=None,
                       deadline=None, callback=None):
    
    if headers is None:
      headers = {}
    if 'x-goog-api-version' not in headers:
      headers['x-goog-api-version'] = '2'
    headers['accept-encoding'] = 'gzip, *'
    try:
      resp_tuple = yield super(_StorageApi, self).do_request_async(
          url, method=method, headers=headers, payload=payload,
          deadline=deadline, callback=callback)
    except urlfetch.DownloadError as e:
      raise errors.TimeoutError(
          'Request to Google Cloud Storage timed out.', e)

    raise ndb.Return(resp_tuple)
475497
def call_api(http_method, path, opts = {})
      request = build_request(http_method, path, opts)
      response = request.run

      if @config.debugging
        @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
      end

      unless response.success?
        if response.timed_out?
          fail ApiError.new('Connection timed out')
        elsif response.code == 0
          # Errors from libcurl will be made visible here
          fail ApiError.new(:code => 0,
                            :message => response.return_message)
        else
          fail ApiError.new(:code => response.code,
                            :response_headers => response.headers,
                            :response_body => response.body),
               response.status_message
        end
      end

      if opts[:return_type]
        data = deserialize(response, opts[:return_type])
      else
        data = nil
      end
      return data, response.code, response.headers
    end
658520
def request_show(self, id, **kwargs):
        ""
        api_path = "/api/v2/requests/{id}.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, **kwargs)
1159944
function (opts, id) {
        let uri = this.classUrl
        if (id) {
          uri += '/' + id
        }

        return new Promise(function (resolve, reject) {
          new Requestor({ api_version: instance.api_version }).request({
            method: 'post',
            url: [Conekta.api_base, uri].join(''),
            data: opts.data || {},
            next: function (error, response) {
              if (!error) {
                response = this.listObjectsToArray(response)
                this._json = response
                this._id = response.id
                this.build_children()
              }
              if (opts.next !== undefined) {
                opts.next(error, this)
              } else {
                if (error) {
                  reject(error)
                } else {
                  resolve(this)
                }
              }
            }.bind(this)
          })
        }.bind(this))
      }
867004
static function optimizeFunction( $useComments, &$php, $tpl, &$node, &$resourceData )
    {
        $ret = 0;
        /* Just run the optimizer over all parameters */
        if ( isset( $node[3] ) and is_array( $node[3] ) )
        {
            foreach ( $node[3] as $key => $parameter )
            {
                $ret = $ret | eZTemplateOptimizer::optimizeVariable( $useComments, $php, $tpl, $node[3][$key], $resourceData );
            }
        }
        return $ret;
    }
682214
function makeApiUrl(options,parameters) {

    var query = parameters;

    //
    // If any parameter given in array, make it string separated by semicolon(;)
    //
    for(let key in query){
        if( _.isArray(query[key]) ){
            query[key] = _.join(query[key],';');
        }
    }

    let curTime = Math.floor(Date.now() / 1000);
    let randomToken = randomstring.generate(6);

    query.time = curTime;
    query.apiKey  = options.API_KEY;

    //
    // Sort parameters according to codeforces API rules
    //
    query = _
        .chain(query)
        .map( (value, key) => {
            return { key, value };
        })
        .orderBy(['key', 'value'], ['desc', 'desc'])
        .reverse()
        .keyBy('key')
        .mapValues('value')
        .value();

    let qsFy = qs.stringify(query,{ encode: false });
    let apiSig = `${randomToken}/${options.method}?${qsFy}#${options.API_SECRET}`;

    apiSig = sha512(apiSig).toString();
    query.apiSig = randomToken + apiSig;
    qsFy = qs.stringify(query,{ encode: false });

    let url = `${options.API_URL}/${options.method}?${qsFy}`;

    return url;
}
572395
function Request(opts, callback) {
    this.opts = opts;
    this.callback = callback;

    Object.defineProperty(this, 'method', {
        get: function() {
            return opts.method;
        },
    });

    Object.defineProperty(this, 'path', {
        get: function() {
            return opts.uri;
        },
    });

    /**
     * Parse the body of the request as a JSON object and return it.
     */
    Object.defineProperty(this, 'data', {
        get: function() {
            return opts.body ? JSON.parse(opts.body) : opts.body;
        },
    });

    /**
     * Return the raw body passed to request
     */
    Object.defineProperty(this, 'rawData', {
        get: function() {
            return opts.body;
        },
    });

    Object.defineProperty(this, 'queryParams', {
        get: function() {
            return opts.qs;
        },
    });

    Object.defineProperty(this, 'headers', {
        get: function() {
            return opts.headers || {};
        },
    });
}
1202719
def make_request(name, params=None, version="V001", key=None, api_type="web",
                 fetcher=get_page, base=None, language="en_us"):
    

    params = params or {}
    params["key"] = key or API_KEY
    params["language"] = language

    if not params["key"]:
        raise ValueError("API key not set, please set DOTA2_API_KEY")

    url = url_map("%s%s/%s/" % (base or BASE_URL, name, version), params)
    return fetcher(url)
194570
def optimized(fn):
    

    def _optimized(self, *args, **kwargs):
        """ This method calls the pycastC function if
        optimization is enabled and the pycastC function
        is available.

        :param: PyCastObject self: reference to the calling object.
                                    Needs to be passed to the pycastC function,
                                    so that all uts members are available.
        :param: list *args: list of arguments the function is called with.
        :param: dict **kwargs: dictionary of parameter  names and values the function has been called with.

        :return result of the function call either from pycast or pycastC module.
        :rtype: function
        """
        if self.optimizationEnabled:
            class_name = self.__class__.__name__
            module     = self.__module__.replace("pycast", "pycastC")
            try:
                imported = __import__("%s.%s" % (module, class_name), globals(), locals(), [fn.__name__])
                function = getattr(imported, fn.__name__)
                return function(self, *args, **kwargs)
            except ImportError:
                print  "[WARNING] Could not enable optimization for %s, %s" % (fn.__name__, self)
                return fn(self, *args, **kwargs)
        else:
            return fn(self, *args, **kwargs)

    setattr(_optimized, "__name__", fn.__name__)
    setattr(_optimized, "__repr__", fn.__repr__)
    setattr(_optimized, "__str__",  fn.__str__)
    setattr(_optimized, "__doc__",  fn.__doc__)

    return _optimized
1257085
function API(opts) {
  opts = opts || {};

  this.request = opts.request || request;
  this.baseUrl = opts.baseUrl || BASE_URL;
  this.payProHttp = null; // Only for testing
  this.doNotVerifyPayPro = opts.doNotVerifyPayPro;
  this.timeout = opts.timeout || 50000;
  this.logLevel = opts.logLevel || 'silent';
  this.supportStaffWalletId = opts.supportStaffWalletId;

  log.setLevel(this.logLevel);
}
345613
function JSONPPolling (opts) {
  Polling.call(this, opts);

  // define global callbacks array if not present
  // we do this here (lazily) to avoid unneeded global pollution
  if (!callbacks) {
    // we need to consider multiple engines in the same page
    if (!global.___eio) global.___eio = [];
    callbacks = global.___eio;
  }

  // callback identifier
  this.index = callbacks.length;

  // add callback to jsonp global
  var self = this;
  callbacks.push(function (msg) {
    self.onData(msg);
  });

  // append to query string
  this.query.j = this.index;
}
559772
def _requests(self, url, method='GET', headers=None, params=None, data=None, errors=None):

        '''  '''

        title = '%s._requests' % self.__class__.__name__
    
    # import dependencies
        from time import time
        import requests

    # validate access token
        if not self._access_token:
            self.access_token()
            if self.retrieve_details:
                self._get_products()
    
    # refresh token
        current_time = time()
        if current_time > self.expires_at:
            self.access_token()
            if self.retrieve_details:
                self._get_products()

    # construct request kwargs
        request_kwargs = {
            'url': url,
            'headers': { 
                'Authorization': 'Bearer %s' % self._access_token,
                'Accept': 'application/json;v=2'
            },
            'params': {},
            'data': {}
        }
        if headers:
            request_kwargs['headers'].update(headers)
        if params:
            request_kwargs['params'].update(params)
        if data:
            request_kwargs['data'].update(data)

    # send request
        if method == 'POST':
            try:
                response = requests.post(**request_kwargs)
            except Exception:
                if self.requests_handler:
                    request_kwargs['method'] = 'POST'
                    request_object = requests.Request(**request_kwargs)
                    return self.requests_handler(request_object)
                else:
                    raise
        elif method == 'GET':
            try:
                response = requests.get(**request_kwargs)
            except Exception:
                if self.requests_handler:
                    request_kwargs['method'] = 'GET'
                    request_object = requests.Request(**request_kwargs)
                    return self.requests_handler(request_object)
                else:
                    raise
        else:
            raise ValueError('%s(method='') must be either GET or POST' % title)

    # handle response
        response_details = self.response_handler.handle(response, errors)
        
        return response_details
1014696
function () {
    this.worker = new Worker('./js/optimizer-worker.js')
    this.worker.onmessage = function (event) {
      switch (event.data.command) {
        case 'optimized':
          Optimizer.oncomplete(event.data.id, event.data.output, event.data.saved)
      }
    }
    this.worker.onerror = function (event) {
      console.error(event)
    }
  }
925904
def _make_req(self, method, url, methname, headers=None):
        """"""

        # Build up headers
        hset = hdrs.HeaderDict()

        # Walk through our global headers
        for hdr, value in self._headers.items():
            # If it's a callable, call it
            if callable(value):
                value = value(methname)
            else:
                # OK, just stringify it
                value = str(value)

            # If it's meaningful, attach it
            if value:
                hset[hdr] = value

        # Were headers passed in?
        if headers is not None:
            # Update from specified headers
            hset.update(headers)

        # Hook method to instantiate requests
        self._debug("Creating request %s.%s(%r, %r, headers=%r)",
                    self._req_class.__module__, self._req_class.__name__,
                    method, url, hset)
        return self._req_class(method, url, self._client, self._procstack,
                               headers=hset, debug=self._debug)
626260
def _req(self, method="get", verb=None, headers={}, params={}, data={}):
        
        url = self.BASE_URL.format(verb=verb)
        request_headers = {"content-type": "application/json"}
        request_params = {"api_key": self.API_KEY}
        request_headers.update(headers)
        request_params.update(params)
        return getattr(requests, method)(
            url, params=request_params, headers=request_headers, data=data
        )
735103
def request(req=None, method=None, requires_response=True):
    """"""
    if req is None:
        return functools.partial(request, method=method,
                                 requires_response=requires_response)

    @functools.wraps(req)
    def wrapper(self, *args, **kwargs):
        if self.lsp_ready:
            params = req(self, *args, **kwargs)
            if params is not None:
                self.emit_request(method, params, requires_response)
    return wrapper