/*
Add the files to the backup file
512385
public String getBackupFilename(String strFilenameTemplate)
    {
        Date now = new Date();
        String strDate = this.dateToString(now);
        for (int i = 0; i < strDate.length(); i++)
        {
            char ch = strDate.charAt(i);
            if (!Character.isLetterOrDigit(ch))
                strDate = strDate.substring(0, i) + '_' + strDate.substring(i + 1, strDate.length());
        }
        return MessageFormat.format(strFilenameTemplate, strDate);
    }
645618
def add(self):
        
        log = getLogger('ocrd.workspace_backup.add')
        mets_str = self.workspace.mets.to_xml()
        chksum = _chksum(mets_str)
        backups = self.list()
        if backups and backups[0].chksum == chksum:
            log.info('No changes since last backup: %s' % backups[0])
        else:
            timestamp = datetime.now().timestamp()
            d = join(self.backup_directory, '%s.%s' % (chksum, timestamp))
            mets_file = join(d, 'mets.xml')
            log.info("Backing up to %s" % mets_file)
            makedirs(d)
            with open(mets_file, 'wb') as f:
                f.write(mets_str)
        return chksum
1128024
def makeBackupFile(self, dstPath, fileName):
        

        with open(os.devnull) as devnull:
            SP.call(['mongodump', '--db', self.dbName, '--out', dstPath],
                    stdout=devnull,
                    stderr=devnull)
            SP.call(['zip',
                     '-r',
                     os.path.join(dstPath, fileName),
                     os.path.join(dstPath, self.dbName)],
                    stdout=devnull,
                    stderr=devnull)

        SP.call(['rm', '-rf', os.path.join(dstPath, self.dbName)])
78970
function createBackupFile(sourceUrl, backupTmpFilePath) {
  return new Promise((resolve, reject) => {
    couchbackup.backup(
      sourceUrl,
      fs.createWriteStream(backupTmpFilePath),
      (err) => {
        if (err) {
          return reject(new VError(err, 'CouchBackup process failed'));
        }
        debug('couchbackup to file done; uploading to S3');
        resolve('creating backup file complete');
      }
    );
  });
}
173819
def prepend_to_file(path, data, bufsize=1<<15):
    
    # Backup the file #
    backupname = path + os.extsep + 'bak'
    # Remove previous backup if it exists #
    try: os.unlink(backupname)
    except OSError: pass
    os.rename(path, backupname)
    # Open input/output files,  note: outputfile's permissions lost #
    with open(backupname) as inputfile:
        with open(path, 'w') as outputfile:
            outputfile.write(data)
            buf = inputfile.read(bufsize)
            while buf:
                outputfile.write(buf)
                buf = inputfile.read(bufsize)
    # Remove backup on success #
    os.remove(backupname)
302494
function addAllFilesAndSubdirectories(dir, doneCallback) {
            FileSystem.resolve(dir, function (err, directory) {
                function visitor(entry) {
                    if (entry.isFile) {
                        if (!isFileExcluded(entry)) { // ignore .dotfiles and non-.js files
                            addFilesToTern([entry.fullPath]);
                        }
                    } else {
                        return !isDirectoryExcluded(entry.fullPath) &&
                            entry.name.indexOf(".") !== 0 &&
                            !stopAddingFiles;
                    }
                }

                if (err) {
                    return;
                }

                if (dir === FileSystem.getDirectoryForPath(rootTernDir)) {
                    doneCallback();
                    return;
                }

                directory.visit(visitor, doneCallback);
            });
        }
1054073
function copyFiles(srcfile, dstfile, callback) {
        var fs = require("fs");
        var rs = fs.createReadStream(srcfile);
        var ws = fs.createWriteStream(dstfile);
        rs.on("data", function(d) {
            ws.write(d);
        });
        rs.on("end", function() {
            ws.end();
            callback(true);
        });
    }
861760
function( files, options, callback ) {
	if ( !Array.isArray( files ) ) {
		files = [files];
	}
	if ( typeof options === 'function' ) {
		callback = options;
		options = null;
	} else if ( typeof options === 'string' ) {
		options = { msg: options };
	}
	options = options || {};
	addExtraOptions( [ 'quiet', 'depth', 'msg' ], options );
	executeSvn( [ 'commit' ].concat( files ), options, callback );
}
162790
def add_files(session, imagedir, verbose):
  """"""

  def add_file(session, basename, userid, shotid, sessionid):
    """Parse a single filename and add it to the list."""
    session.add(File(userid, basename, sessionid, shotid))

  filenames = os.listdir(imagedir)
  for filename in filenames:
    basename, extension = os.path.splitext(filename)
    if extension == db_file_extension:
      if verbose>1: print("  Adding file '%s'..." % (basename))
      parts = string.split(basename, "_")
      ctype = parts[0]
      shotid = int(parts[2])
      userid = ctype + '_%d' % int(parts[1])
      if parts[0] == "Impostor":
        sessionid = 3
      elif parts[0] == "Genuine" and shotid <= 6:
        sessionid = 1
      elif parts[0] == "Genuine" and shotid > 6:
        sessionid = 2
        shotid = shotid - 6
      add_file(session, basename, userid, shotid, sessionid)
454608
public void putFiles(String local, FileTransferProgress progress,
			boolean resume) throws FileNotFoundException, SftpStatusException,
			SshException, TransferCancelledException {
		putFiles(local, pwd(), progress, resume);
	}
623724
function addFileResource(cmd, file, params, callback) {
    if( !file ) return callback({error:true,message:"no file provided"});
    if( !fs.existsSync(file) ) return callback({error:true,message:"no file found: "+file});
    if( !fs.statSync(file).isFile() ) return callback({error:true,message:"not a file: "+file});
    if( !params ) return callback({error:true,message:"no resource parameters provided"});
    if( !params.package_id ) return callback({error:true,message:"no package_id provided"});

    // clean up filename
    var name = getCkanFilename(file);
    var folder = new Date().toISOString()+'/'+name;
    
    // set default / known parameters
    params.url = server+"/storage/f/"+encodeURIComponent(folder);
    if( !params.name ) params.name = file.replace(/.*\//,'');
    params.size = fs.statSync(file).size;
    params.resource_type = "file.upload";
    
    exports.exec(cmd, params, function(err, pkg){
        if( err ) return callback(err);
        
        rest.post(server + '/storage/upload_handle', {
            multipart: true,
            headers : {
                Authorization : key
            },
            data: {
              key: folder,
              file: rest.file(file, null, fs.statSync(file).size, null, params.mimetype)
            }
        }).on('complete', function(data) {
            // HACK: redirects seem to fire complete twice.  this is bad
            if( !callback ) return;
            
            if (data instanceof Error) {
                callback(data);
            } else {
                callback(null, data);
            }
            callback = null;
        });
    });

}
978392
public void addFileSet(FileSet fs) {
    add(fs);
    if (fs.getProject() == null) {
      fs.setProject(getProject());
    }
  }
724767
protected function addResourceFiles()
    {
        foreach ($this->data as $service => $resources) {
            foreach ($resources as $resourceName => $records) {
                $this->package->zipResourceFile($service . '/' . $resourceName . '.json', $records);
            }
        }
    }
1199114
function addFiles (formData, files) {
    var file, arr, key, i = 0, filename;

    for (key in files) {
        if (files.hasOwnProperty(key) && files[key]) {

            if (files[key] instanceof Array) {
                arr = files[key];
                filename = getFilename(arr[i]) || null;

                for (i = 0; i < arr.length; i += 1) {
                    formData.append(key + '[' + i + ']', arr[i]);
                }
            } else {
                file = files[key];
                filename = getFilename(file) || null;
                formData.append(key, file, filename);
            }
        }
    }
}
1160676
function _append($data)
    {
        if ($this->_using_tmpfile) {
            // Add CONTINUE records if necessary
            if (strlen($data) > $this->_limit) {
                $data = $this->_addContinue($data);
            }
            fwrite($this->_filehandle, $data);
            $this->_datasize += strlen($data);
        } else {
            parent::_append($data);
        }
    }
22007
public function backupAction()
    {
        $filter = $this->getSearchFilter();
        $model = $this->getModel();

        $tables = $model->load();
        $allTables = [];
        $noDataTables = [];
        foreach($tables as $table) {
            if ($table['type'] == 'view' && (!array_key_exists('include_views', $filter) || $filter['include_views'] != '1')) {
                continue;
            }
            $allTables[] = $table['name'];
            if ($table['respondentData'] === true && (!array_key_exists('include_respondent_data', $filter) || $filter['include_respondent_data'] != '1')) {
                $noDataTables[] = $table['name'];
            }
        }

        $filename = $this->getBackupFilename($filter);
        $dbConfig = $this->getDatabaseConfig();
        $dumpSettings = [
            'include-tables' => $allTables,
            'no-data' => $noDataTables,
            'single-transaction' => true,
            'lock-tables' => false,
            'add-locks' => false,
            'add-drop-table' => true,
        ];

        ini_set('max_execution_time', 300);

        try {
            $dump = new \Ifsnop\Mysqldump\Mysqldump($dbConfig['dsn'], $dbConfig['username'], $dbConfig['password'], $dumpSettings);
            $dump->start($filename);
            echo sprintf($this->_('Database backup completed. File can be found in %s'), $filename);
        } catch (\Exception $e) {
            echo 'mysqldump-php error: ' . $e->getMessage();
        }
    }
704279
def append_file_data(_dir, data)
      File.open(to_path, 'ab') { |file| file.write(data) }
    end