コード例 #1
0
bool ManageSieveCommand::deleteScript()
{
    if ( !d->t ) {
        d->name = string();
        end();
        d->t = new Transaction( this );
        // select first, so the no() calls below work
        d->query =
            new Query( "select active from scripts "
                       "where owner=$1 and name=$2",
                       this );
        d->query->bind( 1, d->sieve->user()->id() );
        d->query->bind( 2, d->name );
        d->t->enqueue( d->query );
        // then delete
        Query * q = new Query( "delete from scripts where owner=$1 and "
                               "name=$2 and active='f'", this );
        q->bind( 1, d->sieve->user()->id() );
        q->bind( 2, d->name );
        d->t->enqueue( q );
        if ( d->no.isEmpty() )
            d->t->commit();
    }

    if ( !d->t->done() )
        return false;

    if ( d->t->failed() ) {
        no( "Couldn't delete script: " + d->t->error() );
    }
    else {
        Row * r = d->query->nextRow();
        if ( !r )
            no( "No such script" );
        else if ( r->getBoolean( "active" ) )
            no( "Can't delete active script" );
        else
            log( "Deleted script " + d->name );
    }

    return true;
}
コード例 #2
0
int main(int, char **argv)
{
    // get a file to read and builds map to support queries
    TextQuery file = build_textfile(argv[1]);

    // iterate with the user: prompt for a word to find and print results
    do {
        string sought;
        if (!get_word(sought)) break;
        // find all the occurrences of the requested string
        Query name(sought);
        Query notq = ~name;
        const set<TextQuery::line_no> locs = notq.eval(file);
        cout << "\nExecuted Query for: " << notq << endl;

        // report no matches
        print_results(locs, file);
    } while (true);  // loop indefinitely; the exit is inside the loop
    return 0;
}
コード例 #3
0
ファイル: SMTLIBLoggingSolver.cpp プロジェクト: h15/klee
		bool computeValue(const Query& query, ref<Expr> &result)
		{
			startQuery(query.withFalse(), "Value");

			bool success = solver->impl->computeValue(query, result);
			finishQuery(success);
			if (success)
			  os << ";   Result: " << result << "\n";
			os << "\n";
			return success;
		}
