Restore one 1-activity backup
554039
static protected function build_activity_plan($controller, $activityid) {

        $plan = $controller->get_plan();
        $info = $controller->get_info();
        $infoactivity = $info->activities[$activityid];

        // Add the activity task, responsible for restoring
        // all the module related information. So it conditionally
        // as far as the module can be missing on restore
        if ($task = restore_factory::get_restore_activity_task($infoactivity)) { // can be missing
            $plan->add_task($task);
            $controller->get_progress()->progress();

            // For the given activity path, add as many block tasks as necessary
            // TODO: Add blocks, we need to introspect xml here
            $blocks = backup_general_helper::get_blocks_from_path($task->get_taskbasepath());
            foreach ($blocks as $basepath => $name) {
                if ($task = restore_factory::get_restore_block_task($name, $basepath)) {
                    $plan->add_task($task);
                    $controller->get_progress()->progress();
                } else {
                    // TODO: Debug information about block not supported
                }
            }
        } else { // Activity is missing in target site, inform plan about that
            $plan->set_missing_modules();
        }

    }
212129
private void restoreBackupIncremental() {

        try {
            if (fa.isStreamElement(fileName + ".backup")) {
                RAShadowFile.restoreFile(fileName + ".backup",
                                         fileName + ".data");
            } else {
/*
                // this is to ensure file has been written fully but it is not necessary
                // as semantics dictate that if a backup does not exist, the file
                // was never changed or was fully written to
                if (FileUtil.exists(cacheFileName)) {
                    int flags = DataFileCache.getFlags(cacheFileName);

                    if (!BitMap.isSet(flags, DataFileCache.FLAG_ISSAVED)) {
                        FileUtil.delete(cacheFileName);
                    }
                }
*/
            }

            deleteBackup();
        } catch (IOException e) {
            throw Error.error(ErrorCode.FILE_IO_ERROR, fileName + ".backup");
        }
    }
44541
def restore_session(self):
        

        session = [foundations.strings.to_string(path)
                   for path in self.__settings.get_key(self.__settings_section, "session").toStringList()
                   if foundations.common.path_exists(path)]

        LOGGER.debug("> Restoring session :'{0}'.".format(session))
        success = True
        for path in session:
            if os.path.isfile(path):
                success *= self.load_file(path)
            else:
                success *= self.add_project(path)
        return success
1331326
private function restoreBackup()
    {
        $hash       = $this->getHash();
        $connection = $this->entityManager->getConnection();

        $this->backupService->restoreBackup($connection, $hash);
    }
715748
def restore_from_disk(self, clean_old_snapshot=False):
        
        base_filename = "%s/%s_%s_*.dat" % (self.snapshot_path, self.name, self.expiration)
        availables_snapshots = glob.glob(base_filename)
        last_period = self.current_period - dt.timedelta(days=self.expiration-1)
        for filename in availables_snapshots:
            snapshot_period = dt.datetime.strptime(filename.split('_')[-1].strip('.dat'), "%Y-%m-%d")
            if snapshot_period <  last_period and not clean_old_snapshot:
                continue
            else:
                self._union_bf_from_file(filename)
                if snapshot_period == self.current_period:
                    self._union_bf_from_file(filename, current=True)

            if snapshot_period < last_period and clean_old_snapshot:
                os.remove(filename)
        self.ready = True
1182608
protected function restoreUserSessionBackup()
    {
        if ($this->userSessionBackup === null) {
            unset($_SESSION[self::SESSION_PARAMETER_CLOUDCONTROL]);
        } else {
            $_SESSION[self::SESSION_PARAMETER_CLOUDCONTROL] = $this->userSessionBackup;
        }
    }
1129658
def restore_state(self):
        """"""
        last_path = setting('directory', '', expected_type=str)
        self.output_directory.setText(last_path)
1284198
private function restore()
    {
        $this->deleteDirectory('app');
        $this->deleteDirectory('bootstrap');
        $this->deleteDirectory('routes');

        $this->info('Copying back App');
        File::copyDirectory($this->backupDirectory . '/app', 'app');
        $this->info('Copying back bootstrap');
        File::copyDirectory($this->backupDirectory . '/bootstrap', 'bootstrap');
        $this->info('Copying back routes');
        File::copyDirectory($this->backupDirectory . '/routes', 'routes');

        File::copy($this->backupDirectory . '/composer.json', 'composer.json');
        File::copy($this->backupDirectory . '/config/auth.php', 'config/auth.php');
        File::copy($this->backupDirectory . '/config/database.php', 'config/database.php');

        $this->info('Backup successful');
    }
667439
def restore_state(self):
        """"""
        # restore last source path
        last_source_path = setting(
            'lastSourceDir', self.default_directory, expected_type=str)
        self.source_directory.setText(last_source_path)

        # restore path pdf output
        last_output_dir = setting(
            'lastOutputDir', self.default_directory, expected_type=str)
        self.output_directory.setText(last_output_dir)

        # restore default output dir combo box
        use_default_output_dir = bool(setting(
            'useDefaultOutputDir', True, expected_type=bool))
        self.scenario_directory_radio.setChecked(
            use_default_output_dir)
