Validation and typecasting.
432847
def check_int(num,
              num_descr='number',
              min_value=0,
              max_value=np.Inf):
    """"""

    if not np.isfinite(num) or num < min_value or num > max_value:
        raise ValueError('{}={} is not finite or '
                         'is not >= {} or '
                         'is not < {}'.format(num_descr, num, min_value, max_value))

    return int(num)
320929
final void typeCheck(E e) {
        Class<?> eClass = e.getClass();
        if (eClass != elementType && eClass.getSuperclass() != elementType)
            throw new ClassCastException(eClass + " != " + elementType);
    }
1187594
private static void formalTypeParameter(Result sb, TypeParameterElement typeParameter) throws IOException
    {
        sb.append(typeParameter.getSimpleName());
        List<? extends TypeMirror> bounds = typeParameter.getBounds();
        if (!bounds.isEmpty())
        {
            TypeMirror tm = bounds.get(0);
            if (TypeKind.DECLARED == tm.getKind())
            {
                DeclaredType dt = (DeclaredType) tm;
                if (ElementKind.CLASS != dt.asElement().getKind())
                {
                    sb.append(':');
                }
            }
        }
        for (TypeMirror bound : bounds)
        {
            sb.append(':');
            fieldTypeSignature(sb, bound);
        }
    }
361031
function makeReflectTypes(uniforms, useIndex) {
  var obj = {}
  for(var i=0; i<uniforms.length; ++i) {
    var n = uniforms[i].name
    var parts = n.split(".")
    var o = obj
    for(var j=0; j<parts.length; ++j) {
      var x = parts[j].split("[")
      if(x.length > 1) {
        if(!(x[0] in o)) {
          o[x[0]] = []
        }
        o = o[x[0]]
        for(var k=1; k<x.length; ++k) {
          var y = parseInt(x[k])
          if(k<x.length-1 || j<parts.length-1) {
            if(!(y in o)) {
              if(k < x.length-1) {
                o[y] = []
              } else {
                o[y] = {}
              }
            }
            o = o[y]
          } else {
            if(useIndex) {
              o[y] = i
            } else {
              o[y] = uniforms[i].type
            }
          }
        }
      } else if(j < parts.length-1) {
        if(!(x[0] in o)) {
          o[x[0]] = {}
        }
        o = o[x[0]]
      } else {
        if(useIndex) {
          o[x[0]] = i
        } else {
          o[x[0]] = uniforms[i].type
        }
      }
    }
  }
  return obj
}
986687
def validate(self, instance, value):
        """"""
        try:
            intval = int(value)
            if not self.cast and abs(value - intval) > TOL:
                self.error(
                    instance=instance,
                    value=value,
                    extra='Not within tolerance range of {}.'.format(TOL),
                )
        except (TypeError, ValueError):
            self.error(instance, value, extra='Cannot cast to integer.')
        _in_bounds(self, instance, intval)
        return intval
715481
def _FormatTypeCheck(type_):
  """"""
  if isinstance(type_, tuple):
    items = [_FormatTypeCheck(t) for t in type_]
    return "(%s)" % ", ".join(items)
  elif hasattr(type_, "__name__"):
    return type_.__name__
  else:
    return repr(type_)
1126645
def validate_type(self, type_):
        
        if type_ is not None and type_ not in self.types_set:
            raise ValueError('Invalid type for %s:%s' % (self.__class__, type_))
247723
private void validateTypeNotIn(TypeMirror t, Set<TypeKind> invalidKinds) {
        if (invalidKinds.contains(t.getKind()))
            throw new IllegalArgumentException(t.toString());
    }
1037542
private <T>  void composeIfPossible(Validator<T> v, T t) {
        final FluentValidator self = this;
        if (v instanceof ValidatorHandler) {
            ((ValidatorHandler) v).compose(self, context, t);
        }
    }
