Fetches the example queries for a specific corpus.

@param rawCorpusNames specifies the corpora the examples are fetched from.
484717
@GET
  @Path("corpora/example-queries/")
  @Produces(MediaType.APPLICATION_XML)
  public List<ExampleQuery> getExampleQueries(
    @QueryParam("corpora") String rawCorpusNames) throws WebApplicationException
  {

    Subject user = SecurityUtils.getSubject();
      
    try
    {
      String[] corpusNames;
      if (rawCorpusNames != null)
      {
        corpusNames = rawCorpusNames.split(",");
      }
      else
      {
        List<AnnisCorpus> allCorpora = queryDao.listCorpora();
        corpusNames = new String[allCorpora.size()];
        for (int i = 0; i < corpusNames.length; i++)
        {
          corpusNames[i] = allCorpora.get(i).getName();
        }
      }

      List<String> allowedCorpora = new ArrayList<>();

      // filter by which corpora the user is allowed to access
      for (String c : corpusNames)
      {
        if (user.isPermitted("query:*:" + c))
        {
          allowedCorpora.add(c);
        }
      }

      List<Long> corpusIDs = queryDao.mapCorpusNamesToIds(allowedCorpora);
      return queryDao.getExampleQueries(corpusIDs);
    }
    catch (Exception ex)
    {
      log.error("Problem accessing example queries", ex);
      throw new WebApplicationException(ex, 500);
    }
  }
365881
public DocServiceBuilder exampleRequestForMethod(String serviceName, String methodName,
                                                     Object... exampleRequests) {
        requireNonNull(exampleRequests, "exampleRequests");
        return exampleRequestForMethod(serviceName, methodName, ImmutableList.copyOf(exampleRequests));
    }
48992
private Collection<String> createEnablesQuery() {
        Collection<String> query = null;
        Collection<String> requiredFeatures = getRequireFeature();
        if (requiredFeatures != null) {
            query = new ArrayList<String>();
            for (String required : requiredFeatures) {
                String temp = "wlpInformation.provideFeature=" + required;

                String version = findVersion();
                if (version != null) {
                    temp += "&wlpInformation.appliesToFilterInfo.minVersion.value=";
                    temp += version;
                }

                temp += "&type=";
                temp += getType().getValue(); // get the long name of the Type
                query.add(temp);
            }
        }
        return query;
    }
929374
def get_sentences(corpus):
		'''
		
		'''
		assert isinstance(corpus, ParsedCorpus)
		return itertools.chain(*[[[corpus._term_idx_store.getidxstrict(t.lower_) for t in sent
		                           if not t.is_punct]
		                          for sent in doc.sents]
		                         for doc in corpus.get_parsed_docs()])
395402
private List onQuery(EntityMetadata m, Client client)
    {
        boolean useLuceneOrES = !MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata());
        QueryTranslator translator = new QueryTranslator();
        List<Map<String, Object>> columnsToOutput = translator.getColumnsToOutput(m, getKunderaQuery(), useLuceneOrES);
        translator.translate(getKunderaQuery(), m, useLuceneOrES);
        Filter filters = translator.getFilters();
        if (!translator.isWhereOrAggregationQuery() || !useLuceneOrES)
        {
            return ((HBaseClient) client).findData(m, null, translator.getStartRow(), translator.getEndRow(),
                    columnsToOutput, filters);
        }
        else
        {
            return populateUsingLucene(m, client, null, null);
        }
    }
886516
private void manageService(Entity rawEntity){

        CloudFoundryService cloudFoundryService;
        if (rawEntity instanceof CloudFoundryService){

            cloudFoundryService = (CloudFoundryService) rawEntity;
        
            String serviceName = cloudFoundryService
                    .getConfig(CloudFoundryService.SERVICE_INSTANCE_NAME);


            if (!Strings.isEmpty(serviceName)){

                Entities.waitForServiceUp(cloudFoundryService,
                        cloudFoundryService.getConfig(BrooklynConfigKeys.START_TIMEOUT));

                bindingServiceToEntity(serviceName);
                setCredentialsOnService(cloudFoundryService);
                cloudFoundryService.operation(getEntity());
            } else {
                log.error("Trying to get service instance name from {}, but getting null",
                        cloudFoundryService);
            }
        } else {
            log.error("The service entity {} is not available from the application {}",
                    new Object[]{rawEntity, getEntity()});

            throw new NoSuchElementException("No entity matching id " + rawEntity.getId() +
                    " in Management Context "+getEntity().getManagementContext()+
                    " during entity service binding "+getEntity().getId());
        }
    }
877003
def simpleQuery(self, queryType, rawResults = False, **queryArgs) :
        
        return SimpleQuery(self, queryType, rawResults, **queryArgs)
367322
def fetchFirstExample(self, exampleDict, rawResults = False) :
        """"""
        return self.simpleQuery('first-example', rawResults = rawResults, example = exampleDict)
