Validate a generated HTML file
    :param pelican: pelican object
499815
def validate_files(pelican):
    
    for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
        for name in filenames:
            if should_validate(name):
                filepath = os.path.join(dirpath, name)
                validate(filepath)
1003763
def validate_examples(example_file):
    

    def test_example(raw):
        example = tf.train.Example()
        example.ParseFromString(raw)

        pi = np.frombuffer(example.features.feature['pi'].bytes_list.value[0], np.float32)
        value = example.features.feature['outcome'].float_list.value[0]
        assert abs(pi.sum() - 1) < 1e-4, pi.sum()
        assert value in (-1, 1), value

    opts = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.ZLIB)
    for record in tqdm(tf.python_io.tf_record_iterator(example_file, opts)):
        test_example(record)
1221863
def validate (self):
    
    if not os.path.isfile(self.pathname):
      self.message.append('Filename "%s" does not exist.')
    else:
      try:
        with open(self.pathname, 'r') as stream:
          pass
      except IOError:
        self.messages.append('Could not open "%s" for reading.' % self.pathname)

    for line in self.commands:
      messages = [ ]
      if line.cmd and not line.cmd.validate(messages):
        msg = 'error: %s: %s' % (line.cmd.name, " ".join(messages))
        self.log.messages.append(msg)

    return len(self.log.messages) == 0
502281
def validate(self, instance, value):
        
        if isinstance(value, string_types) and self.mode is not None:
            try:
                value = open(value, self.mode)
            except (IOError, TypeError):
                self.error(instance, value,
                           extra='Cannot open file: {}'.format(value))
        if not all([hasattr(value, attr) for attr in ('read', 'seek')]):
            self.error(instance, value, extra='Not a file-like object')
        if not hasattr(value, 'mode') or self.valid_modes is None:
            pass
        elif value.mode not in self.valid_modes:
            self.error(instance, value,
                       extra='Invalid mode: {}'.format(value.mode))
        if getattr(value, 'closed', False):
            self.error(instance, value, extra='File is closed.')
        return value
1046577
def _validate(cls, options, items, warnfn):
        ""

        if 'html' in Store.display_formats:
            pass
        elif 'fig' in items and items['fig'] not in Store.display_formats:
            msg = ("Requesting output figure format %r " % items['fig']
                   + "not in display formats %r" % Store.display_formats)
            if warnfn is None:
                print('Warning: {msg}'.format(msg=msg))
            else:
                warnfn(msg)

        backend = Store.current_backend
        return Store.renderers[backend].validate(options)
363124
def _validate(url):
    
    if url is None:
        return
    parsed = urlparse(url)
    if not parsed.scheme or not parsed.netloc:
        raise ValueError("Invalid URL header")
