Example #1
0
//#define CMD_IDENT    "IDENT"   // IDENT <num-robots> [ <robot_id> <name>
// <type> <num-provides> <provides>
int client_ident( char *msgbuf, robot *myrobot)
{
	string msg = CMD_IDENT;
	stringstream convert;
	unsigned char len;

	//cout << "In IDENT" << endl;

	pthread_mutex_lock( &robots_mutex );
	msg += " ";
	convert << robots.size() - 1;
	msg += convert.str();
	for (list<robot_p>::iterator i = robots.begin();
			i != robots.end(); ++i)
	{
		if((*i)->get_session_id() != myrobot->get_session_id())
		{
			msg += " ";
			convert.str("");
			convert << (*i)->get_session_id();
			msg += convert.str();
			msg += " ";
			msg += (*i)->get_name();
			msg += " ";
			msg += (*i)->get_type_id();
			msg += " ";
			convert.str("");
			convert << (*i)->get_num_of_provides();
			msg += convert.str();
			vector<string> provides = (*i)->get_provides();
			for (unsigned int i = 0; i < provides.size(); ++i)
			{
				msg += " " + provides[i];
			}
		}
	}
	pthread_mutex_unlock( &robots_mutex );

	len = strlen(msg.c_str());
	//cout << "Size is: " << (int) len << endl;
	//cout << "Msg is: " << msg << endl;
	strncpy(msgbuf, msg.c_str(), len);


	if (( comm->send_msg( myrobot->get_sock(), len, msgbuf ) == -1 ))
	{
		//cout << "**error> reading message in client_handler" << endl;
		push_paint("ERROR", "client_ident: reading message in client_handler",
				   myrobot->get_session_id(), myrobot->get_name());
		return STATE_QUIT;
	}
	else
	{
		if(PluginManager->hooked("OUTGOING"))
		{
			PluginManager->outgoing(msgbuf);
		}
		push_paint("SENT", msgbuf, myrobot->get_session_id(), myrobot->get_name());
	}


	return STATE_IDLE;
}
Example #2
0
void  l_cut(list<  vector<Number> >& l, int size){
    typename list< vector<Number> >::iterator i;
    for (i =l.begin(); i != l.end(); i++) {
        (*i).resize(size);
    }
}
Example #3
0
void Player::handleControl (list<int> &pressing) {
    if(state!=DEAD && state!=LOSE && state!=WIN){
        for(list<int>::iterator it=pressing.begin();it!=pressing.end();it++){
            switch(*(it)){
            case SDLK_DOWN:
                if((y+1)<MAX_Y && map.passThrough(y+1,x)){
                        if(state==0){
                            state = FRONT;
                        }
                    }
                break;
            case SDLK_RIGHT:
                if((x+1)<MAX_X && map.passThrough(y,x+1)){
                        if(state==0){
                            state = RIGHT;
                        }
                    }
                break;
            case SDLK_LEFT:
                if((x-1)>=0 && map.passThrough(y,x-1)){
                        if(state==0){
                            state = LEFT;
                        }
                    }
                break;
            case SDLK_UP:
                if((y-1)>=0 && map.passThrough(y-1,x)){
                        if(state==0){
                            state = BACK;
                        }
                    }
                break;
            case SDLK_b:
                    if(bombNumber>map.bombs.size()){
                        if(map.get(y,x)!=BOMB){
                            map.set(y,x,BOMB);
                            map.bombs.push_back(new Bomb(x,y,bombRange));
                        }
                    }
                break;
            }
        }
        if(map.get(y,x)==FIRE){
            die();
        }
        else if(map.get(y,x)==FIREPOWER){
            map.pickItem(y,x,FIREPOWER);
            bombRange++;
        }
        else if(map.get(y,x)==BOMBPLUS){
            map.pickItem(y,x,BOMBPLUS);
            bombNumber++;
        }
        else if(map.get(y,x)==KEY){
            map.pickItem(y,x,KEY);
            state = WIN;
        }

    }
    if(state!=LOSE){
        if(deadTime){
            deadTime--;
            if(deadTime==0){
                state = STOP;
                frame = 0;
            }
        }else if(imuneTime){
            imuneTime--;
        }
    }
}
// Drawing routine.
void drawScene(void)
{
    // Light position vectors.	
    float lightPos0[] = { 1.0, 1.0, 0.0, 0.0 };
    
    // Material property vectors.
    float matSpec[] = { 0.0, 0.0, 0.0, 1.0 };
    float matShine[] = { 50.0 };
    float matEmission[] = {0.0, 0.0, 0.0, 1.0};
    
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    glDisable(GL_LIGHTING);  
    
    drawGUI();
    
    glColor3f(0.0, 0.0, 0.0);

    for (int i = 0; i < slides.size(); i++)
    {
        glBegin(GL_LINES);
        glVertex3f(slides[i].linex, slides[i].liney, 0.0);
        glVertex3f(slides[i].linex, slides[i].liney - lineLength, 0.0);
        glEnd();

        glPushMatrix();

        if(slides[i].sliding){
                slides[i].y = mousey;
                if(slides[i].y > slides[i].liney){
                    slides[i].y = slides[i].liney;
                }
                if(slides[i].y < slides[i].liney - lineLength){
                    slides[i].y = slides[i].liney - lineLength;
                }
        }

        glBegin(GL_POLYGON);
        glVertex3f(slides[i].linex - lineLength / 2.0, slides[i].y, 0.0);
        glVertex3f(slides[i].linex - lineLength / 2.0, slides[i].y - lineLength / 5.0, 0.0);
        glVertex3f(slides[i].linex + lineLength / 2.0, slides[i].y - lineLength / 5.0, 0.0);
        glVertex3f(slides[i].linex + lineLength / 2.0, slides[i].y, 0.0);
        glEnd();
        glPopMatrix();
    }
    
    displacement.x = ((slides[0].y - slides[0].liney) + lineLength / 2) / 50;
    displacement.y = ((slides[1].y - slides[1].liney) + lineLength / 2) / 50;
    displacement.z = ((slides[2].y - slides[2].liney) + lineLength / 2) / 50;
    
    randDisplacementMin.x = ((slides[3].y - slides[3].liney) + lineLength / 2) / 50;
    randDisplacementMin.y = ((slides[4].y - slides[4].liney) + lineLength / 2) / 50;
    randDisplacementMin.z = ((slides[5].y - slides[5].liney) + lineLength / 2) / 50;
    
    randDisplacementMax.x = ((slides[6].y - slides[6].liney) + lineLength / 2) / 50;
    randDisplacementMax.y = ((slides[7].y - slides[7].liney) + lineLength / 2) / 50;
    randDisplacementMax.z = ((slides[8].y - slides[8].liney) + lineLength / 2) / 50;
    
    redrawTime = (slides[9].liney - slides[9].y) * 100 + 50;
    
    lifeTime = (slides[10].liney - slides[10].y) * 1000 + 100;
    
    particleRadius = (slides[11].liney - slides[11].y) + 1;
    
    if (slides[12].liney - slides[12].y > lineLength / 2)
    {
        randomColor = false;
    }
    else
    {
        randomColor = true;
    }
    
    particleColor[0] = (slides[13].liney - slides[13].y) / 3;
    particleColor[1] = (slides[14].liney - slides[14].y) / 3;
    particleColor[2] = (slides[15].liney - slides[15].y) / 3;
   
    // Light0 is positioned.
    glPushMatrix();
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
    glTranslatef(lightPos0[0], lightPos0[1], lightPos0[2]);
    glPopMatrix();
    
    glEnable(GL_LIGHTING);   
    
    for(list<particle>::iterator i = parts.begin(); i != parts.end(); i++)
    {
        // Material properties of particle.
        if (randomColor)
        {
            glMaterialfv(GL_FRONT, GL_AMBIENT, i->color);
            glMaterialfv(GL_FRONT, GL_DIFFUSE, i->color);
        }
        else
        {
            glMaterialfv(GL_FRONT, GL_AMBIENT, particleColor);
            glMaterialfv(GL_FRONT, GL_DIFFUSE, particleColor);
        }
        glMaterialfv(GL_FRONT, GL_SPECULAR, matSpec);
        glMaterialfv(GL_FRONT, GL_SHININESS, matShine);
        glMaterialfv(GL_FRONT, GL_EMISSION, matEmission);
        glPushMatrix();    
        glTranslatef(i->position.x, i->position.y, i->position.z);
        i->position.x += displacement.x + i->randDisplacement.x;
        i->position.y += displacement.y + i->randDisplacement.y;
        i->position.z += displacement.z + i->randDisplacement.z;
        glutSolidSphere(particleRadius, 20.0, 20.0);
        glPopMatrix();
        if(i->age > lifeTime)
        {
            parts.erase(i);
        }
        else
        {
            i->age++;
        }
    }
    
    glFlush();
    glutPostRedisplay();
}
ExpressionValue SemanticEval::evaluateFCall(RefPortugolAST f, list<ExpressionValue>& args) {
  ExpressionValue v;
  Symbol s;
  try {
    s = stable.getSymbol(SymbolTable::GlobalScope, f->getText());
    v.set(s.type);
  } catch(SymbolTableException& e) {
    stringstream msg;
    msg << "Função \"" << f->getText() << "\" não foi declarada";
    ErrorHandler::self()->add(msg.str(), f->getLine());      
    return v;
  }

  ParameterSig params = s.param;

  if(params.isVariable()) {
    //nao permitir 0 argumentos
    if(args.size() == 0) {
      stringstream msg;
      msg << "Pelo menos um argumento deve ser passado para a função \"" << f->getText() << "\"";
      ErrorHandler::self()->add(msg.str(), f->getLine());      
      return v;
    }
    //nao permitir matrizes como argumentos de funcoes com parametros variaveis
    int count = 1;
    for(list<ExpressionValue>::iterator it = args.begin();
        it != args.end(); ++it) {
      if(!(*it).isPrimitive()) {
        stringstream msg;
        msg << "Argumento " << count;
        msg << " da função \"" << f->getText() << "\" não pode ser matriz/conjunto";
        ErrorHandler::self()->add(msg.str(), f->getLine());      
        return v;
      }
      count++;
    }
    return v;
  }
  
  if(params.symbolList().size() != args.size()) {
    stringstream msg;
    msg << "Número de argumentos diferem do número de parâmetros da função \""
      << f->getText() << "\"";
    ErrorHandler::self()->add(msg.str(), f->getLine());      
    return v;
  }

  list< pair<string,SymbolType> >::iterator pit = params.symbolList().begin();
  list< pair<string,SymbolType> >::iterator pend = params.symbolList().end();

  list<ExpressionValue>::iterator ait = args.begin();
  list<ExpressionValue>::iterator aend = args.end();

  int count = 1;
  while((pit != pend) && (ait != aend)) {
    if(!(*ait).isCompatibleWidth((*pit).second)) {
      stringstream msg;
      msg << "Argumento " << count << " da função \"" << f->getText() << "\" deve ser do tipo \""
        << (*pit).second.toString() << "\"";
      ErrorHandler::self()->add(msg.str(), f->getLine());              
      return v;
    }    
    ++count;
    ++pit;
    ++ait;
  }
  return v;
}
void CompilerDriver_pix::pixNetworkZoneChecks(Firewall *fw,
                                              list<FWObject*> &all_interfaces)
{
    multimap<string, FWObject*> netzone_objects;
    Helper helper(NULL);

    for (std::list<FWObject*>::iterator i=all_interfaces.begin(); i!=all_interfaces.end(); ++i)
    {
        Interface *iface = dynamic_cast<Interface*>(*i);
        assert(iface);

        if (iface->getOptionsObject()->getBool("cluster_interface")) continue;
        if (iface->isDedicatedFailover()) continue;
        if (iface->isUnprotected()) continue;


        /*
         * in PIX, we need network zones to be defined for all
         * interfaces
         */
        string netzone_id = iface->getStr("network_zone");
        if (netzone_id=="")
        {
            QString err("Network zone definition is missing for interface '%1' (%2)");
            abort(fw, NULL, NULL,
                  err.arg(iface->getName().c_str())
                  .arg(iface->getLabel().c_str()).toStdString());
            throw FatalErrorInSingleRuleCompileMode();
        }

        FWObject *netzone = objdb->findInIndex(
            FWObjectDatabase::getIntId(netzone_id));
        if (netzone==NULL) 
        {
            QString err("Network zone points at nonexisting object for "
                        "interface '%1' (%2)");
            abort(fw, NULL, NULL,
                  err.arg(iface->getName().c_str())
                  .arg(iface->getLabel().c_str()).toStdString());
            throw FatalErrorInSingleRuleCompileMode();
        }
/*
 * netzone may be a group, in which case we need to expand it
 * (recursively). 
 * 
 * 1. We create new temporary object (type Group).
 *
 * 2. put it in the database somewhere
 *
 * 3. add all objects that belong to the network zone to this
 * group. We add objects directly, not as a reference.
 *
 * 4. finally replace reference to the old network zone object in the
 * interface with reference to this new group.
 *
 * 5. we store ID of the original network zone object 
 *    using iface->setStr("orig_netzone_id")
 *
 * This ensures netzones do not contain other groups and do not
 * require any recursive expanding anymore. Since objects were added
 * to netzones directly, we do not need to bother with dereferencing,
 * too.
 */
        list<FWObject*> ol;
        helper.expand_group_recursive(netzone, ol);

        FWObject *nz = objdb->createObjectGroup();
        assert(nz!=NULL);
        nz->setName("netzone_" + iface->getLabel());
        objdb->add(nz);

        for (list<FWObject*>::iterator j=ol.begin(); j!=ol.end(); ++j)
        {
            Address *addr = Address::cast(*j);
            if (addr == NULL || addr->getAddressPtr() == NULL)
            {
                QString err("Network zone of interface '%1' uses object '%2' "
                            "that is not an address");
                abort(fw, NULL, NULL,
                      err.arg(iface->getLabel().c_str())
                      .arg((*j)->getName().c_str()).toStdString());
                throw FatalErrorInSingleRuleCompileMode();
            }

/*
  Commented out for SF bug 3213019

  currently we do not support ipv6 with PIX/ASA and FWSM. If user
  creates a group to be used as network zone object and places ipv6
  address in it, this address should be ignored while compiling the
  policy but this should not be an error. Compiler uses network zone
  group to do various address matching operations when it tries to
  determine an interface for a rule where user did not specify
  one. Since we never (should) have ipv6 in policy and nat rules,
  compiler is not going to have anything to compare to ipv6 address in
  the network zone even if there is one and this ipv6 address is going
  to be ignored.


            if (addr->getAddressPtr()->isV6())
            {
                QString err("Network zone of interface '%1' uses object '%2' "
                            "that is IPv6 address");
                abort(fw, NULL, NULL,
                      err.arg(iface->getLabel().c_str())
                      .arg((*j)->getName().c_str()).toStdString());
                throw FatalErrorInSingleRuleCompileMode();
            }
*/
            netzone_objects.insert(
                pair<string,FWObject*>(iface->getLabel(),*j));
            nz->addRef(*j);
        }
        iface->setStr("orig_netzone_id", netzone_id );
        iface->setStr("network_zone",
                      FWObjectDatabase::getStringId(nz->getId()) );
    }


/*
 * the same object (network or host) can not belong to network zones
 * of two different interfaces. Map netzone_objects holds pairs
 * interface_id/object. We just make sure the same object does not
 * appear in two pairs with different interfaces.
 */
    multimap<string,FWObject*>::iterator k;
    for (k=netzone_objects.begin(); k!=netzone_objects.end(); ++k)
    {
        multimap<string,FWObject*>::iterator l;
        l=k;
        ++l;
        for ( ; l!=netzone_objects.end(); ++l)
        {
            if ( l->second->getId() == k->second->getId() )
            {
                if (k->first==l->first)
                {
                    QString err("Object %1 is used more than once in network "
                                "zone of interface '%2'");
                    abort(fw, NULL, NULL,
                          err.arg(l->second->getName().c_str())
                          .arg(k->first.c_str()).toStdString());
                    throw FatalErrorInSingleRuleCompileMode();
                } else
                {
                    QString err("Object %1 is used in network zones of "
                                "interfaces '%2' and '%3'");
                    abort(fw, NULL, NULL,
                          err.arg(l->second->getName().c_str())
                          .arg(k->first.c_str())
                          .arg(l->first.c_str()).toStdString());
                    throw FatalErrorInSingleRuleCompileMode();
                }
            }
        }
    }


}
template<class T> void print(list<T>& a)
{
	typename list<T>::iterator it; //模板函数处理类中类时,需要加typename关键字;
	for (it = a.begin(); it != a.end(); it++)
		cout << *it << endl;
}
Example #8
0
void checkOpen(list<openEntry> &openLedger, list<profitEntry> &profitLedger, const int ID, int &openPosition)
{
	if (openAvg == 0)
	{
		for (list<openEntry>::iterator iter = openLedger.begin(); iter != openLedger.end(); iter++)
		{
			// Short
			if (openPosition < 0)
			{
				if (barsInPtr[ID + 1 + shiftOpen] <= iter->profitPrice)
				{
					// Open satisfies profit threshold
					moveProfitLedger(profitLedger, ID, iter->qtyOpen, barsInPtr[ID + 1 + shiftOpen]);
					openLedger.erase(iter);
					// Update openPosition
					if(openLedger.empty())
					{
						openPosition = 0;
						// We have deleted the last openLedger entry
						// This protects against the iterator losing reference
						break;
					}
					else
					{
						openPosition = sumQty(openLedger);
					}
				}
			}
			// Long
			else
			{
				if (barsInPtr[ID + 1 + shiftOpen] >= iter->profitPrice)
				{
					// Open satisfies profit threshold
					moveProfitLedger(profitLedger, ID, iter->qtyOpen, barsInPtr[ID + 1 + shiftOpen]);
					openLedger.erase(iter);
					// Update openPosition
					if(openLedger.empty())
					{
						openPosition = 0;
						// We have deleted the last openLedger entry
						// This protects against the iterator losing reference
						break;
					}
					else
					{
						openPosition = sumQty(openLedger);
					}
				}
			}
		}
	}
	else
	{
		double profitPrice = getAvgPftPrice(openLedger);

		if (openPosition < 0)
		{
			if (barsInPtr[ID + 1 + shiftOpen] <= profitPrice)
			{
				// Open satisfies profit threshold
				while (!openLedger.empty())
				{
					moveProfitLedger(profitLedger, openLedger.front().sigIndex, openLedger.front().qtyOpen, barsInPtr[ID + 1 + shiftOpen]);
					profitLedger.pop_front();
				}
				openPosition = 0;
			}
		}
		else
		{
			if (barsInPtr[ID + 1 + shiftOpen] >= profitPrice)
			{
				// Open satisfies profit threshold
				while (!openLedger.empty())
				{
					moveProfitLedger(profitLedger, openLedger.front().sigIndex, openLedger.front().qtyOpen, barsInPtr[ID + 1 + shiftOpen]);
					profitLedger.pop_front();
				}
			}
			openPosition = 0;
		}
	}
};
Example #9
0
list<string>::iterator range_archi(list<string>::iterator i,tree<string>& tr, tree<string>::iterator i_archi, list<string> liste)
{
    
    string lexem;
    lexem=*i;
    list<string>::iterator j;
    tree<string>::iterator i_nom_archi;
    tree<string>::iterator i_process;
    tree<string>::iterator nom_entity;
    tree<string>::iterator loc;
    tree<string>::iterator i_declaration;
    tree<string>::iterator i_type_declaration;
    tree<string>::iterator i_nom_signal;
    tree<string>::iterator i_range_instructions_concurentes;
    tree<string>::iterator i_range_instructions_sequentielles;
    
    i++;
    
    i_nom_archi=tr.append_child(i_archi,*i);
    i++;
    if(*i=="of")
    {
        i++;
        
        loc=find(tr.begin(), tr.end(), "entity" );
        loc++;
        if (*loc==*i)
        {
        nom_entity=tr.append_child(i_nom_archi,*i);
        }
        else
        {
            cout << "l'architecture "<< *i <<" ne correspond à aucune entity" << endl;
        }
        
        i++;
        if(*i=="is")
        {
            i++;
                    if(*i !="begin")
                    {
                        i_declaration=tr.append_child(i_nom_archi,"declaration");
                        i_type_declaration=tr.append_child(i_declaration,*i);
                        if(*i=="signal" )
                        {
                            j=i;
                            if(i!=liste.end())
                            {
                                j++;
                            }
                            while(*i=="signal")
                            {
                                i++;
                                j=i;
                                if(i!=liste.end())
                                {
                                    j++;
                                }
                                if(*j==":")
                                {
                                    i_nom_signal=tr.append_child(i_type_declaration,*i);                                
                                    i++;                                
                                    i=range_signal(i,tr,i_nom_signal);
                                    if(*i==";")
                                    {
                                       i++;
                                    }
                                    else
                                    {
                                        cout<<"erreur architecture : manque ';' dans la declaration"<<endl;
                                        return i;
                                    }
                                }
                                else if (*j==",")
                                {                                    
                                    i=range_multi_signaux(i,tr,i_nom_signal,i_type_declaration, liste); //retourne le point virgule de la ligne sur laquelle il est
                                    i++;
                                }
                            } 
                        }
                        
                        
                    }
            //cout <<"ici range archi"<<*i<< endl;
            //cout << *i<< endl;
            
                    if(*i=="begin")
                    {
                        i++;
                        j=i;
                        if(i!=liste.end())
                        {
                            j++;
                        }
                        //cout<<"i vaut: " << *i << endl <<"j vaut: "<<*j <<endl;
                        //cout<<"ici debut begin"<<endl;
                        
                        
                        while((*i!="end") && (*j!=*i_nom_archi))
                        //while(*j!=*i_nom_archi)    
                        {
                            if(*i != "process")
                            {
                                loc=find(tr.begin(), tr.end(), "instructions_concurentes" );                                
                                if (*loc!="instructions_concurentes")
                                {                                
                                    i_range_instructions_concurentes=tr.append_child(i_nom_archi,"instructions_concurentes");
                                }                                
                                    i=range_instructions_concurentes(i,tr,i_range_instructions_concurentes,*i_nom_archi,liste);                                
                            }
                            else
                            {
                               // cout<< " vue process i vaut : "<< *i << endl;
                                i_process=tr.append_child(i_nom_archi,"process");
                                i=range_instrcutions_sequentielles(i,tr,i_process,liste);
                                
                            }
                         //i++;
                         j=i;
                         if(i!=liste.end())
                         {
                             j++;
                         }
                        // cout<<"i vaut: " << *i << endl <<"j vaut: "<<*j <<endl;
                        }
                       
                        //*/
                    }
                             
                    else
                    {
                        cout<<"erreur architecture : manque 'begin'"<<endl;
                        return i;                            
                    }
                    
        }
        else
        {
            cout<<"erreur architecture : manque 'is'"<<endl;
            return i;
        }
    }   
    else
    {
       cout<<"erreur architecture : manque 'of'"<<endl;
       return i;
    }
    
    return i;
}
Example #10
0
void ViewParser::tag_start(const QString &tag, const list<QString> &attrs)
{
    // the tag that will be actually written out
    QString oTag = tag;

    if (m_bInHead)
        return;

    QString style;

    if (tag == "img"){
        QString src;
        for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); ++it){
            QString name = (*it).lower();
            ++it;
            QString value = *it;
            if (name == "src"){
                src = value;
                break;
            }
        }
        if (src.left(10) == "icon:smile"){
            bool bOK;
            unsigned nSmile = src.mid(10).toUInt(&bOK, 16);
            if (bOK){
                const smile *s = smiles(nSmile);
                if (s == NULL)
                    return;
                if (*s->exp == 0){
                    res += quoteString(s->paste);
                    return;
                }
            }
        }
    }else if (tag == "a"){
        m_bInLink = true;
    }else if (tag == "html"){ // we display as a part of a larger document
        return;
    }else if (tag == "head"){
        m_bInHead = 1;
        return;
    }else if (tag == "body"){ // we display as a part of a larger document
        oTag = "span";
    }
    QString tagText;
    tagText += "<";
    tagText += oTag;
    for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); ++it){
        QString name = (*it).lower();
        ++it;
        QString value = *it;

        // Handling for attributes of specific tags.
        if (tag == "body"){
            if (name == "bgcolor"){
                style += "background-color:" + value + ";";
                continue;
            }
        }else if (tag == "font"){
            if (name == "color" && m_bIgnoreColors)
                continue;
        }

        // Handle for generic attributes.
        if (name == "style"){
            style += value;
            continue;
        }

        tagText += " ";
        tagText += name;
        if (!value.isEmpty()){
            tagText += "=\"";
            tagText += value;
            tagText += "\"";
        }
    }

    // Quite crude but working CSS to remove color styling.
    // It won't filter out colors as part of 'background', but life's tough.
    // (If it's any comfort, Qt probably won't display it either.)
    if (!style.isEmpty()){
        if (m_bIgnoreColors){
            list<QString> opt = parseStyle(style);
            list<QString> new_opt;
            for (list<QString>::iterator it = opt.begin(); it != opt.end(); ++it){
                QString name = *it;
                it++;
                if (it == opt.end())
                    break;
                QString value = *it;
                if ((name == "color") ||
                        (name == "background-color") ||
                        (name == "font-size") ||
                        (name == "font-style") ||
                        (name == "font-weight") ||
                        (name == "font-family"))
                    continue;
                new_opt.push_back(name);
                new_opt.push_back(value);
            }
            style = makeStyle(new_opt);
        }
        if (!style.isEmpty())
            tagText += " style=\"" + style + "\"";
    }
    tagText += ">";
    res += tagText;
}
Example #11
0
// Compute block size from block count or vice versa depending on which was
// specified on the command line
bool Par2Creator::ComputeBlockSizeAndBlockCount(const list<CommandLine::ExtraFile> &extrafiles)
{
  // Determine blocksize from sourceblockcount or vice-versa
  if (blocksize > 0)
  {
    u64 count = 0;

    for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++)
    {
      count += (i->FileSize() + blocksize-1) / blocksize;
    }

    if (count > 32768)
    {
      cerr << "Block size is too small. It would require " << count << "blocks." << endl;
      return false;
    }

    sourceblockcount = (u32)count;
  }
  else if (sourceblockcount > 0)
  {
    if (sourceblockcount < extrafiles.size())
    {
      // The block count cannot be less that the number of files.

      cerr << "Block count is too small." << endl;
      return false;
    }
    else if (sourceblockcount == extrafiles.size())
    {
      // If the block count is the same as the number of files, then the block
      // size is the size of the largest file (rounded up to a multiple of 4).

      u64 largestsourcesize = 0;
      for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++)
      {
        if (largestsourcesize < i->FileSize())
        {
          largestsourcesize = i->FileSize();
        }
      }

      blocksize = (largestsourcesize + 3) & ~3;
    }
    else
    {
      u64 totalsize = 0;
      for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++)
      {
        totalsize += (i->FileSize() + 3) / 4;
      }

      if (sourceblockcount > totalsize)
      {
        sourceblockcount = (u32)totalsize;
        blocksize = 4;
      }
      else
      {
        // Absolute lower bound and upper bound on the source block size that will
        // result in the requested source block count.
        u64 lowerBound = totalsize / sourceblockcount;
        u64 upperBound = (totalsize + sourceblockcount - extrafiles.size() - 1) / (sourceblockcount - extrafiles.size());

        u64 bestsize = lowerBound;
        u64 bestdistance = 1000000;
        u64 bestcount = 0;

        u64 count;
        u64 size;

        // Work out how many blocks you get for the lower bound block size
        {
          size = lowerBound;

          count = 0;
          for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++)
          {
            count += ((i->FileSize()+3)/4 + size-1) / size;
          }

          if (bestdistance > (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count))
          {
            bestdistance = (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count);
            bestcount = count;
            bestsize = size;
          }
        }

        // Work out how many blocks you get for the upper bound block size
        {
          size = upperBound;

          count = 0;
          for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++)
          {
            count += ((i->FileSize()+3)/4 + size-1) / size;
          }

          if (bestdistance > (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count))
          {
            bestdistance = (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count);
            bestcount = count;
            bestsize = size;
          }
        }

        // Use binary search to find best block size
        while (lowerBound+1 < upperBound)
        {
          size = (lowerBound + upperBound)/2;

          count = 0;
          for (ExtraFileIterator i=extrafiles.begin(); i!=extrafiles.end(); i++)
          {
            count += ((i->FileSize()+3)/4 + size-1) / size;
          }

          if (bestdistance > (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count))
          {
            bestdistance = (count>sourceblockcount ? count-sourceblockcount : sourceblockcount-count);
            bestcount = count;
            bestsize = size;
          }

          if (count < sourceblockcount)
          {
            upperBound = size;
          }
          else if (count > sourceblockcount)
          {
            lowerBound = size;
          }
          else
          {
            upperBound = size;
          }
        }

        size = bestsize;
        count = bestcount;

        if (count > 32768)
        {
          cerr << "Error calculating block size." << endl;
          return false;
        }

        sourceblockcount = (u32)count;
        blocksize = size*4;
      }
    }
  }

  return true;
}
Example #12
0
VOID PrintUntouchedRanges(SEC sec)
{
    // Make a bool vector big enough to describe the whole section, 1 bool per byte
    vector<bool> touched(SEC_Size(sec));

    // Put the rtn's that are touched in a set
    set<RTN> rtnSet;

    // Mark the ranges for bbls that have been executed
    for (list<const BBLSTATS*>::const_iterator bi = statsList.begin(); bi != statsList.end(); bi++)
    {
        const BBLSTATS * stats = *bi;
        
        // Is this bbl contained in the section?
        if (stats->_start < SEC_Address(sec) || stats->_start >= SEC_Address(sec) + SEC_Size(sec))
            continue;
        
        // Is the bbl executed?
        if (!stats->_executed)
            continue;
        
        RTN rtn = RTN_FindByAddress(stats->_start);
        if (RTN_Valid(rtn))
            rtnSet.insert(rtn);
        
        // Mark all the bytes of the bbl as executed
        for (ADDRINT i = stats->_start - SEC_Address(sec); i < stats->_start + stats->_size - SEC_Address(sec); i++)
        {
            ASSERTX(i < SEC_Size(sec));
            
            touched[i] = true;
        }
    }

    // Print the routines that are not touched
    out << "    Routines that are not executed" << endl;
    for (RTN rtn = SEC_RtnHead(sec); RTN_Valid(rtn); rtn = RTN_Next(rtn))
    {
        if (rtnSet.find(rtn) == rtnSet.end())
        {
            out << "      " << RTN_Name(rtn) << endl;
        }
    }
    
    // Print the ranges of untouched addresses
    out << "    Code ranges that are not executed" << endl;
    string rtnName = "";
    for (UINT32 i = 0; i < SEC_Size(sec);)
    {
        // Find the first not touched address
        while(touched[i])
        {
            i++;
            
            if (i == SEC_Size(sec))
                return;
        }
        UINT32 start = i;
        
        // Find the first touched address
        while(!touched[i] && i < SEC_Size(sec)) i++;

        ADDRINT startAddress = SEC_Address(sec) + start;

        // Print the rtn name, if it has changed
        IMG img = IMG_FindByAddress(startAddress);
        string imgName = (IMG_Valid(img) ? IMG_Name(img) : "InvalidImg");
        RTN rtn = RTN_FindByAddress(startAddress);
        string newName = (RTN_Valid(rtn) ? RTN_Name(rtn) : "InvalidRtn");
        if (rtnName != newName)
        {
            out << " Image: " << imgName <<  "  Rtn: " << newName << endl;
            rtnName = newName;
        }

        out << "        " << SEC_Address(sec) + start << ":" << SEC_Address(sec) + i - 1 << endl;
    }
}
Example #13
0
void ODESimulator::DetectCollisions()
{
  dJointGroupEmpty(contactGroupID);
  //clear feedback structure
  for(map<pair<ODEObjectID,ODEObjectID>,ODEContactList>::iterator i=contactList.begin();i!=contactList.end();i++) {
    i->second.points.clear();
    i->second.forces.clear();
    i->second.feedbackIndices.clear();
  }
  gContacts.clear();

  pair<ODEObjectID,ODEObjectID> cindex;
  int jcount=0;
  if(settings.rigidObjectCollisions) {
    //call the collision routine between objects and the world
    dSpaceCollide(envSpaceID,(void*)this,collisionCallback);

    for(list<ODEContactResult>::iterator j=gContacts.begin();j!=gContacts.end();j++,jcount++) {
      //// int is not necessarily big enough, use intptr_t
      //int o1 = (int)dGeomGetData(j->o1);
      //int o2 = (int)dGeomGetData(j->o2);
      intptr_t o1 = (intptr_t)dGeomGetData(j->o1);
      intptr_t o2 = (intptr_t)dGeomGetData(j->o2);
      if(o1 < 0) {  //it's an environment
	cindex.first = ODEObjectID(0,(-o1-1));
      }
      else {
	cindex.first = ODEObjectID(2,o1);
      }
      if(o2 < 0) {  //it's an environment
	cindex.second = ODEObjectID(0,(-o2-1));
      }
      else {
	cindex.second = ODEObjectID(2,o2);
      }
      if(o1 < 0 && o2 < 0) {
	fprintf(stderr,"Warning, detecting terrain-terrain collisions?\n");
      }
      else {
	j->feedback.resize(j->contacts.size());
	SetupContactResponse(cindex.first,cindex.second,jcount,*j);
      }
    }
  }

  //do robot-environment collisions
  for(size_t i=0;i<robots.size();i++) {
    cindex.first = ODEObjectID(1,i);

    //call the collision routine between the robot and the world
    list<ODEContactResult>::iterator gContactStart = --gContacts.end();
    dSpaceCollide2((dxGeom *)robots[i]->space(),(dxGeom *)envSpaceID,(void*)this,collisionCallback);
    ++gContactStart;
    ProcessContacts(gContactStart,gContacts.end(),settings);

    //setup the contact "joints" and contactLists
    for(list<ODEContactResult>::iterator j=gContactStart;j!=gContacts.end();j++,jcount++) {
      bool isBodyo1 = false, isBodyo2 = false;
      for(size_t k=0;k<robots[i]->robot.links.size();k++) {
	if(robots[i]->triMesh(k) && j->o1 == robots[i]->geom(k)) isBodyo1=true;
	if(robots[i]->triMesh(k) && j->o2 == robots[i]->geom(k)) isBodyo2=true;
      }
      intptr_t body,obj;
      if(isBodyo2) {
	printf("Warning, ODE collision result lists bodies in reverse order\n");
	Assert(!isBodyo1);
	body = (intptr_t)dGeomGetData(j->o2);
	obj = (intptr_t)dGeomGetData(j->o1);
      }
      else {
	Assert(!isBodyo2);
	Assert(isBodyo1);
	body = (intptr_t)dGeomGetData(j->o1);
	obj = (intptr_t)dGeomGetData(j->o2);
      }
      //printf("Collision between body %d and obj %d\n",body,obj);
      Assert(body >= 0 && body < (int)robots[i]->robot.links.size());
      Assert(obj >= -(int)envs.size() && obj < (int)objects.size());
      if(robots[i]->robot.parents[body] == -1 && obj < 0) { //fixed links
	fprintf(stderr,"Warning, colliding a fixed link and the terrain\n");
	continue;
      }
      cindex.first.bodyIndex = body;
      if(obj < 0) {  //it's an environment
	cindex.second = ODEObjectID(0,(-obj-1));
      }
      else {
	cindex.second = ODEObjectID(2,obj);
      }
      SetupContactResponse(cindex.first,cindex.second,jcount,*j);
    }

    if(settings.robotSelfCollisions) {
      robots[i]->EnableSelfCollisions(true);

      cindex.second = ODEObjectID(1,i);
      list<ODEContactResult>::iterator gContactStart = --gContacts.end();
      //call the self collision routine for the robot
      dSpaceCollide(robots[i]->space(),(void*)robots[i],selfCollisionCallback);
      ++gContactStart;
      
      ProcessContacts(gContactStart,gContacts.end(),settings);

      //setup the contact "joints" and contactLists
      for(list<ODEContactResult>::iterator j=gContactStart;j!=gContacts.end();j++,jcount++) {
	intptr_t body1 = (intptr_t)dGeomGetData(j->o1);
	intptr_t body2 = (intptr_t)dGeomGetData(j->o2);
	//printf("Collision between body %d and body %d\n",body1,body2);
	Assert(body1 >= 0 && body1 < (int)robots[i]->robot.links.size());
	Assert(body2 >= 0 && body2 < (int)robots[i]->robot.links.size());
	cindex.first.bodyIndex = body1;
	cindex.second.bodyIndex = body2;
	SetupContactResponse(cindex.first,cindex.second,jcount,*j);
      }
    }

    if(settings.robotRobotCollisions) {    
      for(size_t k=i+1;k<robots.size();k++) {
	cindex.second = ODEObjectID(1,k);
	list<ODEContactResult>::iterator gContactStart = --gContacts.end();
	dSpaceCollide2((dxGeom *)robots[i]->space(),(dxGeom *)robots[k]->space(),(void*)this,collisionCallback);
	++gContactStart;
	ProcessContacts(gContactStart,gContacts.end(),settings);

	//setup the contact "joints" and contactLists
	for(list<ODEContactResult>::iterator j=gContactStart;j!=gContacts.end();j++,jcount++) {
	  intptr_t body1 = (intptr_t)dGeomGetData(j->o1);
	  intptr_t body2 = (intptr_t)dGeomGetData(j->o2);
	  //printf("Collision between robot %d and robot %d\n",i,k);
	  Assert(body1 >= 0 && body1 < (int)robots[i]->robot.links.size());
	  Assert(body2 >= 0 && body2 < (int)robots[k]->robot.links.size());
	  cindex.first.bodyIndex = body1;
	  cindex.second.bodyIndex = body2;
	  SetupContactResponse(cindex.first,cindex.second,jcount,*j);
	}
      }
    }
  }
}
Example #14
0
int client_send_pose( char *msgbuf, robot *myrobot)
{
	string p(msgbuf);
	stringstream istream(p);
	string command;
	long session_id;
	ostringstream oss;
	pose *temp = 0;
	unsigned char len = 0;

	//cout << "Read global ask pose command: " << p << endl;

	istream >> command >> session_id;

	oss << "POSE";
	oss << " ";

	list<robot_p>::iterator i;
	if(session_id < 0)
	{
		ostringstream posestream;
		int num_poses = 0;
		for (i = robots.begin(); i != robots.end(); ++i)
		{
			if ((*i)->get_type_id() != "gui")
			{
				num_poses++;
				posestream << " ";
				session_id = (*i)->get_session_id();
				posestream << session_id;
				posestream << " ";
				if ((temp = (*i)->get_pose()))
				{
					posestream << temp->get_x() << " "
							   << temp->get_y() << " "
							   << temp->get_theta() << " "
							   << temp->get_confidence();
				}
				else
				{
					posestream << " 0 0 0 0";
				}
			}
		}
		oss << num_poses << posestream.str();
	}
	else if (find_robot(session_id, i) &&
			 ((*i)->get_type_id() != "gui"))
	{
		oss << "1";
		oss << " ";
		session_id = (*i)->get_session_id();
		oss << session_id;
		oss << " ";
		if ((temp = (*i)->get_pose()))
		{
			oss << temp->get_x() << " "
				<< temp->get_y() << " "
				<< temp->get_theta() << " "
				<< temp->get_confidence();
		}
		else
		{
			oss << " 0 0 0 0";
		}
	}
	else
	{
		oss << "0";
	}

	//cerr << "**sending> " << oss.str() << endl;
	strncpy( msgbuf, oss.str().c_str(), MAX_BUFFER-1 );
	len = strlen(msgbuf);
	if(comm->send_msg( myrobot->get_sock(), len, msgbuf) == -1)
	{
		//cerr << "**error> failed to send message" << endl;
		push_paint("ERROR", "failed to send message",
				   myrobot->get_session_id(), myrobot->get_name());
		return STATE_QUIT;
	}
	else
	{
		if(PluginManager->hooked("OUTGOING"))
		{
			PluginManager->outgoing(msgbuf);
		}
		push_paint("SENT", msgbuf, myrobot->get_session_id(), myrobot->get_name());
	}

	return STATE_IDLE;
}
Example #15
0
	void drawChildren(const GLMatrix4 &t, const GLMatrix4 &nt) 
	{
		for(i = children.begin(); i != children.end(); i++)
			(*i)->draw(t, nt);
	}