コード例 #4
0
JNIEXPORT jlong JNICALL Java_io_realm_internal_TableQuery_nativeFind(
    JNIEnv* env, jobject, jlong nativeQueryPtr, jlong fromTableRow)
{
    Query* pQuery = Q(nativeQueryPtr);
    Table* pTable = Ref2Ptr(pQuery->get_table());
    if (!QUERY_VALID(env, pQuery))
        return -1;
    // It's valid to go 1 past the end index
    if ((fromTableRow < 0) || (S(fromTableRow) > pTable->size())) {
        // below check will fail with appropriate exception
        (void) ROW_INDEX_VALID(env, pTable, fromTableRow);
        return -1;
    }

    try {
        size_t r = pQuery->find( S(fromTableRow) );
        return (r == not_found) ? jlong(-1) : jlong(r);
    } CATCH_STD()
    return -1;
}
コード例 #5
0
int main(int argc, char **argv)
{
  // gets file to read and builds map to support queries
  TextQuery file = get_file(argc, argv);

  // iterate with the user: prompt for a word to find and print results
  while (true) {
    string sought1, sought2, sought3;
    if (!get_words(sought1, sought2)) break;
    cout << "\nenter third word: ";
    cin >> sought3;
    // find all the occurrences of the requested string
    Query q = Query(sought1) & Query(sought2) | Query(sought3);
    cout << "\nExecuting Query for: " << q << endl;
    const auto results = q.eval(file);
    // report matches
    print(cout, results);
  }
  return 0;
}
コード例 #6
0
ファイル: TileNode.cpp プロジェクト: cicerolp/hashedcubes
void TileNode::queryTile(const SpatialDimension* hashing, const Query& query, Response& response, ulong level) const {
	const ulong d = level % hashing->key().size();

	if (query.evalTile(d)) {
		if (query.getTile(d) == _pivot.value() || (last() && util::intersects(_pivot.value(), query.getTile(d)))) {
			aggregateTile(hashing, query, response, level);

		} else if (_pivot.value().z < query.zoom) {
			if (_container[0] != nullptr) _container[0]->queryTile(hashing, query, response, level + 1);
			if (_container[1] != nullptr) _container[1]->queryTile(hashing, query, response, level + 1);
			if (_container[2] != nullptr) _container[2]->queryTile(hashing, query, response, level + 1);
			if (_container[3] != nullptr) _container[3]->queryTile(hashing, query, response, level + 1);
		} 		
	} else {
		if (_container[0] != nullptr) _container[0]->queryTile(hashing, query, response, level + 1);
		if (_container[1] != nullptr) _container[1]->queryTile(hashing, query, response, level + 1);
		if (_container[2] != nullptr) _container[2]->queryTile(hashing, query, response, level + 1);
		if (_container[3] != nullptr) _container[3]->queryTile(hashing, query, response, level + 1);
	}
}
コード例 #7
0
// static
Query* MultiFieldQueryParser::parse(const TCHAR* query, const TCHAR** _fields, const uint8_t* flags, Analyzer* analyzer) {
	BooleanQuery* bQuery = _CLNEW BooleanQuery();
	for (size_t i = 0; _fields[i]!=NULL; i++) {
	  //TODO: this is really confusing... why not refactor _fields and flags to use a array object.
	  //flags can be NULL since NULL == 0...
		/*if (flags[i] == NULL) {
			_CLLDELETE(bQuery);
			_CLTHROWA(CL_ERR_IllegalArgument, "_fields.length != flags.length");
		}*/
		QueryParser* qp = _CLNEW QueryParser(_fields[i], analyzer);
		Query* q = qp->parse(query);
		if (q!=NULL && // q never null, just being defensive
			(!(q->instanceOf(BooleanQuery::getClassName())) || ((BooleanQuery*)q)->getClauseCount()>0)) {
				bQuery->add(q, true, (BooleanClause::Occur)flags[i]);
		} else
			_CLLDELETE(q);
		_CLLDELETE(qp);
	}
	return bQuery;
}
コード例 #8
0
ファイル: dns.cpp プロジェクト: Iaroslav464/libtins
void DNS::add_query(const Query &query) {
    string new_str = encode_domain_name(query.dname());
    // Type (2 bytes) + Class (2 Bytes)
    new_str.insert(new_str.end(), sizeof(uint16_t) * 2, ' ');
    *(uint16_t*)&new_str[new_str.size() - 4] = Endian::host_to_be<uint16_t>(query.type());
    *(uint16_t*)&new_str[new_str.size() - 2] = Endian::host_to_be<uint16_t>(query.query_class());

    uint32_t offset = new_str.size(), threshold = answers_idx;
    update_records(answers_idx, answers_count(), threshold, offset);
    update_records(authority_idx, authority_count(), threshold, offset);
    update_records(additional_idx, additional_count(), threshold, offset);
    records_data.insert(
        records_data.begin() + threshold,
        new_str.begin(),
        new_str.end()
    );
    dns.questions = Endian::host_to_be<uint16_t>(
        questions_count() + 1
    );
}
コード例 #9
0
ファイル: MasterServer.cpp プロジェクト: xmulyj/sfs
bool MasterServer::get_fileinfo(const string &fid, FileInfo &fileinfo)
{
	//查找cache
	map<string, FileInfo>::iterator it = m_fileinfo_cache.find(fid);
	if(it != m_fileinfo_cache.end())
	{
		fileinfo = it->second;
		return true;
	}
	//查找数据库
	if(m_db_connection == NULL)
		return false;

	char sql_str[1024];
	snprintf(sql_str, 1024, "select fid,name,size,chunkid,chunkip,chunkport,findex,foffset from SFS.fileinfo_%s where fid='%s'"
							,fid.substr(0,2).c_str(), fid.c_str());
	Query query = m_db_connection->query(sql_str);
	StoreQueryResult res = query.store();
	if (!res || res.empty())
		return false;

	size_t i;
	for(i=0; i<res.num_rows(); ++i)
	{
		ChunkPath chunk_path;
		fileinfo.fid      = res[i]["fid"].c_str();
		fileinfo.name     = res[i]["name"].c_str();
		fileinfo.size     = atoi(res[i]["size"].c_str());
		chunk_path.id     = res[i]["chunkid"].c_str();
		chunk_path.ip     = res[i]["chunkip"].c_str();
		chunk_path.port   = atoi(res[i]["chunkport"].c_str());
		chunk_path.index  = atoi(res[i]["findex"].c_str());
		chunk_path.offset = atoi(res[i]["foffset"].c_str());

		fileinfo.add_chunkpath(chunk_path);
	}
	//添加到cache
	m_fileinfo_cache.insert(std::make_pair(fileinfo.fid, fileinfo));

	return true;
}
コード例 #10
0
ファイル: ggob.cpp プロジェクト: argarak/tw-light
void GobDefender::calculate()
{
	STACKTRACE;
	SpaceObject::calculate();
	if (!ship) {
		die();
		return;
	}
	if (!(random(3))) {
		if (next_shoot_time < gobgame->game_time) {
			SpaceObject *target = NULL;
			Query q;
			if (advanced)
				q.begin(this, OBJECT_LAYERS, 330 );
			else
				q.begin(this, OBJECT_LAYERS &~ bit(LAYER_SHIPS), 290 );
			while (q.currento && !target) {
				if (!q.currento->sameTeam(ship) && (q.currento->get_team() != gobgame->station_team) && !q.currento->isPlanet()) {
					SpaceLine *l = new PointLaser (
						this, palette_color[7], 2 + advanced, 40,
						this, q.currento
						);
					add(l);
					if (l->exists()) target = q.currento;
				}
				q.next();
			}
			q.end();
			if (target) {
				if (advanced)
					next_shoot_time = gobgame->game_time + 360;
				else
					next_shoot_time = gobgame->game_time + 560;
			}
		}
	}
	double a = base_phase + (gobgame->game_time % 120000) * ( PI2 / 1000.0) / 6;
	angle = normalize(a,PI2);
	pos = normalize(ship->normal_pos() + 270 * unit_vector ( angle ));
	return;
}
コード例 #11
0
ファイル: nph_mysql.cpp プロジェクト: dxli/XR-Fit
int updateError(int id, int error)
{
    Connection con(use_exceptions);
    try
    {
        ostringstream strbuf;
        unsigned int i = 0;
        con.connect(DATABASE, HOST, USER, PASSWORD);
        Query query = con.query();
        strbuf << "UPDATE tasks SET error="<<error<<" WHERE id=" << id;
        query.exec(strbuf.str());
	strbuf.str("");
        strbuf << "UPDATE tasks SET done=0 WHERE id=" << id;
        query.exec(strbuf.str());
	strbuf.str("");
        strbuf << "UPDATE tasks SET started=-1 WHERE id=" << id;
        query.exec(strbuf.str());
    }
    catch (const BadQuery& er)
    {
    // Handle any query errors
        cerr << "updateDone - Query error: " << er.what() << endl;
        return -1;
    }
    catch (const BadConversion& er)
    {
    // Handle bad conversions
        cerr << "updateDone - Conversion error: " << er.what() << endl <<
                "\tretrieved data size: " << er.retrieved <<
                ", actual size: " << er.actual_size << endl;
        return -1;
    }
    catch (const Exception& er)
    {
    // Catch-all for any other MySQL++ exceptions
        cerr << "updateDone - Error: " << er.what() << endl;
        return -1;
    }

    return 0;
}        
コード例 #12
0
    auto_ptr<DBClientCursor> SyncClusterConnection::_queryOnActive(const string &ns, Query query, int nToReturn, int nToSkip,
            const BSONObj *fieldsToReturn, int queryOptions, int batchSize ) {

        if ( _customQueryHandler && _customQueryHandler->canHandleQuery( ns, query ) ) {

            LOG( 2 ) << "custom query handler used for query on " << ns << ": "
                     << query.toString() << endl;

            return _customQueryHandler->handleQuery( _connAddresses,
                                                     ns,
                                                     query,
                                                     nToReturn,
                                                     nToSkip,
                                                     fieldsToReturn,
                                                     queryOptions,
                                                     batchSize );
        }

        for ( size_t i=0; i<_conns.size(); i++ ) {
            try {
                auto_ptr<DBClientCursor> cursor =
                    _conns[i]->query( ns , query , nToReturn , nToSkip , fieldsToReturn , queryOptions , batchSize );
                if ( cursor.get() )
                    return cursor;

                log() << "query on " << ns << ": " << query.toString() << " failed to: "
                      << _conns[i]->toString() << " no data" << endl;
            }
            catch ( std::exception& e ) {

                log() << "query on " << ns << ": " << query.toString() << " failed to: "
                      << _conns[i]->toString() << " exception: " << e.what() << endl;
            }
            catch ( ... ) {

                log() << "query on " << ns << ": " << query.toString() << " failed to: "
                      << _conns[i]->toString() << " exception" << endl;
            }
        }
        throw UserException( 8002 , str::stream() << "all servers down/unreachable when querying: " << _address );
    }