1285414
def _get_db_refs(term):
    """"""
    db_refs = {}
    # Here we extract the text name of the Agent
    # There are two relevant tags to consider here.
    # The <text> tag typically contains a larger phrase surrounding the
    # term but it contains the term in a raw, non-canonicalized form.
    # The <name> tag only contains the name of the entity but it is
    # canonicalized. For instance, MAP2K1 appears as MAP-2-K-1.
    agent_text_tag = term.find('name')
    if agent_text_tag is not None:
        db_refs['TEXT'] = agent_text_tag.text
        # If we have some drum-terms, the matched-name of the first
        # drum-term (e.g. "MAP2K1") is a better value for TEXT than
        # the name of the TERM (e.g. "MAP-2-K-1") so we put that in there
        drum_terms = term.findall('drum-terms/drum-term')
        if drum_terms:
            matched_name = drum_terms[0].attrib.get('matched-name')
            if matched_name:
                db_refs['TEXT'] = matched_name

    # We make a list of scored grounding terms from the DRUM terms
    grounding_terms = _get_grounding_terms(term)
    if not grounding_terms:
        # This is for backwards compatibility with EKBs without drum-term
        # scored entries. It is important to keep for Bioagents
        # compatibility.
        dbid = term.attrib.get('dbid')
        if dbid:
            dbids = dbid.split('|')
            for dbname, dbid in [d.split(':') for d in dbids]:
                if not db_refs.get(dbname):
                    db_refs[dbname] = dbid
        return db_refs, None, []


    # This is the INDRA prioritization of grounding name spaces. Lower score
    # takes precedence.
    ns_priority = {
        'HGNC': 1,
        'UP': 1,
        'FPLX': 2,
        'CHEBI': 3,
        'PC': 3,
        'GO': 4,
        'FA': 5,
        'XFAM': 5,
        'NCIT': 5
    }
    # We get the top priority entry from each score group
    score_groups = itertools.groupby(grounding_terms, lambda x: x['score'])
    top_per_score_group = []
    ambiguities = []
    for score, group in score_groups:
        entries = list(group)
        for entry in entries:
            priority = 100
            for ref_ns, ref_id in entry['refs'].items():
                # Skip etc UP entries
                if ref_ns == 'UP' and ref_id == 'etc':
                    continue
                try:
                    priority = min(priority, ns_priority[ref_ns])
                except KeyError:
                    pass
                if ref_ns == 'UP':
                    if not up_client.is_human(ref_id):
                        priority = 4
            entry['priority'] = priority
        if len(entries) > 1:
            top_entry = entries[0]
            top_idx = 0
            for i, entry in enumerate(entries):
                # We take the lowest priority entry within the score group
                # as the top entry
                if entry['priority'] < top_entry['priority']:
                    # This is a corner case in which a protein family
                    # should be prioritized over a specific protein,
                    # specifically when HGNC was mapped from NCIT but
                    # FPLX was not mapped from NCIT, the HGNC shouldn't
                    # take precedence.
                    if entry.get('comment') == 'HGNC_FROM_NCIT' and \
                        'FPLX' in top_entry['refs'] and \
                        top_entry.get('comment') != 'FPLX_FROM_NCIT':
                        continue
                    top_entry = entry
                    top_idx = i
            for i, entry in enumerate(entries):
                if i == top_idx:
                    continue
                if (entry['priority'] - top_entry['priority']) <= 1:
                    ambiguities.append((top_entry, entry))
        else:
            top_entry = entries[0]
        top_per_score_group.append(top_entry)
    # Get the top priority for each score group
    priorities = [entry['priority'] for entry in top_per_score_group]

    # By default, we coose the top priority entry from the highest score group
    top_grounding = top_per_score_group[0]
    # Sometimes the top grounding has much lower priority and not much higher
    # score than the second grounding. Typically 1.0 vs 0.82857 and 5 vs 2.
    # In this case we take the second entry. A special case is handled where
    # a FPLX entry was mapped from FA, in which case priority difference of < 2
    # is also accepted.
    if len(top_per_score_group) > 1:
        score_diff = top_per_score_group[0]['score'] - \
                     top_per_score_group[1]['score']
        priority_diff = top_per_score_group[0]['priority'] - \
                        top_per_score_group[1]['priority']
        if score_diff < 0.2 and (priority_diff >= 2 or \
            top_per_score_group[0].get('comment') == 'FPLX_FROM_FA'):
            top_grounding = top_per_score_group[1]
    relevant_ambiguities = []
    for amb in ambiguities:
        if top_grounding not in amb:
            continue
        if top_grounding == amb[0]:
            relevant_ambiguities.append({'preferred': amb[0],
                                         'alternative': amb[1]})
        else:
            relevant_ambiguities.append({'preferred': amb[1],
                                         'alternative': amb[0]})

    for k, v in top_grounding['refs'].items():
        db_refs[k] = v

    # Now standardize db_refs to the INDRA standards
    # We need to add a prefix for CHEBI
    chebi_id = db_refs.get('CHEBI')
    if chebi_id and not chebi_id.startswith('CHEBI:'):
        db_refs['CHEBI'] = 'CHEBI:%s' % chebi_id
    # We need to strip the trailing version number for XFAM and rename to PF
    pfam_id = db_refs.get('XFAM')
    if pfam_id:
        pfam_id = pfam_id.split('.')[0]
        db_refs.pop('XFAM', None)
        db_refs['PF'] = pfam_id
    # We need to add GO prefix if it is missing
    go_id = db_refs.get('GO')
    if go_id:
        if not go_id.startswith('GO:'):
            db_refs['GO'] = 'GO:%s' % go_id
    # We need to deal with Nextprot families
    nxp_id = db_refs.get('FA')
    if nxp_id:
        db_refs.pop('FA', None)
        db_refs['NXPFA'] = nxp_id
    # We need to rename PC to PUBCHEM
    pc_id = db_refs.get('PC')
    if pc_id:
        db_refs.pop('PC', None)
        db_refs['PUBCHEM'] = pc_id

    # Here we also get and return the type, which is a TRIPS
    # ontology type. This is to be used in the context of
    # Bioagents.
    ont_type = top_grounding['type']

    return db_refs, ont_type, relevant_ambiguities
