Transforms Swagger query params into correct JSON Schema
@param {Object} queryModel - Swagger query params model
@returns {Object} JSON Schema object
763092
function swaggerQueryParamsToSchema(queryModel) {
  const requiredFields = [];
  const transformedProperties = {};
  _.forOwn(queryModel.items.properties, (value, key) => {
    if (value.required) {
      requiredFields.push(key);
    }
    transformedProperties[key] = {
      ...value
    };

    if (!_.isNil(transformedProperties[key].required)) {
      delete transformedProperties[key].required;
    }
  });

  return {
    title: queryModel.title,
    description: queryModel.description,
    additionalProperties: false,
    required: requiredFields,
    properties: transformedProperties
  };
}
679368
function convertAndMergeHiddenQueryProps(model, json, omitProps, builder) {
  const queryProps = model[QUERY_PROPS_PROPERTY];

  if (!queryProps) {
    // The model has no query properties.
    return json;
  }

  const modelClass = model.constructor;
  const keys = Object.keys(queryProps);

  for (let i = 0, l = keys.length; i < l; ++i) {
    const key = keys[i];

    if (!omitProps || !omitProps.includes(key)) {
      const queryProp = queryPropToKnexRaw(queryProps[key], builder);
      json[modelClass.propertyNameToColumnName(key)] = queryProp;
    }
  }

  return json;
}
422121
def _parse_query_dict(query_data, model):
        
        operator = 'iexact'
        if query_data['field'] == '_OR':
            query_data['operator'] = operator
            return query_data

        parts = query_data['field'].split('__')
        if len(parts) < 2:
            field = parts[0]
        else:
            if parts[-1] in dict(AdvancedFilterQueryForm.OPERATORS).keys():
                field = '__'.join(parts[:-1])
                operator = parts[-1]
            else:
                field = query_data['field']

        query_data['field'] = field
        mfield = get_fields_from_path(model, query_data['field'])
        if not mfield:
            raise Exception('Field path "%s" could not be followed to a field'
                            ' in model %s', query_data['field'], model)
        else:
            mfield = mfield[-1]  # get the field object

        if query_data['value'] is None:
            query_data['operator'] = "isnull"
        elif query_data['value'] is True:
            query_data['operator'] = "istrue"
        elif query_data['value'] is False:
            query_data['operator'] = "isfalse"
        else:
            if isinstance(mfield, DateField):
                # this is a date/datetime field
                query_data['operator'] = "range"  # default
            else:
                query_data['operator'] = operator  # default

        if isinstance(query_data.get('value'),
                      list) and query_data['operator'] == 'range':
            date_from = date_to_string(query_data.get('value_from'))
            date_to = date_to_string(query_data.get('value_to'))
            query_data['value'] = ','.join([date_from, date_to])

        return query_data
1242524
def build_request_to_validator_map(schema, resolver):
    
    schema_models = schema.get('models', {})
    return dict(
        (
            RequestMatcher(api['path'], operation['method']),
            ValidatorMap.from_operation(operation, schema_models, resolver)
        )
        for api in schema['apis']
        for operation in api['operations']
    )
