Parse & validate a part according to section #3

        The logic applied follows section 3 guidelines from top
        to bottom.
172780
def _parse_section_three(self, part, mimetypes):
        

        link = 'tools.ietf.org/html/rfc2388#section-3'

        if part.disposition != 'form-data' or not part.name:
            self.fail('Each part of a multipart/form-data requires a '
                      'Content-Disposition header with a disposition type '
                      'of "form-data" AND a unique "name" parameter.', link)
        elif part.type.lower() not in mimetypes:
            allowed = ', '.join(mimetypes)
            self.fail('Invalid upload Content-Type. Each part of the '
                      'multipart/form-data upload MUST be one of: %s. '
                      '%s is not allowed.' % (allowed, part.type), link)
821354
protected function performValidation()
    {
        // All the fixed fields declared above are objects that MUST use keys that match the regular expression: ^[a-zA-Z0-9\.\-_]+$.
        foreach (array_keys($this->attributes()) as $attribute) {
            if (is_array($this->$attribute)) {
                foreach ($this->$attribute as $k => $v) {
                    if (!preg_match('~^[a-zA-Z0-9\.\-_]+$~', $k)) {
                        $this->addError("Invalid key '$k' used in Components Object for attribute '$attribute', does not match ^[a-zA-Z0-9\.\-_]+\$.");
                    }
                }
            }
        }
    }
748960
def process_ruleset( ruleset, dirname = nil )
      all_file_names = []
      all_parts = []
      all_parts_name = nil
      current_part = nil
      current_part_name = nil
      ruleset.lines do |line|
        if !all_parts_name && ( all_parts_name = get_all( line ) )
          all_parts_name = File.join( dirname, all_parts_name ) if dirname
          all_file_names << all_parts_name
        elsif ( current_part_name = get_start( line ) )
          current_part_name = File.join( dirname, current_part_name ) if dirname
          if current_part
            current_part.close
          end
          current_part = File.open( current_part_name, "w" )
          all_file_names << current_part_name
        elsif get_end( line ) && current_part
          current_part.close
          current_part = nil
        elsif current_part
          current_part.puts line
          all_parts << line
        else
          all_parts << line
        end
      end
      if current_part
        current_part.close
      end
      if all_parts_name
        f = File.open( all_parts_name, "w" )
        all_parts.each do |line|
          f.puts( line )
        end
        f.close
      end
      if all_file_names.length
        xml_fn = File.basename( all_file_names[0],".*" ) + "_xml_entity_refs"
        xml_fn = File.join( File.dirname( all_file_names[0] ), xml_fn )
        xml = File.open( xml_fn, "w" )
        all_file_names.each do |fn|
          bn = File.basename( fn, ".*" )
          xml.puts( "<!ENTITY #{bn} PUBLIC '' '#{fn}'>")
        end
        xml.close
      end
    end
392152
function parseAwsIni(ini) {
  var section,
      out = Object.create(null),
      re = /^\[([^\]]+)\]\s*$|^([a-z_]+)\s*=\s*(.+?)\s*$/,
      lines = ini.split(/\r?\n/)

  lines.forEach(function(line) {
    var match = line.match(re)
    if (!match) return
    if (match[1]) {
      section = match[1]
      if (out[section] == null) out[section] = Object.create(null)
    } else if (section) {
      out[section][match[2]] = match[3]
    }
  })

  return out
}
289574
protected function parseRules()
    {
        // Break apart the rule data on line breaks:
        $lines = explode("\n", $this->getRawRules());

        // Each group of data is split by a blank line -- process one group
        // at a time:
        $currentGroup = array();
        foreach ($lines as $currentLine) {
            if (empty($currentLine) && !empty($currentGroup)) {
                $this->processRuleGroup($currentGroup);
                $currentGroup = array();
            } else {
                $currentGroup[] = preg_replace("/\s+/", " ", $currentLine);
            }
        }

        // Still have unprocessed data after the loop?  Handle it now:
        if (!empty($currentGroup)) {
            $this->processRuleGroup($currentGroup);
        }
    }
