Example #1
0
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);
      }
      else if (upa != upper.end() && lowb != lower.end() && upa->first == p[i] && lowb->first == q[i]) {
        int d = blow.get(lowb->second) + bup.get(upa->second) - 3;
        ans = (tot-d >= d); 
      }
      else {
        cerr << "Ooops!" << endl;
        assert(false);
      }
      puts(ans ? "CW" : "CCW");
    }
  }
  return 0;
}
//--------------------------------------
bool ofGetKeyPressed(int key){
	if(key==-1) return pressedKeys.size();
	return pressedKeys.find(key)!=pressedKeys.end();
}
Example #3
0
set<int> SetOperation::Union()
{
    set<int> result(setA.begin(), setA.end());
    result.insert(setB.begin(), setB.end());
    return result;
}
Example #4
0
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");
}
Example #5
0
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();
}
Example #6
0
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&h[i].h);
		h[i].num=i;
	}
	for(int i=n;i;i--)
	{
		S.insert(h[i]);
		it=S.find(h[i]);
		if(it!=S.begin())
		{
			it--;
			update(h[i],*it);
			if(it!=S.begin())
			{
				it--;
				update(h[i],*it);
				it++;
			}
			it++;
		}
		if((++it)!=S.end())
		{
			update(h[i],*it);
			if((++it)!=S.end())
				update(h[i],*it);
			it--;
		}
		it--;
	}
	for(int i=1;i<=n;i++)
	{
		g[i][0]=next[next[i][1]][0];
		f[i][0][0]=dist[i][1];
		f[i][0][1]=dist[next[i][1]][0];
	}
	for(int j=1;j<=20;j++)
		for(int i=1;i<=n;i++)
		{
			g[i][j]=g[g[i][j-1]][j-1];
			f[i][j][0]=f[i][j-1][0]+f[g[i][j-1]][j-1][0];
			f[i][j][1]=f[i][j-1][1]+f[g[i][j-1]][j-1][1];
		}
	scanf("%d",&x0);
	int s0=0;
	LL a=1e15,b=0;
	for(int i=1;i<=n;i++)
	{
		LL dista=0,distb=0;
		query(i,x0,dista,distb);
		if(distb&&(!s0||a*distb>b*dista))
		{
			s0=i;
			a=dista;
			b=distb;
		}
	}
	printf("%d\n",s0);
	scanf("%d",&m);
	while(m--)
	{
		int s,x;
		scanf("%d%d",&s,&x);
		LL dista=0,distb=0;
		query(s,x,dista,distb);
		printf("%lld %lld\n",dista,distb);
	}
	return 0;
}
Example #7
0
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;
}
Example #8
0
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 << "{";
        for (set<int>::iterator it1 = temp_set.begin(); it1 != temp_set.end(); it1++) {
            cout << ids_item_map.find(*it1)->second << "," ;
        }
        cout << "}" << endl;
    }
    
    **/
    
    int k = 1;
    
    while (true) {
        k = k+1;
        set<set<int> > fk;
        set<set<int> > ck = apriori_gen(freq_itemsets[k-2]);
        // printing candidate itemsets
        /**
        for (set<set<int> >::iterator it = ck.begin(); it != ck.end(); it++) {
            set<int> temp_set  = *it;
            cout << "{";
            for (set<int>::iterator it1 = temp_set.begin(); it1 != temp_set.end(); it1++) {
                cout << ids_item_map.find(*it1)->second << "," ;
            }
            cout << "}" << endl;
        }
        **/
        // printing candidate itemsets
        // support counting for candidate itemsets
        // hash tree constructions and passing transactions
        
        
        // break if no candidates are generated
        
        if (ck.size() == 0) {
            break;
        }
        cout << "bef gen" << endl;
        fk = generate_fk_frm_ck(ck);
        cout << "end gen" << endl;
        if (fk.size() == 0) {
            break;
        }else{
            freq_itemsets.push_back(fk);
        }
    }
    
    for (int i = 0; i<freq_itemsets.size(); i++) {
        cout << i+1 << " frequent itemsets" << endl;
        set<set<int> > temp_set_set = freq_itemsets[i];
        for (set<set<int> >::iterator it = temp_set_set.begin(); it != temp_set_set.end(); it++) {
            set<int> temp_set = (*it);
            cout << "{";
            for (set<int>::iterator it1 = temp_set.begin(); it1 != temp_set.end(); it1++) {
                cout << (*it1) << ",";
            }
            cout << "}" << endl;
        }
        cout << endl;
        
    }
    
    
    return 0;
}
Example #9
0
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;
          isSgStatement(stmt->get_parent())->remove_statement(stmt);
        }
        return currentLiveVars;
      } else {
        currentLiveVars.erase(in);
        if (in->get_initializer()) {
          getUsedVariables(in->get_initializer(), currentLiveVars);
        }
        return currentLiveVars;
      }
    }
    default: cerr << "computeLiveVars: " << stmt->class_name() << endl; abort();
  }
}
Example #10
0
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);
      if (subj.type == VARIABLE) {
        result[subj.get.variable] = begin->at(0);
      }
      if (pred.type == VARIABLE) {
        if (subj.type == VARIABLE && subj.get.variable == pred.get.variable) {
          if (begin->at(0) != begin->at(1)) {
            continue;
          }
        }
        result[pred.get.variable] = begin->at(1);
      }
      if (obj.type == VARIABLE) {
        if (subj.type == VARIABLE && subj.get.variable == obj.get.variable) {
          if (begin->at(0) != begin->at(2)) {
            continue;
          }
        }
        if (pred.type == VARIABLE && pred.get.variable == obj.get.variable) {
          if (begin->at(1) != begin->at(2)) {
            continue;
          }
        }
        result[obj.get.variable] = begin->at(2);
      }
      selection.push_back(result);
    }
    if (slot == atom.get.frame.slots.begin) {
      intermediate.swap(selection);
    } else {
      vector<size_t> joinvars (allvars.size() + newvars.size());
      vector<size_t>::iterator jit = set_intersection(allvars.begin(),
          allvars.end(), newvars.begin(), newvars.end(), joinvars.begin());
      joinvars.resize(jit - joinvars.begin());
      join(intermediate, selection, joinvars, intermediate);
    }
    allvars.insert(newvars.begin(), newvars.end());
  }
  results.swap(intermediate);
  DEBUG("Number selected = ", results.size());
}
Example #11
0
void query(Condition &condition, set<varint_t> &allvars, Relation &results) {
  deque<void*> negated;
  Relation intermediate;
  switch (condition.type) {
    case ATOMIC: {
      query(condition.get.atom, allvars, results);
      return;
    }
    case CONJUNCTION: {
      Condition *subformula = condition.get.subformulas.begin;
      for (; subformula != condition.get.subformulas.end; ++subformula) {
        if (subformula->type == NEGATION) {
          negated.push_back((void*)subformula->get.subformulas.begin);
          continue;
        }
        Relation subresult;
        set<varint_t> newvars;
        // TODO vvv this won't work right if a non-special query
        // has not been performed first
        if (special(*subformula, intermediate, subresult)) {
          if (subformula == condition.get.subformulas.begin) {
            cerr << "[ERROR] Must have non-special query at beginning of conjunction." << endl;
          }
          intermediate.swap(subresult);
          continue;
        }
        query(*subformula, newvars, subresult);
        if (subformula == condition.get.subformulas.begin) {
          intermediate.swap(subresult);
        } else {
          vector<size_t> joinvars(allvars.size() + newvars.size());
          vector<size_t>::iterator jit = set_intersection(allvars.begin(),
              allvars.end(), newvars.begin(), newvars.end(), joinvars.begin());
          joinvars.resize(jit - joinvars.begin());
          join(intermediate, subresult, joinvars, intermediate);
        }
        allvars.insert(newvars.begin(), newvars.end());
      }
      break;
    }
    case DISJUNCTION: {
      cerr << "[ERROR] Disjunction is not supported." << endl;
      return;
    }
    case EXISTENTIAL: {
      // assuming all quantified variables are uniquely named in the scope of the rule
      Condition *subformula = condition.get.subformulas.begin;
      for (; subformula != condition.get.subformulas.end; ++subformula) {
        if (subformula->type == NEGATION) {
          negated.push_back((void*)subformula->get.subformulas.begin);
        }
        Relation subresult;
        query(*subformula, allvars, subresult);
        intermediate.splice(intermediate.end(), subresult);
      }
      break;
    }
    case NEGATION: {
      cerr << "[ERROR] This should never happen.  query should not be called directly on negated formulas." << endl;
      return;
    }
    default: {
      cerr << "[ERROR] Unhandled case " << (int)condition.type << " on line " << __LINE__ << endl;
      return;
    }
  }
// TODO deal with negation later, if at all
#if 1
  deque<void*>::iterator it = negated.begin();
  for (; !intermediate.empty() && it != negated.end(); ++it) {
    Relation negresult;
    Condition *cond = (Condition*) *it;
    if (special(*cond, intermediate, negresult)) {
      intermediate.sort();
      negresult.sort();
      Relation leftover(intermediate.size());
      Relation::iterator iit = set_difference(intermediate.begin(),
          intermediate.end(), negresult.begin(), negresult.end(),
          leftover.begin());
      Relation newinter;
      newinter.splice(newinter.end(), leftover,
                      leftover.begin(), iit);
      intermediate.swap(newinter);
      continue;
    }
    query(*((Condition*)(*it)), allvars, negresult);
    minusrel(intermediate, negresult, intermediate);
  }
#endif
  results.swap(intermediate);
}
Example #12
0
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;

         sl.push_back(sn);
      }
   }

   return sl.size();
}
Example #13
0
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;
   log().trace << "Available slaves" << std::endl;
   for ( vector <set <int> >::const_iterator vi = avail.begin(); vi != avail.end(); ++vi)
   {
      log().trace << "Level " << lvl << " ";
      for ( set< int >::const_iterator si = vi->begin(); si != vi->end(); ++si)
        log().trace << *si << ",";
      log().trace << std::endl;
      lvl++;
   }
  
   log().trace << "Candidate slaves ";
   for (set<int>::const_iterator cs = candidate->begin(); cs != candidate->end(); ++ cs)
     log().trace << *cs << ",";
   log().trace << std::endl;