コード例 #13
0
ファイル: tristatetree.cpp プロジェクト: niklasf/chessx
TriStateTree::TriStateTree(const Query& query)
{
	m_state = Unknown;
	m_nodeCount = query.count();
	m_nodes = new Node[m_nodeCount];
	m_leafCount = 0;
	m_leafs = new Node*[m_nodeCount];
	Node** nodeStack = new Node*[m_nodeCount];
	int stackTop = -1;

	for (int element = 0; element < m_nodeCount; element++) {
		if (query.isElementSearch(element)) {
			/* search == leaf node, add to stack & add to list of leaf nodes */
			m_nodes[element].m_state = Unknown;
			m_nodes[element].m_operator = Search::NullOperator;
			m_nodes[element].m_parent = 0;
			m_nodes[element].m_leftChild = m_nodes[element].m_rightChild = 0;
			nodeStack[++stackTop] = &m_nodes[element];
			m_leafs[m_leafCount++] = &m_nodes[element];
		} else {
			/* operator == branch node, pop children off stack & add to stack */
			m_nodes[element].m_state = Unknown;
			m_nodes[element].m_operator = query.searchOperator(element);
			m_nodes[element].m_parent = 0;
			if (m_nodes[element].m_operator == Search::Not) {
				m_nodes[element].m_rightChild = 0;
			} else {
				m_nodes[element].m_rightChild = nodeStack[stackTop--];
				m_nodes[element].m_rightChild->m_parent = &m_nodes[element];
			}
			m_nodes[element].m_leftChild = nodeStack[stackTop--];
			m_nodes[element].m_leftChild->m_parent = &m_nodes[element];
			nodeStack[++stackTop] = &m_nodes[element];
		}
	}

	delete[] nodeStack;

	//stack should now be empty
	Q_ASSERT(stackTop == 0);
}
コード例 #14
0
static void generateSummary( Summary &summary, char *htmlInput, const char *queryStr, const char *urlStr ) {
	Xml xml;
	ASSERT_TRUE(xml.set(htmlInput, strlen(htmlInput), 0, CT_HTML));

	Words words;
	ASSERT_TRUE(words.set(&xml, true));

	Bits bits;
	ASSERT_TRUE(bits.set(&words));

	Url url;
	url.set(urlStr);

	Sections sections;
	ASSERT_TRUE(sections.set(&words, &bits, &url, "", CT_HTML));

	Query query;
	ASSERT_TRUE(query.set2(queryStr, langEnglish, true));

	LinkInfo linkInfo;
	memset ( &linkInfo , 0 , sizeof(LinkInfo) );
	linkInfo.m_lisize = sizeof(LinkInfo);

	Title title;
	ASSERT_TRUE(title.setTitle(&xml, &words, 80, &query, &linkInfo, &url, NULL, 0, CT_HTML, langEnglish));

	Pos pos;
	ASSERT_TRUE(pos.set(&words));

	Bits bitsForSummary;
	ASSERT_TRUE(bitsForSummary.setForSummary(&words));

	Phrases phrases;
	ASSERT_TRUE(phrases.set(&words, &bits));

	Matches matches;
	matches.setQuery(&query);
	ASSERT_TRUE(matches.set(&words, &phrases, &sections, &bitsForSummary, &pos, &xml, &title, &url, &linkInfo));

	summary.setSummary(&xml, &words, &sections, &pos, &query, 180, 3, 3, 180, &url, &matches, title.getTitle(), title.getTitleLen());
}
コード例 #15
0
ファイル: shpnarlu.cpp プロジェクト: argarak/tw-light
NaroolPoison::NaroolPoison(NaroolGas *gas, int nduration, float poison, Ship *nship, SpaceSprite *osprite) :
SpaceObject (gas, nship->normal_pos(), 0.0, osprite),
oship(nship),
poison(poison),
duration(nduration)
{
	STACKTRACE;
	target = oship;
	id |= NAROOL_POISON_ID;
	layer = LAYER_HOTSPOTS;
	start = TRUE;
	collide_flag_anyone = 0;
	Query q;
	for (q.begin(oship, bit(LAYER_HOTSPOTS), 10); q.current; q.next()) {
		if ((q.current->getID() == getID()) && (((NaroolPoison*)q.current)->oship == oship)) {
			((NaroolPoison*)q.current)->duration = duration;
			state = 0;
		}
	}
	q.end();
}
コード例 #16
0
ファイル: kernel_interface.cpp プロジェクト: AmirAbrams/haiku
status_t
packagefs_read_query(fs_volume* fsVolume, void* cookie, struct dirent* buffer,
	size_t bufferSize, uint32* _num)
{
	Volume* volume = (Volume*)fsVolume->private_volume;
	Query* query = (Query*)cookie;

	FUNCTION("volume: %p, query: %p\n", volume, query);

	VolumeWriteLocker volumeWriteLocker(volume);

	status_t error = query->GetNextEntry(buffer, bufferSize);
	if (error == B_OK)
		*_num = 1;
	else if (error == B_ENTRY_NOT_FOUND)
		*_num = 0;
	else
		return error;

	return B_OK;
}
コード例 #17
0
ファイル: database.cpp プロジェクト: Xackery/ZEQ
void Database::prepare(const std::string& sql, Query& query)
{
    sqlite3_stmt* stmt;
    int rc = sqlite3_prepare_v2(m_Sqlite, sql.c_str(), sql.length(), &stmt, nullptr);
    
    if (rc != SQLITE_OK)
    {
        //throw
    }
    
    query.setStmt(stmt);
}
コード例 #18
0
ファイル: Product.cpp プロジェクト: unixo/SENG
/**
   @brief Returns a product with given ID
 
   @param[in] aPid    The requested product ID
 
   @return A pointer to the requested Product, NULL if not found
 */
