Automatically loads configuration from datadir, instantiates specified
config class and validates it with specified confing definition class
337262
protected function loadConfig(): void
    {
        $configClass = $this->getConfigClass();
        $configDefinitionClass = $this->getConfigDefinitionClass();
        try {
            $this->config = new $configClass(
                $this->getRawConfig(),
                new $configDefinitionClass()
            );
        } catch (InvalidConfigurationException $e) {
            throw new UserException($e->getMessage(), 0, $e);
        }
    }
76802
public function loadConfiguration()
    {
        $builder = $this->getContainerBuilder();
        $config = $this->validateConfig($this->defaults);

        // define driver
        $default = $builder->addDefinition($this->prefix('default'))
            ->setFactory($config['driver'])
            ->setAutowired($config['autowired']);

        // define panel
        if ($config['debugger']) {
            $panel = $builder->addDefinition($this->prefix('panel'))
                ->setFactory(Panel::class, [$default]);

            // linked panel to tracy
            $builder->getDefinition('tracy.bar')
                ->addSetup('addPanel', [$panel]);
        }
    }
312320
def from_config(cls, config):
        """"""
        auth_key = None
        password_file = config["authentication.passwordFile"]
        if password_file is not None:
            try:
                auth_key = open(config["authentication.passwordFile"]).read()
                auth_key = re.sub(r"\s", "", auth_key)
            except IOError:
                LOG.error("Could not load password file!")
                sys.exit(1)
        password = config["authentication.password"]
        if password is not None:
            auth_key = password
        connector = Connector(
            mongo_address=config["mainAddress"],
            doc_managers=config["docManagers"],
            oplog_checkpoint=os.path.abspath(config["oplogFile"]),
            collection_dump=config["onlyDump"] or not config["noDump"],
            only_dump=config["onlyDump"],
            batch_size=config["batchSize"],
            continue_on_error=config["continueOnError"],
            auth_username=config["authentication.adminUsername"],
            auth_key=auth_key,
            fields=config["fields"],
            exclude_fields=config["exclude_fields"],
            ns_set=config["namespaces.include"],
            ex_ns_set=config["namespaces.exclude"],
            dest_mapping=config["namespaces.mapping"],
            namespace_options=config["namespaces.namespace_options"],
            gridfs_set=config["namespaces.gridfs"],
            ssl_certfile=config["ssl.sslCertfile"],
            ssl_keyfile=config["ssl.sslKeyfile"],
            ssl_ca_certs=config["ssl.sslCACerts"],
            ssl_cert_reqs=config["ssl.sslCertificatePolicy"],
            tz_aware=config["timezoneAware"],
        )
        return connector
415662
public static function classConstructor()
    {
        $locator = new ConfigurationLocator(array(
            __DIR__ . self::BAV_PATH,
            self::INCLUDE_PATH
        ));
        $configuration = $locator->locate();
        if ($configuration == null) {
            $configuration = new DefaultConfiguration();
            
        }
        self::setConfiguration($configuration);
    }