*/
/*
   int64_t totalFreeSpaceOnCandidates = 0;
   for( set<int>::iterator j = candidate->begin(); j != candidate->end(); ++j )
   {
       totalFreeSpaceOnCandidates += m_mSlaveList[*j].m_llAvailDiskSpace;
   }
   int64_t avgFreeSpaceOnCandidates = totalFreeSpaceOnCandidates / candidate->size();

   for( set<int>::iterator c = candidate->begin(); c != candidate->end(); )
       if( m_mSlaveList[*c].m_llAvailDiskSpace < avgFreeSpaceOnCandidates )
       {
           set<int>::iterator tmp = c++;
           candidate->erase( tmp );
       }
       else
           ++c;
*/

   std::vector<int> slavesOrderedByFreeSpace( candidate->begin(), candidate->end() );
   std::sort( slavesOrderedByFreeSpace.begin(), slavesOrderedByFreeSpace.end(), SortByFreeSpace( m_mSlaveList ) );

   slavesOrderedByFreeSpace.resize( slavesOrderedByFreeSpace.size() / 2 + slavesOrderedByFreeSpace.size() % 2 );
   candidate->clear();
   candidate->insert( slavesOrderedByFreeSpace.begin(), slavesOrderedByFreeSpace.end() );

   // Choose a random node.
   timeval t;
   gettimeofday(&t, 0);
   srand(t.tv_usec);
   int r = int(candidate->size() * (double(rand()) / RAND_MAX));
   set<int>::iterator n = candidate->begin();
   for (int i = 0; i < r; ++ i)
      n ++;

   // If there is no other active transaction on this node, return.
   if( m_mSlaveList.find( *n ) == m_mSlaveList.end() )
      log().error << __PRETTY_FUNCTION__ << ": (1) about to add new slave to list " << *n << std::endl;

   sn = m_mSlaveList[*n];
   if (sn.m_iActiveTrans == 0)
   {
//      log().trace << "Choosen slave without active transactions " << sn.m_iNodeID << std::endl;
      return 1;
   }

   // Choose node with lowest number of active transactions.
   set<int>::iterator s = n;
   do
   {
      if (++s == candidate->end())
         s = candidate->begin();
      if( m_mSlaveList.find( *s ) == m_mSlaveList.end() )
         log().error << __PRETTY_FUNCTION__ << ": (2) about to add new slave to list " << *s << std::endl;
      if (m_mSlaveList[*s].m_iActiveTrans < sn.m_iActiveTrans)
      {
         sn = m_mSlaveList[*s];
         if (sn.m_iActiveTrans == 0)
            break;
      }
   } while (s != n);

