Retrieve the given association.
@param {Object} req The HTTP request.
@param {Object} res The HTTP result.
180670
function retrieveAssociation(req, res) {
  if(redirect(req.params.id, '', '', res)) {
    return;
  }

  switch(req.accepts(['json', 'html'])) {
    // TODO: support HTML in future
    //case 'html':
    //  res.sendFile(path.resolve(__dirname + '/../../web/association.html'));
    //  break;
    default:
      var id = req.params.id;
      var rootUrl = req.protocol + '://' + req.get('host');
      var queryPath = req.originalUrl;
      req.chickadee.getAssociation(req, id, null, rootUrl, queryPath,
                                   function(response, status) {
        res.status(status).json(response);
      });
      break;
  }
}
253349
function (req, res) {

            //To avoid errors, escape table
            req.params.table = escape(req.params.table);

            //Get all fields from table
            lastQry = connection.query('SHOW COLUMNS FROM ??', req.params.table, function (err, rows) {
                if (err) return sendError(res, err.code);


                var fields, limit, order, where;


                //All general Settings


                //Select only certain columns?
                if (typeof req.query[settings.paramPrefix + "fields"] !== "undefined" && typeof req.query[settings.paramPrefix + "fields"] == "string" && req.query[settings.paramPrefix + "fields"] !== "") {
                    var req_fields = escape(req.query[settings.paramPrefix + "fields"]);
                    if (checkIfFieldsExist(req_fields, rows)) {
                        fields = req_fields;
                    } else {
                        return sendError(res, "Failed to fetch all fields specified in _fields");
                    }
                } else {
                    fields = '*';
                }

                //Parse order by and order direction
                if (typeof req.query[settings.paramPrefix + "order"] !== "undefined" && typeof req.query[settings.paramPrefix + "order"] === "object") {
                    var orderObj = req.query[settings.paramPrefix + "order"];
                    var orderArr = [];
                    for (var order_field in orderObj) {
                        if (orderObj.hasOwnProperty(order_field)) {
                            if (checkIfFieldsExist(order_field, rows)) {
                                if (orderObj[order_field].toUpperCase() == "ASC" || orderObj[order_field].toUpperCase() == "DESC") {
                                    orderArr.push(req.params.table + ".`" + order_field + "` " + orderObj[order_field].toUpperCase());
                                } else {
                                    return sendError(res, "Order option for " + order_field + " in _order is invalid. Please use either ASC or DESC");
                                }
                            } else {
                                return sendError(res, "Failed to fetch " + order_field + " specified in _order");
                            }
                        }
                    }
                    order = orderArr.join(',');
                }

                //Parse limit
                if (typeof req.query[settings.paramPrefix + "limit"] !== "undefined" && typeof req.query[settings.paramPrefix + "limit"] === "string" && req.query[settings.paramPrefix + "limit"] !== "") {

                    var limitStr = req.query[settings.paramPrefix + "limit"];


                    var limitArr = limitStr.split(',');
                    if (limitArr.length > 2) {
                        return sendError(res, "Limit specificed in _limit is invalid. Limit does not allow more than 2 comma separated values");
                    }
                    for (var i = 0; i < limitArr.length; i++) {
                        var lim = parseInt(limitArr[i]);
                        if (isNaN(lim)) {
                            return sendError(res, "Limit specificed in _limit is invalid. Please use a comma to separate start and amount");
                        }
                        limitArr[i] = lim;
                    }

                    limit = limitArr.join(',');

                }


                //Parse all other get params as selector
                var whereArr = [];

                for (var q in req.query) {
                    if (req.query.hasOwnProperty(q)) {
                        if (q.substr(0, 1) !== settings.paramPrefix) {
                            if (checkIfFieldsExist(q, rows)) {

                                if (typeof req.query[q] === "string") {
                                    //If it is a simple string, the api assumes = as the operator
                                    whereArr.push(mysql.format('?? = ?', [q, escape(req.query[q])]));

                                } else if (typeof req.query[q] === "object") {

                                    for (var selector in req.query[q]) {
                                        if (req.query[q].hasOwnProperty(selector)) {
                                            var op, val = connection.escape(escape(req.query[q][selector]));
                                            //MYSQLify the operator
                                            switch (selector.toUpperCase()) {
                                                case 'GREAT':
                                                    op = "> ";
                                                    break;
                                                case 'SMALL':
                                                    op = "< ";
                                                    break;
                                                case 'EQGREAT':
                                                    op = '>= ';
                                                    break;
                                                case 'EQSMALL':
                                                    op = '<= ';
                                                    break;
                                                case 'IN':
                                                    op = 'IN (';
                                                    val = escape(req.query[q][selector]).split(',').map(function (item) {
                                                        return connection.escape(item);
                                                    }).join(',') + ')';
                                                    break;
                                                case 'LIKE':
                                                    op = 'LIKE ';                                            
                                                    break;
                                                case 'EQ':
                                                    op = '= ';
                                                    break;
                                                default:
                                                    op = '= ';
                                                    break;
                                            }
                                            whereArr.push(mysql.format('?? ' + op + val, [q]));
                                        }
                                    }

                                } else {
                                    return sendError(res, "Can't read parameter specified for the field " + q + " in the table " + req.params.table);
                                }


                            } else {
                                return sendError(res, "Can't find the field" + q + " in the table " + req.params.table);
                            }
                        }
                    }
                }

                if (whereArr.length > 0) {
                    where = whereArr.join(' AND ')
                }

                //Bring in MYSQL syntax
                fields = fields ? fields : '*';
                order = order ? 'ORDER BY ' + order : '';
                limit = limit ? 'LIMIT ' + limit : '';
                where = where ? 'WHERE ' + where : '';

                //Fire query
                lastQry = connection.query("SELECT " + fields + " FROM ?? " + where + " " + order + " " + limit, [req.params.table], function (err, rows) {
                    if (err) return sendError(res, err.code);
                    res.send({
                        result: 'success',
                        json: rows,
                        table: req.params.table,
                        length: rows.length
                    });
                });
            });
        }