Example #16
0
/**
 * \brief     writes the signals in the given list to the output file
 * \param[in] fileOutput Pointer to the Output file
 * \param[in] m_listSignals List of Signals
 * \param[in] m_ucLength Message length
 * \param[in] m_cDataFormat If 1 dataformat Intel, 0- Motorola
 * \param[in] writeErr If true write error signals also else write onlt correct signals
 * \return    Status code
 *
 * Writes the signals in the given list to the output file.
 */
bool CSignal::WriteSignaltofile(fstream& fileOutput, list<CSignal> &m_listSignals, int m_ucLength, int m_cDataFormat, bool writeErr)
{
    bool bResult = true;
    list<CSignal>::iterator sig;

    for (sig=m_listSignals.begin(); sig!=m_listSignals.end(); ++sig)
    {
        // SIG_NAME,SIG_LENGTH,WHICH_BYTE_IN_MSG,START_BIT,SIG_TYPE,MAX_VAL,MIN_VAL,SIG_DATA_FORMAT,SIG_OFFSET,SIG_FACTOR,SIG_UNIT
        // write signal only if it is valid
        if((sig->m_uiError == CSignal::SIG_EC_NO_ERR) || (sig->m_uiError == CSignal::SIG_EC_OVERFLOW) || writeErr)
        {
            // For signal having motoroal format, the message length could be less
            // then eight byte. so in that case the whichByte needs to be shifted
            // accordingly.
            fileOutput << T_SIG << " " << sig->m_acName.c_str();
            fileOutput << "," << dec << sig->m_ucLength;
            fileOutput << "," << dec << sig->m_ucWhichByte;
            fileOutput << "," << dec << sig->m_ucStartBit;

            switch(sig->m_ucType)
            {
                case CSignal::SIG_TYPE_BOOL:
                case CSignal::SIG_TYPE_UINT:
                    fileOutput << "," << sig->m_ucType;
                    fileOutput << "," << dec << sig->m_MaxValue.uiValue;
                    fileOutput << "," << dec << sig->m_MinValue.uiValue;
                    break;

                case CSignal::SIG_TYPE_INT:
                    fileOutput << "," << sig->m_ucType;
                    fileOutput << "," << dec << sig->m_MaxValue.iValue;
                    fileOutput << "," << dec << sig->m_MinValue.iValue;
                    break;

                case CSignal::SIG_TYPE_FLOAT:
                    fileOutput << "," << sig->m_ucType;
                    fileOutput << "," << sig->m_MaxValue.fValue;
                    fileOutput << "," << sig->m_MinValue.fValue;
                    break;

                case CSignal::SIG_TYPE_DOUBLE:
                    fileOutput << "," << sig->m_ucType;
                    fileOutput << "," << sig->m_MaxValue.dValue;
                    fileOutput << "," << sig->m_MinValue.dValue;
                    break;

                case CSignal::SIG_TYPE_INT64:
                    fileOutput << ",I";
                    fileOutput << "," << dec << sig->m_MaxValue.i64Value;
                    fileOutput << "," << dec << sig->m_MinValue.i64Value;
                    break;

                case CSignal::SIG_TYPE_UINT64:
                    fileOutput << ",U";
                    fileOutput << "," << dec << sig->m_MaxValue.ui64Value;
                    fileOutput << "," << dec << sig->m_MinValue.ui64Value;
                    break;

                default:
                    break;
            }

            fileOutput << "," << sig->m_ucDataFormat;
            fileOutput << "," << sig->m_fOffset;
            fileOutput << "," << sig->m_fScaleFactor;
            fileOutput << "," << sig->m_acUnit.c_str();
            fileOutput << "," << sig->m_acMultiplex.c_str();
            fileOutput << "," << sig->m_rxNode.c_str() << endl;
            CValueDescriptor val;
            val.writeValueDescToFile(fileOutput, sig->m_ucType, sig->m_listValueDescriptor);

            if(sig->m_uiError == CSignal::SIG_EC_OVERFLOW)
            {
                bResult = false;
            }
        }
        else
        {
            bResult = false;
        }
    }

    return bResult;
}
void CompilerDriver_pix::pixSecurityLevelChecks(Firewall *fw,
                                                list<FWObject*> &all_interfaces)
{
    for (std::list<FWObject*>::iterator i=all_interfaces.begin(); i!=all_interfaces.end(); ++i)
    {
        Interface *iface = dynamic_cast<Interface*>(*i);
        assert(iface);

        if (iface->getOptionsObject()->getBool("cluster_interface")) continue;

        if ((iface->getOptionsObject()->getStr("type") == "" ||
             iface->getOptionsObject()->getStr("type") == "ethernet") &&
            iface->getByType(Interface::TYPENAME).size() > 0)
        {
            // Parent vlan interface (i.e. trunk)
            if (!iface->isUnprotected())
            {
                QString err(
                    "Interface %1 has vlan subinterfaces, it can not "
                    "be used for ACL. Marking this interface \"unprotected\" "
                    "to exclude it."
                );
                warning(fw, NULL, NULL,
                        err.arg(iface->getName().c_str())
                        .toStdString());
                iface->setUnprotected(true);
            }
        }

        // Tests for label, security level and network zone make sense
        // only for interfaces that can be used in ACLs or to bind
        // ACLs to.  Unnumbered interfaces can't, so we do not need to
        // run these checks.  One example of unnumbered interface is
        // parent interface for vlan subinterfaces.
        if (iface->isUnnumbered()) continue;
        if (iface->isUnprotected()) continue;

/*
 * there shouldn't be two interfaces with the same security level and
 * same label
 * 
 */
        for (std::list<FWObject*>::iterator j=all_interfaces.begin(); j!=all_interfaces.end(); ++j)
        {
            Interface *iface2 = dynamic_cast<Interface*>(*j);
            assert(iface2);
            if (iface2->isUnnumbered()) continue;
            if (iface2->isUnprotected()) continue;
            if (iface->getId()==iface2->getId()) continue;
            if (iface->getOptionsObject()->getBool("cluster_interface") ||
                iface2->getOptionsObject()->getBool("cluster_interface"))
                continue;

            // see #2351. Security levels do not have to be unique
            // if (iface->getSecurityLevel()==iface2->getSecurityLevel())
            // {
            //     QString err(
            //         "Security level of each interface should be unique, "
            //         "however interfaces %1 (%2) and %3 (%4)"
            //         " have the same security level."
            //     );
            //     abort(fw, NULL, NULL,
            //           err.arg(iface->getName().c_str())
            //           .arg(iface->getLabel().c_str())
            //           .arg(iface2->getName().c_str())
            //           .arg(iface2->getLabel().c_str()).toStdString());
            //     throw FatalErrorInSingleRuleCompileMode();
            // }

            if (iface->getLabel()==iface2->getLabel())
            {
                QString err(
                    "Label of each interface should be unique, "
                    "however interfaces %1 (%2) and %3 (%4)"
                    " have the same."
                );
                abort(fw, NULL, NULL,
                      err.arg(iface->getName().c_str())
                      .arg(iface->getLabel().c_str())
                      .arg(iface2->getName().c_str())
                      .arg(iface2->getLabel().c_str()).toStdString());
                throw FatalErrorInSingleRuleCompileMode();
            }
        }

        // We only do limited checks for dedicated failover
        // interfaces because they are not used in ACLs or
        // anywhere else in configuration, except in "failover"
        // commands.
        if (iface->isDedicatedFailover()) continue;

    }
}
Example #18
0
	void Line2f::CleanOutLine(list<Line2f>& outline, float minDist2)
	{
		Line2f* last = &outline.back();
		bool done = false;
		int idx = 0;
		if (outline.begin() == outline.end())
		  return;
		for(list<Line2f>::iterator pIt = outline.begin(); !done; )
		{
			Vector2f Va = last->vertices.back();
			Vector2f Vb = pIt->vertices.front();

			Vector2f Na = last->src;
			Vector2f Nb = pIt->src;

			float Ao = atan2f(Na.y-Nb.y, Na.x-Nb.x);
			float Aa = atan2f(Va.y-Nb.y, Va.x-Nb.x);
			float Ab = atan2f(Vb.y-Nb.y, Vb.x-Nb.x);

			if( IsAngleInBetween(Aa, Ab, Ao) )
			{
				Vector2f ip0;
				Vector2f ip1;
				float t0;
				float t1;

				if( last->vertices.size() > 1 )
				{
					Vector2f Pa = pIt->src;
					list<Line2f>::iterator pIt2 = pIt;
					GoNext(outline, pIt2);
					Vector2f Pb = pIt2->src;

					while( last->vertices.size() > 1 )
					{
						Vb = *(--(--last->vertices.end()));
						if( linePointDist2D_Segments2(Pa, Pb, Vb) < minDist2 )
						{
							Va = Vb;
							last->vertices.pop_back();
						}
						else
						{
							break;
						}
					}
				}

				if( last->vertices.size() > 1 )
				{
					Vb = *(--(--last->vertices.end()));
					Nb = last->src;
				}
				else
				{
					list<Line2f>::iterator pIt2 = pIt;
					GoPrev(outline, pIt2);
					GoPrev(outline, pIt2);
					Vb = pIt2->vertices.back();
					Nb = pIt2->src;
				}
				// TODO flawed logic here, we wish to extend Va so that the segment Va-Vb is perpendicular to Va-Nb
				float OrigLength = (Nb-Na).length();
				float TransLength = (Vb-Va).length();
				if( OrigLength > TransLength )
				{
					Va = Vb+(Va-Vb)*(OrigLength/TransLength);
				}


				int intersectionPoints = 0;
				while( intersectionPoints == 0)
				{
					Vector2f Pa = pIt->src;
					Na = pIt->vertices.front();
					if( pIt->vertices.size() > 1 )
					{
						pIt->vertices.pop_front();
						Nb = pIt->vertices.front();
		
						list<Line2f>::iterator pIt2 = pIt;
						GoPrev(outline, pIt2);
						Pa = pIt2->src;
					}
					else
					{
						pIt = outline.erase(pIt);
						if( pIt == outline.end() )
						{
							if( outline.size() == 0) return; // this outline shrank to death
							done = true;
							pIt = outline.begin();
						}
						Nb = pIt->vertices.front();
					}
					Vector2f Pb = pIt->src;

					// TODO flawed logic here, we wish to extend Na so that the segment Na-Nb is perpendicular to Na-Pa
					OrigLength = (Pb-Pa).length();
					TransLength = (Nb-Na).length();
					if( OrigLength > TransLength )
					{
						Na = Nb+(Na-Nb)*(OrigLength/TransLength);
					}
					
					intersectionPoints = intersect2D_Segments(Vb, Va, Na, Nb, ip0, ip1, t0, t1);
					switch( intersectionPoints )
					{
					case 0:
						// just loop again.
						break;
					case 1:
						last->vertices.back() = ip0;
						break;
					case 2:
						// this should be impossible, but floating point precision will probably make us end up here.
						assert("If this assertion ever happen, go into the CleanOutLine and remove it. You can safely ignore it and continue!");
						break; 
					}
				}
			}
			last = &(*pIt);
			pIt++;
			done = done || pIt == outline.end();
			idx++;
		}
	}
