Check for the validify of the filter.
976409
def check_filter_validity(self, reply, filter_str):
        
        try:
            f_ind = reply.index(filter_str)
            l_ind = reply.rindex(filter_str)
        except Exception:
            fail_reason = vdp_const.filter_failure_reason % (reply)
            LOG.error("%s", fail_reason)
            return False, fail_reason
        if f_ind != l_ind:
            # Currently not supported if reply contains a filter keyword
            fail_reason = vdp_const.multiple_filter_failure_reason % (reply)
            LOG.error("%s", fail_reason)
            return False, fail_reason
        return True, None
322520
def is_valid(self, value):
        ''' 

        '''
        try:
            if validation_on():
                self.validate(value, False)
        except ValueError:
            return False
        else:
            return True
386749
def is_api_filter(self, filter_field):
        """"""
        if self.filter_type == 'server':
            for choice in self.filter_choices:
                if (choice[0] == filter_field and len(choice) > 2 and
                        choice[2]):
                    return True
        return False
330386
public function validate(): void
    {
        $this->validateRootFilter();
        $this->validateRelations();
        $this->validateSorts();
        $this->validateOffset();
        $this->validateLimit();
        $this->validateFields();
    }
924259
private boolean matches(String filter, String value) {
        if (filter == null) {
            return true;
        }
        return filter.equals(value);
    }
1036658
def validate_a_time_filter(self, value):
        
        if value:
            try:
                utils.parse_datetime_range(value)
            except Exception as e:
                raise serializers.ValidationError(e.message)

        return value
120336
def _applyFilter(lst, filterMethod, filterArgs):
        '''
            
        '''
        if filterMethod == FILTER_METHOD_AND:
            return lst.filterAnd(**filterArgs)
        else: # ALready validated in addFIlter that type is AND or OR
            return lst.filterOr(**filterArgs)