869199
def process_request(self, req, resp):  # pylint: disable=unused-argument
        

        try:
            creds = self._get_creds(req)
            self.auth_creds(*creds)
        except (AuthRejected, AuthRequired, InvalidAuthSyntax) as exc:
            exc.headers = self._error_headers
            if not self.optional:
                abort(exc)
1207200
function zrevrank(key, member, req) {
  var zset = this.getKey(key, req);
  if(zset === undefined) return null;
  return zset.zrevrank(member);
}
857736
function getModel(req, res, next, model) {
		var fullModel = Rhapsody.requireModel(model, true);

		if(!fullModel) {
			Rhapsody.log.verbose('Nonexistent model', 'Couldn\'t find collection %s.', model);
			return responseUtils.respond(res, 400); //Malformed syntax or a bad query
		}

		//This model does not allow REST API
		if(!fullModel.options.allowREST) {
			return responseUtils.respond(res, 404);
		}

		req.fullModel = fullModel;

		next();
	}
1112500
function(req, res) {
    let id = req.allParams()['id'];
    let model = pluralize.singular(req.param('model'));

    req.options.controller = model;
    req.options.model = model;

    if (sails.controllers[model].update !== undefined) {
      return sails.controllers[model].update(req, res);
    } else {
      req.body = JsonApiService.deserialize(req.body);
      return JsonApiService.updateOneRecord(req, res);
    }
  }
124653
function(req){
    var params = req.params.all();
    _.merge(params, req.headers);
    return _.merge(params, req.query);
  }
