Called during __init__.  Check consistency of schema in database with
        classes in memory.  Load all Python modules for stored items, and load
        version information for upgrader service to run later.
429536
def _startup(self):
        
        typesToCheck = []

        for oid, module, typename, version in self.querySchemaSQL(_schema.ALL_TYPES):
            if self.debug:
                print
                print 'SCHEMA:', oid, module, typename, version
            if typename not in _typeNameToMostRecentClass:
                try:
                    namedAny(module)
                except ValueError as err:
                    raise ImportError('cannot find module ' + module, str(err))
            self.typenameAndVersionToID[typename, version] = oid

        # Can't call this until typenameAndVersionToID is populated, since this
        # depends on building a reverse map of that.
        persistedSchema = self._loadTypeSchema()

        # Now that we have persistedSchema, loop over everything again and
        # prepare old types.
        for (typename, version), typeID in self.typenameAndVersionToID.iteritems():
            cls = _typeNameToMostRecentClass.get(typename)

            if cls is not None:
                if version != cls.schemaVersion:
                    typesToCheck.append(
                        self._prepareOldVersionOf(
                            typename, version, persistedSchema))
                else:
                    typesToCheck.append(cls)

        for cls in typesToCheck:
            self._checkTypeSchemaConsistency(cls, persistedSchema)

        # Schema is consistent!  Now, if I forgot to create any indexes last
        # time I saw this table, do it now...
        extantIndexes = self._loadExistingIndexes()
        for cls in typesToCheck:
            self._createIndexesFor(cls, extantIndexes)

        self._upgradeManager.checkUpgradePaths()
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__}")
1045377
def init_app(self, app, decorators=None):
        
        self.decorators = decorators or self.decorators
        self.app = app

        self.load_config(app)
        # self.load_apispec(app)
        if self.template_file is not None:
            self.template = self.load_swagger_file(self.template_file)
        self.register_views(app)
        self.add_headers(app)

        if self.parse:
            if RequestParser is None:
                raise RuntimeError('Please install flask_restful')
            self.parsers = {}
            self.schemas = {}
            self.format_checker = jsonschema.FormatChecker()
            self.parse_request(app)

        self._configured = True
        app.swag = self
1260525
def initialize(self):
        """"""
        self.Base.metadata.create_all(self.session.bind)
        logger.debug("initialized sqlalchemy orm tables")
1231628
def init_versioning(self, app, database, versioning_manager=None):
        """"""
        try:
            pkg_resources.get_distribution('sqlalchemy_continuum')
        except pkg_resources.DistributionNotFound:  # pragma: no cover
            default_versioning = False
        else:
            default_versioning = True

        app.config.setdefault('DB_VERSIONING', default_versioning)

        if not app.config['DB_VERSIONING']:
            return

        if not default_versioning:  # pragma: no cover
            raise RuntimeError(
                'Please install extra versioning support first by running '
                'pip install invenio-db[versioning].'
            )

        # Now we can import SQLAlchemy-Continuum.
        from sqlalchemy_continuum import make_versioned
        from sqlalchemy_continuum import versioning_manager as default_vm
        from sqlalchemy_continuum.plugins import FlaskPlugin

        # Try to guess user model class:
        if 'DB_VERSIONING_USER_MODEL' not in app.config:  # pragma: no cover
            try:
                pkg_resources.get_distribution('invenio_accounts')
            except pkg_resources.DistributionNotFound:
                user_cls = None
            else:
                user_cls = 'User'
        else:
            user_cls = app.config.get('DB_VERSIONING_USER_MODEL')

        plugins = [FlaskPlugin()] if user_cls else []

        # Call make_versioned() before your models are defined.
        self.versioning_manager = versioning_manager or default_vm
        make_versioned(
            user_cls=user_cls,
            manager=self.versioning_manager,
            plugins=plugins,
        )

        # Register models that have been loaded beforehand.
        builder = self.versioning_manager.builder

        for tbl in database.metadata.tables.values():
            builder.instrument_versioned_classes(
                database.mapper, get_class_by_table(database.Model, tbl)
            )