798393
public void validate() {
        // AutoResetToZero
        if (niceMinValue > 0 || niceMaxValue < 0) {
            autoResetToZero = false;
        }

        // Threshold
        if (threshold < niceMinValue || threshold > niceMaxValue) {
            threshold = niceMaxValue;
        }

        // MinMeasuredValue
        if (minMeasuredValue < niceMinValue || minMeasuredValue > niceMaxValue) {
            minMeasuredValue = value;
        }

        // MaxMeasuredValue
        if (maxMeasuredValue > niceMaxValue || maxMeasuredValue < niceMinValue) {
            maxMeasuredValue = value;
        }

        // PeakValue
        if (peakValue < niceMinValue || peakValue > niceMaxValue) {
            peakValue = value;
        }

        // TrackStart
        if (Double.compare(trackStart, niceMinValue) <= 0 || Double.compare(trackStart, niceMaxValue) >= 0 || Double.compare(trackStart, trackStop) >= 0) {
            trackStart = niceMinValue;
        }

        // TrackStop
        if ((Double.compare(trackStop, niceMinValue)) <= 0 || Double.compare(trackStop, niceMaxValue) >= 0 || Double.compare(trackStop, trackStart) <= 0) {
            trackStop = niceMaxValue;
        }

        // TrackSection
        if (Double.compare(trackSection, niceMinValue) <= 0 || Double.compare(trackSection, niceMaxValue) >= 0 || Double.compare(trackSection, trackStart) <= 0 || Double.compare(trackSection, trackStop) >= 0) {
            trackSection = ((trackStart + (trackStop - trackStart) / 2.0));
        }

        // Areas
        for (Section area : areas) {
            if ((area.getStart() < niceMinValue) || Double.compare(area.getStart(), niceMaxValue) >= 0 || Double.compare(area.getStart(), area.getStop()) >= 0) {
                area.setStart(niceMinValue);
            }

            if (area.getStop() < niceMinValue || area.getStop() > niceMaxValue || Double.compare(area.getStop(), area.getStart()) <= 0) {
                area.setStop(niceMaxValue);
            }

            if (Double.compare(area.getStart(), minValue) == 0) {
                area.setStart(niceMinValue);
            }

            if (Double.compare(area.getStop(), maxValue) == 0) {
                area.setStop(niceMaxValue);
            }
        }

        // Sections
        for (Section section : sections) {
            if ((section.getStart() < niceMinValue) || Double.compare(section.getStart(), niceMaxValue) >= 0 || Double.compare(section.getStart(), section.getStop()) >= 0) {
                section.setStart(niceMinValue);
            }

            if (section.getStop() < niceMinValue || section.getStop() > niceMaxValue || Double.compare(section.getStop(), section.getStart()) <= 0) {
                section.setStop(niceMaxValue);
            }

            if (Double.compare(section.getStart(), minValue) == 0) {
                section.setStart(niceMinValue);
            }

            if (Double.compare(section.getStop(), maxValue) == 0) {
                section.setStop(niceMaxValue);
            }
        }

        // TickmarkSections
        for (Section tickmarkSection : tickmarkSections) {
            if ((tickmarkSection.getStart() < niceMinValue) || Double.compare(tickmarkSection.getStart(), niceMaxValue) >= 0 || Double.compare(tickmarkSection.getStart(), tickmarkSection.getStop()) >= 0) {
                tickmarkSection.setStart(niceMinValue);
            }

            if (tickmarkSection.getStop() < niceMinValue || tickmarkSection.getStop() > niceMaxValue || Double.compare(tickmarkSection.getStop(), tickmarkSection.getStart()) <= 0) {
                tickmarkSection.setStop(niceMaxValue);
            }

            if (Double.compare(tickmarkSection.getStart(), minValue) == 0) {
                tickmarkSection.setStart(niceMinValue);
            }

            if (Double.compare(tickmarkSection.getStop(), maxValue) == 0) {
                tickmarkSection.setStop(niceMaxValue);
            }
        }

        // Recalculate the redrawTolerance
        redrawFactor = redrawTolerance * getRange();

        // Correct the value (needed for init with negative minValue)
        value = value < niceMinValue ? niceMinValue : (value > niceMaxValue ? niceMaxValue : value);
    }
