Validates a submission file

        :param file_path: path to file to be loaded.
        :param data: pre loaded YAML object (optional).
        :return: Bool to indicate the validity of the file.
976342
def validate(self, **kwargs):
        
        try:
            submission_file_schema = json.load(open(self.default_schema_file, 'r'))

            additional_file_section_schema = json.load(open(self.additional_info_schema, 'r'))

            # even though we are using the yaml package to load,
            # it supports JSON and YAML
            data = kwargs.pop("data", None)
            file_path = kwargs.pop("file_path", None)

            if file_path is None:
                raise LookupError("file_path argument must be supplied")

            if data is None:
                data = yaml.load_all(open(file_path, 'r'), Loader=Loader)

            for data_item_index, data_item in enumerate(data):
                if data_item is None:
                    continue
                try:
                    if not data_item_index and 'data_file' not in data_item:
                        validate(data_item, additional_file_section_schema)
                    else:
                        validate(data_item, submission_file_schema)

                except ValidationError as ve:
                    self.add_validation_message(
                            ValidationMessage(file=file_path,
                                                message=ve.message + ' in ' + str(ve.instance)))

            if self.has_errors(file_path):
                return False
            else:
                return True

        except ScannerError as se:  # pragma: no cover
            self.add_validation_message(  # pragma: no cover
                ValidationMessage(file=file_path, message=
                    'There was a problem parsing the file.  '
                    'This can be because you forgot spaces '
                    'after colons in your YAML file for instance.  '
                    'Diagnostic information follows.\n' + str(se)))
            return False

        except Exception as e:
            self.add_validation_message(ValidationMessage(file=file_path, message=e.__str__()))
            return False
832159
protected boolean validClassFilePath(String path)
	{
		if(path==null)
		{
			return false;
		}
		File file=new File(path);
		return file.exists()&&file.isFile();
	}
1332477
def AddFileReadData(self, path, file_data_path):
    
    if self.file_system.FileEntryExistsByPath(path):
      raise ValueError('Path: {0:s} already set.'.format(path))

    with open(file_data_path, 'rb') as file_object:
      file_data = file_object.read()

    self._AddParentDirectories(path)
    self.file_system.AddFileEntry(path, file_data=file_data)
784838
def check_syntax(self, app_path=None):
        
        app_path = app_path or '.'

        for filename in sorted(os.listdir(app_path)):
            error = None
            status = True
            if filename.endswith('.py'):
                try:
                    with open(filename, 'rb') as f:
                        ast.parse(f.read(), filename=filename)
                except SyntaxError:
                    status = False
                    # cleanup output
                    e = []
                    for line in traceback.format_exc().split('\n')[-5:-2]:
                        e.append(line.strip())
                    error = ' '.join(e)

            elif filename.endswith('.json'):
                try:
                    with open(filename, 'r') as fh:
                        json.load(fh)
                except ValueError as e:
                    status = False
                    error = e
            else:
                # skip unsupported file types
                continue

            if error:
                # update validation data errors
                self.validation_data['errors'].append(
                    'Syntax validation failed for {} ({}).'.format(filename, error)
                )

            # store status for this file
            self.validation_data['fileSyntax'].append({'filename': filename, 'status': status})
1032513
def load_parameter_file(file_path, name = ''):
    
    if not os.path.exists(file_path):
        raise ValueError("{} doest not exist".format(file_path))
    if os.path.isdir(file_path):
        return ParameterNode(name, directory_path = file_path)
    data = _load_yaml_file(file_path)
    return _parse_child(name, data, file_path)
554683
def _submit(self, pathfile, filedata, filename):
		'''
		
		'''
		if pathfile and os.path.exists(pathfile):
			files = {'file': open(pathfile, 'rb')}
		elif filedata:
			assert filename
			files = {'file' : (filename, io.BytesIO(filedata))}
		else:
			raise ValueError("You must pass either a valid file path, or a bytes array containing the captcha image!")

		payload = {
			'key'    : self.api_key,
			'method' : 'post',
			'json'   : True,
			}

		self.log.info("Uploading to 2Captcha.com.")

		url = self.getUrlFor('input', {})

		request = requests.post(url, files=files, data=payload)

		if not request.ok:
			raise exc.CaptchaSolverFailure("Posting captcha to solve failed!")

		resp_json = json.loads(request.text)
		return self._process_response(resp_json)
1246406
public static boolean validatePath(String path) {
        if(path == null) {
            Log.w(TAG, "Uploading path not set");
            return false;
        }

        try {
            uriFromString(path);
            return true;
        } catch(DataSinkException e) {
            return false;
        }
    }
436759
def validate_yaml_file(schema: dict, yaml_file: Path):
    

    with yaml_file.open() as f:
        data = yaml.load(f)

    jsonschema.validate(data, schema)
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
424899
def validate(self, path):
        """"""
        # Exclude hidden files and folders with '.' prefix
        if os.path.basename(path).startswith('.'):
            return False

        # Check that current path level is more than min path and less than max path
        if not self.check_level(path):
            return False

        if self.filters:
            if not self._level_filters(path):
                return False

        # Force include and exclude iterations to be strings in case of integer filters
        # Handle exclusions
        if self.to_exclude:
            if any(str(ex).lower() in path.lower() for ex in self.to_exclude):
                return False

        # Handle inclusions
        if self.to_include:
            if not any(str(inc).lower() in path.lower() for inc in self.to_include):
                return False

        return True
