The default validator only accepts files ending in .py
        (and not prefixed by a period).
169429
def default_validator(self, filepath):
        
        return filepath.endswith('.py') and \
            not os.path.basename(filepath).startswith('.')
371602
def parse_rule(cls, txt):
        
        types = {"glob": GlobRule,
                 "regex": RegexRule,
                 "range": RangeRule,
                 "before": TimestampRule,
                 "after": TimestampRule}

        # parse form 'x(y)' into x, y
        label, txt = Rule._parse_label(txt)
        if label is None:
            if '*' in txt:
                label = "glob"
            else:
                label = "range"
        elif label not in types:
            raise ConfigurationError(
                "'%s' is not a valid package filter type" % label)

        rule_cls = types[label]
        txt_ = "%s(%s)" % (label, txt)

        try:
            rule = rule_cls._parse(txt_)
        except Exception as e:
            raise ConfigurationError("Error parsing package filter '%s': %s: %s"
                                     % (txt_, e.__class__.__name__, str(e)))
        return rule
1097015
async def validate(self, request: web.Request):
        
        parameters = {}
        files = {}
        errors = self.errors_factory()
        body = None

        if request.method in request.POST_METHODS:
            try:
                body = await self._content_receiver.receive(request)
            except ValueError as e:
                errors[request.content_type].add(str(e))
            except TypeError:
                errors[request.content_type].add('Not supported content type')

        for name, param in self._parameters.items():
            where = param['in']
            schema = param.get('schema', param)
            vtype = schema['type']
            is_array = vtype == 'array'

            if where == 'query':
                source = request.query
            elif where == 'header':
                source = request.headers
            elif where == 'path':
                source = request.match_info
            elif body is None:
                source = ()
            elif where == 'formData':
                source = body
            elif where == 'body':
                if isinstance(body, BaseException):
                    errors[name].add(str(body))
                else:
                    parameters[name] = body
                continue
            else:
                raise ValueError(where)

            if is_array and hasattr(source, 'getall'):
                collection_format = param.get('collectionFormat')
                default = param.get('default', [])
                value = get_collection(source, name,
                                       collection_format, default)
                if param.get('minItems') and not value \
                        and name not in self._required:
                    continue
            elif isinstance(source, Mapping) and name in source and (
                vtype not in ('number', 'integer') or source[name] != ''
            ):
                value = source[name]
            elif 'default' in param:
                parameters[name] = param['default']
                continue
            elif name in self._required:
                errors[name].add('Required')
                if isinstance(source, BaseException):
                    errors[name].add(str(body))
                continue
            else:
                continue

            if is_array:
                vtype = schema['items']['type']
                vformat = schema['items'].get('format')
            else:
                vformat = schema.get('format')

            if source is body and isinstance(body, dict):
                pass
            elif vtype not in ('string', 'file'):
                value = convert(name, value, vtype, vformat, errors)

            if vtype == 'file':
                files[name] = value
            else:
                parameters[name] = value

        parameters = self._validate(parameters, errors)
        parameters.update(files)
        return parameters, errors
1227455
def validate(self, data, all_data=None):
        

        all_data = all_data or {}

        if hasattr(data, 'stream'):
            data.file = data.stream

        if hasattr(data, 'file'):
            if data.file:
                v = data.filename
            else:
                raise Exception, 'Unsupport type %s' % type(data)
        else:
            v = data
#        if v is None:

        msg = TEST_NOT_EMPTY()(v)
        if self.required:
            if msg:
                return False, msg
        else:
            if msg:
                return True, self.default

        try:
            if isinstance(data, list):
                v = []
                for i in data:
                    v.append(self.to_python(i))
                data = v
            else:
                data = self.to_python(data)
        except:
            return False, unicode(ERR_CONVERT) % (data, self.__class__.__name__)
        for v in self.get_validators():
            msg = v(data, all_data)
            if msg:
                return False, msg
        return True, data
