Copy remote file to local hardrive
@param  {string}   url  url of the remote file
@param  {string}   dest destination where to copy file
@param  {Function} cb   callback when file is copied
@return {void}
771898
function(url, dest, cb) {
      var get = request(url);
      get.on('response',  function (res) {
        res.pipe(fs.createWriteStream(dest));
        res.on('end', function () {
          cb();
        });
        res.on('error', function (err) {
          cb(err);
        });
      });
    }
1357077
public static boolean copyFile(final File src, final File dest)
    throws FileNotFoundException, IOException {
        return copyFile(src, dest, -1, true);
    }
156312
function copyMedia (path, to, cert, callback) {
  var hookPath = __dirname + '/../data/buffer/hook.sh'
  debug('copyMedia', path, to, cert)

  if (/^http/.test(to)) {
    debug('using http')
    var parsed = url.parse(to)
    debug('parsed', parsed)

    var domain = url.parse(to).domain
    var file = url.parse(to).path
    debug(domain, file)

    var a = parsed.pathname.split('/')
    var uri = parsed.protocol + '//' + parsed.host
    for (var i = 0; i < a.length - 1; i++) {
      uri += a[i] + '/'
    }
    uri += urlencode(a[i])
    debug('uri', uri)

    // uri = 'https://phone.servehttp.com:8000/data/buffer/image/'  + urlencode('file%3A%2F%2F%2Fmedia%2Fmelvin%2FElements%2Fpichunter.com%2F2443342_15_o.jpg')

    var options = {
      method: 'PUT',
      url: uri,
      key: fs.readFileSync(cert),
      cert: fs.readFileSync(cert),
      headers: { // We can define headers too
        'Content-Type': 'image/jpg'
      }
    }

    debug(options)
    fs.createReadStream(path).pipe(request.put(options, function (err, response, body) {
      if (err) {
        debug(err)
        callback(err)
      } else {
        debug('success')
        callback(null)
        setTimeout(function () {
          exec(hookPath)
        }, 0)
      }
    }))
  } else {
    fs.copy(path, to, function (err) {
      if (err) {
        callback(err)
      } else {
        callback(null, null)
        setTimeout(function () {
          exec(hookPath)
        }, 0)
      }
    })
  }
}
1285346
function move(src, dest) {
	return rename(src, dest).catch((err) => {
		// try copying
		return copy(src, dest).then(() => {
			// delete source
			return unlink(src);
		});
	});
}
1277775
public static Object copy(Object src, Object dest, int length) {
		System.arraycopy(src, 0, dest, 0, length);
		return dest;
	}
263552
function(app, dest, from) {

    // Assess our situation
    var localPath = from || app.task.pkg.dir;
    var needsDownload = (app.task.pkg.url && !localPath) ? true : false;
    log.debug(format('App requires download: %s', needsDownload));

    // Start the chain
    return Promise.try(function() {

      // If this is a remote package then download it and
      // return the directory
      if (needsDownload) {
        return kbox.util.download.downloadFiles([app.task.pkg.url], dest);
      }

      // Otherwise just copy from --from
      else {

        return Promise.fromNode(function(cb) {

          // Make sure we overwrite
          var options = {clobber: true};

          // Do the copying
          fs.copy(localPath, dest, options, cb);
          log.debug(format('Copied %s to %s', localPath, dest));

        });

      }

    });

  }
293337
function copyFile(srcPath, destPath) {
        let srcFileInfo = path.parse(srcPath) || {};
        if (!path.extname(destPath) && srcFileInfo.ext) {
            // destination is a directory!
            return copyFileIntoDirectory(srcPath, destPath);
        } else {
            return new Promise(function (resolve, reject) {
                fs.copy(srcPath, destPath, function (err) {
                    if (!err) {
                        resolve();
                    } else {
                        reject(err);
                    }
                });
            });
        }
    }