969348
def parse(self, data_in, *args, **kwargs):
        
        if not os.path.exists(data_in):
            raise ValueError("File / Directory does not exist: %s" % data_in)

        if os.path.isdir(data_in):
            submission_filepath = os.path.join(data_in, 'submission.yaml')
            if not os.path.exists(submission_filepath):
                submission_filepath = os.path.join(data_in, 'submission.yml')
                if not os.path.exists(submission_filepath):
                    raise ValueError("No submission file in %s" % data_in)
            data_in = submission_filepath

        # first validate submission file:
        with open(data_in, 'r') as submission_file:
            submission_data = list(yaml.load_all(submission_file, Loader=Loader))

            if len(submission_data) == 0:
                raise RuntimeError("Submission file (%s) is empty" % data_in)

            submission_file_validator = SubmissionFileValidator()
            if not submission_file_validator.validate(file_path=data_in,
                                                      data=submission_data):
                raise RuntimeError(
                    "Submission file (%s) did not pass validation: %s" %
                    (data_in, self._pretty_print_errors(
                        submission_file_validator.get_messages())))

        metadata = {}
        tables = []

        # validator for table data
        data_file_validator = DataFileValidator()

        index = 0
        for i in range(0, len(submission_data)):
            if not submission_data[i]: # empty YAML document
                continue
            if 'data_file' not in submission_data[i]:
                metadata = submission_data[i] # information about whole submission
                continue
            table_filepath = os.path.join(os.path.dirname(data_in),
                                          submission_data[i]['data_file'])
            with open(table_filepath, 'r') as table_file:
                if not os.path.exists(table_filepath):
                    raise ValueError(
                        "table file: %s does not exist" % table.data_file)

                table_data = yaml.load(table_file, Loader=Loader)

                if not data_file_validator.validate(data=table_data,
                                                    file_path=table_filepath):
                    raise RuntimeError(
                        "Data file (%s) did not pass validation: %s" %
                        (table_filepath, self._pretty_print_errors(
                            data_file_validator.get_messages())))

                index = index + 1
                table = Table(index=index, metadata=submission_data[i],
                              data=table_data)
                tables.append(table)

        return ParsedData(metadata, tables)
1335561
def read(self, file_path=None):
        
        if not file_path:
            file_path = self.file_path

        # abort if the file path does not exist
        if not os.path.exists(file_path):
            self.oops("Sorry, but {} does not exist".format(file_path))
            return False

        # abort if the file path is not a file
        if not os.path.isfile(file_path):
            self.oops("Sorry, but {} is not a file".format(file_path))
            return False

        with open(file_path) as handler:
            return handler.read()
1299965
def isValid(folder, epoch=0):
    
    # Validate by checking for the training 'silence.pkl' on the given epoch
    # This file is unique to our pre-processed dataset generated by 'process_dataset.py'
    return os.path.exists(os.path.join(folder, str(epoch), "train", "silence.pkl"))
87503
def ensure_file(path):
        
        try:
            exists = isfile(path)
            if not exists:
                with open(path, 'w+') as fname:
                    fname.write('initialized')
                return (True, path)
            return (True, 'exists')
        except OSError as e:  # pragma: no cover
            return (False, e)
675075
async def validate(state, holdout_glob):
  

  if not glob.glob(holdout_glob):
    print('Glob "{}" didn\'t match any files, skipping validation'.format(
          holdout_glob))
  else:
    await run(
        'python3', 'validate.py', holdout_glob,
        '--flagfile={}'.format(os.path.join(FLAGS.flags_dir, 'validate.flags')),
        '--work_dir={}'.format(fsdb.working_dir()))
871130
def is_valid_py_file(path):
    '''
    
    '''
    import os

    is_valid = False
    if os.path.isfile(path) and not os.path.splitext(path)[1] == '.pyx':
        try:
            with open(path, 'rb') as f:
                compile(f.read(), path, 'exec')
                is_valid = True
        except:
            pass
    return is_valid
345756
def validate_data_files(problem, data_files, min_size):
  """"""
  # Check that all files are present
  data_dir = os.path.split(data_files[0])[0]
  out_filepaths = problem.out_filepaths(data_dir)
  missing_filepaths = set(out_filepaths) - set(data_files)
  if missing_filepaths:
    tf.logging.error("Missing %d data files", len(missing_filepaths))

  # Check that each file is at least 100M
  too_small = []
  for data_file in data_files:
    length = get_length(data_file)
    if length < min_size:
      too_small.append(data_file)
  if too_small:
    tf.logging.error("%d files too small", len(too_small))

  bad_files = too_small + list(missing_filepaths)
  return bad_files