261563
function validateDefinition(conn, arrDefinition, objUnit, objValidationState, bAssetCondition, handleResult){
	
	function getFilterError(filter){
		if (!filter)
			return "no filter";
		if (hasFieldsExcept(filter, ["what", "asset", "type", "own_funds", "address", "amount", "amount_at_least", "amount_at_most"]))
			return "unknown fields in filter";
		if (filter.what !== "input" && filter.what !== "output")
			return "invalid what="+filter.what;
		if (bAssetCondition && filter.asset === "this asset" && objValidationState.bDefiningPrivateAsset)
			return "private asset cannot reference itself";
		if ("asset" in filter && !(filter.asset === "base" || isStringOfLength(filter.asset, constants.HASH_LENGTH) || bAssetCondition && filter.asset === "this asset"))
			return "invalid asset: "+filter.asset;
		if (filter.what === "output"){
			if ("type" in filter)
				return "output canot have type";
			if ("own_funds" in filter)
				return "output canot have own_funds";
		}
		if (bAssetCondition && "own_funds" in filter)
			return "asset condition cannot be filtered by own_funds";
		if ("type" in filter && filter.type !== "issue" && filter.type !== "transfer")
			return "invalid type: "+filter.type;
		if ("own_funds" in filter && typeof filter.own_funds !== "boolean")
			return "own_funds must be boolean";
		if (bAssetCondition && filter.address === 'this address')
			return "asset condition cannot reference this address";
		if ("address" in filter && !isValidAddress(filter.address) && filter.address !== 'this address') // it is ok if the address was never used yet
			return "invalid address: "+filter.address;
		if ("amount" in filter && !isPositiveInteger(filter.amount))
			return "amount must be positive int";
		if ("amount_at_least" in filter && !isPositiveInteger(filter.amount_at_least))
			return "amount_at_least must be positive int";
		if ("amount_at_most" in filter && !isPositiveInteger(filter.amount_at_most))
			return "amount_at_most must be positive int";
		if (filter.amount && (filter.amount_at_least || filter.amount_at_most))
			return "can't have amount and amount_at_least/most at the same time";
		return null;
	}
	
	// it is difficult to ease this condition for bAssetCondition:
	// we might allow _this_ asset (the asset this condition is attached to) to be private but we might have only part of this asset's payments disclosed,
	// some parties may see more disclosed than others.
	function determineIfAnyOfAssetsIsPrivate(arrAssets, cb){
		if (arrAssets.length === 0)
			return cb(false);
		conn.query("SELECT 1 FROM assets WHERE unit IN(?) AND is_private=1 LIMIT 1", [arrAssets], function(rows){
			cb(rows.length > 0);
		});
	}
	
	function evaluate(arr, bInNegation, cb){
		complexity++;
		if (complexity > constants.MAX_COMPLEXITY)
			return cb("complexity exceeded");
		if (!isArrayOfLength(arr, 2))
			return cb("expression must be 2-element array");
		var op = arr[0];
		var args = arr[1];
		switch(op){
			case 'or':
			case 'and':
				if (!Array.isArray(args))
					return cb(op+" args must be array");
				if (args.length < 2)
					return cb(op+" must have at least 2 options");
				var count_options_with_sig = 0;
				async.eachSeries(
					args,
					function(arg, cb2){
						evaluate(arg, bInNegation, function(err, bHasSig){
							if (err)
								return cb2(err);
							if (bHasSig)
								count_options_with_sig++;
							cb2();
						});
					},
					function(err){
						if (err)
							return cb(err);
						cb(null, op === "and" && count_options_with_sig > 0 || op === "or" && count_options_with_sig === args.length);
					}
				);
				break;
				
			case 'r of set':
				if (hasFieldsExcept(args, ["required", "set"]))
					return cb("unknown fields in "+op);
				if (!isPositiveInteger(args.required))
					return cb("required must be positive");
				if (!Array.isArray(args.set))
					return cb("set must be array");
				if (args.set.length < 2)
					return cb("set must have at least 2 options");
				if (args.required > args.set.length)
					return cb("required must be <= than set length");
				//if (args.required === args.set.length)
				//    return cb("required must be strictly less than set length, use and instead");
				//if (args.required === 1)
				//    return cb("required must be more than 1, use or instead");
				var count_options_with_sig = 0;
				async.eachSeries(
					args.set,
					function(arg, cb2){
						evaluate(arg, bInNegation, function(err, bHasSig){
							if (err)
								return cb2(err);
							if (bHasSig)
								count_options_with_sig++;
							cb2();
						});
					},
					function(err){
						if (err)
							return cb(err);
						var count_options_without_sig = args.set.length - count_options_with_sig;
						cb(null, args.required > count_options_without_sig);
					}
				);
				break;
				
			case 'weighted and':
				if (hasFieldsExcept(args, ["required", "set"]))
					return cb("unknown fields in "+op);
				if (!isPositiveInteger(args.required))
					return cb("required must be positive");
				if (!Array.isArray(args.set))
					return cb("set must be array");
				if (args.set.length < 2)
					return cb("set must have at least 2 options");
				var weight_of_options_with_sig = 0;
				var total_weight = 0;
				async.eachSeries(
					args.set,
					function(arg, cb2){
						if (hasFieldsExcept(arg, ["value", "weight"]))
							return cb2("unknown fields in weighted set element");
						if (!isPositiveInteger(arg.weight))
							return cb2("weight must be positive int");
						total_weight += arg.weight;
						evaluate(arg.value, bInNegation, function(err, bHasSig){
							if (err)
								return cb2(err);
							if (bHasSig)
								weight_of_options_with_sig += arg.weight;
							cb2();
						});
					},
					function(err){
						if (err)
							return cb(err);
						if (args.required > total_weight)
							return cb("required must be <= than total weight");
						var weight_of_options_without_sig = total_weight - weight_of_options_with_sig;
						cb(null, args.required > weight_of_options_without_sig);
					}
				);
				break;
				
			case 'sig':
				if (bInNegation)
					return cb(op+" cannot be negated");
				if (bAssetCondition)
					return cb("asset condition cannot have "+op);
				if (hasFieldsExcept(args, ["algo", "pubkey"]))
					return cb("unknown fields in "+op);
				if (args.algo === "secp256k1")
					return cb("default algo must not be explicitly specified");
				if ("algo" in args && args.algo !== "secp256k1")
					return cb("unsupported sig algo");
				if (!isStringOfLength(args.pubkey, constants.PUBKEY_LENGTH))
					return cb("wrong pubkey length");
				return cb(null, true);
				
			case 'hash':
				if (bInNegation)
					return cb(op+" cannot be negated");
				if (bAssetCondition)
					return cb("asset condition cannot have "+op);
				if (hasFieldsExcept(args, ["algo", "hash"]))
					return cb("unknown fields in "+op);
				if (args.algo === "sha256")
					return cb("default algo must not be explicitly specified");
				if ("algo" in args && args.algo !== "sha256")
					return cb("unsupported hash algo");
				if (!ValidationUtils.isValidBase64(args.hash, constants.HASH_LENGTH))
					return cb("wrong base64 hash");
				return cb();
				
			case 'address':
				if (objValidationState.bNoReferences)
					return cb("no references allowed in address definition");
				if (bInNegation)
					return cb(op+" cannot be negated");
				if (bAssetCondition)
					return cb("asset condition cannot have "+op);
				var other_address = args;
				if (!isValidAddress(other_address))
					return cb("invalid address");
				storage.readDefinitionByAddress(conn, other_address, objValidationState.last_ball_mci, {
					ifFound: function(arrInnerAddressDefinition){
						console.log("inner address:", arrInnerAddressDefinition);
						evaluate(arrInnerAddressDefinition, bInNegation, cb);
					},
					ifDefinitionNotFound: function(definition_chash){
					//	if (objValidationState.bAllowUnresolvedInnerDefinitions)
					//		return cb(null, true);
						var bAllowUnresolvedInnerDefinitions = !(constants.version === '1.0t' && constants.alt === '1');
						var arrDefiningAuthors = objUnit.authors.filter(function(author){
							return (author.address === other_address && objectHash.getChash160(author.definition) === definition_chash);
						});
						if (arrDefiningAuthors.length === 0) // no address definition in the current unit
							return bAllowUnresolvedInnerDefinitions ? cb(null, true) : cb("definition of inner address "+other_address+" not found");
						if (arrDefiningAuthors.length > 1)
							throw "more than 1 address definition";
						var arrInnerAddressDefinition = arrDefiningAuthors[0].definition;
						evaluate(arrInnerAddressDefinition, bInNegation, cb);
					}
				});
				break;
				
			case 'definition template':
				// ['definition template', ['unit', {param1: 'value1'}]]
				if (objValidationState.bNoReferences)
					return cb("no references allowed in address definition");
				if (!isArrayOfLength(args, 2))
					return cb("2-element array expected in "+op);
				var unit = args[0];
				var params = args[1];
				if (!isStringOfLength(unit, constants.HASH_LENGTH))
					return cb("unit must be 44 bytes long");
				if (!ValidationUtils.isNonemptyObject(params))
					return cb("params must be non-empty object");
				for (var key in params)
					if (typeof params[key] !== "string" && typeof params[key] !== "number")
						return cb("each param must be string or number");
				conn.query(
					"SELECT payload FROM messages JOIN units USING(unit) \n\
					WHERE unit=? AND app='definition_template' AND main_chain_index<=? AND +sequence='good' AND is_stable=1", 
					[unit, objValidationState.last_ball_mci], 
					function(rows){
						if (rows.length !== 1)
							return cb("template not found or too many");
						var template = rows[0].payload;
						var arrTemplate = JSON.parse(template);
						try{
							var arrFilledTemplate = replaceInTemplate(arrTemplate, params);
							console.log(require('util').inspect(arrFilledTemplate, {depth: null}));
						}
						catch(e){
							if (e instanceof NoVarException)
								return cb(e.toString());
							else
								throw e;
						}
						evaluate(arrFilledTemplate, bInNegation, cb);
					}
				);
				break;
				
			case 'seen address':
				if (objValidationState.bNoReferences)
					return cb("no references allowed in address definition");
				if (!isValidAddress(args)) // it is ok if the address was never used yet
					return cb("invalid seen address");
				return cb();
				
			case 'seen definition change':
			case 'has definition change':
				if (objValidationState.bNoReferences)
					return cb("no references allowed in address definition");
				if (!isArrayOfLength(args, 2))
					return cb(op+" must have 2 args");
				var changed_address = args[0];
				var new_definition_chash = args[1];
				if (bAssetCondition && (changed_address === 'this address' || new_definition_chash === 'this address'))
					return cb("asset condition cannot reference this address in "+op);
				if (!isValidAddress(changed_address) && changed_address !== 'this address') // it is ok if the address was never used yet
					return cb("invalid changed address");
				if (!isValidAddress(new_definition_chash) && new_definition_chash !== 'this address')
					return cb("invalid new definition chash");
				return cb();
				
			case 'cosigned by':
				if (bInNegation)
					return cb(op+" cannot be negated");
				if (!isValidAddress(args)) // it is ok if the address was never used yet
					return cb("invalid cosigner address");
				return cb();
				
			case 'not':
				evaluate(args, true, cb);
				break;
				
			case 'in data feed':
				if (objValidationState.bNoReferences)
					return cb("no references allowed in address definition");
				if (!Array.isArray(args))
					return cb(op+" arg must be array");
				if (args.length !== 4 && args.length !== 5)
					return cb(op+" must have 4 or 5 args");
				var arrAddresses = args[0];
				var feed_name = args[1];
				var relation = args[2];
				var value = args[3];
				var min_mci = args[4];
				if (!isNonemptyArray(arrAddresses))
					return cb("no addresses in "+op);
				for (var i=0; i<arrAddresses.length; i++)
					if (!isValidAddress(arrAddresses[i])) // it is ok if the address was never used yet
						return cb("address "+arrAddresses[i]+" not valid");
				complexity += arrAddresses.length-1; // 1 complexity point for each address (1 point was already counted)
				if (!isNonemptyString(relation))
					return cb("no relation");
				if (["=", ">", "<", ">=", "<=", "!="].indexOf(relation) === -1)
					return cb("invalid relation: "+relation);
				if (!isNonemptyString(feed_name))
					return cb("no feed_name");
				if (feed_name.length > constants.MAX_DATA_FEED_NAME_LENGTH)
					return cb("feed_name too long");
				if (typeof value === "string"){
					if (!isNonemptyString(value))
						return cb("no value");
					if (value.length > constants.MAX_DATA_FEED_VALUE_LENGTH)
						return cb("value too long");
				}
				else if (typeof value === "number"){
					if (!isInteger(value))
						return cb("no fractional values allowed");
				}
				else
					return cb("invalid value");
				if (typeof min_mci !== 'undefined' && !isNonnegativeInteger(min_mci))
					return cb(op+": invalid min_mci");
				return cb();
				
			case 'in merkle':
				if (bInNegation)
					return cb(op+" cannot be negated");
				if (objValidationState.bNoReferences)
					return cb("no references allowed in address definition");
				if (bAssetCondition)
					return cb("asset condition cannot have "+op);
				if (!Array.isArray(args))
					return cb(op+" arg must be array");
				if (args.length !== 3 && args.length !== 4)
					return cb(op+" must have 3 or 4 args");
				var arrAddresses = args[0];
				var feed_name = args[1];
				var element = args[2];
				var min_mci = args[3];
				if (!isNonemptyArray(arrAddresses))
					return cb("no addresses in "+op);
				for (var i=0; i<arrAddresses.length; i++)
					if (!isValidAddress(arrAddresses[i])) // it is ok if the address was never used yet
						return cb("address "+arrAddresses[i]+" not valid");
				complexity += arrAddresses.length-1; // 1 complexity point for each address (1 point was already counted)
				if (!isNonemptyString(feed_name))
					return cb("no feed_name");
				if (feed_name.length > constants.MAX_DATA_FEED_NAME_LENGTH)
					return cb("feed_name too long");
			//	if (!isStringOfLength(element_hash, constants.HASH_LENGTH))
			//		return cb("incorrect length of element hash");
				if (!element.match(/[\w ~,.\/\\;:!@#$%^&*\(\)=+\[\]\{\}<>\?|-]{1,100}/))
					return cb("incorrect format of merkled element");
				if (typeof min_mci !== 'undefined' && !isNonnegativeInteger(min_mci))
					return cb(op+": invalid min_mci");
				return cb();
				
			case 'mci':
			case 'age':
				var relation = args[0];
				var value = args[1];
				if (!isNonemptyString(relation))
					return cb("no relation");
				if (["=", ">", "<", ">=", "<=", "!="].indexOf(relation) === -1)
					return cb("invalid relation: "+relation);
				if (!isNonnegativeInteger(value))
					return cb(op+" must be a non-neg number");
				break;
				
			case 'has':
			case 'has one':
			case 'seen':
				if (objValidationState.bNoReferences)
					return cb("no references allowed in address definition");
				var err = getFilterError(args);
				if (err)
					return cb(err);
				if (op === 'seen'){
					if (!args.address)
						return cb('seen must specify address');
					if (args.what === 'input' && (args.amount || args.amount_at_least || args.amount_at_most))
						return cb('amount not allowed in seen input');
					if ('own_funds' in args)
						return cb('own_funds not allowed in seen');
				}
				if (!args.asset || args.asset === 'base' || bAssetCondition && args.asset === "this asset")
					return cb();
				determineIfAnyOfAssetsIsPrivate([args.asset], function(bPrivate){
					if (bPrivate)
						return cb("asset must be public");
					cb();
				});
				break;
				
			case 'has equal':
			case 'has one equal':
				if (objValidationState.bNoReferences)
					return cb("no references allowed in address definition");
				if (hasFieldsExcept(args, ["equal_fields", "search_criteria"]))
					return cb("unknown fields in "+op);
				
				if (!isNonemptyArray(args.equal_fields))
					return cb("no equal_fields");
				var assocUsedFields = {};
				for (var i=0; i<args.equal_fields.length; i++){
					var field = args.equal_fields[i];
					if (assocUsedFields[field])
						return cb("duplicate "+field);
					assocUsedFields[field] = true;
					if (["asset", "address", "amount", "type"].indexOf(field) === -1)
						return cb("unknown field: "+field);
				}
				
				if (!isArrayOfLength(args.search_criteria, 2))
					return cb("search_criteria must be 2-elements array");
				var arrAssets = [];
				for (var i=0; i<2; i++){
					var filter = args.search_criteria[i];
					var err = getFilterError(filter);
					if (err)
						return cb(err);
					if (!(filter.asset || filter.asset === 'base' || bAssetCondition && filter.asset === "this asset"))
						arrAssets.push(filter.asset);
				}
				if (args.equal_fields.indexOf("type") >= 0 && (args.search_criteria[0].what === "output" || args.search_criteria[1].what === "output"))
					return cb("outputs cannot have type");
				if (arrAssets.length === 0)
					return cb();
				determineIfAnyOfAssetsIsPrivate(arrAssets, function(bPrivate){
					bPrivate ? cb("all assets must be public") : cb();
				});
				break;
				
			case 'sum':
				if (objValidationState.bNoReferences)
					return cb("no references allowed in address definition");
				if (hasFieldsExcept(args, ["filter", "equals", "at_least", "at_most"]))
					return cb("unknown fields in "+op);
				var err = getFilterError(args.filter);
				if (err)
					return cb(err);
				if (args.filter.amount || args.filter.amount_at_least || args.filter.amount_at_most)
					return cb("sum filter cannot restrict amounts");
				if ("equals" in args && !isNonnegativeInteger(args.equals))
					return cb("equals must be nonnegative int");
				if ("at_least" in args && !isPositiveInteger(args.at_least))
					return cb("at_least must be positive int");
				if ("at_most" in args && !isPositiveInteger(args.at_most))
					return cb("at_most must be positive int");
				if ("equals" in args && ("at_least" in args || "at_most" in args))
					return cb("can't have equals and at_least/at_most at the same time")
				if (!("equals" in args) && !("at_least" in args) && !("at_most" in args))
					return cb("at least one of equals, at_least, at_most must be specified");
				if (!args.filter.asset || args.filter.asset === 'base' || bAssetCondition && args.filter.asset === "this asset")
					return cb();
				determineIfAnyOfAssetsIsPrivate([args.filter.asset], function(bPrivate){
					bPrivate ? cb("asset must be public") : cb();
				});
				break;
				
			default:
				return cb("unknown op: "+op);
		}
	}
	
	var complexity = 0;
	evaluate(arrDefinition, false, function(err, bHasSig){
		if (err)
			return handleResult(err);
		if (!bHasSig && !bAssetCondition)
			return handleResult("each branch must have a signature");
		if (complexity > constants.MAX_COMPLEXITY)
			return handleResult("complexity exceeded");
		handleResult();
	});
}
625721
def is_valid(self):
        """"""
        for lineedit in self.lineedits:
            if lineedit in self.validate_data and lineedit.isEnabled():
                validator, invalid_msg = self.validate_data[lineedit]
                text = to_text_string(lineedit.text())
                if not validator(text):
                    QMessageBox.critical(self, self.get_name(),
                                     "%s:<br><b>%s</b>" % (invalid_msg, text),
                                     QMessageBox.Ok)
                    return False
        return True
442012
def _validate_filters(cls, filters):
        """"""
        for k in iterkeys(filters):
            if k not in cls.filters:
                # Mirror "unexpected keyword argument" message:
                raise TypeError("%s got an unsupported filter type '%s'" %
                                (cls.__name__, k))
206244
def _validated(self, data):
        """"""
        errors = []
        for sub in self.schemas:
            try:
                return sub(data)
            except NotValid as ex:
                errors.extend(ex.args)

        raise NotValid(' and '.join(errors))
178978
def _validate_filters_ndb(cls, filters, model_class):
    """"""
    if not filters:
      return

    properties = model_class._properties


    for idx, f in enumerate(filters):
      prop, ineq, val = f
      if prop not in properties:
        raise errors.BadReaderParamsError(
            "Property %s is not defined for entity type %s",
            prop, model_class._get_kind())

      # Attempt to cast the value to a KeyProperty if appropriate.
      # This enables filtering against keys.
      try:
        if (isinstance(val, basestring) and
            isinstance(properties[prop],
              (ndb.KeyProperty, ndb.ComputedProperty))):
          val = ndb.Key(urlsafe=val)
          filters[idx] = [prop, ineq, val]
      except:
        pass

      # Validate the value of each filter. We need to know filters have
      # valid value to carry out splits.
      try:
        properties[prop]._do_validate(val)
      except db.BadValueError, e:
        raise errors.BadReaderParamsError(e)
1118654
function (vObject, filter) {
        /**
         * Definition:
         *   <!ELEMENT filter (comp-filter)>
         */
        if (filter) {
            if (vObject.name == filter.name) {
                return this._validateFilterSet(vObject, filter["comp-filters"], this._validateCompFilter) &&
                       this._validateFilterSet(vObject, filter["prop-filters"], this._validatePropFilter);
            }
            else
                return false;
        }
        else
            return true;


    }
160722
def match(self, rule):
        
        if len(self.filters) == 0:
            return True

        for filter in self.filters:
            if filter.match(rule):
                return True
        return False
816881
def _verify_validates(self, spec, path):
        """"""
        validates = spec['validates']

        if isinstance(validates, list):
            for validator in validates:
                self._verify_validator(validator, path)
        else:
            self._verify_validator(validates, path)
381673
def validate(self, model, validator=None):
    
    for filter_ in self.filters:
      if not filter_(model):
        return True

    is_valid, message = self.is_valid(model, validator)
    if not is_valid:
      model.add_error(self.pretty_property_name or self.property_name, message)
    return is_valid
54331
def _ni(field, filter_value):
        
        valid = False
        if field not in filter_value:
            valid = True
        return valid