Called by the daemon broker to initialize the module
181494
def init(self):  # pylint: disable=too-many-branches
        """"""
        if not self.enabled:
            logger.info(" the module is disabled.")
            return True

        try:
            connections = self.test_connection()
        except Exception as exp:  # pylint: disable=broad-except
            logger.error("initialization, test connection failed. Error: %s", str(exp))

        if self.influxdb_enabled:
            try:
                # Check that configured TSDB is existing, else creates...
                dbs = self.influx.get_list_database()
                for db in dbs:
                    if db.get('name') == self.influxdb_database:
                        logger.info("the database %s is existing.", self.influxdb_database)
                        break
                else:
                    # Create the database
                    logger.info("creating database %s...", self.influxdb_database)
                    self.influx.create_database(self.influxdb_database)

                # Check that configured TSDB retention is existing, else creates...
                if self.influxdb_retention_name:
                    rps = self.influx.get_list_retention_policies()
                    for rp in rps:
                        if rp.get('name') == self.influxdb_retention_name:
                            logger.info("the retention policy %s is existing.",
                                        self.influxdb_retention_name)
                            break
                    else:
                        # Create a retention policy for this database
                        logger.info("creating database retention policy: %s - %s - %s...",
                                    self.influxdb_retention_name, self.influxdb_retention_duration,
                                    self.influxdb_retention_replication)
                        self.influx.create_retention_policy(
                            self.influxdb_retention_name, self.influxdb_retention_duration,
                            self.influxdb_retention_replication, database=self.influxdb_database)

                # Check that configured TSDB user is existing, else creates...
                if self.influxdb_username:
                    users = self.influx.get_list_users()
                    for user in users:
                        if user.get('user') == self.influxdb_username:
                            logger.info("the user %s is existing.",
                                        self.influxdb_username)
                            break
                    else:
                        # Create a retention policy for this database
                        logger.info("creating user: %s...", self.influxdb_username)
                        self.influx.create_user(self.influxdb_username, self.influxdb_password,
                                                admin=False)

                connections = connections or True
            except Exception as exp:  # pylint: disable=broad-except
                logger.error("InfluxDB, DB initialization failed. Error: %s", str(exp))

        return connections
651666
public static synchronized void initialize(int myHostId, CatalogContext catalogContext, HostMessenger messenger) throws BundleException, IOException {
        ImporterStatsCollector statsCollector = new ImporterStatsCollector(myHostId);
        ImportManager em = new ImportManager(myHostId, messenger, statsCollector);
        VoltDB.instance().getStatsAgent().registerStatsSource(
                StatsSelector.IMPORTER,
                myHostId,
                statsCollector);

        m_self = em;
        em.create(catalogContext);
    }
486393
def _init(self):
        
        assert self._name
        assert self._group

        # self.n = 0
        self.u = []
        self.name = []
        self.idx = []
        self.uid = {}

        if not self._unamey:
            self._unamey = self._algebs
        else:
            assert len(self._unamey) == len(self._algebs)

        if not self._unamex:
            self._unamex = self._states
        else:
            assert len(self._unamex) == len(self._states)

        for item in self._data.keys():
            self.__dict__[item] = []

        for bus in self._ac.keys():
            for var in self._ac[bus]:
                self.__dict__[var] = []
        for node in self._dc.keys():
            for var in self._dc[node]:
                self.__dict__[var] = []

        for var in self._states + self._algebs + self._service:
            self.__dict__[var] = []

        self._flags['sysbase'] = False
        self._flags['allocate'] = False
        self._flags['address'] = False
1132331
function init() {
    // When code is sent to Espruino, search it for bits of assembler and then assemble them
    Espruino.addProcessor("transformForEspruino", function(code, callback) {
      findASMBlocks(code, "", callback);
    });
    // When a module is sent to Espruino...
    Espruino.addProcessor("transformModuleForEspruino", function(module, callback) {
      findASMBlocks(module.code, " in "+module.name, function(code) {
        module.code = code;
        callback(module);
      });
    });
  }