57933
function copyFile(source, target) {
    var deferred,
        rd,
        wr;

    if (typeof fs.copyFile === 'function') {
        return Q.ninvoke(fs, 'copyFile', source, target);
    }

    deferred = Q.defer();

    rd = fs.createReadStream(source);
    wr = fs.createWriteStream(target);

    rd.on('error', function (err) {
        deferred.reject(err);
    });

    wr.on('error', function (err) {
        deferred.reject(err);
    });
    wr.on('close', function () {
        deferred.resolve();
    });

    rd.pipe(wr);

    return deferred.promise;
}
747965
function _copyFileSync(src, dest, flag) {
    const SIZE = 65536;

    const COPYFILE_EXCL = 1;
    const COPYFILE_FICLONE = 2;
    const COPYFILE_FICLONE_FORCE = 4;

    const constants = {
        COPYFILE_EXCL,
        COPYFILE_FICLONE,
        COPYFILE_FICLONE_FORCE,
    };

    const isNumber = (a) => typeof a === 'number';
    const or = (a, b) => a | b;
    const getValue = (obj) => (key) => obj[key];

    const getMaxMask = (obj) => Object
          .keys(obj)
          .map(getValue(obj))
          .reduce(or);

    const MAX_MASK = getMaxMask(constants);
    const isExcl = (flags) => flags & COPYFILE_EXCL;


    const writeFlag = isExcl(flag) ? 'wx' : 'w';

    const {
        size,
        mode,
    } = fs.statSync(src);

    const fdSrc = fs.openSync(src, 'r');
    const fdDest = fs.openSync(dest, writeFlag, mode);

    const length = size < SIZE ? size : SIZE;

    let pos = 0;
    const peaceSize = size < SIZE ? 0 : size % SIZE;
    const offset = 0;

    let buffer = Buffer.allocUnsafe(length);
    for (let i = 0; length + pos + peaceSize <= size; i++, pos = length * i) {
        fs.readSync(fdSrc, buffer, offset, length, pos);
        fs.writeSync(fdDest, buffer, offset, length, pos);
    }

    if (peaceSize) {
        const length = peaceSize;
        buffer = Buffer.allocUnsafe(length);
        fs.readSync(fdSrc, buffer, offset, length, pos);
        fs.writeSync(fdDest, buffer, offset, length, pos);
    }

    fs.closeSync(fdSrc);
    fs.closeSync(fdDest);
}
119551
def copyfile(source, dest, backup_mode='', cachedir=''):
    '''
    
    '''
    if not os.path.isfile(source):
        raise IOError(
            '[Errno 2] No such file or directory: {0}'.format(source)
        )
    if not os.path.isdir(os.path.dirname(dest)):
        raise IOError(
            '[Errno 2] No such file or directory: {0}'.format(dest)
        )
    bname = os.path.basename(dest)
    dname = os.path.dirname(os.path.abspath(dest))
    tgt = mkstemp(prefix=bname, dir=dname)
    shutil.copyfile(source, tgt)
    bkroot = ''
    if cachedir:
        bkroot = os.path.join(cachedir, 'file_backup')
    if backup_mode == 'minion' or backup_mode == 'both' and bkroot:
        if os.path.exists(dest):
            backup_minion(dest, bkroot)
    if backup_mode == 'master' or backup_mode == 'both' and bkroot:
        # TODO, backup to master
        pass
    # Get current file stats to they can be replicated after the new file is
    # moved to the destination path.
    fstat = None
    if not salt.utils.platform.is_windows():
        try:
            fstat = os.stat(dest)
        except OSError:
            pass

    # The move could fail if the dest has xattr protections, so delete the
    # temp file in this case
    try:
        shutil.move(tgt, dest)
    except Exception:
        __clean_tmp(tgt)
        raise

    if fstat is not None:
        os.chown(dest, fstat.st_uid, fstat.st_gid)
        os.chmod(dest, fstat.st_mode)
    # If SELINUX is available run a restorecon on the file
    rcon = salt.utils.path.which('restorecon')
    if rcon:
        policy = False
        try:
            policy = salt.modules.selinux.getenforce()
        except (ImportError, CommandExecutionError):
            pass
        if policy == 'Enforcing':
            with fopen(os.devnull, 'w') as dev_null:
                cmd = [rcon, dest]
                subprocess.call(cmd, stdout=dev_null, stderr=dev_null)
    if os.path.isfile(tgt):
        # The temp file failed to move
        __clean_tmp(tgt)