778618
public function after_restore() {
        global $DB;

        // Get the blockid.
        $blockid = $this->get_blockid();

        // Extract block configdata and update it to point to the new quiz.
        $configdata = $DB->get_field('block_instances', 'configdata', array('id' => $blockid));
        $newconfigdata = '';

        // The block was configured.
        if (!empty($configdata)) {

            $config = unserialize(base64_decode($configdata));
            $config->activityparent = 'quiz';
            $config->activityparentid = 0;
            $config->gradeformat = isset($config->gradeformat) ? $config->gradeformat : 1;

            if (!empty($config->quizid)
                    && $quizmap = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'quiz', $config->quizid)) {
                $config->activityparentid = $quizmap->newitemid;
            }

            // Set the decimal valuue as appropriate.
            if ($config->gradeformat == 1) {
                // This block is using percentages, do not display any decimal places.
                $config->decimalpoints = 0;
            } else {
                // Get the decimal value from the corresponding quiz.
                $config->decimalpoints = $DB->get_field('quiz', 'decimalpoints', array('id' => $config->activityparentid));
            }

            // Get the grade_items record to set the activitygradeitemid.
            $info = $DB->get_record('grade_items',
                    array('iteminstance' => $config->activityparentid, 'itemmodule' => $config->activityparent));
            $config->activitygradeitemid = 0;
            if ($info) {
                $config->activitygradeitemid = $info->id;
            }

            unset($config->quizid);
            $newconfigdata = base64_encode(serialize($config));
        }

        // Update the configuration and convert the block.
        $DB->set_field('block_instances', 'configdata', $newconfigdata, array('id' => $blockid));
        $DB->set_field('block_instances', 'blockname', 'activity_results', array('id' => $blockid));
    }
1284132
def restore(self):
        """"""
        if not self._snapshot:
            return
        yield from self.set_muted(self._snapshot['muted'])
        yield from self.set_volume(self._snapshot['volume'])
        yield from self.set_stream(self._snapshot['stream'])
        self.callback()
        _LOGGER.info('restored snapshot of state of %s', self.friendly_name)
964665
def restore(self, chksum, choose_first=False):
        
        log = getLogger('ocrd.workspace_backup.restore')
        bak = None
        candidates = glob(join(self.backup_directory, '%s*' % chksum))
        if not candidates:
            log.error("No backup found: %s" % chksum)
            return
        if len(candidates) > 1 and not choose_first:
            raise Exception("Not unique, could be\n%s" % '\n'.join(candidates))
        bak = candidates[0]
        self.add()
        log.info("Restoring from %s/mets.xml" % bak)
        src = join(bak, 'mets.xml')
        dest = self.workspace.mets_target
        log.debug('cp "%s" "%s"', src, dest)
        copy(src, dest)
        self.workspace.reload_mets()
707
protected static function restoreFromSession()
    {
        $session = Http\Session::getInstance();

        try {
            $mapper = new UserMapper(Database::get());
            $user   = $mapper->findFromSession($session);
        } catch (\Exception $exception) {
            $user = new Data\User\User();
        }

        static::$user = $user;
    }
634977
def restore(path, password_file=None):
    
    vault = VaultLib(get_vault_password(password_file))
    atk_path = os.path.join(ATK_VAULT, path)

    # Load stored data
    with open(os.path.join(atk_path, 'encrypted'), 'rb') as f:
        old_data = f.read()
    with open(os.path.join(atk_path, 'hash'), 'rb') as f:
        old_hash = f.read()

    # Load new data
    with open(path, 'rb') as f:
        new_data = f.read()
        new_hash = hashlib.sha1(new_data).hexdigest()

    # Determine whether to re-encrypt
    if old_hash != new_hash:
        new_data = vault.encrypt(new_data)
    else:
        new_data = old_data

    # Update file
    with open(path, 'wb') as f:
        f.write(new_data)

    # Clean atk vault
    os.remove(os.path.join(atk_path, 'encrypted'))
    os.remove(os.path.join(atk_path, 'hash'))
1336728
function restore() {
    if (isOriginal) return;
    else isOriginal = true;
    ['log', 'debug', 'info', 'warn', 'error'].forEach((item) => {
        console[item] = originalConsoleFunctions[item];
    });
}
498069
def restore(self, trial, checkpoint=None):
        
        if checkpoint is None or checkpoint.value is None:
            checkpoint = trial._checkpoint
        if checkpoint is None or checkpoint.value is None:
            return True
        if trial.runner is None:
            logger.error("Unable to restore - no runner.")
            self.set_status(trial, Trial.ERROR)
            return False
        try:
            value = checkpoint.value
            if checkpoint.storage == Checkpoint.MEMORY:
                assert type(value) != Checkpoint, type(value)
                trial.runner.restore_from_object.remote(value)
            else:
                worker_ip = ray.get(trial.runner.current_ip.remote())
                trial.sync_logger_to_new_location(worker_ip)
                with warn_if_slow("restore_from_disk"):
                    ray.get(trial.runner.restore.remote(value))
            trial.last_result = checkpoint.last_result
            return True
        except Exception:
            logger.exception("Error restoring runner for Trial %s.", trial)
            self.set_status(trial, Trial.ERROR)
            return False
975180
@Override
    @Transactional
    public Restoration restartRestore(String restoreId) throws SnapshotException {
        Restoration restoration = this.jobManager.stopRestore(restoreId);
        restoration.setEndDate(null);
        restoration.setStatus(RestoreStatus.RETRIEVING_FROM_STORAGE);
        restoration = restoreRepo.save(restoration);
        eventLog.logRestoreUpdate(restoration);
        return this.restoreCompleted(restoration);
    }