当前位置: 首页>>代码示例>>C++>>正文


C++ set::end方法代码示例

本文整理汇总了C++中set::end方法的典型用法代码示例。如果您正苦于以下问题:C++ set::end方法的具体用法?C++ set::end怎么用?C++ set::end使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在set的用法示例。


在下文中一共展示了set::end方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: main

int main() {
  int que;
  scanf("%d", &que);
  for (int i = 0; i < que; i++) {
    scanf("%d %d %d", t+i, &p[i].x, &p[i].y);
    if (t[i]) {
      scanf("%d %d", &q[i].x, &q[i].y);
    }
    else {
      vp.push_back(make_pair(p[i], i));
    }
  }
  sort(vp.begin(), vp.end());
  for (int i = 0; i < vp.size(); i++)
    id[vp[i].second] = i+1;
  fen bup(vp.size() + 2), blow(vp.size()+ 2);
  for (int i = 0; i < que; i++) {
    if (t[i] == 0) {
      pair<point, int> now = make_pair(p[i], id[i]);
      lower.insert(now);
      set<pair<point, int> >::iterator it = lower.lower_bound(now);
      if (baddown(it))
        lower.erase(it);
      else {
        blow.upd(now.second, +1);
        set<pair<point, int> >::iterator nx = it;
        nx++;
        while (nx != lower.end() && baddown(nx)) {
          blow.upd(nx->second, -1);
          lower.erase(nx++);
        }
        nx = it;
        while (nx != lower.begin()) {
          nx--;
          if (baddown(nx)) {
            blow.upd(nx->second, -1);
            lower.erase(nx);
            nx = it;
          }
          else
            break;
        }
      }

      // upper
      upper.insert(now);
      it = upper.lower_bound(now);
      if (badup(it))
        upper.erase(it);
      else {
        bup.upd(now.second, +1);
        set<pair<point, int> >::iterator nx = it;
        nx++;
        while (nx != upper.end() && badup(nx)) {
          bup.upd(nx->second, -1);
          upper.erase(nx++);
        }
        nx = it;
        while (nx != upper.begin()) {
          nx--;
          if (badup(nx)) {
            bup.upd(nx->second, -1);
            upper.erase(nx);
            nx = it;
          }
          else
            break;
        }
      }
    }
    else {
      int ans = 1, tot = (int)upper.size() + (int)lower.size() - 4;
      set<pair<point, int> >::iterator lowa = lower.lower_bound(make_pair(p[i], -1)), lowb = lower.lower_bound(make_pair(q[i], -1));
      set<pair<point, int> >::iterator upa = upper.lower_bound(make_pair(p[i], -1)), upb = upper.lower_bound(make_pair(q[i], -1));
      if (lowa != lower.end() && lowb != lower.end() && lowa->first == p[i] && lowb->first == q[i]) {
        int d = blow.get(lowb->second) - blow.get(lowa->second);
        if (d > 0) {
          d--;
          ans = (tot-d >= d);
        }
        else {
          d = -d - 1;
          ans = (d >= tot-d);
        }
      }
      else if (upa != upper.end() && upb != upper.end() && upa->first == p[i] && upb->first == q[i]) {
        int d = bup.get(upb->second) - bup.get(upa->second);
        if (d > 0) {
          d--;
          ans = (d >= tot-d);
        }
        else {
          d = -d - 1;
          ans = (tot-d >= d);
        }
      }
      else if (lowa != lower.end() && upb != upper.end() && lowa->first == p[i] && upb->first == q[i]) {
        int d = blow.get(lowa->second) + bup.get(upb->second) - 3;
        ans = (d >= tot-d);
      }
//.........这里部分代码省略.........
开发者ID:wifai,项目名称:competitive-programming,代码行数:101,代码来源:c.cpp

示例2: ofGetKeyPressed

//--------------------------------------
bool ofGetKeyPressed(int key){
	if(key==-1) return pressedKeys.size();
	return pressedKeys.find(key)!=pressedKeys.end();
}
开发者ID:6301158,项目名称:openFrameworks_0.071_debian_package,代码行数:5,代码来源:ofEvents.cpp

示例3: result

set<int> SetOperation::Union()
{
    set<int> result(setA.begin(), setA.end());
    result.insert(setB.begin(), setB.end());
    return result;
}
开发者ID:bazingaterry,项目名称:OhMyOJCode,代码行数:6,代码来源:1001.cpp

示例4: main

int main() {
    scanf("%d %d", &n, &T);

    for (int i = 1; i <= n; i++) {
	scanf("%d %d", a + i, t + i);
	prob cur = prob(a[i], t[i], i);
	S.insert(cur);
	v.pb(cur);
	num[a[i]].pb(cur);
    }
    sort(v.begin(), v.end());
    
    int temp = 0;
    for (int i = 1; i <= n; i++) {

	for (auto P : num[i - 1]) {
	    //debug("(%d) ==> Deletando %d\n", i, P.id);
	    if (S.find(P) != S.end()) S.erase(P);
	    if (resp.find(P) != resp.end()) {
		temp -= P.t;
		resp.erase(P);
	    }
	}

	set<prob>::iterator it = S.begin();
	int tam = resp.size();
	while (it != S.end() && tam < i) {
	    resp.insert(*it);
	    temp += it->t;
	    S.erase(it);
	    tam++;
	    it = S.begin();
	}

	//debug("--> %d %d\n", tam, temp);
	if (temp <= T)
	    mx = max(mx, tam);
	
	// if (tam > mx && temp <= T) {
	//     mx = tam;
	    
	//     //debug("(%d) --> %d %d\n", i, mx, temp);
	//     final.clear();
	//     for (auto P : resp)
	// 	final.pb(P);
	// }	
    }

    
    printf("%d\n%d\n", mx, mx);
    int cur = 1;
    
    for (int i = 0; i < n; i++) {
	if (cur <= mx && mx <= v[i].a) {
	    printf("%d ", v[i].id);
	    cur++;
	}
    }
    
    printf("\n");
}
开发者ID:breno-helf,项目名称:Maratona,代码行数:61,代码来源:D.cpp

示例5: DoAnswer

void DoAnswer(MCONTACT hContact, const TalkBot::MessageInfo *info, bool sticky = false)
{
	if (info->Answer[0] == _T('\0'))
		return;
	int waitTime, thinkTime = 0;
	int defWaitTime = Config.AnswerPauseTime * 1000;
	if (Config.PauseDepends)
		waitTime = defWaitTime * (int)info->Answer.length() / 25;
	else
		waitTime = defWaitTime;
	if (Config.PauseRandom)
	{
		//Let it be up to 4 times longer.
		waitTime =  waitTime * (rand() % 300) / 100 + waitTime;
	}
	if (waitTime == 0)
		waitTime = 50; //it's essential, because otherwise message will be added later 
					   //then its response, that will cause incorrect ordering of 
					   //messages in the opened history (reopening will
					   //help, but anyway it's no good)
	if (NotifyTyping(hContact) && Config.AnswerThinkTime)
	{
		thinkTime = Config.AnswerThinkTime * 1000;
		if (Config.PauseRandom)
		{
			//Let it be up to 4 times longer.
			thinkTime = thinkTime * (rand() % 300) / 100 + thinkTime;
		}				
	}
	cs.Enter();
	//Check if this contact's timer handler is now waiting for a cs.
	bool needTimerRearrange = false;
	if (!actionQueue.empty() && actionQueue.front().hContact == hContact)
	{
		needTimerRearrange = true;
		KillTimer(NULL, timerID);
		cs.Leave();
		cs.Enter();
	}
	if (!actionQueue.empty())
	{
		list<QueueElement>::iterator it = actionQueue.end();
		--it;
		while (true)
		{
			if ((*it).hContact == hContact)
			{
				if ((*it).Sticky)
					break;
				list<QueueElement>::iterator tmp = it;
				if (tmp != actionQueue.begin())
					--tmp;
				actionQueue.erase(it);
				it = tmp;
				if (actionQueue.empty())
					break;
			}
			if (it == actionQueue.begin())
				break;
			--it;
		}
	}
	typingContactsLock.Enter();
	if (typingContacts.find(hContact) != typingContacts.end())
	{
		CallService(MS_PROTO_SELFISTYPING, hContact, (LPARAM)PROTOTYPE_SELFTYPING_OFF);
		typingContacts.erase(hContact);
	}
	typingContactsLock.Leave();
	if (actionQueue.empty())
		needTimerRearrange = true;
	if (thinkTime)
		actionQueue.push_back(QueueElement(hContact, StartTyping, thinkTime, NULL, sticky));
	actionQueue.push_back(QueueElement(hContact, TimerAnswer, waitTime, info, sticky));
	if (needTimerRearrange)
		UpdateTimer();
	cs.Leave();
}
开发者ID:0xmono,项目名称:miranda-ng,代码行数:78,代码来源:actionQueue.cpp

示例6: difference

set<int> difference(const set<int>& s1, const set<int>& s2)
{
  set<int> diff;
  set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(diff, diff.end()));
  return diff;
}
开发者ID:mariokonschake,项目名称:cppTraversal,代码行数:6,代码来源:sets.cpp

示例7: main

int main(){
    
    input_file.open( input_file_name );
    
    while (input_file){
        string s;
        if (!getline( input_file, s )) break;
        no_of_trans++;
        istringstream ss( s );
        while (ss)
        {
            string s;
            if (!getline( ss, s, ',' )) break;
            items.insert(s);
        }
    }
    
    input_file.close();
    
    
    cout << items.size() << endl;

    int id = 1;
    for (set<string>::iterator it = items.begin(); it != items.end(); it++) {
        item_ids_map.insert(pair<string, int>(*it, id));
        ids_item_map.insert(pair<int, string>(id, *it));
        id++;
    }
    
    /**
    for (map<string, int>:: iterator it = item_ids_map.begin(); it != item_ids_map.end(); it++) {
        cout << it->first << " -- " << it ->second << endl;
    }
    **/
    
    vector<set<set<int> > > freq_itemsets;
    
    
    // finding 1 freq itemsets
    map<set<int>,int> temp_map;
    for (int i = 1; i<=items.size(); i++) {
        set<int> temp_set;
        temp_set.insert(i);
        temp_map.insert(pair<set<int>,int>(temp_set,0) );
    }
    
    /**
    for (map<set<int>,int>::iterator it = temp_map.begin(); it != temp_map.end(); it++) {
        set<int> temp_set = it->first;
        cout << "{";
        for (set<int>::iterator it1 = temp_set.begin(); it1 != temp_set.end(); it1++) {
            cout << *it1 << ",";
        }
        cout << "} -- " << it->second << endl;
    }
    **/
    
    // iterating through every trasaction for counting support
    
    input_file.open( input_file_name);
    while (input_file)
    {
        string s;
        if (!getline( input_file, s )) break;
        istringstream ss( s );
        
        set<int> trans_temp;
        while (ss)
        {
            string s;
            if (!getline( ss, s, ',' )) break;
            int item_id = item_ids_map.find(s)->second;
            set<int> temp_set;
            temp_set.insert(item_id);
            trans_temp.insert(item_id);
            temp_map.find(temp_set)->second++;
        }
        transactions_int.insert(trans_temp);
        
    }
    input_file.close();
    
    set<set<int> > f1;
    
    for (map<set<int>,int>::iterator it = temp_map.begin(); it != temp_map.end(); it++) {
        float itemset_support = (it->second)/no_of_trans;
        set<int> temp_set = it->first;
        if (itemset_support > min_support) {
            f1.insert(temp_set);
        }
    }
    
    freq_itemsets.push_back(f1);
    
    
    // priting freq 1 item sets
    /**
    for (set<set<int> >::iterator it = f1.begin(); it != f1.end(); it++) {
        set<int> temp_set  = *it;
        cout << "{";
//.........这里部分代码省略.........
开发者ID:lakshg13,项目名称:Data_Mining,代码行数:101,代码来源:dataMining.cpp

示例8: computeLiveVars

set<SgInitializedName*> computeLiveVars(SgStatement* stmt, const X86CTranslationPolicy& conv, map<SgLabelStatement*, set<SgInitializedName*> >& liveVarsForLabels, set<SgInitializedName*> currentLiveVars, bool actuallyRemove) {
  switch (stmt->variantT()) {
    case V_SgBasicBlock: {
      const SgStatementPtrList& stmts = isSgBasicBlock(stmt)->get_statements();
      for (size_t i = stmts.size(); i > 0; --i) {
        currentLiveVars = computeLiveVars(stmts[i - 1], conv, liveVarsForLabels, currentLiveVars, actuallyRemove);
      }
      return currentLiveVars;
    }
    case V_SgPragmaDeclaration: return currentLiveVars;
    case V_SgDefaultOptionStmt: return currentLiveVars;
    case V_SgCaseOptionStmt: {
      return computeLiveVars(isSgCaseOptionStmt(stmt)->get_body(), conv, liveVarsForLabels, currentLiveVars, actuallyRemove);
    }
    case V_SgLabelStatement: {
      liveVarsForLabels[isSgLabelStatement(stmt)] = currentLiveVars;
      return currentLiveVars;
    }
    case V_SgGotoStatement: {
      return liveVarsForLabels[isSgGotoStatement(stmt)->get_label()];
    }
    case V_SgSwitchStatement: {
      SgSwitchStatement* s = isSgSwitchStatement(stmt);
      SgBasicBlock* swBody = isSgBasicBlock(s->get_body());
      ROSE_ASSERT (swBody);
      const SgStatementPtrList& bodyStmts = swBody->get_statements();
      set<SgInitializedName*> liveForBody; // Assumes any statement in the body is possible
      for (size_t i = 0; i < bodyStmts.size(); ++i) {
        setUnionInplace(liveForBody, computeLiveVars(bodyStmts[i], conv, liveVarsForLabels, currentLiveVars, actuallyRemove));
      }
      return computeLiveVars(s->get_item_selector(), conv, liveVarsForLabels, liveForBody, actuallyRemove);
    }
    case V_SgContinueStmt: {
      return makeAllPossibleVars(conv);
    }
    case V_SgIfStmt: {
      set<SgInitializedName*> liveForBranches = computeLiveVars(isSgIfStmt(stmt)->get_true_body(), conv, liveVarsForLabels, currentLiveVars, actuallyRemove);
      setUnionInplace(liveForBranches, (isSgIfStmt(stmt)->get_false_body() != NULL ? computeLiveVars(isSgIfStmt(stmt)->get_false_body(), conv, liveVarsForLabels, currentLiveVars, actuallyRemove) : set<SgInitializedName*>()));
      return computeLiveVars(isSgIfStmt(stmt)->get_conditional(), conv, liveVarsForLabels, liveForBranches, actuallyRemove);
    }
    case V_SgWhileStmt: {
      while (true) {
        set<SgInitializedName*> liveVarsSave = currentLiveVars;
        currentLiveVars = computeLiveVars(isSgWhileStmt(stmt)->get_body(), conv, liveVarsForLabels, currentLiveVars, false);
        currentLiveVars = computeLiveVars(isSgWhileStmt(stmt)->get_condition(), conv, liveVarsForLabels, currentLiveVars, false);
        setUnionInplace(currentLiveVars, liveVarsSave);
        if (liveVarsSave == currentLiveVars) break;
      }
      if (actuallyRemove) {
        set<SgInitializedName*> liveVarsSave = currentLiveVars;
        currentLiveVars = computeLiveVars(isSgWhileStmt(stmt)->get_body(), conv, liveVarsForLabels, currentLiveVars, true);
        currentLiveVars = computeLiveVars(isSgWhileStmt(stmt)->get_condition(), conv, liveVarsForLabels, currentLiveVars, true);
        setUnionInplace(currentLiveVars, liveVarsSave);
      }
      return currentLiveVars;
    }
    case V_SgBreakStmt: return set<SgInitializedName*>();
    case V_SgExprStatement: {
      SgExpression* e = isSgExprStatement(stmt)->get_expression();
      switch (e->variantT()) {
        case V_SgAssignOp: {
          SgVarRefExp* lhs = isSgVarRefExp(isSgAssignOp(e)->get_lhs_operand());
          ROSE_ASSERT (lhs);
          SgInitializedName* in = lhs->get_symbol()->get_declaration();
          if (currentLiveVars.find(in) == currentLiveVars.end()) {
            if (actuallyRemove) {
              // cerr << "Removing assignment " << e->unparseToString() << endl;
              isSgStatement(stmt->get_parent())->remove_statement(stmt);
            }
            return currentLiveVars;
          } else {
            currentLiveVars.erase(in);
            getUsedVariables(isSgAssignOp(e)->get_rhs_operand(), currentLiveVars);
            return currentLiveVars;
          }
        }
        case V_SgFunctionCallExp: {
          getUsedVariables(e, currentLiveVars);
          SgFunctionRefExp* fr = isSgFunctionRefExp(isSgFunctionCallExp(e)->get_function());
          ROSE_ASSERT (fr);
          if (fr->get_symbol()->get_declaration() == conv.interruptSym->get_declaration()) {
            setUnionInplace(currentLiveVars, makeAllPossibleVars(conv));
            return currentLiveVars;
          } else {
            return currentLiveVars;
          }
        }
        default: {
          getUsedVariables(e, currentLiveVars);
          return currentLiveVars;
        }
      }
    }
    case V_SgVariableDeclaration: {
      ROSE_ASSERT (isSgVariableDeclaration(stmt)->get_variables().size() == 1);
      SgInitializedName* in = isSgVariableDeclaration(stmt)->get_variables()[0];
      bool isConst = isConstType(in->get_type());
      if (currentLiveVars.find(in) == currentLiveVars.end() && isConst) {
        if (actuallyRemove) {
          // cerr << "Removing decl " << stmt->unparseToString() << endl;
//.........这里部分代码省略.........
开发者ID:Federico2014,项目名称:edg4x-rose,代码行数:101,代码来源:x86AssemblyToC.C

示例9: query

void query(Atomic &atom, set<varint_t> &allvars, Relation &results) {
  switch (atom.type) {
    case ATOM:
      query_atom(atom.get.atom, allvars, results);
      return;
    case MEMBERSHIP:
    case SUBCLASS:
    case EQUALITY:
      return; // only concerned with triples for data
    case EXTERNAL:
      cerr << "[ERROR] This should never happen, at line " << __LINE__ << endl;
      return;
    case FRAME:
      break; // just handle outside this messy switch
    default:
      cerr << "[ERROR] Unhandled case " << (int) atom.type << " at line " << __LINE__ << endl;
      return;
  }
  Relation intermediate;
  Term subj = atom.get.frame.object;
  if (subj.type == LIST) {
    return; // no lists (real lists, not rdf:Lists) in RDF
  }
  if (subj.type == FUNCTION) {
    cerr << "[ERROR] Functions are currently unsupported." << endl;
    return;
  }
  varint_t maxvar = 0;
  Tuple mintriple(3);
  Tuple maxtriple(3);
  if (subj.type == CONSTANT) {
    mintriple[0] = maxtriple[0] = subj.get.constant;
  } else {
    mintriple[0] = 0;
    maxtriple[0] = CONSTINT_MAX;
    maxvar = subj.get.variable;
  }
  pair<Term, Term> *slot = atom.get.frame.slots.begin;
  for (; slot != atom.get.frame.slots.end; ++slot) {
    Term pred = slot->first;
    Term obj = slot->second;
    if (pred.type == LIST || obj.type == LIST) {
      Relation empty;
      results.swap(empty);
      return;
    }
    if (pred.type == FUNCTION || obj.type == FUNCTION) {
      cerr << "[ERROR] Functions are currently unsupported." << endl;
      return;
    }
    set<varint_t> newvars;
    if (subj.type == VARIABLE) {
      newvars.insert(subj.get.variable);
    }
    if (pred.type == CONSTANT) {
      mintriple[1] = maxtriple[1] = pred.get.constant;
    } else {
      mintriple[1] = 0;
      maxtriple[1] = CONSTINT_MAX;
      maxvar = max(maxvar, pred.get.variable);
      newvars.insert(pred.get.variable);
    }
    if (obj.type == CONSTANT) {
      mintriple[2] = maxtriple[2] = obj.get.constant;
    } else {
      mintriple[2] = 0;
      maxtriple[2] = CONSTINT_MAX;
      maxvar = max(maxvar, obj.get.variable);
      newvars.insert(obj.get.variable);
    }
    int idx = (subj.type == CONSTANT ? 0x4 : 0x0) |
              (pred.type == CONSTANT ? 0x2 : 0x0) |
              ( obj.type == CONSTANT ? 0x1 : 0x0);
    Index::const_iterator begin, end;
    switch (idx) {
      case 0x0:
      case 0x4:
      case 0x6:
      case 0x7: // SPO
        begin = idxspo.lower_bound(mintriple);
        end = idxspo.upper_bound(maxtriple);
        break;
      case 0x2:
      case 0x3: // POS
        begin = idxpos.lower_bound(mintriple);
        end = idxpos.upper_bound(maxtriple);
        break;
      case 0x1:
      case 0x5: // OSP
        begin = idxosp.lower_bound(mintriple);
        end = idxosp.upper_bound(maxtriple);
        break;
      default:
        cerr << "[ERROR] Unhandled case " << hex << idx << " at line " << dec << __LINE__ << endl;
        return;
    }
    // TODO the following loop could probably be more efficient
    Relation selection;
    for (; begin != end; ++begin) {
      Tuple result(maxvar + 1);
//.........这里部分代码省略.........
开发者ID:jrweave,项目名称:phd,代码行数:101,代码来源:infer-rules.cpp

示例10: chooseIONode

int SlaveManager::chooseIONode(set<int>& loclist, int mode, vector<SlaveNode>& sl, const SF_OPT& option, const int rep_dist, const vector<int>* restrict_loc)
{
   CGuardEx sg(m_SlaveLock);

   timeval t;
   gettimeofday(&t, 0);
   srand(t.tv_usec);

   sl.clear();

   if (m_mSlaveList.empty())
      return SectorError::E_NODISK;

   if (!loclist.empty())
   {
      SlaveNode sn;
      int rc = findNearestNode(loclist, option.m_strHintIP, sn);
      if( rc < 0 )
          return rc;

      sl.push_back(sn);

      // if this is a READ_ONLY operation, one node is enough
      if ((mode & SF_MODE::WRITE) == 0)
         return sl.size();

      // the first node will be the closest to the client; the client writes to that node only
      for (set<int>::iterator i = loclist.begin(); i != loclist.end(); i ++)
      {
         if (*i == sn.m_iNodeID)
            continue;

         if( m_mSlaveList.find( *i ) == m_mSlaveList.end() ) 
            log().error << __PRETTY_FUNCTION__ << ":  about to add new slave to list " << *i << std::endl;

         sl.push_back(m_mSlaveList[*i]);
      }
   }
   else
   {
      // no available nodes for READ_ONLY operation
      if ((mode & SF_MODE::WRITE) == 0)
         return 0;

      //TODO: optimize the node selection process; no need to scan all nodes

      set<int> avail;

      vector<int> path_limit;
      if (option.m_strCluster.c_str()[0] != '\0')
         Topology::parseTopo(option.m_strCluster.c_str(), path_limit);

      for (map<int, SlaveNode>::iterator i = m_mSlaveList.begin(); i != m_mSlaveList.end(); ++ i)
      {
         // skip bad & lost nodes
         if (i->second.m_iStatus != SlaveStatus::NORMAL) {
            continue;
         }

         // if client specifies a cluster ID, then only nodes on the cluster are chosen
         if (!path_limit.empty())
         {
            int clusterId = i->second.m_viPath.back();
            if( std::find( path_limit.begin(), path_limit.end(), clusterId ) == path_limit.end() ) {
               continue;
            }
         }

         // if there is location restriction on the file, check path as well
         if ((NULL != restrict_loc) && (!restrict_loc->empty()))
         {
            int clusterId = i->second.m_viPath.back();
            if( std::find( restrict_loc->begin(), restrict_loc->end(), clusterId ) == restrict_loc->end() ) {
               continue;
            }
         }

         // only nodes with more than minimum available disk space are chosen
         if (i->second.m_llAvailDiskSpace > (m_llSlaveMinDiskSpace + option.m_llReservedSize))
            avail.insert(i->first);
      }

      if (avail.empty())
         return SectorError::E_NODISK;

     
      SlaveNode sn;
      findNearestNode(avail, option.m_strHintIP, sn);

      sl.push_back(sn);

      // otherwise choose more nodes for immediate replica
      for (int i = 0; i < option.m_iReplicaNum - 1; ++ i)
      {
         set<int> locid;
         for (vector<SlaveNode>::iterator j = sl.begin(); j != sl.end(); ++ j)
            locid.insert(j->m_iNodeID);

         if (choosereplicanode_(locid, sn, option.m_llReservedSize, rep_dist, restrict_loc) <= 0)
            break;
//.........这里部分代码省略.........
开发者ID:deniskin82,项目名称:sector-sphere,代码行数:101,代码来源:slavemgmt.cpp

示例11: choosereplicanode_

int SlaveManager::choosereplicanode_(set<int>& loclist, SlaveNode& sn, const int64_t& filesize, const int rep_dist, const vector<int>* restrict_loc)
{
   // If all source nodes are busy, we should skip the replica.
   /*
   bool idle = false;
   for (set<int>::const_iterator i = loclist.begin(); i != loclist.end(); ++ i)
   {
      // TODO: each slave may set a capacity limit, which could be more than 2 active trasactions.
      if (m_mSlaveList[*i].m_iActiveTrans <= 1)
      {
         idle = true;
         break;
      }
   }
   if (!idle)
      return -1;
   */

   vector< set<int> > avail;
   avail.resize(m_pTopology->m_uiLevel + 2);

   // find the topology of current replicas
   vector< vector<int> > locpath;
   set<string> usedIP;
   for (set<int>::iterator i = loclist.begin(); i != loclist.end(); ++ i)
   {
      map<int, SlaveNode>::iterator p = m_mSlaveList.find(*i);
      if (p == m_mSlaveList.end())
         continue;
      locpath.push_back(p->second.m_viPath);
      usedIP.insert(p->second.m_strIP);
   }

   // TODO: this should not be calcuated each time.

   for (map<int, SlaveNode>::iterator i = m_mSlaveList.begin(); i != m_mSlaveList.end(); ++ i)
   {
      // skip bad&lost slaves
      if (i->second.m_iStatus != SlaveStatus::NORMAL)
         continue;

      // only nodes with more than minimum availale disk space are chosen
      if (i->second.m_llAvailDiskSpace < (m_llSlaveMinDiskSpace + filesize))
         continue;

      // cannot replicate to a node already having the data
      if (loclist.find(i->first) != loclist.end())
         continue;

      // if a location restriction is applied to the file, only limited nodes can be chosen
      if ((NULL != restrict_loc) && (!restrict_loc->empty()))
      {

         int clusterId = i->second.m_viPath.back();
         if( std::find( restrict_loc->begin(), restrict_loc->end(), clusterId ) == restrict_loc->end() ) 
         {
            continue;
         }
      }

      // Calculate the distance from this slave node to the current replicas
      // We want maximize the distance to closest node.
      int level = m_pTopology->min_distance(i->second.m_viPath, locpath);

      // if users define a replication distance, then only nodes within rep_dist can be chosen
      if ((rep_dist >= 0) && (level > rep_dist))
         continue;

      // if level is 1, it is possible there is a replica on slave on same node (same IP)
      // we do not want to have more than 1 replica per node
      // this can happen is several slaves started per node, one slave per volume
      if ( level == 1 )
      {
        set<string>::iterator fs = usedIP.find(i->second.m_strIP);
        if (fs != usedIP.end())
          continue;
      }

      // level <= m_pTopology->m_uiLevel + 1.
      // We do not want to replicate on the same node (level == 0), even if they are different slaves.
      if (level > 0)
         avail[level].insert(i->first);
   }

   set<int>* candidate = NULL;
   // choose furthest node within replica distance
   for (int i = m_pTopology->m_uiLevel + 1; i > 0; -- i)
   {
      if (!avail[i].empty())
      {
         candidate = &avail[i];
         break;
      }
   }

   if (NULL == candidate)
      return SectorError::E_NODISK;

/*
   int lvl = 0;
//.........这里部分代码省略.........
开发者ID:deniskin82,项目名称:sector-sphere,代码行数:101,代码来源:slavemgmt.cpp

示例12:

// this is set union for the blob coloring algo
set<int> set_union(set<int>& a, set<int>& b)
{
  set<int> retVal = a;
  retVal.insert(b.begin(),b.end());
  return retVal;
}
开发者ID:kscottz,项目名称:ClassCrap,代码行数:7,代码来源:vision_methods.cpp

示例13: sharedSecret

set<DeviceID> EbNRadioBT2PSI::handshake(const set<DeviceID> &deviceIDs)
{
  set<DeviceID> encountered;

  for(auto it = deviceIDs.begin(); it != deviceIDs.end(); it++)
  {
    EbNDeviceBT2 *device = deviceMap_.get(*it);

    // Only perform active confirmation once per device
    if(!device->isConfirmed() && (getHandshakeScheme() == ConfirmScheme::Active))
    {
      // TODO: Make sure that there is enough time to contact the remote
      // device (or time out) prior to the next action

      LOG_D("EbNRadioBT2PSI", "Attempting to connect to device (ID %d, Address %s)", device->getID(), device->getAddress().toString().c_str());

      unique_lock<mutex> discDevicesLock(discDevicesMutex_);
      if(discDevices_.insert(device->getAddress()).second == false)
      {
        LOG_D("EbNRadioBT2PSI", "Skipping connection, already performed during this discovery period");
        break;
      }
      discDevicesLock.unlock();

      int sock = hci_.connectBT2(device->getAddress(), 1, 5000);
      if(sock >= 0)
      {
        LOG_D("EbNRadioBT2PSI", "Connected!");

        Client *psiClient = new JL10_Client();
        Server *psiServer = new JL10_Server();
        psiClient->SetAdaptive();
        psiServer->SetAdaptive();
        psiClient->Setup(1024);
        psiServer->Setup(1024);

        unique_lock<mutex> setLock(setMutex_);
        psiClient->LoadData(psiClientData_);
        psiServer->LoadData(psiServerData_);
        setLock.unlock();

        psiClient->Initialize(1024);
        psiServer->Initialize(1024);

        LOG_D("EbNRadioBT2PSI", "PSI Server and Client initialized...");

        uint32_t messageSize = 0;
        vector<uint8_t> message;
        vector<string> output;
        bool success = true;

        //Exchanging and computing the shared secret
        if(success && (success = hci_.send(sock, dhExchange_.getPublic(), dhExchange_.getPublicSize(), 30000)))
        {
          vector<uint8_t> remotePublic(dhExchange_.getPublicSize());
          if(success && (success = hci_.recv(sock, remotePublic.data(), dhExchange_.getPublicSize(), 30000)))
          {
            SharedSecret sharedSecret(SharedSecret::ConfirmScheme::Active);
            if(dhExchange_.computeSharedSecret(sharedSecret, remotePublic.data()))
            {
              LOG_E("EbNRadioBT2PSI", "Computed shared secret!");
              device->addSharedSecret(sharedSecret);
            }
            else
            {
              LOG_E("EbNRadioBT2PSI", "Could not compute shared secret");
            }
          }
        }

        //Act as client first
        if(success && (success = hci_.recv(sock, (uint8_t *)&messageSize, 4, 30000)))
        {
          LOG_D("EbNRadioBT2PSI", "HC1 - Incoming message of size %u", messageSize);
          message.resize(messageSize);

          if(success && (success = hci_.recv(sock, message.data(), messageSize, 30000)))
          {
            vector<string> publishedData = parsePSIMessage(message);
            psiClient->StoreData(publishedData);

            output.clear();
            (psiClient->*(psiClient->m_vecRequest[0]))(output);

            constructPSIMessage(message, output);
            LOG_D("EbNRadioBT2PSI", "HC1 - Sending message of size %zu", message.size());
            success = hci_.send(sock, message.data(), message.size(), 30000);
          }
        }

        if(success && (success = hci_.recv(sock, (uint8_t *)&messageSize, 4, 30000)))
        {
          LOG_D("EbNRadioBT2PSI", "HC2 - Incoming message of size %u", messageSize);
          message.resize(messageSize);

          if(success && (success = hci_.recv(sock, message.data(), messageSize, 30000)))
          {
            vector<string> input = parsePSIMessage(message);
            (psiClient->*(psiClient->m_vecOnResponse[0]))(input);

//.........这里部分代码省略.........
开发者ID:cDoru,项目名称:ebn-sddr,代码行数:101,代码来源:EbNRadioBT2PSI.cpp

示例14: Visit

void SimpleSnpCallPileupVisitor::Visit(const PileupPosition &pileupData)
{

    if (pileupData.Position<m_chrLeftPos || pileupData.Position>=m_chrRightPos)
        return;

    if (m_snpPositions->find(pileupData.Position)==m_snpPositions->end())
        return;

    // random dicer
    unsigned UniformSeed = chrono::system_clock::now().time_since_epoch().count();
    mt19937_64 UniformGenerator(UniformSeed);
    uniform_int_distribution<int> UniformDist;

    UniformDist = uniform_int_distribution<int>(0, pileupData.PileupAlignments.size());
    auto UniformDicer = bind(UniformDist, UniformGenerator);

    // reference base
    char refBase = m_fasta->at(pileupData.Position-m_chrLeftPos);

    if (refBase=='N')
        return;

    // information buffer
    int globalDepth         = 0;
    double globalMapAvgQual = 0;
    int globalStrandPos     = 0;
    int globalStrandNeg     = 0;

    list<tuple<char,int,int,double>> bamData;
    set<char> alleleBases;
    map<char, int> alleleDepth;
    map<char, double> alleleMapAvgQual;
    map<char, int> alleleStrandPos;
    map<char, int> alleleStrandNeg;
    // iterate through alignments
    for (int i=0; i<pileupData.PileupAlignments.size(); i++)
    {
        char readBase;
        BamAlignment al = pileupData.PileupAlignments[i].Alignment;

        // update global info
        globalDepth         += 1;
        globalMapAvgQual    += al.MapQuality*al.MapQuality;
        if (al.IsReverseStrand())
            globalStrandNeg += 1;
        else
            globalStrandPos += 1;

        // downsampling
        if (UniformDicer()>m_downSample)
            continue;

        // data info
        int nx = GenericBamAlignmentTools::numBamAlignmentMismatches(al);
        int nm = GenericBamAlignmentTools::numBamAlignmentMatches(al);
        double nr = nm/(nm+nx+0.);

        if (pileupData.PileupAlignments[i].IsCurrentDeletion)
        {
            bamData.push_back(tuple<char,int,int,double>('-',0,al.MapQuality,1.));
        }else
        {
            readBase = al.QueryBases.at(pileupData.PileupAlignments[i].PositionInAlignment);
            int baseQuality = int(al.Qualities.at(pileupData.PileupAlignments[i].PositionInAlignment))-33;

            // debug
            if (baseQuality<0)
            {
                cout << int(al.Qualities.at(pileupData.PileupAlignments[i].PositionInAlignment)) << endl;
            }

            if (readBase==refBase || readBase=='N')
            {
                bamData.push_back(tuple<char,int,int,double>(readBase, baseQuality, al.MapQuality,1.));
            }
            else
            {
                bamData.push_back(tuple<char,int,int,double>(readBase, baseQuality, al.MapQuality,nr));
            }
        }

        // here is deletion
        if (pileupData.PileupAlignments[i].IsCurrentDeletion)
            continue;

        // update allele info
        if (readBase!='N' && readBase!=refBase)
        {
            if (pileupData.PileupAlignments[i].IsSegmentBegin || pileupData.PileupAlignments[i].IsSegmentEnd)
                continue;

            if (alleleBases.find(readBase)==alleleBases.end())
            {
                alleleDepth[readBase]         = 1;
                alleleMapAvgQual[readBase]    = al.MapQuality*al.MapQuality;
                if (al.IsReverseStrand())
                {
                    alleleStrandPos[readBase] = 0;
                    alleleStrandNeg[readBase] = 1;
//.........这里部分代码省略.........
开发者ID:homopolymer,项目名称:PyroTools,代码行数:101,代码来源:GenericIndividualSnpCall.cpp

示例15: main

int main() {
	inp(t);

	while(t--) {
		inp(k);
		inp(q);
		for(int a=0;a<k;a++)
			inp(A[a]);
		for(int a=0;a<k;a++)
			inp(B[a]);

		sort(A,A+k);
		sort(B,B+k);

		s.clear();
		s1.clear();

		lli ind=1;
		big=min((lli)10000,k*k);

		lli i=0,j=0,kri=0,a1,b1;

		for(int a=0;a<k;a++) {
			s.insert(mp(A[0]+B[a],ii(0,a)));
			s.insert(mp(A[a]+B[0],ii(a,0)));
		}
		// cout<<s.size()<<endl;
		a1=k;
		b1=k;

		set<pair<lli,ii> >::iterator it;

		while(ind<=big) {
			it=s.begin();
			ans[ind++]=it->first;
			s1.insert(it->second);
			// cout<<ind-1<<" "<<ans[ind-1]<<endl;
			// cout<<big<<endl;
			if((it->second).first==i) {
				a1--;
				// i++;
				if(a1==0 && (i+1)<k) {
					i++;

					// while(i<k) {
					for(int a=0;a<k;a++) {
						if(s1.find(ii(i,a))!=s1.end())
							continue;
						a1++;
						s.insert(mp(A[i]+B[a],ii(i,a)));
					}
						// if(a1)
						// 	break;
						// i++;
				}
				
			}
			if((it->second).second==j) {
				b1--;
				if(b1==0 && (j+1)<k) {
					j++;
					for(int a=0;a<k;a++) {
						if(s1.find(ii(a,j))!=s1.end())
							continue;
						b1++;
						s.insert(mp(A[a]+B[j],ii(a,j)));
					}					
				}
			}

			s.erase(s.begin());
		}

		while(q--) {
			inp(num);
			// if(num>big)
			// 	printf("0\n");
			printf("%lld\n", ans[num]);
		}
	}

	return 0;
}
开发者ID:saikrishna17394,项目名称:Code,代码行数:83,代码来源:lowsum.cpp


注:本文中的set::end方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。