Remove modules by calling remove method on those configured for removal.
429645
def do_remove(self, loglevel=logging.DEBUG):
		
		shutit_global.shutit_global_object.yield_to_draw()
		cfg = self.cfg
		# Now get the run_order keys in order and go.
		self.log('PHASE: remove', level=loglevel)
		self.pause_point('\nNow removing any modules that need removing', print_input=False, level=3)
		# Login at least once to get the exports.
		for module_id in self.module_ids():
			module = self.shutit_map[module_id]
			self.log('considering whether to remove: ' + module_id, level=logging.DEBUG)
			if cfg[module_id]['shutit.core.module.remove']:
				self.log('removing: ' + module_id, level=logging.DEBUG)
				self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False)
				if not module.remove(self):
					self.log(self.print_modules(), level=logging.DEBUG)
					self.fail(module_id + ' failed on remove', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child) # pragma: no cover
				else:
					if self.build['delivery'] in ('docker','dockerfile'):
						# Create a directory and files to indicate this has been removed.
						self.send(' command mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + ' && command rm -f ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/built && command touch ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/removed', loglevel=loglevel, echo=False)
						# Remove from "installed" cache
						if module.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed:
							self.get_current_shutit_pexpect_session_environment().modules_installed.remove(module.module_id)
						# Add to "not installed" cache
						self.get_current_shutit_pexpect_session_environment().modules_not_installed.append(module.module_id)
				self.logout(echo=False)
172592
public function uninstall($module_id)
    {
        try {
            $result = $this->canUninstall($module_id);
        } catch (Exception $ex) {
            $result = $ex->getMessage();
        }

        $this->hook->attach("module.uninstall.before|$module_id", $result, $this);

        if ($result !== true) {
            return $result;
        }

        $this->module->delete($module_id);
        $this->setOverrideConfig();

        $this->hook->attach("module.uninstall.after|$module_id", $result, $this);
        return $result;
    }
754413
protected function removeNotUsedSettings($moduleSettings, $moduleId)
    {
        $moduleConfigs = array_keys($this->getModuleConfigs($moduleId));
        $moduleSettings = $this->parseModuleSettings($moduleSettings);

        $configsToRemove = array_diff($moduleConfigs, $moduleSettings);
        if (!empty($configsToRemove)) {
            $this->removeModuleConfigs($moduleId, $configsToRemove);
        }
    }
1171531
protected void cleanUp() {

        m_importResource = null;
        m_importZip = null;
        m_report = null;
        m_linkStorage = null;
        m_linkPropertyStorage = null;
        m_groupsToCreate = null;
        m_cms = null;
    }
1004971
def remove_grad_hooks(module, input):
    
    for hook in list(module.param_hooks.keys()):
        module.param_hooks[hook].remove()
        module.param_hooks.pop(hook)
    for hook in list(module.var_hooks.keys()):
        module.var_hooks[hook].remove()
        module.var_hooks.pop(hook)
32863
function () {
            this.unloadCommonModules();
            var pageModRefpaths = this._modulesPaths.page;
            for (var pageId in pageModRefpaths) {
                if (pageModRefpaths.hasOwnProperty(pageId)) {
                    this.unloadPageModules(pageId);
                }
            }
        }
342880
def remove(cls, module_name):
        
        module_guards = cls._guards.get(module_name, False)
        if module_guards:
            module_guards.pop()
            cls._num_entries -= 1
            if cls._num_entries < 1:
                if cls._num_entries < 0:
                    raise Exception(
                        'Bug: ImportGuardHook._num_entries became negative!'
                    )
                cls._uninstall()
11155
public function remove($moduleId)
    {
        $controllerMap = $this->get();
        unset($controllerMap[strtolower($moduleId)]);

        $this->set($controllerMap);
    }
856953
def demote(self):
    
    import sys  # Grab a hold of `sys` early since we'll be un-importing our module in this process.

    unimported_modules = []
    for name, module in reversed(sorted(sys.modules.items())):
      if self.imported_from_bootstrap(module):
        unimported_modules.append(sys.modules.pop(name))

    sys.path[:] = [path for path in sys.path if os.path.realpath(path) != self._realpath]
    sys.path.append(self._sys_path_entry)

    return unimported_modules
621547
function _cleanModulesOnElement(enabledElement) {
  const modules = store.modules;

  Object.keys(modules).forEach(function(key) {
    if (typeof modules[key].removeEnabledElementCallback === 'function') {
      modules[key].removeEnabledElementCallback(enabledElement);
    }
  });
}
1096832
public void clearRegisteredModules()
    {
        ServletContext servletContext = getServletContext();
        
        for ( Iterator ii = _registeredModules.keySet().iterator(); ii.hasNext(); )  
        {
            String modulePrefix = ( String ) ii.next();
            servletContext.removeAttribute( Globals.MODULE_KEY + modulePrefix );
            servletContext.removeAttribute( Globals.REQUEST_PROCESSOR_KEY + modulePrefix );
        }
        
        _registeredModules.clear();
    }
1228231
public function remove()
    {
        $f = json_decode(file_get_contents(FEnv::get("framework.root").
            "elements/config_files/core/apps.json"));
        foreach ($f as $one => $val) {
            if ($val->name == $this->name) {
                unset($f->$one);
                break;
            }
        }

        $f = json_encode($f, JSON_PRETTY_PRINT);
        file_put_contents(FEnv::get("framework.root")."elements/config_files/core/apps.json", $f);

        Server::delete(FEnv::get("framework.root")."apps/".$this->name, "directory");
        Server::delete(
            FEnv::get("framework.root")."public/components/apps/".strtolower($this->name),
            'directory'
        );
    }
444174
def _remove(self, args):
        '''
        
        '''
        if len(args) < 2:
            raise SPMInvocationError('A package must be specified')

        packages = args[1:]
        msg = 'Removing packages:\n\t{0}'.format('\n\t'.join(packages))

        if not self.opts['assume_yes']:
            self.ui.confirm(msg)

        for package in packages:
            self.ui.status('... removing {0}'.format(package))

            if not self._pkgdb_fun('db_exists', self.opts['spm_db']):
                raise SPMDatabaseError('No database at {0}, cannot remove {1}'.format(self.opts['spm_db'], package))

            # Look at local repo index
            pkg_info = self._pkgdb_fun('info', package, self.db_conn)
            if pkg_info is None:
                raise SPMInvocationError('Package {0} not installed'.format(package))

            # Find files that have not changed and remove them
            files = self._pkgdb_fun('list_files', package, self.db_conn)
            dirs = []
            for filerow in files:
                if self._pkgfiles_fun('path_isdir', filerow[0]):
                    dirs.append(filerow[0])
                    continue
                file_hash = hashlib.sha1()
                digest = self._pkgfiles_fun('hash_file', filerow[0], file_hash, self.files_conn)
                if filerow[1] == digest:
                    self._verbose('Removing file {0}'.format(filerow[0]), log.trace)
                    self._pkgfiles_fun('remove_file', filerow[0], self.files_conn)
                else:
                    self._verbose('Not removing file {0}'.format(filerow[0]), log.trace)
                self._pkgdb_fun('unregister_file', filerow[0], package, self.db_conn)

            # Clean up directories
            for dir_ in sorted(dirs, reverse=True):
                self._pkgdb_fun('unregister_file', dir_, package, self.db_conn)
                try:
                    self._verbose('Removing directory {0}'.format(dir_), log.trace)
                    os.rmdir(dir_)
                except OSError:
                    # Leave directories in place that still have files in them
                    self._verbose('Cannot remove directory {0}, probably not empty'.format(dir_), log.trace)

            self._pkgdb_fun('unregister_pkg', package, self.db_conn)
419864
def delete_modules(self):
        ''' 

        '''
        from gc import get_referrers
        from types import FrameType

        log.debug("Deleting %s modules for %s" % (len(self._modules), self))

        for module in self._modules:

            # Modules created for a Document should have three referrers at this point:
            #
            # - sys.modules
            # - self._modules
            # - a frame object
            #
            # This function will take care of removing these expected references.
            #
            # If there are any additional referrers, this probably means the module will be
            # leaked. Here we perform a detailed check that the only referrers are expected
            # ones. Otherwise issue an error log message with details.
            referrers = get_referrers(module)
            referrers = [x for x in referrers if x is not sys.modules]
            referrers = [x for x in referrers if x is not self._modules]
            referrers = [x for x in referrers if not isinstance(x, FrameType)]
            if len(referrers) != 0:
                log.error("Module %r has extra unexpected referrers! This could indicate a serious memory leak. Extra referrers: %r" % (module, referrers))

            # remove the reference from sys.modules
            if module.__name__ in sys.modules:
                del sys.modules[module.__name__]

        # remove the reference from self._modules
        self._modules = None
859125
def clean(file_, imports):
    """"""
    modules_not_imported = compare_modules(file_, imports)
    re_remove = re.compile("|".join(modules_not_imported))
    to_write = []

    try:
        f = open_func(file_, "r+")
    except OSError:
        logging.error("Failed on file: {}".format(file_))
        raise
    else:
        for i in f.readlines():
            if re_remove.match(i) is None:
                to_write.append(i)
        f.seek(0)
        f.truncate()

        for i in to_write:
            f.write(i)
    finally:
        f.close()

    logging.info("Successfully cleaned up requirements in " + file_)
473100
protected function removeMiddlewareFromApp()
    {
        if ($this->middlewareRemoved) {
            return;
        }

        $this->middlewareRemoved = true;

        $reflection = new ReflectionClass($this->app);
        $property = $reflection->getProperty('middleware');
        $property->setAccessible(true);
        $oldMiddlewares = $property->getValue($this->app);
        $newMiddlewares = [];
        foreach ($oldMiddlewares as $middle) {
            if ((new ReflectionClass($middle))->hasMethod('terminate') && $middle != 'Dingo\Api\Http\Middleware\Request') {
                $newMiddlewares = array_merge($newMiddlewares, [$middle]);
            }
        }
        $property->setValue($this->app, $newMiddlewares);
        $property->setAccessible(false);
    }
535786
def _disable_module(module):
        """"""
        try:
            subprocess.check_call(['a2dismod', module])
        except subprocess.CalledProcessError as e:
            # Note: catch error here to allow the attempt of disabling
            # multiple modules in one go rather than failing after the
            # first module fails.
            log('Error occurred disabling module %s. '
                'Output is: %s' % (module, e.output), level=ERROR)