1124617
function typecast(value, originalValue, properties) {
        const options = this[_privateKey]._options;

        // Allow transform to manipulate raw properties.
        if (properties.transform) {
            value = properties.transform.call(this[_privateKey]._root, value, originalValue, properties);
        }

        // Allow null to be preserved.
        if (value === null && options.preserveNull) {
            return null;
        }

        // Helper function designed to detect and handle usage of array-form custom error messages for validators
        function detectCustomErrorMessage(key) {
            if (typeof properties[key] === 'object' && properties[key].errorMessage && properties[key].value) {
                return properties[key];
            }
            else  if (_.isArray(properties[key])) {
                return {
                    value: properties[key][0],
                    errorMessage: properties[key][1]
                };
            }
            else {
                return {
                    value: properties[key],
                    errorMessage: undefined
                };
            }
        }

        // Property types are always normalized as lowercase strings despite shorthand definitions being available.
        switch (properties.type) {
            case 'string':
                // Reject if object or array.
                if (_.isObject(value) || _.isArray(value)) {
                    throw new StringCastError(value, originalValue, properties);
                }

                // If index is being set with null or undefined, set value and end.
                if (value === undefined || value === null) {
                    return undefined;
                }

                // Typecast to String.
                value = value + '';

                // If stringTransform function is defined, use.
                // This is used before we do validation checks (except to be sure we have a string at all).
                if (properties.stringTransform) {
                    value = properties.stringTransform.call(this[_privateKey]._root, value, originalValue, properties);
                }

                // If clip property & maxLength properties are set, the string should be clipped.
                // This is basically a shortcut property that could be done with stringTransform.
                if (properties.clip !== undefined && properties.maxLength !== undefined) {
                    value = value.substr(0, properties.maxLength);
                }

                let enumValidation;

                // Detect custom error message usage for enum (can't use function here as enum is expected to be an array)
                if (typeof properties.enum === 'object' && properties.enum.errorMessage && properties.enum.value) {
                    enumValidation = properties.enum;
                }
                else if (_.isArray(properties.enum) && _.isArray(properties.enum[0])) {
                    enumValidation = {
                        value: properties.enum[0],
                        errorMessage: properties.enum[1]
                    };
                }
                else {
                    enumValidation = {
                        value: properties.enum,
                        errorMessage: undefined
                    };
                }

                // If enum is being used, be sure the value is within definition.
                if (
                    enumValidation.value !== undefined &&
                    _.isArray(enumValidation.value) &&
                    enumValidation.value.indexOf(value) === -1
                ) {
                    throw new StringEnumValidationError(enumValidation.errorMessage, value, originalValue, properties);
                }

                // Detect custom error message usage for minLength
                let minLength = detectCustomErrorMessage('minLength');

                // If minLength is defined, check to be sure the string is > minLength.
                if (minLength.value !== undefined && value.length < minLength.value) {
                    throw new StringMinLengthValidationError(minLength.errorMessage, value, originalValue, properties);
                }

                // Detect custom error message usage for maxLength
                let maxLength = detectCustomErrorMessage('maxLength');

                // If maxLength is defined, check to be sure the string is < maxLength.
                if (maxLength.value !== undefined && value.length > maxLength.value) {
                    throw new StringMaxLengthValidationError(maxLength.errorMessage, value, originalValue, properties);
                }

                // Detect custom error message usage for maxLength
                let regex = detectCustomErrorMessage('regex');

                // If regex is defined, check to be sure the string matches the regex pattern.
                if (regex.value && !regex.value.test(value)) {
                    throw new StringRegexValidationError(regex.errorMessage, value, originalValue, properties);
                }

                return value;

            case 'number':
                // If index is being set with null, undefined, or empty string: clear value.
                if (value === undefined || value === null || value === '') {
                    return undefined;
                }

                // Set values for boolean.
                if (_.isBoolean(value)) {
                    value = value ? 1 : 0;
                }

                // Remove/convert number group separators
                if (typeof value === 'string') {
                    if (options.useDecimalNumberGroupSeparator) {
                        // Remove decimals
                        value = value.replace(/\./g, '');
                        // Replace commas with decimals for js parsing
                        value = value.replace(/,/g, '.');
                    }
                    else {
                        //Remove commas
                        value = value.replace(/,/g, '');
                    }

                    // Reject if string was not a valid number
                    if (isNaN(Number(value))) {
                      throw new NumberCastError('String', value, originalValue, properties);
                    }
                }

                // Reject if array, object, or not numeric.
                if (_.isArray(value)) {
                    throw new NumberCastError('Array', value, originalValue, properties);
                }
                else if (_.isObject(value)) {
                    throw new NumberCastError('Object', value, originalValue, properties);
                }
                else if (!isNumeric(value)) {
                    throw new NumberCastError('Non-numeric', value, originalValue, properties);
                }

                // Typecast to number.
                value = Number(value);

                // Transformation after typecasting but before validation and filters.
                if (properties.numberTransform) {
                    value = properties.numberTransform.call(this[_privateKey]._root, value, originalValue, properties);
                }

                // Detect custom error message usage for min
                let min = detectCustomErrorMessage('min');

                if (min.value !== undefined && value < min.value) {
                    throw new NumberMinValidationError(min.errorMessage, value, originalValue, properties);
                }

                // Detect custom error message usage for min
                let max = detectCustomErrorMessage('max');

                if (max.value !== undefined && value > max.value) {
                    throw new NumberMaxValidationError(max.errorMessage, value, originalValue, properties);
                }

                return value;

            case 'boolean':
                // If index is being set with null, undefined, or empty string: clear value.
                if (value === undefined || value === null || value === '') {
                    return undefined;
                }

                // If is String and is 'false', convert to Boolean.
                if (value === 'false') {
                    return false;
                }

                // If is Number, <0 is true and >0 is false.
                if (isNumeric(value)) {
                    return (value * 1) > 0;
                }

                // Use Javascript to eval and return boolean.
                value = !!value;

                // Transformation after typecasting but before validation and filters.
                if (properties.booleanTransform) {
                    value = properties.booleanTransform.call(this[_privateKey]._root, value, originalValue, properties);
                }

                return value;

            case 'array':
                // If it's an object, typecast to an array and return array.
                if (_.isObject(value)) {
                    value = _.toArray(value);
                }

                // Reject if not array.
                if (!_.isArray(value)) {
                    throw new ArrayCastError(value, originalValue, properties);
                }

                // Arrays are never set directly.
                // Instead, the values are copied over to the existing SchemaArray instance.
                // The SchemaArray is initialized immediately and will always exist.
                originalValue.length = 0;
                _.each(value, (arrayValue) => {
                    originalValue.push(arrayValue);
                });

                return originalValue;

            case 'object':
                // If it's not an Object, reject.
                if (!_.isObject(value)) {
                    throw new ObjectCastError(value, originalValue, properties);
                }

                // If object is schema object and an entirely new object was passed, clear values and set.
                // This preserves the object instance.
                if (properties.objectType) {
                    // The object will usually exist because it's initialized immediately for deep access within SchemaObjects.
                    // However, in the case of Array elements, it will not exist.
                    let schemaObject;
                    if (originalValue !== undefined) {
                        // Clear existing values.
                        schemaObject = originalValue;
                        schemaObject.clear();
                    } else {
                        // The SchemaObject doesn't exist yet. Let's initialize a new one.
                        // This is used for Array types.
                        schemaObject = new properties.objectType({}, this[_privateKey]._root);
                    }

                    // Copy value to SchemaObject and set value to SchemaObject.
                    for (const key in value) {
                        schemaObject[key] = value[key];
                    }
                    value = schemaObject;
                }

                // Otherwise, it's OK.
                return value;

            case 'date':
                // If index is being set with null, undefined, or empty string: clear value.
                if (value === undefined || value === null || value === '') {
                    return undefined;
                }

                // Reject if object, array or boolean.
                if (!_.isDate(value) && !_.isString(value) && !_.isNumber(value)) {
                    throw new DateCastError(value, originalValue, properties);
                }

                // Attempt to parse string value with Date.parse (which returns number of milliseconds).
                if (_.isString(value)) {
                    value = Date.parse(value);
                }

                // If is timestamp, convert to Date.
                if (isNumeric(value)) {
                    value = new Date((value + '').length > 10 ? value : value * 1000);
                }

                // If the date couldn't be parsed, do not modify index.
                if (value == 'Invalid Date' || !_.isDate(value)) {
                    throw new DateParseValidationError(null, value, originalValue, properties);
                }

                // Transformation after typecasting but before validation and filters.
                if (properties.dateTransform) {
                    value = properties.dateTransform.call(this[_privateKey]._root, value, originalValue, properties);
                }

                return value;

            default: // 'any'
                return value;
        }
    }
