Runs finalize phase; run after all builds are complete and all modules
	have been stopped.
976509
def do_finalize():
	
	def _finalize(shutit):
		# Stop all the modules
		shutit.stop_all()
		# Finalize in reverse order
		shutit.log('PHASE: finalizing object ' + str(shutit), level=logging.DEBUG)
		# Login at least once to get the exports.
		for module_id in shutit.module_ids(rev=True):
			# Only finalize if it's thought to be installed.
			if shutit.is_installed(shutit.shutit_map[module_id]):
				shutit.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False)
				if not shutit.shutit_map[module_id].finalize(shutit):
					shutit.fail(module_id + ' failed on finalize', shutit_pexpect_child=shutit.get_shutit_pexpect_session_from_id('target_child').pexpect_child) # pragma: no cover
				shutit.logout(echo=False)
		for fshutit in shutit_global.shutit_global_object.shutit_objects:
			_finalize(fshutit)
979445
def after_processing(eng, objects):
        """"""
        super(InvenioProcessingFactory, InvenioProcessingFactory)\
            .after_processing(eng, objects)
        if eng.has_completed:
            eng.save(WorkflowStatus.COMPLETED)
        else:
            eng.save(WorkflowStatus.HALTED)
        db.session.commit()
186507
private void finish() {
        try {
            GlobalEnablementBuilder globalEnablementBuilder = getBeanManager().getServices().get(GlobalEnablementBuilder.class);
            for (BeanRegistration registration : additionalBeans) {
                processBeanRegistration(registration, globalEnablementBuilder);
            }
            for (ObserverRegistration registration : additionalObservers) {
                processObserverRegistration(registration);
            }
        } catch (Exception e) {
            throw new DefinitionException(e);
        }
    }
1296062
def finish(self):
        
        self.repo.git.checkout(self.current_branch)
        self.repo.close()
1010829
def finalize_target(self):
		
		shutit_global.shutit_global_object.yield_to_draw()
		self.pause_point('\nFinalizing the target module (' + self.shutit_main_dir + '/shutit_setup.py)', print_input=False, level=3)
		# Can assume conn_module exists at this point
		for mod in self.conn_modules:
			if mod.module_id == self.build['conn_module']:
				conn_module = mod
				break
		conn_module.finalize(self)
445893
public void finishOpenedActivities(){
		// Stops the activityStack listener
		activitySyncTimer.cancel();
		if(!config.trackActivities){
			useGoBack(3);
			return;
		}
		ArrayList<Activity> activitiesOpened = getAllOpenedActivities();
		// Finish all opened activities
		for (int i = activitiesOpened.size()-1; i >= 0; i--) {
			sleeper.sleep(MINISLEEP);
			finishActivity(activitiesOpened.get(i));
		}
		activitiesOpened = null;
		sleeper.sleep(MINISLEEP);
		// Finish the initial activity, pressing Back for good measure
		finishActivity(getCurrentActivity(true, false));
		stopActivityMonitor();
		setRegisterActivities(false);
		this.activity = null;
		sleeper.sleepMini();
		useGoBack(1);
		clearActivityStack();
	}
1115275
def buildFinished(self, build, wfb):
        """"""

        # by the time we get here, the Build has already released the worker,
        # which will trigger a check for any now-possible build requests
        # (maybeStartBuilds)

        results = build.build_status.getResults()

        self.building.remove(build)
        if results == RETRY:
            d = self._resubmit_buildreqs(build)
            d.addErrback(log.err, 'while resubmitting a build request')
        else:
            complete_at_epoch = self.master.reactor.seconds()
            complete_at = epoch2datetime(complete_at_epoch)
            brids = [br.id for br in build.requests]

            d = self.master.data.updates.completeBuildRequests(
                brids, results, complete_at=complete_at)
            # nothing in particular to do with this deferred, so just log it if
            # it fails..
            d.addErrback(log.err, 'while marking build requests as completed')

        if wfb.worker:
            wfb.worker.releaseLocks()
350703
def _finish(self):
        """"""
        self.finished = True
        if self._callback:
            self._callback(self)
        self._finish_event.set()
1199417
public function finalize()
    {
        @flock($this->getFileResource(), LOCK_UN);
        @fclose($this->getFileResource());
        @unlink($this->getFileName());
    }
