Get BEL API arango db handle
161356
def get_belapi_handle(client, username=None, password=None):
    """"""

    (username, password) = get_user_creds(username, password)

    sys_db = client.db("_system", username=username, password=password)

    # Create a new database named "belapi"
    try:
        if username and password:
            belapi_db = sys_db.create_database(
                name=belapi_db_name,
                users=[{"username": username, "password": password, "active": True}],
            )
        else:
            belapi_db = sys_db.create_database(name=belapi_db_name)
    except arango.exceptions.DatabaseCreateError:
        if username and password:
            belapi_db = client.db(belapi_db_name, username=username, password=password)
        else:
            belapi_db = client.db(belapi_db_name)

    try:
        belapi_db.create_collection(belapi_settings_name)
    except Exception:
        pass

    try:
        belapi_db.create_collection(belapi_statemgmt_name)
    except Exception:
        pass

    return belapi_db
151762
function parseDB(callback) {
    pgStructure(getConfig('database.host'), getConfig('database.database'), getConfig('database.user'),
        getConfig('database.password'), { port: getConfig('database.port'), schema: getConfig('database.schema') },
        callback);
}
454698
function getRenameIndexSQL($xmldb_table, $xmldb_index, $newname) {
    /// Get the real index name
        $dbindexname = $this->mdb->get_manager()->find_index_name($xmldb_table, $xmldb_index);
        $xmldb_index->setName($newname);
        $results = array('DROP INDEX ' . $dbindexname);
        $results = array_merge($results, $this->getCreateIndexSQL($xmldb_table, $xmldb_index));
        return $results;
    }