1021952
function(args, types) {
		this._validating = true;
		var is = this._match(args, types);
		this._validating = false;
		return is;
	}
855383
private static Set<Kind> validateOperators(Set<Kind> kinds) {
    for (Kind kind : kinds) {
      if (!COMPOUND_ASSIGNMENT_OPERATORS.contains(kind)) {
        throw new IllegalArgumentException(kind.name() + " is not a compound-assignment operator.");
      }
    }
    return kinds;
  }
519723
def validate_program(self):
        """"""
        terminals = [0]
        for node in self.program:
            if isinstance(node, _Function):
                terminals.append(node.arity)
            else:
                terminals[-1] -= 1
                while terminals[-1] == 0:
                    terminals.pop()
                    terminals[-1] -= 1
        return terminals == [-1]
133633
def validate(self, instance, value):
        """"""
        if not isinstance(value, (tuple, list, np.ndarray)):
            self.error(instance, value)
        if self.coerce:
            value = self.wrapper(value)
        valid_class = (
            self.wrapper if isinstance(self.wrapper, type) else np.ndarray
        )
        if not isinstance(value, valid_class):
            self.error(instance, value)
        allowed_kinds = ''.join(TYPE_MAPPINGS[typ] for typ in self.dtype)
        if value.dtype.kind not in allowed_kinds:
            self.error(instance, value, extra='Invalid dtype.')
        if self.shape is None:
            return value
        for shape in self.shape:
            if len(shape) != value.ndim:
                continue
            for i, shp in enumerate(shape):
                if shp not in ('*', value.shape[i]):
                    break
            else:
                return value
        self.error(instance, value, extra='Invalid shape.')
