Test a file and check what should be done with the resulting file.
974779
function handle(filePath) {
    var file = toVFile(filePath)
    var result = test(file)

    if (mask(result, INCLUDE)) {
      if (one) {
        callback(null, file)
        return true
      }

      results.push(file)
    }

    if (mask(result, BREAK)) {
      callback(null, one ? null : results)
      return true
    }
  }
298935
def _check_file(self, filename):
    
    # If the user specifies an invalid severity use comment.
    log_threshold = Nit.SEVERITY.get(self._severity, Nit.COMMENT)

    failure_count = 0
    fail_threshold = Nit.WARNING if self._strict else Nit.ERROR

    for i, nit in enumerate(self._get_nits(filename)):
      if i == 0:
        print()  # Add an extra newline to clean up the output only if we have nits.
      if nit.severity >= log_threshold:
        print('{nit}\n'.format(nit=nit))
      if nit.severity >= fail_threshold:
        failure_count += 1
    return failure_count
991445
def _analyze_file(self, f):
        """"""

        f.seek(0)
        # Check for BOMs
        if self.CHECK_BOM:
            encoding = self.has_bom(f)
            f.seek(0)
        else:
            util.warn_deprecated(
                "'CHECK_BOM' attribute is deprecated. "
                "Please override 'has_bom` function to control or avoid BOM detection."
            )
        # Check file extensions
        if encoding is None:
            encoding = self._utf_strip_bom(self.header_check(f.read(1024)))
            f.seek(0)
        if encoding is None:
            encoding = self._utf_strip_bom(self.content_check(f))
            f.seek(0)

        return encoding
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
568851
function check(result, test) {

  const CHECKERS = [ _checkExitCode, _checkOutput, _checkStdout, _checkStderr ];
  var errors = [];

  CHECKERS.forEach(function (checker) {
    var error = checker(result, test);
    if (error) {
      errors.push(error);
    }
  });
  
  return errors;
}
515263
def do_failures(self, arg):
        
        usable, filename, append = self._redirect_split(arg)
        a = self.tests[self.active]
        args = self.curargs
        splitargs = usable.split()
        if len(splitargs) > 0:
            tfilter = splitargs[0]
        else:
            tfilter = "*"

        outfiles = None
        if len(splitargs) > 1:
            outfiles = splitargs[1:len(splitargs)]

        result = a.failures(outfiles, args["threshold"], tfilter)
        self._redirect_output(result, filename, append, msg.info)
355486
private void checkFile() throws IORuntimeException {
		Assert.notNull(file, "File to write content is null !");
		if(this.file.exists() && false == file.isFile()){
			throw new IORuntimeException("File [{}] is not a file !", this.file.getAbsoluteFile());
		}
	}
366
function readSpecFile(file, options) {
    if (options.verbose > 1) {
        file ? console.error('GET ' + file) : console.error('GET <stdin>');
    }
    if (!file) {
        // standard input
        return readFileStdinAsync();
    } else if (file && file.startsWith('http')) {
        // remote file
        return fetch(file).then(res => {
            if (res.status !== 200) {
                throw new Error(`Received status code ${res.status}`);
            }
            return res.text();
        })
    } else {
        // local file
        // TODO error handlers?
        return readFileAsync(file, 'utf8');
    }
}
122575
def _ensure_file_is_good(self, current_time):
        """"""
        if self._last_file_mapping_update and current_time - self._last_file_mapping_update <= self._stat_interval:
            return

        self._last_file_mapping_update = time.time()

        try:
            st = os.stat(self._filename)
        except EnvironmentError, err:
            if err.errno == errno.ENOENT:
                self._log_info('file removed')
                self.close()
                return
            raise

        fid = self.get_file_id(st)
        if fid != self._fid:
            self._log_info('file rotated')
            self.close()
        elif self._file.tell() > st.st_size:
            if st.st_size == 0 and self._ignore_truncate:
                self._logger.info("[{0}] - file size is 0 {1}. ".format(fid, self._filename) +
                                  "If you use another tool (i.e. logrotate) to truncate " +
                                  "the file, your application may continue to write to " +
                                  "the offset it last wrote later. In such a case, we'd " +
                                  "better do nothing here")
                return
            self._log_info('file truncated')
            self._update_file(seek_to_end=False)
        elif REOPEN_FILES:
            self._log_debug('file reloaded (non-linux)')
            position = self._file.tell()
            self._update_file(seek_to_end=False)
            if self.active:
                self._file.seek(position, os.SEEK_SET)
356193
def overwrite_file_check(args, filename):
    """"""
    if not args['overwrite'] and os.path.exists(filename):
        # Confirm overwriting of the file, or modify filename
        if args['no_overwrite']:
            overwrite = False
        else:
            try:
                overwrite = confirm_input(input('Overwrite {0}? (yes/no): '
                                                .format(filename)))
            except (KeyboardInterrupt, EOFError):
                sys.exit()
        if not overwrite:
            new_filename = modify_filename_id(filename)
            while os.path.exists(new_filename):
                new_filename = modify_filename_id(new_filename)
            return new_filename
    return filename
