Optimize a rule by replacing validators with functions and rewriting requiredXXX validators to arrays.
191118
function optimizeRule( rule ) {
		var validatorName,
			requiredProperties,
			i;

		for ( validatorName in validators )
			rule[ validatorName ] = validatorFunction( rule[ validatorName ] );

		var nothingRequired = true;
		for ( i in validatorsRequired ) {
			validatorName = validatorsRequired[ i ];
			requiredProperties = optimizeRequiredProperties( rule[ validatorName ] );
			// Don't set anything if there are no required properties. This will allow to
			// save some memory by GCing all empty arrays (requiredProperties).
			if ( requiredProperties.length ) {
				rule[ validatorName ] = requiredProperties;
				nothingRequired = false;
			}
		}

		rule.nothingRequired = nothingRequired;
		rule.noProperties = !( rule.attributes || rule.classes || rule.styles );
	}
818484
function standardizeRule( rule ) {
		rule.elements = convertValidatorToHash( rule.elements, /\s+/ ) || null;
		rule.propertiesOnly = rule.propertiesOnly || ( rule.elements === true );

		var delim = /\s*,\s*/,
			i;

		for ( i in validators ) {
			rule[ i ] = convertValidatorToHash( rule[ i ], delim ) || null;
			rule[ validatorsRequired[ i ] ] = extractRequired( convertValidatorToHash(
				rule[ validatorsRequired[ i ] ], delim ), rule[ i ] ) || null;
		}

		rule.match = rule.match || null;
	}
890456
function () {
            this.errors = {};
            return flatten(this._static.validators.map(function runValidator(validator) {
                var col = validator.col, val = this.__values[validator.col], ret = validator.validate(val);
                this.errors[col] = ret;
                return ret;
            }, this));
        }
128739
def run_validator(pattern):
    

    start = ''
    if isinstance(pattern, six.string_types):
        start = pattern[:2]
        pattern = InputStream(pattern)

    if not start:
        start = pattern.readline()[:2]
        pattern.seek(0)

    parseErrListener = STIXPatternErrorListener()

    lexer = STIXPatternLexer(pattern)
    # it always adds a console listener by default... remove it.
    lexer.removeErrorListeners()

    stream = CommonTokenStream(lexer)

    parser = STIXPatternParser(stream)
    parser.buildParseTrees = False
    # it always adds a console listener by default... remove it.
    parser.removeErrorListeners()
    parser.addErrorListener(parseErrListener)

    # To improve error messages, replace "<INVALID>" in the literal
    # names with symbolic names.  This is a hack, but seemed like
    # the simplest workaround.
    for i, lit_name in enumerate(parser.literalNames):
        if lit_name == u"<INVALID>":
            parser.literalNames[i] = parser.symbolicNames[i]

    parser.pattern()

    # replace with easier-to-understand error message
    if not (start[0] == '[' or start == '(['):
        parseErrListener.err_strings[0] = "FAIL: Error found at line 1:0. " \
                                          "input is missing square brackets"

    return parseErrListener.err_strings
933706
function(name, validator) {
    var async = this.isAsync(name);
    var rule = new Rule(name, rules[name], async);
    rule.setValidator(validator);
    return rule;
  }
758226
def generate_minimum_validator(minimum, exclusiveMinimum=False, **kwargs):
    
    return functools.partial(validate_minimum, minimum=minimum, is_exclusive=exclusiveMinimum)