708613
function &get($key, $raw = false) {
		// handle virtual fields
		if (isset($this->vFields[$key])) {
			$out = (is_callable($this->vFields[$key]))
				? call_user_func($this->vFields[$key], $this) : $this->vFields[$key];
			return $out;
		}
		$fields = $this->fieldConf;
		$id = $this->primary;
		if ($key == '_id' && $this->dbsType == 'sql')
			$key = $id;
		if ($this->whitelist && !in_array($key,$this->whitelist)) {
			$out = null;
			return $out;
		}
		if ($raw) {
			$out = $this->exists($key) ? $this->mapper->{$key} : NULL;
			if ($this->dbsType == 'mongo' && !$this->db->legacy() && $out instanceof \MongoDB\Model\BSONArray)
				$out = (array) $out;
			return $out;
		}
		if (!empty($fields) && isset($fields[$key]) && is_array($fields[$key])
			&& !array_key_exists($key,$this->fieldsCache)) {
			// load relations
			if (isset($fields[$key]['belongs-to-one'])) {
				// one-to-X, bidirectional, direct way
				if (!$this->exists($key) || is_null($this->mapper->{$key}))
					$this->fieldsCache[$key] = null;
				else {
					// get config for this field
					$relConf = $fields[$key]['belongs-to-one'];
					// fetch related model
					$rel = $this->getRelFromConf($relConf,$key);
					// am i part of a result collection?
					if ($cx = $this->getCollection()) {
						// does the collection has cached results for this key?
						if (!$cx->hasRelSet($key)) {
							// build the cache, find all values of current key
							$relKeys = array_unique($cx->getAll($key,true));
							// find related models
							$crit = array($relConf[1].' IN ?', $relKeys);
							$relSet = $rel->find($this->mergeWithRelFilter($key, $crit),
								$this->getRelFilterOption($key),$this->_ttl);
							// cache relSet, sorted by ID
							$cx->setRelSet($key, $relSet ? $relSet->getBy($relConf[1]) : NULL);
						}
						// get a subset of the preloaded set
						$result = $cx->getSubset($key,(string) $this->get($key,true));
						$this->fieldsCache[$key] = $result ? $result[0] : NULL;
					} else {
						$crit = array($relConf[1].' = ?', $this->get($key, true));
						$crit = $this->mergeWithRelFilter($key, $crit);
						$this->fieldsCache[$key] = $rel->findone($crit,
							$this->getRelFilterOption($key),$this->_ttl);
					}
				}
			}
			elseif (($type = isset($fields[$key]['has-one']))
				|| isset($fields[$key]['has-many'])) {
				$type = $type ? 'has-one' : 'has-many';
				$fromConf = $fields[$key][$type];
				if (!is_array($fromConf))
					trigger_error(sprintf(self::E_REL_CONF_INC, $key),E_USER_ERROR);
				$rel = $this->getRelInstance($fromConf[0],null,$key,true);
				$relFieldConf = $rel->getFieldConfiguration();
				$relType = isset($relFieldConf[$fromConf[1]]['belongs-to-one']) ?
					'belongs-to-one' : 'has-many';
				// one-to-*, bidirectional, inverse way
				if ($relType == 'belongs-to-one') {
					$toConf = $relFieldConf[$fromConf[1]]['belongs-to-one'];
					if (!is_array($toConf))
						$toConf = array($toConf, $id);
					if ($toConf[1] != $id && (!$this->exists($toConf[1])
							|| is_null($this->mapper->get($toConf[1]))))
						$this->fieldsCache[$key] = null;
					elseif ($cx=$this->getCollection()) {
						// part of a result set
						if (!$cx->hasRelSet($key)) {
							// emit eager loading
							$relKeys = $cx->getAll($toConf[1],true);
							$crit = array($fromConf[1].' IN ?', $relKeys);
							$relSet = $rel->find($this->mergeWithRelFilter($key,$crit),
								$this->getRelFilterOption($key),$this->_ttl);
							$cx->setRelSet($key, $relSet ? $relSet->getBy($fromConf[1],true) : NULL);
						}
						$result = $cx->getSubset($key, array($this->get($toConf[1])));
						$this->fieldsCache[$key] = $result ? (($type == 'has-one')
							? $result[0][0] : CortexCollection::factory($result[0])) : NULL;
					}	// no collection
					elseif (($val=$this->getRaw($toConf[1])) && $val!==NULL) {
						$crit=[$fromConf[1].' = ?',$val];
						$crit=$this->mergeWithRelFilter($key,$crit);
						$opt=$this->getRelFilterOption($key);
						$this->fieldsCache[$key]=(($type=='has-one')
							?$rel->findone($crit,$opt,$this->_ttl)
							:$rel->find($crit,$opt,$this->_ttl))?:NULL;
					} else
						$this->fieldsCache[$key] = NULL;
				}
				// many-to-many, bidirectional
				elseif ($relType == 'has-many') {
					$toConf = $relFieldConf[$fromConf[1]]['has-many'];
					$mmTable = $this->mmTable($fromConf,$key,$toConf);
					// create mm table mapper
					if (!$this->get($id,true)) {
						$this->fieldsCache[$key] = null;
						return $this->fieldsCache[$key];
					}
					$id = $toConf['relPK'];
					$rel = $this->getRelInstance(null,array('db'=>$this->db,'table'=>$mmTable));
					if ($cx = $this->getCollection()) {
						if (!$cx->hasRelSet($key)) {
							// get IDs of all results
							$relKeys = $cx->getAll($id,true);
							// get all pivot IDs
							$filter = [$fromConf['relField'].' IN ?',$relKeys];
							if ($fromConf['isSelf']) {
								$filter[0].= ' OR '.$fromConf['relField'].'_ref IN ?';
								$filter[] = $relKeys;
							}
							$mmRes = $rel->find($filter,null,$this->_ttl);
							if (!$mmRes)
								$cx->setRelSet($key, NULL);
							else {
								$pivotRel = array();
								$pivotKeys = array();
								foreach($mmRes as $model) {
									$val = $model->get($key,true);
									if ($fromConf['isSelf']) {
										$refVal = $model->get($fromConf['relField'].'_ref',true);
										$pivotRel[(string) $refVal][] = $val;
										$pivotRel[(string) $val][] = $refVal;
										$pivotKeys[] = $val;
										$pivotKeys[] = $refVal;
									} else {
										$pivotRel[ (string) $model->get($fromConf['relField'])][] = $val;
										$pivotKeys[] = $val;
									}
								}
								// cache pivot keys
								$cx->setRelSet($key.'_pivot', $pivotRel);
								// preload all rels
								$pivotKeys = array_unique($pivotKeys);
								$fRel = $this->getRelInstance($fromConf[0],null,$key,true);
								$crit = array($id.' IN ?', $pivotKeys);
								$relSet = $fRel->find($this->mergeWithRelFilter($key, $crit),
									$this->getRelFilterOption($key),$this->_ttl);
								$cx->setRelSet($key, $relSet ? $relSet->getBy($id) : NULL);
								unset($fRel);
							}
						}
						// fetch subset from preloaded rels using cached pivot keys
						$fkeys = $cx->getSubset($key.'_pivot', array($this->get($id)));
						$this->fieldsCache[$key] = $fkeys ?
							CortexCollection::factory($cx->getSubset($key, $fkeys[0])) : NULL;
					} // no collection
					else {
						// find foreign keys
						$fId=$this->get($fromConf['localKey'],true);
						$filter = [$fromConf['relField'].' = ?',$fId];
						if ($fromConf['isSelf']) {
							$filter = [$fromConf['relField'].' = ?',$fId];
							$filter[0].= ' OR '.$fromConf['relField'].'_ref = ?';
							$filter[] = $filter[1];
						}
						$results = $rel->find($filter,null,$this->_ttl);
						if (!$results)
							$this->fieldsCache[$key] = NULL;
						else {
							$fkeys = $results->getAll($key,true);
							if ($fromConf['isSelf']) {
								// merge both rel sides and remove itself
								$fkeys = array_diff(array_merge($fkeys,
									$results->getAll($key.'_ref',true)),[$fId]);
							}
							// create foreign table mapper
							unset($rel);
							$rel = $this->getRelInstance($fromConf[0],null,$key,true);
							// load foreign models
							$filter = array($fromConf['relPK'].' IN ?', $fkeys);
							$filter = $this->mergeWithRelFilter($key, $filter);
							$this->fieldsCache[$key] = $rel->find($filter,
								$this->getRelFilterOption($key),$this->_ttl);
						}
					}
				}
			}
			elseif (isset($fields[$key]['belongs-to-many'])) {
				// many-to-many, unidirectional
				$fields[$key]['type'] = self::DT_JSON;
				$result = $this->getRaw($key);
				if ($this->dbsType == 'sql')
					$result = json_decode($result, true);
				if (!is_array($result))
					$this->fieldsCache[$key] = $result;
				else {
					// create foreign table mapper
					$relConf = $fields[$key]['belongs-to-many'];
					$rel = $this->getRelFromConf($relConf,$key);
					$fkeys = array();
					foreach ($result as $el)
						$fkeys[] = (is_int($el)||ctype_digit($el))?(int)$el:(string)$el;
					// if part of a result set
					if ($cx = $this->getCollection()) {
						if (!$cx->hasRelSet($key)) {
							// find all keys
							$relKeys = ($cx->getAll($key,true));
							if ($this->dbsType == 'sql'){
								foreach ($relKeys as &$val) {
									$val = substr($val, 1, -1);
									unset($val);
								}
								$relKeys = json_decode('['.implode(',',$relKeys).']');
							} else
								$relKeys = call_user_func_array('array_merge', $relKeys);
							// get related models
							if (!empty($relKeys)) {
								$crit = array($relConf[1].' IN ?', array_unique($relKeys));
								$relSet = $rel->find($this->mergeWithRelFilter($key, $crit),
								$this->getRelFilterOption($key),$this->_ttl);
								// cache relSet, sorted by ID
								$cx->setRelSet($key, $relSet ? $relSet->getBy($relConf[1]) : NULL);
							} else
								$cx->setRelSet($key, NULL);
						}
						// get a subset of the preloaded set
						$this->fieldsCache[$key] = CortexCollection::factory($cx->getSubset($key, $fkeys));
					} else {
						// load foreign models
						$filter = array($relConf[1].' IN ?', $fkeys);
						$filter = $this->mergeWithRelFilter($key, $filter);
						$this->fieldsCache[$key] = $rel->find($filter,
							$this->getRelFilterOption($key),$this->_ttl);
					}
				}
			}
			// resolve array fields
			elseif (isset($fields[$key]['type'])) {
				if ($this->dbsType == 'sql') {
					if ($fields[$key]['type'] == self::DT_SERIALIZED)
						$this->fieldsCache[$key] = unserialize($this->mapper->{$key});
					elseif ($fields[$key]['type'] == self::DT_JSON)
						$this->fieldsCache[$key] = json_decode($this->mapper->{$key},true);
				}
				if ($this->exists($key) && preg_match('/BOOL/i',$fields[$key]['type'])) {
					$this->fieldsCache[$key] = (bool) $this->mapper->{$key};
				}
			}
		}
		// fetch cached value, if existing
		// TODO: fix array key reference editing, #71
//		if (array_key_exists($key,$this->fieldsCache))
//			$val = $this->fieldsCache[$key];
//		elseif ($this->exists($key)) {
//			$val =& $this->mapper->{$key};
//		} else
//			$val = NULL;
		$val = array_key_exists($key,$this->fieldsCache) ? $this->fieldsCache[$key]
			: (($this->exists($key)) ? $this->mapper->{$key} : null);
		if ($this->dbsType == 'mongo' && (($this->db->legacy() && $val instanceof \MongoId) ||
				(!$this->db->legacy() && $val instanceof \MongoDB\BSON\ObjectId))) {
			// conversion to string makes further processing in template, etc. much easier
			$val = (string) $val;
		}
		// custom getter
		$out = $this->emit('get_'.$key, $val);
		return $out;
	}
