OpenVPN status initdb method
544494
def cli(conf):
    
    try:
        config = init_config(conf)
        debug = config.getboolean('DEFAULT', 'debug')
        conn = get_conn(config.get('DEFAULT','statusdb'))
        cur = conn.cursor()
        sqlstr = '''create table client_status
        (session_id text PRIMARY KEY, username text, userip text, 
            realip text, realport int,ctime int,
            inbytes int, outbytes int, 
            acct_interval int, session_timeout int, uptime int)
        '''
        try:
            cur.execute('drop table client_status')
        except:
            pass
        cur.execute(sqlstr)
        print 'flush client status database'
        conn.commit()
        conn.close()
    except:
        traceback.print_exc()
105151
def _initDatabase(self):
        
        queries = []

        if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0:
            for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]:
                sqlFile = open(scriptFilePath, "r")
                queriesInFile = self.extractFromSQLFile(sqlFile)
                sqlFile.close()

                queries.extend(queriesInFile)

        def failCallback(error):
            errorMessage = str(error)
            if isinstance(error, Failure):
                errorMessage = error.getErrorMessage()

            self.log.error(
                "[Viper.MySQL] _initDatabase() database error: {errorMessage}",
                errorMessage=errorMessage
            )

        def runCallback(transaction, queries):
            try:
                for query in queries:
                    transaction.execute(query)
            except Exception as e:
                failCallback(e)
                return

        interaction = self.runInteraction(runCallback, queries)
        interaction.addErrback(failCallback)
859426
def init(self):
        """"""
        if not self.export_enable:
            return None

        try:
            db = InfluxDBClient(host=self.host,
                                port=self.port,
                                username=self.user,
                                password=self.password,
                                database=self.db)
            get_all_db = [i['name'] for i in db.get_list_database()]
        except InfluxDBClientError as e:
            logger.critical("Cannot connect to InfluxDB database '%s' (%s)" % (self.db, e))
            sys.exit(2)

        if self.db in get_all_db:
            logger.info(
                "Stats will be exported to InfluxDB server: {}".format(db._baseurl))
        else:
            logger.critical("InfluxDB database '%s' did not exist. Please create it" % self.db)
            sys.exit(2)

        return db
622271
@Override
    public void init() throws InitializationException {
        if (null == embedded || "true".equalsIgnoreCase(embedded)) {
            Log.warn("Audit4j Database Handler runs on embedded mode. See " + ErrorGuide.ERROR_URL
              + "embeddeddb for further details.");
            server = HSQLEmbededDBServer.getInstance();
            db_driver = server.getDriver();
            db_url = server.getNetworkProtocol() + ":file:audit4jdb";
            if (db_user == null) {
                db_user = Utils.EMBEDED_DB_USER;
            }
            if (db_password == null) {
                db_password = Utils.EMBEDED_DB_PASSWORD;
            }
            server.setUname(db_user);
            server.setPassword(db_password);
            server.start();
        }

        factory = ConnectionFactory.getInstance();
        factory.setDataSource(dataSource);
        factory.setDriver(getDb_driver());
        factory.setUrl(getDb_url());
        factory.setUser(getDb_user());
        factory.setPassword(getDb_password());

        factory.setDataSourceClass(db_datasourceClass);
        factory.setAutoCommit(db_pool_autoCommit);
        if (db_pool_connectionTimeout != null) {
            factory.setConnectionTimeout(db_pool_connectionTimeout);
        }
        if (db_pool_idleTimeout != null) {
            factory.setIdleTimeout(db_pool_idleTimeout);
        }
        if (db_pool_maximumPoolSize != null) {
            factory.setMaximumPoolSize(db_pool_maximumPoolSize);
        }
        if (db_pool_maxLifetime != null) {
            factory.setMaxLifetime(db_pool_maxLifetime);
        }
        if (db_pool_minimumIdle != null) {
            factory.setMinimumIdle(db_pool_minimumIdle);
        }

        if (getDb_connection_type() != null && getDb_connection_type().equals(POOLED_CONNECTION)) {
            factory.setConnectionType(ConnectionType.POOLED);
        } else if (getDb_connection_type() != null && getDb_connection_type().equals(JNDI_CONNECTION)) {
            factory.setConnectionType(ConnectionType.JNDI);
            factory.setJndiDataSource(getDb_jndi_datasource());
        } else {
            factory.setConnectionType(ConnectionType.SINGLE);
        }

        factory.init();

        try {
            getDaoForTable(default_table_name);
        } catch (HandlerException e) {
            throw new InitializationException("Unable to create tables", e);
        }

    }