//   log().trace << "Choosen slave with lowest no of active transactions " << sn.m_iNodeID << std::endl;

   return 1;
}
Example #14
0
// 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;
}
Example #15
0
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);

            LOG_D("EbNRadioBT2PSI", "HC2 - Result (Size = %zu)", psiClient->m_vecResult.size());
          }
        }

        //Act as server second
        if(success)
        {
          output.clear();
          psiServer->PublishData(output);
          constructPSIMessage(message, output);
          LOG_D("EbNRadioBT2PSI", "HS1 - 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", "HS2 - Incoming message of size %u", messageSize);
          message.resize(messageSize);

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

            output.clear();
            (psiServer->*(psiServer->m_vecResponse[0]))(output);

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

        // TODO: Process the result to update matching set

        delete psiClient;
        delete psiServer;

        LOG_D("EbNRadioBT2PSI", "Waiting for remote client to close connection...");
        hci_.waitClose(sock, 30000);
        LOG_D("EbNRadioBT2PSI", "Done!");

        close(sock);
      }
    }

    device->setShakenHands(true);
  }

  // Going through all devices to report 'encountered' devices, meaning
  // the devices we have shaken hands with and confirmed
  for(auto it = deviceMap_.begin(); it != deviceMap_.end(); it++)
  {
    EbNDevice *device = it->second;
    if(device->hasShakenHands() && device->isConfirmed())
    {
      encountered.insert(device->getID());
    }
  }

  return encountered;
}
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;
                }
                else
                {
                    alleleStrandPos[readBase] = 1;
                    alleleStrandNeg[readBase] = 0;
                }
                alleleBases.insert(readBase);
            }else
            {
                alleleDepth[readBase]         += 1;
                alleleMapAvgQual[readBase]    += al.MapQuality*al.MapQuality;
                if (al.IsReverseStrand())
                    alleleStrandNeg[readBase] += 1;
                else
                    alleleStrandPos[readBase] += 1;
            }
        }
    }

    // save allele info
    for (set<char>::iterator iter=alleleBases.begin(); iter!=alleleBases.end(); iter++)
    {
        Allele allele;
        allele.m_chrID            = pileupData.RefId;
        allele.m_chrPosition      = pileupData.Position;
        allele.m_allele           = *iter;
        allele.m_reference        = refBase;
        allele.m_alleleDepth      = alleleDepth[*iter];
        allele.m_alleleMapAvgQual = sqrt(alleleMapAvgQual[*iter])/allele.m_alleleDepth;
        allele.m_alleleStrandPos  = alleleStrandPos[*iter];
        allele.m_alleleStrandNeg  = alleleStrandNeg[*iter];

        // global info
        allele.m_globalDepth      = globalDepth;
        allele.m_globalMapAvgQual = sqrt(globalMapAvgQual)/globalDepth;
        allele.m_globalStrandPos  = globalStrandPos;
        allele.m_globalStrandNeg  = globalStrandNeg;

        m_snpAlleles->push_back(allele);
    }

    (*m_bamData)[pileupData.Position] = bamData;
}
Example #17
0
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;
}
Example #18
0
bool GetKeyState(int key)
{
  int vk = 0;

  if(key >= eRENDERDOC_Key_A && key <= eRENDERDOC_Key_Z)
    vk = key;
  if(key >= eRENDERDOC_Key_0 && key <= eRENDERDOC_Key_9)
    vk = key;

  switch(key)
  {
    case eRENDERDOC_Key_Divide: vk = VK_DIVIDE; break;
    case eRENDERDOC_Key_Multiply: vk = VK_MULTIPLY; break;
    case eRENDERDOC_Key_Subtract: vk = VK_SUBTRACT; break;
    case eRENDERDOC_Key_Plus: vk = VK_ADD; break;
    case eRENDERDOC_Key_F1: vk = VK_F1; break;
    case eRENDERDOC_Key_F2: vk = VK_F2; break;
    case eRENDERDOC_Key_F3: vk = VK_F3; break;
    case eRENDERDOC_Key_F4: vk = VK_F4; break;
    case eRENDERDOC_Key_F5: vk = VK_F5; break;
    case eRENDERDOC_Key_F6: vk = VK_F6; break;
    case eRENDERDOC_Key_F7: vk = VK_F7; break;
    case eRENDERDOC_Key_F8: vk = VK_F8; break;
    case eRENDERDOC_Key_F9: vk = VK_F9; break;
    case eRENDERDOC_Key_F10: vk = VK_F10; break;
    case eRENDERDOC_Key_F11: vk = VK_F11; break;
    case eRENDERDOC_Key_F12: vk = VK_F12; break;
    case eRENDERDOC_Key_Home: vk = VK_HOME; break;
    case eRENDERDOC_Key_End: vk = VK_END; break;
    case eRENDERDOC_Key_Insert: vk = VK_INSERT; break;
    case eRENDERDOC_Key_Delete: vk = VK_DELETE; break;
    case eRENDERDOC_Key_PageUp: vk = VK_PRIOR; break;
    case eRENDERDOC_Key_PageDn: vk = VK_NEXT; break;
    case eRENDERDOC_Key_Backspace: vk = VK_BACK; break;
    case eRENDERDOC_Key_Tab: vk = VK_TAB; break;
    case eRENDERDOC_Key_PrtScrn: vk = VK_SNAPSHOT; break;
    case eRENDERDOC_Key_Pause: vk = VK_PAUSE; break;
    default: break;
  }

  if(vk == 0)
    return false;

  bool keydown = GetAsyncKeyState(vk) != 0;

  if(inputWindows.empty() || !keydown)
    return keydown;

  for(auto it = inputWindows.begin(); it != inputWindows.end(); ++it)
  {
    HWND w = *it;
    HWND fore = GetForegroundWindow();

    while(w)
    {
      if(w == fore)
        return keydown;

      w = GetParent(w);
    }
  }

  return false;
}
Example #19
0
    void drillDown( boost::filesystem::path root, bool use_db, bool use_coll, bool top_level=false ) {
        log(2) << "drillDown: " << root.string() << endl;

        // skip hidden files and directories
        if (root.leaf()[0] == '.' && root.leaf() != ".")
            return;

        if ( is_directory( root ) ) {
            boost::filesystem::directory_iterator end;
            boost::filesystem::directory_iterator i(root);
            boost::filesystem::path indexes;
            while ( i != end ) {
                boost::filesystem::path p = *i;
                i++;

                if (use_db) {
                    if (boost::filesystem::is_directory(p)) {
                        error() << "ERROR: root directory must be a dump of a single database" << endl;
                        error() << "       when specifying a db name with --db" << endl;
                        printHelp(cout);
                        return;
                    }
                }

                if (use_coll) {
                    if (boost::filesystem::is_directory(p) || i != end) {
                        error() << "ERROR: root directory must be a dump of a single collection" << endl;
                        error() << "       when specifying a collection name with --collection" << endl;
                        printHelp(cout);
                        return;
                    }
                }

                // don't insert oplog
                if (top_level && !use_db && p.leaf() == "oplog.bson")
                    continue;

                if ( p.leaf() == "system.indexes.bson" ) {
                    indexes = p;
                }
                else if (_restoreShardingConfig && is_directory(p) && p.leaf() == "config") {
                    // Config directory should have already been restored. Skip it here.
                    continue;
                }
                else {
                    drillDown(p, use_db, use_coll);
                }
            }

            if (!indexes.empty())
                drillDown(indexes, use_db, use_coll);

            return;
        }

        if ( endsWith( root.string().c_str() , ".metadata.json" ) ) {
            // Metadata files are handled when the corresponding .bson file is handled
            return;
        }

        if ( ! ( endsWith( root.string().c_str() , ".bson" ) ||
                 endsWith( root.string().c_str() , ".bin" ) ) ) {
            error() << "don't know what to do with file [" << root.string() << "]" << endl;
            return;
        }

        log() << root.string() << endl;

        if ( root.leaf() == "system.profile.bson" ) {
            log() << "\t skipping" << endl;
            return;
        }

        string ns;
        if (use_db) {
            ns += _db;
        }
        else {
            string dir = root.branch_path().string();
            if ( dir.find( "/" ) == string::npos )
                ns += dir;
            else
                ns += dir.substr( dir.find_last_of( "/" ) + 1 );

            if ( ns.size() == 0 )
                ns = "test";
        }

        verify( ns.size() );

        string oldCollName = root.leaf(); // Name of the collection that was dumped from
        oldCollName = oldCollName.substr( 0 , oldCollName.find_last_of( "." ) );
        if (use_coll) {
            ns += "." + _coll;
        }
        else {
            ns += "." + oldCollName;
        }

        log() << "\tgoing into namespace [" << ns << "]" << endl;

        if ( _drop ) {
            if (root.leaf() != "system.users.bson" ) {
                log() << "\t dropping" << endl;
                conn().dropCollection( ns );
            } else {
                // Create map of the users currently in the DB
                BSONObj fields = BSON("user" << 1);
                scoped_ptr<DBClientCursor> cursor(conn().query(ns, Query(), 0, 0, &fields));
                while (cursor->more()) {
                    BSONObj user = cursor->next();
                    _users.insert(user["user"].String());
                }
            }
        }

        BSONObj metadataObject;
        if (_restoreOptions || _restoreIndexes) {
            boost::filesystem::path metadataFile = (root.branch_path() / (oldCollName + ".metadata.json"));
            if (!boost::filesystem::exists(metadataFile.string())) {
                // This is fine because dumps from before 2.1 won't have a metadata file, just print a warning.
                // System collections shouldn't have metadata so don't warn if that file is missing.
                if (!startsWith(metadataFile.leaf(), "system.")) {
                    log() << metadataFile.string() << " not found. Skipping." << endl;
                }
            } else {
                metadataObject = parseMetadataFile(metadataFile.string());
            }
        }

        _curns = ns.c_str();
        _curdb = NamespaceString(_curns).db;
        _curcoll = NamespaceString(_curns).coll;

        if (_restoreOptions && metadataObject.hasField("options")) {
            // Try to create collection with given options
            createCollectionWithOptions(metadataObject["options"].Obj());
        }

        processFile( root );
        if (_drop && root.leaf() == "system.users.bson") {
            // Delete any users that used to exist but weren't in the dump file
            for (set<string>::iterator it = _users.begin(); it != _users.end(); ++it) {
                BSONObj userMatch = BSON("user" << *it);
                conn().remove(ns, Query(userMatch));
            }
            _users.clear();
        }

        if (_restoreIndexes && metadataObject.hasField("indexes")) {
            vector<BSONElement> indexes = metadataObject["indexes"].Array();
            for (vector<BSONElement>::iterator it = indexes.begin(); it != indexes.end(); ++it) {
                createIndex((*it).Obj(), false);
            }
        }
    }