Example #19
0
retval_t ScimBridgeAgentImpl::run_event_loop ()
{
    scim_bridge_pdebugln (5, "run_event_loop ()");

    while (running) {
        int max_fd = -1;

        fd_set read_set;
        fd_set write_set;
        fd_set error_set;
        FD_ZERO (&read_set);
        FD_ZERO (&write_set);
        FD_ZERO (&error_set);
        for (list<ScimBridgeAgentSocketClient*>::iterator i = clients.begin (); running && i != clients.end ();) {
            ScimBridgeAgentSocketClient *client = *i;

            const scim_bridge_agent_event_type_t triggers = client->get_trigger_events ();
            const int socket_fd = client->get_socket_fd ();
            if (socket_fd < 0) {
                if (triggers & SCIM_BRIDGE_AGENT_EVENT_ERROR && !client->handle_event (SCIM_BRIDGE_AGENT_EVENT_ERROR)) {                        
                    i = clients.erase (i);
                    delete client;
                    continue;
                }
            } else {
                if (socket_fd > max_fd) max_fd = socket_fd;
                if (triggers & SCIM_BRIDGE_AGENT_EVENT_READ) {
                    scim_bridge_pdebugln (1, "FD (%d) is registred as a reading socket", socket_fd);
                    FD_SET (socket_fd, &read_set);
                }
                if (triggers & SCIM_BRIDGE_AGENT_EVENT_WRITE) {
                    FD_SET (socket_fd, &write_set);
                    scim_bridge_pdebugln (1, "FD (%d) is registred as a writing socket", socket_fd);
                }
                if (triggers & SCIM_BRIDGE_AGENT_EVENT_ERROR) {
                    FD_SET (socket_fd, &error_set);
                    scim_bridge_pdebugln (1, "FD (%d) is registred as a error socket", socket_fd);
                }
            }
            ++i;
        }

        scim_bridge_pdebugln (2, "Waiting for an event...");
        const int retval = select (max_fd + 1, &read_set, &write_set, &error_set, NULL);
        if (retval < 0 && errno != EINTR) {
            if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
                continue;
            } else {
                scim_bridge_perrorln ("An exception occurred at selecting the sockets: %s", strerror (errno));
            }
        }

        const bool interrupted = interruption_listener->is_interrupted ();
        interruption_listener->clear_interruption ();
        if (interrupted) scim_bridge_pdebugln (3, "Caught an interruption");

        for (list<ScimBridgeAgentSocketClient*>::iterator i = clients.begin (); i != clients.end ();) {
            ScimBridgeAgentSocketClient *client = *i;

            const int socket_fd = client->get_socket_fd ();
            const scim_bridge_agent_event_type_t triggers = client->get_trigger_events ();

            scim_bridge_agent_event_type_t events = SCIM_BRIDGE_AGENT_EVENT_NONE;

            if (socket_fd >= 0 && FD_ISSET (socket_fd, &read_set) && (triggers & SCIM_BRIDGE_AGENT_EVENT_READ)) {
                if (events == SCIM_BRIDGE_AGENT_EVENT_NONE) {
                    scim_bridge_pdebug (2, "Invoked triggers: READ");
                } else {
                    scim_bridge_pdebug (2, ", READ");
                }
                events |= SCIM_BRIDGE_AGENT_EVENT_READ;
            }
            if (socket_fd >= 0 && FD_ISSET (socket_fd, &write_set) && (triggers & SCIM_BRIDGE_AGENT_EVENT_WRITE)) {
                if (events == SCIM_BRIDGE_AGENT_EVENT_NONE) {
                    scim_bridge_pdebug (2, "Invoked triggers: WRITE");
                } else {
                    scim_bridge_pdebug (2, ", WRITE");
                }
                events |= SCIM_BRIDGE_AGENT_EVENT_WRITE;
            }
            if ((socket_fd < 0 || FD_ISSET (socket_fd, &error_set)) && (triggers & SCIM_BRIDGE_AGENT_EVENT_ERROR)) {
                if (events == SCIM_BRIDGE_AGENT_EVENT_NONE) {
                    scim_bridge_pdebug (2, "Invoked triggers: ERROR");
                } else {
                    scim_bridge_pdebug (2, ", ERROR");
                }
                events |= SCIM_BRIDGE_AGENT_EVENT_ERROR;
            }
            if (interrupted && (triggers & SCIM_BRIDGE_AGENT_EVENT_INTERRUPT)) {
                if (events == SCIM_BRIDGE_AGENT_EVENT_NONE) {
                    scim_bridge_pdebug (2, "Invoked triggers: INTERRUPT");
                } else {
                    scim_bridge_pdebug (2, ", INTERRUPT");
                }
                events |= SCIM_BRIDGE_AGENT_EVENT_INTERRUPT;
            }

            if (events != SCIM_BRIDGE_AGENT_EVENT_NONE) {
                scim_bridge_pdebug (2, "\n");
                if (!client->handle_event (events)) {
                    i = clients.erase (i);
                    delete client;
                    continue;
                }
            }
            ++i;
        }
    }

    return RETVAL_SUCCEEDED;
}
Example #20
0
void RNAFuncs::drawRNAStructure(const string &seq, const string &structure, const string &filename_prefix, const string &structname, const list<pair<Uint,Uint> > &regions, const SquigglePlotOptions &options)
{
  const double base_fontsize=12;

  float *X, *Y,min_X=0,max_X=0,min_Y=0,max_Y=0;
  Uint i;
  short *pair_table;
  int id_PS,id_FIG=0,id;
  int color_black, *colors;
  double xpos,ypos;
  char buf[10];
  string filename;
  double *points;
  int numPoints;

#ifdef HAVE_LIBGD
  int id_PNG=0,id_JPG=0;
#endif

  X = new float[structure.size()];
  Y = new float[structure.size()];
  points=new double[2*structure.size()];
  colors=new int[NUM_COLORS];

  assert(seq.size() == structure.size());

  pair_table = make_pair_table(structure.c_str());
  i = naview_xy_coordinates(pair_table, X, Y);
  if(i!=structure.size())
    cerr << "strange things happening in squigglePlot ..." << endl;
    
  // scale image
  for(i=0;i<structure.size();i++)
    {
      X[i]*=static_cast<float>(options.scale);
      Y[i]*=static_cast<float>(options.scale);
    }  

  // calculate image dimensions
  for(i=0;i<structure.size();i++)
    {
      min_X=min(min_X,X[i]);
      max_X=max(max_X,X[i]);
      min_Y=min(min_Y,Y[i]);
      max_Y=max(max_Y,Y[i]);
    }

  // add a border to image size
  min_X-=10;
  max_X+=10;
  min_Y-=10;
  max_Y+=10;

  //id_PS  = g2_open_PS("ali.ps", g2_A4, g2_PS_port);
  filename=filename_prefix + ".ps";
  id_PS  = g2_open_EPSF((char*)filename.c_str());
  g2_set_coordinate_system(id_PS,-min_X,-min_Y,1,1);

  if(options.generateFIG)
    {
      filename=filename_prefix + ".fig";
      id_FIG=g2_open_FIG((char*)filename.c_str());
      g2_set_coordinate_system(id_FIG,-min_X,-min_Y,1,1);
    }
#ifdef HAVE_LIBGD
  if(options.generatePNG)
    {
      filename=filename_prefix + ".png";
      id_PNG=g2_open_gd((char*)filename.c_str(),(int)(max_X-min_X),(int)(max_Y-min_Y),g2_gd_png);
      g2_set_coordinate_system(id_PNG,-min_X,-min_Y,1,1);
    }
   if(options.generateJPG)
     {
       filename=filename_prefix + ".jpg"; 
       id_JPG=g2_open_gd((char*)filename.c_str(),(int)(max_X-min_X),(int)(max_Y-min_Y),g2_gd_jpeg);
       g2_set_coordinate_system(id_PS,-min_X,-min_Y,1,1);
     }
#endif

  id     = g2_open_vd();
  g2_attach(id,id_PS);

  if(options.generateFIG)
    {
      g2_attach(id,id_FIG);
    }

#ifdef HAVE_LIBGD
  if(options.generatePNG)
    g2_attach(id,id_PNG);
  if(options.generateJPG)
    g2_attach(id,id_JPG);
#endif

  // cout << "min_X: " << min_X <<",max_X: " << max_X << ",min_Y: " << min_Y << "max_Y: " << max_Y << endl; 
  //  g2_set_coordinate_system(id_PS,595/2.0,842/2.0,0.5,0.5);

  // define colors
  if(options.greyColors)
    {
      color_black=g2_ink(id_PS,0,0,0);
      for(i=0;i<NUM_COLORS;i++)
	colors[i]=g2_ink(id_PS,0,0,0);

      if(options.generateFIG)
	{
	  color_black=g2_ink(id_FIG,0,0,0);
	  for(i=0;i<NUM_COLORS;i++)
	    colors[i]=g2_ink(id_FIG,0,0,0);
	}
      
#ifdef HAVE_LIBGD
      if(options.generatePNG)
	{
	  color_black=g2_ink(id_PNG,0,0,0);
	  for(i=0;i<NUM_COLORS;i++)
	    colors[i]=g2_ink(id_PNG,0,0,0);	  
	}

      if(options.generateJPG)
	{
	  color_black=g2_ink(id_JPG,0,0,0);
	  for(i=0;i<NUM_COLORS;i++)
	    colors[i]=g2_ink(id_JPG,0,0,0);	  
	}     
#endif
    }
  else
    {
      color_black=g2_ink(id,0,0,0);
      colors[COLOR_RED]=g2_ink(id_PS,COLOR_DEF_RED);
      colors[COLOR_GREEN]=g2_ink(id_PS,COLOR_DEF_GREEN);
      colors[COLOR_BLUE]=g2_ink(id_PS,COLOR_DEF_BLUE);
      colors[COLOR_YELLOW]=g2_ink(id_PS,COLOR_DEF_YELLOW);
      colors[COLOR_MAGENTA]=g2_ink(id_PS,COLOR_DEF_MAGENTA);
      colors[COLOR_TURKIS]=g2_ink(id_PS,COLOR_DEF_TURKIS);

      if(options.generateFIG)
	{
	  color_black=g2_ink(id_FIG,0,0,0);
	  colors[COLOR_RED]=g2_ink(id_FIG,COLOR_DEF_RED);
	  colors[COLOR_GREEN]=g2_ink(id_FIG,COLOR_DEF_GREEN);
	  colors[COLOR_BLUE]=g2_ink(id_FIG,COLOR_DEF_BLUE);
	  colors[COLOR_YELLOW]=g2_ink(id_FIG,COLOR_DEF_YELLOW);
	  colors[COLOR_MAGENTA]=g2_ink(id_FIG,COLOR_DEF_MAGENTA);
	  colors[COLOR_TURKIS]=g2_ink(id_FIG,COLOR_DEF_TURKIS);
	}
      
#ifdef HAVE_LIBGD
      if(options.generatePNG)
	{
	  color_black=g2_ink(id_PNG,0,0,0);
	  colors[COLOR_RED]=g2_ink(id_PNG,COLOR_DEF_RED);
	  colors[COLOR_GREEN]=g2_ink(id_PNG,COLOR_DEF_GREEN);
	  colors[COLOR_BLUE]=g2_ink(id_PNG,COLOR_DEF_BLUE);
	  colors[COLOR_YELLOW]=g2_ink(id_PNG,COLOR_DEF_YELLOW);
	  colors[COLOR_MAGENTA]=g2_ink(id_PNG,COLOR_DEF_MAGENTA);
	  colors[COLOR_TURKIS]=g2_ink(id_PNG,COLOR_DEF_TURKIS);
	}

      if(options.generateJPG)
	{
	  color_black=g2_ink(id_JPG,0,0,0);
	  colors[COLOR_RED]=g2_ink(id_JPG,COLOR_DEF_RED);
	  colors[COLOR_GREEN]=g2_ink(id_JPG,COLOR_DEF_GREEN);
	  colors[COLOR_BLUE]=g2_ink(id_JPG,COLOR_DEF_BLUE);
	  colors[COLOR_YELLOW]=g2_ink(id_JPG,COLOR_DEF_YELLOW);
	  colors[COLOR_MAGENTA]=g2_ink(id_JPG,COLOR_DEF_MAGENTA);
	  colors[COLOR_TURKIS]=g2_ink(id_JPG,COLOR_DEF_TURKIS);
	}
#endif
    }
  
  for(i=0;i<structure.size();i++)
    {
      // connection to next base
      if(i<structure.size()-1)
	{
	 // if the connected bases are only in one of the structures
	  // use the appropriate color
	  g2_line(id,X[i],Y[i],X[i+1],Y[i+1]);
	  
	  // draw circles at line endpoints
	  g2_filled_circle(id,X[i],Y[i],0.7*options.scale);       // circles are drawn twice, but thats ok ...
	}
    }

  // draw pairings
  // !!! pair_table indexing begins at 1 !!!
  for(i=0;i<structure.size();i++)
    {
	if((unsigned short)pair_table[i+1]>i+1)
	  {	    	    
	    // pairs in both structures
	    g2_line(id,X[i],Y[i],X[pair_table[i+1]-1],Y[pair_table[i+1]-1]);
	  }
    }

  // draw regions
  g2_set_line_width(id,0.4);
  list<pair<Uint,Uint> >::const_iterator it;  
  Uint regionNr=0;

  for(it=regions.begin();it!=regions.end();it++)
    {
      double center_x=0,center_y=0;

      // fill coordinate list
	for(i=0;i < it->second;i++)
	  {
	    points[2*i]=X[it->first+i];
	    points[2*i+1]=Y[it->first+i];

	    center_x+=X[it->first+i];
	    center_y+=Y[it->first+i];
	  }
	numPoints=it->second-1;
	center_x/=numPoints;   // center of gravity
	center_y/=numPoints;
	
	g2_pen(id,colors[regionNr % NUM_COLORS]);
	g2_poly_line(id,numPoints,points);
	sprintf(buf,"%d",regionNr+1);
	g2_string(id,center_x,center_y,buf);   // draw region number

	regionNr++;
    }
  
  // mark 5' end

  g2_pen(id,color_black);
  g2_string(id,X[0]-20,Y[0],"5'");

  g2_set_font_size(id,base_fontsize*options.scale);
  g2_set_line_width(id,0.2);
  
  // draw sequence
  for(i=0;i<structure.size();i++)
    {
     g2_pen(id,color_black); // match 
     xpos=X[i]-(base_fontsize*options.scale)/2;
     ypos=Y[i]-4;
     sprintf(buf,"%c",seq[i]);
     g2_string(id,xpos,ypos,buf);

     /*
     if(!options.hideBaseNumbers)
       {
	 // draw base number
	 if(basenr % options.baseNumInterval == 0)
	   {	 
	     sprintf(buf,"%d",basenr);
	     g2_string(id,xpos-20,ypos,buf);
	   }
	   }*/     
    }

    // draw structure name
    g2_string(id,min_X,max_Y-10,(char*)structname.c_str());
        
    g2_flush(id);
    g2_close(id);

    free(pair_table);
    DELETE(X);
    DELETE(Y);
    DELETE(points);
    DELETE(colors);
}
Example #21
0
vector <Planet> Planet::getPredictions(int t, list<Fleet> fs, int start) 
{
    vector<Planet> predictions;
    Planet p(*this);
    for (list<Fleet>::iterator f = fs.begin(); f != fs.end(); ++f ) {
        if (f->sourcePlanet()->planetID() == this->planetID() && f->turnsRemaining() - start == this->distance(f->destinationPlanet())){
            p.shipsCount_m -= f->shipsCount();
            f = fs.erase(f);
            if(f==fs.end())
                break;
        }
    }
    predictions.push_back(p);

    for(int i(1);i!=t+1;i++){
        if(!p.owner_m->isNeutral()){
            p.shipsCount_m += p.growthRate_m;
        }
        std::map<const Player*,int> participants;
        participants[p.owner_m] = p.shipsCount_m;
    
        for (Fleets::iterator it = incomingFleets_m.begin(); it != incomingFleets_m.end(); ++it ) {
            Fleet* f = *it;
            int tr = f->turnsRemaining();
            if (tr - start == i ) {
                participants[f->owner()] += f->shipsCount();
            }
        }

        for (list<Fleet>::iterator f = fs.begin(); f != fs.end(); ++f ) {
            if (f->destinationPlanet()->planetID() == this->planetID() && f->turnsRemaining() - start == i ) {
                participants[f->owner()] += f->shipsCount();
                f = fs.erase(f);
                if(f == fs.end())
                    break;
            } else if ( f->sourcePlanet()->planetID() == this->planetID() && f->turnsRemaining() - start -i == this->distance(f->destinationPlanet())){
                participants[f->owner()] -= f->shipsCount();
                f = fs.erase(f);
                if(f == fs.end())
                    break;
            }
        }
    
    

        Fleet winner(0, 0);
        Fleet second(0, 0);
        for (std::map<const Player*,int>::iterator f = participants.begin(); f != participants.end(); ++f) {
            if (f->second > second.shipsCount()) {
                if(f->second > winner.shipsCount()) {
                    second = winner;
                    winner = Fleet(f->first, f->second);
                } else {
                    second = Fleet(f->first, f->second);
                }
            }
        }
 
        if (winner.shipsCount() > second.shipsCount()) {
            p.shipsCount_m = winner.shipsCount() - second.shipsCount();
            p.owner_m = winner.owner();
        } else {
            p.shipsCount_m = 0;
        }
        predictions.push_back(p);
    }
    return predictions;
}
Example #22
0
/***************************************************************************
*
* Function:  replayTransactions
*
* Purpose:   Reads the qualifying files and processes the transactions
*	     starting with the first one with an id greater than the last
*	     id handed out before the backup and ending with the last
*	     transaction committed before the stop date.
****************************************************************************/
void ReplayTxnLog::replayTransactions(list<string>& fileNames) {
    list<string>::iterator curFile;
    vector<string> v;
    curFile = fileNames.begin();
    LogEntry logEntry;
    string statement;
    bool done = false;
    bool confirmed = true;
    oam::Oam oam;

    curFile = fileNames.begin();

//	cout << "Searching files for first transaction to process." << endl << endl;

    while (!done && curFile != fileNames.end()) {
        ifstream dataFile(curFile->c_str());
        if(confirmed) {
            displayProgress(*curFile);
        }
        while(!done && getNextCalpontLogEntry(dataFile, logEntry)) {
            if(logEntry.fLogTime >= fStopDate) {
                done = true;
            }
            else if(logEntry.fVersionID > fStartVersionID) {
                if(confirmed) {
                    processStatement(logEntry);
                }
                /*
                				else if(displaySummaryAndConfirm(logEntry)) {
                					confirmed = true;
                					if(!fReportMode) {

                						// Log start message.
                						ostringstream oss;
                						oss << "First transaction ID to be processed is " << logEntry.fVersionID << ".";
                						string msg = oss.str();
                						logging::logEventToDataLog(logging::M0019, msg);

                						// Turn off DML/DDL logging to keep from the statements from
                						// being logged again.
                						#ifdef OAM_AVAILABLE
                						cout << endl << "Turning off DML/DDL logging." << endl << endl;
                						oam.updateLog(oam::MANDISABLEDSTATE, "system", "data");
                						#endif
                					}
                					displayProgress(*curFile);
                					processStatement(logEntry);
                				}
                				else {
                					done = true;
                				}
                */
            }
        }
        dataFile.close();
        curFile++;
    }

    // Turn DML/DDL logging back on.
    /*
    	if(!fReportMode && confirmed) {
    		#ifdef OAM_AVAILABLE
    		cout << endl << "Turning DML/DDL logging back on." << endl << endl;
    		oam.updateLog(oam::ENABLEDSTATE, "system", "data");
    		#endif

    		// Log complete message.
    		ostringstream oss;
    		oss << "Last transaction ID processed was " << fLogEntryLastCommit.fVersionID << ".";
    		string msg = oss.str();
    		logging::logEventToDataLog(logging::M0020, msg);
    	}
    */
}
Example #23
0
ExpressionValue SemanticEval::evaluateLValue(RefPortugolAST id, list<ExpressionValue>& dim) {
/*
  1: lvalue (id) deve ter sido declarado no escopo global ou local
  2: o tipo do lvalue (id) deve ser o mesmo da declaracao (primitivo/dimensoes)
  3: as expressoes das dimensoes devem ser numericas inteiras. [1.2] ou ["aa"] ->erro
*/

  bool islocal;
  Symbol lvalue;
  ExpressionValue ret;

  try {
    lvalue = stable.getSymbol(currentScope, id->getText(), true);
    if(lvalue.scope == SymbolTable::GlobalScope) {
      islocal = false;
    } else {
      islocal = true;
    }
  } catch(SymbolTableException& e) {
    stringstream msg;    
    msg << "Variável \"" << id->getText() << "\" não foi declarada";
    ErrorHandler::self()->add(msg.str(), id->getLine());
    return ret;
  }

  ret.setPrimitiveType(lvalue.type.primitiveType());

  if(lvalue.isFunction) {
    stringstream msg;
    msg << "Função \"" << id->getText() << "\" não pode ser usada como variável";
    ErrorHandler::self()->add(msg.str(), id->getLine());
    return ret;    
  }

  if(lvalue.type.isPrimitive()) {
    ret.set(lvalue.type);
    if(dim.size() > 0) {
      stringstream msg;
      msg << "Variável \"" << id->getText() << "\" não é uma matriz/conjunto";
      ErrorHandler::self()->add(msg.str(), id->getLine());
      return ret;
    } else {
      return ret;
    }
  } else {//matriz/conjunto    

//     ret.setPrimitive(true);
//     ret.setPrimitiveType(lvalue.type.primitiveType());

    //checar expressoes dos subscritos
    list<ExpressionValue>::iterator it;
    for(it = dim.begin(); it != dim.end();++it) {
      if(!(*it).isNumeric(true)) {
        ErrorHandler::self()->add("Subscritos de conjuntos/matrizes devem ser valores numéricos inteiros ou equivalente", id->getLine());
      }
    }

    /* Nota: checar pelas dimensoes impede que 
       se passe matriz como parametros. Checar subscritos apenas 
       em atribuicoes.
    */

    //checar numero de dimensoes usado
    // - So eh permitido matrizes como lvalue sem subscritos, ou com todos os seus subscritos

    if(dim.size() > 0) {
      //matriz com seus subscritos, retorna apenas o tipo primitivo
      ret.setPrimitive(true);

      if(lvalue.type.dimensions().size() != dim.size()) {
        stringstream msg;
        msg << "Matriz/conjunto \"" << id->getText() << "\" possui " << lvalue.type.dimensions().size();
  
        if(dim.size() == 1) {
          msg << " dimensão";
        } else {
          msg << " dimensões";
        }
        msg << " Use " << lvalue.type.dimensions().size() << " subscrito(s)";
        ErrorHandler::self()->add(msg.str(), id->getLine());
      } 
    } else {
      //variavel matriz sem subscritos, retorna tipo matriz
      ret.setPrimitive(true);
      ret.setDimensions(lvalue.type.dimensions());
    }
    return ret;
  }
}
void QueueUserACLInfo::setUserAcls(list<QueueACL> &userAclsList) {
	list<QueueACL>::iterator it = userAclsList.begin();
	for (; it != userAclsList.end(); it++) {
		infoProto.add_useracls((QueueACLProto) *it);
	}
}
Example #25
0
Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
{
  Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
  Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
  Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
  Double estLambda;
  if (eSliceType == I_SLICE)
  {
    estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(Double)m_numberOfPixel, BETA1), bpp); 
  }
  else
  {
    estLambda = alpha * pow( bpp, beta );
  }
  
  Double lastLevelLambda = -1.0;
  Double lastPicLambda   = -1.0;
  Double lastValidLambda = -1.0;
  list<TEncRCPic*>::iterator it;
  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
  {
    if ( (*it)->getFrameLevel() == m_frameLevel )
    {
      lastLevelLambda = (*it)->getPicActualLambda();
    }
    lastPicLambda     = (*it)->getPicActualLambda();

    if ( lastPicLambda > 0.0 )
    {
      lastValidLambda = lastPicLambda;
    }
  }

  if ( lastLevelLambda > 0.0 )
  {
    lastLevelLambda = Clip3( 0.1, 10000.0, lastLevelLambda );
    estLambda = Clip3( lastLevelLambda * pow( 2.0, -3.0/3.0 ), lastLevelLambda * pow( 2.0, 3.0/3.0 ), estLambda );
  }

  if ( lastPicLambda > 0.0 )
  {
    lastPicLambda = Clip3( 0.1, 2000.0, lastPicLambda );
    estLambda = Clip3( lastPicLambda * pow( 2.0, -10.0/3.0 ), lastPicLambda * pow( 2.0, 10.0/3.0 ), estLambda );
  }
  else if ( lastValidLambda > 0.0 )
  {
    lastValidLambda = Clip3( 0.1, 2000.0, lastValidLambda );
    estLambda = Clip3( lastValidLambda * pow(2.0, -10.0/3.0), lastValidLambda * pow(2.0, 10.0/3.0), estLambda );
  }
  else
  {
    estLambda = Clip3( 0.1, 10000.0, estLambda );
  }

  if ( estLambda < 0.1 )
  {
    estLambda = 0.1;
  }

  m_estPicLambda = estLambda;

  Double totalWeight = 0.0;
  // initial BU bit allocation weight
  for ( Int i=0; i<m_numberOfLCU; i++ )
  {
    Double alphaLCU, betaLCU;
    if ( m_encRCSeq->getUseLCUSeparateModel() )
    {
      alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
      betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
    }
    else
    {
      alphaLCU = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
      betaLCU  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
    }

    m_LCUs[i].m_bitWeight =  m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU );

    if ( m_LCUs[i].m_bitWeight < 0.01 )
    {
      m_LCUs[i].m_bitWeight = 0.01;
    }
    totalWeight += m_LCUs[i].m_bitWeight;
  }
  for ( Int i=0; i<m_numberOfLCU; i++ )
  {
    Double BUTargetBits = m_targetBits * m_LCUs[i].m_bitWeight / totalWeight;
    m_LCUs[i].m_bitWeight = BUTargetBits;
  }

  return estLambda;
}
//______________________________________________________________________________
void
ice::util::iceCommandEventQuery::processEventsForJob( const string& CID, 
						      const list<soap_proxy::EventWrapper*>& ev )
{
  

  static const char* method_name = "iceCommandEventQuery::processEventsForJob() - ";

  //if(GID=="N/A") return;

  {  //MUTEX FOR RESCHEDULE
    boost::recursive_mutex::scoped_lock M_reschedule( glite::wms::ice::util::CreamJob::s_reschedule_mutex );
    string ignore_reason;  
    CreamJob tmp_job;
    if( glite::wms::ice::util::IceUtils::ignore_job( CID, tmp_job, ignore_reason ) ) {
      CREAM_SAFE_LOG( m_log_dev->warnStream() << method_name  << " TID=[" << getThreadID() << "] "
      		      << "IGNORING EVENTS for CreamJobID ["
		      << CID << "] for reason: " << ignore_reason
		      );
		            
      return;
    }
  
   
  
  int num_events = ev.size();

  if( !num_events ) // this should not happen
    return;

  CREAM_SAFE_LOG(m_log_dev->debugStream() << method_name << " TID=[" << getThreadID() << "] "
		 << "Processing [" << num_events << "] event(s) for Job ["
		 << tmp_job.describe() << "] userdn ["
		 << tmp_job.user_dn() << "] and ce url ["
		 << tmp_job.cream_address() << "]."
		 );
  
  list<soap_proxy::EventWrapper*>::const_iterator evt_it;// = ev.begin();
  int evt_counter = 0;
  for( evt_it = ev.begin(); evt_it != ev.end(); ++evt_it ) {
    
    CREAM_SAFE_LOG(m_log_dev->debugStream() << method_name << " TID=[" << getThreadID() << "] "
		   << "EventID ["
		   << (*evt_it)->id << "] timestsamp ["
		   << (*evt_it)->timestamp << "]"
		 );
    
    bool removed = false;
    /**
       WRITE ON ICE's DATABASE ONLY IF THIS IS THE LAST EVENT
       FOR THE CURRENT JOB, i.e. if evt_counter == (num_events-1)
    */
    this->processSingleEvent( tmp_job, *evt_it, evt_counter == (num_events-1), removed );

    if(removed)
      return;
    
    ++evt_counter;
  }
  } // MUTEX FOR RESCHEDULE
}
Example #27
0
void localPhase(string haplotypes[][2], list<pop> & window, int ntarget){
 
  double ehhmax = -1;
  
  string totalHaplotypes[ntarget][2];
  
  for(int k = 0; k < 1000; k++){
    
    string tempHaplotypes[ntarget][2] ;
    
    int tlength = haplotypes[0][0].size();
    
    for(int nt = 0; nt < ntarget ; nt++){
      if(tlength > 0 ){
   	tempHaplotypes[nt][0] = haplotypes[nt][0].substr(tlength - 5, 5);
   	tempHaplotypes[nt][1] = haplotypes[nt][1].substr(tlength - 5, 5);
      }
      else{
   	tempHaplotypes[nt][0] = "00000";
   	tempHaplotypes[nt][1] = "00000";
      }
    }
 
    int snpIndex  = 0;

    for(list<pop>::iterator pos = window.begin(); pos != window.end(); pos++){    
      
      int indIndex = 0;

      for(vector<int>::iterator ind = pos->geno_index.begin(); ind != pos->geno_index.end(); ind++){      
	int g = pos->geno_index[indIndex];
	double rang  = ((double)rand() / (double)(RAND_MAX));
	if(rang < pos->unphred_p[indIndex][0]){
	  g = 0;
	}
	else if(rang < pos->unphred_p[indIndex][1]){
	  g = 1;
	}
	else{
	  g = 2;
	}	
	if(g == 0 ){
          tempHaplotypes[indIndex][0].append("0");
          tempHaplotypes[indIndex][1].append("0");
        }
	if( g == 2 ){	
	  tempHaplotypes[indIndex][0].append("1");
	  tempHaplotypes[indIndex][1].append("1");
	}
	if(g == 1){
	  double ranh  = ((double)rand() / (double)(RAND_MAX)); 
	  if(ranh < 0.5){
	    tempHaplotypes[indIndex][0].append("0");
	    tempHaplotypes[indIndex][1].append("1");
	  }
	  else{
	    tempHaplotypes[indIndex][0].append("1");
	    tempHaplotypes[indIndex][1].append("0");
	  }
	}	
	indIndex++; 
      }
      snpIndex++; 
    } 


    double ehh = EHH(tempHaplotypes, ntarget);    
    if(ehh > ehhmax){
      ehhmax = ehh;
      loadImprovement(tempHaplotypes, totalHaplotypes, ntarget);

    }
  }
  appendHaplotypes(totalHaplotypes, haplotypes, ntarget);
}
Example #28
0
void display(list<T>& l)
{
    copy(l.begin(), l.end(), ostream_iterator<T>(cout, "\t"));
}
Example #29
0
// Constructor for moving object, it not create entity (mesh, skeleton) but build animation on pre-exist entity
CAnimatedSceneObject::CAnimatedSceneObject( const CEntityId& Id, const list < std::string >& Animations )
{
	_Id = Id;
	_ObjectName = "";
	_ClusterIG = "";
	_MeshName = "";
	_SkeletonName = "";
	_Distance = 0;

	_Skeleton = NULL;
	_Instance = NULL;

	CEntityCL *entity = getEntity(Id);
	if(entity)
	{
		_Skeleton = *entity->skeleton();
		_Transform = _Skeleton;

		_Position = _Skeleton->getPos();
		_Rotation = _Skeleton->getRotQuat();

		// create play list manager and animation set
		_PlayListManager = Scene->createPlayListManager();
		_AnimationSet = Driver->createAnimationSet();

		//fill animation set
		for( list< string >::const_iterator its = Animations.begin(); its != Animations.end(); ++its )
		{
			uint idAnim;
			try
			{
				idAnim = _AnimationSet->addAnimation( ( *its + string(".anim") ).c_str(), (*its).c_str() );
			}
			catch(Exception &)
			{
				idAnim = UAnimationSet::NotFound;
				if( idAnim == UAnimationSet::NotFound)
				{
					nlwarning( "CAnimatedSceneObject::CAnimatedSceneObject Animation %s not found for entity CEntityId(%u,%f)", (*its).c_str(), Id.Type, (double)(sint64)Id.Id );
					continue;
				}
			}
			_MapAnimation.insert( make_pair( *its, idAnim ) );
		}

		// build animation set
		_AnimationSet->build();

		// create playlist
		_PlayList = _PlayListManager->createPlayList( _AnimationSet );

		_Status = SAnimationStatus();
		_Status.SequenceAnim = 1;
		_Status.ApplyDisplacement = 1;

		// register skeleton in playlist
		_PlayList->registerTransform( *entity->skeleton() );

		// Snap to ground(the snap check if it's a flyer).
		entity->pacsPos(_Position);
		entity->snapToGround();
		_Position = entity->pos();

		CMatrix current;
		current.identity ();
		current.setRot (_Rotation);

		// Rotation 90°
		CMatrix rot90;
		rot90.identity ();
		rot90.rotateZ (-(float)Pi/2);
		current *= rot90;

		_Transform->unfreezeHRC();

		_Transform->setPos(_Position);
		_Transform->setRotQuat(current.getRot());

		_Transform->freezeHRC();

		_IdAnimationPlayed = -1;

		if( _Id.Type == RYZOMID::npc )
		{
			sendEndSequenceMessage( _Id, 1 );
		}
	}
	else
	{
		_PlayList = NULL;
		_AnimationSet = NULL;
		_PlayListManager = NULL;
	}
}
Example #30
0
int main ( int argc, char* argv[] )
{
    if ( argc != 2 )
    {
	cout << "usage : " << argv[0] << " SLCFileName" << endl;
	cout << argv[0] << " will generate a slc file & idx files" << endl;
	return 0;
    }
    initLC();
    initMaterials();

//    list<SLCNode*> nodes;
    SLCSceneNode scene ( "test_scene");
    scene.addChild ( gmat );
    scene.addChild ( gmat1 );
    scene.addChild ( gmatLine0 );
    scene.addChild ( gmatLine );
    scene.addChild ( gmatLine2 );
    scene.addChild ( gmatLine3 );

    {
	SLCLayerNode* layer = new SLCLayerNode ( "background", gmat );
	nodes.push_back ( layer );
	SLCLODNode* lod = new SLCLODNode();
	nodes.push_back ( lod );
	SLCLODPageNode* lodpage = new SLCLODPageNode();
	nodes.push_back ( lodpage );
	lodpage->delayloading = false;
	lodpage->kdtree = "background0.idx";
	lodpage->imposter = true;
	scene.addChild ( layer );
	layer->addChild ( lod );
	lod->addChild ( lodpage );

	SLCTransformNode* t = new SLCTransformNode ();
//	mat_rotatematrix ( t->mat, M_PI / 2, 2 );
	mat_translatematrix ( t->mat, -100, -100, 0 );
	nodes.push_back ( t );
	lodpage->addChild ( t );

	float w = 8900;
	float h = 10800;
	SLCRectNode* rc1 = new SLCRectNode ( gmat1 );
	nodes.push_back ( rc1 );
	rc1->pnts[0] = vec2f ( 0, 0 );
	rc1->pnts[1] = vec2f ( w, 0 );
	rc1->pnts[2] = vec2f ( w, h );
	rc1->pnts[3] = vec2f ( 0, h );
	rc1->z = -2;
//	lodpage->addChild ( rc1 );
	t->addChild ( rc1 );
    }

    {
	SLCLayerNode* layer = new SLCLayerNode ( "global routing", gmat );
	nodes.push_back ( layer );
	SLCLODNode* lod = new SLCLODNode();
	nodes.push_back ( lod );
	SLCLODPageNode* lodpage = new SLCLODPageNode();
	nodes.push_back ( lodpage );
	lodpage->delayloading = false;
	lodpage->kdtree = "globalrouting0.idx";
	lodpage->imposter = true;
	scene.addChild ( layer );
	layer->addChild ( lod );
	lod->addChild ( lodpage );
	float w, h;
	lodpage->addChild ( globalrouting_lod0(gmat, w, h) );
    }

    {
	float w, h;
	SLCLayerNode* layer = new SLCLayerNode ( "local routing", gmat );
	nodes.push_back ( layer );
	SLCLODNode* lod = new SLCLODNode();
	nodes.push_back ( lod );
	SLCLODPageNode* lodpage = new SLCLODPageNode();
	nodes.push_back ( lodpage );
	lodpage->delayloading = false;
	lodpage->kdtree = "localrouting0.idx";
	lodpage->imposter = true;
	scene.addChild ( layer );
	layer->addChild ( lod );
	lodpage->addChild ( localrouting_lod0(gmat, w, h) );

	SLCLODPageNode* lodpage1 = new SLCLODPageNode();
	nodes.push_back ( lodpage1 );
	lod->addChild ( lodpage1 );
	lod->addChild ( lodpage );
	lod->scales.push_back (0.00019);
    }
    {
	float w, h;
	SLCLayerNode* layer = new SLCLayerNode ( "logic", gmat );
	nodes.push_back ( layer );
	scene.addChild ( layer );

	SLCLODNode* lod = new SLCLODNode();
	nodes.push_back ( lod );
	layer->addChild ( lod );

	SLCLODPageNode* lodpage0 = new SLCLODPageNode();
	nodes.push_back ( lodpage0 );
	lodpage0->delayloading = false;
	lodpage0->kdtree = "logic0.idx";
	lodpage0->imposter = true;
	lodpage0->addChild ( logic_lod0( gmat, w, h) );

	SLCLODPageNode* lodpage1 = new SLCLODPageNode();
	nodes.push_back ( lodpage1 );
	lodpage1->delayloading = false;
	lodpage1->kdtree = "logic1.idx";
	lodpage1->imposter = true;
	lodpage1->addChild ( logic_lod1( gmat, w, h) );

	SLCLODPageNode* lodpage2 = new SLCLODPageNode();
	nodes.push_back ( lodpage2 );
	lodpage2->delayloading = false;
	lodpage2->kdtree = "logic2.idx";
	lodpage2->imposter = true;
	lodpage2->addChild ( logic_lod2( gmat, w, h) );

	lod->addChild ( lodpage0 );
	lod->addChild ( lodpage1 );
	lod->addChild ( lodpage2 );
	lod->scales.push_back (0.00019);
	lod->scales.push_back (0.00022);
    }

    {
	float w, h;
	SLCLayerNode* layer = new SLCLayerNode ( "port", gmat );
	nodes.push_back ( layer );
	SLCLODNode* lod = new SLCLODNode();
	nodes.push_back ( lod );
	SLCLODPageNode* lodpage = new SLCLODPageNode();
	nodes.push_back ( lodpage );
	lodpage->delayloading = false;
	lodpage->kdtree = "port0.idx";
	lodpage->imposter = true;
	scene.addChild ( layer );
	layer->addChild ( lod );
	lodpage->addChild ( port_lod0( gmat, w, h) );
	SLCLODPageNode* lodpage1 = new SLCLODPageNode();
	nodes.push_back ( lodpage1 );
	lod->addChild ( lodpage1 );
	lod->addChild ( lodpage );

	lod->scales.push_back (0.00026);
    }
//     ofstream o;
//     o.open ("test.xml" );
//     o << scene.toXML();
//     o.close();

    // ********************************************************************************
    SLCNode2LC node2lc ( &scene );
    node2lc.convert ( argv[1] );

    for ( list<SLCNode*>::iterator pp=nodes.begin(); pp!=nodes.end(); ++pp )
        delete *pp;
    
    LC nlc;
    clock_t t = clock();
    nlc.load ( argv[1] );
    cout << "parse finished, elapse " << clock() - t << "(ms), kdtreesize = " << nlc.kdtrees.size() << endl;

    t = clock();
    LCReport rpt ( nlc );
    rpt.printCounter ();
    cout << "traverse finished, elapse " << clock() - t << "(ms)" << endl;

    t = clock();
    nlc.free();
    cout << "free LC finished, elapse " << clock() - t << "(ms)" << endl;
    
    return 0;
}