Product * Product::productByID(int aPid)
{
    // get an instance of the database
    Database &db = Database::instance();
    
    // ask Database for a valid connection to mySQL
    Connection *conn = db.getConnection();
    
    // obtain an instance of mysqlpp::Query and init it
    Query q = conn->query();
    q << SQL_PRODUCT_PROXY << aPid;    
    StoreQueryResult res = q.store();
    if (!res.empty()) {
        StoreQueryResult::const_iterator it = res.begin();
        Row row = *it;
        
        return new Product(row);
    }
    
    return NULL;
}
コード例 #19
0
ファイル: Category.cpp プロジェクト: unixo/SENG
/**
   @brief Fetch a category by specifing its ID
 
   @param[in]    aCid Category ID to be fetched
   @return    An instance of category
 */
Category *Category::categoryByID(int aCid)
{
    Category *cat = NULL;
    
    // get an instance of the database
    Database &db = Database::instance();
    
    // obtain an instance of mysqlpp::Query and init it
    Query q = db.getConnection()->query();
    q << SQL_CATEGORY_BYID << aCid;
    StoreQueryResult res = q.store();
    if (!res.empty()) {
        cat = new Category();
        cat->setIntForKey(KEY_CAT_CID, aCid);
        cat->setValueForKey(KEY_CAT_NAME, (string) res[0][KEY_CAT_NAME]);
        
        return cat;
    }

    return NULL;
}
コード例 #20
0
ファイル: shotresult.cpp プロジェクト: Sangil-Lee/RefCode
void ShotResult::deleteRemark()
{
	int currow = mtw_Shotremark->currentRow();
	if(currow < 0 ) return;
	if(messageBox("Are you sure to delete the record ?",APPLYCANCELBOX)==MSGNOK) return;
	map<int,int>::iterator mapIndexiter;
	try {
		mapIndexiter = mmapIndex.find(currow);
		int index = mapIndexiter->second;
		Query query = m_con.query();
		query << "delete from REMARKT where idx=%0";
		query.parse();
		query.use(index);
		readRemark(mshotno);
		//mtw_Shotremark->removeRow(currow);
	} catch (const BadQuery& er) {
		cerr << "Query error: " << er.what() << endl;
	} catch (const Exception& er) {
		cerr << er.what() << endl;
	};
}
コード例 #21
0
//static
Query* MultiFieldQueryParser::parse(const TCHAR** _queries, const TCHAR** _fields, Analyzer* analyzer)
{
	BooleanQuery* bQuery = _CLNEW BooleanQuery();
	for (size_t i = 0; _fields[i]!=NULL; i++)
	{
		if (_queries[i] == NULL) {
			_CLLDELETE(bQuery);
			_CLTHROWA(CL_ERR_IllegalArgument, "_queries.length != _fields.length");
		}
		// TODO: Reuse qp instead of creating it over and over again
		QueryParser* qp = _CLNEW QueryParser(_fields[i], analyzer);
		Query* q = qp->parse(_queries[i]);
		if (q!=NULL && // q never null, just being defensive
			(!(q->instanceOf(BooleanQuery::getClassName()) || ((BooleanQuery*)q)->getClauseCount() > 0))) {
				bQuery->add(q, true, BooleanClause::SHOULD);
		} else
			_CLLDELETE(q);
		_CLLDELETE(qp);
	}
	return bQuery;
}
コード例 #22
0
ファイル: user.cpp プロジェクト: aox/aox
Query * User::create( EventHandler * owner )
{
    Query *q = new Query( owner );

    if ( !valid() ) {
        q->setError( "Invalid user data." );
    }
    else if ( exists() ) {
        q->setError( "User exists already." );
    }
    else {
        d->q = 0;
        d->t = new Transaction( this );
        d->mode = UserData::Creating;
        d->state = Unverified;
        d->user = owner;
        d->result = q;
    }

    return q;
}
コード例 #23
0
ファイル: TestExtractTerms.cpp プロジェクト: Beirdo/beirdobot
void testExtractFromFuzzyQuery( CuTest * tc )
{
    Directory *     pIndex  = setUpIndex();
    IndexReader *   pReader = IndexReader::open( pIndex );
    TermSet         termSet;
    FuzzyQuery *    fuzzy;
    Term *          t1;
    Query *         rewrite;


    t1 = _CLNEW Term( _T("data"), _T("aaaab") );
    fuzzy = _CLNEW FuzzyQuery( t1, 0.7f );
    rewrite = fuzzy->rewrite( pReader );
    rewrite->extractTerms( &termSet );
    _CLLDECDELETE( t1 );

    assertEqualsMsg( _T( "wrong number of terms" ), 4, termSet.size() );
    for( TermSet::iterator itTerms = termSet.begin(); itTerms != termSet.end(); itTerms++ )
    {
        Term * pTerm = *itTerms;
        if(    0 != _tcscmp( _T( "aaaaa" ), pTerm->text()) 
            && 0 != _tcscmp( _T( "aaaab" ), pTerm->text())
            && 0 != _tcscmp( _T( "aaabb" ), pTerm->text())
            && 0 != _tcscmp( _T( "aaaac" ), pTerm->text()))
        {
            assertTrueMsg( _T( "wrong term" ), false );
        }
    }

    clearTermSet( termSet );
    if( rewrite != fuzzy )
        _CLDELETE( rewrite );
    _CLDELETE( fuzzy );
    
    pReader->close();
    _CLDELETE( pReader );

    closeIndex( pIndex );
    pIndex = NULL;
}
コード例 #24
0
ファイル: VRReasoner.cpp プロジェクト: infobeisel/polyvr
vector<VRReasoner::Result> VRReasoner::process(string query, VROntology* onto) {
    cout << "VRReasoner query: " << query << endl;

    map<string, Variable> vars;
    map<string, Result> results;
    list<Query> queries;
    queries.push_back(Query(query));

    int itr=0;
    int itr_max = 20;

    for(; queries.size() > 0 && itr < itr_max; itr++) {
        Query q = queries.back();
        cout << "query " << q.toString() << endl;

        if (q.query.state == 1) { queries.pop_back(); continue; };
        q.query.updateLocalVariables(vars, onto);

        if (Eval(q.query, vars, onto, queries)) {
            if (q.query.verb == "q") {
                string v = q.query.lvars[0].value;
                if (results.count(v) == 0) results[v] = Result();
                results[v].instances = vars[v].instances;
            }
        }

        for (auto s : q.statements) Eval(s, vars, onto, queries);
    }


    cout << " break after " << itr << " queries\n";
    for (auto r : results) {
        cout << "  result " << r.first << endl;
        for (auto i : r.second.instances) cout << "   instance " << i->toString() << endl;
    }

    vector<VRReasoner::Result> res;
    for (auto r : results) res.push_back(r.second);
    return res;
}
コード例 #25
0
ファイル: Product.cpp プロジェクト: unixo/SENG
/**
   @brief Show all configurations which include a given product
 
   @param[in] aPid    Given product ID 
 */
