Finds entities matching a given string pattern. \nOptions: [ ontologies | classes | properties | concepts ]
170716
def do_get(self, line):
        """"""
        line = line.split()
        _pattern = ""
        if len(line) > 1:
            _pattern = line[1]
        opts = self.GET_OPTS

        if (not line) or (line[0] not in opts) or (not _pattern):
            self.help_get()
            return
            # self._print("Usage: get [%s] <name>" % "|".join([x for x in opts]))

        elif line[0] == "ontology":
            if not self.all_ontologies:
                self._help_nofiles()
            else:
                self._select_ontology(_pattern)

        elif line[0] in opts and not self.current:
            self._help_noontology()
            return

        elif line[0] == "class":
            g = self.current['graph']
            if g.all_classes:
                self._select_class(_pattern)
            else:
                self._print("No classes available.")

        elif line[0] == "property":
            g = self.current['graph']
            if g.all_properties:
                self._select_property(_pattern)
            else:
                self._print("No properties available.")

        elif line[0] == "concept":
            g = self.current['graph']
            if g.all_skos_concepts:
                self._select_concept(_pattern)
            else:
                self._print("No concepts available.")

        else:  # should never arrive here
            pass
1160248
def _get_named_patterns():
    """"""
    resolver = urlresolvers.get_resolver(None)
    patterns = sorted([(key, value[0][0][0])
                       for key, value in resolver.reverse_dict.items()
                       if isinstance(key, string_types)
                       ])
    return patterns
119036
function gatherEntityFilters(context, expression) {
    let ii, len, bf, result, obj;

    let filter = expression[0];
    result = EntityFilter.create();

    switch (filter) {
        case ANY:
        case ANY_FILTER:
        case ALL:
        case ALL_FILTER:
        case NONE:
        case NONE_FILTER:
        case INCLUDE:
        case INCLUDE_FILTER:
            if (expression[1] === ROOT) {
                result.add(ROOT);
            } else {
                obj = context.valueOf(expression[1], true);

                if (!obj) {
                    if (filter == ALL_FILTER) {
                        result.add(ROOT);
                        return;
                    }
                    return null;
                }
                bf = context.componentsToBitfield(context, obj);

                // filter = expression[0];
                switch (filter) {
                    case ALL_FILTER:
                        filter = ALL;
                        break;
                    case ANY_FILTER:
                        filter = ANY;
                        break;
                    case NONE_FILTER:
                        filter = NONE;
                        break;
                    case INCLUDE_FILTER:
                        filter = INCLUDE;
                        break;
                    default:
                        break;
                }
                // console.log('CONVERTED TO BF', filter, bf.toString(), bf.toJSON() );
                result.add(filter, bf);
            }
            break;
        case AND:
            expression = expression.slice(1); // _.rest(expression);

            for (ii = 0, len = expression.length; ii < len; ii++) {
                obj = gatherEntityFilters(context, expression[ii]);
                if (!obj) {
                    return null;
                }
                result.filters = result.filters.concat(obj.filters);
            }
            break;
        default:
            return null;
    }

    return result;
}
223655
@Override
	public boolean matches(Object entity) {
		T t = property.get(entity);
		
		for (T value : values) {
			if (t.compareTo(value) == 0) {
				return true;
			}
		}
		
		return false;
	}
195687
@Override
    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)
    {
        List entities = new ArrayList<E>();
        for (Object key : keys)
        {
            entities.add(find(entityClass, key));
        }
        return entities;
    }
721846
def find(self,
             regexp, negate_regexp=False,
             class_pattern=None,
             find_fnc=re.search,
             refresh_cache=False):
        
        if refresh_cache or not hasattr(self, 'cache'):
            self._populate_cache()

        b = self.cache
        split_regexp = regexp.split('/')

        # traverse as deep as possible in the cache
        # special case if the first character is not the root, i.e. not ""
        if split_regexp[0] == '':
            for d in split_regexp:
                if d in b:
                    b = b[d]
                else:
                    break
        else:
            b = b['']

        # perform the search
        for path, (obj, classname) in b['obj']:
            if class_pattern:
                if not fnmatch(classname, class_pattern):
                    continue
            joined_path = os.path.join(*['/', path, obj])
            result = find_fnc(regexp, joined_path)
            if (result is not None) ^ negate_regexp:
                yield joined_path, result
564313
def find_by_any(self, identifier, how):
        
        if "i" in how:
            match = self.find_by_id(identifier)
            if match:
                return match
        if "l" in how:
            match = self.find_by_localpath(identifier)
            if match:
                return match
        if "c" in how:
            match = self.find_by_canonical(identifier)
            if match:
                return match
