Initialize mongopatcher on the database by setting it manifest
194673
def init(version, force):
    """"""
    version = version or current_app.config['MONGOPATCHER_DATAMODEL_VERSION']
    _get_mongopatcher().manifest.initialize(version, force)
    print('Datamodel initialized to version %s' % version)
190868
def init_db_conn(connection_name, HOSTS=None):
    
    el = elasticsearch.Elasticsearch(hosts=HOSTS)
    el_pool.connections[connection_name] = ElasticSearchClient(el)
715122
def get_app(config):
    
    # First, disable debug. It will be enabled in the configuration, later.
    web.config.debug = False

    config = _put_configuration_defaults(config)

    mongo_client = MongoClient(host=config.get('mongo_opt', {}).get('host', 'localhost'))
    database = mongo_client[config.get('mongo_opt', {}).get('database', 'INGInious')]
    gridfs = GridFS(database)

    # Init database if needed
    db_version = database.db_version.find_one({})
    if db_version is None:
        database.submissions.ensure_index([("username", pymongo.ASCENDING)])
        database.submissions.ensure_index([("courseid", pymongo.ASCENDING)])
        database.submissions.ensure_index([("courseid", pymongo.ASCENDING), ("taskid", pymongo.ASCENDING)])
        database.submissions.ensure_index([("submitted_on", pymongo.DESCENDING)])  # sort speed
        database.user_tasks.ensure_index(
            [("username", pymongo.ASCENDING), ("courseid", pymongo.ASCENDING), ("taskid", pymongo.ASCENDING)],
            unique=True)
        database.user_tasks.ensure_index([("username", pymongo.ASCENDING), ("courseid", pymongo.ASCENDING)])
        database.user_tasks.ensure_index([("courseid", pymongo.ASCENDING), ("taskid", pymongo.ASCENDING)])
        database.user_tasks.ensure_index([("courseid", pymongo.ASCENDING)])
        database.user_tasks.ensure_index([("username", pymongo.ASCENDING)])

    appli = CookieLessCompatibleApplication(MongoStore(database, 'sessions'))

    # Init gettext
    available_languages = {
        "en": "English",
        "fr": "Français"
    }

    for lang in available_languages.keys():
        appli.add_translation(lang, gettext.translation('messages', get_root_path() + '/frontend/i18n', [lang]))

    builtins.__dict__['_'] = appli.gettext

    if config.get("maintenance", False):
        template_helper = TemplateHelper(PluginManager(), None,
                                         'frontend/templates',
                                         'frontend/templates/layout',
                                         'frontend/templates/layout_lti',
                                         config.get('use_minified_js', True))
        template_helper.add_to_template_globals("get_homepath", appli.get_homepath)
        template_helper.add_to_template_globals("_", _)
        appli.template_helper = template_helper
        appli.init_mapping(urls_maintenance)
        return appli.wsgifunc(), appli.stop

    default_allowed_file_extensions = config['allowed_file_extensions']
    default_max_file_size = config['max_file_size']

    zmq_context, __ = start_asyncio_and_zmq(config.get('debug_asyncio', False))

    # Init the different parts of the app
    plugin_manager = PluginManager()

    # Create the FS provider
    if "fs" in config:
        fs_provider = filesystem_from_config_dict(config["fs"])
    else:
        task_directory = config["tasks_directory"]
        fs_provider = LocalFSProvider(task_directory)

    default_problem_types = {
        problem_type.get_type(): problem_type for problem_type in [DisplayableCodeProblem,
                                                                   DisplayableCodeSingleLineProblem,
                                                                   DisplayableFileProblem,
                                                                   DisplayableMultipleChoiceProblem,
                                                                   DisplayableMatchProblem]
    }

    course_factory, task_factory = create_factories(fs_provider, default_problem_types, plugin_manager, WebAppCourse, WebAppTask)

    user_manager = UserManager(appli.get_session(), database, config.get('superadmins', []))

    update_pending_jobs(database)

    client = create_arch(config, fs_provider, zmq_context, course_factory)

    lti_outcome_manager = LTIOutcomeManager(database, user_manager, course_factory)

    submission_manager = WebAppSubmissionManager(client, user_manager, database, gridfs, plugin_manager, lti_outcome_manager)

    template_helper = TemplateHelper(plugin_manager, user_manager, 'frontend/templates',
                                     'frontend/templates/layout',
                                     'frontend/templates/layout_lti',
                                     config.get('use_minified_js', True))



    # Init web mail
    smtp_conf = config.get('smtp', None)
    if smtp_conf is not None:
        web.config.smtp_server = smtp_conf["host"]
        web.config.smtp_port = int(smtp_conf["port"])
        web.config.smtp_starttls = bool(smtp_conf.get("starttls", False))
        web.config.smtp_username = smtp_conf.get("username", "")
        web.config.smtp_password = smtp_conf.get("password", "")
        web.config.smtp_sendername = smtp_conf.get("sendername", "no-reply@ingnious.org")

    # Add some helpers for the templates
    template_helper.add_to_template_globals("_", _)
    template_helper.add_to_template_globals("str", str)
    template_helper.add_to_template_globals("available_languages", available_languages)
    template_helper.add_to_template_globals("get_homepath", appli.get_homepath)
    template_helper.add_to_template_globals("allow_registration", config.get("allow_registration", True))
    template_helper.add_to_template_globals("user_manager", user_manager)
    template_helper.add_to_template_globals("default_allowed_file_extensions", default_allowed_file_extensions)
    template_helper.add_to_template_globals("default_max_file_size", default_max_file_size)
    template_helper.add_other("course_admin_menu",
                              lambda course, current: course_admin_utils.get_menu(course, current, template_helper.get_renderer(False),
                                                                                  plugin_manager, user_manager))
    template_helper.add_other("preferences_menu",
                              lambda current: preferences_utils.get_menu(appli, current, template_helper.get_renderer(False),
                                                                                 plugin_manager, user_manager))

    # Not found page
    appli.notfound = lambda: web.notfound(template_helper.get_renderer().notfound('Page not found'))

    # Enable stacktrace display if needed
    web_debug = config.get('web_debug', False)
    appli.internalerror = internalerror_generator(template_helper.get_renderer(False))
    if web_debug is True:
        web.config.debug = True
        appli.internalerror = debugerror
    elif isinstance(web_debug, str):
        web.config.debug = False
        appli.internalerror = emailerrors(web_debug, appli.internalerror)

    # Insert the needed singletons into the application, to allow pages to call them
    appli.plugin_manager = plugin_manager
    appli.course_factory = course_factory
    appli.task_factory = task_factory
    appli.submission_manager = submission_manager
    appli.user_manager = user_manager
    appli.template_helper = template_helper
    appli.database = database
    appli.gridfs = gridfs
    appli.default_allowed_file_extensions = default_allowed_file_extensions
    appli.default_max_file_size = default_max_file_size
    appli.backup_dir = config.get("backup_directory", './backup')
    appli.webterm_link = config.get("webterm", None)
    appli.lti_outcome_manager = lti_outcome_manager
    appli.allow_registration = config.get("allow_registration", True)
    appli.allow_deletion = config.get("allow_deletion", True)
    appli.available_languages = available_languages
    appli.welcome_page = config.get("welcome_page", None)
    appli.static_directory = config.get("static_directory", "./static")
    appli.webdav_host = config.get("webdav_host", None)

    # Init the mapping of the app
    appli.init_mapping(urls)

    # Loads plugins
    plugin_manager.load(client, appli, course_factory, task_factory, database, user_manager, submission_manager, config.get("plugins", []))

    # Start the inginious.backend
    client.start()

    return appli.wsgifunc(), lambda: _close_app(appli, mongo_client, client)