37968
def validate(args):
    
    p = OptionParser(validate.__doc__)

    opts, args = p.parse_args(args)

    try:
        agpfile, componentfasta, targetfasta = args
    except Exception as e:
        sys.exit(p.print_help())

    agp = AGP(agpfile)
    build = Fasta(targetfasta)
    bacs = Fasta(componentfasta, index=False)

    # go through this line by line
    for aline in agp:
        try:
            build_seq = build.sequence(dict(chr=aline.object,
                start=aline.object_beg, stop=aline.object_end))

            if aline.is_gap:
                assert build_seq.upper() == aline.gap_length * 'N', \
                    "gap mismatch: %s" % aline
            else:
                bac_seq = bacs.sequence(dict(chr=aline.component_id,
                    start=aline.component_beg, stop=aline.component_end,
                    strand=aline.orientation))

                assert build_seq.upper() == bac_seq.upper(), \
                        "sequence mismatch: %s" % aline

            logging.debug("%s:%d-%d verified" % (aline.object,
                aline.object_beg, aline.object_end))

        except Exception as e:
            logging.error(e)
201857
private void parse( FormattableContainer currentRule ) {
        try {
            for( ;; ) {
                int ch = reader.nextBlockMarker();
                switch( ch ) {
                    case -1:
                        return; // end of input reached
                    case ';':
                        parseSemicolon( currentRule );
                        break;
                    case '{':
                        parseBlock( currentRule );
                        break;
                    default:
                        throw createException( "Unrecognized input: '" + reader.getLookAhead() + "'" );
                }
            }
        } catch( LessException ex ) {
            ex.addPosition( reader.getFileName(), reader.getLine(), reader.getColumn() );
            throw ex;
        } catch( RuntimeException ex ) {
            LessException lessEx = new LessException( ex );
            lessEx.addPosition( reader.getFileName(), reader.getLine(), reader.getColumn() );
            throw lessEx;
        }
    }
1029393
function validateParens(parens, elements) {
            const leftParen = parens.leftParen;
            const rightParen = parens.rightParen;
            const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
            const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen);
            const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
            const hasRightNewline = !astUtils.isTokenOnSameLine(tokenBeforeRightParen, rightParen);
            const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);

            if (hasLeftNewline && !needsNewlines) {
                context.report({
                    node: leftParen,
                    messageId: "unexpectedAfter",
                    fix(fixer) {
                        return sourceCode.getText().slice(leftParen.range[1], tokenAfterLeftParen.range[0]).trim()

                            // If there is a comment between the ( and the first element, don't do a fix.
                            ? null
                            : fixer.removeRange([leftParen.range[1], tokenAfterLeftParen.range[0]]);
                    }
                });
            } else if (!hasLeftNewline && needsNewlines) {
                context.report({
                    node: leftParen,
                    messageId: "expectedAfter",
                    fix: fixer => fixer.insertTextAfter(leftParen, "\n")
                });
            }

            if (hasRightNewline && !needsNewlines) {
                context.report({
                    node: rightParen,
                    messageId: "unexpectedBefore",
                    fix(fixer) {
                        return sourceCode.getText().slice(tokenBeforeRightParen.range[1], rightParen.range[0]).trim()

                            // If there is a comment between the last element and the ), don't do a fix.
                            ? null
                            : fixer.removeRange([tokenBeforeRightParen.range[1], rightParen.range[0]]);
                    }
                });
            } else if (!hasRightNewline && needsNewlines) {
                context.report({
                    node: rightParen,
                    messageId: "expectedBefore",
                    fix: fixer => fixer.insertTextBefore(rightParen, "\n")
                });
            }
        }
516766
def _parse_rule(self, rule):
        '''
        
        '''
        values = rule.strip().split(self.RULE_DELIM, 4)

        if len(values) >= 4:
            codes = values[3].split(',')
            for i in range(0, len(codes)):
                try:
                    codes[i] = int(codes[i], 0)
                except ValueError as e:
                    binwalk.core.common.warning("The specified return code '%s' for extractor '%s' is not a valid number!" % (codes[i], values[0]))
            values[3] = codes

        if len(values) >= 5:
            values[4] = (values[4].lower() == 'true')

        return values
