Sometimes, the Stitch compliation appears to happen before all files are copied over to
the `tmpDir`.  We simply wait until they are.
503996
function assertFiles(expectedNumFiles, tmpDir, callback) {
    function countFiles() {
      var numFiles = 0;
      grunt.file.recurse(tmpDir, function(abspath, rootdir, subdir, filename) {
        numFiles++;
      });
      return numFiles === expectedNumFiles;
    }

    var interval = setInterval(function() {
      if (countFiles()) {
        clearInterval(interval);
        callback();
      }
    }, 100);
  }
931696
def _incomplete_files(filenames):
  """"""
  tmp_files = [get_incomplete_path(f) for f in filenames]
  try:
    yield tmp_files
    for tmp, output in zip(tmp_files, filenames):
      tf.io.gfile.rename(tmp, output)
  finally:
    for tmp in tmp_files:
      if tf.io.gfile.exists(tmp):
        tf.io.gfile.remove(tmp)
1228530
def cleanup(site, stitch)

      files = stitch.all_files.map{ |f| File.absolute_path(f)}
      files.concat stitch.deleted

      if files.size > 0
        site.static_files.clone.each do |sf|
          if sf.kind_of?(Jekyll::StaticFile) and files.include? sf.path
            site.static_files.delete(sf)
          end
        end
      end
    end
1126193
function _monkeyPatchMainCc(compiler, complete) {
  let finalContents;

  let mainPath = path.join(compiler.dir, 'src', 'node.cc');
  let mainC = fs.readFileSync(mainPath, {
    encoding: 'utf8',
  });

  // content split, and original start/end
  let constant_loc = 1;
  let lines = mainC.split('\n');
  let startLine = lines.indexOf('  // TODO use parse opts');
  let endLine = lines.indexOf('  option_end_index = i;'); // pre node 0.11.6 compat
  let isPatched = lines.indexOf('// NEXE_PATCH_IGNOREFLAGS');

  if (isPatched !== -1) {
    _log('already patched node.cc');
    return complete();
  }

  /**
   * This is the new method of passing the args. Tested on node.js 0.12.5
   * and iojs 2.3.1
   **/
  if (endLine === -1 && startLine === -1) {
    // only if the pre-0.12.5 failed.
    _log('using the after 0.12.5 method of ignoring flags.');

    startLine = lines.indexOf(
      "  while (index < nargs && argv[index][0] == '-') {",
    ); // beginning of the function
    endLine = lines.indexOf('  // Copy remaining arguments.');
    endLine--; // space, then it's at the }

    constant_loc = lines.length + 1;
  } else {
    _log('using 0.10.x > method of ignoring flags');
    lines[endLine] = '  option_end_index = 1;';
  }

  /**
   * This is the method for 5.5.0
   **/
  if (endLine === -1 || startLine === -1) {
    _log('using the after 5.5.0 method of ignoring flags.');

    startLine = lines.indexOf(
      "  while (index < nargs && argv[index][0] == '-' && !short_circuit) {",
    ); // beginning of the function
    endLine = lines.indexOf('  // Copy remaining arguments.');
    endLine--; // space, then it's at the }

    constant_loc = lines.length + 1;
  }

  // other versions here.
  if (endLine === -1 || startLine === -1) {
    // failsafe.
    _log('error', 'Failed to find a way to patch node.cc to ignoreFlags');
    _log('startLine =', startLine, '| endLine =', endLine);
    if (!/^1(1|2)\./.test(compiler.version)) {
      process.exit(1);
    }
  }

  // check if it's been done
  lines[constant_loc] = '// NEXE_PATCH_IGNOREFLAGS';

  for (var i = startLine; i < endLine; i++) {
    lines[i] = undefined; // set the value to undefined so it's skipped by the join
  }

  _log('patched node.cc');

  finalContents = lines.join('\n');

  // write the file contents
  fs.writeFile(
    mainPath,
    finalContents,
    {
      encoding: 'utf8',
    },
    function(err) {
      if (err) {
        _log('error', 'failed to write to', mainPath);
        return process.exit(1);
      }

      return complete();
    },
  );
}
613620
def tmpdir():
    
    target = None
    try:
        with _tmpdir_extant() as target:
            yield target
    finally:
        if target is not None:
            shutil.rmtree(target, ignore_errors=True)
