IntegerSet IntegerSet::set_union(const IntegerSet& o){ IntegerSet out; for(int i = 0; i < num_elements; i++){ out.add(elements[i]); } for(int i = 0; i < o.num_elements; i++){ out.add(o.elements[i]); } return out; }
void testParse2() { IntegerSet a; a.parse(" [-3,2] 5 8-9 10- "); // insert(-3,2); insert(5); insert(8,9); insert(10,INT_MAX); unit_assert(a.intervalCount() == 3); unit_assert(a.size() == 9ul + numeric_limits<int>::max()-10+1); vector<int> b; IntegerSet::const_iterator it = a.begin(); for (int i=0; i<11; ++i, ++it) // don't copy to the end() unless you have lots of time and space ;) b.push_back(*it); unit_assert(b.size() == 11); unit_assert(b[0] == -3); unit_assert(b[1] == -2); unit_assert(b[2] == -1); unit_assert(b[3] == 0); unit_assert(b[4] == 1); unit_assert(b[5] == 2); unit_assert(b[6] == 5); unit_assert(b[7] == 8); unit_assert(b[8] == 9); unit_assert(b[9] == 10); unit_assert(b[10] == 11); }
IntegerSet IntegerSet::intersectionOfSets(IntegerSet set1, IntegerSet set2){ IntegerSet returnSet; for(int i = 0; i < setSize; i++) if(set1.getItem(i)==1 && set2.getItem(i)==1) returnSet.insertItem(i); return returnSet; }
void testScanEventSet(SpectrumListPtr sl) { if (os_) *os_ << "testScanEventSet:\n"; IntegerSet scanEventSet; scanEventSet.insert(0,0); scanEventSet.insert(2,3); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_ScanEventSet(scanEventSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 7); unit_assert(filter.spectrumIdentity(0).id == "scan=100"); unit_assert(filter.spectrumIdentity(1).id == "scan=102"); unit_assert(filter.spectrumIdentity(2).id == "scan=103"); unit_assert(filter.spectrumIdentity(3).id == "scan=104"); unit_assert(filter.spectrumIdentity(4).id == "scan=106"); unit_assert(filter.spectrumIdentity(5).id == "scan=107"); unit_assert(filter.spectrumIdentity(6).id == "scan=108"); }
bool IntegerSet::isEqual(IntegerSet set1, IntegerSet set2){ for(int i = 0; i < setSize; i++){ if(set1.getItem(i) != set2.getItem(i)) return false; } return true; }
int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); RUN_ALL_TESTS(); std::getchar(); // keep console window open until Return keystroke IntegerSet iS; iS.insertElement(5); iS.insertElement(99); std::cout << iS; }
IntegerSet Command::set( bool parseMsns = false ) { IntegerSet result; ImapSession *s = 0; if ( imap() ) s = imap()->session(); uint n1 = 0, n2 = 0; bool done = false; while ( ok() && !done ) { char c = nextChar(); if ( c == '*' ) { step(); n1 = 0; if ( s ) n1 = s->largestUid(); else error( Bad, "Need a mailbox session to use * as an UID/MSN" ); } else if ( c >= '1' && c <= '9' ) { if ( parseMsns ) n1 = msn(); else n1 = nzNumber(); } else { error( Bad, "number or '*' expected, saw: " + following() ); } c = nextChar(); if ( c == ':' ) { if ( n2 ) error( Bad, "saw colon after range (" + fn( n1 ) + ":" + fn( n2 ) + "), saw:" + following() ); n2 = n1; n1 = 0; step(); } else if ( ok() ) { if ( n2 ) result.add( n1, n2 ); else result.add( n1 ); n1 = 0; n2 = 0; if ( c == ',' ) step(); else done = true; } }; return result; }
void ImapSession::recordExpungedFetch( const IntegerSet & set ) { IntegerSet already = set.intersection( d->expungedFetched ); d->expungedFetched.add( set ); if ( already.isEmpty() ) return; (void)new ImapByeResponse( d->i, "BYE [CLIENTBUG] " "These messages have been expunged: " + set.set() ); }
IntegerSet IntegerSet::set_difference(const IntegerSet& o){ IntegerSet out; // for(int i = 0; i < o.num_elements; i++){ // if(!contains(o.elements[i])){ // out.add(o.elements[i]); // } // } for(int i = 0; i < num_elements; i++){ if(!o.contains(elements[i])){ out.add(elements[i]); } } return out; }
void MaildirMailbox::readSubDir( const EString & sub ) { DIR * dir = opendir( ( d->path + "/" + sub ).cstr() ); if ( !dir ) return; Map<EStringList> files; IntegerSet times; struct dirent * de = readdir( dir ); while ( de ) { if ( de->d_name[0] >= '0' && de->d_name[0] <= '9' ) { EString n( de->d_name ); int i = n.find( '.' ); bool ok = false; if ( i > 0 ) i = n.mid( 0, i ).number( &ok ); if ( ok ) { EString * f = new EString ( sub ); f->append( "/" ); f->append( n ); EStringList * l = 0; l = files.find( i ); if ( !l ) { l = new EStringList; files.insert( i, l ); times.add( i ); // XXX: how very evil } l->append( f ); } else { // no dot in the name... what is it? } } de = readdir( dir ); } closedir( dir ); while ( !times.isEmpty() ) { uint n = times.smallest(); times.remove( n ); EStringList * l = files.find( n ); EStringList::Iterator i( *l ); while ( i ) { d->messages.append( *i ); ++i; } } }
Duration RandomInsertTestImpl(IntegerSet set, int n) { std::mt19937 random(5757); std::uniform_int_distribution<> distribution(0, 16384); auto start = Now(); for (int i = 0; i < n; ++i) { set.insert(distribution(random)); } return Now() - start; }
void SessionInitialiser::recordExpunges() { if ( !d->expunges ) return; Row * r = 0; IntegerSet uids; while ( (r=d->expunges->nextRow()) != 0 ) uids.add( r->getInt( "uid" ) ); if ( uids.isEmpty() ) return; List<Session>::Iterator i( d->sessions ); while ( i ) { Session * s = i; ++i; s->expunge( uids ); } }
void ImapSession::emitUpdates( Transaction * t ) { if ( d->emitting ) return; d->emitting = true; bool work = false; Scope x( d->l ); IntegerSet e; e.add( expunged() ); e.remove( d->expungesReported ); if ( !e.isEmpty() ) { d->expungesReported.add( e ); while ( !e.isEmpty() ) { (void)new ImapExpungeResponse( e.smallest(), this ); work = true; e.remove( e.smallest() ); } } emitFlagUpdates( t ); if ( d->uidnext < uidnext() ) { if ( !d->existsResponse ) { d->existsResponse = new ImapSessionData::ExistsResponse( this, d ); work = true; } if ( !d->recentResponse ) { d->recentResponse = new ImapSessionData::RecentResponse( this, d ); work = true; } if ( !d->uidnextResponse ) { d->uidnextResponse = new ImapSessionData::UidnextResponse( this, d ); work = true; } } if ( d->nms < nextModSeq() ) d->nms = nextModSeq(); if ( d->changed.isEmpty() ) d->cms = d->nms; if ( work ) d->i->unblockCommands(); d->i->emitResponses(); d->emitting = false; }
int main(){ // Create objects IntegerSet A; IntegerSet B; IntegerSet C; // Fill sets cin >> A; cout << "\n\t" << A; cin >> B; cout << "\n\t" << B; // Increment and Decrement Test cout << "\n\tIncrementing each element in A" << endl; A = ++A; cout << "\n\t" << A << endl; cout << "\n\tDecrementing each element in B" << endl; B = --B; cout << "\n\t" << B << endl; // Mathematical functions C = A^B; cout << "\n\tThe intersection of Set A and Set B is: "; C.printSet(); C = A+B; cout << "\n\tThe union of Set A and Set B is: "; C.printSet(); C = A-B; cout << "\n\tThe difference of Set A and Set B is: "; C.printSet(); bool equal = (A==B); if(equal) cout << "\n\tA and B are equal"; cout << endl; }
void testMSLevelSet(SpectrumListPtr sl) { if (os_) *os_ << "testMSLevelSet:\n"; IntegerSet msLevelSet; msLevelSet.insert(1); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_MSLevelSet(msLevelSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 4); unit_assert(filter.spectrumIdentity(0).id == "scan=100"); unit_assert(filter.spectrumIdentity(1).id == "scan=103"); unit_assert(filter.spectrumIdentity(2).id == "scan=106"); unit_assert(filter.spectrumIdentity(3).id == "scan=109"); IntegerSet msLevelSet2; msLevelSet2.insert(2); SpectrumList_Filter filter2(sl, SpectrumList_FilterPredicate_MSLevelSet(msLevelSet2)); if (os_) { printSpectrumList(filter2, *os_); *os_ << endl; } unit_assert(filter2.size() == 6); unit_assert(filter2.spectrumIdentity(0).id == "scan=101"); unit_assert(filter2.spectrumIdentity(1).id == "scan=102"); unit_assert(filter2.spectrumIdentity(2).id == "scan=104"); unit_assert(filter2.spectrumIdentity(3).id == "scan=105"); unit_assert(filter2.spectrumIdentity(4).id == "scan=107"); unit_assert(filter2.spectrumIdentity(5).id == "scan=108"); }
void testScanNumberSet(SpectrumListPtr sl) { if (os_) *os_ << "testScanNumberSet:\n"; IntegerSet scanNumberSet; scanNumberSet.insert(102,104); scanNumberSet.insert(107); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_ScanNumberSet(scanNumberSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 4); unit_assert(filter.spectrumIdentity(0).id == "scan=102"); unit_assert(filter.spectrumIdentity(1).id == "scan=103"); unit_assert(filter.spectrumIdentity(2).id == "scan=104"); unit_assert(filter.spectrumIdentity(3).id == "scan=107"); }
// ** Films::formatGenres std::string Films::formatGenres( const IntegerSet& genres ) { const char* genreName[] = { "", "Экшн", "Приключения", "Мультфильм", "Детский", "Комедия", "Криминал", "Документальный", "Драма", "Фентези", "Нуар", "Ужасы", "Музыкальный", "Таинственный", "Романтический", "Научная фантастика", "Триллер", "Военный", "Вестерн", "IMAX", }; std::string result; for( IntegerSet::const_iterator i = genres.begin(), end = genres.end(); i != end; ++i ) { if( result != "" ) { result += ", "; } result += genreName[*i]; } return result; }
void testIndexSet(SpectrumListPtr sl) { if (os_) *os_ << "testIndexSet:\n"; IntegerSet indexSet; indexSet.insert(3,5); indexSet.insert(7); indexSet.insert(9); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_IndexSet(indexSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 5); unit_assert(filter.spectrumIdentity(0).id == "scan=103"); unit_assert(filter.spectrumIdentity(1).id == "scan=104"); unit_assert(filter.spectrumIdentity(2).id == "scan=105"); unit_assert(filter.spectrumIdentity(3).id == "scan=107"); unit_assert(filter.spectrumIdentity(4).id == "scan=109"); }
void testParse() { IntegerSet a; a.parse(" [-3,2] [5,5] [8,9] booger "); // insert(-3,2); insert(5); insert(8,9); unit_assert(a.intervalCount() == 3); unit_assert(a.size() == 9); vector<int> b; copy(a.begin(), a.end(), back_inserter(b)); unit_assert(b.size() == 9); unit_assert(b[0] == -3); unit_assert(b[1] == -2); unit_assert(b[2] == -1); unit_assert(b[3] == 0); unit_assert(b[4] == 1); unit_assert(b[5] == 2); unit_assert(b[6] == 5); unit_assert(b[7] == 8); unit_assert(b[8] == 9); }
//------------------------------------------------------------------------------ // Add cluster to a tree int NTree::AddCluster (IntegerSet &b, char *label) { Error = 0; int n = b.size(); if (n > 1 && n < ((NNodePtr)Root)->Cluster.size()) { // non trivial set NNodePtr p = (NNodePtr)Root; NNodePtr q = (NNodePtr)(p->GetChild()); bool done = false; SetRelations r; // locate insertion point while (q && !done) { r = Relationship (b, q->Cluster); switch (r) { case IDENTITY: done = true; Error = 1; // we already have this cluster break; case SUBSET: p = q; q = (NNodePtr)(q->GetChild()); break; case DISJOINT: p = q; q = (NNodePtr)(q->GetSibling()); break; case SUPERSET: done = true; break; case OVERLAPPING: done = true; Error = 2; // can't be a part of a tree break; default: break; } } if (Error == 0) { // Create node NNodePtr nunode = (NNodePtr)NewNode (); Internals++; nunode->SetWeight(n); nunode->Cluster = b; if (label) nunode->SetLabel (label); // Insert node in tree switch (r) { case SUBSET: p->SetChild (nunode); nunode->SetAnc (p); break; case DISJOINT: p->SetSibling (nunode); nunode->SetAnc (p->GetAnc()); break; case SUPERSET: if (q == p->GetChild()) { p->SetChild (nunode); nunode->SetChild (q); nunode->SetAnc (p); q->SetAnc (nunode); } else { p->SetSibling (nunode); nunode->SetChild (q); nunode->SetAnc (p->GetAnc()); q->SetAnc (nunode); } NNodePtr tmp = q; NNodePtr s = (NNodePtr)(q->GetSibling()); NNodePtr t = (NNodePtr)(q->GetAnc()); while (s) { r = Relationship (s->Cluster, b); if ((r == IDENTITY) || (r == SUBSET)) { s->SetAnc(nunode); tmp = s; s = (NNodePtr)(s->GetSibling()); } else { t->SetSibling (s); tmp->SetSibling (s->GetSibling()); t = s; t->SetSibling (NULL); s = (NNodePtr)(tmp->GetSibling()); } } break; // checkSiblings (q, nunode->cluster); } // nunode->GetDegreeOf (); // nunode->anc->degree = nunode->degree - nunode->degree - 1; } } return Error; }
SetRelations Relationship (IntegerSet &one, IntegerSet &two) { SetRelations result; /* cout << " {"; std::copy (one.begin(), one.end(), std::ostream_iterator<int>(cout, " ")); cout << "}"; cout << " {"; std::copy (two.begin(), two.end(), std::ostream_iterator<int>(cout, " ")); cout << "}"; */ if (one == two) result = IDENTITY; else if (std::includes (two.begin(), two.end(), one.begin(), one.end())) result = SUBSET; // one is a subset of two else if (std::includes (one.begin(), one.end(), two.begin(), two.end())) result = SUPERSET; // two is a subset of one else { IntegerSet common; std::set_intersection (one.begin(), one.end(), two.begin(), two.end(), std::inserter (common, common.end())); if (common.size() == 0) result = DISJOINT; else result = OVERLAPPING; } // cout << "result=" << result << endl; return result; }
void Select::execute() { if ( state() != Executing ) return; if ( Flag::id( "\\Deleted" ) == 0 ) { // should only happen when we flush the entire database during // testing, so we don't bother being accurate or fast, but // simply try again in a second. (void)new Timer( this, 1 ); return; } if ( !d->permissions ) { if ( d->condstore ) imap()->setClientSupports( IMAP::Condstore ); if ( d->annotate ) imap()->setClientSupports( IMAP::Annotate ); if ( d->mailbox->deleted() ) error( No, d->mailbox->name().ascii() + " is deleted" ); if ( !ok() ) { finish(); return; } d->permissions = new Permissions( d->mailbox, imap()->user(), this ); } if ( d->permissions && !d->session ) { if ( !d->permissions->ready() ) return; if ( !d->permissions->allowed( Permissions::Read ) ) { error( No, d->mailbox->name().ascii() + " is not accessible" ); finish(); return; } if ( !d->readOnly && !d->permissions->allowed( Permissions::KeepSeen ) ) d->readOnly = true; } if ( !::firstUnseenCache ) ::firstUnseenCache = new SelectData::FirstUnseenCache; if ( mailboxGroup() && !d->sessionPreloader ) { d->sessionPreloader = new SessionPreloader( mailboxGroup()->contents(), this ); d->sessionPreloader->execute(); IntegerSet s; List<Mailbox>::Iterator i( mailboxGroup()->contents() ); while ( i ) { if ( !::firstUnseenCache->find( i, i->nextModSeq() ) ) s.add( i->id() ); ++i; } if ( s.count() > 2 ) { d->cacheFirstUnseen = new Query( "select min(uid) as uid, mailbox, " "max(modseq) as modseq " "from mailbox_messages mm " "where mailbox=any($1) and not seen " "group by mailbox", this ); d->cacheFirstUnseen->bind( 1, s ); d->cacheFirstUnseen->execute(); } } if ( d->sessionPreloader ) { while ( d->cacheFirstUnseen && d->cacheFirstUnseen->hasResults() ) { Row * r = d->cacheFirstUnseen->nextRow(); Mailbox * m = Mailbox::find( r->getInt( "mailbox" ) ); ::firstUnseenCache->insert( m, 1 + r->getBigint( "modseq" ), r->getInt( "uid" ) ); } if ( d->cacheFirstUnseen && !d->cacheFirstUnseen->done() ) return; if ( !d->sessionPreloader->done() ) return; } if ( !d->session ) { d->session = new ImapSession( imap(), d->mailbox, d->readOnly ); d->session->setPermissions( d->permissions ); imap()->beginSession( d->session ); } if ( !d->session->initialised() ) return; if ( d->session->isEmpty() ) d->needFirstUnseen = false; else if ( ::firstUnseenCache && ::firstUnseenCache->find( d->mailbox, d->session->nextModSeq() ) ) d->needFirstUnseen = false; else d->needFirstUnseen = true; if ( d->needFirstUnseen && !d->firstUnseen ) { d->firstUnseen = new Query( "select uid from mailbox_messages mm " "where mailbox=$1 and not seen " "order by uid limit 1", this ); d->firstUnseen->bind( 1, d->mailbox->id() ); d->firstUnseen->execute(); } if ( d->firstUnseen && !d->firstUnseen->done() ) return; d->session->emitUpdates( 0 ); // emitUpdates often calls Imap::runCommands, which calls this // function, which will then change its state to Finished. so // check that and don't repeat the last few responses. if ( state() != Executing ) return; respond( "OK [UIDVALIDITY " + fn( d->session->uidvalidity() ) + "]" " uid validity" ); if ( d->firstUnseen ) { if ( !::firstUnseenCache ) ::firstUnseenCache = new SelectData::FirstUnseenCache; Row * r = d->firstUnseen->nextRow(); if ( r ) ::firstUnseenCache->insert( d->mailbox, d->session->nextModSeq(), r->getInt( "uid" ) ); } if ( ::firstUnseenCache ) { uint unseen = ::firstUnseenCache->find( d->mailbox, d->session->nextModSeq() ); if ( unseen ) respond( "OK [UNSEEN " + fn( d->session->msn( unseen ) ) + "] first unseen" ); } if ( imap()->clientSupports( IMAP::Condstore ) && !d->session->isEmpty() ) { uint nms = d->session->nextModSeq(); if ( nms < 2 ) nms = 2; respond( "OK [HIGHESTMODSEQ " + fn( nms-1 ) + "] highest modseq" ); } if ( imap()->clientSupports( IMAP::Annotate ) ) { Permissions * p = d->session->permissions(); if ( p && p->allowed( Permissions::WriteSharedAnnotation ) ) respond( "OK [ANNOTATIONS 262144] Arbitrary limit" ); else respond( "OK [ANNOTATIONS READ-ONLY] Missing 'n' right" ); } if ( d->session->readOnly() ) setRespTextCode( "READ-ONLY" ); else setRespTextCode( "READ-WRITE" ); finish(); }
int main() { IntegerSet a; IntegerSet b; IntegerSet c; IntegerSet d; cout << "Enter set A:\n"; a.inputSet(); cout << "\nEnter set B:\n"; b.inputSet(); c = a.unionOfSets(b); d = a.intersectionOfSets(b); cout << "\nUnion of A and B is:\n"; c.printSet(); cout << "Intersection of A and B is:\n"; d.printSet(); if (a.isEqualTo(b)) cout << "Set A is equal to set B\n"; else cout << "Set A is not equal to set B\n"; cout << "\nInserting 77 into set A...\n"; a.insertElement(77); cout << "Set A is now:\n"; a.printSet(); cout << "\nDeleting 77 from set A...\n"; a.deleteElement(77); cout << "Set A is now:\n"; a.printSet(); const int arraySize = 10; int intArray[ arraySize ] = { 25, 67, 2, 9, 99, 105, 45, -5, 100, 1 }; IntegerSet e(intArray, arraySize); cout << "\nSet e is:\n"; e.printSet(); cout << endl; } // end main
int MAST (NTree &T1, NTree &T2) { int result = 0; // 1. create lists of the nodes in T1 and T2 in postorder int count = 0; NodeVector pot1; NodeIterator <Node> n1 (T1.GetRoot()); Node *q = n1.begin(); while (q) { q->SetIndex (count); pot1.push_back ((NNode *)q); count++; q = n1.next(); } count = 0; NodeVector pot2; NodeIterator <Node> n2 (T2.GetRoot()); q = n2.begin(); while (q) { q->SetIndex (count); pot2.push_back ((NNode *)q); count++; q = n2.next(); } // Matrix to hold solutions int **m; m = new int *[T1.GetNumNodes()]; for (int i = 0; i < T1.GetNumNodes(); i++) m[i] = new int [T2.GetNumNodes()]; for (int i = 0; i < T1.GetNumNodes(); i++) for (int j = 0; j <T2.GetNumNodes(); j++) m[i][j] = 0; // 2. Visit all pairs of nodes in T1 and T2 for (int i = 0; i < T1.GetNumNodes(); i++) { for (int j = 0; j <T2.GetNumNodes(); j++) { if (pot1[i]->IsLeaf() || pot2[j]->IsLeaf()) { // Both are leaves, so MAST[i,j] is 1 if labels are identical if (pot1[i]->IsLeaf() && pot2[j]->IsLeaf()) { if ( pot1[i]->GetLabel() == pot2[j]->GetLabel()) m[i][j] = 1; } else { // Only one is a leaf, so MAST[i,j] is 1 if leaf is element in cluster IntegerSet common; std::set_intersection (pot1[i]->Cluster.begin(), pot1[i]->Cluster.end(), pot2[j]->Cluster.begin(), pot2[j]->Cluster.end(), std::inserter (common, common.end())); int w = common.size(); m[i][j] = w; } } else { // Both are internals so MAST[i,j] is MAX (diag, match) std::vector <NodePtr> pchildren, qchildren; // diag int diag = 0; // Get MAST of base of subtree in t1 and immediate children of // base of subtree in t2, and at the same time store list of // immediate children NodePtr p = pot2[j]->GetChild(); while (p) { qchildren.push_back(p); diag = std::max (diag, m[i][p->GetIndex()]); p = p->GetSibling(); } // get MAST of base of subtree in t2 and immediate children of // base of subtree in t1, and at the same time store list of // immediate children NodePtr q = pot1[i]->GetChild(); while (q) { pchildren.push_back(q); diag = std::max (diag, m[q->GetIndex()][j]); q = q->GetSibling(); } // maximum weighted bipartite matching #if USE_MATCHING int match = 0; graph g; g.make_directed(); // Nodes for p and q children map <int, node, less <int> > p_node; map <int, node, less <int> > q_node; for (int k = 0; k < pchildren.size(); k++) { node n = g.new_node(); p_node[k] = n; } for (int k = 0; k < qchildren.size(); k++) { node n = g.new_node(); q_node[k] = n; } // Edges edge_map<int> weights(g, 0); for (int k = 0; k < pchildren.size(); k++) { for (int r = 0; r < qchildren.size(); r++) { int v = pchildren[k]->GetIndex(); int w = qchildren[r]->GetIndex(); // It seems that if the partition "from" is much larger than "to, // the matching algorithm can blow up with a memory access error // in fheap.c. Reversing the graph seems to help. edge e; if (pchildren.size() < qchildren.size()) e = g.new_edge (p_node[k], q_node[r]); else e = g.new_edge (q_node[r], p_node[k]); weights[e] = m[v][w]; } } // cout << "g" << endl; // cout << g; // g.save(); // cout << "Start matching..."; if (g.number_of_nodes() == 0) { match = 0; } else { mwbmatching mwbm; mwbm.set_vars (weights); if (mwbm.check(g) != algorithm::GTL_OK) { cout << "Maximum weight bipartite matching algorithm check failed" << endl; exit(1); } else { if (mwbm.run(g) != algorithm::GTL_OK) { cout << "Error running maximum weight bipartite matching algorithm" << endl; exit(1); } else { match = mwbm.get_mwbm(); } } } // cout << "matching done (" << match << ")" << endl; #else // For now (sigh) brute force generation of all matchings. Eventually // will need to do this more efficiently int n = std::max (pchildren.size(), qchildren.size()); // Store a vector of indices of children of subtree in t2. // We will permute this to generate all matchings. If t2 // has fewer children than subtree in t1, vector will contain // one or more "null" (-1) values. std::vector <int> perm; for (int k = 0; k < n; k++) { if (k < qchildren.size()) perm.push_back (k); else perm.push_back (-1); } // Generate all matchings // First matching int match = 0; for (int k = 0; k < n; k++) { if ((k < pchildren.size()) && (perm[k] != -1)) { int v = pchildren[k]->GetIndex(); int w = qchildren[perm[k]]->GetIndex(); match += m[v][w]; } } // Remaining matchings while (next_permutation (perm.begin(), perm.end()) ) { int this_match = 0; for (int k = 0; k < n; k++) { if ((k < pchildren.size()) && (perm[k] != -1)) { int v = pchildren[k]->GetIndex(); int w = qchildren[perm[k]]->GetIndex(); this_match += m[v][w]; } } match = std::max (match, this_match); } #endif m[i][j] = std::max (diag, match); } } } result = m[T1.GetNumNodes() - 1][T2.GetNumNodes() - 1]; // Show matrix /* for (int i = 0; i < T1.GetNumNodes(); i++) { cout << setw(3) << i << "|"; for (int j = 0; j < T2.GetNumNodes(); j++) cout << setw(3) << m[i][j]; cout << endl; } */ // clean up for (int i = 0; i < T1.GetNumNodes(); i++) delete [] m[i]; delete [] m; return result; }
void Status::execute() { if ( state() != Executing ) return; // first part. set up. if ( !permitted() ) return; Session * session = imap()->session(); Mailbox * current = 0; if ( session ) current = session->mailbox(); // second part. see if anything has happened, and feed the cache if // so. make sure we feed the cache at once. if ( d->unseenCount || d->recentCount || d->messageCount ) { if ( d->unseenCount && !d->unseenCount->done() ) return; if ( d->messageCount && !d->messageCount->done() ) return; if ( d->recentCount && !d->recentCount->done() ) return; } if ( !::cache ) ::cache = new StatusData::StatusCache; if ( d->unseenCount ) { while ( d->unseenCount->hasResults() ) { Row * r = d->unseenCount->nextRow(); StatusData::CacheItem * ci = ::cache->find( r->getInt( "mailbox" ) ); if ( ci ) { ci->hasUnseen = true; ci->unseen = r->getInt( "unseen" ); } } } if ( d->recentCount ) { while ( d->recentCount->hasResults() ) { Row * r = d->recentCount->nextRow(); StatusData::CacheItem * ci = ::cache->find( r->getInt( "mailbox" ) ); if ( ci ) { ci->hasRecent = true; ci->recent = r->getInt( "recent" ); } } } if ( d->messageCount ) { while ( d->messageCount->hasResults() ) { Row * r = d->messageCount->nextRow(); StatusData::CacheItem * ci = ::cache->find( r->getInt( "mailbox" ) ); if ( ci ) { ci->hasMessages = true; ci->messages = r->getInt( "messages" ); } } } // third part. are we processing the first command in a STATUS // loop? if so, see if we ought to preload the cache. if ( mailboxGroup() && d->cacheState < 3 ) { IntegerSet mailboxes; if ( d->cacheState < 1 ) { // cache state 0: decide which messages List<Mailbox>::Iterator i( mailboxGroup()->contents() ); while ( i ) { StatusData::CacheItem * ci = ::cache->provide( i ); bool need = false; if ( d->unseen || d->recent || d->messages ) need = true; if ( ci->hasUnseen || ci->hasRecent || ci->hasMessages ) need = false; if ( need ) mailboxes.add( i->id() ); ++i; } if ( mailboxes.count() < 3 ) d->cacheState = 3; } if ( d->cacheState == 1 ) { // state 1: send queries if ( d->unseen ) { d->unseenCount = new Query( "select mailbox, count(uid)::int as unseen " "from mailbox_messages " "where mailbox=any($1) and not seen " "group by mailbox", this ); d->unseenCount->bind( 1, mailboxes ); d->unseenCount->execute(); } if ( d->recent ) { d->recentCount = new Query( "select id as mailbox, " "uidnext-first_recent as recent " "from mailboxes where id=any($1)", this ); d->recentCount->bind( 1, mailboxes ); d->recentCount->execute(); } if ( d->messages ) { d->messageCount = new Query( "select count(*)::int as messages, mailbox " "from mailbox_messages where mailbox=any($1) " "group by mailbox", this ); d->messageCount->bind( 1, mailboxes ); d->messageCount->execute(); } d->cacheState = 2; } if ( d->cacheState == 2 ) { // state 2: mark the cache as complete. IntegerSet mailboxes; List<Mailbox>::Iterator i( mailboxGroup()->contents() ); while ( i ) { StatusData::CacheItem * ci = ::cache->find( i->id() ); if ( ci && d->unseenCount ) ci->hasUnseen = true; if ( ci && d->recentCount ) ci->hasRecent = true; if ( ci && d->messageCount ) ci->hasMessages = true; ++i; } // and drop the queries d->cacheState = 3; d->unseenCount = 0; d->recentCount = 0; d->messageCount = 0; } } // the cache item we'll actually read from StatusData::CacheItem * i = ::cache->provide( d->mailbox ); // fourth part: send individual queries if there's anything we need if ( d->unseen && !d->unseenCount && !i->hasUnseen ) { d->unseenCount = new Query( "select $1::int as mailbox, " "count(uid)::int as unseen " "from mailbox_messages " "where mailbox=$1 and not seen", this ); d->unseenCount->bind( 1, d->mailbox->id() ); d->unseenCount->execute(); } if ( !d->recent ) { // nothing doing } else if ( d->mailbox == current ) { // we'll pick it up from the session } else if ( i->hasRecent ) { // the cache has it } else if ( !d->recentCount ) { d->recentCount = new Query( "select id as mailbox, " "uidnext-first_recent as recent " "from mailboxes where id=$1", this ); d->recentCount->bind( 1, d->mailbox->id() ); d->recentCount->execute(); } if ( !d->messages ) { // we don't need to collect } else if ( d->mailbox == current ) { // we'll pick it up } else if ( i->hasMessages ) { // the cache has it } else if ( d->messages && !d->messageCount ) { d->messageCount = new Query( "select count(*)::int as messages, " "$1::int as mailbox " "from mailbox_messages where mailbox=$1", this ); d->messageCount->bind( 1, d->mailbox->id() ); d->messageCount->execute(); } if ( d->unseenCount || d->recentCount || d->messageCount ) { if ( d->unseenCount && !d->unseenCount->done() ) return; if ( d->messageCount && !d->messageCount->done() ) return; if ( d->recentCount && !d->recentCount->done() ) return; } // fifth part: return the payload. EStringList status; if ( d->messages && i->hasMessages ) status.append( "MESSAGES " + fn( i->messages ) ); else if ( d->messages && d->mailbox == current ) status.append( "MESSAGES " + fn( session->messages().count() ) ); if ( d->recent && i->hasRecent ) status.append( "RECENT " + fn( i->recent ) ); else if ( d->recent && d->mailbox == current ) status.append( "RECENT " + fn( session->recent().count() ) ); if ( d->uidnext ) status.append( "UIDNEXT " + fn( d->mailbox->uidnext() ) ); if ( d->uidvalidity ) status.append( "UIDVALIDITY " + fn( d->mailbox->uidvalidity() ) ); if ( d->unseen && i->hasUnseen ) status.append( "UNSEEN " + fn( i->unseen ) ); if ( d->modseq ) { int64 hms = d->mailbox->nextModSeq(); // don't like this. an empty mailbox will have a STATUS HMS of // 1 before it receives its first message, and also 1 after. if ( hms > 1 ) hms--; status.append( "HIGHESTMODSEQ " + fn( hms ) ); } respond( "STATUS " + imapQuoted( d->mailbox ) + " (" + status.join( " " ) + ")" ); finish(); }
void GroupTopology::Create(ListOfIntegerSets &groups, int mpitag) { groups.AsTable(group_lproc); // group_lproc = group_proc Table group_mgroupandproc; group_mgroupandproc.SetDims(NGroups(), group_lproc.Size_of_connections() + NGroups()); for (int i = 0; i < NGroups(); i++) { int j = group_mgroupandproc.GetI()[i]; group_mgroupandproc.GetI()[i+1] = j + group_lproc.RowSize(i) + 1; group_mgroupandproc.GetJ()[j] = i; j++; for (int k = group_lproc.GetI()[i]; j < group_mgroupandproc.GetI()[i+1]; j++, k++) { group_mgroupandproc.GetJ()[j] = group_lproc.GetJ()[k]; } } // build groupmaster_lproc with lproc = proc groupmaster_lproc.SetSize(NGroups()); // simplest choice of the group owner for (int i = 0; i < NGroups(); i++) { groupmaster_lproc[i] = groups.PickElementInSet(i); } // load-balanced choice of the group owner, which however can lead to // isolated dofs // for (i = 0; i < NGroups(); i++) // groupmaster_lproc[i] = groups.PickRandomElementInSet(i); ProcToLProc(); // build group_mgroup group_mgroup.SetSize(NGroups()); int send_counter = 0; int recv_counter = 0; for (int i = 1; i < NGroups(); i++) if (groupmaster_lproc[i] != 0) // we are not the master { recv_counter++; } else { send_counter += group_lproc.RowSize(i)-1; } MPI_Request *requests = new MPI_Request[send_counter]; MPI_Status *statuses = new MPI_Status[send_counter]; int max_recv_size = 0; send_counter = 0; for (int i = 1; i < NGroups(); i++) { if (groupmaster_lproc[i] == 0) // we are the master { group_mgroup[i] = i; for (int j = group_lproc.GetI()[i]; j < group_lproc.GetI()[i+1]; j++) { if (group_lproc.GetJ()[j] != 0) { MPI_Isend(group_mgroupandproc.GetRow(i), group_mgroupandproc.RowSize(i), MPI_INT, lproc_proc[group_lproc.GetJ()[j]], mpitag, MyComm, &requests[send_counter]); send_counter++; } } } else // we are not the master if (max_recv_size < group_lproc.RowSize(i)) { max_recv_size = group_lproc.RowSize(i); } } max_recv_size++; IntegerSet group; if (recv_counter > 0) { int count; MPI_Status status; int *recv_buf = new int[max_recv_size]; for ( ; recv_counter > 0; recv_counter--) { MPI_Recv(recv_buf, max_recv_size, MPI_INT, MPI_ANY_SOURCE, mpitag, MyComm, &status); MPI_Get_count(&status, MPI_INT, &count); group.Recreate(count-1, recv_buf+1); int g = groups.Lookup(group); group_mgroup[g] = recv_buf[0]; if (lproc_proc[groupmaster_lproc[g]] != status.MPI_SOURCE) { cerr << "\n\n\nGroupTopology::GroupTopology: " << MyRank() << ": ERROR\n\n\n" << endl; mfem_error(); } } delete [] recv_buf; } MPI_Waitall(send_counter, requests, statuses); delete [] statuses; delete [] requests; }
bool PopCommand::session() { if ( !d->mailbox ) { d->mailbox = d->pop->user()->inbox(); log( "Attempting to start a session on " + d->mailbox->name().ascii() ); d->permissions = new Permissions( d->mailbox, d->pop->user(), this ); } if ( !d->permissions->ready() ) return false; if ( !d->session ) { if ( !d->permissions->allowed( Permissions::Read ) ) { d->pop->err( "Insufficient privileges" ); return true; } else { bool ro = true; if ( d->permissions->allowed( Permissions::KeepSeen ) && d->permissions->allowed( Permissions::DeleteMessages ) && d->permissions->allowed( Permissions::Expunge ) ) ro = false; d->session = new PopCommandData::PopSession( d->mailbox, ro, this ); d->session->setPermissions( d->permissions ); d->pop->setSession( d->session ); } } if ( !d->session->initialised() ) return false; if ( !d->map ) { d->session->clearUnannounced(); IntegerSet s( d->session->messages() ); IntegerSet r; d->map = new Map<Message>; while ( !s.isEmpty() ) { uint uid = s.smallest(); s.remove( uid ); Message * m = MessageCache::provide( d->mailbox, uid ); if ( !m->databaseId() ) r.add( uid ); d->map->insert( uid, m ); } if ( !r.isEmpty() ) { d->findIds = new Query( "select message, uid " "from mailbox_messages " "where mailbox=$1 and uid=any($2)", this ); d->findIds->bind( 1, d->mailbox->id() ); d->findIds->bind( 2, r ); d->findIds->execute(); } } if ( d->findIds && !d->findIds->done() ) return false; while ( d->findIds && d->findIds->hasResults() ) { Row * r = d->findIds->nextRow(); Message * m = d->map->find( r->getInt( "uid" ) ); if ( m ) m->setDatabaseId( r->getInt( "message" ) ); } d->session->clearUnannounced(); d->pop->setMessageMap( d->map ); d->pop->setState( POP::Transaction ); d->pop->ok( "Done" ); return true; }
void test() { // instantiate IntegerSet IntegerSet a; unit_assert(a.empty()); a.insert(1); unit_assert(!a.empty()); a.insert(2); a.insert(IntegerSet::Interval(0,2)); a.insert(0,2); a.insert(4); // verify virtual container contents: 0, 1, 2, 4 if (os_) { copy(a.begin(), a.end(), ostream_iterator<int>(*os_," ")); *os_ << endl; } vector<int> b; copy(a.begin(), a.end(), back_inserter(b)); unit_assert(b.size() == 4); unit_assert(b[0] == 0); unit_assert(b[1] == 1); unit_assert(b[2] == 2); unit_assert(b[3] == 4); // insert [2,4], and verify contents: 0, 1, 2, 3, 4 a.insert(2,4); if (os_) { copy(a.begin(), a.end(), ostream_iterator<int>(*os_," ")); *os_ << endl; } b.clear(); copy(a.begin(), a.end(), back_inserter(b)); unit_assert(b.size() == 5); for (int i=0; i<5; i++) unit_assert(i == b[i]); }
int main(){ IntegerSet s1,s2; s1.add(1); s1.add(5); s1.add(10); s1.add(15); s1.add(100); s2.add(2); s2.add(5); s2.add(15); s2.add(50); s2.add(90); IntegerSet q; q = s1.set_union(s2); cout << q.contains(1) << q.contains(2) << q.contains(5) << q.contains(15) << q.contains(50) << q.contains(100) << q.contains(200) << endl; q = s1.set_difference(s2); cout << q.contains(1) << q.contains(2) << q.contains(5) << q.contains(15) << q.contains(50) << q.contains(100) << q.contains(200) << endl; }
void SpoolManager::execute() { // Fetch a list of spooled messages, and the next time we can try // to deliver each of them. uint delay = UINT_MAX; if ( !d->q ) { IntegerSet have; List<DeliveryAgent>::Iterator a( d->agents ); while ( a ) { if ( a->working() ) { have.add( a->messageId() ); delay = 900; ++a; } else { d->agents.take( a ); } } log( "Starting queue run" ); d->again = false; reset(); EString s( "select d.message, " "extract(epoch from" " min(coalesce(dr.last_attempt+interval '900 s'," " d.deliver_after," " current_timestamp)))::bigint" "-extract(epoch from current_timestamp)::bigint as delay " "from deliveries d " "join delivery_recipients dr on (d.id=dr.delivery) " "where (dr.action=$1 or dr.action=$2) " ); if ( !have.isEmpty() ) s.append( "and not d.message=any($3) " ); s.append( "group by d.message " "order by delay" ); d->q = new Query( s, this ); d->q->bind( 1, Recipient::Unknown ); d->q->bind( 2, Recipient::Delayed ); if ( !have.isEmpty() ) d->q->bind( 3, have ); d->q->execute(); } if ( d->q && !d->q->done() ) return; // Is there anything we might do? if ( d->q && !d->q->rows() ) { // No. Just finish. reset(); log( "Ending queue run" ); return; } // Yes. What? if ( d->q ) { while ( d->q->hasResults() ) { Row * r = d->q->nextRow(); int64 deliverableAt = r->getBigint( "delay" ); if ( deliverableAt <= 0 ) { DeliveryAgent * a = new DeliveryAgent( r->getInt( "message" ) ); (void)new Timer( a, d->agents.count() * 5 ); d->agents.append( a ); } else if ( delay > deliverableAt ) delay = deliverableAt; } if ( delay < UINT_MAX ) { log( "Will process the queue again in " + fn( delay ) + " seconds" ); d->t = new Timer( this, delay ); } d->q = 0; } reset(); }