964929
@PostConstruct
    public void initDatabase() {
        MongoDBInit.LOGGER.info("initializing MongoDB");
        String dbName = System.getProperty("mongodb.name");
        if (dbName == null) {
            throw new RuntimeException("Missing database name; Set system property 'mongodb.name'");
        }
        MongoDatabase db = this.mongo.getDatabase(dbName);

        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:mongodb/*.ndjson");
            MongoDBInit.LOGGER.info("Scanning for collection data");
            for (Resource res : resources) {
                String filename = res.getFilename();
                String collection = filename.substring(0, filename.length() - 7);
                MongoDBInit.LOGGER.info("Found collection file: {}", collection);
                MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);
                try (Scanner scan = new Scanner(res.getInputStream(), "UTF-8")) {
                    int lines = 0;
                    while (scan.hasNextLine()) {
                        String json = scan.nextLine();
                        Object parse = JSON.parse(json);
                        if (parse instanceof DBObject) {
                            DBObject dbObject = (DBObject) parse;
                            dbCollection.insertOne(dbObject);
                        } else {
                            MongoDBInit.LOGGER.error("Invalid object found: {}", parse);
                            throw new RuntimeException("Invalid object");
                        }
                        lines++;
                    }
                    MongoDBInit.LOGGER.info("Imported {} objects into collection {}", lines, collection);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Error importing objects", e);
        }
    }
742898
function init(config) {
    var deferred = Q.defer();

    connect(config.mongo.url, config.mongo.debug, config.mongo.mongos)
        .then(function () {

            IdxInfoModel = getModel({
                name: 'idx',
                fields: {
                    str: { type: String, index: { unique: true } },
                    name: String,
                    count: Number
                }
            });

            deferred.resolve(config);
        })
        .catch(function (err) {
            deferred.reject(err);
        });

    return deferred.promise;
}
66714
def configure_mongodb(self):
        
        self._display_info("Trying default configuration")

        host = "localhost"
        database_name = "INGInious"

        should_ask = True
        if self.try_mongodb_opts(host, database_name):
            should_ask = self._ask_boolean(
                "Successfully connected to MongoDB. Do you want to edit the configuration anyway?", False)
        else:
            self._display_info("Cannot guess configuration for MongoDB.")

        while should_ask:
            self._display_question(
                "Please enter the MongoDB host. If you need to enter a password, here is the syntax:")
            self._display_question("mongodb://USERNAME:PASSWORD@HOST:PORT/AUTHENTIFICATION_DATABASE")
            host = self._ask_with_default("MongoDB host", host)
            database_name = self._ask_with_default("Database name", database_name)
            if not self.try_mongodb_opts(host, database_name):
                if self._ask_boolean("Cannot connect to MongoDB. Would you like to continue anyway?", False):
                    break
            else:
                self._display_info("Successfully connected to MongoDB")
                break

        return {"mongo_opt": {"host": host, "database": database_name}}
231457
def _init_db(self):
        """"""
        with self._get_db() as db:
            with open(self.schemapath) as f:
                db.cursor().executescript(f.read())
            db.commit()
342365
function MongooseAdapter() {
    this.idAttributeName = cramit.config.database.idAttributeName || '_id';

    if( ! cramit.config.database.instance) {
      //console.log("MongooseAdapter():  Require Mongoose.");
      this.mongoose = require('mongoose');
    } else {
      //console.log("MongooseAdapter():  Using Mongoose instance.");
      this.mongoose = cramit.config.database.instance;
    }
    
    DatabaseAdapter.call(this, cramit.config, cramit.log);
  }
146711
def init(**kwargs):
    

    # TODO: Iterate through all engines in name set.
    database = kwargs.pop('database', False)
    if database and not database_exists(engine['default'].url):
        create_database(engine['default'].url, encoding='utf8')
        clear_cache()

    expression = lambda target, table: table.create(target)
    test = lambda target, table: table.exists(target)
    op(expression, test=test, primary='init', secondary='create', **kwargs)
1055181
function createDitcherInstance(mongoUrl, callback) {
  // Default config used by ditcher if no connection string
  // is provided
  var config = {
    database: {
      host: process.env.MONGODB_HOST || '127.0.0.1',
      port: process.env.FH_LOCAL_DB_PORT || 27017,
      name: 'FH_LOCAL'
    }
  };

  if (mongoUrl) {
    try {
      config = utils.parseMongoConnectionURL(mongoUrl);
    } catch(e) {
      return callback(e);
    }
  }

  var versString = (mongoUrl) ? "db per app" : "shared db";
  var ditcher = new fhditcher.Ditcher(config, logger, versString, function () {
    return callback(null, ditcher);
  });
}
1109421
function _preHandlers() {
  var session;
  // enable db connection
  if(config.db.enabled) {
    var db = require('./db');
    db.init(config.db);
    logger.info(pkgname + "  mongodb initialized at:"+config.db.url);

    // export crudHelper
    exports.crudHelpers = require('mongoose-plugins').crudHelpers;
    exports.installUserSchema = require('mongoose-plugins').installUserSchema;

    // enable db sessions
    var oneWeek = 657450000;
    session = express.session({
      key    : config.app.key,
      store  : new Session({url: config.db.url }), 
      cookie : { maxAge: config.app.cookieAge||oneWeek }, 
      secret : config.app.secret
    });
    logger.info(pkgname + "  persistent sessions enabled");
  } else {
    session = express.session({
        key    : config.app.key,
        secret : config.app.secret
      });
    logger.info(pkgname + "  in-memory sessions enabled");
  }
  app.use(session);

}
1353523
def _connect_database(config):
    
    settings = config.registry.settings

    mongo_uri = "mongodb://localhost:27017"
    mongodb_name = "test"

    if settings.get("mongo_url"):
        mongo_uri = settings["mongo_url"]

    if settings.get("mongodb_name"):
        mongodb_name = settings["mongodb_name"]

    return mongoengine.connect(mongodb_name, host=mongo_uri)
95884
def init_app(self, app, config_prefix='MONGOALCHEMY'):
        """"""

        self.config_prefix = config_prefix
        def key(suffix):
            return '%s_%s' % (config_prefix, suffix)

        if key('DATABASE') not in app.config:
            raise ImproperlyConfiguredError("You should provide a database name "
                                            "(the %s setting)." % key('DATABASE'))

        uri = _get_mongo_uri(app, key)
        rs = app.config.get(key('REPLICA_SET'))
        timezone = None
        if key('TIMEZONE') in app.config:
            timezone = pytz.timezone(app.config.get(key('TIMEZONE')))
        self.session = session.Session.connect(app.config.get(key('DATABASE')),
                                               safe=app.config.get(key('SAFE_SESSION'),
                                                                   False),
                                               timezone = timezone,
                                               host=uri, replicaSet=rs)
        self.Document._session = self.session
1336700
function mongooseInit(mongoose, logger, config) {
  const Log = logger.bind('mongoose-init')

  mongoose.Promise = Promise

  logUtil.logActionStart(
    Log,
    'Connecting to Database',
    _.omit(config.mongo, ['pass'])
  )

  mongoose.connect(config.mongo.URI)

  globals.mongoose = mongoose

  Log.log('mongoose connected')

  return mongoose
}
184071
def Initialize(api_key, api_secret, api_host="localhost", api_port=443, api_ssl=True, asyncblock=False, timeout=10, req_method="get"):
    
    config = Config()

    if api_ssl:
        proto = "https"
    else:
        proto = "http"
    api_url = "%s://%s:%s/client/api" % (proto, api_host, api_port)
    if os.access(os.path.expanduser("~") , os.W_OK):
        d = os.path.expanduser("~")
    else:
        d = tempfile.gettempdir()
    cache_file = os.getenv('MOLNCTRL_CACHE') or '.molnctrl_cache'
    if os.path.exists(os.path.join(d, cache_file)):
        apicache = pickle.load(open( os.path.join(d, cache_file), "rb" ))
    else:
        method = {'description': u'lists all available apis on the server, provided by the Api Discovery plugin',
            'isasync': False,
            'name': u'listApis',
            'params': [{'description': u'API name',
            'length': 255,
            'name': u'name',
            'related': [],
            'required': False,
            'type': u'string'}],
            'related': [],
            'requiredparams': []}
        _create_api_method(CSApi, "list_apis", method)
        c = CSApi(api_url, api_key, api_secret, asyncblock)
        apicache = cachemaker.monkeycache(c.list_apis())
        pickle.dump(apicache, open(os.path.join(d, cache_file), "wb"))

    for verb, methods in six.iteritems(apicache):
        if isinstance(methods, dict):
            for method in six.iterkeys(methods):
                _create_api_method(CSApi, "%s_%s" % (verb, method), methods[method])
    return CSApi(api_url, api_key, api_secret, asyncblock, timeout, req_method)
216083
def init_db(uri, base, **kwargs):
    
    engine = create_engine(uri, **kwargs)
    base.metadata.create_all(engine)
    return engine
362039
def initdb():
    

    print("Syncing up database...")
    cwd_to_sys_path()
    if db and hasattr(db, "Model"):
        db.create_all()
        for m in db.Model.__subclasses__():
            if hasattr(m, "initialize__"):
                print("Sync up model: %s ..." % m.__name__)
                getattr(m, "initialize__")()

    print("Done")