289405
private void generateQuery(SQLiteDatabaseSchema schema) {
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("query").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).returns(Cursor.class);
		methodBuilder.addParameter(Uri.class, "uri");
		methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(String.class), "projection").build());
		methodBuilder.addParameter(String.class, "selection");
		methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(String.class), "selectionArgs").build());
		methodBuilder.addParameter(String.class, "sortOrder");

		boolean hasOperation = hasOperationOfType(schema, methodBuilder, JQLType.SELECT);

		if (!hasOperation) {
			methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.SELECT);
			classBuilder.addMethod(methodBuilder.build());
			return;
		}

		methodBuilder.addStatement("$T returnCursor=null", Cursor.class);

		for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
			for (SQLiteModelMethod daoMethod : daoDefinition.getCollection()) {
				if (daoMethod.jql.operationType != JQLType.SELECT)
					continue;
				// methodBuilder.addJavadoc("method $L.$L\n",
				// daoDefinition.getName(), daoMethod.getName());
			}
		}

		defineJavadocHeaderForContentOperation(methodBuilder, "query");

		methodBuilder.beginControlFlow("switch (sURIMatcher.match(uri))");
		for (Entry<String, ContentEntry> item : uriSet.entrySet()) {
			if (item.getValue().select == null)
				continue;

			defineJavadocForContentUri(methodBuilder, item.getValue().select);

			// methodBuilder.addJavadoc("uri $L\n", item.getKey());

			methodBuilder.beginControlFlow("case $L:", item.getValue().pathIndex);
			methodBuilder.addCode("// URI: $L\n", item.getValue().select.contentProviderUri());
			methodBuilder.addStatement("returnCursor=dataSource.get$L().$L(uri, projection, selection, selectionArgs, sortOrder)", item.getValue().select.getParent().getName(),
					item.getValue().select.contentProviderMethodName);
			methodBuilder.addStatement("break");
			methodBuilder.endControlFlow();
		}
		methodBuilder.beginControlFlow("default:");
		methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.SELECT);
		methodBuilder.endControlFlow();

		methodBuilder.endControlFlow();

		defineJavadocFooterForContentOperation(methodBuilder);

		if (hasOperation) {
			methodBuilder.addStatement("return returnCursor");
		}

		classBuilder.addMethod(methodBuilder.build());
	}
1013085
def get_swagger_view(title=None, url=None, patterns=None, urlconf=None):
    
    class SwaggerSchemaView(APIView):
        _ignore_model_permissions = True
        exclude_from_schema = True
        permission_classes = [AllowAny]
        renderer_classes = [
            CoreJSONRenderer,
            renderers.OpenAPIRenderer,
            renderers.SwaggerUIRenderer
        ]

        def get(self, request):
            generator = SchemaGenerator(
                title=title,
                url=url,
                patterns=patterns,
                urlconf=urlconf
            )
            schema = generator.get_schema(request=request)

            if not schema:
                raise exceptions.ValidationError(
                    'The schema generator did not return a schema Document'
                )

            return Response(schema)

    return SwaggerSchemaView.as_view()
376167
function convertExistingQueryProps(json, builder) {
  const keys = Object.keys(json);

  for (let i = 0, l = keys.length; i < l; ++i) {
    const key = keys[i];
    const value = json[key];

    if (isQueryProp(value)) {
      json[key] = queryPropToKnexRaw(value, builder);
    }
  }

  return json;
}
441779
function initModelSchema (args) {
    var controller = this
    var model = this.model
    // if model does not have schema do not create schema controller
    if (!model.schemaData) {
        return
    }
    // get accountId column
    var accountIdColumn = model.columnName('accountId') 
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // index inputs
    var input = {
        // optionally get schema for action
        action: 'query.action',
        // get full schema including meta data
        meta: 'query.meta',
    }
    // create path if it does not exist
    if (!this.paths['/schema']) {
        this.paths['/schema'] = {}
    }
    // add GET /schema handler
    this.paths['/schema'].get = [
        {
            input: input,
            method: function (args) {
                return schema(controller, args)
            },
            methodName: 'schema',
            role: role,
        }
    ]
}
1127516
def params_to_mongo(query_params):
    
    if not query_params:
        return {}
    for key, value in query_params.items():
        if isinstance(value, list):
            query_params[key] = {'$in': value}
    return query_params
66505
function doQuery(options) {
            return models.Tag.add(options.data.tags[0], _.omit(options, ['data']))
                .then((model) => {
                    return {
                        tags: [urlsForTag(model.id, model.toJSON(options), options)]
                    };
                });
        }
570025
private String buildJsonSchemaRefForModel(Class<?> modelClass, File artifactFile) {
    try {
      ZipFile zipFile = new ZipFile(artifactFile);
      String halDocsDomainPath = getHalDocsDomainPath(zipFile);
      if (halDocsDomainPath != null && hasJsonSchemaFile(zipFile, modelClass)) {
        return JsonSchemaBundleTracker.SCHEMA_URI_PREFIX + halDocsDomainPath
            + "/" + modelClass.getName() + ".json";
      }
      return null;
    }
    catch (IOException ex) {
      throw new RuntimeException("Unable to read artifact file: " + artifactFile.getAbsolutePath() + "\n" + ex.getMessage(), ex);
    }
  }