491685
def validate_xml(file):
    """"""
    max_file_size = current_app.config.get(
        'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024)
    if file.size > max_file_size:
        return False

    with file.open() as fp:
        try:
            content = fp.read().decode('utf-8')
            xml.dom.minidom.parseString(content)
            return True
        except:
            return False
137762
def validate(self, r):
        '''
        
        '''
        if self.show_invalid:
            r.valid = True
        elif r.valid:
            if not r.description:
                r.valid = False

            if r.size and (r.size + r.offset) > r.file.size:
                r.valid = False

            if r.jump and (r.jump + r.offset) > r.file.size:
                r.valid = False

            if hasattr(r, "location") and (r.location != r.offset):
                r.valid = False

        if r.valid:
            # Don't keep displaying signatures that repeat a bunch of times
            # (e.g., JFFS2 nodes)
            if r.id == self.one_of_many:
                r.display = False
            elif r.many:
                self.one_of_many = r.id
            else:
                self.one_of_many = None
14973
def validate(cls, cfg, path="", nested=0, parent_cfg=None):
        

        # number of critical errors found
        num_crit = 0

        # number of non-critical errors found
        num_warn = 0


        # check for missing keys in the config
        for name in dir(cls):
            if nested > 0:
                break
            try:
                attr = getattr(cls, name)
                if isinstance(attr, Attribute):
                    if attr.default is None and name not in cfg:
                        # no default value defined, which means its required
                        # to be set in the config file
                        if path:
                            attr_full_name = "%s.%s" % (path, name)
                        else:
                            attr_full_name = name
                        raise vodka.exceptions.ConfigErrorMissing(
                            attr_full_name, attr)
                    attr.preload(cfg, name)

            except vodka.exceptions.ConfigErrorMissing as inst:
                if inst.level == "warn":
                    vodka.log.warn(inst.explanation)
                    num_warn += 1
                elif inst.level == "critical":
                    vodka.log.error(inst.explanation)
                    num_crit += 1


        if type(cfg) in [dict, Config]:
            keys = list(cfg.keys())
            if nested > 0:
                for _k, _v in cfg.items():
                    _num_crit, _num_warn = cls.validate(
                        _v,
                        path=("%s.%s" % (path, _k)),
                        nested=nested-1,
                        parent_cfg=cfg
                    )
                    num_crit += _num_crit
                    num_warn += _num_warn
                return num_crit, num_warn
        elif type(cfg) == list:
            keys = list(range(0, len(cfg)))
        else:
            raise ValueError("Cannot validate non-iterable config value")



        # validate existing keys in the config
        for key in keys:
            try:
                _num_crit, _num_warn = cls.check(cfg, key, path)
                num_crit += _num_crit
                num_warn += _num_warn
            except (
                vodka.exceptions.ConfigErrorUnknown,
                vodka.exceptions.ConfigErrorValue,
                vodka.exceptions.ConfigErrorType
            ) as inst:
                if inst.level == "warn":
                    vodka.log.warn(inst.explanation)
                    num_warn += 1
                elif inst.level == "critical":
                    vodka.log.error(inst.explanation)
                    num_crit += 1

        return num_crit, num_warn
1306635
def _validate_templates(self, app, files, verbose):
        
        from uliweb import application
        from uliweb.core.template import template_file
        from uliweb.utils.common import trim_path

        app.template_loader.log = None
        for f in files:
            try:
                t = app.template_loader.load(f)
                if verbose:
                    print 'PASSED', f
            except Exception as e:
                print 'FAILED', f, str(e)
885856
def validate(self):
        
        # Ange Albertini (@angie4771) can kill me for this! :)
        if self.dosHeader.e_magic.value != consts.MZ_SIGNATURE:
            raise excep.PEException("Invalid MZ signature. Found %d instead of %d." % (self.dosHeader.magic.value, consts.MZ_SIGNATURE))
        
        if self.dosHeader.e_lfanew.value > len(self):
            raise excep.PEException("Invalid e_lfanew value. Probably not a PE file.")
            
        if self.ntHeaders.signature.value != consts.PE_SIGNATURE: 
            raise excep.PEException("Invalid PE signature. Found %d instead of %d." % (self.ntHeaders.optionaHeader.signature.value, consts.PE_SIGNATURE))
            
        if self.ntHeaders.optionalHeader.numberOfRvaAndSizes.value > 0x10:
            print excep.PEWarning("Suspicious value for NumberOfRvaAndSizes: %d." % self.ntHeaders.optionaHeader.numberOfRvaAndSizes.value)
197589
def validate(self):
        
        assert self.path, "{} must have a path".format(self.__class__.__name__)
        _, dotext = os.path.splitext(self.path)
        ext = dotext.lstrip('.')
        # don't validate for single-digit extension, or no extension
        if len(ext) > 1:
            assert ext in self.allowed_formats, "{} must have one of the following"
            "extensions: {} (instead, got '{}' from '{}')".format(
            self.__class__.__name__, self.allowed_formats, ext, self.path)
224043
def validate_pattern(fn):
    
    directory, pattern = parse_pattern(fn)
    if directory is None:
        print_err("Invalid pattern {}.".format(fn))
        return None, None
    target = resolve_path(directory)
    mode = auto(get_mode, target)
    if not mode_exists(mode):
        print_err("cannot access '{}': No such file or directory".format(fn))
        return None, None
    if not mode_isdir(mode):
        print_err("cannot access '{}': Not a directory".format(fn))
        return None, None
    return target, pattern
13955
def load(self, file):
		
		if isfile(file):
			try:
				config = load_source("config", file)
			except Exception as e:
				raise ExceptionInConfigError(e)
			option_missing = False
			values = {}
			for option in self.options:
				# Make sure all options are avaliable (validators aren't run in this case
				# because there are no values defined)
				if option.name not in dir(config):
					values[option.name] = option.default_value
					option_missing = True
				else:
					# Retrieve the option value
					value = getattr(config, option.name)
					# Make sure validator passes
					if option.validator != None:	
						# If validation doesn't pass
						if not option.validator(value):
							# Resort to default value
							values[option.name] = option.default_value
							if self.validation_failed != None:
								self.validation_failed(option.name, value)
							else:
								raise ValidationError(option.name)
							option_missing = True
						# If validation passes
						else:
							values[option.name] = value
					else:
						values[option.name] = value
				if option_missing:
					self.dump(file)
			return _EditableConfig(values, self.options, file, 
				validation_failed=self.validation_failed, debug=self.debug)
		else:
			error = "'%s' not found" % file
			raise FileNotFoundError(error) if version.startswith("3") else IOError(error)
224745
def validate(fname):
    
    validation = {
        "errors": [],
        "warnings": []
    }
    for line in _process(fname):
        kind, message = _determine(line)
        if kind in validation:
            validation[kind].append(message)
    return validation
648438
def validate(args):
    
    p = OptionParser(validate.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    imputed, withheld = args
    register = {}
    fp = open(withheld)
    for row in fp:
        if row[0] == "#":
            continue
        v = VcfLine(row)
        register[(v.seqid, v.pos)] = v.genotype

    logging.debug("Imported {0} records from `{1}`".\
                    format(len(register), withheld))

    fp = must_open(imputed)
    hit = concordant = 0
    seen = set()
    for row in fp:
        if row[0] == "#":
            continue
        v = VcfLine(row)
        chr, pos, genotype = v.seqid, v.pos, v.genotype
        if (chr, pos) in seen:
            continue
        seen.add((chr, pos))
        if (chr, pos) not in register:
            continue
        truth = register[(chr, pos)]
        imputed = genotype.split(":")[0]
        if "|" in imputed:
            imputed = "/".join(sorted(genotype.split(":")[0].split("|")))
            #probs = [float(x) for x in genotype.split(":")[-1].split(",")]
            #imputed = max(zip(probs, ["0/0", "0/1", "1/1"]))[-1]
        hit += 1
        if truth == imputed:
            concordant += 1
        else:
            print(row.strip(), "truth={0}".format(truth), file=sys.stderr)

    logging.debug("Total concordant: {0}".\
            format(percentage(concordant, hit)))
311511
def run_validation(options):
    
    if options.files == sys.stdin:
        results = validate(options.files, options)
        return [FileValidationResults(is_valid=results.is_valid,
                                      filepath='stdin',
                                      object_results=results)]

    files = get_json_files(options.files, options.recursive)

    results = [validate_file(fn, options) for fn in files]

    return results