667204
private void parseValues(String[] args, boolean validate) {
        // This boolean becomes true if we encounter a command, which indicates we need
        // to stop parsing (the parsing of the command will be done in a sub JCommander
        // object)
        boolean commandParsed = false;
        int i = 0;
        boolean isDashDash = false; // once we encounter --, everything goes into the main parameter
        while (i < args.length && !commandParsed) {
            String arg = args[i];
            String a = trim(arg);
            args[i] = a;
            p("Parsing arg: " + a);

            JCommander jc = findCommandByAlias(arg);
            int increment = 1;
            if (!isDashDash && !"--".equals(a) && isOption(a) && jc == null) {
                //
                // Option
                //
                ParameterDescription pd = findParameterDescription(a);

                if (pd != null) {
                    if (pd.getParameter().password()) {
                        increment = processPassword(args, i, pd, validate);
                    } else {
                        if (pd.getParameter().variableArity()) {
                            //
                            // Variable arity?
                            //
                            increment = processVariableArity(args, i, pd, validate);
                        } else {
                            //
                            // Regular option
                            //
                            Class<?> fieldType = pd.getParameterized().getType();

                            // Boolean, set to true as soon as we see it, unless it specified
                            // an arity of 1, in which case we need to read the next value
                            if (pd.getParameter().arity() == -1 && isBooleanType(fieldType)) {
                                handleBooleanOption(pd, fieldType);
                            } else {
                                increment = processFixedArity(args, i, pd, validate, fieldType);
                            }
                            // If it's a help option, remember for later
                            if (pd.isHelp()) {
                                helpWasSpecified = true;
                            }
                        }
                    }
                } else {
                    if (options.acceptUnknownOptions) {
                        unknownArgs.add(arg);
                        i++;
                        while (i < args.length && !isOption(args[i])) {
                            unknownArgs.add(args[i++]);
                        }
                        increment = 0;
                    } else {
                        throw new ParameterException("Unknown option: " + arg);
                    }
                }
            } else {
                //
                // Main parameter
                //
                if ("--".equals(arg) && !isDashDash) {
                    isDashDash = true;
                }
                else if (commands.isEmpty()) {
                    //
                    // Regular (non-command) parsing
                    //
                    initMainParameterValue(arg);
                    String value = a; // If there's a non-quoted version, prefer that one
                    Object convertedValue = value;

                    // Fix
                    // Main parameter doesn't support Converter
                    // https://github.com/cbeust/jcommander/issues/380
                    if (mainParameter.annotation.converter() != null && mainParameter.annotation.converter() != NoConverter.class){
                        convertedValue = convertValue(mainParameter.parameterized, mainParameter.parameterized.getType(), null, value);
                    }

                    Type genericType = mainParameter.parameterized.getGenericType();
                    if (genericType instanceof ParameterizedType) {
                        ParameterizedType p = (ParameterizedType) genericType;
                        Type cls = p.getActualTypeArguments()[0];
                        if (cls instanceof Class) {
                            convertedValue = convertValue(mainParameter.parameterized, (Class) cls, null, value);
                        }
                    }

                    for(final Class<? extends IParameterValidator> validator : mainParameter.annotation.validateWith()
                            ) {
                        mainParameter.description.validateParameter(validator,
                            "Default", value);
                    }

                    mainParameter.description.setAssigned(true);
                    mainParameter.addValue(convertedValue);
                } else {
                    //
                    // Command parsing
                    //
                    if (jc == null && validate) {
                        throw new MissingCommandException("Expected a command, got " + arg, arg);
                    } else if (jc != null) {
                        parsedCommand = jc.programName.name;
                        parsedAlias = arg; //preserve the original form

                        // Found a valid command, ask it to parse the remainder of the arguments.
                        // Setting the boolean commandParsed to true will force the current
                        // loop to end.
                        jc.parse(validate, subArray(args, i + 1));
                        commandParsed = true;
                    }
                }
            }
            i += increment;
        }

        // Mark the parameter descriptions held in fields as assigned
        for (ParameterDescription parameterDescription : descriptions.values()) {
            if (parameterDescription.isAssigned()) {
                fields.get(parameterDescription.getParameterized()).setAssigned(true);
            }
        }

    }