214367
function (dbname, version) {
		if (mockIndexedDBTestFlags.openDBShouldBlock === true) {
			mockIndexedDB_openDBTimer = setTimeout(function () {
				mockIndexedDBOpenDBRequest.callBlockedHandler();
				mockIndexedDB_openDBBlocked = true;
			}, 20);
		}
		else if (mockIndexedDBTestFlags.openDBShouldAbort === true) {
			mockIndexedDB_openDBTimer = setTimeout(function () {
				mockIndexedDBOpenDBRequest.callAbortHandler();
				mockIndexedDB_openDBAbort = true;
			}, 20);
		}
		else if (mockIndexedDBTestFlags.upgradeNeeded === true) {
			mockIndexedDB_openDBTimer = setTimeout(function () {
				mockIndexedDBOpenDBRequest.callUpgradeNeeded();
				mockIndexedDB_openDBUpgradeNeeded = true;
			}, 20);
		}
		// these are order dependent, so we don't have to set so many
		// flags in the test. can leave 'canOpenDB' in its default
		// true state, so long as the other fail vars are checked first.
		else if (mockIndexedDBTestFlags.canOpenDB === true) {
			mockIndexedDB_openDBTimer = setTimeout(function () {
				mockIndexedDBOpenDBRequest.callSuccessHandler();
				mockIndexedDB_openDBSuccess = true;
			}, 20);
		}
		else {
			mockIndexedDB_openDBTimer = setTimeout(function () {
				mockIndexedDBOpenDBRequest.callErrorHandler();
				mockIndexedDB_openDBFail = true;
			}, 20);
		}

		return mockIndexedDBOpenDBRequest;
	}
286468
private void closeSessionAndCreateAndOpenUntitledDb() throws Exception {
        getExtensionLoader().sessionAboutToChangeAllPlugin(null);
        model.closeSession();
        log.info("Create and Open Untitled Db");
        model.createAndOpenUntitledDb();
    }
884595
function (DB_name, account, pass, onOpenDone) {

		var conn = SR._storage.openDB(DB_name, dbSetting.serverIP, dbSetting.serverPort);

		// load fail
		if (conn === undefined) {
			LOG.error('cannot open DB: ' + DB_name, 'SR.DB');
			return onOpenDone(false);
		}

		// open DB & load the collection data from DB
		conn.open(function (err, client) {

			// check if error
			if (err) {
				LOG.error(err, 'SR.DB');
				return UTIL.safeCall(onOpenDone, false);
			}

			var user_created = false;

			var auth_user = function () {

				// authenticate into the DB
				LOG.sys('authenticating DB [' + DB_name + ']...', 'SR.DB');

				// NOTE: use client.admin().authenticate will force using admin account
				//	   but in general we should not do that

				client.authenticate(account, pass, function (err, replies) {

					if (err) {

						// if this is repeated call
						if (user_created === true) {
							LOG.error(err, 'SR.DB');
							LOG.warn('DB authentication failure', 'SR.DB');
							return UTIL.safeCall(onOpenDone, false);
						}

						// create DB user/pass (assume it's a new DB)
						LOG.warn('auth error, assume DB does not exist, try to create new DB...', 'SR.DB');

						// NOTE: right now this action is always successful, so it's like no auth exists
						//	   might be a bug in MongoDB
						user_created = true;

						client.admin().authenticate(SR.Settings.DB_ADMIN.account, SR.Settings.DB_ADMIN.pass, function (err, replies) {
							if (err) {
								LOG.error(err, 'SR.DB');
								LOG.error('DB admin auth failure, please make sure DB_ADMIN is setup correctly either in system or project setting', 'SR.DB');
								return UTIL.safeCall(onOpenDone, false);
							}

							client.addUser(account, pass, function (err, result) {

								if (err) {
									LOG.error(err, 'SR.DB');
									LOG.warn('DB addUser failure', 'SR.DB');
									return UTIL.safeCall(onOpenDone, false);
								}

								LOG.warn('DB addUser success, re-authenticate', 'SR.DB');
								auth_user();
							});
						});

						return;
					}

					LOG.warn('DB authentication success', 'SR.DB');

					// store client for later access
					l_DBconn[DB_name] = conn;
					l_DBclient[DB_name] = client;
					UTIL.safeCall(onOpenDone, true);
				});
			}

			// perform first DB authentication
			auth_user();
		});
	}
