NB: global config options (e.g. daemonize, pidfile,
 logfile, redis options) won't be checked on reload.
 should we do a full restart if some of these change?
8021
def reload
      # TODO refactor cfg load and key retrieval, consolidate with initial load
      prev_pikelet_cfg = pikelet_definitions(@config.all)

      @config.reload

      current_pikelet_cfg = pikelet_definitions(@config.all)

      prev_keys    = prev_pikelet_cfg.keys
      current_keys = current_pikelet_cfg.keys

      removed     = prev_keys - current_keys
      added       = current_keys - prev_keys
      ask_running = current_keys - (added + removed)

      # for sections previously there and still there, ask them
      # to make the config change; they will if they can, or will signal
      # restart is needed if not
      # reload() returns trinary value here; true means the change was made, false
      # means the pikelet needs to be restarted, nil means no change
      # was required.
      ask_running.each do |ask_key|
        next unless pikelet = @pikelets.detect {|pik| ask_key == pik.type}

        if pikelet.reload(current_pikelet_cfg[pikelet.type]).is_a?(FalseClass)
          removed << pikelet.type
          added << pikelet.type
        end
      end

      pikelets_to_remove = @pikelets.select{|pik| removed.include?(pik.type) }
      pikelets_to_remove.map(&:stop)
      @pikelets -= pikelets_to_remove

      added_defs = current_pikelet_cfg.select {|k, v| added.include?(k) }

      create_pikelets(added_defs).each do |pik|
        @pikelets << pik
        pik.start
      end
    end
983715
def Initialize(config=None,
               external_hostname = None,
               admin_password = None,
               redownload_templates = False,
               repack_templates = True,
               token = None):
  """"""

  print("Checking write access on config %s" % config["Config.writeback"])
  if not os.access(config.parser.filename, os.W_OK):
    raise IOError("Config not writeable (need sudo?)")

  print("\nStep 0: Importing Configuration from previous installation.")
  options_imported = 0
  prev_config_file = config.Get("ConfigUpdater.old_config", default=None)
  if prev_config_file and os.access(prev_config_file, os.R_OK):
    print("Found config file %s." % prev_config_file)
    # pytype: disable=wrong-arg-count
    if builtins.input("Do you want to import this configuration? "
                      "[yN]: ").upper() == "Y":
      options_imported = ImportConfig(prev_config_file, config)
    # pytype: enable=wrong-arg-count
  else:
    print("No old config file found.")

  print("\nStep 1: Setting Basic Configuration Parameters")
  print("We are now going to configure the server using a bunch of questions.")
  ConfigureDatastore(config)
  ConfigureUrls(config, external_hostname=external_hostname)
  ConfigureEmails(config)

  print("\nStep 2: Key Generation")
  if config.Get("PrivateKeys.server_key", default=None):
    if options_imported > 0:
      print("Since you have imported keys from another installation in the "
            "last step,\nyou probably do not want to generate new keys now.")
    # pytype: disable=wrong-arg-count
    if (builtins.input("You already have keys in your config, do you want to"
                       " overwrite them? [yN]: ").upper() or "N") == "Y":
      config_updater_keys_util.GenerateKeys(config, overwrite_keys=True)
    # pytype: enable=wrong-arg-count
  else:
    config_updater_keys_util.GenerateKeys(config)

  FinalizeConfigInit(
      config,
      token,
      admin_password=admin_password,
      redownload_templates=redownload_templates,
      repack_templates=repack_templates,
      prompt=True)