346803
function getDbName(uri) {
  var parsedMongooseUri = mongoUriParser.parse(uri);
  var dbName = parsedMongooseUri.database;
  return dbName;
}
625233
def get_db_session(engine):
    ""

    db = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
    db.configure(bind=engine)
    db.autoflush = True

    return db
431721
function(db) {

		function get_documents(data, config, plv8, ERROR, WARNING) {

			function get_document(id) {
				return plv8.execute("SELECT * FROM documents WHERE id = $1 LIMIT 1", [id])[0];
			}

			function get_type(id) {
				return plv8.execute("SELECT * FROM types WHERE id = $1 LIMIT 1", [id])[0];
			}

			function error(msg) {
				plv8.elog(ERROR, msg);
			}

			function warn(msg) {
				plv8.elog(WARNING, msg);
			}

			function is_object(a) {
				return a && (typeof a === 'object');
			}

			function is_array(a) {
				return a && (a instanceof Array);
			}

			function is_string(a) {
				return a && (typeof a === 'string');
			}

			function is_uuid(obj) {
				return /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/.test(obj);
			}

			function get_property_step(last, current) {
				return is_object(last) ? last[current] : undefined;
			}

			/** Get value of property from provided object using a path.
			 * @param obj {object} The object from where to find the value.
			 * @param path {string} The path to the value in object.
			 * @returns {mixed} The value from the object at the end of path or `undefined` if any part is missing.
			 */
			function get_property(obj, path) {
				if(!is_object(obj)) { return error('get_property(obj, ...) not object: '+ obj); }
				if(!is_string(path)) { return error('get_property(..., path) not string: '+ path); }
				return path.split('.').reduce(get_property_step, obj);
			}

			/** Get document by UUID */
			function fetch_object_by_uuid(data, prop, uuid) {
				if(!is_object(data)) { return error('fetch_object_by_uuid(data, ..., ...) not object: '+ data); }
				if(!is_string(prop)) { return error('fetch_object_by_uuid(..., prop, ...) not string: '+ prop); }
				if(!is_uuid(uuid)) { return warn('Property ' + prop + ' was not uuid: ' + uuid); }
				if(data.documents[uuid] === undefined) {
					data.documents[uuid] = get_document(uuid);
				} else {
					return warn('Document already fetched: ' + uuid);
				}
			}

			/* */
			function fetch_object(data, prop) {
				var uuid = get_property(data, prop);
				if(is_array(uuid)) {
					return uuid.forEach(fetch_object_by_uuid.bind(undefined, data, prop));
				}
				return fetch_object_by_uuid(data, prop, uuid);
			}

			// Check for bad input

			if(!is_object(data)) { return error("get_documents(data, ...) not object"); }
			if(!is_array(config)) { return error("get_documents(..., config) not array"); }

			//var types_id = data.types_id;
			//if(!is_uuid(types_id)) { return error("data.types_id not valid UUID: " + types_id); }

			// Get document type
			//var type = get_type(types_id);
			//if(!is_object(type)) { return error("type not valid object: " + type); }

			//var relations = type.relations || {};
			//if(!is_object(relations)) { return error("type.relations not valid object: " + relations); }

			// Populate documents from `config`
			data.documents = {};
			config.forEach( fetch_object.bind(undefined, data) );
			return data.documents;
		}

		return db.query('CREATE OR REPLACE FUNCTION get_documents(data json, config json) RETURNS json LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(get_documents, ["data", "config", "plv8", "ERROR", "WARNING"]));
	}
560870
function getBoolean(): \Closure {
    return function($value, \Mustache_LambdaHelper $helper) {
      return HtmlHelper::encode(\Yii::$app->formatter->asBoolean($helper->render($value)));
    };
  }
1291068
def query(self):
        """"""
        if self._query is None:
            query_string = self.environ.get('QUERY_STRING')
            self._query = QueryDict([
                (k.decode('utf-8'), v.decode('utf-8'))
                for k, v in urlparse.parse_qsl(
                    query_string, keep_blank_values=True)
            ])
        return self._query
894418
public static br[] get(nitro_service client) throws Exception
	{
		br resource = new br();
		resource.validate("get");
		return (br[]) resource.get_resources(client);
	}
909970
def fetch(method, uri, params_prefix=None, **params):
    """"""
    params = urlencode(_prepare_params(params, params_prefix))
    binary_params = params.encode('ASCII')

    # build the HTTP request
    url = "https://%s/%s.xml" % (CHALLONGE_API_URL, uri)
    req = Request(url, binary_params)
    req.get_method = lambda: method

    # use basic authentication
    user, api_key = get_credentials()
    auth_handler = HTTPBasicAuthHandler()
    auth_handler.add_password(
        realm="Application",
        uri=req.get_full_url(),
        user=user,
        passwd=api_key
    )
    opener = build_opener(auth_handler)

    try:
        response = opener.open(req)
    except HTTPError as e:
        if e.code != 422:
            raise
        # wrap up application-level errors
        doc = ElementTree.parse(e).getroot()
        if doc.tag != "errors":
            raise
        errors = [e.text for e in doc]
        raise ChallongeException(*errors)

    return response
296567
function findById(id) {
  return db
    .collection(config.get('arangodb:collections:users:name'))
    .document(id)
    .then((user) => {
      user._id = user._key;

      return user;
    })
    .catch({code: 404}, () => null);
}
514430
def get(self, params, **options):
        """"""
        options = self.client._merge_options({ 'full_payload': True })
        return self.client.get('/events', params, **options)
1122357
def query(self):
        
        query_context = QueryContext(**json.loads(request.form.get('query_context')))
        security_manager.assert_datasource_permission(query_context.datasource)
        payload_json = query_context.get_payload()
        return json.dumps(
            payload_json,
            default=utils.json_int_dttm_ser,
            ignore_nan=True,
        )
590834
def get(self, *args, **kwargs):
        '''
        '''
        self = self.select(*args, **kwargs)

        payload = self._payload_builder(self._query)
        response = self.execute_query(payload)

        return response
490808
function get_db (ent, done) {
    var folder = internals.makefolderpath(opts.folder, ent)
    var db = dbmap[folder]
    if (db) {
      return done(null, db)
    }
    internals.ensurefolder(folder, internals.error(done, function () {
      db = dbmap[folder]
      if (db) {
        return done(null, db)
      }
      try {
        db = dbmap[folder] = LevelQuery(Levelup(folder, opts))
        db.query.use(JsonqueryEngine())
      }
      catch (e) {
        db = dbmap[folder]
        if (db) {
          return done(null, db)
        }
        return done(e)
      }
      return done(null, db)
    }))
  }
195573
function getDatabase(index, opts) {
  var db;
  if(!this._databases[index]) {
    db = new Database(this, opts);
    this._databases[index] = db;
  }
  return this._databases[index];
}