1331429
private void init() {
    host = DEFAULT_HOST;
    port = DEFAULT_PORT;
    database = DEFAULT_DATABASE;
    user = DEFAULT_USER;
    password = DEFAULT_PASSWORD;
    cachePreparedStatements = DEFAULT_CACHE_PREPARED_STATEMENTS;
    pipeliningLimit = DEFAULT_PIPELINING_LIMIT;
    sslMode = DEFAULT_SSLMODE;
  }
1094293
function init(options) {
    if (options === void 0) { options = {}; }
    if ('debug' in options) {
        diag.debug.enabled = options.debug;
        Q.longStackSupport = options.debug;
    }
    if ('serverUrl' in options) {
        var myURL = url.parse(options.serverUrl);
        if (!myURL.protocol && !myURL.host) {
            return Q.reject(new Error(options.serverUrl + " is not an accepted Url, please add a Host and a Protocol."));
        }
    }
    _.assignWith(exports.initOptions, cloneServerInitOptions(options), function (left, right) { return _.isUndefined(right) ? left : right; });
    if ('push' in options) {
        exports.initOptions.push = _.cloneDeep(options.push);
    }
    return device.ready;
}
866570
function _initStorage(options) {
    var self = this;
    var dbInfo = {
        db: null
    };

    if (options) {
        for (var i in options) {
            dbInfo[i] = options[i];
        }
    }

    // Get the current context of the database;
    var dbContext = dbContexts[dbInfo.name];

    // ...or create a new context.
    if (!dbContext) {
        dbContext = createDbContext();
        // Register the new context in the global container.
        dbContexts[dbInfo.name] = dbContext;
    }

    // Register itself as a running localForage in the current context.
    dbContext.forages.push(self);

    // Replace the default `ready()` function with the specialized one.
    if (!self._initReady) {
        self._initReady = self.ready;
        self.ready = _fullyReady;
    }

    // Create an array of initialization states of the related localForages.
    var initPromises = [];

    function ignoreErrors() {
        // Don't handle errors here,
        // just makes sure related localForages aren't pending.
        return Promise$1.resolve();
    }

    for (var j = 0; j < dbContext.forages.length; j++) {
        var forage = dbContext.forages[j];
        if (forage !== self) {
            // Don't wait for itself...
            initPromises.push(forage._initReady()["catch"](ignoreErrors));
        }
    }

    // Take a snapshot of the related localForages.
    var forages = dbContext.forages.slice(0);

    // Initialize the connection process only when
    // all the related localForages aren't pending.
    return Promise$1.all(initPromises).then(function () {
        dbInfo.db = dbContext.db;
        // Get the connection or open a new one without upgrade.
        return _getOriginalConnection(dbInfo);
    }).then(function (db) {
        dbInfo.db = db;
        if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
            // Reopen the database for upgrading.
            return _getUpgradedConnection(dbInfo);
        }
        return db;
    }).then(function (db) {
        dbInfo.db = dbContext.db = db;
        self._dbInfo = dbInfo;
        // Share the final connection amongst related localForages.
        for (var k = 0; k < forages.length; k++) {
            var forage = forages[k];
            if (forage !== self) {
                // Self is already up-to-date.
                forage._dbInfo.db = dbInfo.db;
                forage._dbInfo.version = dbInfo.version;
            }
        }
    });
}
718858
def init_db_conn(
        connection_name, HOST=None, PORT=None, DB=None, PASSWORD=None):
    
    rpool = redis.ConnectionPool(
        host=HOST, port=PORT, db=DB, password=PASSWORD)
    r = redis.Redis(connection_pool=rpool)
    redis_pool.connections[connection_name] = RedisClient(r)