115080
def _startup(self):
        
        global _ac_config_logs
        global sconf_global
        global SConfFS

        self.lastEnvFs = self.env.fs
        self.env.fs = SConfFS
        self._createDir(self.confdir)
        self.confdir.up().add_ignore( [self.confdir] )

        if self.logfile is not None and not dryrun:
            # truncate logfile, if SConf.Configure is called for the first time
            # in a build
            if self.logfile in _ac_config_logs:
                log_mode = "a"
            else:
                _ac_config_logs[self.logfile] = None
                log_mode = "w"
            fp = open(str(self.logfile), log_mode)
            self.logstream = SCons.Util.Unbuffered(fp)
            # logfile may stay in a build directory, so we tell
            # the build system not to override it with a eventually
            # existing file with the same name in the source directory
            self.logfile.dir.add_ignore( [self.logfile] )

            tb = traceback.extract_stack()[-3-self.depth]
            old_fs_dir = SConfFS.getcwd()
            SConfFS.chdir(SConfFS.Top, change_os_dir=0)
            self.logstream.write('file %s,line %d:\n\tConfigure(confdir = %s)\n' %
                                 (tb[0], tb[1], str(self.confdir)) )
            SConfFS.chdir(old_fs_dir)
        else:
            self.logstream = None
        # we use a special builder to create source files from TEXT
        action = SCons.Action.Action(_createSource,
                                     _stringSource)
        sconfSrcBld = SCons.Builder.Builder(action=action)
        self.env.Append( BUILDERS={'SConfSourceBuilder':sconfSrcBld} )
        self.config_h_text = _ac_config_hs.get(self.config_h, "")
        self.active = 1
        # only one SConf instance should be active at a time ...
        sconf_global = self
206805
public void configureSettingsFromFile(File globalSettings, File userSettings)
        throws InvalidConfigurationFileException {

        SettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
        if (globalSettings != null) {
            request.setGlobalSettingsFile(globalSettings);
        }
        if (userSettings != null) {
            request.setUserSettingsFile(userSettings);
        }
        request.setSystemProperties(SecurityActions.getProperties());

        MavenSettingsBuilder builder = new MavenSettingsBuilder();
        this.settings = builder.buildSettings(request);

        // ensure we keep offline(boolean) if previously set
        propagateProgrammaticOfflineIntoSettings();
    }
930470
def reload(self):
        
        logging.debug('Reloading config file as files have been modified.')
        self.config.plugin, self.config.general = self.config.reload()
        logging.debug('Reloading plugins as files have been modified.')
        self.loader = plugin_manager.PluginLoader(
            self._plugin_path, self.config.plugin)
        self._plugin_mod_time = os.path.getmtime(self._plugin_path)
        self._config_mod_time = os.path.getmtime(self._config_file_path)
1159017
def reload_config(self, async=True, verbose=False):
        '''
        
        '''
        # If we're using an API version older than 4.5.0, don't use async
        api_version = float(self.api_version()['api_version'])
        if api_version < 4.5:
            async = False
        url = '{}/{}{}'.format(
            self.rest_url, 'reload', '?asynchronous=1' if async else ''
        )
        return self.__auth_req_post(url, verbose=verbose)
268650
def reload_webservers():
    
    if env.verbosity:
        print env.host, "RELOADING apache2"
    with settings(warn_only=True):
        a = sudo("/etc/init.d/apache2 reload")
        if env.verbosity:
            print '',a        
    if env.verbosity:

        #Reload used to fail on Ubuntu but at least in 10.04 it works
        print env.host,"RELOADING nginx"
    with settings(warn_only=True):
        s = run("/etc/init.d/nginx status")
        if 'running' in s:
            n = sudo("/etc/init.d/nginx reload")
        else:
            n = sudo("/etc/init.d/nginx start")
    if env.verbosity:
        print ' *',n
    return True