865732
def init(opts):
    '''
    
    '''
    log.debug('Initting esxcluster proxy module in process %s', os.getpid())
    log.debug('Validating esxcluster proxy input')
    schema = EsxclusterProxySchema.serialize()
    log.trace('schema = %s', schema)
    proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {}))
    log.trace('proxy_conf = %s', proxy_conf)
    try:
        jsonschema.validate(proxy_conf, schema)
    except jsonschema.exceptions.ValidationError as exc:
        raise salt.exceptions.InvalidConfigError(exc)

    # Save mandatory fields in cache
    for key in ('vcenter', 'datacenter', 'cluster', 'mechanism'):
        DETAILS[key] = proxy_conf[key]

    # Additional validation
    if DETAILS['mechanism'] == 'userpass':
        if 'username' not in proxy_conf:
            raise salt.exceptions.InvalidConfigError(
                'Mechanism is set to \'userpass\', but no '
                '\'username\' key found in proxy config.')
        if 'passwords' not in proxy_conf:
            raise salt.exceptions.InvalidConfigError(
                'Mechanism is set to \'userpass\', but no '
                '\'passwords\' key found in proxy config.')
        for key in ('username', 'passwords'):
            DETAILS[key] = proxy_conf[key]
    else:
        if 'domain' not in proxy_conf:
            raise salt.exceptions.InvalidConfigError(
                'Mechanism is set to \'sspi\', but no '
                '\'domain\' key found in proxy config.')
        if 'principal' not in proxy_conf:
            raise salt.exceptions.InvalidConfigError(
                'Mechanism is set to \'sspi\', but no '
                '\'principal\' key found in proxy config.')
        for key in ('domain', 'principal'):
            DETAILS[key] = proxy_conf[key]

    # Save optional
    DETAILS['protocol'] = proxy_conf.get('protocol')
    DETAILS['port'] = proxy_conf.get('port')

    # Test connection
    if DETAILS['mechanism'] == 'userpass':
        # Get the correct login details
        log.debug('Retrieving credentials and testing vCenter connection for '
                  'mehchanism \'userpass\'')
        try:
            username, password = find_credentials()
            DETAILS['password'] = password
        except salt.exceptions.SaltSystemExit as err:
            log.critical('Error: %s', err)
            return False
    return True
512853
private function init()
    {
        if (!$this->enchant_broker) {
            if (!extension_loaded('enchant')) {
                $this->error = "Enchant extension not available";
                return;
            }

            $this->enchant_broker = enchant_broker_init();
        }

        if (!enchant_broker_dict_exists($this->enchant_broker, $this->lang)) {
            $this->error = "Unable to load dictionary for selected language using Enchant";
            return;
        }

        $this->enchant_dictionary = enchant_broker_request_dict($this->enchant_broker, $this->lang);
    }
1246148
public static synchronized void initialize(
            int myHostId,
            CatalogContext catalogContext,
            boolean isRejoin,
            boolean forceCreate,
            HostMessenger messenger,
            List<Pair<Integer, Integer>> partitions)
            throws ExportManager.SetupException
    {
        ExportManager em = new ExportManager(myHostId, catalogContext, messenger);
        m_self = em;
        if (forceCreate) {
            em.clearOverflowData();
        }
        em.initialize(catalogContext, partitions, isRejoin);

        RealVoltDB db=(RealVoltDB)VoltDB.instance();
        db.getStatsAgent().registerStatsSource(StatsSelector.EXPORT,
                myHostId, // m_siteId,
                em.getExportStats());
    }
1342336
private void init(){

		errorProducerEnabled = MoskitoConfigurationHolder.getConfiguration().getBuiltinProducersConfig().isErrorProducer();

		statsMap = new ConcurrentHashMap<>();
        statsList = new CopyOnWriteArrayList<>();

		cumulatedStats = new ErrorStats("cumulated");
		statsList.add(cumulatedStats);

		catchers = new ConcurrentHashMap<>();

		//it is complicated to actually remove the error producer from the system if disabled, but the flag renders it invisible and
		//disables most methos.
		if (!errorProducerEnabled)
			return;

		ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(this);


		//add charts for cumulated errors.
		AfterStartTasks.submitTask(new Runnable() {
			@Override
			public void run() {
				AccumulatorRepository.getInstance().createAccumulator(createAccumulatorDefinition("Errors.Cumulated.Total", "total", "cumulated"));
			}
		});
		AfterStartTasks.submitTask(new Runnable() {
			@Override
			public void run() {
				AccumulatorRepository.getInstance().createAccumulator(createAccumulatorDefinition("Errors.Cumulated.Initial", "initial", "cumulated"));
			}
		});

		errorHandlingConfig = null;
	}