void Product::showCompatibleProducts(int aPid)
{
    // get an instance of the database
    Database& db = Database::instance();
    
    // ask Database for a valid connection to mySQL
    Connection *conn = db.getConnection();
    
    // obtain an instance of mysqlpp::Query and init it
    Query q = conn->query();
    q << "CALL offers_by_product(" << aPid << ")";
    StoreQueryResult res = q.store();
    
    for (int i = 1; q.more_results(); ++i) {
        cout << "\n\nCONFIGURATION DETAIL\n====================\n";        
        db.printResult(res);

        cout << "\nConfiguration includes the following products:\n"
                "=============================================\n";

        res = q.store_next();
        db.printResult(res);
        cout << endl;
        
        res = q.store_next();        
        StoreQueryResult res = q.store();
    }
}
コード例 #26
0
void DeviceManager::EnumerateDevices()
{

	XnStatus nRetVal = XN_STATUS_OK;

    xn::NodeInfoList deviceList;
    nRetVal = context_->EnumerateProductionTrees(XN_NODE_TYPE_DEVICE, NULL, deviceList, NULL);
    CHECK_RV(nRetVal, "Enumerate");
    
    for(xn::NodeInfoList::Iterator iter = deviceList.Begin(); iter != deviceList.End(); ++iter) 
    { 
        xn::NodeInfo node = (*iter);
        
        SensorDevice* sensor = new SensorDevice();
        char deviceName[256];
        
        //Create Device Context in the global production tree
        nRetVal = context_->CreateProductionTree(node);
        CHECK_RV(nRetVal, "Create Device");
        
        Query query;
        query.AddNeededNode(node.GetInstanceName());
        
        xnOSMemCopy(deviceName, node.GetInstanceName(), xnOSStrLen(node.GetInstanceName()));
        sensor->SetDeviceName(deviceName);
        
        //Create Image and Depth generators for this device
        nRetVal = context_->CreateAnyProductionTree(XN_NODE_TYPE_IMAGE, &query, *(sensor->GetImageGenerator()));
        CHECK_RV(nRetVal, "Create Image Generator");
        nRetVal = context_->CreateAnyProductionTree(XN_NODE_TYPE_DEPTH, &query, *(sensor->GetDepthGenerator()));
        CHECK_RV(nRetVal, "Create Depth Generator");
        
        //Align the RGB and Depth Cameras
        sensor->AlignSensors();
        
        devices_.push_back(sensor);
	}
	
	context_->StartGeneratingAll();
}
コード例 #27
0
    //-------------------------------------------------------------
    vector<Media> API::search( Query query ){
        vector<Media> toReturn;
        if ( query.api_key == "" ) query.api_key = api_key;

        if ( query.requiresAuthentication() && !bAuthenticated ){
            ofLogWarning("You must authenticate to use some of these parameters!");
            return toReturn;
        }

        string result = makeAPICall("flickr.photos.search", query.getQueryParameters(), FLICKR_XML, query.requiresAuthentication());
        ofxXmlSettings xml; xml.loadFromBuffer(result);
        xml.pushTag("rsp");{
            xml.pushTag("photos"); {

                for (int i=0; i<xml.getNumTags("photo"); i++){
                    Media med;

                    med.id = xml.getAttribute("photo", "id", "", i);
                    med.farm = xml.getAttribute("photo", "farm", "", i);
                    med.secret = xml.getAttribute("photo", "secret", "", i);
                    med.server = xml.getAttribute("photo", "server", "", i);
                    med.originalsecret = xml.getAttribute("photo", "originalsecret", "", i);
                    med.originalformat = xml.getAttribute("photo", "originalformat", "", i);

                    string t = xml.getAttribute("photo", "media", "", i);
                    if ( t == "photo"){
                        med.type = FLICKR_PHOTO;
                    } else if ( t == "video"){
                        med.type = FLICKR_VIDEO;
                    } else {
                        med.type = FLICKR_UNKNOWN;
                    }

                    toReturn.push_back(med);
                }

            } xml.popTag();
        } xml.popTag();
        return toReturn;
    }