762530
function initializeKVPersistent (config) {
	/* NB Makes FS syscalls each time in case config changes during lifetime.
	 * Could cache the set of initialized dirs if this is a performance issue. */

	/* First try a mkdir. Dir might exist already. */
	try {
		fs.mkdirSync(config.cache.persistentDir);
	} catch (e) {
	}

	/* If we have a dir now, we're happy.
	 * This also works if persistentDir is a symlink. */
	try {
		const stats = fs.lstatSync(config.cache.persistentDir);
		if (stats.isDirectory()) {
			return true;
		} else {
			return false;
		}
	} catch (e) {
		/* Hmm. */
		return false;
	}
}
106132
def initializenb():
    

    logger.info('Working directory: {0}'.format(os.getcwd()))
    logger.info('Run on {0}'.format(asctime()))
    try:
        fileroot = os.environ['fileroot']
        logger.info('Setting fileroot to {0} from environment variable.\n'.format(fileroot))
        candsfile = 'cands_{0}_merge.pkl'.format(fileroot)
        noisefile = 'noise_{0}_merge.pkl'.format(fileroot)
    except KeyError:
        sdmdir = os.getcwd()
        logger.info('Setting sdmdir to current directory {0}\n'.format(os.path.abspath(sdmdir)))
        candsfiles = glob.glob('cands_*_merge.pkl')
        noisefiles = glob.glob('noise_*_merge.pkl')
        if len(candsfiles) == 1 and len(noisefiles) == 1:
            logger.info('Found one cands/merge file set')
        else:
            logger.warn('Found multiple cands/noise file sets. Taking first.')

        candsfile = candsfiles[0]
        noisefile = noisefiles[0]
        fileroot = candsfile.rstrip('_merge.pkl').lstrip('cands_')
    logger.info('Set: \n\t candsfile {} \n\t noisefile {} \n\t fileroot {} '.format(candsfile, noisefile, fileroot))
    return (candsfile, noisefile, fileroot)
872364
function(reload) {

        var bundle          = self.bundle;
        var model           = self.model;
        var modelDirName    = self.modelDirName;

        // this is supposed to happen on load or for dev env; on reload, with a checksum
        var conf        = getConfigSync(bundle);
        local.locals    = conf.locals;

        if (conf) {
            _configuration = conf.connectors;

            console.debug("CONF READY ", model, conf.path);
            //TODO - More controls...

            //For now, I just need the F..ing entity name.
            var modelPath       = local.modelPath = _(conf.path + '/' + modelDirName);
            var entitiesPath    = local.entitiesPath = _(modelPath + '/entities');
            console.debug('models scaning... ', entitiesPath, fs.existsSync(entitiesPath));
            if (!fs.existsSync(entitiesPath)) {
                fs.mkdirSync(entitiesPath) // creating empty path
            }

            var connectorPath   = _(modelPath + '/lib/connector.js');
            //Getting Entities Manager.
            var exists = fs.existsSync(connectorPath);
            if (exists) {
                if (cacheless)
                    delete require.cache[_(connectorPath, true)];

                var Connector = require(_(connectorPath, true));

                self.connect(
                    Connector,
                    function onConnect(err, conn) {
                        if (err) {
                            console.error(err.stack);
                            self.emit('model#ready', err, self.bundle, self.name, null)

                        } else {
                            local.connection = conn;
                            self.emit('model#ready', false, self.bundle, self.name, conn)
                        }
                    }
                )
            } else {//Means that no connector was found in models.

                //finished.
                self.emit('model#ready', new Error('[ '+self.name+' ] No connector found'), self.bundle, self.name, conn)
            }

        } else {
            console.debug("no configuration found...");
            self.emit('model#ready', new Error('no configuration found for your model: ' + model), self.bundle, self.name, null)
        }

        return self
    }
228265
def reload(self, config=None, debug=False):
        
        try:
            # log configuration handling
            # get log level
            # (if not in configuration file, log level is set to debug)
            level = get_loglevel(
                self._get_param(
                    'global',
                    'log.level',
                    config,
                    'debug',
                    )
                )
            # configure access log
            self._set_access_log(config, level)
            # configure error log
            self._set_error_log(config, level, debug)

            # load template files
            self._load_templates(config)

            # loading the auth configuration
            self._init_auth(config)

            # Loading the attributes
            self.attributes_file = \
                self._get_param('attributes', 'attributes.file', config)
            cherrypy.log.error(
                msg="loading attributes file '%(file)s'" %
                    {'file': self.attributes_file},
                severity=logging.DEBUG
            )

            self.notifications = {}

            self.attributes = Attributes(self.attributes_file)

            cherrypy.log.error(
                msg="init directories backends",
                severity=logging.DEBUG
            )
            self._init_backends(config)
            self._check_backends()

            # loading the ppolicy
            self._init_ppolicy(config)

            # loading custom javascript
            self._init_custom_js(config)

            cherrypy.log.error(
                msg="application started",
                severity=logging.INFO
            )

        except Exception as e:
            self._handle_exception(e)
            cherrypy.log.error(
                msg="application failed to start",
                severity=logging.ERROR
            )
            exit(1)