740069
function(_content,_out){
        if (!_content) return;
        var _lines = _content.split('\n');
        if (!_lines||!_lines.length) return;
        for(var i=0,l=_lines.length,_line;i<l;i++){
            _line = _lines[i];
            if (!!_trim){
                _line = _line.trim();
                if (!_line) continue;
            } 
            _doParseSectionTextLine(_line,_out);
            if (!!_trim&&i<l-1) _out.push('__OUT.push(\'\\n\');');
        }
    }
380361
function validateMessageFormat(message) {
  function validateTypeStructure(message) {
    const typeParts = message.type.split('.'),
      baseType = typeParts[0],
      typeDepth = typeParts.length;

    if (typeDepth > 2)
      throw new Error(
        'Message type has too many dot separated sections: ' + message.type
      );

    const previousDepth = messageTypeDepths[baseType];

    if (previousDepth && previousDepth !== typeDepth) {
      throw new Error(
        `All messages of type ${baseType} must have the same structure. ` +
          `${
            message.type
          } has ${typeDepth} part(s), but earlier messages had ${previousDepth} part(s).`
      );
    }

    messageTypeDepths[baseType] = typeDepth;
  }

  function validatePageSummary(message) {
    const type = message.type;
    if (!type.endsWith('.pageSummary')) return;

    if (!message.url)
      throw new Error(`Page summary message (${type}) didn't specify a url`);

    if (!message.group)
      throw new Error(`Page summary message (${type}) didn't specify a group.`);
  }

  function validateSummaryMessage(message) {
    const type = message.type;
    if (!type.endsWith('.summary')) return;

    if (message.url)
      throw new Error(
        `Summary message (${type}) shouldn't be url specific, use .pageSummary instead.`
      );

    if (!message.group)
      throw new Error(`Summary message (${type}) didn't specify a group.`);

    const groups = groupsPerSummaryType[type] || [];
    if (groups.includes(message.group)) {
      throw new Error(
        `Multiple summary messages of type ${type} and group ${message.group}`
      );
    }
    groupsPerSummaryType[type] = groups.concat(message.group);
  }

  validateTypeStructure(message);
  validatePageSummary(message);
  validateSummaryMessage(message);
}
450513
void parseBlock( FormattableContainer currentRule ) {
        Operation expr = null;
        String name = null;
        Expression guard = null;
        StringBuilder builder = cachesBuilder;
        boolean wasWhite = false;
        for( ;; ) {
            char ch = reader.read();
            switch( ch ) {
                case '{':
                    String selector;
                    if( name == null ) {
                        selector = trim( builder );
                    } else {
                        selector = name;
                        name = null;
                        throwUnrecognizedInputIfAny( builder, ch );
                    }
                    if( selector.endsWith( "@" ) ) { // selector with variable name like abc@{foo}abc
                        builder.append( selector );
                        builder.append( ch );
                        break;
                    }
                    if( selector.contains( ":extend(" ) ) {
                        selector = LessExtend.addLessExtendsTo( currentRule, reader, selector );
                    }
                    Rule rule = rule( currentRule, selector, expr, guard );
                    currentRule.add( rule );
                    expr = null;
                    guard = null;
                    String[] selectors = rule.getSelectors();
                    for( String sel : selectors ) {
                        currentRule.getMixins().add( sel.trim(), rule );
                    }
                    return;
                case '/':
                    if( !comment( isWhitespace( builder ) ? currentRule : null ) ) {
                        builder.append( ch );
                    }
                    wasWhite = false;
                    break;
                case '\"':
                case '\'':
                    readQuote( ch, builder );
                    wasWhite = false;
                    break;
                case '(':
                    String cmd;
                    if( name == null ) {
                        int idx = builder.lastIndexOf( " when" );
                        if( idx < 0 || (idx + 5 != builder.length() && builder.indexOf( " when " ) < 0) ) {
                            if( isSelector( builder ) || !reader.nextIsMixinParam( true ) ) {
                                builder.append( ch );
                                break;
                            }
                        }
                        name = trim( builder );
                        if( idx < 0 ) {
                            expr = parseParameterList();
                            break;
                        } else {
                            cmd = name.substring( idx + 1 );
                            name = name.substring( 0, idx );
                        }
                    } else {
                        cmd = trim( builder );
                    }
                    char operator;
                    boolean isNot = false;
                    switch( cmd ) {
                        case "when not":
                            isNot = true;
                            //$FALL-THROUGH$
                        case "when":
                            operator = 0;
                            break;
                        case "and not":
                            isNot = true;
                            //$FALL-THROUGH$
                        case "and":
                            operator = '&';
                            break;
                        case ",not":
                        case ", not":
                            isNot = true;
                            //$FALL-THROUGH$
                        case ",":
                            operator = '|';
                            break;
                        default:
                            throw createException( "Unrecognized input: '" + cmd + "'" );
                    }
                    Expression right = parseExpression( (char)0 );
                    ch = read();
                    if( ch != ')' ) {
                        throw createException( "Unrecognized input: '" + ch + "'" );
                    }
                    if( isNot ) {
                        right = new Operation( reader, right, '!' );
                    }
                    guard = ( operator == 0 ) ? right : concat( guard, operator, right );
                    break;
                default:
                    boolean isWhite = Character.isWhitespace( ch );
                    if( isWhite ) {
                        if( builder.length() == 0 ) {
                            break;
                        }
                        if( wasWhite ) {
                            break;
                        } else {
                            builder.append( ' ' );
                            wasWhite = true;
                        }
                    } else {
                        builder.append( ch );
                        wasWhite = false;
                    }
            }
        }
    }