573611
async def loadmodule(self, module):
        '''
        
        '''
        self._logger.debug('Try to load module %r', module)
        if hasattr(module, '_instance'):
            self._logger.debug('Module is already initialized, module state is: %r', module._instance.state)
            if module._instance.state == ModuleLoadStateChanged.UNLOADING or module._instance.state == ModuleLoadStateChanged.UNLOADED:
                # Wait for unload
                um = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.UNLOADED)
                await um
            elif module._instance.state == ModuleLoadStateChanged.SUCCEEDED:
                pass
            elif module._instance.state == ModuleLoadStateChanged.FAILED:
                raise ModuleLoadException('Cannot load module %r before unloading the failed instance' % (module,))
            elif module._instance.state == ModuleLoadStateChanged.NOTLOADED or module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
                # Wait for succeeded or failed
                sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
                fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
                _, m = await M_(sm, fm)
                if m is sm:
                    pass
                else:
                    raise ModuleLoadException('Module load failed for %r' % (module,))
        if not hasattr(module, '_instance'):
            self._logger.info('Loading module %r', module)
            inst = module(self.server)
            # Avoid duplicated loading
            module._instance = inst
            # When reloading, some of the dependencies are broken, repair them
            if hasattr(module, 'referencedBy'):
                inst.dependedBy = set([m for m in module.referencedBy if hasattr(m, '_instance') and m._instance.state != ModuleLoadStateChanged.UNLOADED])
            # Load Module
            for d in module.depends:
                if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.FAILED:
                    raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, d))
            try:
                for d in module.depends:
                    if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.SUCCEEDED:
                        d._instance.dependedBy.add(module)
                preloads = [d for d in module.depends if not hasattr(d, '_instance') or \
                            d._instance.state != ModuleLoadStateChanged.SUCCEEDED]
                for d in preloads:
                    self.subroutine(self.loadmodule(d), False)
                sms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.SUCCEEDED) for d in preloads]
                fms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.FAILED) for d in preloads]
                def _callback(event, matcher):
                    raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, event.module))
                await self.with_callback(self.wait_for_all(*sms), _callback, *fms)
            except:
                for d in module.depends:
                    if hasattr(d, '_instance') and module in d._instance.dependedBy:
                        self._removeDepend(module, d)
                self._logger.warning('Loading module %r stopped', module, exc_info=True)
                # Not loaded, send a message to notify that parents can not 
                async def _msg():
                    await self.wait_for_send(ModuleLoadStateChanged(module, ModuleLoadStateChanged.UNLOADED, inst))
                self.subroutine(_msg(), False)
                del module._instance
                raise
            for d in preloads:
                d._instance.dependedBy.add(module)
            self.activeModules[inst.getServiceName()] = module
            await module._instance.changestate(ModuleLoadStateChanged.LOADING, self)
            await module._instance.load(self)
            if module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
                sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
                fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
                _, m = await M_(sm, fm)
                if m is sm:
                    pass
                else:
                    raise ModuleLoadException('Module load failed for %r' % (module,))
            self._logger.info('Loading module %r completed, module state is %r', module, module._instance.state)
            if module._instance.state == ModuleLoadStateChanged.FAILED:
                raise ModuleLoadException('Module load failed for %r' % (module,))
333823
def _init():
    """"""
    import importlib
    import os
    import re

    filenames = os.listdir(os.path.dirname(__file__))

    module_names = set()
    for filename in filenames:
        match = re.match(r'^(?P<name>[A-Z_a-z]\w*)\.py[co]?$', filename)
        if match:
            module_names.add(match.group('name'))

    for module_name in module_names:
        try:
            module = importlib.import_module('.' + module_name, __name__)
        except ImportError:
            continue

        for name, member in module.__dict__.items():
            if not isinstance(member, type):
                # skip non-new-style classes
                continue
            if not issubclass(member, Engine):
                # skip non-subclasses of Engine
                continue
            if member is Engine:
                # skip "abstract" class Engine
                continue

            try:
                handle = member.handle
            except AttributeError:
                continue

            engines[handle] = member