228910
public static synchronized void reloadExistingConfigurations() {
		if (LOG.isDebugEnabled()) {
			LOG.debug("Reloading " + REGISTRY.keySet().size()
					+ " existing configurations");
		}
		for (Configuration conf : REGISTRY.keySet()) {
			conf.reloadConfiguration();
		}
	}
153087
function Config(opts) {
  _.extend(this, {
    appName: 'ndm', // used by rc.
    serviceJsonPath: path.resolve(process.cwd(), 'service.json'),
    tmpServiceJsonPath: null, // used during install phase.
    logsDirectory: this.defaultLogsDirectory(),
    env: process.env,
    uid: null,
    gid: null,
    console: null, // In upstart 1.4, where should logs be sent? <logged|output|owner|none>
    sudo: null,
    headless: false,
    filter: null,
    modulePrefix: '',
    nodeBin: process.execPath,
    baseWorkingDirectory: path.resolve(process.cwd()),
    globalPackage: false,
    platform: null, // override the platform ndm generates services for
    platformApis: {
      ubuntu: require('./platform-apis/ubuntu'),
      centos: require('./platform-apis/centos'),
      darwin: require('./platform-apis/darwin'),
      initd: require('./platform-apis/init-d')
    },
    parsers: {
      sudo: function(v) { return v.toString() === 'true' },
      headless: function(v) { return v.toString() === 'true' },
      globalPackage: function(v) { return v.toString() === 'true' }
    }
  }, opts);

  // allow platform to be overridden.
  this.platform = this.os();

  // allow platform and env to be overridden before applying.
  _.extend(this, this._getEnv(), opts);

  this._rcOverride();
}
874958
def OnClearGlobals(self, event):
        """"""

        msg = _("Deleting globals and reloading modules cannot be undone."
                " Proceed?")
        short_msg = _("Really delete globals and modules?")

        choice = self.main_window.interfaces.get_warning_choice(msg, short_msg)

        if choice:
            self.main_window.grid.actions.clear_globals_reload_modules()

            statustext = _("Globals cleared and base modules reloaded.")
            post_command_event(self.main_window, self.main_window.StatusBarMsg,
                               text=statustext)