1230104
function(){
            _.each(this.rules, function(rule){
                rule.regex = eval(rule.regex.toString().replace(/^\//,'/^'));
            });
        }
696404
function(model, attr) {
      var attrValidationSet = model.validation ? _.result(model, 'validation')[attr] || {} : {};

      // If the validator is a function or a string, wrap it in a function validator
      if (_.isFunction(attrValidationSet) || _.isString(attrValidationSet)) {
        attrValidationSet = {
          fn: attrValidationSet
        };
      }

      // Stick the validator object into an array
      if(!_.isArray(attrValidationSet)) {
        attrValidationSet = [attrValidationSet];
      }

      // Reduces the array of validators into a new array with objects
      // with a validation method to call, the value to validate against
      // and the specified error message, if any
      return _.reduce(attrValidationSet, function(memo, attrValidation) {
        _.each(_.without(_.keys(attrValidation), 'msg', 'msgKey'), function(validator) {
          memo.push({
            fn: defaultValidators[validator],
            val: attrValidation[validator],
            msg: attrValidation.msg,
            msgKey: attrValidation.msgKey
          });
        });
        return memo;
      }, []);
    }
1082385
def get_rules(self, optimized):
        
        self.insert_start_to_accepting()
        # If CFG is not requested, avoid the following O(n^3) rule.
        # It can be solved and a string can be generated faster with BFS of DFS

        if optimized == 0:
            self.insert_self_to_empty_and_insert_all_intemediate(optimized)
        self.insert_symbol_pushpop()
        return self.rules
1253548
public function setupRules()
    {
        // we need to allow all the tokens in json
        $this->rules->validator = new Validator(['*none', '*meta.json', '!comment']);

        $this->rules->addMany([
            'string' => CommonFeatures::strings(['single' => '\'', 'double' => '"'], [
                'context' => ['!operator.escape', '!comment', '!string'],
            ]),

            'symbol.function' => new Rule(new RegexMatcher('/function\s+([a-z_]\w+)\s*\(/i')),

            'operator.escape' => new Rule(new RegexMatcher('/(\\\(?:x[0-9a-fA-F]{1,2}|u\{[0-9a-fA-F]{1,6}\}|[0-7]{1,3}|.))/i'), [
                'context' => ['string']
            ]),

            'comment' => new Rule(new CommentMatcher(['//'], [['/*', '*/']]), ['priority' => 3]),

            'call' => new Rule(new RegexMatcher('/(' . self::IDENTIFIER . ')\s*\(/iu'), ['priority' => -1]),

            'keyword' => new Rule(new WordMatcher([
                'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval',
                'void', 'with', 'break', 'catch', 'class', 'const', 'super', 'throw',
                'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch',
                'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger',
                'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof', 'get', 'set', 'from'
            ]), ['context' => ['!string', '!comment', '!symbol', '!call']]),

            'constant.special' => new Rule(new WordMatcher(['null', 'true', 'false'])),
            'variable.special' => new Rule(new SubStringMatcher('this')),

            'number' => new Rule(new RegexMatcher('/\b(-?(?:0[0-7]+|0[xX][0-9a-fA-F]+|0b[01]+|\d+))\b/')),

            'operator.punctuation' => new Rule(new WordMatcher([',', ';'], ['separated' => false]), ['priority' => 0]),
            'operator'             => new Rule(new RegexMatcher('/(=>|\+{1,2}|-{1,2}|={1,3}|\|{1,2}|&{1,2})/'), ['priority' => 0]),

            'string.regex' => [
                new OpenRule(new RegexMatcher('#(?>[\[=(?:+,!]|^|return|=>|&&|\|\|)\s*(/).*?/#m'), [
                    'context' => ['!comment', '!string']
                ]),
                new Rule(new RegexMatcher('#\/.*(/[gimuy]{0,5})#m'), [
                    'priority' => 1,
                    'factory'  => new TokenFactory(ContextualToken::class),
                    'context'  => ['!operator.escape', 'string.regex']
                ])
            ],

            'variable' => new Rule(new RegexMatcher('/\b(?<!\.)(' . self::IDENTIFIER . ':?)/iu'), [
                'priority' => -1,
                'enabled'  => $this->variables
            ]),

            'variable.property' => [
                new Rule(new RegexMatcher('/(?=[\w)\]]\s*\.([a-z_]\w*))/i'), [
                    'priority' => -2
                ]),
                new Rule(new RegexMatcher('/(\w+)\s*:/si'), [
                    'context' => ['meta.json', '!comment', '!string']
                ]),
            ],

            'meta.json' => new Rule(new RegexMatcher('/(?<=[=(,])\s*(\{(?>[^{}]|(?1))+\})/m'), [
                'factory' => new TokenFactory(MetaToken::class)
            ])
        ]);
    }
829658
function optimize (source, path, module)
  {
    var result = sourceTrans.optimize (source, module.name, options.moduleVar);
    var stat = sourceTrans.TRANS_STAT;
    switch (result.status) {

      case stat.OK:

        //----------------------------------------------------------
        // Module already enclosed in a closure with no arguments.
        //----------------------------------------------------------
        return /** @type {OperationResult} */ {
          status: STAT.INDENTED,
          data:   sourceTrans.renameModuleRefExps (module, options.indent + result.data, options.moduleVar)
        };


      case stat.NO_CLOSURE_FOUND:

        //----------------------------------------------------------
        // Unwrapped source code.
        // It must be validated to make sure it's safe.
        //----------------------------------------------------------
        if (path)
          verboseOut.write ('Validating ' + path.cyan + '...');
        var valid = sourceTrans.validateUnwrappedCode (source);
        if (valid)
        // The code passed validation.
          verboseOut.ok ();
        else {
          verboseOut.writeln ('FAILED'.yellow);
          warnAboutGlobalCode (valid, path);
          // If --force, continue.
        }
        // Either the code is valid or --force was used, so process it.
        return /** @type {OperationResult} */ {
          status: STAT.OK,
          data:   sourceTrans.renameModuleRefExps (module, source, options.moduleVar)
        };


      case stat.RENAME_REQUIRED:

        //----------------------------------------------------------
        // Module already enclosed in a closure, with its reference
        // passed in as the function's argument.
        //----------------------------------------------------------
        /** @type {ModuleClosureInfo} */
        var modInfo = result.data;
        if (!options.renameModuleRefs) {
          warn ('The module variable reference <cyan>%</cyan> doesn\'t match the preset name on the config setting ' +
            '<cyan>moduleVar=\'%\'</cyan>.%%%',
            modInfo.moduleVar, options.moduleVar, NL, reportErrorLocation (path),
            getExplanation ('Either rename the variable or enable <cyan>renameModuleRefs</cyan>.')
          );
          // If --force, continue.
        }
        return /** @type {OperationResult} */ {
          status: STAT.OK,
          data:   sourceTrans.renameModuleVariableRefs (modInfo.closureBody, modInfo.moduleVar, options.moduleVar)
        };


      case stat.INVALID_DECLARATION:

        warn ('Wrong module declaration: <cyan>%</cyan>', result.data);
        // If --force, continue.
        break;


      default:
        throw new Error ('Optimize failed. It returned ' + JSON.stringify (result));
    }
    // Optimization failed. Return the unaltered source code.
    return /** @type {OperationResult} */ {status: STAT.OK, data: source};
  }
975150
function assembleValidation(validation) {
  if (!_.isPlainObject(validation)) {
    validation = {rule: validation, params: []};
  }
  if (_.isString(validation.rule)) {
    var splitRule = validation.rule.split(':');
    validation.rule = splitRule[0];
    if (_.isEmpty(validation.params)) {
      validation.params = _.tail(splitRule);
    }
  } else if (!_.isFunction(validation.rule)) {
    throw new TypeError('Invalid validation');
  }
  return validation;
}
891442
function applyRules(rules, stem) {

  for (let i = 0, l = rules.length; i < l; i++) {
    const [min, pattern, replacement = ''] = rules[i];

    if (stem.slice(-pattern.length) === pattern) {
      const newStem = stem.slice(0, -pattern.length) + replacement,
            m = computeM(newStem);

      if (m <= min)
        continue;

      return newStem;
    }
  }

  return stem;
}
781516
function setRules (rules) {
    debug('set rules', rules)
    // require array
    assert.ok(Array.isArray(rules), 'rules array required')
    // add each rule
    _.each(rules, rule => this.setRule(rule))
}
370656
function processRule(rule) {
    if (typeof rule !== 'function' && typeof rule !== 'string') {
        OBLIGATIONS.precondition(Array.isArray(rule) && rule[0] || rule.name, 'Validator name must be specified.');
    }
    var __result;
    main: {
        if (typeof rule === 'string') {
            __result = exports.create(rule);
            break main;
        } else if (typeof rule === 'function') {
            __result = new exports.Validator({ validate: rule });
            break main;
        } else if (Array.isArray(rule)) {
            __result = exports.create.apply(exports, rule);
            break main;
        } else {
            __result = exports.create(rule.name, rule);
            break main;
        }
    }
    OBLIGATIONS.postcondition(__result instanceof exports.Validator);
    return __result;
}
696978
function applyAllowedRuleToArray( itemsRule, items, validItems ) {
		if ( !itemsRule )
			return false;

		// True means that all elements of array are accepted (the asterix was used for classes).
		if ( itemsRule === true )
			return true;

		for ( var i = 0, l = items.length, item; i < l; ++i ) {
			item = items[ i ];
			if ( !validItems[ item ] )
				validItems[ item ] = itemsRule( item );
		}

		return false;
	}
543040
def relevant_rules_for_match(self, action, subject):
        """"""
        matches = []
        for rule in self.rules:
            rule.expanded_actions = self.expand_actions(rule.actions)
            if rule.is_relevant(action, subject):
                matches.append(rule)

        return self.optimize(matches[::-1])