521758
def _validate_markdown(self, expfile):
        ''''''

        try:
            import yaml
        except:
            bot.error('Python yaml is required for testing yml/markdown files.')
            sys.exit(1)

        self.metadata = {}
        uid = os.path.basename(expfile).strip('.md')
     
        if os.path.exists(expfile):
            with open(expfile, "r") as stream:
                docs = yaml.load_all(stream)
                for doc in docs:
                    if isinstance(doc,dict):
                        for k,v in doc.items():
                            print('%s: %s' %(k,v))
                            self.metadata[k] = v
            self.metadata['uid'] = uid
       
            fields = ['github', 'preview', 'name', 'layout',
                      'tags', 'uid', 'maintainer']

            # Tests for all fields
            for field in fields:
                if field not in self.metadata:
                    return False
                if self.metadata[field] in ['',None]:
                    return False

            if 'github' not in self.metadata['github']:
                return notvalid('%s: not a valid github repository' % name)
            if not isinstance(self.metadata['tags'],list):
                return notvalid('%s: tags must be a list' % name)
            if not re.search("(\w+://)(.+@)*([\w\d\.]+)(:[\d]+){0,1}/*(.*)", self.metadata['github']):
                return notvalid('%s is not a valid URL.' %(self.metadata['github']))

        return True
892879
def valid_file(value):
    
    if not value:
        raise argparse.ArgumentTypeError("'' is not a valid file path")
    elif not os.path.exists(value):
        raise argparse.ArgumentTypeError(
            "%s is not a valid file path" % value)
    elif os.path.isdir(value):
        raise argparse.ArgumentTypeError(
            "%s is a directory, not a regular file" % value)
    return value
1194202
def validate(self):
        
        val = self._condition.lower()
        if val and val[0] in "+-":
            val = val[1:]

        matcher = PatternFilter
        if not val or val.startswith('/') and val.endswith('/'):
            pass
        elif val.replace('.', '0').isdigit():
            matcher = FloatFilter
        elif self._condition in (TRUE | FALSE):
            matcher = BoolFilter
        elif any(val.endswith(i) for i in ByteSizeFilter.UNITS) and val[:-1].isdigit():
            matcher = ByteSizeFilter
        elif TimeFilter.TIMEDELTA_RE.match(val):
            matcher = TimeFilter

        self._inner = matcher(self._name, self._condition)
697154
def validate_source
      fail Exceptions::TemplateNameIsMissing, 'Template file name is missing.' if empty?
      fail Exceptions::TemplateDoesNotExist, "File \"#{params.template}\" does not exist" unless exists?
      fail Exceptions::TemplateNameIsInvalid, "File \"#{params.template}\" is not a valid erb template: file ending erb" unless erb_template?
    end
660502
def is_valid_file(parser,arg):
	""""""
	if not os.path.exists(arg):
       		parser.error("File %s not found"%arg)
	else:
	       	return arg
599004
def _validate_file_format(self, file_format):
        """"""

        if file_format not in self.valid_file_formats:
            raise InvalidFileFormatError(
                "{} is not a valid file format".format(file_format)
            )

        return file_format
83896
def plugin_valid(self, filename):
        
        filename = os.path.basename(filename)
        for regex in self.regex_expressions:
            if regex.match(filename):
                return True
        return False
1064
def load_validator(schema_path, schema):
    
    # Get correct prefix based on OS
    if os.name == 'nt':
        file_prefix = 'file:///'
    else:
        file_prefix = 'file:'

    resolver = RefResolver(file_prefix + schema_path.replace("\\", "/"), schema)
    validator = Draft4Validator(schema, resolver=resolver)

    return validator
1039943
def parse_file_type(file_type):
    '''
    
    '''
    valid_file_filter = r'^([\w ]+)\((\*(?:\.(?:\w+|\*))*(?:;\*\.\w+)*)\)$'
    match = re.search(valid_file_filter, file_type)

    if match:
        return match.group(1).rstrip(), match.group(2)
    else:
        raise ValueError('{0} is not a valid file filter'.format(file_type))