444823
def init(self):
        
        # some modules might need to be imported "on the other side of the fork"
        # .. but the, when importing this module, the import is not tested
        #
        # 
        # from openalpr import Alpr
        from valkka.mvision.alpr.openalpr_fix import Alpr
        self.movement = MovementDetector()
        self.alpr = Alpr(self.country, self.conf_file, self.runtime_data)
        if not self.alpr.is_loaded():
            self.alpr = None
            return
        self.alpr.set_top_n(self.top_n)
        self.reset()
        
        """
        # test in ipython:
        from valkka.mvision.alpr.openalpr_fix import Alpr
        country="eu"
        conf_file="/usr/share/openalpr/config/openalpr.defaults.conf"
        runtime_data="/usr/share/openalpr/runtime_data"
        a = Alpr(country, conf_file, runtime_data)
        a.is_loaded()        
        """
411170
def init(opts):
    '''
    
    '''
    log.debug('Initting esxi proxy module in process %s', os.getpid())
    log.debug('Validating esxi proxy input')
    schema = EsxiProxySchema.serialize()
    log.trace('esxi_proxy_schema = %s', schema)
    proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {}))
    log.trace('proxy_conf = %s', proxy_conf)
    try:
        jsonschema.validate(proxy_conf, schema)
    except jsonschema.exceptions.ValidationError as exc:
        raise InvalidConfigError(exc)

    DETAILS['proxytype'] = proxy_conf['proxytype']
    if ('host' not in proxy_conf) and ('vcenter' not in proxy_conf):
        log.critical('Neither \'host\' nor \'vcenter\' keys found in pillar '
                     'for this proxy.')
        return False
    if 'host' in proxy_conf:
        # We have started the proxy by connecting directly to the host
        if 'username' not in proxy_conf:
            log.critical('No \'username\' key found in pillar for this proxy.')
            return False
        if 'passwords' not in proxy_conf:
            log.critical('No \'passwords\' key found in pillar for this proxy.')
            return False
        host = proxy_conf['host']

        # Get the correct login details
        try:
            username, password = find_credentials(host)
        except SaltSystemExit as err:
            log.critical('Error: %s', err)
            return False

        # Set configuration details
        DETAILS['host'] = host
        DETAILS['username'] = username
        DETAILS['password'] = password
        DETAILS['protocol'] = proxy_conf.get('protocol')
        DETAILS['port'] = proxy_conf.get('port')
        return True

    if 'vcenter' in proxy_conf:
        vcenter = proxy_conf['vcenter']
        if not proxy_conf.get('esxi_host'):
            log.critical('No \'esxi_host\' key found in pillar for this proxy.')
        DETAILS['esxi_host'] = proxy_conf['esxi_host']
        # We have started the proxy by connecting via the vCenter
        if 'mechanism' not in proxy_conf:
            log.critical('No \'mechanism\' key found in pillar for this proxy.')
            return False
        mechanism = proxy_conf['mechanism']
        # Save mandatory fields in cache
        for key in ('vcenter', 'mechanism'):
            DETAILS[key] = proxy_conf[key]

        if mechanism == 'userpass':
            if 'username' not in proxy_conf:
                log.critical('No \'username\' key found in pillar for this '
                             'proxy.')
                return False
            if 'passwords' not in proxy_conf and proxy_conf['passwords']:
                log.critical('Mechanism is set to \'userpass\' , but no '
                             '\'passwords\' key found in pillar for this '
                             'proxy.')
                return False
            for key in ('username', 'passwords'):
                DETAILS[key] = proxy_conf[key]
        elif mechanism == 'sspi':
            if 'domain' not in proxy_conf:
                log.critical('Mechanism is set to \'sspi\' , but no '
                             '\'domain\' key found in pillar for this proxy.')
                return False
            if 'principal' not in proxy_conf:
                log.critical('Mechanism is set to \'sspi\' , but no '
                             '\'principal\' key found in pillar for this '
                             'proxy.')
                return False
            for key in ('domain', 'principal'):
                DETAILS[key] = proxy_conf[key]

        if mechanism == 'userpass':
            # Get the correct login details
            log.debug('Retrieving credentials and testing vCenter connection'
                      ' for mehchanism \'userpass\'')
            try:
                username, password = find_credentials(DETAILS['vcenter'])
                DETAILS['password'] = password
            except SaltSystemExit as err:
                log.critical('Error: %s', err)
                return False

    # Save optional
    DETAILS['protocol'] = proxy_conf.get('protocol', 'https')
    DETAILS['port'] = proxy_conf.get('port', '443')
    DETAILS['credstore'] = proxy_conf.get('credstore')