940320
function loadConfig(configToLoad) {
  var config = {};
  var filePath = '';

  if (configToLoad) {

    if (isObject(configToLoad)) {
      config = configToLoad;
    } else {
      filePath = configToLoad;
      config = readConfigFromFile(filePath);
    }

    if (!config.rules) {
      config.rules = {};
    }
    config.rules = Object.keys(config.rules).reduce(function(obj, ruleId) {
      if (!Array.isArray(config.rules[ruleId])) {
        obj[ruleId] = [config.rules[ruleId]];
      }
      return obj;
    }, {});

    validator.validate(config, filePath);

        // If an `extends` property is defined, it represents a configuration file to use as
        // a 'parent'. Load the referenced file and merge the configuration recursively.
    if (config.extends) {
      var configExtends = config.extends;

      if (!Array.isArray(config.extends)) {
        configExtends = [config.extends];
      }

            // Make the last element in an array take the highest precedence
      config = configExtends.reduceRight(function(previousValue, parentPath) {

        if (parentPath === 'nplint:recommended') {
                    // Add an explicit substitution for eslint:recommended to conf/eslint.json
                    // this lets us use the eslint.json file as the recommended rules
          parentPath = path.resolve(__dirname, '../conf/nplint.json');
        } else if (isFilePath(parentPath)) {
                  // If the `extends` path is relative, use the directory of the current configuration
                  // file as the reference point. Otherwise, use as-is.
          parentPath = (!isAbsolutePath(parentPath) ?
                    path.join(path.dirname(filePath), parentPath) :
                    parentPath
                );
        }

        try {
          return util.mergeConfigs(loadConfig(parentPath), previousValue);
        } catch (e) {
                  // If the file referenced by `extends` failed to load, add the path to the
                  // configuration file that referenced it to the error message so the user is
                  // able to see where it was referenced from, then re-throw
          e.message += '\nReferenced from: ' + filePath;
          throw e;
        }

      }, config);

    }

  }

  return config;
}
841913
def load_configuration_from_file(directory, args):
    """"""
    args = copy.copy(args)

    directory_or_file = directory
    if args.config is not None:
        directory_or_file = args.config

    options = _get_options(directory_or_file, debug=args.debug)

    args.report = options.get('report', args.report)
    threshold_dictionary = docutils.frontend.OptionParser.thresholds
    args.report = int(threshold_dictionary.get(args.report, args.report))

    args.ignore_language = get_and_split(
        options, 'ignore_language', args.ignore_language)

    args.ignore_messages = options.get(
        'ignore_messages', args.ignore_messages)

    args.ignore_directives = get_and_split(
        options, 'ignore_directives', args.ignore_directives)

    args.ignore_substitutions = get_and_split(
        options, 'ignore_substitutions', args.ignore_substitutions)

    args.ignore_roles = get_and_split(
        options, 'ignore_roles', args.ignore_roles)

    return args
1041450
public static DataNode instantiateDataNode(String args[],
                                      Configuration conf) throws IOException {
    if (conf == null)
      conf = new Configuration();
    if (!parseArguments(args, conf)) {
      printUsage();
      return null;
    }
    if (conf.get("dfs.network.script") != null) {
      LOG.error("This configuration for rack identification is not supported" +
          " anymore. RackID resolution is handled by the NameNode.");
      System.exit(-1);
    }
    String[] dataDirs = getListOfDataDirs(conf);
        dnThreadName = "DataNode: [" +
                        StringUtils.arrayToString(dataDirs) + "]";
    return makeInstance(dataDirs, conf);
  }
602116
public function loadConfiguration(): void
	{
		$config = $this->validateConfig($this->defaults);
		$builder = $this->getContainerBuilder();

		Validators::assertField($config, 'siteKey', 'string');
		Validators::assertField($config, 'secretKey', 'string');

		$builder->addDefinition($this->prefix('provider'))
			->setFactory(ReCaptchaProvider::class, [$config['siteKey'], $config['secretKey']]);
	}
18827
def FinalizeConfigInit(config,
                       token,
                       admin_password = None,
                       redownload_templates = False,
                       repack_templates = True,
                       prompt = True):
  """"""
  config.Set("Server.initialized", True)
  print("\nWriting configuration to %s." % config["Config.writeback"])
  config.Write()
  print("Initializing the datastore.")
  # Reload the config and initialize the GRR database.
  server_startup.Init()

  print("\nStep 3: Adding GRR Admin User")
  try:
    CreateUser("admin", password=admin_password, is_admin=True)
  except UserAlreadyExistsError:
    if prompt:
      # pytype: disable=wrong-arg-count
      if ((builtins.input("User 'admin' already exists, do you want to "
                          "reset the password? [yN]: ").upper() or "N") == "Y"):
        UpdateUser("admin", password=admin_password, is_admin=True)
      # pytype: enable=wrong-arg-count
    else:
      UpdateUser("admin", password=admin_password, is_admin=True)

  print("\nStep 4: Repackaging clients with new configuration.")
  if prompt:
    redownload_templates = RetryBoolQuestion(
        "Server debs include client templates. Re-download templates?", False)
    repack_templates = RetryBoolQuestion("Repack client templates?", True)
  if redownload_templates:
    InstallTemplatePackage()
  # Build debug binaries, then build release binaries.
  if repack_templates:
    repacking.TemplateRepacker().RepackAllTemplates(upload=True, token=token)
  print("\nGRR Initialization complete! You can edit the new configuration "
        "in %s.\n" % config["Config.writeback"])
  print("Please restart the service for the new configuration to take "
        "effect.\n")