コード例 #28
0
ファイル: dnsquery.cpp プロジェクト: obscure76/dnsquery
        void initializeServices()
        {
            if (conn.connect(dbname.c_str(), dbserver.c_str(), dbuser.c_str(), dbpswd.c_str())) {
                cout<<"Connected to DB";
            } else {
                cout<<"Could not connect to DB";
                exit(-1);
            }
            try {
                Query query = conn.query();
                query << 
                    "  CREATE TABLE IF NOT EXISTS mytable (" <<
                    "  domain CHAR(100) NOT NULL PRIMARY KEY, " <<
                    "  count INT UNSIGNED, " <<
                    "  mean DOUBLE UNSIGNED, " <<
                    "  sumofsq DOUBLE UNSIGNED, "<<
                    "  stddev DOUBLE UNSIGNED, " << 
                    "  startTime  TIMESTAMP , " <<
                    "  endTime  TIMESTAMP ); ";
                query.execute();
                cout<<"Table created";
            } catch (const Exception& er){
                cerr << er.what() << std::endl;
                exit(-1);
            }

            if (ldns_resolver_new_frm_file(&res, NULL) != LDNS_STATUS_OK)
            {
                fprintf(stderr, "%s", "Could not create resolver obj");
                exit(-1);
            }
            ldns_resolver_set_dnssec(res, true);
            ldns_resolver_set_dnssec_cd(res, true);
            uint8_t fam = LDNS_RESOLV_INETANY;
            ldns_resolver_set_ip6(res, fam);	
            if (!res) {
                fprintf(stderr, "%s", "Could not create resolver obj");
                exit(-1);
            }
        }