Example #20
0
void Editor::formatStreamLine(){
	string out;
	char cf='0';
	for( int k=0;k<is_line.size(); ){
		int from=k;
		char pf=cf;
		int c=is_line[k],is_sz=is_line.size();
		if( !isgraph( c ) ){
			for( ++k;k<is_sz && !isgraph(is_line[k]);++k ){}
		}else if( !isfmt( c,k+1<is_sz?is_line[k+1]:0 ) ){
			for( ++k;k<is_sz && !isfmt( is_line[k],k+1<is_sz?is_line[k+1]:0 );++k ){}
			cf='6';
		}else if( c==';' ){					//comment?
			k=is_sz;
			cf='4';
		}else if( c=='\"' ){		//string const?
			for( ++k;k<is_sz && is_line[k]!='\"';++k ){}
			if( k<is_sz ) ++k;
			cf='1';
		}else if( isalpha( c ) ){		//ident?
			for( ++k;k<is_sz && isid(is_line[k]);++k ){}
			if( keyWordSet.find( is_line.substr( from,k-from ) )==keyWordSet.end() ) cf='2';
			else cf='3';
		}else if( c=='$' ){
			for( ++k;k<is_sz && isxdigit(is_line[k]);++k ){}
			cf='5';
		}else if( isdigit( c ) ){	//numeric const?
			for( ++k;k<is_sz && isdigit(is_line[k]);++k ){}
			cf='5';
		}
		if( cf!=pf ){
			out+="\\cf";out+=cf;out+=' ';
		}
		out+=is_line.substr( from,k-from );
	}
	if( is_line[0]=='F' && is_line.find( "Function" )==0 ){
		for( int k=8;k<is_line.size();++k ){
			if( isalpha( is_line[k] ) ){
				int start=k;
				for( ++k;k<is_line.size() && isid(is_line[k]);++k ){}
				funcList.insert( is_linenum,is_line.substr( start,k-start ) );
				break;
			}
		}
	}else if( is_line[0]=='T' && is_line.find( "Type" )==0 ){
		for( int k=4;k<is_line.size();++k ){
			if( isalpha( is_line[k] ) ){
				int start=k;
				for( ++k;k<is_line.size() && isid(is_line[k]);++k ){}
				typeList.insert( is_linenum,is_line.substr( start,k-start ) );
				break;
			}
		}
	}else if( is_line[0]=='.' ){
		for( int k=1;k<is_line.size();++k ){
			if( isalpha( is_line[k] ) ){
				int start=k;
				for( ++k;k<is_line.size() && isid(is_line[k]);++k ){}
				labsList.insert( is_linenum,is_line.substr( start,k-start ) );
				break;
			}
		}
	}
	is_line=out+"\\line ";
}
Example #21
0
set<int> myunion(const set<int>& s1, const set<int>& s2)
{
  set<int> u;
  set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(u, u.begin()));
  return u;
}
Example #22
0
int main() {
	const bool debug = false;
	int i, j, k;
	P bg, nd, t;
	while(~scanf("%d%d%d%d", &x1, &y1, &x2, &y2)) {
		if(x1 == 0 && x2 == 0 && y1 == 0 && y2 == 0)break;
		scanf("%d", &n);

		x.clear();x.insert(x1);x.insert(x2);
		y.clear();y.insert(y1);y.insert(y2);

		for(i = 0; i < n; i++) {
			b[i].init();
			x.insert(b[i].x1);
			x.insert(b[i].x2);
			y.insert(b[i].y1);
			y.insert(b[i].y2);
		}
		hx.clear();
		hy.clear();

		//把地图扩大二倍后,矩阵内部就可以被填充,矩阵边界就可以走了

		//对x离散化
		for(si = x.begin(), mx = 1; si != x.end(); hx[*si++] = mx, mx+=2) ;


		//对y离散化
		for(si = y.begin(), my = 1; si != y.end(); hy[*si++] = my, my+=2);

		//初始化
		for(j = 0; j < 4; ++j){
			for(i = 0; i < mx; ++i){
				fill(v[j][i], v[j][i] + my, false);
				fill(s[j][i], s[j][i] + my, inf);
			}
		}
		for(i = 0; i < mx; ++i){
			fill(m[i], m[i] + my, 0);
		}

		//填充矩阵,填充为1
		for(i = 0; i < n; i++) {
			int xuper = hx[b[i].x2];
			int yuper = hy[b[i].y2];
			//填充上下边界
			for(j = hx[b[i].x1]; j <= xuper; j++){
				m[j][hy[b[i].y1]]=m[j][hy[b[i].y2]]=1;
			}
			//填充左右边界
			for(k = hy[b[i].y1]; k <= yuper; k++){
				m[hx[b[i].x1]][k]=m[hx[b[i].x2]][k]=1;
			}
			//填充矩阵内部
			for(j = hx[b[i].x1] + 1; j < xuper; j++) {
				for(k = hy[b[i].y1] + 1; k < yuper; k++) {
					m[j][k]=2;
				}
			}
		}


		//此路不同,标记为2
		for(i=1;i<mx-1;i++){
			for(j=1;j<my-1;j++){
				if(m[i-1][j]&&m[i][j-1]&&m[i+1][j]&&m[i][j+1])
					m[i][j]=2;
			}
		}

		if(debug) {
			puts("---- stp ----");
			for(i = 0; i < mx; i++) {
				for(j = 0; j < my; j++) {
					printf(" %2d",m[i][j]);
				}
				puts("");
			}
			puts("---- stp ----\n\n");
		}


		while(!que.empty())que.pop();

		nd.x = hx[x2];
		nd.y = hy[y2];

		bg.x = hx[x1];
		bg.y = hy[y1];

		bg.stp = 0;
		//分别标记出发点的四个方向,并入‡队
		for(i = 0; i < 4; i++) {
			bg.d = i;
			v[i][bg.x][bg.y] = true;
			s[i][bg.x][bg.y] = 0;
			que.push(bg);
		}

		int ndnum=0;

		while(!que.empty()) {

			bg = que.top();que.pop();

			//由于是优先搜索,所以只要到达就一定是最优的
			if(bg.x == nd.x && bg.y == nd.y){
				break;
			}

			for(i = 0; i < 4; i++) {

				//回头,不会有更优的答案
				if((i+2)%4 == bg.d)continue;

				t.x = bg.x + pos[i][0];
				t.y = bg.y + pos[i][1];

				//越界
				if(t.x < 0 || t.y < 0 || t.x >= mx || t.y >= my)continue;

				//此路不通
				if(m[t.x][t.y] >1)continue;

				//更新步数
				t.stp = s[bg.d][bg.x][bg.y] + (i == bg.d?0:1);

				//此地点已经达到过,且更优
				if(v[i][t.x][t.y] && t.stp >= s[i][t.x][t.y])continue;




				//此路可以更新
				s[i][t.x][t.y] = t.stp;
				v[i][t.x][t.y] = true;
				t.d = i;

				que.push(t);
			}

		}

		int ans = inf;
		for(i = 0; i < 4; i++) {
			if(ans > s[i][nd.x][nd.y])
				ans = s[i][nd.x][nd.y];
		}
		printf("%d\n", ans==inf?-1:ans);

		if(debug) {
			puts("---- stp ----");
			for(i = 0; i < mx; i++) {
				for(j = 0; j < my; j++) {
					if(m[i][j]){
						printf(" %2d",-m[i][j]);
					}else{
						int tmp=inf;
						for(int kk=0;kk<4;kk++){
							if(tmp>s[kk][i][j]){
								tmp=s[kk][i][j];
							}
						}
						if(tmp==inf)tmp=-3;
						printf(" %2d",tmp);
					}

				}
				puts("");
			}
			puts("---- stp ----\n\n");
		}

	}
	return 0;
}
LabelUpdateThread::LabelUpdateThread(const set<string> &labelsToDelete,
	const map<string, string> &labelsToRename)
{
	copy(labelsToDelete.begin(), labelsToDelete.end(), inserter(m_labelsToDelete, m_labelsToDelete.begin()));
	copy(labelsToRename.begin(), labelsToRename.end(), inserter(m_labelsToRename, m_labelsToRename.begin()));
}
Example #24
0
void work() {
	for (int i = 0; i < 40005; i++) {
		f[i] = i;
	}
	for (int i = 0; i < 40005; i++) {
		g[i].clear();
	}
	
	cb.clear();
	ans.clear();
	dd.clear();
	i1.clear();
	qu.clear();
	
	int n, m, q, u, v, a, b, c;
	scanf("%d %d %d", &n, &m, &q);
	
	for (int i = 0; i < m; i++) {
		scanf("%d %d", &u, &v);
		if (u > v) swap(u, v);
		i1.push_back(make_pair(u, v));
	}
	for (int i = 0; i < q; i++) {
		scanf("%d %d %d", &a, &b, &c);
		if (a == 1) {
			if (b > c) swap(b, c);
			dd[make_pair(b, c)]++;
		}
		qu.push_back(make_tuple(a, b, c));
	}
	
	for (int i = 0; i < m; i++) {
		if (dd[i1[i]] == 0) {
			if (cb.find(i1[i]) == cb.end()) {
				if (i1[i].first == i1[i].second) continue;
				cb.insert(i1[i]);
				g[i1[i].first].push_back(i1[i].second);
				g[i1[i].second].push_back(i1[i].first);
			} else {
				uni(i1[i].first, i1[i].second);
			}
		} else {
			dd[i1[i]]--;
		}
	}
	
	memset(vis, 0, sizeof(vis));
	dfs(1, -1, 0);
	
	slpf::init(n);
	
	for (int i = q-1 ; i >= 0; i--) {
		int a = get<0>(qu[i]), b = get<1>(qu[i]), c = get<2>(qu[i]);
		if (a == 1) {
			if (getf(b) == getf(c)) continue;
			slpf::modify(getf(b), getf(c));
		} else {
			if (getf(b) == getf(c)) {
				ans.push_back(0);
			} else {
				ans.push_back(slpf::query(getf(b), getf(c)));
			}
		}
	}
	
	int s = ans.size();
	for (int i = s-1; i >= 0; i--) {
		printf("%d\n", ans[i]);
	}
}
//--------------------------------------
bool ofGetMousePressed(int button){ //by default any button
	if(button==-1) return pressedMouseButtons.size();
	return pressedMouseButtons.find(button)!=pressedMouseButtons.end();
}
 set<int>::iterator next(set<int>::iterator it, set<int> &S) {
     return it == S.end() ? it : ++it;
 }