1134949
def py3(check):
    

    if check in get_valid_checks():
        path_to_module = os.path.dirname(get_version_file(check))
    else:
        path_to_module = check

    if not os.path.exists(path_to_module):
        abort(u"{} does not exist.".format(path_to_module))

    echo_info(u"Validating python3 compatibility of {}...".format(check))
    results = validate_py3(path_to_module)

    if results:
        echo_failure(u"Incompatibilities were found for {}:".format(check))
        current_path = None
        for problem in sorted(results, key=itemgetter("path")):
            # validate_py3 returns an array a dicts like
            # {
            #     "message": "Line 23, Column 8: Calling a dict.iter*() method",
            #     "file": "/path/to/file.py",
            # }
            path = problem["path"]
            if current_path is None or path != current_path:
                echo_info(u"File {}:".format(path))
            echo_failure("  {}".format(problem["message"]))
            current_path = path
        abort()
    else:
        echo_success(u"{} is compatible with python3".format(check))
1099572
function validate(dname) {
    var filenames = glob.sync(dname + '/src/*.ts*');
    filenames = filenames.concat(glob.sync(dname + '/src/**/*.ts*'));

    if (filenames.length == 0) {
        return [];
    }

    var imports = [];

    try {
        var pkg = require(path.resolve(dname) + '/package.json');
    } catch (e) {
        return [];
    }
    var ignore = IGNORE[pkg['name']] || [];
    var deps = pkg['dependencies'];

    // Extract all of the imports from the TypeScript files.
    filenames.forEach(fileName => {
        var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true);
        imports = imports.concat(getImports(sourceFile));
        //console.log(fileName, getImports(sourceFile));
    });
    var names = Array.from(new Set(imports)).sort();
    names = names.map(function(name) {
        var parts = name.split('/');
        if (name.indexOf('@') === 0) {
            return parts[0] + '/' + parts[1];
        }
        return parts[0];
    })

    var problems = [];
    names.forEach(function(name) {
        if (name === '..' || name === '.' || ignore.indexOf(name) !== -1) {
            return;
        }
        if (!deps[name]) {
            problems.push('Missing package: ' + name);
        }
    });
    Object.keys(deps).forEach(function(name) {
        if (versions[name]) {
            var desired = '^' + versions[name];
            if (deps[name] !== desired) {
                problems.push('Bad core version: ' + name + ' should be ' + desired);
            }
        }
        if (ignore.indexOf(name) !== -1) {
            return;
        }
        if (names.indexOf(name) === -1) {
            problems.push('Unused package: ' + name);
        }
    });
    return problems;
}
695419
def validate(self):
        
        if not self.file.exists():
            raise ValueError("File \"%s\" doesn't exists")

        if not self.search:
            raise ValueError("Search cannot be empty")

        if not self.replace:
            raise ValueError("Replace cannot be empty")

        if self.match not in ('file', 'line'):
            raise ValueError("Match must be one of: file, line")

        try:
            codecs.lookup(self.encoding)
        except LookupError:
            raise ValueError("Unknown encoding: \"%s\"" % self.encoding)
568195
def check_with_pyflakes(source_code, filename=None):
    """"""
    try:
        if filename is None:
            filename = '<string>'
        try:
            source_code += '\n'
        except TypeError:
            # Python 3
            source_code += to_binary_string('\n')
            
        import _ast
        from pyflakes.checker import Checker
        # First, compile into an AST and handle syntax errors.
        try:
            tree = compile(source_code, filename, "exec", _ast.PyCF_ONLY_AST)
        except SyntaxError as value:
            # If there's an encoding problem with the file, the text is None.
            if value.text is None:
                results = []
            else:
                results = [(value.args[0], value.lineno)]
        except (ValueError, TypeError):
            # Example of ValueError: file contains invalid \x escape character
            # (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674797)
            # Example of TypeError: file contains null character
            # (see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=674796)
            results = []
        else:
            # Okay, it's syntactically valid.  Now check it.
            w = Checker(tree, filename)
            w.messages.sort(key=lambda x: x.lineno)
            results = []
            coding = encoding.get_coding(source_code)
            lines = source_code.splitlines()
            for warning in w.messages:
                if 'analysis:ignore' not in \
                   to_text_string(lines[warning.lineno-1], coding):
                    results.append((warning.message % warning.message_args,
                                    warning.lineno))
    except Exception:
        # Never return None to avoid lock in spyder/widgets/editor.py
        # See Issue 1547
        results = []
        if DEBUG_EDITOR:
            traceback.print_exc()  # Print exception in internal console
    return results