124536
private boolean waitForFileCompleted(AlluxioURI uri) {
    try {
      CommonUtils.waitFor("file completed", () -> {
        try {
          return mFileSystem.getStatus(uri).isCompleted();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }, WaitForOptions.defaults().setTimeoutMs(MAX_OPEN_WAITTIME_MS));
      return true;
    } catch (InterruptedException ie) {
      Thread.currentThread().interrupt();
      return false;
    } catch (TimeoutException te) {
      return false;
    }
  }
848728
def postprocess(self):
        
        # Add suffix to all sub_dir/{items}
        for path in self.neb_dirs:
            for f in VASP_NEB_OUTPUT_SUB_FILES:
                f = os.path.join(path, f)
                if os.path.exists(f):
                    if self.final and self.suffix != "":
                        shutil.move(f, "{}{}".format(f, self.suffix))
                    elif self.suffix != "":
                        shutil.copy(f, "{}{}".format(f, self.suffix))

        # Add suffix to all output files
        for f in VASP_NEB_OUTPUT_FILES + [self.output_file]:
            if os.path.exists(f):
                if self.final and self.suffix != "":
                    shutil.move(f, "{}{}".format(f, self.suffix))
                elif self.suffix != "":
                    shutil.copy(f, "{}{}".format(f, self.suffix))
245479
def tmpdir(self):
        """"""
        if self._tmpdir is None:
            self._tmpdir = tempfile.mkdtemp(prefix="igraph.")
            atexit.register(cleanup_tmpdir, self._tmpdir)
        return self._tmpdir
23018
def make_temp(suffix="", prefix="tmp", dir=None):
    
    temporary = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
    os.close(temporary[0])
    try:
        yield temporary[1]
    finally:
        os.remove(temporary[1])
43776
protected function isSpamAttempt()
    {

        /*
        * loop through all files in the tmp directory and
        * delete garbage files
        */
        $dir = $this->tmp_path;
        $numPrefixChars = strlen($this->file_prefix);
        $files = scandir($dir);
        foreach ($files as $file) {
            if (is_file($dir . DIRECTORY_SEPARATOR . $file)) {
                if (substr($file, 0, $numPrefixChars) == $this->file_prefix) {
                    $lastModified = filemtime($dir . DIRECTORY_SEPARATOR . $file);
                    if ((time() - $lastModified) > 3600) {
                        unlink($dir . DIRECTORY_SEPARATOR . $file);
                    }
                }
            }
        }

        /*
        * end deleting garbage files
        */
        $remoteAddr = $this->ip;
        $userAgent  = $_SERVER['HTTP_USER_AGENT'];
        $filename   = $this->file_prefix . md5($remoteAddr.$userAgent) . '.tmp';
        $file       = $dir . DIRECTORY_SEPARATOR . $filename;

        if (!file_exists($file)) {
            $handle = fopen($file, 'w');
            fwrite($handle, time());
            fclose($handle);

            return false;
        }

        $lastAttack = file_get_contents($file);
        $difference = time() - $lastAttack;
        if ($difference > $this->allowed_rate) {
            unlink($file);
        } else {
            return true;
        }

        return false;
    }
671318
synchronized void checkLeases() {
    int numPathsChecked = 0;
    for(; sortedLeases.size() > 0; ) {
      final Lease oldest = sortedLeases.first();
      if (!oldest.expiredHardLimit()) {
        return;
      }
      
      // internalReleaseLease() removes paths corresponding to empty files,
      // i.e. it needs to modify the collection being iterated over
      // causing ConcurrentModificationException
      String[] leasePaths = new String[oldest.getPaths().size()];
      oldest.getPaths().toArray(leasePaths);
      LOG.info("Lease " + oldest
          + " has expired hard limit. Recovering lease for paths: "
          + Arrays.toString(leasePaths));
      for(String p : leasePaths) {
        if (++numPathsChecked > this.maxPathsPerCheck) {
          return;
        }
        try {
          fsnamesystem.getFSNamesystemMetrics().numLeaseRecoveries.inc();
          fsnamesystem.internalReleaseLeaseOne(
              oldest, p, this.discardLastBlockIfNoSync);
        } catch (IOException e) {
          LOG.error("Cannot release the path "+p+" in the lease "+oldest, e);
          removeLease(oldest, p);
          fsnamesystem.getFSNamesystemMetrics().numLeaseManagerMonitorExceptions.inc();
        }
      }
    }
  }
377471
def _wait_for_files(path):
    
    timeout = 0.001
    remaining = []
    while timeout < 1.0:
        remaining = []
        if os.path.isdir(path):
            L = os.listdir(path)
            for target in L:
                _remaining = _wait_for_files(target)
                if _remaining:
                    remaining.extend(_remaining)
            continue
        try:
            os.unlink(path)
        except FileNotFoundError as e:
            if e.errno == errno.ENOENT:
                return
        except (OSError, IOError, PermissionError):
            time.sleep(timeout)
            timeout *= 2
            remaining.append(path)
        else:
            return
    return remaining
1062193
def delayed_bamprep_merge(samples, run_parallel):
    
    if any("combine" in data[0] for data in samples):
        return run_parallel("delayed_bam_merge", samples)
    else:
        return samples
882243
def retry_mkstemp(suffix='', prefix='tmp', directory=None, max_retries=3):
    
    if directory is None:
        directory = current_app.config['CFG_TMPSHAREDDIR']
    for retry_count in range(1, max_retries + 1):
        try:
            tmp_file_fd, tmp_file_name = tempfile.mkstemp(suffix=suffix,
                                                          prefix=prefix,
                                                          dir=directory)
        except OSError as e:
            if e.errno == 19 and retry_count <= max_retries:
                # AFS Glitch?
                time.sleep(10)
            else:
                raise
        else:
            break
    return tmp_file_fd, tmp_file_name
1181315
def _recursive_overwrite(self, src, dest):
        
        if os.path.isdir(src):
            if not os.path.isdir(dest):
                os.makedirs(dest)
            files = os.listdir(src)
            for f in files:
                self._recursive_overwrite(os.path.join(src, f),
                                          os.path.join(dest, f))
        else:
            shutil.copyfile(src, dest, follow_symlinks=False)
591660
function rmdirSyncRecursive(root, chunks) {

  var chunk = chunks.pop();
  if (!chunk) {
    return;
  }
  var pathname = path.join(root, '..'); // backtrack

  if (fs.existsSync(root) === false) { // already done
    return rmdirSyncRecursive(root, chunks);
  }
  var err = fs.rmdirSync(root);
  return err ? err : rmdirSyncRecursive(pathname, chunks); // let's magic
}
595189
def _pre_dump(cls):
        """"""
        shutil.rmtree(cls.outdir, ignore_errors=True)
        os.makedirs(cls.outdir)
        super(PlotMetric, cls)._pre_dump()