906007
private void complete(final InstallationManager.InstallationModification modification, final FinalizeCallback callback) {
        final List<File> processed = new ArrayList<File>();
        List<File> reenabled = Collections.emptyList();
        List<File> disabled = Collections.emptyList();
        try {
            try {
                // Update the state to invalidate and process module resources
                if (stateUpdater.compareAndSet(this, State.PREPARED, State.INVALIDATE)) {
                    if (mode == PatchingTaskContext.Mode.APPLY) {
                        // Only invalidate modules when applying patches; on rollback files are immediately restored
                        for (final File invalidation : moduleInvalidations) {
                            processed.add(invalidation);
                            PatchModuleInvalidationUtils.processFile(this, invalidation, mode);
                        }
                        if (!modulesToReenable.isEmpty()) {
                            reenabled = new ArrayList<File>(modulesToReenable.size());
                            for (final File path : modulesToReenable) {
                                reenabled.add(path);
                                PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.ROLLBACK);
                            }
                        }
                    } else if(mode == PatchingTaskContext.Mode.ROLLBACK) {
                        if (!modulesToDisable.isEmpty()) {
                            disabled = new ArrayList<File>(modulesToDisable.size());
                            for (final File path : modulesToDisable) {
                                disabled.add(path);
                                PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.APPLY);
                            }
                        }
                    }

                }
                modification.complete();
                callback.completed(this);
                state = State.COMPLETED;
            } catch (Exception e) {
                this.moduleInvalidations.clear();
                this.moduleInvalidations.addAll(processed);
                this.modulesToReenable.clear();
                this.modulesToReenable.addAll(reenabled);
                this.modulesToDisable.clear();
                this.moduleInvalidations.addAll(disabled);
                throw new RuntimeException(e);
            }
        } finally {
            if (state != State.COMPLETED) {
                try {
                    modification.cancel();
                } finally {
                    try {
                        undoChanges();
                    } finally {
                        callback.operationCancelled(this);
                    }
                }
            } else  {
                try {
                    if (checkForGarbageOnRestart) {
                        final File cleanupMarker = new File(installedImage.getInstallationMetadata(), "cleanup-patching-dirs");
                        cleanupMarker.createNewFile();
                    }
                    storeFailedRenaming();
                } catch (IOException e) {
                    PatchLogger.ROOT_LOGGER.debugf(e, "failed to create cleanup marker");
                }
            }
        }
    }
675680
public static function finish() {

        if(empty(self::$profiler) === false) {

            self::$profiler = array_merge([
                'elapsed'   =>  self::getTime(time() - self::$profiler['start']),
                'memory'    =>  self::getMemoryUsage(),
                'cpu'       =>  self::getUsageCPU(),
                'stack'     =>  self::getStackCalls()
            ], self::$profiler);

            unset(self::$profiler['start']);
        }
    }
1043553
private void complete() {
		if (stopped) {
			return;
		}

		log.info("Spidering process is complete. Shutting down...");
		this.stopped = true;
		if (httpSender != null) {
			this.getHttpSender().shutdown();
			httpSender = null;
		}

		// Notify the controller to clean up memory
		controller.reset();

		// Issue the shutdown command on a separate thread, as the current thread is most likely one
		// from the pool
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (threadPool != null) {
					threadPool.shutdown();
				}
				// Notify the listeners -- in the meanwhile
				notifyListenersSpiderComplete(true);
				controller.reset();
				threadPool = null;
			}
		}, "ZAP-SpiderShutdownThread-" + id).start();
	}
1374536
def end_step(self, lineno, timestamp=None, result_code=None):
        """"""
        self.state = self.STATES['step_finished']
        step_errors = self.sub_parser.get_artifact()
        step_error_count = len(step_errors)
        if step_error_count > settings.PARSER_MAX_STEP_ERROR_LINES:
            step_errors = step_errors[:settings.PARSER_MAX_STEP_ERROR_LINES]
            self.artifact["errors_truncated"] = True
        self.current_step.update({
            "finished": timestamp,
            "finished_linenumber": lineno,
            # Whilst the result code is present on both the start and end buildbot-style step
            # markers, for Taskcluster logs the start marker line lies about the result, since
            # the log output is unbuffered, so Taskcluster does not know the real result at
            # that point. As such, we only set the result when ending a step.
            "result": self.RESULT_DICT.get(result_code, "unknown"),
            "errors": step_errors
        })
        # reset the sub_parser for the next step
        self.sub_parser.clear()
456296
function finished(err) {
    if (err) self.critical('Failed to store %s. %s.', base, err.message);
    if (fn) fn(err, collection);
  }
697278
@Override
    public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) {
        Map<String, String> envVars = returnEnvironmentVars(build, listener);
        if (envVars == null) {
            return;
        }

        try {
            returnGhprbSimpleStatus(envVars).onBuildComplete(build, listener, repo);
        } catch (GhprbCommitStatusException e) {
            e.printStackTrace();
        }
    }
523583
public void finishSynch() throws IOException {
		if (finishing != null) {
			finishing.blockException(0);
			return;
		}
		finishing = new SynchronizationPoint<>();
		try {
			AsyncWork<Integer, IOException> lastWrite = writeOps.getLastPendingOperation();
			if (lastWrite != null) {
				lastWrite.blockException(0);
			}
			deflater.finish();
			if (!deflater.finished()) {
				byte[] writeBuf = new byte[8192];
				do {
					int nb = deflater.deflate(writeBuf, 0, writeBuf.length);
					if (nb <= 0) break;
					output.writeSync(ByteBuffer.wrap(writeBuf, 0, nb));
				} while (!deflater.finished());
			}
			finishing.unblock();
		} catch (IOException e) {
			finishing.error(e);
			throw e;
		}
	}
835119
public synchronized void finish() {
    if (!this.isInitialized()) {
      throw new IllegalStateException("Torrent not yet initialized!");
    }

    if (!this.isComplete()) {
      throw new IllegalStateException("Torrent download is not complete!");
    }

    eventDispatcher.multicaster().downloadComplete();
    setClientState(ClientState.SEEDING);
  }