865904
def on_init(app):  # pylint: disable=unused-argument
    
    docs_path = os.path.abspath(os.path.dirname(__file__))
    root_path = os.path.abspath(os.path.join(docs_path, '..'))
    apidoc_path = 'sphinx-apidoc'
    swg2rst_path = 'swg2rst'
    if hasattr(sys, 'real_prefix'):  # Check to see if we are in a virtualenv
        # If we are, assemble the path manually
        bin_path = os.path.abspath(os.path.join(sys.prefix, 'bin'))
        apidoc_path = os.path.join(bin_path, apidoc_path)
        swg2rst_path = os.path.join(bin_path, swg2rst_path)
    check_call([apidoc_path, '-o', docs_path, os.path.join(root_path, 'user_tasks'),
                os.path.join(root_path, 'user_tasks/migrations')])
    json_path = os.path.join(docs_path, 'swagger.json')
    rst_path = os.path.join(docs_path, 'rest_api.rst')
    check_call([swg2rst_path, json_path, '-f', 'rst', '-o', rst_path])
159686
def Initialize(self):
    """"""
    super(GRRFlow, self).Initialize()
    self._client_version = None
    self._client_os = None
    self._client_knowledge_base = None

    if "r" in self.mode:
      state = self.Get(self.Schema.FLOW_STATE_DICT)
      self.context = self.Get(self.Schema.FLOW_CONTEXT)
      self.runner_args = self.Get(self.Schema.FLOW_RUNNER_ARGS)
      args = self.Get(self.Schema.FLOW_ARGS)
      if args:
        self.args = args.payload

      if state:
        self.state = AttributedDict(state.ToDict())
      else:
        self.state = AttributedDict()

      self.Load()

    if self.state is None:
      self.state = AttributedDict()
710409
def load_modules(self, args):
        """"""

        # Init the plugins dict
        # Active plugins dictionnary
        self._plugins = collections.defaultdict(dict)
        # Load the plugins
        self.load_plugins(args=args)

        # Init the export modules dict
        # Active exporters dictionnary
        self._exports = collections.defaultdict(dict)
        # All available exporters dictionnary
        self._exports_all = collections.defaultdict(dict)
        # Load the export modules
        self.load_exports(args=args)

        # Restoring system path
        sys.path = sys_path
762749
def init():
    
    global _users, _names
    _configure_app(app)
    _users, _names = _init_login_manager(app)
    _configure_logger()
    init_scheduler(app.config.get('SQLALCHEMY_DATABASE_URI'))
    db.init(app.config.get('SQLALCHEMY_DATABASE_URI'))
33741
def init(context, reset, force):
    """"""
    existing_tables = context.obj['store'].engine.table_names()
    if force or reset:
        if existing_tables and not force:
            message = f"Delete existing tables? [{', '.join(existing_tables)}]"
            click.confirm(click.style(message, fg='yellow'), abort=True)
        context.obj['store'].drop_all()
    elif existing_tables:
        click.echo(click.style("Database already exists, use '--reset'", fg='red'))
        context.abort()

    context.obj['store'].setup()
    message = f"Success! New tables: {', '.join(context.obj['store'].engine.table_names())}"
    click.echo(click.style(message, fg='green'))
1266971
def _init_module_cache():
		

		# While there are not loaded modules, load these ones
		if len(FieldTranslation._modules) < len(FieldTranslation._model_module_paths):
			for module_path in FieldTranslation._model_module_paths:
				FieldTranslation._modules[module_path] = importlib.import_module(module_path)
			return True
		return False
765875
private void init(boolean upgrade)
    {
        initAdapter();
        initQueries();
        if (upgrade)
        {
            dbUpgrade();
        }

        // First contact with the DB is version checking (if no connection opened by pool).
        // If DB is in wrong version or not available, just wait for it to be ready.
        boolean versionValid = false;
        while (!versionValid)
        {
            try
            {
                checkSchemaVersion();
                versionValid = true;
            }
            catch (Exception e)
            {
                String msg = e.getLocalizedMessage();
                if (e.getCause() != null)
                {
                    msg += " - " + e.getCause().getLocalizedMessage();
                }
                jqmlogger.error("Database not ready: " + msg + ". Waiting for database...");
                try
                {
                    Thread.sleep(10000);
                }
                catch (Exception e2)
                {
                }
            }
        }
    }
