Get a unique id given a query_string
499580
def get_unique_document_id(query_str):
    # type: (str) -> str
    """"""
    assert isinstance(query_str, string_types), (
        "Must receive a string as query_str. Received {}"
    ).format(repr(query_str))

    if query_str not in _cached_queries:
        _cached_queries[query_str] = sha1(str(query_str).encode("utf-8")).hexdigest()
    return _cached_queries[query_str]
573656
private Integer getUniqueId(Object object) {
    Integer id = idCache.get(object);
    if (id == null) {
      id = uidGenerator.incrementAndGet();
      Integer existing = idCache.putIfAbsent(object, id);
      if (existing != null) {
        return existing;
      }
    }
    return id;
  }
462545
private String getTSUIDForMetric(final String query_string, TSDB tsdb) {
    if (query_string == null || query_string.isEmpty()) {
      throw new BadRequestException("The query string was empty");
    }
    
    // m is of the following forms:
    // metric[{tag=value,...}]
    // where the parts in square brackets `[' .. `]' are optional.
    final HashMap<String, String> tags = new HashMap<String, String>();
    String metric = null;
    try {
      metric = Tags.parseWithMetric(query_string, tags);
    } catch (IllegalArgumentException e) {
      throw new BadRequestException(e);
    }
    
    // sort the UIDs on tagk values
    final ByteMap<byte[]> tag_uids = new ByteMap<byte[]>();
    for (final Entry<String, String> pair : tags.entrySet()) {
      tag_uids.put(tsdb.getUID(UniqueIdType.TAGK, pair.getKey()), 
          tsdb.getUID(UniqueIdType.TAGV, pair.getValue()));
    }
    
    // Byte Buffer to generate TSUID, pre allocated to the size of the TSUID
    final ByteArrayOutputStream buf = new ByteArrayOutputStream(
        TSDB.metrics_width() + tag_uids.size() * 
        (TSDB.tagk_width() + TSDB.tagv_width()));
    try {
      buf.write(tsdb.getUID(UniqueIdType.METRIC, metric));
      for (final Entry<byte[], byte[]> uids: tag_uids.entrySet()) {
        buf.write(uids.getKey());
        buf.write(uids.getValue());
      }
    } catch (IOException e) {
      throw new BadRequestException(e);
    }
    final String tsuid = UniqueId.uidToString(buf.toByteArray());
    
    return tsuid;
  }
960912
function getQueryParams(params) {
        params = params || {};
        var url = $location.url();
        var idx = url.indexOf('?');

        // if there is a query string
        if (idx < 0) { return {}; }

        // get the query string and split the keyvals
        var query = url.substring(idx + 1);
        var keyVals = query.split('&');

        // put each key/val into the params object
        _.each(keyVals, function (keyVal) {
            var keyValArr = keyVal.split('=');
            params[keyValArr[0]] = keyValArr[1];
        });

        return params;
    }
13351
def string_id(self):
    
    id = self.id()
    if not isinstance(id, basestring):
      id = None
    return id
199339
def _query(_node_id, value=None, **kw):
    ""
    query_result = []
    try:
        query_result = db.execute(text(fetch_query_string('select_query_from_node.sql')), **kw).fetchall()
    except DatabaseError as err:
        current_app.logger.error("DatabaseError: %s, %s", err, kw)
        return value
    #current_app.logger.debug("queries kw: %s", kw)
    #current_app.logger.debug("queries value: %s", value)
    current_app.logger.debug("queries: %s", query_result)
    if query_result:
        values = []
        for query_name in [x['name'] for x in query_result]:
            if query_name:
                result = []
                try:
                    current_app.logger.debug("query_name: %s", query_name)
                    #current_app.logger.debug("kw: %s", kw)
                    # Query string can be insert or select here
                    #statement = text(fetch_query_string(query_name))
                    #params = [x.key for x in statement.params().get_children()]
                    #skw = {key: kw[key] for key in params}
                    #result = db.execute(statement, **skw)
                    result = db.execute(text(fetch_query_string(query_name)), **kw)
                    current_app.logger.debug("result query: %s", result.keys())
                except (DatabaseError, StatementError) as err:
                    current_app.logger.error("DatabaseError (%s) %s: %s", query_name, kw, err)
                if result and result.returns_rows:
                    result = result.fetchall()
                    #values.append(([[dict(zip(result.keys(), x)) for x in result]], result.keys()))
                    #values.append((result.fetchall(), result.keys()))
                    #current_app.logger.debug("fetchall: %s", values)
                    if len(result) == 0:
                        values.append(([], []))
                    else:
                        current_app.logger.debug("result: %s", result)
                        # There may be more results, but only interested in the
                        # first one. Use the older rowify method for now.
                        # TODO: use case for rowify?
                        values.append(rowify(result, [(x, None) for x in result[0].keys()]))
                        #current_app.logger.debug("fetchone: %s", values)
        value = values
    #current_app.logger.debug("value: %s", value)
    return value