354766
function(query) {
        var queryObj = {q: ''};
        if(!query) {
            return queryObj;
        }

        var qArray = query.split('&');
        var qObj = qs.parse(query);
        for(var i = 0, len = qArray.length; i < len; i++) {
            var queryItem = decodeURIComponent(qArray[i]).replace('=', '');
            if(/^\?/g.test(queryItem)) {
                debug('matched query: %s', queryItem) ;
                queryObj.q = queryItem;
                break;
            }
        }

        queryObj.m = qObj._mcss == 'true' || qObj._mcss == 'y';
        return queryObj;
    }
1213250
function modelQuery(options) {
            return models.Post.add(options.data.posts[0], omit(options, ['data']))
                .then((model) => {
                    const post = urlsForPost(model.id, model.toJSON(options), options);

                    if (post.status === 'published') {
                        // When creating a new post that is published right now, signal the change
                        post.statusChanged = true;
                    }

                    return {posts: [post]};
                });
        }
1351992
function ( req, model ) {
		// Create data object (monolithic combination of all parameters)
		// Omit the blacklisted params (like JSONP callback param, etc.)

		// Allow customizable blacklist for params NOT to include as values.
		req.options.values = req.options.values || {};
		req.options.values.blacklist = req.options.values.blacklist;

		// Validate blacklist to provide a more helpful error msg.
		var blacklist = req.options.values.blacklist;
		if ( blacklist && !_.isArray( blacklist ) ) {
			throw new Error( 'Invalid `req.options.values.blacklist`. Should be an array of strings (parameter names.)' );
		}

		// Get values using the model identity as resource identifier
		var values = req.param( _.kebabCase( model.globalId ) ) || {};

		// Omit built-in runtime config (like query modifiers)
		values = _.omit( values, blacklist || [] );

		// Omit any params w/ undefined values
		values = _.omit( values, function ( p ) {
			if ( _.isUndefined( p ) ) return true;
		} );

		// Omit jsonp callback param (but only if jsonp is enabled)
		var jsonpOpts = req.options.jsonp && !req.isSocket;
		jsonpOpts = _.isObject( jsonpOpts ) ? jsonpOpts : {
			callback: JSONP_CALLBACK_PARAM
		};
		if ( jsonpOpts ) {
			values = _.omit( values, [ jsonpOpts.callback ] );
		}

		return values;
	}
905762
def validate_query_params(self, request):
        
        # TODO: For jsonapi error object conformance, must set jsonapi errors "parameter" for
        # the ValidationError. This requires extending DRF/DJA Exceptions.
        for qp in request.query_params.keys():
            if not self.query_regex.match(qp):
                raise ValidationError('invalid query parameter: {}'.format(qp))
            if len(request.query_params.getlist(qp)) > 1:
                raise ValidationError(
                    'repeated query parameter not allowed: {}'.format(qp))
937798
function filterJson(query, data) {
  let newData = data;

  if ('summary' in query) {
    newData = _(data).reduce((memo, layer) => {
      memo[layer.name] = {
        features: layer.features.length,
        jsonsize: JSON.stringify(layer).length,
      };
      return memo;
    }, {});
  } else if ('nogeo' in query) {
    // Recursively remove all "geometry" fields, replacing them with geometry's size
    const filter = (val, key) => {
      if (key === 'geometry') {
        return val.length;
      } else if (_.isArray(val)) {
        return _.map(val, filter);
      } else if (_.isObject(val)) {
        _.each(val, (v, k) => {
          val[k] = filter(v, k);
        });
      }
      return val;
    };
    newData = _.map(data, filter);
  }
  return newData;
}
847031
function modelQuery(options) {
            return models.Role.findAll(options)
                .then((models) => {
                    let roles = models.map((role) => {
                        return role.toJSON();
                    });

                    if (options.permissions !== 'assign') {
                        return {roles: roles};
                    }

                    return Promise.filter(roles.map((role) => {
                        return canThis(options.context).assign.role(role)
                            .return(role)
                            .catch(() => {});
                    }), (value) => {
                        return value && value.name !== 'Owner';
                    }).then((roles) => {
                        return {
                            roles: roles
                        };
                    });
                });
        }