886868
function getConfig(name, def) {

        var i, j;

        // Load initital config.
        if (!config) {

            var external;

            config = grunt.config.get('cog') || {options: {}};

            // Expand general external definitions to category specific definitions.
            if (config.options.external instanceof Array) {
                external = config.options.external;
                config.options.external = {lib: [], css: [], fonts: []};
                for (i=0; i < external.length; i++) {
                    if (!db.categories[external[i]]) {
                        grunt.fail.fatal("Cannot figure out applicaple categories for external dependency: " + external[i]);
                    }
                    for(j = 0; j < db.categories[external[i]].length; j++) {
                        config.options.external[db.categories[external[i]][j]].push(external[i]);
                    }
                }
            }

            // Expand also for unit tests.
            if (config.options.test && config.options.test.unit && config.options.test.unit.external instanceof Array) {
                external = config.options.test.unit.external;
                config.options.test.unit.lib = [];
                config.options.test.unit.css = [];
                for (i=0; i < external.length; i++) {
                    if (!db.categories[external[i]]) {
                        grunt.fail.fatal("Cannot figure out applicaple categories for external dependency: " + external[i]);
                        continue;
                    }
                    for(j = 0; j < db.categories[external[i]].length; j++) {
                        config.options.test.unit[db.categories[external[i]][j]].push(external[i]);
                    }
                }
            }
        }

        var ret = config.options;

        if (!name) {
            return ret;
        }

        var parts = name.split('.');
        for (i=0; i < parts.length; i++) {
            if (!ret) {
                return def;
            }
            ret = ret[parts[i]];
        }

        return ret || def;
    }
452304
function initServicesDir (config, dir) {
    // iterate over file names in directory
    _.each(fs.readdirSync(dir), file => {
        // get absolute file
        var absFile = `${dir}/${file}`
        // match services files
        var matches = file.match(/^(.*?)\.service\.js$/)
        // load file if it matches filename pattern
        if (matches) {
            // get service name from file name
            var serviceName = changeCase.camelCase(matches[1])
            // load service
            var service = require(path.relative(__dirname, absFile))
            // validate service name if defined
            if (defined(service.name)) {
                assert(service.name === serviceName, `service name ${service.name} does not match filename ${absFile}`)
            }
            // otherwise set service name from file name
            else {
                service.name = serviceName
            }
            // if service is already defined merge over existing definition
            if (defined(config.services[service.name])) {
                _.merge(config.services[service.name], service)
            }
            // otherwise set new service
            else {
                config.services[service.name] = service
            }
        }
        // ignore anything else
        else {
            debug('initServicesDir: ignoring %s', absFile)
        }
    })
}
489399
public static function initialise()
		{
		// Create the class index for autoloading or including
		$paths = array(dirname(__FILE__));
		while (list($i, $path) = each($paths))
			{
			$subDirectorys = glob($path . "*", GLOB_MARK | GLOB_ONLYDIR | GLOB_NOSORT);
			if (is_array($subDirectorys))
				{
				foreach ($subDirectorys as $subDirectory)
					{
					$paths[] = $subDirectory;
					}
				}
			$files = glob($path . "*.php", 0);
			if (is_array($files))
				{
				foreach ($files as $file)
					{
					$class = substr(basename($file), 0, -4);
					self::$classIndex[$class] = $file;
					}
				}
			}
		krsort(self::$classIndex);
		// Only use autoloading if spl_autoload_register() is available and no __autoload() is defined (because 
		// __autoload() breaks if spl_autoload_register() is used. 
		if (function_exists("spl_autoload_register") && !is_callable("__autoload"))
			{
			spl_autoload_register(array(__CLASS__, "autoload"));
			}
		// Otherwise include all class files
		else
			{
			foreach (self::$classIndex as $class => $file)
				{
				if (!class_exists($class))
					{
					require_once($file);
					}
				}
			}
		}
68158
def create(cls, config_file=None):
        
        if cls.instance is None:
            cls.instance = cls(config_file)

            # Load config file, possibly overwriting the defaults
            cls.instance.load_ini()

        if config_file and config_file != cls.instance.config_file:
            raise RuntimeError("Configuration initialized a second time with a different file!")

        return cls.instance