1189680
private void checkGrammar(List<GRule> ruleList, List<Nonterminal> nonterminalList, List<GTerminal> terminalList) throws IOException
    {
        for (Nonterminal nt : nonterminalList)
        {
            boolean hasLhs = false;
            for (GRule rule : ruleList)
            {
                if (nt.equals(rule.getLeft()))
                {
                    hasLhs = true;
                    break;
                }
            }
            if (!hasLhs)
            {
                print(System.err);
                throw new GrammarException("Nonterminal "+nt.toString()+" is not left part of any rule");
            }
        }
        for (GTerminal t : terminalList)
        {
            if (GTerminal.class.equals(t.getClass()))
            {
                String expr = t.getExpression();
                if (expr.isEmpty())
                {
                    print(System.err);
                    throw new GrammarException("Terminal "+t.getName()+" accepts empty string");
                }
                DFA<Integer> dfa = Regex.createDFA(expr);
                if (dfa.getRoot().isAccepting())
                {
                    print(System.err);
                    throw new GrammarException("Terminal "+t.getName()+" accepts empty string");
                }
                ExecutableElement reducer = t.getReducer();
                if (reducer != null)
                {
                    if (t.isWhiteSpace())
                    {
                        if (reducer.getReturnType().getKind() != TypeKind.VOID)
                        {
                            boolean ok = false;
                            for (ExecutableElement insert : ElementFilter.methodsIn(El.getTypeElement(InputReader.class.getCanonicalName()).getEnclosedElements()))
                            {
                                List<? extends VariableElement> parameters = insert.getParameters();
                                if (parameters.size() == 1 && Typ.isAssignable(reducer.getReturnType(), parameters.get(0).asType()))
                                {
                                    ok = true;
                                    break;
                                }
                            }
                            if (!ok)
                            {
                                throw new GrammarException("white-space terminal has return type not suitable for InputReader.insert "+reducer);
                            }
                        }
                    }
                }
            }
        }
        for (GRule rule : ruleList)
        {
            for (Symbol symbol : rule.getRight())
            {
                if (symbol instanceof Eof)
                {
                    throw new GrammarException("eof terminal "+symbol+" in "+rule.getDescription());
                }
                if (symbol instanceof GTerminal)
                {
                    GTerminal terminal = (GTerminal) symbol;
                    if (terminal.isWhiteSpace())
                    {
                        throw new GrammarException("white-space terminal "+terminal+" in "+rule.getDescription());
                    }
                }
            }
            ExecutableElement reducer = rule.getReducer();
            if (reducer != null)
            {
                List<? extends VariableElement> params = reducer.getParameters();
                int index = 0;
                for (Symbol symbol : rule.getRight())
                {
                    if (symbol instanceof GTerminal)
                    {
                        GTerminal t = (GTerminal) symbol;
                        ExecutableElement red = t.getReducer();
                        if (red != null && red.getReturnType().getKind() != TypeKind.VOID)
                        {
                            if (index >= params.size())
                            {
                                print(System.err);
                                throw new GrammarException("Too few parameters for "+rule.getDescription());
                            }
                            index++;
                        }
                    }
                    else
                    {
                        Nonterminal nt = (Nonterminal) symbol;
                        boolean nonVoid = false;
                        for (GRule r : nt.getLhsRule())
                        {
                            ExecutableElement red = r.getReducer();
                            if (red != null && red.getReturnType().getKind() != TypeKind.VOID)
                            {
                                if (index >= params.size())
                                {
                                    print(System.err);
                                    throw new GrammarException("Method "+red+"return value not consumed in "+rule.getDescription());
                                }
                                nonVoid = true;
                            }
                        }
                        if (nonVoid)
                        {
                            index++;
                        }
                    }
                }
                for (;index < params.size();index++)
                {
                    boolean pc = false;
                    ParserContext annotation = params.get(index).getAnnotation(ParserContext.class);
                    if (annotation == null)
                    {
                        print(System.err);
                        throw new GrammarException("extra parameter "+params.get(index)+" for "+rule.getDescription()+" which are not @ParserContext");
                    }
                }
            }
            else
            {
                if (!rule.getLeft().isStart())
                {
                    for (Symbol symbol : rule.getRight())
                    {
                        if (symbol.getReducerType().getKind() != TypeKind.VOID)
                        {
                            throw new GrammarException(rule.getDescription()+" doesn't have reducer but "+symbol+" has");
                        }
                    }
                }
            }
        }
    }
1217602
function constraintsRepr(
    constraints,    // :: StrMap (Array TypeClass)
    outer,          // :: String -> String
    inner           // :: String -> TypeClass -> String -> String
  ) {
    var $reprs = [];
    (sortedKeys (constraints)).forEach (function(k) {
      var f = inner (k);
      constraints[k].forEach (function(typeClass) {
        $reprs.push (f (typeClass) (stripNamespace (typeClass) + ' ' + k));
      });
    });
    return when ($reprs.length > 0)
                (wrap ('') (outer (' => ')))
                (when ($reprs.length > 1)
                      (parenthesize (outer))
                      (joinWith (outer (', '), $reprs)));
  }
921736
def _validated(self, data):
        """"""
        try:
            return self.convert(data)
        except (TypeError, ValueError) as ex:
            raise NotValid(*ex.args)