Example #27
0
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; ++i)
    scanf("%lld", a+i);
  long long sum1 = 0, ma1 = -1e18, sum2 = 0, ma2 = -1e18;
  for (int i = 0; i < n; ++i) {
    if (i & 1) {
      if (a[i] > 0)
        sum1 += a[i];
      ma1 = max(ma1, a[i]);
    }
    else {
      if (a[i] > 0)
        sum2 += a[i];
      ma2 = max(ma2, a[i]);
    }
  }
  fill(live, live+n, 1);
  if (ma1 < 0) sum1 = ma1;
  if (ma2 < 0) sum2 = ma2;
  if (sum1 > sum2) {
    if (ma1 < 0) {
      for (int i = 0; i < n; ++i)
        if (a[i] == ma1) {
          used[i] = 1;
          break;
        }
    }
    else {
      for (int i = 1; i < n; i += 2)
        if (a[i] >= 0)
          used[i] = 1;
    }
  }
  else {
    if (ma2 < 0) {
      for (int i = 0; i < n; ++i)
        if (a[i] == ma2) {
          used[i] = 1;
          break;
        }
    }
    else {
      for (int i = 0; i < n; i += 2)
        if (a[i] >= 0)
          used[i] = 1;
    }
  }
  long long ans = 0;
  for (int i = 0; i < n; ++i)
    if (used[i]) ans += a[i];
  for (int i = 0; i < n; ++i) {
    upd(i, 1);
    st.insert(i);
  }
  printf("%lld\n", ans);
  vector<int> op;
  while (st.size() > 1) {
    for (auto it = st.begin(); it != st.end(); ++it) {
      if (used[*it]) continue;
      auto nx = it;
      ++nx;
      bool del = 0;
      if (it == st.begin() || nx == st.end()) {
        del = 1;
      }
      else {
        auto pr = it; --pr;
        if (used[*pr] == used[*nx])
          del = 1;
      }
      if (del) {
        op.push_back(get(*it));
        if (nx != st.end()) {
          used[*it] = used[*nx];
          rem(*nx);
        }
        if (it != st.begin()) {
          auto pr = it; --pr;
          used[*it] = used[*pr];
          rem(*pr);
        }
        break;
      }
    }
  }
  printf("%d\n", op.size());
  for (int x : op)
    printf("%d\n", x);
  return 0;
}
Example #28
0
    Query ConfigDiffTracker<ValType,ShardType>::
        configDiffQuery( const set<ChunkVersion>& extraMinorVersions ) const
    {
        verifyAttached();

        //
        // Basic idea behind the query is to find all the chunks $gt the current max version, and
        // then also update chunks that we need minor versions - splits and (2.0) max chunks on
        // shards
        //

        static const int maxMinorVersionClauses = 50;
        BSONObjBuilder queryB;

        int numStaleMinorClauses = extraMinorVersions.size() + _maxShardVersions->size();

#ifdef _DEBUG
        // In debug builds, randomly trigger full reloads to exercise both codepaths
        if( rand() % 2 ) numStaleMinorClauses = maxMinorVersionClauses;
#endif

        queryB.append(ChunkType::ns(), _ns);

        //
        // If we have only a few minor versions to refresh, we can be more selective in our query
        //
        if( numStaleMinorClauses < maxMinorVersionClauses ){

            //
            // Get any version changes higher than we know currently
            //
            BSONArrayBuilder queryOrB( queryB.subarrayStart( "$or" ) );
            {
                BSONObjBuilder queryNewB( queryOrB.subobjStart() );
                {
                    BSONObjBuilder ts(queryNewB.subobjStart(ChunkType::DEPRECATED_lastmod()));
                    // We should *always* pull at least a single chunk back, this lets us quickly
                    // detect if our collection was unsharded (and most of the time if it was
                    // resharded) in the meantime
                    ts.appendTimestamp( "$gte", _maxVersion->toLong() );
                    ts.done();
                }

                queryNewB.done();
            }

            // Get any shard version changes higher than we know currently
            // Needed since there could have been a split of the max version chunk of any shard
            // TODO: Ideally, we shouldn't care about these
            for( typename map<ShardType, ChunkVersion>::const_iterator it = _maxShardVersions->begin(); it != _maxShardVersions->end(); it++ ){

                BSONObjBuilder queryShardB( queryOrB.subobjStart() );
                queryShardB.append(ChunkType::shard(), nameFrom( it->first ) );
                {
                    BSONObjBuilder ts(queryShardB.subobjStart(ChunkType::DEPRECATED_lastmod()));
                    ts.appendTimestamp( "$gt", it->second.toLong() );
                    ts.done();
                }
                queryShardB.done();
            }

            // Get any minor version changes we've marked as interesting
            // TODO: Ideally we shouldn't care about these
            for( set<ChunkVersion>::const_iterator it = extraMinorVersions.begin(); it != extraMinorVersions.end(); it++ ){

                BSONObjBuilder queryShardB( queryOrB.subobjStart() );
                {
                    BSONObjBuilder ts(queryShardB.subobjStart(ChunkType::DEPRECATED_lastmod()));
                    ts.appendTimestamp( "$gt", it->toLong() );
                    ts.appendTimestamp( "$lt",
                                        ChunkVersion( it->majorVersion() + 1, 0, OID() ).toLong() );
                    ts.done();
                }
                queryShardB.done();
            }

            queryOrB.done();
        }

        BSONObj query = queryB.obj();

        LOG(2) << "major version query from " << *_maxVersion << " and over "
               << _maxShardVersions->size() << " shards is " << query << endl;

        //
        // NOTE: IT IS IMPORTANT FOR CONSISTENCY THAT WE SORT BY ASC VERSION, TO HANDLE
        // CURSOR YIELDING BETWEEN CHUNKS BEING MIGRATED.
        //
        // This ensures that changes to chunk version (which will always be higher) will always
        // come *after* our current position in the chunk cursor.
        //

        Query queryObj(query);
        queryObj.sort(BSON( "lastmod" << 1 ));

        return Query( query );
    }