825243
private synchronized void initFsDataSet(Configuration conf,
      AbstractList<File> dataDirs, int numNamespaces) throws IOException {
    if (data != null) { // Already initialized
      return;
    }

    // get version and id info from the name-node
    boolean simulatedFSDataset = 
      conf.getBoolean("dfs.datanode.simulateddatastorage", false);

    if (simulatedFSDataset) {
      storage.createStorageID(selfAddr.getPort());
      // it would have been better to pass storage as a parameter to
      // constructor below - need to augment ReflectionUtils used below.
      conf.set("dfs.datanode.StorageId", storage.getStorageID());
      try {
        data = (FSDatasetInterface) ReflectionUtils.newInstance(
            Class.forName(
            "org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"),
            conf);
      } catch (ClassNotFoundException e) {
        throw new IOException(StringUtils.stringifyException(e));
      }
    } else {
      data = new FSDataset(this, conf, numNamespaces);
    }
  }
495967
private void setupData(ValidationConfig config, ClassLoader classLoader) {
        // A config object is always used to use a common code path, so the parsed
        // ValidationConfig may be null if a validation.xml wasn't found.
        if (config != null) {
            versionID = config.getVersionID();

            defaultProvider = config.getDefaultProvider();
            defaultProvider = defaultProvider != null ? defaultProvider.trim() : defaultProvider;

            messageInterpolator = config.getMessageInterpolator();
            messageInterpolator = messageInterpolator != null ? messageInterpolator.trim() : messageInterpolator;

            traversableResolver = config.getTraversableResolver();
            traversableResolver = traversableResolver != null ? traversableResolver.trim() : traversableResolver;

            constraintMapping = config.getConstraintMappings();

            constraintValidatorFactory = config.getConstraintValidatorFactory();
            constraintValidatorFactory = constraintValidatorFactory != null ? constraintValidatorFactory.trim() : constraintValidatorFactory;

            properties = config.getProperties();
        }
        appClassloader = classLoader;
    }
187733
def _load_config(initial_namespace=None, defaults=None):
    # type: (Optional[str], Optional[str]) -> ConfigLoader
    
    # load defaults
    if defaults:
        config = ConfigLoader()
        config.update_from_object(defaults)

    namespace = getattr(config, 'CONFIG_NAMESPACE', initial_namespace)
    app_config = getattr(config, 'APP_CONFIG', None)

    # load customised config
    if app_config:
        if namespace is None:
            config.update_from_object(app_config)
        else:
            _temp = ConfigLoader()
            _temp.update_from_object(app_config, lambda key: key.startswith(namespace))
            config.update(_temp.namespace(namespace))

    return config
797801
def init_config(cls):
        
        try:
            # first load current conf and only overwrite needed params
            # we don't want to reset everything
            config_file = os.path.expanduser(cls.home_config)
            config = cls.load(config_file, 'global')
            cls._del('global', 'api.env')

            hidden_apikey = '%s...' % cls.get('api.key', '')[:6]
            apikey = click.prompt('Api key (xmlrpc)',
                                  default=hidden_apikey)
            if apikey == hidden_apikey:
                # if default value then use actual value not hidden one
                apikey = cls.get('api.key')
            env_choice = click.Choice(list(cls.apienvs.keys()))
            apienv = click.prompt('Environnment [production]/ote',
                                  default=cls.default_apienv,
                                  type=env_choice,
                                  show_default=False)
            sshkey = click.prompt('SSH keyfile',
                                  default='~/.ssh/id_rsa.pub')
            hidden_apikeyrest = '%s...' % cls.get('apirest.key', '')[:6]
            apikeyrest = click.prompt('Api key (REST)',
                                      default=hidden_apikeyrest)
            if apikeyrest == hidden_apikeyrest:
                # if default value then use actual value not hidden one
                apikeyrest = cls.get('apirest.key')

            config.update({
                'api': {'key': apikey,
                        'host': cls.apienvs[apienv]},
            })
            if apikeyrest:
                config.update({
                    'apirest': {'key': apikeyrest},
                })

            if sshkey is not None:
                sshkey_file = os.path.expanduser(sshkey)
                if os.path.exists(sshkey_file):
                    config['sshkey'] = [sshkey_file]

            directory = os.path.expanduser(os.path.dirname(config_file))
            if not os.path.exists(directory):
                mkpath(directory, 0o700)

            # save to disk
            cls.save(config_file, config)
            # load in memory
            cls.load(config_file, 'global')
        except (KeyboardInterrupt, click.exceptions.Abort):
            cls.echo('Aborted.')
            sys.exit(1)