992921
def query(self, name, node):
        
        #log.debug('searching schema for (%s)', name)
        qref = qualify(name, node, node.namespace())
        query = BlindQuery(qref)
        result = query.execute(self.schema)
        return (result, [])
1090505
public DocServiceBuilder exampleRequestForMethod(String serviceName, String methodName,
                                                     Iterable<?> exampleRequests) {
        requireNonNull(serviceName, "serviceName");
        requireNonNull(methodName, "methodName");
        requireNonNull(exampleRequests, "exampleRequests");

        for (Object e : exampleRequests) {
            requireNonNull(e, "exampleRequests contains null.");
            exampleRequest0(serviceName, methodName,
                            serializeExampleRequest(serviceName, methodName, e));
        }
        return this;
    }
866121
protected List<String> getPersistQueries(EntityMetadata entityMetadata, Object entity,
        org.apache.cassandra.thrift.Cassandra.Client conn, List<RelationHolder> rlHolders, Object ttlColumns) {
        List<String> queries;
        if (entityMetadata.isCounterColumnType()) {
            queries = createUpdateQueryForCounter(entityMetadata, entity, conn, rlHolders);
        } else {
            queries = createInsertQuery(entityMetadata, entity, conn, rlHolders, ttlColumns);
        }
        return queries;
    }
1290491
def get_raw_query(self):
        
        query = self.base_query.copy()
        search_query = self.search_query.copy()
        query.update(search_query)

        # Add sorting criteria
        sorting = self.resolve_sorting(query)
        query.update(sorting)

        # Check if sort_on is an index and if is sortable. Otherwise, assume
        # the sorting must be done manually
        catalog = api.get_tool(self.catalog_name)
        sort_on = query.get("sort_on", None)
        if sort_on and not self.is_sortable_index(sort_on, catalog):
            del(query["sort_on"])
        return query
801241
def fetch(self):
        
        params = values.of({})

        payload = self._version.fetch(
            'GET',
            self._uri,
            params=params,
        )

        return EntityInstance(
            self._version,
            payload,
            service_sid=self._solution['service_sid'],
            identity=self._solution['identity'],
        )
812647
public String[] loadAllRealNames ()
        throws PersistenceException
    {
        final ArrayList<String> names = new ArrayList<String>();

        // do the query
        execute(new Operation<Object>() {
            public Object invoke (Connection conn, DatabaseLiaison liaison)
                throws PersistenceException, SQLException
            {
                Statement stmt = conn.createStatement();
                try {
                    String query = "select realname from users";
                    ResultSet rs = stmt.executeQuery(query);
                    while (rs.next()) {
                        names.add(rs.getString(1));
                    }

                    // nothing to return
                    return null;

                } finally {
                    JDBCUtil.close(stmt);
                }
            }
        });

        // finally construct our result
        return names.toArray(new String[names.size()]);
    }
673658
def fetchall_with_fieldnames(self, sql: str, *args) \
            -> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        self.db_exec_with_cursor(cursor, sql, *args)
        try:
            rows = cursor.fetchall()
            fieldnames = [i[0] for i in cursor.description]
            return rows, fieldnames
        except:  # nopep8
            log.exception("fetchall_with_fieldnames: SQL was: " + sql)
            raise
1206797
def query(self, name):
        
        #log.debug('searching schema for (%s)', name)
        schema = self.schema
        wsdl = self.wsdl()
        if wsdl is None:
            qref = qualify(name, schema.root, schema.tns)
        else:
            qref = qualify(name, wsdl.root, wsdl.tns)
        query = BlindQuery(qref)
        result = query.execute(schema)
        return (result, [])