1159669
function boot() {
        // load dependencies
        cli = cli || define.cache.get(MODULE_ID_CLI, "minor").factory();

        var nw;
        var ui;
        try {
            // listen for OS open file event
            nw = require("nw");
            ui = require("nw.gui");
        }
        catch(e) {
            // ignore
        }

        // specify cli options
        if (nw) {
            cli.option("--ui", "Opens the selector in nw.js.");
        }
        else if (!host.isRuntimeBrowserFamily()) {
            cli.option("--ui", MSG_UI_UNAVAILABLE);
        }
        if (host.runtime == host.RUNTIME_NODEJS) {
            cli.option("--debug [port]", "Starts node.js in debug mode.");
        }
        else {
            cli.option("--debug [port]", MSG_DEBUG_UNAVAILABLE);
        }
        cli.option("--repo <url>", "Overrides the main repository for the active profile.");
        if (host.isRuntimeBrowserFamily()) {
            cli.option("--theme <url>", "Loads the specified css theme.");
        }
        cli.option("--config <json>", "A JSON object with parameters for the package module loaded.");
        cli.option("--profile <name>", "Overrides the active profile.");
        cli.option("--gh-username <username>", "Overrides the global configuration GitHub username key.");
        cli.option("--gh-password <password>", "Overrides the global configuration GitHub password key.");
        cli.option("--gh-token <token>", "Overrides the global configuration GitHub token key.");
        cli.option("--gh-branch <branch>", "Overrides the global configuration GitHub branch key.");
        cli.option("--gh-enable-pre-release <enable>", "Overrides the global configuration GitHub enable pre-release key.");
        cli.command("profile", "Performs configuration profile operations.")
            .command("list", "Lists all of the profiles available in the configuration.")
            .action(profileList);
        cli.command("profile")
            .command("add <name>", "Add a new profile.")
            .action(profileAdd);
        cli.command("profile")
            .command("copy <name>", "Creates a copy of the current profile with the given name.")
            .action(profileCopy);
        cli.command("profile")
            .command("remove <name>", "Removes the profile with the given name.")
            .action(profileRemove);
        cli.command("profile")
            .command("current", "Displays the name of the active profile.")
            .action(profileCurrent);
        cli.command("profile")
            .command("switch <name>", "Activates the profile with the given name.")
            .action(profileSwitch);
        cli.command("profile")
            .command("set <section> <key> <value>", "Sets the key value combination in the active profile.")
            .action(profileSet);
        cli.parameter("allume <selector>");
        var p = cli.parse(allume.parameters);

        //
        // start the loading process for the specified selector
        //
        function open(selector) {
            if (p["--debug"] && host.runtime == host.RUNTIME_NODEJS) {
                return debug(p);
            }
            if (p["--ui"] && !ui) {
                if (!nw) {
                    allume.update(allume.STATUS_ERROR, MSG_UI_UNAVAILABLE);
                    return;
                }

                // spawn nw.js process for allume with parameters
                var findpath = nw.findpath;
                childProcess = childProcess || require("child_process");
                path = path || require("path");

                var PATH_NW = findpath();
                var PATH_APP = path.join(__dirname, "..");
                var PATH_CWD = process.cwd();
                var env = Object.create(process.env);
                env.PWD = process.cwd();

                process.argv.splice(1, 1);
                process.argv[0] = PATH_APP;
                for (var a in process.argv) {
                    process.argv[a] = process.argv[a].replace(/"/g, "\"");
                }

                var ls = childProcess.spawn(PATH_NW, process.argv, {"cwd": PATH_CWD, "env" : env});

                ls.stdout.on("data", function(data) {
                    console.log(data.toString().trim());
                });

                ls.stderr.on("data", function(data) {
                    console.error(data.toString().trim());
                });

                return;
            }

            var requests = [];
            var request = selector;
            if (p["--config"]) {
                var json;
                try {
                    json = JSON.parse(p["--config"].json);
                }
                catch(e) {
                    var e = new Error("Make sure the data you pass to the --config switch is valid JSON data.");
                    e.name = "error-invalid-configuration";
                    if (typeof document !== "undefined" && firstOpen) {
                        allume.update(e);
                    }
                    else {
                        console.error(e);
                    }
                    firstOpen = false;
                    return;
                }
                request = { "package" : selector, "configuration" : json };
            }
            requests.push(request);

            if (requests) {
                using.apply(using, requests).then(function () {
                    if (firstOpen) {
                        allume.hide();
                        firstOpen = false;
                    }
                }, function (loader) {
                    usingFailed(loader);
                    var e = new Error(err);
                    e.name = errName;
                    if (typeof document !== "undefined" && firstOpen) {
                        allume.update(e);
                        firstOpen = false;
                    }
                    else {
                        console.error(e);
                    }
                });
            }
        }

        if (p) {
            // attach config function to allume
            allume.config = config;

            // process commands and options
            if (p.repo) {
                repo = p.repo;
            }
            if (p["--profile"]) {
                allume.update(allume.STATUS_ERROR, MSG_MISSING_FEATURE);
                profile = p.profile;
            }
            if (p["--theme"] && typeof document !== "undefined") {
                var theme = document.createElement("link");
                theme.rel = "stylesheet";
                theme.href = p["--theme"].url;
                document.head.appendChild(theme);
            }
            if (p["--gh-username"]) {
                config.github = config.github || {};
                config.github.username = p["--gh-username"].username;
            }
            if (p["--gh-password"]) {
                config.github = config.github || {};
                config.github.password = p["--gh-password"].password;
            }
            if (p["--gh-token"]) {
                config.github = config.github || {};
                config.github.token = p["--gh-token"].token;
            }
            if (p["--gh-branch"]) {
                config.github = config.github || {};
                config.github.branch = p["--gh-branch"].branch;
            }
            if (p["--gh-enable-pre-release"]) {
                var val = p["--gh-enable-pre-release"].enable;
                config.github = config.github || {};
                config.github.enablePreRelease = !(val == "false" || !val);
            }
            if (p["--help"]) {
                if (typeof document !== "undefined") {
                    var e = new Error(p["--help"]);
                    e.name = "help";
                    allume.update(e);
                }
            }
            else if (!p.selector && !p.profile && (!p["--ui"] || ui)) {
                if (host.isRuntimeBrowserFamily() && !host.isRuntimeNodeFamily()) {
                    //debug
                    window.location = "../about.html";
                }
                else {
                    var e = new Error("The boot sequence can't start because no package was specified. If you are the developer of the app using allume, then please make sure you specify the package to load.");
                    e.name = "error-invalid-package";
                    if (typeof document !== "undefined") {
                        allume.update(e);
                    }
                    else {
                        console.error(e);
                    }
                }
            }
            else if (p.selector || p["--ui"]) {
                if (ui) {
                    // listen for OS open file event
                    ui.App.on("open", function(cmdline) {
                        cmdline = cmdline.replace(/"([^"]+)"/g, function(a) {
                            return a.replace(/\s/g, "&nbsp;");
                        }).split(" ");
                        for (var i = 0, length = cmdline.length, arg = "", args = []; i < length; ++i) {
                            arg = cmdline[i].replace(/&nbsp;/g, " ");
                            // filter by exe file and exe args.
                            if (arg === "\"" + process.execPath + "\"" || arg.search(/^\-\-/) === 0) continue;
                            args.push(arg);
                        }
                        console.log("OPEN", args);
                        open(args[args.length -1]);
                    });
                }

                open(p.selector);
            }
        }
        else {
            if (typeof document !== "undefined") {
                var e = new Error("Parameters where missing or invalid. Please check your browser javascript console.");
                e.name = "error-invalid-parameter";
                allume.update(e);
            }
        }
    }