1079155
function(src, dest) {
    var contents,
        srcExists = fs.existsSync(src),
        destExists = fs.existsSync(dest),
        stats = srcExists && fs.statSync(src),
        isDirectory = srcExists && stats.isDirectory();

    if (srcExists) {
        if (isDirectory) {
            if (!destExists) {
                fs.mkdirSync(dest);
            }
            fs.readdirSync(src).forEach(function(childItemName) {
                copyRecursiveSync(path.join(src, childItemName),
                    path.join(dest, childItemName));
            });
        } else {
            contents = fs.readFileSync(src);
            fs.writeFileSync(dest, contents);
        }
    }
}
189336
public void copy(Node dest) throws NodeNotFoundException, CopyException {
        try {
            if (isDirectory()) {
                dest.mkdirOpt();
                copyDirectory(dest);
            } else {
                copyFile(dest);
            }
        } catch (FileNotFoundException | CopyException e) {
            throw e;
        } catch (IOException e) {
            throw new CopyException(this, dest, e);
        }
    }
400054
def copy_from_local(self, localsrc, dest, **kwargs):
        
        with io.open(localsrc, 'rb') as f:
            self.create(dest, f, **kwargs)
886788
function copyDirSync(src, dest) {
  if (fs.lstatSync(src).isDirectory()) {
    const files = fs.readdirSync(src);
    files.forEach((file) => {
      const curSource = path.join(src, file);
      const curDest = path.join(dest, file);
      if (fs.lstatSync(curSource).isDirectory()) {
        if (!fs.existsSync(curDest)) {
          createDir(curDest);
        }
        copyDirSync(curSource, curDest);
      } else {
        copyFileSync(curSource, curDest);
      }
    });
  }
}
389075
@Deprecated
  public void copyToLocalFile(Path src, Path dst) throws IOException {
    copyToLocalFile(false, false, src, dst);
  }
831119
function copyDoc (docSrc, docDest, opts0, callback0) {
      const { opts, callback } = getCallback(opts0, callback0)

      const qs = {
        db: dbName,
        doc: docSrc,
        method: 'COPY',
        headers: { 'Destination': docDest }
      }

      if (opts.overwrite) {
        const p = headDoc(docDest).then(
          function (h) {
            if (h.etag) {
              qs.headers.Destination += '?rev=' +
                h.etag.substring(1, h.etag.length - 1)
            }
            relax(qs, callback)
          },
          function (e) {
            if (e && e.statusCode !== 404) {
              if (callback) {
                callback(e)
              } else {
                return Promise.reject(e)
              }
            } else {
              relax(qs, callback)
            }
          }
        )
        if (!callback) {
          return p
        }
      } else {
        return relax(qs, callback)
      }
    }
212194
function download(uri, dest, progressCallback) {
    "use strict";
    progressCallback = progressCallback || function() {};
    var parsedUrl = url.parse(uri, false, true);
    var makeRequest = parsedUrl.protocol === 'https:' ? https.request.bind(https) : http.request.bind(http);
    var serverPort = parsedUrl.port ? parsedUrl.port : parsedUrl.protocol === 'https:' ? 443 : 80;
    var agent = parsedUrl.protocol === 'https:' ? httpsAgent : httpAgent;
    var file = fs.createWriteStream(dest);

    var options = {
        host: parsedUrl.host,
        path: parsedUrl.path,
        agent: agent,
        port: serverPort,
        method: 'GET'
    };

    return new Promise(function (resolve, reject) {

        var req = makeRequest(options, function (response) {
            var size = response.headers['content-length'];
            var progress = 0;

            response.on('data', function(chunk) {
                progress += chunk.length;
                progressCallback(size, progress);
            });

            response.pipe(file);
            file.on('finish', function() {
                resolve({
                    status: response.statusCode
                });
            });
        });

        req.on('error', function(error) {
            file.end();
            rimraf.sync(dest);
            reject(error);
        });

        req.end();
    });
}