29991
function getBearerToken (req, res, next) {
  // check for access token in the authorization header
  if (req.authorization.scheme && req.authorization.scheme.match(/Bearer/i)) {
    req.bearer = req.authorization.credentials
  }

  // check for access token in the query params
  if (req.query && req.query.access_token) {
    if (req.bearer) {
      return next(new UnauthorizedError({
        error: 'invalid_request',
        error_description: 'Multiple authentication methods',
        statusCode: 400
      }))
    }

    req.bearer = req.query.access_token
  }

  // check for access token in the request body
  if (req.body && req.body.access_token) {
    if (req.bearer) {
      return next(new UnauthorizedError({
        error: 'invalid_request',
        error_description: 'Multiple authentication methods',
        statusCode: 400
      }))
    }

    if (req.headers &&
      req.headers['content-type'] !== 'application/x-www-form-urlencoded') {
      return next(new UnauthorizedError({
        error: 'invalid_request',
        error_description: 'Invalid content-type',
        statusCode: 400
      }))
    }

    req.bearer = req.body.access_token
  }

  next()
}
1160531
function fetchExternals(request, body) {

    var includes = parseIncludes(request);
    var user = request.user;
    var requestsByType = groupIncludes(includes, body);

    return when.all(_.map(requestsByType, function(requestData, ancestorType) {
        var ids = _.uniq(requestData.ids);
        return fetchAncestor(ancestorType, ids, _.compact(_.map(requestData.includes, function(i) { return _.rest(i).join("."); })).join(","), request)
          .then(function(response){
            return response;
          })
          .then(function(data) {
            _.each(requestData.includes, function(split) {
              mergeAncestorData(body, split, ancestorType, data);
            });
          })
          .catch(function(err) { console.trace(err.stack || err); });
      })).then(function() {
        return body;
      });
  }
250638
async function retrieveUserFromRedis(res, auth, tokenOrEmail, config) {
  if (config.redisClient) {
    const getFromRedis = util
      .promisify(config.redisClient.get)
      .bind(config.redisClient);
    const cachedUserData = await getFromRedis(`${ns}:${tokenOrEmail}`);
    if (cachedUserData) {
      const data = JSON.parse(cachedUserData);
      const user = auth.createAuthFromData(data);
      auth.currentUser = user;
      res.locals = res.locals || {};
      res.locals.auth = auth;
      return user;
    }
  }
}
922124
function (req, res) {

      var event = req.stripeEvent;
      var data = event.data.object;

      // takes care of unexpected event types
      var transactionMethod = stripeTransactions[event.type] || stripeTransactions.unhandled;

      transactionMethod(req, data, function (err){
        if ( !err ) {
          return res.send(200);
        }
        console.log('stripe webhook error');
        console.log(event.type);
        console.log(err.stack);
        res.send(500, err);
      });

    }
1226877
function get (req, res, next) {
    var prop = pluralize.singular(req.params.resource)
    req.query[prop + 'Id'] = utils.toNative(req.params.id)
    if (!req.query._filter) {
      req.query._filter = prop + 'Id=' + req.params.id
    } else {
      req.query._filter += ',' + prop + 'Id=' + req.params.id
    }
    req.url = '/' + req.params.nested
    next()
  }
385924
function (req, res) {
    var oauthQueryStateToken = req.query.state;
    var oauthCookieStateToken = req.cookies.oauthStateToken;

    if (!oauthQueryStateToken || (!oauthCookieStateToken)) {
      return false;
    } else if (oauthQueryStateToken !== oauthCookieStateToken) {
      return false;
    }

    res.clearCookie('oauthStateToken');

    return true;
  }
1223134
function present(req, res, next) {

    // Sort
    if (req._internal._sort) {
      req._internal._order = req._internal._order || 'ASC'
      req._internal.resource = _.sortBy(req._internal.resource, function (element) {
        return element[req._internal._sort]
      })
      if (req._internal._order === 'DESC') {
        req._internal.resource.reverse()
      }
    }

    // Slice result
    if (req._internal._end || req._internal._limit) {
      res.setHeader('X-Total-Count', req._internal.resource.length)
      res.setHeader('Access-Control-Expose-Headers', 'X-Total-Count')
    }
    req._internal._start = parseInt(req._internal._start) || 0
    if (req._internal._end) {
      req._internal.resource = req._internal.resource.slice(req._internal._start, parseInt(req._internal._end))
    } else if (req._internal._limit) {

      // Convert strings to int and sum to get end value
      req._internal.resource = req._internal.resource.slice(req._internal._start, parseInt(req._internal._start) + parseInt(req._internal._limit))
    }
    res.jsonp(req._internal.resource)
  }
407074
function RestAPI() {
  this.models = {};
  this.router = express.Router();
  this.router.use(require('res-error')({
    log: false
  }));
}
1081853
function getAssociated(name) {
  const path = ['__jsmf__', 'associated']
  if (name !== undefined) {
    path.push(name)
  }
  return _.get(this, path)
}
767395
def get(path, params = nil, headers = {}, auth = true)
      request(path: path, query: params, headers: headers, auth: auth)
    end