395364
def matches_entities(obj, entities, strict=False):
    '''  '''
    if strict and set(obj.entities.keys()) != set(entities.keys()):
        return False

    comm_ents = list(set(obj.entities.keys()) & set(entities.keys()))
    for k in comm_ents:
        current = obj.entities[k]
        target = entities[k]
        if isinstance(target, (list, tuple)):
            if current not in target:
                return False
        elif current != target:
            return False
    return True
789535
def find_all(lookup)
      case lookup
      when ::Module
        each_node.grep(lookup)
      when ::Symbol
        each_node.find_all { |n| n.type == lookup }
      when ::String
        each_node.find_all { |n| n.source == lookup }
      when ::Regexp
        each_node.find_all { |n| n.source =~ lookup }
      else
        raise ::TypeError, "Expected class or symbol, got #{lookup.class}: #{lookup.inspect}"
      end
    end
988742
public List<ENTITY> find(List<Match> matches, List<Order> order) {
        return find(matches, order, 0, 0);
    }
949711
def find_entity(self, x):
        

        qstr = self.prefixes + """
            SELECT ?x WHERE {{
                ?x rn:hasName "{0}" .
            }}
            """.format(x)
        res = self.graph.query(qstr)
        if list(res):
            en = list(res)[0][0].toPython()
            return en
        else:
            return None
468800
def Search(self, text):
    """"""
    if isinstance(text, rdfvalue.RDFString):
      text = str(text)

    return self._regex.search(text)
1339477
def get_regular_expressions(taxonomy_name, rebuild=False, no_cache=False):
    
    # Translate the ontology name into a local path. Check if the name
    # relates to an existing ontology.
    onto_name, onto_path, onto_url = _get_ontology(taxonomy_name)
    if not onto_path:
        raise TaxonomyError("Unable to locate the taxonomy: '%s'."
                            % taxonomy_name)

    cache_path = _get_cache_path(onto_name)
    current_app.logger.debug(
        'Taxonomy discovered, now we load it '
        '(from cache: %s, onto_path: %s, cache_path: %s)'
        % (not no_cache, onto_path, cache_path)
    )

    if os.access(cache_path, os.R_OK):
        if os.access(onto_path, os.R_OK):
            if rebuild or no_cache:
                current_app.logger.debug(
                    "Cache generation was manually forced.")
                return _build_cache(onto_path, skip_cache=no_cache)
        else:
            # ontology file not found. Use the cache instead.
            current_app.logger.warning(
                "The ontology couldn't be located. However "
                "a cached version of it is available. Using it as a "
                "reference."
            )
            return _get_cache(cache_path, source_file=onto_path)

        if (os.path.getmtime(cache_path) >
                os.path.getmtime(onto_path)):
            # Cache is more recent than the ontology: use cache.
            current_app.logger.debug(
                "Normal situation, cache is older than ontology,"
                " so we load it from cache"
            )
            return _get_cache(cache_path, source_file=onto_path)
        else:
            # Ontology is more recent than the cache: rebuild cache.
            current_app.logger.warning(
                "Cache '%s' is older than '%s'. "
                "We will rebuild the cache" %
                (cache_path, onto_path)
            )
            return _build_cache(onto_path, skip_cache=no_cache)

    elif os.access(onto_path, os.R_OK):
        if not no_cache and\
                os.path.exists(cache_path) and\
                not os.access(cache_path, os.W_OK):
            raise TaxonomyError('We cannot read/write into: %s. '
                                'Aborting!' % cache_path)
        elif not no_cache and os.path.exists(cache_path):
            current_app.logger.warning(
                'Cache %s exists, but is not readable!' % cache_path)
        current_app.logger.info(
            "Cache not available. Building it now: %s" % onto_path)
        return _build_cache(onto_path, skip_cache=no_cache)

    else:
        raise TaxonomyError("We miss both source and cache"
                            " of the taxonomy: %s" % taxonomy_name)