Example #29
0
Endpoint EndpointPool::getCandidate(const set<unsigned int>& not_in, int64_t start_time)
{
    //
    // Choose an address to connect to based on most recently seen
    //
    Endpoint candidate;
    
    int64_t now = GetAdjustedTime();
    vector<Endpoint> endpoints = queryColRow<Endpoint(unsigned int, unsigned short, unsigned int, unsigned int)>("SELECT ip, port, time, lasttry FROM Endpoints WHERE lasttry < ? ORDER BY time DESC", now-60*60);
    
    // iterate until we get an address not in not_in or in the same class-B network:
    for (vector<Endpoint>::const_iterator e = endpoints.begin(); e != endpoints.end(); ++e) {
        bool skip = false;
        for (set<unsigned int>::const_iterator ep = not_in.begin(); ep != not_in.end(); ++ep) {
            if (e->getIP() == (*ep)) {
                skip = true;
                break;
            }
        }
        if (skip) continue;
        
        Endpoint candidate = *e;
        if (!candidate.isIPv4() || !candidate.isValid())
            continue;
        
        return candidate;
    }
    
    return Endpoint();
/*
    BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, Endpoint)& item, _endpoints)
        {
        const Endpoint& ep = item.second;
        if (!ep.isIPv4() || !ep.isValid() || not_in.count(ep.getIP() & 0x0000ffff))
            continue;
        int64_t sinceLastSeen = GetAdjustedTime() - ep.getTime();
        int64_t sinceLastTry = GetAdjustedTime() - ep.getLastTry();
        
        // Randomize the order in a deterministic way, putting the standard port first
        int64_t randomizer = (uint64_t)(start_time * 4951 + ep.getLastTry() * 9567851 + ep.getIP() * 7789) % (2 * 60 * 60);
        if (ep.getPort() != htons(_defaultPort))
            randomizer += 2 * 60 * 60;
        
        // Last seen  Base retry frequency
        //   <1 hour   10 min
        //    1 hour    1 hour
        //    4 hours   2 hours
        //   24 hours   5 hours
        //   48 hours   7 hours
        //    7 days   13 hours
        //   30 days   27 hours
        //   90 days   46 hours
        //  365 days   93 hours
        int64_t delay = (int64_t)(3600.0 * sqrt(fabs((double)sinceLastSeen) / 3600.0) + randomizer);
        
        // Fast reconnect for one hour after last seen
        if (sinceLastSeen < 60 * 60)
            delay = 10 * 60;
        
        // Limit retry frequency
        if (sinceLastTry < delay)
            continue;
        
        // If we have IRC, we'll be notified when they first come online,
        // and again every 24 hours by the refresh broadcast.
        //        if (vNodes.size() >= 2 && sinceLastSeen > 24 * 60 * 60)
        //  continue;
        
        // Only try the old stuff if we don't have enough connections
        //if (vNodes.size() >= 8 && sinceLastSeen > 24 * 60 * 60)
        //    continue;
        
        if (start_time > 0 && sinceLastSeen > 24 * 60 * 60)
            continue;
        
        // If multiple addresses are ready, prioritize by time since
        // last seen and time since last tried.
        int64_t score = min(sinceLastTry, (int64_t)24 * 60 * 60) - sinceLastSeen - randomizer;
        if (score > best) {
            best = score;
            candidate = ep;
        }
    }
    return candidate;
 */
}
Example #30
0
int main() {
	const bool debug = false;
	int i, j, k,cs=1;
	while(scanf("%d", &n),n) {

		x.clear();y.clear();

		for(i = 0; i < n; i++) {
			b[i].init();
			x.insert(b[i].x1);
			x.insert(b[i].x2);
			y.insert(b[i].y1);
			y.insert(b[i].y2);
		}
		hx.clear();
		hy.clear();

		//把地图扩大二倍后,矩阵内部就可以被填充,矩阵边界就可以走了

		//对x离散化
		for(si = x.begin(), mx = 2; si != x.end(); hx[*si] = mx, hhx[mx] = *si, si++,mx+=2) ;


		//对y离散化
		for(si = y.begin(), my = 2; si != y.end(); hy[*si] = my, hhy[my] = *si, si++,my+=2);


		for(i = 0; i < mx; ++i){
			fill(m[i], m[i] + my, 0);
		}

		//填充矩阵,填充为1
		for(i = 0; i < n; i++) {
			int xuper = hx[b[i].x2];
			int yuper = hy[b[i].y2];
			//填充上下边界
			for(j = hx[b[i].x1]; j <= xuper; j++){
				if(m[j][hy[b[i].y1]]==0)m[j][hy[b[i].y1]]=1;
				if(m[j][hy[b[i].y2]]==0)m[j][hy[b[i].y2]]=1;
			}
			//填充左右边界
			for(k = hy[b[i].y1]; k <= yuper; k++){
				if(m[hx[b[i].x1]][k]==0)m[hx[b[i].x1]][k]=1;
				if(m[hx[b[i].x2]][k]==0)m[hx[b[i].x2]][k]=1;
			}
			//填充矩阵内部
			for(j = hx[b[i].x1] + 1; j < xuper; j++) {
				for(k = hy[b[i].y1] + 1; k < yuper; k++) {
					m[j][k]=2;
				}
			}
		}




		if(debug) {
			puts("---- stp ----");
			for(i = 0; i < mx; i++) {
				for(j = 0; j < my; j++) {
					printf(" %2d",m[i][j]);
				}
				puts("");
			}
			puts("---- stp ----\n\n");
		}

		double ans = 0;
		for(i=3;i<mx;i+=2){
			for(j=3;j<my;j+=2){
				if(m[i][j]==2){
					ans += get(i,j);
				}
			}
		}
		printf("Test case #%d\nTotal explored area: 180.00 %.2f\n",cs++,ans);


	}
	return 0;
}