Validate file format string.

    Parameters
    ----------
    fmt : `str`
        File format string.
    nfiles : `int`
        Number of files.

    Raises
    ------
    ValueError
        If nfiles < 0 or format string is invalid.
500778
def check_output_format(fmt, nfiles):
    
    if nfiles < 0:
        raise ValueError('Invalid file count: ' + str(nfiles))
    if nfiles == 1:
        return
    try:
        fmt % nfiles
    except TypeError as err:
        raise ValueError(''.join(
            ('Invalid file format string: ', fmt, ': ', str(err))
        ))
1259044
def _validate_format(self, format, kwargs):
        
        kwargs = kwargs.copy()

        # validate
        try:
            kwargs['format'] = _FORMAT_MAP[format.lower()]
        except KeyError:
            raise TypeError("invalid HDFStore format specified [{0}]"
                            .format(format))

        return kwargs
664864
def _size_fmt(num):
    '''
    
    '''
    try:
        num = int(num)
        if num < 1024:
            return '{0} bytes'.format(num)
        num /= 1024.0
        for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'):
            if num < 1024.0:
                return '{0:3.1f} {1}'.format(num, unit)
            num /= 1024.0
    except Exception:
        log.error('Unable to format file size for \'%s\'', num)
        return 'unknown'
1036795
def validate_file(fpath, md5_hash):
    '''
    '''
    hasher = hashlib.md5()
    with open(fpath, 'rb') as f:
        buf = f.read()
        hasher.update(buf)
    if str(hasher.hexdigest()) == str(md5_hash):
        return True
    else:
        return False
1269414
def _validate_format(req):
        '''
        
        '''
        #check for all required keys
        for key in SLOJSONRPC._min_keys:
            if not key in req:
                logging.debug('JSONRPC: Fmt Error: Need key "%s"' % key)
                raise SLOJSONRPCError(-32600)

        #check all keys if allowed
        for key in req.keys():
            if not key in SLOJSONRPC._allowed_keys:
                logging.debug('JSONRPC: Fmt Error: Not allowed key "%s"' % key)
                raise SLOJSONRPCError(-32600)

        #needs to be jsonrpc 2.0
        if req['jsonrpc'] != '2.0':
            logging.debug('JSONRPC: Fmt Error: "jsonrpc" needs to be "2.0"')
            raise SLOJSONRPCError(-32600)
1277776
def fmt_num(num, zero_num=None):
    
    if zero_num is not None:
        num = floatformat(num, zero_num)
    return intcomma(num, False)
306277
def _file_nums_str(self, n_all, n_type, n_ign):
        
        # 'other' is the difference between all and named
        n_oth = n_all - np.sum(n_type)

        f_str = "{} Files".format(n_all) + " ("
        if len(n_type):
            f_str += ", ".join("{} {}".format(name, num) for name, num in
                               zip(self._COUNT_FILE_TYPES, n_type))
            f_str += ", "
        f_str += "other {}; {} ignored)".format(n_oth, n_ign)
        return f_str
758339
def _validate_attrs(dataset):
    
    def check_attr(name, value):
        if isinstance(name, str):
            if not name:
                raise ValueError('Invalid name for attr: string must be '
                                 'length 1 or greater for serialization to '
                                 'netCDF files')
        else:
            raise TypeError("Invalid name for attr: {} must be a string for "
                            "serialization to netCDF files".format(name))

        if not isinstance(value, (str, Number, np.ndarray, np.number,
                                  list, tuple)):
            raise TypeError('Invalid value for attr: {} must be a number, '
                            'a string, an ndarray or a list/tuple of '
                            'numbers/strings for serialization to netCDF '
                            'files'.format(value))

    # Check attrs on the dataset itself
    for k, v in dataset.attrs.items():
        check_attr(k, v)

    # Check attrs on each variable within the dataset
    for variable in dataset.variables.values():
        for k, v in variable.attrs.items():
            check_attr(k, v)