817721
@Override
    public List find(List<IndexClause> ixClause, EntityMetadata m, boolean isRelation, List<String> relations,
            int maxResult, List<String> columns)
    {
        List<Object> entities = new ArrayList<Object>();
        Connection conn = null;
        try
        {
            // ixClause can be 0,1 or more!
            SlicePredicate slicePredicate = new SlicePredicate();

            if (columns != null && !columns.isEmpty())
            {
                List asList = new ArrayList(32);
                for (String colName : columns)
                {
                    if (colName != null)
                    {
                        asList.add(UTF8Type.instance.decompose(colName));
                    }
                }
                slicePredicate.setColumn_names(asList);
            }
            else
            {
                SliceRange sliceRange = new SliceRange();
                sliceRange.setStart(ByteBufferUtil.EMPTY_BYTE_BUFFER);
                sliceRange.setFinish(ByteBufferUtil.EMPTY_BYTE_BUFFER);
                slicePredicate.setSlice_range(sliceRange);
            }
            conn = getConnection();

            if (ixClause.isEmpty())
            {
                KeyRange keyRange = new KeyRange(maxResult);
                keyRange.setStart_key(ByteBufferUtil.EMPTY_BYTE_BUFFER);
                keyRange.setEnd_key(ByteBufferUtil.EMPTY_BYTE_BUFFER);

                if (m.isCounterColumnType())
                {
                    List<KeySlice> ks = conn.getClient().get_range_slices(new ColumnParent(m.getTableName()),
                            slicePredicate, keyRange, getConsistencyLevel());
                    entities = onCounterColumn(m, isRelation, relations, ks);

                }
                else
                {
                    List<KeySlice> keySlices = conn.getClient().get_range_slices(new ColumnParent(m.getTableName()),
                            slicePredicate, keyRange, getConsistencyLevel());

                    if (m.getType().isSuperColumnFamilyMetadata())
                    {
                        Map<ByteBuffer, List<SuperColumn>> qResults = ThriftDataResultHelper.transformThriftResult(
                                ColumnFamilyType.SUPER_COLUMN, keySlices, null);
                        entities = new ArrayList<Object>(qResults.size());
                        computeEntityViaSuperColumns(m, isRelation, relations, entities, qResults);
                    }
                    else
                    {
                        Map<ByteBuffer, List<Column>> qResults = ThriftDataResultHelper.transformThriftResult(
                                ColumnFamilyType.COLUMN, keySlices, null);
                        entities = new ArrayList<Object>(qResults.size());
                        computeEntityViaColumns(m, isRelation, relations, entities, qResults);
                    }
                }
            }
            else
            {
                entities = new ArrayList<Object>();
                for (IndexClause ix : ixClause)
                {
                    List<KeySlice> keySlices = conn.getClient().get_indexed_slices(new ColumnParent(m.getTableName()),
                            ix, slicePredicate, getConsistencyLevel());

                    Map<ByteBuffer, List<Column>> qResults = ThriftDataResultHelper.transformThriftResult(
                            ColumnFamilyType.COLUMN, keySlices, null);
                    // iterate through complete map and populate.
                    entities = new ArrayList<Object>(qResults.size());

                    computeEntityViaColumns(m, isRelation, relations, entities, qResults);
                }
            }
        }
        catch (InvalidRequestException irex)
        {
            log.error("Error during executing find of column family {}, Caused by: .", m.getTableName(), irex);
            throw new PersistenceException(irex);
        }
        catch (UnavailableException uex)
        {
            log.error("Error during executing find of column family {}, Caused by: .", m.getTableName(), uex);
            throw new PersistenceException(uex);
        }
        catch (TimedOutException tex)
        {
            log.error("Error during executing find of column family {}, Caused by: .", m.getTableName(), tex);
            throw new PersistenceException(tex);
        }
        catch (TException tex)
        {
            log.error("Error during executing find of column family {}, Caused by: .", m.getTableName(), tex);
            throw new PersistenceException(tex);
        }
        finally
        {

            releaseConnection(conn);
        }
        return entities;
    }
1245166
def getEntity(self, id=None, uri=None, match=None):
        

        if not id and not uri and not match:
            return None

        if type(id) == type("string"):
            uri = id
            id = None
            if not uri.startswith("http://"):
                match = uri
                uri = None
        if match:
            if type(match) != type("string"):
                return []
            res = []
            if ":" in match: # qname
                for x in self.classes:
                    if match.lower() in x.qname.lower():
                        res += [x]
                for x in self.properties:
                    if match.lower() in x.qname.lower():
                        res += [x]
            else:
                for x in self.classes:
                    if match.lower() in x.uri.lower():
                        res += [x]
                for x in self.properties:
                    if match.lower() in x.uri.lower():
                        res += [x]
            return res
        else:
            for x in self.classes:
                if id and x.id == id:
                    return x
                if uri and x.uri.lower() == uri.lower():
                    return x
            for x in self.properties:
                if id and x.id == id:
                    return x
                if uri and x.uri.lower() == uri.lower():
                    return x
            return None
489028
def firstStringInList(literalEntities, prefLanguage="en"):
    
    match = ""

    if len(literalEntities) == 1:
        match = literalEntities[0]
    elif len(literalEntities) > 1:
        for x in literalEntities:
            if getattr(x, 'language') and getattr(x,
                                                  'language') == prefLanguage:
                match = x
        if not match:  # don't bother about language
            match = literalEntities[0]
    return match
43857
def _search(self, trie, strings, limit=None):
        
        results = [trie.has_keys_with_prefix(s) for s in strings]
        if not any(results):
            return []
        for result, s in zip(results, strings):
            if result is True:
                return trie.values(s)[:limit]