1019779
public void init(BaseDatabase database, Record record)
    {
        super.init(database, record);

        m_gridList = new DataRecordList();      
        m_iEndOfFileIndex = UNKNOWN_POSITION; // Actual end of file (-1 means don't know)

        m_gridBuffer = new DataRecordBuffer();
        m_gridNew = new DataRecordBuffer();
        m_iPhysicalFilePosition = UNKNOWN_POSITION;
        m_iLogicalFilePosition = UNKNOWN_POSITION;

        if (((record.getOpenMode() & DBConstants.OPEN_READ_ONLY) != DBConstants.OPEN_READ_ONLY)
            && (record.getCounterField() != null))
                record.setOpenMode(record.getOpenMode() | DBConstants.OPEN_REFRESH_AND_LOCK_ON_CHANGE_STRATEGY);  // Must have for GridTable to re-read.
    }
1229843
function _initStorage(options) {
	        var self = this;
	        var dbInfo = {
	            db: null
	        };

	        if (options) {
	            for (var i in options) {
	                dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
	            }
	        }

	        var dbInfoPromise = new Promise(function (resolve, reject) {
	            // Open the database; the openDatabase API will automatically
	            // create it for us if it doesn't exist.
	            try {
	                dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
	            } catch (e) {
	                return self.setDriver(self.LOCALSTORAGE).then(function () {
	                    return self._initStorage(options);
	                }).then(resolve)['catch'](reject);
	            }

	            // Create our key/value table if it doesn't exist.
	            dbInfo.db.transaction(function (t) {
	                t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
	                    self._dbInfo = dbInfo;
	                    resolve();
	                }, function (t, error) {
	                    reject(error);
	                });
	            });
	        });

	        return new Promise(function (resolve, reject) {
	            resolve(__webpack_require__(3));
	        }).then(function (lib) {
	            dbInfo.serializer = lib;
	            return dbInfoPromise;
	        });
	    }
388459
private static function _initCommon()
    {
        global $PPHP;

        self::$_req['warnings'] = array();
        self::$_req['status'] = 200;
        self::$_req['redirect'] = false;
        self::$_req['protocol'] = (self::$_req['ssl'] ? 'https' : 'http');
    }
550998
def init_db_conn(connection_name, connection_string, scopefunc=None):
    
    engine = create_engine(connection_string)
    session = scoped_session(sessionmaker(), scopefunc=scopefunc)
    session.configure(bind=engine)
    pool.connections[connection_name] = Connection(engine, session)
647264
@Override
    public void initialize() {
        String adminUsername = "admin";
        String adminPassword = "123456";

        User param = new User();
        param.setUserName(adminUsername);
        User admin = baseDao.getUnique(User.class, param);
        if (admin != null) {
            LoggerHelper.info("database has been initialized.");
            return;
        }
        LoggerHelper.info("begin init database.");
        admin = new User();
        admin.setUserName(adminUsername);
        admin.setUserPassword(HashHelper.getHashedPassword(adminPassword, adminUsername));
        admin.setPasswordSalt(adminUsername);

        Role role = new Role();
        role.setRoleName("ROLE_ADMIN");
        role.setRoleDescription("Administrator");
        baseDao.save(role);

        admin.setRoleList(Arrays.asList(role));
        baseDao.save(admin);

        LoggerHelper.info("init database successfully.");
    }
591126
public void put_server_info(Database database, DbServInfo info) throws DevFailed {
        if (!database.isAccess_checked()) checkAccess(database);

        String[] array;
        array = new String[4];
        array[0] = info.name;
        array[1] = info.host;
        array[2] = (info.controlled) ? "1" : "0";
        array[3] = Integer.toString(info.startup_level);

		/*System.out.println("DbPutServerInfo:");
		for (int i=0 ; i<array.length ; i++)
			System.out.println("	"+array[i]);
		*/

        //	Query info from database
        DeviceData argIn = new DeviceData();
        argIn.insert(array);
        command_inout(database, "DbPutServerInfo", argIn);
    }