954308
private void validate() {
        if (isValid != null) {
            return;
        }

        ParsingValidator v =
            new ParsingValidator(useSchema ? Languages.W3C_XML_SCHEMA_NS_URI
                                 : Languages.XML_DTD_NS_URI);
        List<Source> schemaSourceList = new ArrayList<Source>();
        if (systemId != null) {
            schemaSourceList.add(new StreamSource(systemId));
        }
        addSchemaSources(schemaSource, schemaSourceList);
        v.setSchemaSources(schemaSourceList.toArray(new Source[0]));

        try {
            ValidationResult r =
                v.validateInstance(new SAXSource(validationInputSource));
            isValid = r.isValid() ? Boolean.TRUE : Boolean.FALSE;
            for (ValidationProblem p : r.getProblems()) {
                validationProblem(p);
            }
        } catch (org.xmlunit.ConfigurationException e) {
            throw new ConfigurationException(e.getCause());
        } catch (org.xmlunit.XMLUnitException e) {
            throw new XMLUnitRuntimeException(e.getMessage(), e.getCause());
        }

        if (usingDoctypeReader && isValid == Boolean.FALSE) {
            try {
                messages.append("\nContent was: ")
                    .append(getOriginalContent(validationInputSource));
            } catch (IOException e) {
                // silent but deadly?
            }
        }
    }
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;
	}
386003
def validate(self, result, spec):  # noqa Yes, it's too complex.
        """"""
        if spec is None:
            # None matches anything.
            return
        if isinstance(spec, dict):
            if not isinstance(result, dict):
                raise ValueError('Dictionary expected, but %r found.' % result)
            if spec:
                spec_value = next(iter(spec.values()))  # Yay Python 3!
                for value in result.values():
                    self.validate(value, spec_value)
                spec_key = next(iter(spec.keys()))
                for key in result:
                    self.validate(key, spec_key)
        if isinstance(spec, list):
            if not isinstance(result, list):
                raise ValueError('List expected, but %r found.' % result)
            if spec:
                for value in result:
                    self.validate(value, spec[0])
        if isinstance(spec, tuple):
            if not isinstance(result, tuple):
                raise ValueError('Tuple expected, but %r found.' % result)
            if len(result) != len(spec):
                raise ValueError('Expected %d elements in tuple %r.' %
                                 (len(spec), result))
            for s, value in zip(spec, result):
                self.validate(value, s)
        if isinstance(spec, six.string_types):
            if not isinstance(result, six.string_types):
                raise ValueError('String expected, but %r found.' % result)
        if isinstance(spec, int):
            if not isinstance(result, int):
                raise ValueError('Integer expected, but %r found.' % result)
        if isinstance(spec, bool):
            if not isinstance(result, bool):
                raise ValueError('Boolean expected, but %r found.' % result)