53061
def _check(self, file):
        

        if not os.path.exists(file):
            raise Error("file \"{}\" not found".format(file))

        _, extension = os.path.splitext(file)
        try:
            check = self.extension_map[extension[1:]]
        except KeyError:
            magic_type = magic.from_file(file)
            for name, cls in self.magic_map.items():
                if name in magic_type:
                    check = cls
                    break
            else:
                raise Error("unknown file type \"{}\", skipping...".format(file))

        try:
            with open(file) as f:
                code = "\n".join(line.rstrip() for line in f)
        except UnicodeDecodeError:
            raise Error("file does not seem to contain text, skipping...")

        # Ensure we don't warn about adding trailing newline
        try:
            if code[-1] != '\n':
                code += '\n'
        except IndexError:
            pass

        return check(code)
341514
function doesFileExist (path) {
  return new Promise(resolve => {
    fs.stat(path, (err, stat) => {
      // The file exists if there were no errors, and it's a file
      resolve(!err && stat.isFile())
    })
  })
}
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)
251780
function check( input, expected ) {
            const output = Util.replaceDotsWithSlashes( input );
            expect( output ).toBe( expected.split( '/' ).join( Path.sep ) );
        }
125245
def filesampler(files, testsetsize = 0.1, devsetsize = 0, trainsetsize = 0, outputdir = '', encoding='utf-8'):
        """"""

        if not isinstance(files, list):
            files = list(files)

        total = 0
        for filename in files:
            f = io.open(filename,'r', encoding=encoding)
            count = 0
            for line in f:
                count += 1
            f.close()
            if total == 0:
                total = count
            elif total != count:
                raise Exception("Size mismatch, when multiple files are specified they must contain the exact same amount of lines! (" +str(count)  + " vs " + str(total) +")")

        #support for relative values:
        if testsetsize < 1:
            testsetsize = int(total * testsetsize)
        if devsetsize < 1 and devsetsize > 0:
            devsetsize = int(total * devsetsize)


        if testsetsize >= total or devsetsize >= total or testsetsize + devsetsize >= total:
            raise Exception("Test set and/or development set too large! No samples left for training set!")


        trainset = {}
        testset = {}
        devset = {}
        for i in range(1,total+1):
            trainset[i] = True
        for i in random.sample(trainset.keys(), int(testsetsize)):
            testset[i] = True
            del trainset[i]

        if devsetsize > 0:
            for i in random.sample(trainset.keys(), int(devsetsize)):
                devset[i] = True
                del trainset[i]

        if trainsetsize > 0:
            newtrainset = {}
            for i in random.sample(trainset.keys(), int(trainsetsize)):
                newtrainset[i] = True
            trainset = newtrainset

        for filename in files:
            if not outputdir:
                ftrain = io.open(filename + '.train','w',encoding=encoding)
            else:
                ftrain = io.open(outputdir + '/' +  os.path.basename(filename) + '.train','w',encoding=encoding)
            if not outputdir:
                ftest = io.open(filename + '.test','w',encoding=encoding)
            else:
                ftest = io.open(outputdir + '/' + os.path.basename(filename) + '.test','w',encoding=encoding)
            if devsetsize > 0:
                if not outputdir:
                    fdev = io.open(filename + '.dev','w',encoding=encoding)
                else:
                    fdev = io.open(outputdir + '/' +  os.path.basename(filename) + '.dev','w',encoding=encoding)

            f = io.open(filename,'r',encoding=encoding)
            for linenum, line in enumerate(f):
                if linenum+1 in trainset:
                    ftrain.write(line)
                elif linenum+1 in testset:
                    ftest.write(line)
                elif devsetsize > 0 and linenum+1 in devset:
                    fdev.write(line)
            f.close()

            ftrain.close()
            ftest.close()
            if devsetsize > 0: fdev.close()
545220
def save_and_check(response, local_file, expected_checksum):
    """"""
    with open(local_file, 'wb') as handle:
        for chunk in response.iter_content(4096):
            handle.write(chunk)

    actual_checksum = md5sum(local_file)
    if actual_checksum != expected_checksum:
        logging.error('Checksum mismatch for %r. Expected %r, got %r',
                      local_file, expected_checksum, actual_checksum)
        return False

    return True
896309
public void execute() throws IOException, NoSuchAlgorithmException {
        if (src == null) {
            throw new IllegalArgumentException("Please provide a file to verify");
        }
        if (algorithm == null) {
            throw new IllegalArgumentException("Please provide the algorithm to "
                    + "use to calculate the checksum");
        }
        if (checksum == null) {
            throw new IllegalArgumentException("Please provide a checksum to verify against");
        }
        
        // calculate file's checksum
        MessageDigest md = MessageDigest.getInstance(algorithm);
        FileInputStream fis = new FileInputStream(src);
        String calculatedChecksum;
        try {
            byte[] buf = new byte[1024];
            int read = 0;
            while ((read = fis.read(buf)) != -1) {
                md.update(buf, 0, read);
            }
            calculatedChecksum = toHex(md.digest());
        } finally {
            fis.close();
        }
        
        // verify checksum
        if (!calculatedChecksum.equalsIgnoreCase(checksum)) {
            throw new GradleException("Invalid checksum for file '" +
                    src.getName() + "'. Expected " + checksum.toLowerCase() + 
                    " but got " + calculatedChecksum.toLowerCase() + ".");
        }
    }