1305968
def after_import(self, dataset, result, using_transactions, dry_run, **kwargs):
        
        # Adapted from django's loaddata
        if not dry_run and any(r.import_type == RowResult.IMPORT_TYPE_NEW for r in result.rows):
            connection = connections[DEFAULT_DB_ALIAS]
            sequence_sql = connection.ops.sequence_reset_sql(no_style(), [self._meta.model])
            if sequence_sql:
                cursor = connection.cursor()
                try:
                    for line in sequence_sql:
                        cursor.execute(line)
                finally:
                    cursor.close()
322682
def instance(cls, conn, pkg_name='openquake.server.db.schema.upgrades'):
        
        try:
            # upgrader is an UpgradeManager instance defined in the __init__.py
            upgrader = importlib.import_module(pkg_name).upgrader
        except ImportError:
            raise SystemExit(
                'Could not import %s (not in the PYTHONPATH?)' % pkg_name)
        if not upgrader.read_scripts():
            raise SystemExit(
                'The upgrade_dir does not contain scripts matching '
                'the pattern %s' % upgrader.pattern)
        curs = conn.cursor()
        # check if there is already a versioning table
        curs.execute("SELECT name FROM sqlite_master "
                     "WHERE name=%r" % upgrader.version_table)
        versioning_table = curs.fetchall()
        # if not, run the base script and create the versioning table
        if not versioning_table:
            upgrader.init(conn)
            conn.commit()
        return upgrader
713218
def init_app(self, app):
        
        if (
            'SQLALCHEMY_DATABASE_URI' not in app.config and
            'SQLALCHEMY_BINDS' not in app.config
        ):
            warnings.warn(
                'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
                'Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".'
            )

        app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:')
        app.config.setdefault('SQLALCHEMY_BINDS', None)
        app.config.setdefault('SQLALCHEMY_NATIVE_UNICODE', None)
        app.config.setdefault('SQLALCHEMY_ECHO', False)
        app.config.setdefault('SQLALCHEMY_RECORD_QUERIES', None)
        app.config.setdefault('SQLALCHEMY_POOL_SIZE', None)
        app.config.setdefault('SQLALCHEMY_POOL_TIMEOUT', None)
        app.config.setdefault('SQLALCHEMY_POOL_RECYCLE', None)
        app.config.setdefault('SQLALCHEMY_MAX_OVERFLOW', None)
        app.config.setdefault('SQLALCHEMY_COMMIT_ON_TEARDOWN', False)
        track_modifications = app.config.setdefault(
            'SQLALCHEMY_TRACK_MODIFICATIONS', None
        )
        app.config.setdefault('SQLALCHEMY_ENGINE_OPTIONS', {})

        if track_modifications is None:
            warnings.warn(FSADeprecationWarning(
                'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
                'will be disabled by default in the future.  Set it to True '
                'or False to suppress this warning.'
            ))

        # Deprecation warnings for config keys that should be replaced by SQLALCHEMY_ENGINE_OPTIONS.
        utils.engine_config_warning(app.config, '3.0', 'SQLALCHEMY_POOL_SIZE', 'pool_size')
        utils.engine_config_warning(app.config, '3.0', 'SQLALCHEMY_POOL_TIMEOUT', 'pool_timeout')
        utils.engine_config_warning(app.config, '3.0', 'SQLALCHEMY_POOL_RECYCLE', 'pool_recycle')
        utils.engine_config_warning(app.config, '3.0', 'SQLALCHEMY_MAX_OVERFLOW', 'max_overflow')

        app.extensions['sqlalchemy'] = _SQLAlchemyState(self)

        @app.teardown_appcontext
        def shutdown_session(response_or_exc):
            if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
                if response_or_exc is None:
                    self.session.commit()

            self.session.remove()
            return response_or_exc