コード例 #29
0
ファイル: DynamicModel.cpp プロジェクト: AndyCoder/tomahawk
void
DynamicModel::trackResolveFinished( bool success )
{
    Q_UNUSED( success );

    Query* q = qobject_cast<Query*>( sender() );

    tDebug() << "Got resolveFinished in DynamicModel" << q->track()->toString();
    if ( !m_waitingFor.contains( q ) )
        return;

    if ( !q->playable() )
    {
        tDebug() << "Got not playable or resolved track:" << q->track()->toString() << m_lastResolvedRow << m_currentAttempts;
        m_currentAttempts++;

        int curAttempts = m_startingAfterFailed ? m_currentAttempts - 20 : m_currentAttempts; // if we just failed, m_currentAttempts includes those failures
        if( curAttempts < 20 ) {
            qDebug() << "FETCHING MORE!";
            m_playlist->generator()->fetchNext();
        } else {
            m_startingAfterFailed = true;
            emit trackGenerationFailure( tr( "Could not find a playable track.\n\nPlease change the filters or try again." ) );
        }
    }
    else
    {
        qDebug() << "Got successful resolved track:" << q->track()->toString() << m_lastResolvedRow << m_currentAttempts;

        if ( m_currentAttempts > 0 ) {
            qDebug() << "EMITTING AN ASK FOR COLLAPSE:" << m_lastResolvedRow << m_currentAttempts;
            emit collapseFromTo( m_lastResolvedRow, m_currentAttempts );
        }
        m_currentAttempts = 0;
        m_searchingForNext = false;

        emit checkForOverflow();
    }
    m_waitingFor.removeAll( q );
}
コード例 #30
0
ファイル: mongo_query.cpp プロジェクト: luanhailiang/engine
/*
 * ok, err = query:where(jscode)
 * ok, err = query:where(jscode, lua_table or json_str)
 */
static int query_where(lua_State *L) {
    int n = lua_gettop(L);
    Query *query = userdata_to_query(L, 1);
    std::string jscode = luaL_checkstring(L, 2);

    if (n > 2) {
        BSONObj scope;
        try {
            int type = lua_type(L, 3);
            if (type == LUA_TSTRING) {
                const char *jsonstr = luaL_checkstring(L, 3);
                scope = fromjson(jsonstr);
            } else if (type == LUA_TTABLE) {
                lua_to_bson(L, 3, scope);
            } else {
                throw(LUAMONGO_REQUIRES_JSON_OR_TABLE);
            }
                query->where(jscode, scope);
        } catch (std::exception &e) {
            lua_pushboolean(L, 0);
            lua_pushfstring(L, LUAMONGO_ERR_QUERY_FAILED, e.what());
            return 2;
        } catch (const char *err) {
            lua_pushnil(L);
            lua_pushstring(L, err);
            return 2;
        }
    } else {
        try {
            query->where(jscode);
        } catch (std::exception &e) {
            lua_pushboolean(L, 0);
            lua_pushfstring(L, LUAMONGO_ERR_QUERY_FAILED, e.what());
            return 2;
        }
    }

    lua_pushboolean(L, 1);
    return 1;
}