613729
function validateFileset(fileset, setter) {
    if (Array.isArray(fileset)) {
        async.each(fileset, function(path, callback) {
            if (typeof path === 'string') {
                callback();
            } else {
                callback(util.format('Invalid path: %s', path));
            }
        }, function(err) {
            if (err) {
                console.log(chalk.red(err));
            } else {
                setter(fileset);
            }
        });
    } else {
        console.log(chalk.red('Fileset is not an array: %j'), fileset);
    }
}
393673
def validate_sequence(sequence: str, sequence_is_as_nucleotide=True):
    

    tmp_seq = tempfile.NamedTemporaryFile(mode="wb+", delete=False)

    if len(str(sequence).strip()) == 0:
        raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_ERROR_MSG)

    if str(sequence).strip()[0] != ">":
        tmp_seq.write(">seq1\n".encode())

    tmp_seq.write(sequence.encode())
    tmp_seq.close()

    records = SeqIO.index(tmp_seq.name, "fasta")
    record_count = len(records)

    if record_count == 0:
        raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_ERROR_MSG)

    if record_count > blast_settings.BLAST_MAX_NUMBER_SEQ_IN_INPUT:
        raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_MAX_SEQ_NUMB_ERROR_MSG)

    # read query sequence from temporary file
    first_sequence_list_in_file = SeqIO.parse(tmp_seq.name, "fasta")

    for sequence in first_sequence_list_in_file:

        if len(sequence.seq) <= 10:
            raise forms.ValidationError(blast_settings.BLAST_CORRECT_SEQ_TOO_SHORT_ERROR_MSG)

        if sequence_is_as_nucleotide:
            check_allowed_letters(str(sequence.seq), ALLOWED_NUCL)
        else:
            check_allowed_letters(str(sequence.seq), ALLOWED_AMINOACIDS)

    return tmp_seq
141410
def opt_format(self, fmt):
        
        key = get_enum_key(fmt, FORMATTERS)
        if key is not None:
            self.conf["format"] = key
            print("Set format %r" % key)
        else:
            print("Unknown format %r" % fmt)
1095343
def _check_format(format_str):
    """"""
    if not isinstance(format_str, (_unicode, str)):
        raise TypeError("Invalid format: {0!r}".format(format_str))
    try:
        format_int = _formats[format_str.upper()]
    except KeyError:
        raise ValueError("Unknown format: {0!r}".format(format_str))
    return format_int
814596
def _sanity_check_files(item, files):
    
    msg = None
    file_types = set([("bam" if x.endswith(".bam") else "fastq") for x in files if x])
    if len(file_types) > 1:
        msg = "Found multiple file types (BAM and fastq)"
    file_type = file_types.pop()
    if file_type == "bam":
        if len(files) != 1:
            msg = "Expect a single BAM file input as input"
    elif file_type == "fastq":
        if len(files) not in [1, 2] and item["analysis"].lower() != "scrna-seq":
            pair_types = set([len(xs) for xs in fastq.combine_pairs(files)])
            if len(pair_types) != 1 or pair_types.pop() not in [1, 2]:
                msg = "Expect either 1 (single end) or 2 (paired end) fastq inputs"
        if len(files) == 2 and files[0] == files[1]:
            msg = "Expect both fastq files to not be the same"
    if msg:
        raise ValueError("%s for %s: %s" % (msg, item.get("description", ""), files))
973997
def requires_conversion(cls, fileset, file_format):
        """"""
        if file_format is None:
            return False
        try:
            filset_format = fileset.format
        except AttributeError:
            return False  # Field input
        else:
            return (file_format != filset_format)
1303670
def _is_valid_file(self, path):
        """"""
        return isinstance(path, basestring) and os.path.isfile(path)
636721
def format(self, fmt, **kwargs):
        

        def compute(self):
            values = {}
            try:
                for name, field in kwargs.iteritems():
                    values[name] = reduce(getattr, field.split('.'), self.ctx.form)
            except AttributeError, ex:
                self.ctx.errors.invalid(str(ex))
                return ERROR
            return fmt.format(**values)

        return self.compute.attach(self)(compute)
1225717
def _parse_format(cls, fmt):
        
        fields = []
        if not fmt:
            raise ValueError('empty format')
        for code, length in fmt:
            if length == 0:
                raise ValueError('zero-length field (bug_compat mismatch?)')
            if ((code in ('u', 'i') and length in (8, 16, 32, 64)) or
                    (code == 'f' and length in (32, 64))):
                fields.append('>' + code + str(length // 8))
            elif code == 'b' and length == 8:
                fields.append('?')
            elif code == 'c' and length == 8:
                fields.append('S1')
            else:
                if code not in ['u', 'i', 'b']:
                    raise ValueError('illegal format ({}, {})'.format(code, length))
                fields.append('O')
        return _np.dtype(','.join(fields))