493555
def get_by_id(self, id):
        """"""
        with contextlib.closing(self.database.cursor()) as cursor:
            cursor.execute('SELECT id, name FROM users WHERE id=?', (id,))
            return cursor.fetchone()
295990
def _uniqueid(n=30):
    
    return ''.join(random.SystemRandom().choice(
                   string.ascii_uppercase + string.ascii_lowercase)
                   for _ in range(n))
872623
function querystring(query) {
      var parser = /([^=?&]+)=([^&]*)/g
        , result = {}
        , part;

      //
      // Little nifty parsing hack, leverage the fact that RegExp.exec increments
      // the lastIndex property so we can continue executing this loop until we've
      // parsed all results.
      //
      for (;
        part = parser.exec(query);
        result[decodeURIComponent(part[1])] = decodeURIComponent(part[2])
      );

      return result;
    }
198183
def get_id_by_name(api, search_name):
    
    entities = api.get_all(q='name==' + "'" + search_name + "'").content
    if entities:
        return entities[0].id
    return
25701
function getQueryArgs (ids) {
    // build query args
    var queryArgs = {
        allow: this.query.args.allow,
        session: this.query.session,
        where: {},
    }
    // set ids for query
    queryArgs.where[this.idColumn] = ids
    // if query is for list of ids set all flag
    if (Array.isArray(ids)) {
        queryArgs.all = true
    }
    // otherwise set limit 1
    else {
        queryArgs.limit = 1
    }
    // if query is for original id then set current flag
    if (this.isOriginalId) {
        queryArgs.current = true
    }
    // if custom query args are set then merge
    if (typeof this.queryArgs === 'object') {
        _.merge(queryArgs, this.queryArgs)
    }

    return queryArgs
}
162550
def get_unique_name(self, name):
        

        if name not in self._db:
            self._db[name] = 0
            return name
        else:
            index = self._db[name]
            self._db[name] = index + 1
            return f"{name}_{index}"
331196
def get_by_string(cls, fields, query):
	''''''
	try: pk = int(query)
	except ValueError: pass
	else: return cls.objects.get(pk=pk)
	obj = list(cls.objects.filter(reduce( op.or_,
		list(Q(**{'{}__icontains'.format(f): query}) for f in fields) )))
	if len(obj) > 1:
		raise cls.MultipleObjectsReturned((
			u'Unable to uniquely identify {}'
				' by provided criteria: {!r} (candidates: {})' )\
			.format(cls.__name__, query, ', '.join(it.imap(unicode, obj))) )
	elif not len(obj):
		raise cls.DoesNotExist(
			u'Unable to find site by provided criteria: {!r}'.format(query) )
	return obj[0]
567750
def get_ids(self, request_data, parameter_name='ids'):
        """"""
        if parameter_name not in request_data:
            raise ParseError("`{}` parameter is required".format(parameter_name))

        ids = request_data.get(parameter_name)
        if not isinstance(ids, list):
            raise ParseError("`{}` parameter not a list".format(parameter_name))

        if not ids:
            raise ParseError("`{}` parameter is empty".format(parameter_name))

        if any(map(lambda id: not isinstance(id, int), ids)):
            raise ParseError("`{}` parameter contains non-integers".format(parameter_name))

        return ids
226272
def query_by_id(self, id):
        
        return json.loads(self._get(UrlEncoded(str(id))).body.read().decode('utf-8'))
545385
async def _has_id(self, *args, **kwds):
        
        # if there is only one positional argument
        if len(args) == 1:
            # parse the appropriate query
            result = await parse_string(
                self._query,
                self.service.object_resolver,
                self.service.connection_resolver,
                self.service.mutation_resolver,
                obey_auth=False
            )
            # go to the bottom of the result for the list of matching ids
            return self._find_id(result['data'], args[0])
        # otherwise
        else:
            # treat the attribute like a normal filter
            return self._has_id(**kwds)
479763
def get_page_from_string_or_id(page_string, lang=None):
    """"""
    if type(page_string) == int:
        return Page.objects.get(pk=int(page_string))
    # if we have a string coming from some templates templates
    if (isinstance(page_string, SafeText) or
            isinstance(page_string, str)):
        if page_string.isdigit():
            return Page.objects.get(pk=int(page_string))
        return Page.objects.from_path(page_string, lang)
    # in any other case we return the input becasue it's probably
    # a Page object.
    return page_string