289636
function configureDefaultMode (outputFolder) {
  const logfile = path.join(outputFolder, 'thumbsup.log')
  const stream = fs.createWriteStream(logfile, { flags: 'a' })
  overrideDebugFormat()
  debug.enable('thumbsup:error,thumbsup:warn')
  debug.useColors = () => false
  debug.log = function () {
    const line = util.format.apply(util, arguments) + '\n'
    stream.write(line)
  }
}
515187
def commit_config(self):
        
        # Always generate a rollback config on commit
        self._gen_rollback_cfg()

        if self.config_replace:
            # Replace operation
            filename = self.candidate_cfg
            cfg_file = self._gen_full_path(filename)
            if not self._check_file_exists(cfg_file):
                raise ReplaceConfigException("Candidate config file does not exist")
            if self.auto_rollback_on_error:
                cmd = 'configure replace {} force revert trigger error'.format(cfg_file)
            else:
                cmd = 'configure replace {} force'.format(cfg_file)
            output = self._commit_hostname_handler(cmd)
            if ('original configuration has been successfully restored' in output) or \
               ('error' in output.lower()) or \
               ('failed' in output.lower()):
                msg = "Candidate config could not be applied\n{}".format(output)
                raise ReplaceConfigException(msg)
            elif '%Please turn config archive on' in output:
                msg = "napalm-ios replace() requires Cisco 'archive' feature to be enabled."
                raise ReplaceConfigException(msg)
        else:
            # Merge operation
            filename = self.merge_cfg
            cfg_file = self._gen_full_path(filename)
            if not self._check_file_exists(cfg_file):
                raise MergeConfigException("Merge source config file does not exist")
            cmd = 'copy {} running-config'.format(cfg_file)
            self._disable_confirm()
            output = self._commit_hostname_handler(cmd)
            self._enable_confirm()
            if 'Invalid input detected' in output:
                self.rollback()
                err_header = "Configuration merge failed; automatic rollback attempted"
                merge_error = "{0}:\n{1}".format(err_header, output)
                raise MergeConfigException(merge_error)

        # Save config to startup (both replace and merge)
        output += self.device.send_command_expect("write mem")