1146629
protected void init() {
        Properties props = new Properties();
        props.put("bootstrap.servers", PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_URI_PUBLISHER,
                PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_URI))
                .substring(PropertyUtil.KAFKA_PREFIX.length()));
        props.put("acks", "all");
        props.put("retries", PropertyUtil.getPropertyAsInteger(PropertyUtil.HAWKULAR_APM_KAFKA_PRODUCER_RETRIES, 3));
        props.put("batch.size", 16384);
        props.put("linger.ms", 1);
        props.put("buffer.memory", 33554432);
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        producer = new KafkaProducer<>(props);
    }
524681
def init_module(remote_credences=None,local_path=None):
    """"""
    if remote_credences is not None:
        RemoteConnexion.HOST = remote_credences["DB"]["host"]
        RemoteConnexion.USER = remote_credences["DB"]["user"]
        RemoteConnexion.PASSWORD = remote_credences["DB"]["password"]
        RemoteConnexion.NAME = remote_credences["DB"]["name"]
        MonoExecutant.ConnectionClass = RemoteConnexion
        Executant.ConnectionClass = RemoteConnexion
        abstractRequetesSQL.setup_marks("psycopg2")
    elif local_path is not None:
        LocalConnexion.PATH = local_path
        MonoExecutant.ConnectionClass = LocalConnexion
        Executant.ConnectionClass = LocalConnexion
        abstractRequetesSQL.setup_marks("sqlite3")
    else:
        raise ValueError("Sql module should be init with one of remote or local mode !")
    logging.info(f"Sql module initialized with {MonoExecutant.ConnectionClass.__name__}")
1201274
function init() {
    try {
        keepOrganized().then((AllFiles) => {
            console.log('Marked Reference Links');
            console.log('Created Directory Tree');
            console.log('Setting up watchers...');
            let watcher = new Watcher(AllFiles);
            console.log('Watching for file changes...');
            watcher.on('update', () => {
                console.log('Updating dirTree...')
                keepOrganized().then((AllFiles) => {
                    console.log('Updated dirTree.');
                    watcher.update(AllFiles);
                })
            })
        })
    } catch (err) {
        console.error(err);
    }
}
129176
def init(argv):
    
    # Setting initial configuration values
    config.set_default({
        # driver section
        "driver": {},
        # fs section
        "fs": {},
        # MongoDB section
        "mongodb": {},
    })

    # Parse the command line
    init_parsecmdline(argv[1:])

    # Initiatize the output directory
    fs.init(dry_run=_opt["dry_run"], **config.get_entry('fs'))

    # This baby will handle UNIX signals
    signal.signal(signal.SIGINT,  _handle_signal)
    signal.signal(signal.SIGTERM, _handle_signal)
664304
def initialize(self):
        
        self.main_pid = os.getpid()
        self.processes.extend(self.init_service_processes())
        self.processes.extend(self.init_tornado_workers())
273763
protected function init() : void
    {
        if ($this->initialized) {
            return;
        }
        $this->initialized = true;
        $this->log("Daemon Initialized", LOG_INFO, [ "syslog", STDOUT ], true);
    }
358520
def main(self):
        
        try:
            # Start the daemon mode
            if not self.do_daemon_init_and_start():
                self.exit_on_error(message="Daemon initialization error", exit_code=3)

            self.do_post_daemon_init()

            # We wait for initial conf
            self.wait_for_initial_conf()
            if self.new_conf:
                # Setup the received configuration
                self.setup_new_conf()

                # Allocate Mortal Threads
                self.adjust_worker_number_by_load()

                # Now main loop
                self.do_main_loop()
                logger.info("Exited from the main loop.")

            self.request_stop()
        except Exception:  # pragma: no cover, this should never happen indeed ;)
            self.exit_on_exception(traceback.format_exc())
            raise