bool es_ficha_valida_en_palabra(const Casillero& ficha, const list<Casillero>& palabra_actual) {
    // si está fuera del tablero, no es válida
    if (ficha.fila < 0 || ficha.fila > alto - 1 || ficha.columna < 0 || ficha.columna > ancho - 1) {
        return false;
    }

    // si el casillero está ocupado, tampoco es válida
    if (tablero_letras[ficha.fila][ficha.columna] != VACIO) {
        return false;
    }

    //si le quiere robar un casillero a alguien... 
   if (tablero_usadas_provisorias[ficha.fila][ficha.columna] != VACIO) {
        return false;
    }


    if (palabra_actual.size() > 0) {
        // no es la primera letra de la palabra, ya hay fichas colocadas para esta palabra
        Casillero mas_distante = casillero_mas_distante_de(ficha, palabra_actual);
        int distancia_vertical = ficha.fila - mas_distante.fila;
        int distancia_horizontal = ficha.columna - mas_distante.columna;

        if (distancia_vertical == 0) {
            // la palabra es horizontal
            for (list<Casillero>::const_iterator casillero = palabra_actual.begin(); casillero != palabra_actual.end(); casillero++) {
                if (ficha.fila - casillero->fila != 0) {
                    // no están alineadas horizontalmente
                    return false;
                }
            }

            int paso = distancia_horizontal / abs(distancia_horizontal);
            for (unsigned int columna = mas_distante.columna; columna != ficha.columna; columna += paso) {
                // el casillero DEBE estar ocupado en el tablero de palabras
                if (!(puso_letra_en(ficha.fila, columna, palabra_actual)) && tablero_palabras[ficha.fila][columna] == VACIO) {
                    return false;
                }
            }

        } else if (distancia_horizontal == 0) {
            // la palabra es vertical
            for (list<Casillero>::const_iterator casillero = palabra_actual.begin(); casillero != palabra_actual.end(); casillero++) {
                if (ficha.columna - casillero->columna != 0) {
                    // no están alineadas verticalmente
                    return false;
                }
            }

            int paso = distancia_vertical / abs(distancia_vertical);
            for (unsigned int fila = mas_distante.fila; fila != ficha.fila; fila += paso) {
                // el casillero DEBE estar ocupado en el tablero de palabras
                if (!(puso_letra_en(fila, ficha.columna, palabra_actual)) && tablero_palabras[fila][ficha.columna] == VACIO) {
                    return false;
                }
            }
        }
        else {
            // no están alineadas ni horizontal ni verticalmente
            return false;
        }
    }

    return true;
}
Example #2
0
void* proxy(  )
{

	fd_set	writeSet;
	fd_set	readSet;
	int		maxfd = 0;
	//unsigned char	buf[MAXBUF];
	struct timeval	timeout;

	int		maxfdp		= 0;
	int ret=0;
	ssl_info *sslinfo1;
	sockinfo *tempinfo ;
	sockinfo *tempinfo1;
	map<int, sockinfo*>::iterator it;
	map<int, sockinfo*>::iterator it1;
	map<int, sockinfo*>::iterator it3;
    list<TunnelInfo*>::iterator listit;
    TunnelInfo *tunnelinfo;
    char ReqId[20]={0};
	int backcode=0;

	while ( true )
	{
        //ping
        checkping();//ping

        //控制链接断开,关闭所有连接
        if(mainsockstatus==0){
            shutdown( mainsock,2);
            //释放所有连接
            for ( it3 = socklist.begin(); it3 != socklist.end(); )
            {
                clearsock( it3->first,  it3->second);
                it3++;
            }
            socklist.clear();
            mainsock = 0;
            //改回状态
            mainsockstatus=1;
            //初始化通道
            InitTunnelList(&tunnellist,&tunneladdr);
        }

	    if (lastdnsback == -1 ||(lastdnstime + 600) < get_curr_unixtime())
		{
			lastdnsback	= net_dns( &server_addr, s_name, s_port );
			lastdnstime	= get_curr_unixtime();
			printf( "update dns\r\n" );
		}
		//dns解析成功
        if (lastdnsback != -1)
        {
            CheckStatus();
        }

        //注册端口
        if(socklist.count(mainsock)!=0&&mainsock!=0){

            tempinfo=socklist[mainsock];
            if(tempinfo->isauth==1&&regtunneltime+60<get_curr_unixtime()){
                regtunneltime=get_curr_unixtime();
                for ( listit = tunnellist.begin(); listit != tunnellist.end(); ++listit )
                {
                    tunnelinfo =(TunnelInfo	*)*listit;
                    if(tunnelinfo->regstate==0){
                        memset(ReqId,0,20);
                        memset(tunnelinfo->ReqId,0,20);
                        #if OPENSSL
                        SendReqTunnel(mainsock,mainsslinfo->ssl,ReqId,tunnelinfo->protocol,tunnelinfo->hostname,tunnelinfo->subdomain, tunnelinfo->remoteport ,authtoken);
                        #else
                        SendReqTunnel(mainsock,&mainsslinfo->ssl,ReqId,tunnelinfo->protocol,tunnelinfo->hostname,tunnelinfo->subdomain, tunnelinfo->remoteport,authtoken );
                        #endif
                        //copy
                        memcpy(tunnelinfo->ReqId,ReqId,strlen(ReqId));
                        tunnelinfo->regtime=get_curr_unixtime();//已发
                    }
                }
            }
        }


		timeout.tv_sec	= 0;
		timeout.tv_usec = 5000;
		FD_ZERO( &readSet );
		maxfd	= 0;
		maxfdp	= 0;
		FD_ZERO( &writeSet );

		/* 遍历添加 */
		//map<int, sockinfo*>::iterator it;
		for ( it = socklist.begin(); it != socklist.end();  )
		{

			tempinfo = it->second;
			/* 如果未连接才添加,写入监听 */
			if ( tempinfo->isconnect == 0 )
			{
				FD_SET( it->first, &writeSet );
			}
			else{
				FD_SET( it->first, &readSet );
			}
			maxfdp = it->first > maxfdp ? it->first : maxfdp;
			maxfd++;
			//继续遍历
			sleeps(1);
			++it;
		}

        #if UDPCMD
        if(udpsocket>0){
            maxfdp = udpsocket > maxfdp ? udpsocket : maxfdp;
            FD_SET(udpsocket,&readSet );
        }
        #endif //

		if(maxfd==0)
		{
			sleeps( 500 );
		}

		/*  printf("add ok \r\n"); */
        ret = select( maxfdp + 1, &readSet, &writeSet, NULL, &timeout ); /* 为等待时间传入NULL,则永久等待。传入0立即返回。不要勿用。 */
		if ( ret == -1 && maxfd != 0 )
		{
            echo("select error\r\n");
			continue;
		}

		if ( ret > 0 )
		{


            #if UDPCMD
            if(FD_ISSET(udpsocket,&readSet))
            {
                UdpCmd(udpsocket);
            }
            #endif

			for ( it1 = socklist.begin(); it1 != socklist.end(); )
			{
			    tempinfo = it1->second;
			      //ping
                checkping();//这里添加个ping避免超时
                //判断连接超时sock
                if((tempinfo->linktime+10)<get_curr_unixtime()&&tempinfo->isconnect==0)
                {
					//关闭远程连接
                    if(tempinfo->istype==2){
                        echo("连接本地失败");
                        shutdown( tempinfo->tosock, 2 );
                    }
                    clearsock(it1->first,tempinfo);
                    socklist.erase(it1++);
                    continue;
                }

			    /*等于1才是添加到 readSet的*/
				if (FD_ISSET( it1->first, &readSet )&&tempinfo->isconnect==1 )
				{

                    sslinfo1 = tempinfo->sslinfo;
                    /* 远程的转发给本地 */
                    if ( tempinfo->istype == 1 )
                    {
                        //未连接本地
                        if ( tempinfo->isconnectlocal == 0 )
                        {
                            backcode=ConnectLocal(sslinfo1,&it1,tempinfo,&socklist,&tunneladdr);
                            if(backcode==-1)
                            {
                              continue;
                            }
                        }
                        //等待本地连接完成
                        if( tempinfo->isconnectlocal == 1 )
                        {
                            sleeps( 1 );//避免频繁触发cpu过高
                        }
                        //本地连接完成转发
                        if( tempinfo->isconnectlocal == 2 )
                        {
                            backcode=RemoteToLocal(sslinfo1,tempinfo,&it1,&socklist);
                            if(backcode==-1)
                            {
                              continue;
                            }
                        }
                    }
                    /* 本地的转发给远程 */
                    else if(tempinfo->istype == 2){
                        backcode=LocalToRemote(&it1,tempinfo,sslinfo1,&socklist);
                        if(backcode==-1)
                        {
                          continue;
                        }
                    }
                    //控制连接
                    else if(tempinfo->istype ==3){
                         backcode=CmdSock(&mainsock,tempinfo,&socklist,server_addr,&ClientId,authtoken,&tunnellist,&tunneladdr);
                         if(backcode==-1)
                         {
                             //控制链接断开,标记清空
                             mainsockstatus=0;
                             lasterrtime=get_curr_unixtime();
                             break;
                         }
                    }


				}
				//可写,表示连接上了
				if ( FD_ISSET( it1->first, &writeSet )&&tempinfo->isconnect==0 )
				{
					if ( tempinfo->isconnect == 0 )
					{
					    //检测连接是否可用
						if (check_sock(it1->first)!= 0 )
						{
						    	//关闭远程连接
							if(tempinfo->istype==2){
                                echo("连接本地失败");
							    shutdown( tempinfo->tosock, 2 );
							}
							clearsock(it1->first,tempinfo);
							socklist.erase(it1++);
							continue;
						}


						/* 为远程连接 */
						if ( tempinfo->istype == 1 )
						{
						    //初始化远程连接
                            backcode=RemoteSslInit(&it1,tempinfo,ClientId,&socklist);
                            if(backcode==-1)
                            {
                               continue;
                            }
                            /* 置为1 */
                            tempinfo->isconnect = 1;
						}

                        //本地连接
                        if ( tempinfo->istype == 2 )
						{
                            if(socklist.count(tempinfo->tosock)>0)
                            {
                                tempinfo1 = socklist[tempinfo->tosock];
                                tempinfo1->isconnectlocal=2;
                            }
                            /* 置为1 */
                            tempinfo->isconnect = 1;
						}

					}
				}
				//继续遍历
				++it1;
			}
		}
		//睡1豪秒,避免CPU过高
		sleeps(2);
	}
	return(0);
}
Example #3
0
void dijkstra(double caminho[][15])
{
    int t, cont=0;
    double menor;

    if(!dijkstraencerrado)//se é falso que dijkstra foi finalizado
    {
    
        if(!primeiraexe) //se é a primeira vez que está sendo executado a verificação do menor caminho (iteração k=0)
        {
            menor = caminho[0][1];
            t = 1;

            for(int w = 0; w < 15; w++)
            {
                if(caminho[0][w] != 9999999) //se o caminho nao é a cidade de partida (Criciúma) ou inalcançável
                {
                    if(caminho[0][w] < menor)  // busca a menor distancia em "Criciúma > w"
                    {
                        menor = caminho[0][w];
                        t = w; // grava a cidade específica que apresenta o menor caminho
                    }
                }
            }
        }

        //se não é a primeira execução, nos diz consequentemente que existe ao menos uma cidade já adicionada ao conjunto N
        else
        {
            menor = 9999999;

            for(aux = m.begin(); aux != m.end(); aux++)
            {
                if((aux->second.getkilometragem()) != 9999999) //se o caminho nao é a cidade de partida (Criciúma) ou inalcançável
                {              
                        percorrelista = find(N.begin(), N.end(), (aux->first)); //busca se o caminho não pertence já ao conjunto N

                        if(percorrelista == N.end())
                        {
                            if((aux->second.getkilometragem()) < menor)
                            {
                                menor = aux->second.getkilometragem();
                                t = aux->first; // grava a cidade específica que apresenta o menor caminho
                            }
                        }
                    }
               }
               }
        
        //insere a cidade mais próxima numa lista, pelo final, priorizando a ordem crescente, criando o conjunto N do caminho mais próximo
        N.push_back(t);
        /* testa:
          1 - cidades inalcançáveis por Criciuma é alcançável agora pelo caminho "Criciuma + menor"?
        - Sim > alteração no map em kilometragem e campo "s";
        - Não > continua como estava.

          2 - se a cidade já era alcançável, testa se "Criciuma + menor" é menor que o caminho partindo da ultima
        cidade setada "s".
        */

        if(!primeiraexe)
        {
            for(int z = 0; z < 15; z++)
            {
                if(z!=0) // se a cidade da iteração não é Criciúma
                {

                    /*
                    se o caminho partindo da cidade mais próxima (t) não for inalcançável (infinito) à cidade "z" E for menor
                    que o caminho partindo de Criciúma
                    */
                    if((caminho[t][z] != 9999999) && ((caminho[0][t] + caminho[t][z]) < caminho[0][z]))
                    {
                        aux = m.find(z);
                        if(aux != m.end())
                        {
                            aux->second.setkilometragem((menor + caminho[t][z]));
                            aux->second.sets(t);
                        }
                    }
                }
            }
        }

        else
        {
            aux = m.find(t);
            menor = aux->second.getkilometragem(); //caminho de Criciuma até a cidade "t"

            for(aux = m.begin(); aux != m.end(); aux++)
            {
                if(cont!= 0) //se a chave não é Criciúma (poderia ser: aux->first != 0)
                {
                    //se o caminho não for inancançável pela cidade definida anteriormente como mais próxima
                    if((caminho[t][cont]) != 9999999)
                    {

                        /* Se o caminho da cidade mais proxima encontrada anteriormente (t) para a cidade
                        da iteração (aux) for menor que a kilometragem existente partindo da cidade
                        setada "s"
                        */
                        if((menor + caminho[t][cont]) < (aux->second.getkilometragem()))
                        {
                            aux->second.setkilometragem((menor + caminho[t][cont]));
                            aux->second.sets(t); //nova cidade de partida para chegar na cidade da iteração (aux)
                        }
                    }
                }

                cont++;
            }
        }


        //testa se o destino fornecido esta alcançável
       
       percorrelista = find(N.begin(), N.end(), (destino));


       if(percorrelista != N.end())
       {
                        dijkstraencerrado = true;
                        
                        //REFININANDO O DIJKSTRA
                        
                        N.clear();
                        N.push_front(destino);
                        aux = m.find(destino);
                        
                        while((aux->first) != 0)
                        {
                                         N.push_front((aux->second.gets()));
                                         aux = m.find(aux->second.gets());
                        }
       }
            
        if(!primeiraexe)
        {
            primeiraexe = true;
        }


        dijkstra(caminho);
        
        }
        
   return;

}
/**
 * Utility method for sending a list of process variables.
 */
static void sendAll(list<ProcessVariable::SharedPtr> const& processVariables) {
  for(list<ProcessVariable::SharedPtr>::const_iterator i = processVariables.begin(); i != processVariables.end(); ++i) {
    (*i)->write();
  }
}
Example #5
0
int main(int argc, char* argv[]){
    readDictionary(argv[1]);
    int totalWordsFound = 0;
    int rows, cols;
    bool result = readInGrid (argv[2], rows, cols);
    if ( !result ) {
        cout << "Error reading in file!" << endl;
        exit(1); 
    }
    cout << endl;
    string dir = "";
    timer t;
    t.start();
    for ( int direction = 0; direction < 8; direction++ ){
      for( int startRow = 0; startRow < rows; startRow++){
	for( int startCol = 0 ; startCol < cols; startCol++){
	  int len;
	   switch (direction) { // assumes grid[0][0] is in the upper-left
            case 0:
                len = startRow + 1;
		if(len > 22){
		  len = 22;
		}
		dir = "N  ";
                break; // north
	    case 1:
	        len = getMaxDiagnol(cols - startCol, startRow+1);
	        if(len > 22){
		  len = 22;
	        }
	        dir = "NE";
                break; // north-east
            case 2:
	        len = cols - startCol;
	        if(len > 22){
		  len = 22;
		}
	        dir = "E  ";
                break; // east
            case 3:
	       len = getMaxDiagnol(cols - startCol, rows - startRow);
	       if(len > 22){
	         len = 22;
	       }
	       dir = "SE";
               break; // south-east
            case 4:
               len = rows - startRow;
	       if(len > 22){
	         len = 22;
	       }
	       dir = "S  ";
               break; // south
            case 5:
	      len = getMaxDiagnol(startCol+1, rows-startRow);
	      if(len > 22){
		len = 22;
	      }
	      dir = "SW";
              break; // south-west
            case 6:
              len = startCol+1;
	      if(len > 22){
	        len = 22;
	      }
	      dir = "W  ";
              break; // west
            case 7:
	      len = getMaxDiagnol(startCol+1, startRow+1);
	      if(len > 22){
		len = 22;
	      }
	      dir = "NW";
              break; // north-west
	  }
	  for(int i = len ; i >= 3; i--){
	    char* tempWord = getWordInGrid (startRow, startCol, direction, i, rows, cols);
	    string result = dictionaryTable->searchWord(tempWord);
	    if(result != ""){
	       stringstream streamRow;
	      streamRow << startRow;
	      string stringRow = streamRow.str();
	      stringstream streamCol;
	      streamCol << startCol;
	      string stringCol = streamCol.str();
	      buffer.push_back(dir + " (" + stringRow +  "," + stringCol + ")" + ":            " +  result);
	      totalWordsFound++;
	    }
          }
        }
      }	
    }
    t.stop();
     for (list<string>::const_iterator iterator = buffer.begin(); iterator != buffer.end(); ++iterator) {
    cout << *iterator << endl;
    }
    cout << totalWordsFound << " words found" << endl;
    cout << "Found all words in " << t.getTime() << " seconds" << endl;
    cout << int(t.getTime() * 1000)  << endl;
    return 0;
}
	std::list<int>::iterator firstConnection() {
		return _connections.begin();
	}
void cElementManager::handleParams (const string &tagname, list<sParam> &args,
    const list<string> &attlist, const map<string, string> &attdefault)
{
  list<string>::const_iterator cur = attlist.begin();
  list<sParam>::iterator it;
  for (it = args.begin(); it != args.end(); ++it)
  {
    //flag?
    if ((*it).flag)
    {
      //only advance parameter iterator
      cur++;
    }
    //not a flag
    else
    {
      //empty name?
      if ((*it).name.empty())
      {
        //set the parameter name:
        
        //find the correct attribute name, skipping all flags
        while (cur != attlist.end())
        {
          if ((attdefault.count (*cur) != 0) && (attdefault.find(*cur)->second == ""))  //flag
            cur++;
          else
            break;  //okay, found the correct parameter
        }
        if (cur == attlist.end())    //ARGH! Parameter not found :(
        {
          results->addToList (results->createError ("Received too much parameters for tag " +
              tagname + "!"));
          continue;  //continue with the next parameter...
        }
      }
      //non-empty name?
      else
      {
        //set "cur" to the parameter following the given one
        
        //to speed things up a bit, first look if the iterator is pointing at the right parameter
        // (we won't need to traverse the whole list, if it does)
        if ((cur == attlist.end()) || ((*it).name != *cur))
        {
          list<string>::const_iterator cur2 = cur;  //remember old "cur" value
          for (cur = attlist.begin(); cur != attlist.end(); ++cur)
            if ((*it).name == *cur)
              break;
          if (cur == attlist.end())    //parameter name not found
          {
            //restore old iterator value
            cur = cur2;
            results->addToList (results->createError ("Received unknown parameter " +
                (*it).name + " in tag " + tagname + "!"));
            //clear name/value to avoid confusion in later stages
            (*it).name = "";
            (*it).value = "";
            //proceed with next parameter
            continue;
          }
          //if cur isn't attlist.end(), it's now set to the correct value...
        }
      }
      
      //things common to all non-flag parameters...
      
      //set parameter name
      (*it).name = *cur;
      //if parameter value is empty, set it to default value (if any)
      if ((*it).value.empty() && (attdefault.count (*cur) != 0))
        (*it).value = attdefault.find(*cur)->second;
      //advance parameter iterator
      cur++;
    }
  }
  
  //finally, we add default parameter values to the beginning of the list... these shall get
  //overridden by given values, if any (those shall be later in the list)
  sParam s;
  map<string, string>::const_iterator mit;
  for (mit = attdefault.begin(); mit != attdefault.end(); ++mit)
    if (mit->second != "")  //not a flag
    {
      s.flag = false;
      s.name = mit->first;
      s.value = mit->second;
      args.push_front (s);
    }
}
void CSmartCommunicationDlg::OnButtonStart() 
{		
	char		buf[128],Module[30],msg[256];	
	CData		mdata;	
	int			nErrCode=0;	
	int         FunId;
	CSystemInfo	SystemInfo;
	list<CSocketSmart>::iterator SocketSmart;

	memset(buf,   0x00,sizeof buf);
	memset(msg,	  0x00,sizeof msg);
	memset(Module,0x00,sizeof Module);

	g_CInterface.SetParentpDlg(this);
	//清除显示框中的信息
	OnButtonClear();
	Init();
	m_BtCancel.EnableWindow(FALSE);
	m_BtStart.EnableWindow(FALSE);
	m_BtClear.EnableWindow(TRUE);

	strcpy(msg,"前置系统开始启动并监控所有终端设备,请稍后......");
	AddString(msg);
	WriteLog(msg);
	//初始化第三方接口		
	strcpy(msg,"前置系统正在初始化第三方接口,请稍后......");
	AddString(msg);
	WriteLog(msg);
	if( !g_bInitConnectFlag )
	{	
		if( !g_CInterface.SMT_InterfaceInit(m_ServerIP,m_ServerPort) )
		{
			AddString("前置系统正在初始化第三方接口失败,请退出前置重新启动");
			strcpy(m_ErrMsg,g_CInterface.m_szText);
			goto To_SystemEnd;
		}
		g_bInitConnectFlag=true;
	}
	//前置签到	
	strcpy(msg,"前置系统正在向金仕达签到,请稍后......");
	AddString(msg);
	WriteLog(msg);
	if( !g_CInterface.SMT_SmartFrontLogin(5000) )
	{
		sprintf(m_ErrMsg,"前置向金仕达签到失败[金仕达返回:%s]",g_CInterface.m_szText);
		goto To_SystemEnd;
	}

	//获取黑名单
	strcpy(msg,"前置系统正在装载黑名单,请稍后......");
	AddString(msg);
	WriteLog(msg);	
	FunId=SMT_SMARTFRONTDOWNALLBLACK;
	if( !g_CInterface.SMT_GetAllInitBlackList(FunId) )
	{
		strcpy(m_ErrMsg,g_CInterface.m_szText);
		goto To_SystemEnd;
	}
	

	//获取补助名单
	strcpy(msg,"前置系统正在装载补助名单,请稍后......");
	AddString(msg);
	WriteLog(msg);	
	if( !g_CInterface.SMT_GetAllInitAssistantList(false,0) )
	{
		strcpy(m_ErrMsg,g_CInterface.m_szText);
		goto To_SystemEnd;
	}

	//获取设备的主参数	
	strcpy(msg,"前置系统正在获取设备的主参数,请稍后......");
	AddString(msg);
	WriteLog(msg);
	if( !GetDevicePara() ) 
	{
		strcpy(m_ErrMsg,g_CInterface.m_szText);
		goto To_SystemEnd;
	}
	//显示启动的服务总数
	sprintf(m_ErrMsg,"前置系统总共需要启动%ld个链路服务.",g_LTcpsmart.size());
	AddString(m_ErrMsg);	
	WriteLog(m_ErrMsg);	
	//启动所有通过TCP连接的服务	
	for( SocketSmart=g_LTcpsmart.begin();SocketSmart!=g_LTcpsmart.end();SocketSmart++)
	{
		SocketSmart->SetParent(this);
		SocketSmart->Start();
		sprintf(m_ErrMsg,"开始准备启动 %s 的线程......",SocketSmart->m_IpPar.cIPAddress);
		AddString(m_ErrMsg);	
		WriteLog(m_ErrMsg);
	}
	g_StartFlag = 1;
	//取任务线程
	UINT SMT_StartQueryTaskThread( LPVOID pParam );
	if(AfxBeginThread(SMT_StartQueryTaskThread, (LPVOID)this)==NULL)
	{			
		strcpy(m_ErrMsg,"创建从数据库中取任务的线程失败");	
		goto To_SystemEnd;
	}
	//上传交易记录线程
	UINT SMT_StartUpRecordThread( LPVOID pParam );
	if(AfxBeginThread(SMT_StartUpRecordThread, (LPVOID)this)==NULL)
	{			
		strcpy(m_ErrMsg,"创建从数据库中取任务的线程失败");	
		goto To_SystemEnd;
	}
 	//定时取黑名单线程,每12小时取一次数据
	UINT SMT_EveryDayGetAllInitAssistantThread( LPVOID pParam );
	if(AfxBeginThread(SMT_EveryDayGetAllInitAssistantThread, (LPVOID)this)==NULL)
	{			
		strcpy(m_ErrMsg,"创建从数据库中定时取黑名单的线程失败");	
		goto To_SystemEnd;
	}	
	m_BtRate.EnableWindow(TRUE);
	m_BtCancel.EnableWindow(FALSE);
	m_BtStart.EnableWindow(FALSE);
	return ;	
To_SystemEnd:
	AddString(m_ErrMsg);
	WriteLog(m_ErrMsg);
	OnButtonStop();
	m_BtCancel.EnableWindow(TRUE);
	m_BtStart.EnableWindow(TRUE);
	m_BtClear.EnableWindow(TRUE);		
	m_BtRate.EnableWindow(FALSE);
}
Example #9
0
//------------------------------------------------------------------------------------
int Timetable(void) throw(Exception)
{
try {
   if(CI.Verbose) oflog << "BEGIN Timetable()"
      << " at total time " << fixed << setprecision(3)
      << double(clock()-totaltime)/double(CLOCKS_PER_SEC) << " seconds."
      << endl;

   int ib,iret;
   list<TTSegment>::iterator ttit;

   if(CI.TimeTableFile.size() > 0) {
      iret = ReadTimeTable();
   }
   else if(CI.RefSat.id != -1) {         // user says use this sat only
      // loop over baselines
      for(ib=0; ib<Baselines.size(); ib++) {
         TTSegment ts;
         ts.site1 = word(Baselines[ib],0,'-');
         ts.site2 = word(Baselines[ib],1,'-');
         ts.sat = CI.RefSat;
         ts.start = ts.first = 0;
         ts.end = ts.last = maxCount;
         ts.minelev = ts.maxelev = 0.0;
         ts.length = ts.end - ts.start + 1;
         TimeTable.push_back(ts);
         iret = 0;
      }
   }
   else {
      // loop over baselines
      for(ib=0; ib<Baselines.size(); ib++) {
         iret = ComputeBaselineTimeTable(Baselines[ib]);
         if(iret) break;
      }  // end loop over baselines
   }

   if(iret == 0) {
      // write out timetable to log
      // REF site site sat week use_first use_last data_start data_end
      DayTime tt;
      GSatID sat;
      oflog << "Here is the time table (" << TimeTable.size() << ")" << endl;
      if(CI.Screen)
         cout << "Time table (" << TimeTable.size() << "):" << endl;
      oflog << "# " << Title << endl;
      oflog << "# REF site site sat week use_first use_last data_start data_end\n";
      if(CI.Screen)
         cout << "# REF site site sat week use_first use_last data_start data_end\n";
      for(ttit=TimeTable.begin(); ttit != TimeTable.end(); ttit++) {
         oflog << "REF " << ttit->site1 << " " << ttit->site2 << " " << ttit->sat;
         if(CI.Screen)
            cout << "REF " << ttit->site1 << " " << ttit->site2 << " " << ttit->sat;
         tt = FirstEpoch + CI.DataInterval * ttit->first;
         oflog << tt.printf(" %4F %10.3g");        // TD week rollover!
         if(CI.Screen)
            cout << tt.printf(" %4F %10.3g");        // TD week rollover!
         tt = FirstEpoch + CI.DataInterval * ttit->last;
         oflog << tt.printf(" %10.3g");
         if(CI.Screen)
            cout << tt.printf(" %10.3g");
         tt = FirstEpoch + CI.DataInterval * ttit->start;
         oflog << tt.printf(" %10.3g");
         if(CI.Screen)
            cout << tt.printf(" %10.3g");
         tt = FirstEpoch + CI.DataInterval * ttit->end;
         oflog << tt.printf(" %10.3g");
         if(CI.Screen)
            cout << tt.printf(" %10.3g");
         // TD? ttit->minelev, ttit->maxelev, ttit->length, ttit->metric()
         oflog << " " << fixed << setw(4) << setprecision(1) << ttit->minelev;
         if(CI.Screen)
            cout << " " << fixed << setw(4) << setprecision(1) << ttit->minelev;
         oflog << " " << fixed << setw(4) << setprecision(1) << ttit->maxelev;
         if(CI.Screen)
            cout << " " << fixed << setw(4) << setprecision(1) << ttit->maxelev;
         // write the number of counts for this ref
         oflog << " " << setw(5) << ttit->length;
         if(CI.Screen)
            cout << " " << setw(5) << ttit->length;
         oflog << endl;
         if(CI.Screen)
            cout << endl;

         // for next time
         sat = ttit->sat;
      }
      oflog << "End of time table." << endl;
      if(CI.Screen)
         cout << "End of time table." << endl;
   }

   return iret;

   return 0;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
}   // end Timetable()
Example #10
0
void RTFGenParser::tag_start(const QString &tagName, const list<QString> &attrs)
{
    CharStyle parentStyle, style;
    {
        Tag* pParentTag = m_tags.getTopTagWithCharStyle();
        if (pParentTag != NULL)
        {
            parentStyle = *(pParentTag->pCharStyle);
        }
    }
    style = parentStyle;

    if (tagName == "b"){
        style.bold = true;
    }
    else if (tagName == "i"){
        style.italic = true;
    }
    else if (tagName == "u"){
        style.underline = true;
    }
    else if (tagName == "font"){
        for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); it++){
            QString name = (*it);
            ++it;
            QString value = (*it);
            if (name == "color")
            {
                style.colorIdx = getColorIdx(value);
            }
            else if (name == "face")
            {
                style.faceIdx = getFontFaceIdx(value);
            }
            else if (name == "size")
            {
                int logicalSize = value.toInt();
                if (value[0] == '+' || value[0] == '-')
                    logicalSize += 3;
                if (logicalSize < 1)
                    logicalSize = 1;
                else if (logicalSize > 7)
                    logicalSize = 7;
                style.sizePt = htmlFontSizeToPt(logicalSize);
            }
        }
    }
    else if (tagName == "p"){
        m_paragraphDir = DirUnknown;
        m_lastParagraphPos = res.length();
        m_bSpace = true;
        for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); ++it){
            QString name = (*it).lower();
            ++it;
            QString value = (*it);
            if (name == "dir")
            {
                QString dir = value.lower();
                if (dir == "ltr")
                {
                    res += "\\ltrpar";
                    m_paragraphDir = DirLTR;
                }
                if (dir == "rtl")
                {
                    res += "\\rtlpar";
                    m_paragraphDir = DirRTL;
                }
            }
        }

    }
    else if (tagName == "br"){
        res += "\\line";
        m_bSpace = true;
    }
    else if (tagName == "img"){
        QString src;
        for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); ++it){
            QString name = (*it);
            ++it;
            QString value = (*it);
            if (name == "src"){
                src = value;
                break;
            }
        }
        if (src.left(10) != "icon:smile")
            return;
        bool bOK;
        unsigned nSmile = src.mid(10).toUInt(&bOK, 16);
        if (!bOK)
            return;
        if (nSmile < 16){
            res += "<##icqimage000";
            if (nSmile < 10){
                res += (char)(nSmile + '0');
            }else{
                res += (char)(nSmile - 10 + 'A');
            }
            res += ">";
            return;
        }
        const smile *p = smiles(nSmile);
        if (p)
            res += p->paste;
        return;
    }

    // Process attributes which all tags share.

    for (list<QString>::const_iterator it = attrs.begin(); it != attrs.end(); ++it){
        QString name = (*it).lower();
        ++it;
        QString value = (*it);

        // Any tag might have a STYLE.
        if (name == "style"){
            // A really crude CSS parser goes here:
            QRegExp cssReNum("[0-9]+");
            list<QString> cssProp = parseStyle(value);
            for (list<QString>::iterator it = cssProp.begin(); it != cssProp.end(); ++it){
                QString cssPropName = *it;
                ++it;
                if (it == cssProp.end())
                    break;
                QString cssPropValue = *it;
                if (cssPropName == "font-family")
                {
                    style.faceIdx = getFontFaceIdx(cssPropValue);
                }
                else if (cssPropName == "font-size")
                {
                    cssPropValue = cssPropValue.lower();
                    int length;
                    if (cssReNum.match(cssPropValue, 0, &length) == 0){
                        float number = cssPropValue.left(length).toFloat();
                        QString type = cssPropValue.mid(length);
                        if (type == "pt")
                        {
                            style.sizePt = static_cast<int>(number);
                        }
                        else if (type == "px")
                        {
                            // for now, handle like 'pt', though it's wrong
                            style.sizePt = static_cast<int>(number);
                        }
                        else if (type == "%")
                        {
                            style.sizePt = static_cast<int>(parentStyle.sizePt * (number/100));
                        }
                        // We don't handle 'cm', 'em' etc.
                    }
                    else if (cssPropValue == "smaller")
                    {
                        // FONT SIZE=3 is 'normal', 2 is 'smaller'
                        style.sizePt = htmlFontSizeToPt(2, parentStyle.sizePt);
                    }
                    else if (cssPropValue == "larger")
                    {
                        // FONT SIZE=3 is 'normal', 4 is 'larger'
                        style.sizePt = htmlFontSizeToPt(4, parentStyle.sizePt);
                    }

                    // We don't handle 'small', 'medium' etc. It goes too far
                    // beyond our basic implementation.
                    // Also, empty 'type' would be invalid CSS, thus ignored.
                }
                else if (cssPropName == "font-style")
                {
                    style.italic = (cssPropValue.lower() == "italic");
                }
                else if (cssPropName == "font-weight")
                {
                    style.bold = (cssPropValue.toInt() >= 600);
                }
                else if (cssPropName == "text-decoration")
                {
                    style.underline = (cssPropValue.lower() == "underline");
                }
                else if (cssPropName == "color")
                {
                    style.colorIdx = getColorIdx(cssPropValue);
                }
                else if (cssPropName == "background-color")
                {
                    style.bgColorIdx = getColorIdx(cssPropValue);
                }
            }
        }
    }

    Tag& tag = *(m_tags.pushNew());
    tag.name = tagName;
    // Check if anything changed in the style.
    // Only then the tag deserves getting a charStyle.
    if (parentStyle != style)
    {
        QString rtf = style.getDiffRTF(parentStyle);
        if (!rtf.isEmpty())
        {
            res += rtf.utf8();
            m_bSpace = true;
        }
        tag.setCharStyle(style);
    }
}
/*=================================================================
* Function ID :  ShowDeviceInfo
* Input       :  void
* Output      :  void
* Author      :  
* Date        :  2006  4
* Return	  :  
* Description :  
* Notice	  :  将收到的终端档案信息显示于界面并写日志
*					
*=================================================================*/
void CSmartCommunicationDlg::ShowDeviceInfo( )
{
	CData  cData;
	char   msg[256];
	char   buf[40];
	char   lpbuf[2048];
	int    i=0;
	int    n=0;
	
	memset(msg,0x00,sizeof msg);
	memset(buf,0x00,sizeof buf);

	if( !g_LTcpsmart.empty() )
	{	
		sprintf(msg,"共有 %ld TCP/IP线程链路",g_LTcpsmart.size());
		AddString(msg);
		n=1;
		list<CSocketSmart>::iterator SmtSmart;
		for( SmtSmart=g_LTcpsmart.begin();SmtSmart!=g_LTcpsmart.end();SmtSmart++)
		{			
			memset(lpbuf,0x00,sizeof lpbuf);
			memset(buf,0x00,sizeof buf);
			sprintf(msg,">>>>>第%03ld个TCP/IP通讯服务ID号   %s ",n++,(char*)cData.BcdToAsc((BYTE*)SmtSmart->m_IDNo,4,(BYTE*)buf));
			strcpy(lpbuf,msg);			
			memset(buf,0x00,sizeof buf);
			sprintf(msg,"服务注册号 %s ",(char*)cData.BcdToAsc((BYTE*)SmtSmart->m_regno,4,(BYTE*)buf));
			strcat(lpbuf,msg);			
			sprintf(msg,"服务机器号 %ld ",SmtSmart->m_MacNum);
			strcat(lpbuf,msg);						
			sprintf(msg,"服务端口数% ld",SmtSmart->m_nPortTotal);			
			strcat(lpbuf,msg);			
			memset(buf,0x00,sizeof buf);
			sprintf(msg,"服务机型号 %s",(char*)cData.BcdToAsc((BYTE*)SmtSmart->m_MacCode,2,(BYTE*)buf));
			strcat(lpbuf,msg);							
			sprintf(msg,"服务IP地址 %s",SmtSmart->m_IpPar.cIPAddress);
			strcat(lpbuf,msg);			
			sprintf(msg,"服务端口号 %ld",SmtSmart->m_IpPar.nPortNo);
			strcat(lpbuf,msg);			
			AddString(lpbuf);
			WriteLog(lpbuf);							
			for( i=0; i<SmtSmart->m_nTotalPos; i++)
			{
				memset(buf,0x00,sizeof buf);
				memset(lpbuf,0x00,sizeof lpbuf);
				sprintf(msg,"第%02ld子设备:机器号 %03ld",i+1,SmtSmart->m_SmartPos[i].ucMacNo);
				strcat(lpbuf,msg);								
				memset(buf,0x00,sizeof buf);
				sprintf(msg," ID号 %s",(char*)cData.BcdToAsc(SmtSmart->m_SmartPos[i].ucpIDNo,4,(BYTE*)buf));
				strcat(lpbuf,msg);				
				memset(buf,0x00,sizeof buf);
				sprintf(msg," 注册号 %s",(char*)cData.BcdToAsc(SmtSmart->m_SmartPos[i].ucRegNo,4,(BYTE*)buf));
				strcat(lpbuf,msg);			
				memset(buf,0x00,sizeof buf);
				sprintf(msg," 机型 %s",(char*)cData.BcdToAsc(SmtSmart->m_SmartPos[i].ucpMachineCode,2,(BYTE*)buf));
				strcat(lpbuf,msg);				
				sprintf(msg," 端口号 %ld",SmtSmart->m_SmartPos[i].nPort);
				strcat(lpbuf,msg);
				AddString(lpbuf);
				WriteLog(lpbuf);	
			}
			AddString("    ");
		}
	}
	return ;
}
Example #12
0
string RTFGenParser::parse(const QString &text)
{
    res = "";
    m_codec = m_client->getCodec(m_encoding);
    m_encoding = m_codec->name();
    int charset = 0;
    for (const ENCODING *c = ICQClient::encodings; c->language; c++){
        if (!strcasecmp(c->codec, m_encoding)){
            charset = c->rtf_code;
            break;
        }
    }
#ifdef WIN32
    if ((charset == 0) && !strcasecmp(m_encoding, "system")){
        char buff[256];
        int res = GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_IDEFAULTANSICODEPAGE, (char*)&buff, sizeof(buff));
        if (res){
            unsigned codepage = atol(buff);
            if (codepage){
                for (const rtf_cp *c = rtf_cps; c->cp; c++){
                    if (c->cp == codepage)
                        charset = c->charset;
                }
            }
        }
    }
#endif
    const char *send_encoding = 0;
    m_codec = NULL;
    if (charset){
        for (const ENCODING *c = ICQClient::encodings; c->language; c++){
            if ((c->rtf_code == charset) && c->bMain){
                send_encoding = c->codec;
                m_codec = m_client->getCodec(send_encoding);
                break;
            }
        }
    }

    // Add defaults to the tables
    m_fontFaces.push_back("MS Sans Serif");
    m_colors.push_back(m_foreColor);
    // Create a "fake" tag which'll serve as the default style
    CharStyle style;
    style.faceIdx = 0;
    style.colorIdx = 1; // colors are 1-based (0 = default)
    style.sizePt = 12; // default according to Microsoft
    Tag& tag = *(m_tags.pushNew());
    tag.setCharStyle(style);

    // Assume we go immediately after a tag.
    m_bSpace = true;
    HTMLParser::parse(text);

    string s;
    s = "{\\rtf1\\ansi\\deff0\r\n";
    s += "{\\fonttbl";
    unsigned n = 0;
    for (list<QString>::iterator it_face = m_fontFaces.begin(); it_face != m_fontFaces.end(); it_face++, n++){
        s += "{\\f";
        s += number(n);
        QString face = (*it_face);
        if (face.find("Times") >= 0){
            s += "\\froman";
        }else if (face.find("Courier") >= 0){
            s += "\\fmodern";
        }else{
            s += "\\fswiss";
        }
        if (charset){
            s += "\\fcharset";
            s += number(charset);
        }
        s += " ";
        int pos = face.find(QRegExp(" +["));
        if (pos > 0)
            face = face.left(pos);
        s += face.latin1();
        s += ";}";
    }
    s += "}\r\n";
    s += "{\\colortbl ;";
    for (list<QColor>::iterator it_colors = m_colors.begin(); it_colors != m_colors.end(); ++it_colors){
        QColor c = *it_colors;
        s += "\\red";
        s += number(c.red());
        s += "\\green";
        s += number(c.green());
        s += "\\blue";
        s += number(c.blue());
        s += ";";
    }
    s += "}\r\n";
    s += "\\viewkind4\\pard";
    s += style.getDiffRTF(CharStyle()).utf8();
    s += res;
    s += "\r\n}\r\n";

    log(L_DEBUG, "Resulting RTF: %s", s.c_str());

    return s;
}
Example #13
0
void Client::writeMessagesInQueue(list<Message*> messagesList){
	for(list<Message*>::iterator it=messagesList.begin(); it!=messagesList.end(); ++it){
		this->writeThread->writeMessage((*it));
	}
}
Example #14
0
void iosAppTestApp::draw()
{
	gl::enableAlphaBlending();
	gl::enableDepthRead();
	tester.setState( TestCallbackOrder::DRAW );
	CameraPersp mCam;
	mCam.lookAt( Vec3f( 3, 2, -3 ), Vec3f::zero() );
	mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 );

	if( isUnplugged() )
		gl::clear( Color( 0.2f, 0.2f, 0.3f ) );
	else
		gl::clear( Color( 0.4f, 0.2f, 0.2f ) );		

	gl::enable( GL_TEXTURE_2D );
	gl::color( Color::white() );
	gl::enableDepthRead();
	mTex.bind();
	gl::setMatrices( mCam );
	glPushMatrix();
		gl::multModelView( mCubeRotation );
		gl::drawCube( Vec3f::zero(), Vec3f( 2.0f, 2.0f, 2.0f ) );
	glPopMatrix();
	gl::disable( GL_TEXTURE_2D );
	
	gl::setMatricesWindow( getWindowSize() );
	for( map<uint32_t,TouchPoint>::const_iterator activeIt = mActivePoints.begin(); activeIt != mActivePoints.end(); ++activeIt ) {
		activeIt->second.draw();
	}

	for( list<TouchPoint>::iterator dyingIt = mDyingPoints.begin(); dyingIt != mDyingPoints.end(); ) {
		dyingIt->draw();
		if( dyingIt->isDead() )
			dyingIt = mDyingPoints.erase( dyingIt );
		else
			++dyingIt;
	}
	
	// draw yellow circles at the active touch points
	gl::color( Color( 1, 1, 0 ) );
	for( auto touch : getActiveTouches() )
		gl::drawStrokedCircle( touch.getPos(), 20.0f );
			
	if( getWindow() == mSecondWindow || Display::getDisplays().size() < 2 ) {
		static Font font = Font( "Arial", 48 );
		static std::string lastMessage;
		static gl::Texture messageTex;
		if( lastMessage != mSecondWindowMessage ) {
			TextBox box = TextBox().font( font ).text( mSecondWindowMessage );
			messageTex = box.render();
			lastMessage = mSecondWindowMessage;
		}
		if( messageTex ) {
			gl::color( Color::white() );
			gl::draw( messageTex, Vec2i( ( getWindowWidth() - messageTex.getCleanWidth() ) / 2, getWindowCenter().y ) );
		}
	}
//
	gl::disableDepthRead();
	gl::color( Color( 0.0f, 1.0f, 0.0f ) );
	mFont->drawString( orientationString( getWindowOrientation() ) + "@ " + toString( getWindowContentScale() ), Vec2f( 10.0f, 60.0f ) );
//	gl::drawStringCentered( "Orientation: " + orientationString( getInterfaceOrientation() ), Vec2f( getWindowCenter().x, 30.0f ), Color( 0.0f, 1.0f, 0.0f ), Font::getDefault() ); // ???: why not centered?

	mFont->drawString( toString( floor(getAverageFps()) ) + " fps", Vec2f( 10.0f, 90.0f ) );
}
Example #15
0
bool Program::build(const char *options, list<Header> headers)
{
  m_buildStatus = CL_BUILD_IN_PROGRESS;
  m_buildOptions = options ? options : "";

  // Create build log
  m_buildLog = "";
  llvm::raw_string_ostream buildLog(m_buildLog);

  // Do nothing if program was created with binary
  if (m_source.empty() && m_module)
  {
    m_buildStatus = CL_BUILD_SUCCESS;
    return true;
  }

  if (m_module)
  {
    clearInterpreterCache();
    m_module.reset();
  }

  // Assign a new UID to this program
  m_uid = generateUID();

  // Set compiler arguments
  vector<const char*> args;
  args.push_back("-cl-std=CL1.2");
  args.push_back("-cl-kernel-arg-info");
  args.push_back("-fno-builtin");
#if LLVM_VERSION >= 38
  args.push_back("-debug-info-kind=standalone");
#else
  args.push_back("-g");
#endif
  args.push_back("-triple");
  if (sizeof(size_t) == 4)
    args.push_back("spir-unknown-unknown");
  else
    args.push_back("spir64-unknown-unknown");

  // Define extensions
  for (unsigned i = 0; i < sizeof(EXTENSIONS)/sizeof(const char*); i++)
  {
    args.push_back("-D");
    args.push_back(EXTENSIONS[i]);
  }

  // Disable Clang's optimizations.
  // We will manually run optimization passes and legalize the IR later.
  args.push_back("-O0");

  bool optimize = true;
  bool cl12     = true;

  // Add OpenCL build options
  const char *mainOptions = options;
  const char *extraOptions = getenv("OCLGRIND_BUILD_OPTIONS");
  if (!mainOptions)
    mainOptions = "";
  if (!extraOptions)
    extraOptions = "";
  char *tmpOptions = new char[strlen(mainOptions) + strlen(extraOptions) + 2];
  sprintf(tmpOptions, "%s %s", mainOptions, extraOptions);
  for (char *opt = strtok(tmpOptions, " "); opt; opt = strtok(NULL, " "))
  {
    // Ignore options that break PCH
    if (strcmp(opt, "-cl-fast-relaxed-math") != 0 &&
        strcmp(opt, "-cl-finite-math-only") != 0 &&
        strcmp(opt, "-cl-single-precision-constant") &&
        strcmp(opt, "-cl-unsafe-math-optimizations") != 0)
    {
      // Check for optimization flags
      if (strcmp(opt, "-O0") == 0 || strcmp(opt, "-cl-opt-disable") == 0)
      {
        optimize = false;
        continue;
      }
      else if (strncmp(opt, "-O", 2) == 0)
      {
        optimize = true;
        continue;
      }

#if LLVM_VERSION >= 37
      // Clang no longer supports -cl-no-signed-zeros
      if (strcmp(opt, "-cl-no-signed-zeros") == 0)
        continue;
#endif

      // Check for -cl-std flag
      if (strncmp(opt, "-cl-std=", 8) == 0)
      {
        if (strcmp(opt+8, "CL1.2") != 0)
        {
          cl12 = false;
          args.push_back(opt);
        }
        continue;
      }

      args.push_back(opt);
    }
  }

  if (cl12)
  {
    args.push_back("-cl-std=CL1.2");
  }

  // Pre-compiled header
  char *pchdir = NULL;
  char *pch    = NULL;
  if (!checkEnv("OCLGRIND_DISABLE_PCH") && cl12)
  {
    const char *pchdirOverride = getenv("OCLGRIND_PCH_DIR");
    if (pchdirOverride)
    {
      pchdir = strdup(pchdirOverride);
    }
    else
    {
      // Get directory containing library
#if defined(_WIN32) && !defined(__MINGW32__)
      char libpath[4096];
      HMODULE dll;
      if (GetModuleHandleEx(
            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
            GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
            (LPCSTR)&Program::createFromBitcode, &dll) &&
          GetModuleFileName(dll, libpath, sizeof(libpath)))
      {
#else
      Dl_info dlinfo;
      if (dladdr((const void*)Program::createFromBitcode, &dlinfo))
      {
        const char *libpath = dlinfo.dli_fname;
#endif

        // Construct path to PCH directory
        const char *dirend;
#if defined(_WIN32) && !defined(__MINGW32__)
        if ((dirend = strrchr(libpath, '\\')))
#else
        if ((dirend = strrchr(libpath, '/')))
#endif
        {
          const char *includes_relative = "/../include/oclgrind/";
          size_t length = dirend - libpath;
          pchdir = new char[length + strlen(includes_relative) + 1];
          strncpy(pchdir, libpath, length);
          strcpy(pchdir + length, includes_relative);
        }
      }
    }

    if (pchdir)
    {
      // Select precompiled header
      pch = new char[strlen(pchdir) + 20];
      sprintf(pch, "%s/clc%d.pch", pchdir, (sizeof(size_t) == 4 ? 32 : 64));

      // Check if precompiled header exists
      ifstream pchfile(pch);
      if (!pchfile.good())
      {
        buildLog << "WARNING: Unable to find precompiled header:\n"
                 << pch << "\n";
        delete[] pch;
        pch = NULL;
      }
      pchfile.close();
    }
    else
    {
      buildLog << "WARNING: Unable to determine precompiled header path\n";
    }
  }

  if (pch)
  {
    args.push_back("-isysroot");
    args.push_back(pchdir);

    args.push_back("-include-pch");
    args.push_back(pch);
  }
  else
  {
    // Fall back to embedded clc.h
    args.push_back("-include");
    args.push_back(CLC_H_PATH);
  }

  // Append input file to arguments (remapped later)
  args.push_back(REMAP_INPUT);

  // Create diagnostics engine
  clang::DiagnosticOptions *diagOpts = new clang::DiagnosticOptions();
  llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID(
    new clang::DiagnosticIDs());
  clang::TextDiagnosticPrinter *diagConsumer =
    new clang::TextDiagnosticPrinter(buildLog, diagOpts);
  clang::DiagnosticsEngine diags(diagID, diagOpts, diagConsumer);

  // Create compiler instance
  clang::CompilerInstance compiler;
  compiler.createDiagnostics(diagConsumer, false);

  // Create compiler invocation
  clang::CompilerInvocation *invocation = new clang::CompilerInvocation;
  clang::CompilerInvocation::CreateFromArgs(*invocation,
                                            &args[0], &args[0] + args.size(),
                                            compiler.getDiagnostics());
  compiler.setInvocation(invocation);

  // Remap include files
  std::unique_ptr<llvm::MemoryBuffer> buffer;
  compiler.getHeaderSearchOpts().AddPath(REMAP_DIR, clang::frontend::Quoted,
                                         false, true);
  list<Header>::iterator itr;
  for (itr = headers.begin(); itr != headers.end(); itr++)
  {
    buffer = llvm::MemoryBuffer::getMemBuffer(itr->second->m_source, "", false);
    compiler.getPreprocessorOpts().addRemappedFile(REMAP_DIR + itr->first,
                                                   buffer.release());
  }

  // Remap clc.h
  buffer = llvm::MemoryBuffer::getMemBuffer(CLC_H_DATA, "", false);
  compiler.getPreprocessorOpts().addRemappedFile(CLC_H_PATH, buffer.release());

  // Remap input file
  buffer = llvm::MemoryBuffer::getMemBuffer(m_source, "", false);
  compiler.getPreprocessorOpts().addRemappedFile(REMAP_INPUT, buffer.release());

  // Compile
  clang::EmitLLVMOnlyAction action(m_context->getLLVMContext());
  if (compiler.ExecuteAction(action))
  {
    // Retrieve module
    m_module = action.takeModule();

    // Strip debug intrinsics if not in interactive mode
    if (!checkEnv("OCLGRIND_INTERACTIVE"))
    {
      stripDebugIntrinsics();
    }

    // Run optimizations on module
    if (optimize)
    {
      // Initialize pass managers
      llvm::legacy::PassManager modulePasses;
      llvm::legacy::FunctionPassManager functionPasses(m_module.get());
#if LLVM_VERSION < 37
      modulePasses.add(new llvm::DataLayoutPass());
      functionPasses.add(new llvm::DataLayoutPass());
#endif

      // Populate pass managers with -Oz
      llvm::PassManagerBuilder builder;
      builder.OptLevel = 2;
      builder.SizeLevel = 2;
      builder.populateModulePassManager(modulePasses);
      builder.populateFunctionPassManager(functionPasses);

      // Run passes
      functionPasses.doInitialization();
      llvm::Module::iterator fItr;
      for (fItr = m_module->begin(); fItr != m_module->end(); fItr++)
        functionPasses.run(*fItr);
      functionPasses.doFinalization();
      modulePasses.run(*m_module);
    }

    removeLValueLoads();

    m_buildStatus = CL_BUILD_SUCCESS;
  }
  else
  {
    m_buildStatus = CL_BUILD_ERROR;
  }

  // Dump temps if required
  if (checkEnv(ENV_DUMP_SPIR))
  {
    // Temporary directory
#if defined(_WIN32)
    const char *tmpdir = getenv("TEMP");
#else
    const char *tmpdir = "/tmp";
#endif

    // Construct unique output filenames
    size_t sz = snprintf(NULL, 0, "%s/oclgrind_%lX.XX", tmpdir, m_uid) + 1;
    char *tempCL = new char[sz];
    char *tempIR = new char[sz];
    char *tempBC = new char[sz];
    sprintf(tempCL, "%s/oclgrind_%lX.cl", tmpdir, m_uid);
    sprintf(tempIR, "%s/oclgrind_%lX.ll", tmpdir, m_uid);
    sprintf(tempBC, "%s/oclgrind_%lX.bc", tmpdir, m_uid);

    // Dump source
    ofstream cl;
    cl.open(tempCL);
    cl << m_source;
    cl.close();

    if (m_buildStatus == CL_BUILD_SUCCESS)
    {
      // Dump IR
      std::error_code err;
      llvm::raw_fd_ostream ir(tempIR, err, llvm::sys::fs::F_None);
      llvm::AssemblyAnnotationWriter asmWriter;
      m_module->print(ir, &asmWriter);
      ir.close();

      // Dump bitcode
      llvm::raw_fd_ostream bc(tempBC, err, llvm::sys::fs::F_None);
      llvm::WriteBitcodeToFile(m_module.get(), bc);
      bc.close();
    }

    delete[] tempCL;
    delete[] tempIR;
    delete[] tempBC;
  }

  delete[] tmpOptions;
  delete[] pchdir;
  delete[] pch;

  return m_buildStatus == CL_BUILD_SUCCESS;
}

void Program::clearInterpreterCache()
{
  InterpreterCacheMap::iterator itr;
  for (itr = m_interpreterCache.begin(); itr != m_interpreterCache.end(); itr++)
  {
    delete itr->second;
  }
  m_interpreterCache.clear();
}
Example #16
0
//------------------------------------------------------------------------------------
// preprocess the segment list - get first and last counts
int TimeTableAlgorithm(list<TTSegment>& TTS, list<TTSegment>& TTab) throw(Exception)
{
try {
   bool keep;
   int i,beg,end;
   int begcount,endcount;
   list<TTSegment>::iterator ttit,ttjt;
   typedef pair<int,int> seg;
   list<seg> Segs;
   list<seg>::iterator lit,ljt;

   // 0 sort list in order of decreasing metric()
   // 0.5 delete very small segments
   // 0.6 run through the list, finding the smallest begin, and largest end, counts;
   // call these the begin and end counts.
   // 1. run through the sorted list, starting at largest metric(), and pick out
   // first segments which have the begin and/or end counts; add these to TTab
   // and erase from TTS.
   // 2. run through TTS again, starting at the largest metric(); if a segment
   // includes some counts that have not been covered before, than add this
   // to TTab and erase from TTS. Quit when either the entire range from
   // begcount to endcount is covered, a given minimum metric() is reached,
   // or when the end of TTS is reached.
   // 3. if gaps remain in the coverage, these are real gaps in the data and
   // the estimation will have to reset.
   // 4. sort TTab in increasing order. Run through TTab looking for
   // segments which can be removed without generating gaps; remove these.

   // 0. sort in reverse order (largest metric() first)
   // [ list has its own sort sort(TTS.rbegin(),TTS.rend()); ]
   TTS.sort(decreasingMetricSort);

   // 0.5 delete very small segments and output the sorted list
   // 0.6 find begcount and endcount (after deletion)
   begcount = endcount = -1;
   oflog << "Here is the sorted list of segments:" << endl;
   for(i=1,ttit=TTS.begin(); ttit != TTS.end(); i++) {
      oflog << " " << setw(4) << i << *ttit;
      if(ttit->length < 10) {
         oflog << " -- delete this segment: too small";
         ttit = TTS.erase(ttit); // ttit now points to next seg
      }
      else {
         if(begcount < 0 || ttit->start < begcount)
            begcount = ttit->start;
         if(endcount < 0 || ttit->end > endcount)
            endcount = ttit->end;
         ttit++;
      }
      oflog << endl;
   }
   oflog << "End the sorted list; limits : " << begcount << " - " << endcount << endl;

   for(ttit=TTS.begin(); ttit != TTS.end(); ttit++) {
      if(ttit->length < 10) {
      }
   }
   
   // 1.find the begin point
   for(ttit=TTS.begin(); ttit != TTS.end(); ttit++) {
      if(ttit->start == begcount) {
         oflog << "Found the begin time: " << *ttit << endl;
         TTab.push_back(*ttit);
         beg = ttit->end;
         TTS.erase(ttit);
         break;
      }
   }

   if(beg == endcount) {
      // one segment covers it all - done!
      oflog << "One segment covers it all!" << endl;
      end = endcount;
   }
   else {
      // find the end point
      for(ttit=TTS.begin(); ttit != TTS.end(); ttit++) {
         if(ttit->end == endcount) {
            oflog << "Found the   end time: " << *ttit << endl;
            TTab.push_back(*ttit);
            end = ttit->start;
            TTS.erase(ttit);
            break;
         }
      }

      if(TTab.size() != 2) {
         // error, we didn't find the beg and end -- throw?
         return -2;
      }
   }

   // start list of segs with the ones that contain endpoints
   ttit = TTab.begin();
   Segs.push_back(make_pair(ttit->start,ttit->end));
   ttit++;
   if(ttit != TTab.end())
      Segs.push_back(make_pair(ttit->start,ttit->end));

   if(beg >= end) { // two segments cover it all
      if(Segs.size() > 1) {            // TD unsure if the logic is wrong here...
         ljt = lit = Segs.begin();
         ljt++;
         lit->second = ljt->second;
         if(CI.Debug) oflog << "Two segments cover it all: erase seg ("
            << ljt->first << "-" << ljt->second << ")" << endl;
         Segs.erase(ljt);
      }
   }
   else {
      // 2.
      // start with 
      // |======1st Seg======|            gap                 |=====last Seg======|
      //
      // in general, new segs can be added, so Segs looks like this:
      // |===1st Seg===|    gap       |===2nd Seg===|    gap       |===last Seg===|
      //
      // consider 8 cases of new segments from TTS:
      // 1.   |--------------|                               covers end of seg
      // 2.               |-------|                          lies entirely w/in gap
      // 3.                     |--------|                   covers beg of seg
      // 4.         |--------------------|                   covers entire gap
      // 5.                      |----------------------|    covers entire seg
      // 6. covers seg and gap   |-------------------------------------|
      // 7.         |-------------------------------------|  covers gap and seg
      // 8.                               |-----|            lies entirely w/in seg
      //
      // Here is the algorithm:
      // for each new segment extending from b to e
      // for each i in list of segments in list (extending bi to ei) {
      // if(b > ei) skip to the next i
      // if(e > ei) {                              // b <= ei and e > ei
      //    mod seg i so that ei -> e              // case 1,4,7
      //    if(b < bi) mod seg i so that bi -> b   // case 5,6
      //    while (e >= bj) where j > i,
      //       merge segments i and j and delete j // case 4,6,7
      //    keep this segment
      // }
      // else {                                    // b <= ei and e <= ei
      //    if(e >= bi) {
      //       if(b < bi) {
      //          mod segment i so bi -> b         // case 3
      //          keep this segment
      //       }
      //       //else { ignore this segment }      // case 8
      //    }
      //    else {
      //       make a new segment (b,e),
      //          and insert it before segment i   // case 2
      //       keep this segment
      //    }
      // }
      // } // end of loop over segments i
      // if(keep) add this segment to the time table
      // 
      // loop over all segments, in decreasing order of metric()
      for(i=1,ttit=TTS.begin(); ttit != TTS.end(); i++,ttit++) { // i temp

         if(CI.Debug) { // temp
            oflog << "Here is the current time table (" << TTab.size() << ")"
               << endl;
            for(ttjt=TTab.begin(); ttjt != TTab.end(); ttjt++)
               oflog << " " << *ttjt << endl;
         }

         if(CI.Debug) {
            oflog << "and here is the seg list";
            for(lit=Segs.begin(); lit != Segs.end(); lit++)
               oflog << " (" << lit->first << "-" << lit->second << ")";
            oflog << endl;
         }

         // done if one segment covers all
         lit = Segs.begin();
         if(Segs.size() == 1 && lit->first == begcount && lit->second == endcount)
            break;

         // keep this? you don't want metric to become very small -> failure
         if(ttit->metric() <= 100.0) break;        // TD input param

         beg = ttit->start;
         end = ttit->end;
         if(CI.Debug) oflog << "consider new segment ("
            << beg << "-" << end << ")" << endl;

         // loop over the segs
         keep = false;
         lit = Segs.begin();
         while(lit != Segs.end()) {
            if(beg > lit->second) {
               if(CI.Debug) oflog << " skip seg ("
                  << lit->first << "-" << lit->second << ")" << endl;
               lit++;
               continue;
            }
            if(end > lit->second) {
               if(CI.Debug) oflog << " mod 1 seg ("
                  << lit->first << "-" << lit->second << ")";
               lit->second = end;
               if(beg < lit->first) lit->first=beg;
               if(CI.Debug) oflog << " to ("
                  << lit->first << "-" << lit->second << ")" << endl;
               ljt = lit;
               while(++ljt != Segs.end() && end >= ljt->first) {
                  // merge i and j
                  if(CI.Debug) oflog << " merge segs ("
                     << lit->first << "-" << lit->second << ") and ("
                     << ljt->first << "-" << ljt->second << ")";
                  lit->second = ljt->second;
                  if(CI.Debug) oflog << " and erase seg ("
                     << ljt->first << "-" << ljt->second << ")" << endl;
                  Segs.erase(ljt);
                  ljt = lit;
               }
               keep = true;
            }
            else {
               if(end >= lit->first) {
                  if(beg < lit->first) {
                     if(CI.Debug) oflog << " mod 2 seg ("
                        << lit->first << "-" << lit->second << ")";
                     lit->first = beg;
                     keep = true;
                     if(CI.Debug) oflog << " to ("
                        << lit->first << "-" << lit->second << ")" << endl;
                  }
                  //else { keep=false; ignore -- this seg has nothing new }
               }
               else {
                  seg newseg(beg,end);
                  if(CI.Debug) oflog << " add seg ("
                     << newseg.first << "-" << newseg.second << ")" << endl;
                  Segs.insert(lit,newseg);
                  keep = true;
               }
            }
            break;
         }  // end while loop over segs

         if(keep) {
            TTab.push_back(*ttit);
            TTab.sort(startSort);       // temp
         }

         if(CI.Debug) if(i > 100) break;      // temp

      }  // end for loop over segments TTS

   }  // end if(initial gap is non-zero)

   // 3. are there gaps?
   if(Segs.size() != 1) {
      oflog << "There are real gaps in the data; segments with data:" << endl;
      for(lit=Segs.begin(); lit != Segs.end(); lit++)
         oflog << " (" << lit->first << "-" << lit->second << ")";
      oflog << endl;
   }
   else oflog << "There are no gaps in the data" << endl;

   // sort the timetable
   TTab.sort(startSort);

   // TD 4. edit TTab, removing segments that do not create gaps

   // decide on actual transition times
   for(ttit=TTab.begin(); ttit != TTab.end(); ttit++) {
      if(CI.Verbose) oflog << " " << *ttit << endl;

      // compute the count at which to switch
      if(ttit == TTab.begin()) {
         ttit->first = ttit->start;       // first = start for first segment
         ttjt = ttit;                     // initialize ttjt
      }
      else {
         // switch at the mid-point of overlap
         ttit->first = (ttjt->end + ttit->start)/2;
      }
      ttit->last = ttit->end;             // change later, except for last segment
      if(ttit != TTab.begin()) {
         ttjt->last = ttit->first;        // count at the switch point
         ttjt++;                          // ttjt lags behind ttit by 1
      }
   }

   return 0;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
}
Example #17
0
  ~CGroup ()
  {
    for (list < CView * >::iterator i = children.begin ();
	 i != children.end (); i++)
      delete (*i);
  };
Example #18
0
void Playtree::insertItems( VarTree& elem, const list<string>& files, bool start )
{
    bool first = true;
    VarTree* p_elem = &elem;
    playlist_item_t* p_node = NULL;
    int i_pos = -1;

    playlist_Lock( m_pPlaylist );

    if( p_elem == this )
    {
        for( Iterator it = m_children.begin(); it != m_children.end(); ++it )
        {
            if( it->getId() == m_pPlaylist->p_local_category->i_id )
            {
                p_elem = &*it;
                break;
            }
        }
    }

    if( p_elem->getId() == m_pPlaylist->p_local_category->i_id )
    {
        p_node = m_pPlaylist->p_local_category;
        i_pos = 0;
        p_elem->setExpanded( true );
    }
    else if( p_elem->getId() == m_pPlaylist->p_ml_category->i_id )
    {
        p_node = m_pPlaylist->p_ml_category;
        i_pos = 0;
        p_elem->setExpanded( true );
    }
    else if( p_elem->size() && p_elem->isExpanded() )
    {
        p_node = playlist_ItemGetById( m_pPlaylist, p_elem->getId() );
        i_pos = 0;
    }
    else
    {
        p_node = playlist_ItemGetById( m_pPlaylist,
                                       p_elem->parent()->getId() );
        i_pos = p_elem->getIndex();
        i_pos++;
    }

    if( !p_node )
        goto fin;

    for( list<string>::const_iterator it = files.begin();
         it != files.end(); ++it, i_pos++, first = false )
    {
        input_item_t *pItem;

        if( strstr( it->c_str(), "://" ) )
            pItem = input_item_New( it->c_str(), NULL );
        else
        {
            char *psz_uri = vlc_path2uri( it->c_str(), NULL );
            if( psz_uri == NULL )
                continue;
            pItem = input_item_New( psz_uri, NULL );
            free( psz_uri );
        }

        if( pItem == NULL)
            continue;

        int i_mode = PLAYLIST_APPEND;
        if( first && start )
            i_mode |= PLAYLIST_GO;

        playlist_NodeAddInput( m_pPlaylist, pItem, p_node,
                               i_mode, i_pos, pl_Locked );
    }

fin:
    playlist_Unlock( m_pPlaylist );
}
void cElementManager::addElement (const string &name, list<sElementPart *> contents,
    list<string> attlist, map<string, string> attdefault, bool open, bool empty,
    int tag, string flag)
{
  //sanity checks
  if (elementDefined (name))
  {
    results->addToList (results->createError ("Multiple definition of element " + name + "!"));
    return;
  }

  sElement *e = new sElement;
  e->open = open;
  e->empty = empty;
  if ((tag >= 20) && (tag <= 99))
  {
    e->tag = tag;
    if (lineTags.count (tag))
      results->addToList (results->createError ("Element " + name +
          " uses an already assigned line tag!"));
    lineTags[tag] = name;
  }
  else
    e->tag = 0;
  e->flag = flag;

  //assign element contents, generating the list of closing tags
  e->element.clear();
  list<sElementPart *>::iterator it;
  for (it = contents.begin(); it != contents.end(); ++it)
  {
    sElementPart *ep = *it;
    if (ep->istag)
    {
      string tag = lcase (firstword (ep->text));
      if (elementDefined (tag))
      {
        if (open && !(openElement (tag)))
        {
          delete ep;
          results->addToList (results->createError ("Definition of open " + name +
              " tag contains secure tag " + tag + "!"));
        }
        else if (empty && !(emptyElement (tag)))
        {
          delete ep;
          results->addToList (results->createError ("Definition of empty " + name +
              " tag contains non-empty tag " + tag + "!"));
        }
        else
        {
          e->element.push_back (ep);
          if (!emptyElement(tag)) e->closingseq.push_front (tag);
        }
      }
      else
      {
        //element doesn't exist yet - we must believe that it's correct
        e->element.push_back (ep);
        if (!empty) e->closingseq.push_front (tag);
        results->addToList (results->createWarning ("Definition of element " + name +
            " contains undefined element " + tag + "!"));
      }
    }
    else
      e->element.push_back (ep);
  }

  //assign the element definition
  elements[name] = e;

  //set attribute list
  setAttList (name, attlist, attdefault);
}
Example #20
0
int main(int argc, char* args[])
{
  bool quit = false;
  TTF_Font* font;
  SDL_Color textColor = {0, 0, 0};
  SDL_Event event;
  SDL_Surface* text;
  string message;
  int height;

  if (init(480, 640, 32))
    return 0;
  if (winsock_init(&wsaData))
    return 0;

  if(sock.bindSocket(0) < 0)
  {
    exit(WSAGetLastError());
  }
  sock.isBound = true;
  font = TTF_OpenFont("arial.ttf", 16);
  StringInput test(10, 480 - 26, textColor, font);
  text = TTF_RenderText_Solid(font, "Hello", textColor);

  _beginthread(thread, 0, NULL);

  while(quit == false)
  {
    while(SDL_PollEvent(&event))
    {
      test.handle_input(event);

      if(event.type == SDL_QUIT)
      {
        quit = true;
      }
      if(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RETURN)
      {
        if(!hasServerIp)
        {
          strcpy(serverIp, test.getString().c_str());
          test.clear();
          hasServerIp = true;
          conversation.push_back("Enter the port of the server you would like to connect to");
        }
        else if(!hasServerPort)
        {
          serverPort = atoi(test.getString().c_str());
          test.clear();
          hasServerPort = true;
          conversation.push_back("Enter the name you would like to use");
        }
        else if(!hasName)
        {
          strcpy(name, test.getString().c_str());
          test.clear();
          hasName = true;
          conversation.clear();
        }
        else if(test.getString().compare("") != 0)
        {
          ss.str(string());
          ss << "CIM" << test.getString();
          //conversation.push_back(ss.str());
          if(sock.sendMessage(&serverAddr, ss.str()) < 0)
          {
            conversation.push_back("Error");
          }
          test.clear();
        }
      }
    }
    if(hasName && !isConnected)
    {
      memset(&serverAddr, 0, sizeof(serverAddr));
      serverAddr.sin_family = AF_INET;
      serverAddr.sin_addr.s_addr = inet_addr(serverIp);
      serverAddr.sin_port = htons(serverPort);
      ss.str(string());
      ss << "CCIM" << name;
      sock.sendMessage(&serverAddr, ss.str().c_str());
      isConnected = true;
    }

    SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 220, 220, 220));
    height = 10;
    if (conversation.size() > 15)
      conversation.pop_front();
    for (it = conversation.begin(); it != conversation.end(); it++)
    {
      SDL_FreeSurface(text);
      text = TTF_RenderText_Solid(font, it->c_str(), textColor);
      draw_surface(10, height, text, screen);
      height += 26;
    }
    test.show(screen);

    SDL_Flip(screen);
  }

  TTF_CloseFont(font);
  TTF_Quit();
  SDL_Quit();
  sock.close();

  return 0;
}
void cElementManager::processInternalTag (const string &name, const list<sParam> &params,
    const list<string> &flags)
{
  list<sParam>::const_iterator it;
  list<string>::const_iterator it2;
  if (name == "!element")
  {
    string name, definition, att, flag;
    int tag;
    bool fopen = false, fdelete = false, fempty = false;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "name") name = lcase ((*it).value);
      if (s == "definition") definition = (*it).value;
      if (s == "att") att = (*it).value;
      if (s == "flag") flag = (*it).value;
      if (s == "tag") tag = atoi ((*it).value.c_str());
    }
    for (it2 = flags.begin(); it2 != flags.end(); ++it2)
    {  
      if (*it2 == "open") fopen = true;
      if (*it2 == "delete") fdelete = true;
      if (*it2 == "empty") fempty = true;
    }
    
    if (name.empty())
    {
      results->addToList (results->createError (
          "Received an <!element> tag with no element name!"));
      return;
    }
    //definition can be empty, that's no problem...

    //if we want to delete the tag...
    if (fdelete)
    {
      //sanity check
      if (!elements.count (name))
      {
        results->addToList (results->createWarning (
            "Received request to remove an undefined tag " + name + "!"));
        return;
      }
      removeElement (name);
      return;
    }
    
    //parse tag definition
    parser->simpleParse (definition);
    list<sElementPart *> tagcontents;
    while (parser->hasNext ())
    {
      chunk ch = parser->getNext ();
      if (ch.chk == chunkError)
        results->addToList (results->createError (ch.text));
      else
      {
        //create a new element part
        sElementPart *part = new sElementPart;
        part->text = ch.text;
        part->istag = (ch.chk == chunkTag) ? true : false;
        tagcontents.push_back (part);
      }
    }
    
    //parse attribute list
    list<string> attlist;
    map<string, string> attdefault;
    processParamList (att, attlist, attdefault);
    
    //and do the real work
    addElement (name, tagcontents, attlist, attdefault, fopen, fempty, tag, flag);
  }
  else if (name == "!attlist")
  {
    string name, att;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "name") name = (*it).value;
      if (s == "att") att = (*it).value;
    }
    
    if (name.empty())
    {
      results->addToList (results->createError (
          "Received an <!attlist> tag with no element name!"));
      return;
    }

    //parse attribute list
    list<string> attlist;
    map<string, string> attdefault;
    processParamList (att, attlist, attdefault);
    
    //and do the real work
    setAttList (name, attlist, attdefault);
  }
  else if (name == "!entity")
  {
    string name, value, desc;
    bool fpriv = false, fpub = false, fadd = false, fdel = false, frem = false;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "name") name = (*it).value;
      if (s == "value") value = (*it).value;
      if (s == "desc") desc = (*it).value;
    }
    for (it2 = flags.begin(); it2 != flags.end(); ++it2)
    {  
      if (*it2 == "private") fpriv = true;
      if (*it2 == "publish") fpub = true;
      if (*it2 == "delete") fdel = true;
      if (*it2 == "add") fadd = true;
      if (*it2 == "remove") frem = true;
    }
    
    if (name.empty())
    {
      results->addToList (results->createError (
          "Received an <!entity> tag with no variable name!"));
      return;
    }
    
    //fpub is IGNORED...
    //fadd and frem is IGNORED...
    if (!(fadd) && !(frem))
    {
      if (fdel)
      {
        entities->deleteEntity (name);
        if (!fpriv) //do not announce PRIVATE entities
          state->gotVariable (name, "", true);
      }
      else
      {
        //we now have a new variable...
        entities->addEntity (name, value);
        if (!fpriv) //do not announce PRIVATE entities
          state->gotVariable (name, value);
      }
    }
    else
      results->addToList (results->createWarning (
          "Ignored <!ENTITY> tag with ADD or REMOVE flag."));
  }
  else if (name == "var")
  {
    //this is very similar to the !entity handler above...
    
    string name, desc;
    bool fpriv = false, fpub = false, fadd = false, fdel = false, frem = false;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "name") name = (*it).value;
      if (s == "desc") desc = (*it).value;
    }
    for (it2 = flags.begin(); it2 != flags.end(); ++it2)
    {  
      if (*it2 == "private") fpriv = true;
      if (*it2 == "publish") fpub = true;
      if (*it2 == "add") fadd = true;
      if (*it2 == "delete") fdel = true;
      if (*it2 == "remove") frem = true;
    }
    
    if (name.empty())
    {
      results->addToList (results->createError (
          "Received an <var> tag with no variable name!"));
      return;
    }
    
    //fpriv and fpub is IGNORED...
    //fadd and fdel is IGNORED...
    if (!(fadd) && !(fdel))
      state->gotVAR (name);
    else
      results->addToList (results->createWarning ("Ignored <VAR> tag with ADD or REMOVE flag."));
  }
  else if (name == "b")
    state->gotBOLD();
  else if (name == "i")
    state->gotITALIC();
  else if (name == "u")
    state->gotUNDERLINE();
  else if (name == "s")
    state->gotSTRIKEOUT();
  else if (name == "c")
  {
    string fore, back;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "fore") fore = (*it).value;
      if (s == "back") back = (*it).value;
    }
    RGB fg = state->fgColor();
    RGB bg = state->bgColor();
    if (!fore.empty())
      fg = cMXPColors::self()->color (fore);
    if (!back.empty())
      bg = cMXPColors::self()->color (back);
    state->gotCOLOR (fg, bg);
  }
  else if (name == "h")
    state->gotHIGH();
  else if (name == "font")
  {
    string face, fore, back;
    int size = 0;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "face") face = (*it).value;
      if (s == "size") size = atoi ((*it).value.c_str());
      if (s == "color") fore = (*it).value;
      if (s == "back") back = (*it).value;
    }
    if (face.empty())
      face = state->fontFace();
    if (size == 0)
      size = state->fontSize();
    RGB fg = state->fgColor();
    RGB bg = state->bgColor();
    if (!fore.empty())
      fg = cMXPColors::self()->color (fore);
    if (!back.empty())
      bg = cMXPColors::self()->color (back);
    state->gotFONT (face, size, fg, bg);
  }
  else if (name == "p")
    state->gotP();
  else if (name == "br")
    state->gotBR();
  else if (name == "nobr")
    state->gotNOBR();
  else if (name == "sbr")
    state->gotSBR();
  else if (name == "a")
  {
    string href, hint, expire;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "href") href = (*it).value;
      if (s == "hint") hint = (*it).value;
      if (s == "expire") expire = (*it).value;
    }
    state->gotA (href, hint, expire);
  }
  else if (name == "send")
  {
    string href, hint, expire;
    bool prompt = false;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "href") href = (*it).value;
      if (s == "hint") hint = (*it).value;
      if (s == "expire") expire = (*it).value;
    }
    for (it2 = flags.begin(); it2 != flags.end(); ++it2)
      if (*it2 == "prompt") prompt = true;
    state->gotSEND (href, hint, prompt, expire);
  }
  else if (name == "expire")
  {
    string name;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "name") name = (*it).value;
    }
    //name can be empty - all named links shall then expire
    state->gotEXPIRE (name);
  }
  else if (name == "version")
    state->gotVERSION();
  else if (name == "h1")
    state->gotHtag (1);
  else if (name == "h2")
    state->gotHtag (2);
  else if (name == "h3")
    state->gotHtag (3);
  else if (name == "h4")
    state->gotHtag (4);
  else if (name == "h5")
    state->gotHtag (5);
  else if (name == "h6")
    state->gotHtag (6);
  else if (name == "hr")
    state->gotHR();
  else if (name == "small")
    state->gotSMALL();
  else if (name == "tt")
    state->gotTT();
  else if (name == "sound")
  {
    string fname, t, u;
    int v = 0, l = 0, p = 0;  //shall be overridden by defaults...
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "fname") fname = (*it).value;
      if (s == "t") t = (*it).value;
      if (s == "u") u = (*it).value;
      if (s == "v") v = atoi ((*it).value.c_str());
      if (s == "l") l = atoi ((*it).value.c_str());
      if (s == "p") p = atoi ((*it).value.c_str());
    }
    if (fname.empty())
    {
      results->addToList (results->createError ("Received SOUND tag with no file name!"));
      return;
    }
    if ((v < 0) ||  (v > 100))
    {
      results->addToList (results->createWarning ("Ignoring incorrect V param for SOUND tag."));
      v = 100;  //set default value
    }
    if ((l < -1) || (l > 100) || (l == 0))
    {
      results->addToList (results->createWarning ("Ignoring incorrect L param for SOUND tag."));
      l = 1;  //set default value
    }
    if ((p < 0) ||  (p > 100))
    {
      results->addToList (results->createWarning ("Ignoring incorrect P param for SOUND tag."));
      p = 50;  //set default value
    }
    state->gotSOUND (fname, v, l, p, t, u);
  }
  else if (name == "music")
  {
    string fname, t, u;
    int v = 0, l = 0, c = 0;  //shall be overridden by defaults...
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "fname") fname = (*it).value;
      if (s == "t") t = (*it).value;
      if (s == "u") u = (*it).value;
      if (s == "v") v = atoi ((*it).value.c_str());
      if (s == "l") l = atoi ((*it).value.c_str());
      if (s == "c") c = atoi ((*it).value.c_str());
    }
    if (fname.empty())
    {
      results->addToList (results->createError ("Received MUSIC tag with no file name!"));
      return;
    }
    if ((v < 0) ||  (v > 100))
    {
      results->addToList (results->createWarning ("Ignoring incorrect V param for MUSIC tag."));
      v = 100;  //set default value
    }
    if ((l < -1) || (l > 100) || (l == 0))
    {
      results->addToList (results->createWarning ("Ignoring incorrect L param for MUSIC tag."));
      l = 1;  //set default value
    }
    if ((c != 0) && (c != 1))
    {
      results->addToList (results->createWarning ("Ignoring incorrect C param for MUSIC tag."));
      c = 1;  //set default value
    }
    state->gotMUSIC (fname, v, l, (c!=0), t, u);
  }
  else if (name == "gauge")
  {
    string entity, max, caption, color;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "entity") entity = (*it).value;
      if (s == "max") max = (*it).value;
      if (s == "caption") caption = (*it).value;
      if (s == "color") color = (*it).value;
    }
    if (entity.empty())
    {
      results->addToList (results->createError ("Received GAUGE with no entity name!"));
      return;
    }
    RGB c;
    if (color.empty()) color = "white";
    c = cMXPColors::self()->color (color);
    state->gotGAUGE (entity, max, caption, c);
  }
  else if (name == "stat")
  {
    string entity, max, caption;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "entity") entity = (*it).value;
      if (s == "max") max = (*it).value;
      if (s == "caption") caption = (*it).value;
    }
    if (entity.empty())
    {
      results->addToList (results->createError ("Received STAT with no entity name!"));
      return;
    }
    state->gotSTAT (entity, max, caption);
  }
  else if (name == "frame")
  {
    string name, action, title, align;
    int left = 0, top = 0, width = 0, height = 0;
    bool finternal = false, fscroll = false, ffloat = false;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "name") name = (*it).value;
      if (s == "action") action = (*it).value;
      if (s == "title") title = (*it).value;
      if (s == "align") align = (*it).value;
      if (s == "left") left = state->computeCoord ((*it).value.c_str(), true);
      if (s == "top") top = state->computeCoord ((*it).value.c_str(), false);
      if (s == "width") width = state->computeCoord ((*it).value.c_str(), true);
      if (s == "height") height = state->computeCoord ((*it).value.c_str(), false);
    }
    for (it2 = flags.begin(); it2 != flags.end(); ++it2)
    {
      if (*it2 == "internal") finternal = true;
      if (*it2 == "scrolling") fscroll = true;
      if (*it2 == "floating") ffloat = true;
    }
    if (name.empty())
    {
      results->addToList (results->createError ("Received FRAME tag with no frame name!"));
      return;
    }
    state->gotFRAME (name, action, title, finternal, align, left, top, width, height,
        fscroll, ffloat);
  }
  else if (name == "dest")
  {
    string name;
    int x = 0, y = 0;
    bool feol = false, feof = false;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "name") name = (*it).value;
      if (s == "x") x = atoi ((*it).value.c_str());
      if (s == "y") y = atoi ((*it).value.c_str());
    }
    for (it2 = flags.begin(); it2 != flags.end(); ++it2)
    {
      if (*it2 == "eol") feol = true;
      if (*it2 == "eof") feof = true;
    }
    if (name.empty())
    {
      results->addToList (results->createError ("Received DEST tag with no frame name!"));
      return;
    }
    state->gotDEST (name, x, y, feol, feof);
  }
  else if (name == "relocate")
  {
    string name;
    int port = 0;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "name") name = (*it).value;
      if (s == "port") port = atoi ((*it).value.c_str());
    }
    if (name.empty())
    {
      results->addToList (results->createError ("Received RELOCATE tag with no server name!"));
      return;
    }
    if (port == 0)
    {
      results->addToList (results->createError ("Received RELOCATE tag with no server port!"));
      return;
    }
    state->gotRELOCATE (name, port);
  }
  else if (name == "user")
    state->gotUSER();
  else if (name == "password")
    state->gotPASSWORD();
  else if (name == "image")
  {
    string name, url, t, align;
    int h = 0, w = 0, hspace = 0, vspace = 0;
    bool fismap = false;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "fname") name = (*it).value;
      if (s == "url") url = (*it).value;
      if (s == "t") t = (*it).value;
      if (s == "align") align = (*it).value;
      if (s == "h") h = state->computeCoord ((*it).value.c_str(), true, true);
      if (s == "w") w = state->computeCoord ((*it).value.c_str(), false, true);
      if (s == "hspace") hspace = atoi ((*it).value.c_str());
      if (s == "vspace") vspace = atoi ((*it).value.c_str());
    }
    for (it2 = flags.begin(); it2 != flags.end(); ++it2)
      if (*it2 == "ismap") fismap = true;
    if (name.empty())
    {
      results->addToList (results->createError ("Received IMAGE tag with no image name!"));
      return;
    }
    state->gotIMAGE (name, url, t, h, w, hspace, vspace, align, fismap);
  }
  else if (name == "filter")
  {
/*
    string src, dest, name;
    for (it = params.begin(); it != params.end(); ++it)
    {
      string s = (*it).name;
      if (s == "src") src = (*it).value;
      if (s == "dest") dest = (*it).value;
      if (s == "name") name = (*it).value;
    }
    state->gotFILTER (src, dest, name);
*/
    results->addToList (results->createWarning ("Ignoring unsupported FILTER tag."));
  }
}
int main()
{
    int opcion;
    do
    {
        cout<<"Menu de puntajes"<<endl;
        cout<<"1 Ingresar"<<endl;
        cout<<"2 Imprimir"<<endl;
        cout<<"3 Guardar todos"<<endl;
        cout<<"4 Guardar uno solo"<<endl;
        cout<<"5 Cargar todos"<<endl;
        cout<<"6 Cargar uno solo"<<endl;
        cout<<"7 Salir"<<endl;
        cout<<"Opcion: "<<endl;
        cin>>opcion;

        switch(opcion)
        {
            case 1://Ingresar
            {
                string nombre;
                int puntaje;
                cout<<"Nombre: ";
                cin>>nombre;
                cout<<"Puntaje: ";
                cin>>puntaje;
                puntajes.push_back(new Puntaje(nombre,puntaje));
                break;
            }
            case 2://Imprimir
            {
                for(list<Puntaje*>::iterator i = puntajes.begin();
                        i!=puntajes.end();
                        i++)
                    cout<<(*i)->nombre<<": "<<(*i)->puntaje<<endl;
                break;
            }
            case 3://Guardar todos
            {
                ofstream out("puntajes.dat");
                for(list<Puntaje*>::iterator i = puntajes.begin();
                        i!=puntajes.end();
                        i++)
                {
                    string nombre = (*i)->nombre;
                    int puntaje = (*i)->puntaje;
                    out.write(nombre.c_str(),15);
                    out.write((char*)&puntaje,4);
                }
                out.close();
                break;
            }
            case 4://Cargar uno solo
            {
                cout<<"Ingrese la posicion en la lista: "<<endl;
                int pos_lista;
                cin>>pos_lista;
                cout<<"Ingrese la posicion en el archivo: "<<endl;
                int pos_archivo;
                cin>>pos_archivo;

                ofstream out("puntajes.dat");
                out.seekp(pos_archivo*19);

                list<Puntaje*>::iterator it = puntajes.begin();
                for(int i=0;i<pos_lista;i++)
                {
                    it++;
                }

                cout<<(*it)->nombre.c_str()<<endl;
                cout<<(*it)->puntaje<<endl;

                out.write((*it)->nombre.c_str(),15);
                out.write((char*)&(*it)->puntaje,4);
            }
            case 5://Cargar todos
            {
                ifstream in("puntajes.dat");
                in.seekg(0,ios::end);
                int tamano = in.tellg();
                in.seekg(0);
                while(in.tellg()<tamano)
                {
                    char* nombre = new char[15];
                    int puntaje;
                    in.read(nombre,15);
                    if(nombre)
                    in.read((char*)&puntaje,4);
                    puntajes.push_back(new Puntaje(nombre,puntaje));
                }
                break;
            }
            case 6:
            {
                cout<<"Posicion: ";
                int pos_cargar;
                cin>>pos_cargar;

                if(pos_cargar<0)
                {
                    cout<<"Posicion invalida"<<endl;
                    break;
                }

                ifstream in("puntajes.dat");

                in.seekg(0,ios::end);
                if(pos_cargar*19>in.tellg())
                {
                    cout<<"Posicion invalida"<<endl;
                    break;
                }

                in.seekg(0);
                in.seekg(pos_cargar*19);

                char* nombre=new char[15];
                int puntaje;

                in.read(nombre,15);
                in.read((char*)&puntaje,4);

                puntajes.push_back(new Puntaje(nombre,puntaje));
            }
        }

    }while(opcion!=7);

    return 0;
}
Example #23
0
//This is an old way of drawing a network by recursively drawing as
//program descends through the networks.  However, this means
//visiting each node potentially mutliple times, which is pointless
//when we already have a drawlist which was constructed when the command
//to draw was issued and row levels were computed.
void ScribbleDrawingArea::drawrows_old(NNode *curnode,list<NNode*> &seenlist) {
  list<Link*> innodes=curnode->incoming;
  list<Link*>::iterator curlink;
  list<NNode*>::iterator location;
  char text[20];

  Gdk_Font font ( "-*-courier-bold-*-*-*-*-240-*-*-*-*-*-*");
  Gdk_Color blue("blue");
  get_colormap().alloc(blue);
  Gdk_Color black("black");
  get_colormap().alloc(black);
  Gdk_Color red("red");
  get_colormap().alloc(red);

  if (!((curnode->type)==SENSOR))
    {
    for(curlink=innodes.begin();curlink!=innodes.end();++curlink) {
      location=find(seenlist.begin(),seenlist.end(),((*curlink)->in_node));
      //if (location==seenlist.end()) {
	seenlist.push_back((*curlink)->in_node);

	cout<<"Connecting "<<curnode<<" TO "<<((*curlink)->in_node)<<endl;
	

	//Draw the node as a rectangle!
	//gc=get_style()->get_black_gc();
	
	//Only draw each node once, if it hasn't been seen
	if (location==seenlist.end()) {
	  gc.set_foreground(red);
	  pixmap.draw_rectangle (gc,
				 TRUE,
				 ((*curlink)->in_node)->xpos-15, 
				 ((*curlink)->in_node)->ypos-15,
				 30, 30);
	}
	
	if ((*curlink)->weight<0)
	  gc.set_foreground(blue);
	else gc.set_foreground(black);
	gc.set_line_width(floor(fabs(2*((*curlink)->weight))));
	pixmap.draw_line(gc,
			 curnode->xpos,
			 curnode->ypos,
			 ((*curlink)->in_node)->xpos, 
			 ((*curlink)->in_node)->ypos);
	
	//cout<<"Drawing text: "<<((*curlink)->in_node)->node_id<<endl;

	//Label the node
	gc.set_foreground(black);
	itoa(((*curlink)->in_node)->node_id,text);
	//cout<<"len: "<<strlen(text)<<endl;
	pixmap.draw_text      (font,
			       gc,
			       ((*curlink)->in_node)->xpos+15,
			       ((*curlink)->in_node)->ypos+5,
			       text,
			       strlen(text));
			 

	drawrows_old((*curlink)->in_node,seenlist);
	//
    }

    }

}
Example #24
0
    //-----------------------------------------------------------------------
    std::pair<bool, Real> Math::intersects(const Ray& ray, 
        const list<Plane>::type& planes, bool normalIsOutside)
    {
        list<Plane>::type::const_iterator planeit, planeitend;
        planeitend = planes.end();
        bool allInside = true;
        std::pair<bool, Real> ret;
        std::pair<bool, Real> end;
        ret.first = false;
        ret.second = 0.0f;
        end.first = false;
        end.second = 0;


        // derive side
        // NB we don't pass directly since that would require Plane::Side in 
        // interface, which results in recursive includes since Math is so fundamental
        Plane::Side outside = normalIsOutside ? Plane::POSITIVE_SIDE : Plane::NEGATIVE_SIDE;

        for (planeit = planes.begin(); planeit != planeitend; ++planeit)
        {
            const Plane& plane = *planeit;
            // is origin outside?
            if (plane.getSide(ray.getOrigin()) == outside)
            {
                allInside = false;
                // Test single plane
                std::pair<bool, Real> planeRes = 
                    ray.intersects(plane);
                if (planeRes.first)
                {
                    // Ok, we intersected
                    ret.first = true;
                    // Use the most distant result since convex volume
                    ret.second = std::max(ret.second, planeRes.second);
                }
                else
                {
                    ret.first =false;
                    ret.second=0.0f;
                    return ret;
                }
            }
            else
            {
                std::pair<bool, Real> planeRes = 
                    ray.intersects(plane);
                if (planeRes.first)
                {
                    if( !end.first )
                    {
                        end.first = true;
                        end.second = planeRes.second;
                    }
                    else
                    {
                        end.second = std::min( planeRes.second, end.second );
                    }

                }

            }
        }

        if (allInside)
        {
            // Intersecting at 0 distance since inside the volume!
            ret.first = true;
            ret.second = 0.0f;
            return ret;
        }

        if( end.first )
        {
            if( end.second < ret.second )
            {
                ret.first = false;
                return ret;
            }
        }
        return ret;
    }
Example #25
0
//TODO:search all list
list<int> gtRunTimeData::get_fds_by_names(list<string> dst)
{
	list<int> l;

	list<socketEntityValue>::iterator it;	//for local connect and listen's second loop
	list<string>::iterator agu_it;	//
	list<int>::iterator fds_it;	//for local connect and listen's second loop

	// local
	getLock(&localSocketLock);

	for(it=localSocket.begin(); it!= localSocket.end(); it++) {
		for(agu_it=dst.begin(); agu_it!=dst.end(); agu_it++){
			if( it->name == *agu_it ) {
				l.push_back(it->fd);
			}
		}
	}

	releaseLock(&localSocketLock);

	// connect
	getLock(&connectSocketLock);

	for(it=connectSocket.begin(); it!= connectSocket.end(); it++) {
		for(agu_it=dst.begin(); agu_it!=dst.end(); agu_it++){
			list<string> tmp_s=it->clientList;
			for(list<string>::iterator sit=tmp_s.begin(); sit!=tmp_s.end(); sit++) {
				if( *sit  == *agu_it ) {
					l.push_back(it->fd);
					break;
				}
			}
		}
	}

	releaseLock(&connectSocketLock);

	// listen

	map<listenSockKey, list<socketEntityValue> >::iterator pit; //get value from map
	list<socketEntityValue> tList;      //save list<> from map<>'s value

	getLock(&listenSocketLock);

	for(pit = listenSocket.begin(); pit!= listenSocket.end(); pit++) { // map's value, which is a list<socketEntityValue>.
		tList= pit->second;     //get value from iterator
		for(it=tList.begin(); it != tList.end(); it++) {     //get every fd from list
			for(agu_it=dst.begin(); agu_it!=dst.end(); agu_it++){
				list<string> tmp_s=it->clientList;
				for(list<string>::iterator sit=tmp_s.begin(); sit!=tmp_s.end(); sit++) {
					if( *sit == *agu_it ) {
						l.push_back(it->fd);
					}
				}
			}
		}
	}

	releaseLock(&listenSocketLock);
	l.unique();	//remove duplicate ones;

	return l;
}
Example #26
0
void patchPackage(IStream &f) {
	unsigned version, numpatches;
	read_header(f, version, numpatches);

	if (version==1) error("Old patch.  Can be read by deltup <= 0.2.1.  Support removed before popuralized.");
	bool check_md5sums = version==4;
	// if (version<3) error("Old patch.  Cannot apply.  Try 0.2 series of deltup");
	for (unsigned patch = 0; patch < numpatches; ++patch) {
		FileInfo *oldpackage,
			*newpackage;
		oldpackage = new FileInfo(read_filename(f));
		oldpackage->has_md5=check_md5sums;
		if (check_md5sums) f.read(oldpackage->md5, 16);
		newpackage = new FileInfo(read_filename(f));
		newpackage->has_md5=check_md5sums;
		if (check_md5sums) f.read(newpackage->md5, 16);

		oldpackage->uname = getTmpFilename();
		newpackage->uname = getTmpFilename();
		oldpackage->type=read_word(f);
		newpackage->type=read_word(f);
		oldpackage->compression=9;
		newpackage->compression=read_dword(f);
		unsigned flags = read_dword(f);
		oldpackage->pristineName="";
		newpackage->pristineName=(flags&1)?getTmpFilename():"";
		string deltaName = getTmpFilename();
		bool success;
		{
			OFStream o(deltaName);
			unsigned sizeofpatch = read_dword(f);
			success = sizeofpatch && copy_bytes_to_file(f, o, sizeofpatch); //read numleft and copy bytes
		}
		if (flags&1) {
			OFStream o(newpackage->pristineName);
			unsigned sizeofpatch = read_dword(f);
			success = success && sizeofpatch && copy_bytes_to_file(f, o, sizeofpatch); //same as above
		}
		if (version<4 && oldpackage->type==GZIP) //3 had a bug with gzip
			newpackage->pristineName="";
    
		list<FileInfo*>::iterator s;
		for (s = unfinished.begin(); 
			s != unfinished.end() && (oldpackage->name == (*s)->name); 
			++s) ;
		bool isContinue = s != unfinished.end();

		printf("%s -> %s: ", oldpackage->name.c_str(), newpackage->name.c_str());
		fflush(stdout);
		if (!success) error("patch is truncated\n");
    
		oldpackage->dir = " ";
		for (unsigned i = 0; i < oldrepository.size(); ++i) {
			if (fileExists(oldrepository[i]+oldpackage->name)) {
				oldpackage->dir = oldrepository[i];
			}
		}

		success=false;
		if (info_mode) 
			printf("\n");
		else if (oldpackage->dir==" " && !isContinue) 
			printf("couldn't find source to patch.\n");
		else if (!force_overwrite && fileExists(newpackage->fullname())) // && !remove_intermediate) {
			printf("patch already applied.\n");
		else if (!compressionTypeSupported(oldpackage->type))
			printf("Can't uncompress old package.  Upgrade deltup.\n");
		else if (!compressionTypeSupported(newpackage->type))
			printf("Can't re-compress package.  Upgrade deltup.\n");
		else success=true;
		if (!success) continue;
    
		if (isContinue) {
			delete oldpackage;
			oldpackage = *s;
		} else {
			if ((!(flags&2) && !oldpackage->verify_md5(false)) ||
					!oldpackage->unpack()) {
				printf("previous package is corrupt\n");
				continue;
			}
			if ((flags&2) && !oldpackage->verify_md5(true)) {
				printf("previous package is corrupt\n");
				continue;
			}
		}
		int status = apply_patch(oldpackage->uname,
			newpackage->uname,
			deltaName);
		switch (status) {
			case 2: fprintf(stderr, "Unknown delta format used.  Try upgrading deltup\n"); continue;
			case 1: printf("Error applying patch\n"); continue;
		}
		doneTmpFile(deltaName);
		doneTmpFile(oldpackage->uname);
		// if (oldpackage->pristineName) doneTmpFile(oldpackage->pristineName);

		if (remove_intermediate) {
			// invoke_system(4, "mv", f2Name, " ", f1Name, " -f");
			FileInfo *f = newpackage;
			if (isContinue) {
				delete *s;
				unfinished.erase(s);
			}
			unfinished.push_back(f);
		} else finalize_package(*newpackage);

		printf("OK\n");
	}
}
Example #27
0
main()
{
    double caminho[15][15]; //matriz de adjacência

    //Criciúma
    caminho[0][0]     = 9999999;
    caminho[0][1]     = 10.4;
    caminho[0][2]     = 16.9;
    caminho[0][3]     = 10.5;
    caminho[0][4]     = 13;
    caminho[0][5]     = 9999999;
    caminho[0][6]     = 9999999;
    caminho[0][7]     = 18.8;
    caminho[0][8]     = 9999999;
    caminho[0][9]     = 9999999;
    caminho[0][10]    = 9999999;
    caminho[0][11]    = 17.4;
    caminho[0][12]    = 9999999;
    caminho[0][13]    = 36.2;
    caminho[0][14]    = 9999999;

    //Cocal do Sul
    caminho[1][0]     = 9999999;
    caminho[1][1]     = 9999999;
    caminho[1][2]     = 9999999;
    caminho[1][3]     = 9999999;
    caminho[1][4]     = 9999999;
    caminho[1][5]     = 9999999;
    caminho[1][6]     = 9999999;
    caminho[1][7]     = 17.3;
    caminho[1][8]     = 9.2;
    caminho[1][9]     = 9999999;
    caminho[1][10]    = 9999999;
    caminho[1][11]    = 9999999;
    caminho[1][12]    = 9999999;
    caminho[1][13]    = 9999999;
    caminho[1][14]    = 9999999;

    //Forquilhinha
    caminho[2][0]     = 9999999;
    caminho[2][1]     = 9999999;
    caminho[2][2]     = 9999999;
    caminho[2][3]     = 20.5;
    caminho[2][4]     = 9999999;
    caminho[2][5]     = 9999999;
    caminho[2][6]     = 9999999;
    caminho[2][7]     = 9999999;
    caminho[2][8]     = 9999999;
    caminho[2][9]     = 9999999;
    caminho[2][10]    = 9999999;
    caminho[2][11]    = 13.8;
    caminho[2][12]    = 9999999;
    caminho[2][13]    = 26.6;
    caminho[2][14]    = 54.3;

    //Icara
    caminho[3][0]     = 9999999;
    caminho[3][1]     = 9999999;
    caminho[3][2]     = 20.5;
    caminho[3][3]     = 9999999;
    caminho[3][4]     = 9999999;
    caminho[3][5]     = 9999999;
    caminho[3][6]     = 9999999;
    caminho[3][7]     = 15.5;
    caminho[3][8]     = 9999999;
    caminho[3][9]     = 9999999;
    caminho[3][10]    = 9999999;
    caminho[3][11]    = 9999999;
    caminho[3][12]    = 54.3;
    caminho[3][13]    = 37.1;
    caminho[3][14]    = 37.4;

    //Siderópolis
    caminho[4][0]     = 9999999;
    caminho[4][1]     = 9999999;
    caminho[4][2]     = 9999999;
    caminho[4][3]     = 9999999;
    caminho[4][4]     = 9999999;
    caminho[4][5]     = 12.6;
    caminho[4][6]     = 9999999;
    caminho[4][7]     = 9999999;
    caminho[4][8]     = 16.1;
    caminho[4][9]     = 9999999;
    caminho[4][10]    = 9999999;
    caminho[4][11]    = 10.9;
    caminho[4][12]    = 9999999;
    caminho[4][13]    = 9999999;
    caminho[4][14]    = 9999999;

    //Treviso
    caminho[5][0]     = 9999999;
    caminho[5][1]     = 9999999;
    caminho[5][2]     = 9999999;
    caminho[5][3]     = 9999999;
    caminho[5][4]     = 12.6;
    caminho[5][5]     = 9999999;
    caminho[5][6]     = 18.9;
    caminho[5][7]     = 9999999;
    caminho[5][8]     = 9999999;
    caminho[5][9]     = 9999999;
    caminho[5][10]    = 9999999;
    caminho[5][11]    = 9999999;
    caminho[5][12]    = 9999999;
    caminho[5][13]    = 9999999;
    caminho[5][14]    = 9999999;

    //Lauro Muller
    caminho[6][0]     = 9999999;
    caminho[6][1]     = 9999999;
    caminho[6][2]     = 9999999;
    caminho[6][3]     = 9999999;
    caminho[6][4]     = 9999999;
    caminho[6][5]     = 18.9;
    caminho[6][6]     = 9999999;
    caminho[6][7]     = 9999999;
    caminho[6][8]     = 9999999;
    caminho[6][9]     = 13.1;
    caminho[6][10]    = 9999999;
    caminho[6][11]    = 9999999;
    caminho[6][12]    = 9999999;
    caminho[6][13]    = 9999999;
    caminho[6][14]    = 9999999;

    //Morro da Fumaça
    caminho[7][0]     = 9999999;
    caminho[7][1]     = 13.3;
    caminho[7][2]     = 9999999;
    caminho[7][3]     = 15.5;
    caminho[7][4]     = 9999999;
    caminho[7][5]     = 9999999;
    caminho[7][6]     = 9999999;
    caminho[7][7]     = 9999999;
    caminho[7][8]     = 19.9;
    caminho[7][9]     = 9999999;
    caminho[7][10]    = 9;
    caminho[7][11]    = 9999999;
    caminho[7][12]    = 9999999;
    caminho[7][13]    = 9999999;
    caminho[7][14]    = 9999999;

    //Urussanga
    caminho[8][0]     = 9999999;
    caminho[8][1]     = 9.2;
    caminho[8][2]     = 9999999;
    caminho[8][3]     = 9999999;
    caminho[8][4]     = 16.1;
    caminho[8][5]     = 9999999;
    caminho[8][6]     = 9999999;
    caminho[8][7]     = 19.9;
    caminho[8][8]     = 9999999;
    caminho[8][9]     = 18.6;
    caminho[8][10]    = 9999999;
    caminho[8][11]    = 9999999;
    caminho[8][12]    = 9999999;
    caminho[8][13]    = 9999999;
    caminho[8][14]    = 9999999;

    //Orleans
    caminho[9][0]     = 9999999;
    caminho[9][1]     = 9999999;
    caminho[9][2]     = 9999999;
    caminho[9][3]     = 9999999;
    caminho[9][4]     = 9999999;
    caminho[9][5]     = 9999999;
    caminho[9][6]     = 13.1;
    caminho[9][7]     = 9999999;
    caminho[9][8]     = 18.6;
    caminho[9][9]     = 9999999;
    caminho[9][10]    = 9999999;
    caminho[9][11]    = 9999999;
    caminho[9][12]    = 47.1;
    caminho[9][13]    = 9999999;
    caminho[9][14]    = 9999999;

    //Sangao
    caminho[10][0]     = 9999999;
    caminho[10][1]     = 9999999;
    caminho[10][2]     = 9999999;
    caminho[10][3]     = 10.10;
    caminho[10][4]     = 13;
    caminho[10][5]     = 9999999;
    caminho[10][6]     = 9999999;
    caminho[10][7]     = 9;
    caminho[10][8]     = 9999999;
    caminho[10][9]     = 9999999;
    caminho[10][10]    = 9999999;
    caminho[10][11]    = 9999999;
    caminho[10][12]    = 29.2;
    caminho[10][13]    = 57.1;
    caminho[10][14]    = 12.6;

    //Nova Veneza
    caminho[11][0]     = 9999999;
    caminho[11][1]     = 9999999;
    caminho[11][2]     = 13.8;
    caminho[11][3]     = 9999999;
    caminho[11][4]     = 10.9;
    caminho[11][5]     = 9999999;
    caminho[11][6]     = 9999999;
    caminho[11][7]     = 9999999;
    caminho[11][8]     = 9999999;
    caminho[11][9]     = 9999999;
    caminho[11][10]    = 9999999;
    caminho[11][11]    = 9999999;
    caminho[11][12]    = 9999999;
    caminho[11][13]    = 9999999;
    caminho[11][14]    = 9999999;

    //Tubarão
    caminho[12][0]     = 9999999;
    caminho[12][1]     = 9999999;
    caminho[12][2]     = 9999999;
    caminho[12][3]     = 54.3;
    caminho[12][4]     = 9999999;
    caminho[12][5]     = 9999999;
    caminho[12][6]     = 9999999;
    caminho[12][7]     = 9999999;
    caminho[12][8]     = 9999999;
    caminho[12][9]     = 47.1;
    caminho[12][10]    = 29.2;
    caminho[12][11]    = 9999999;
    caminho[12][12]    = 9999999;
    caminho[12][13]    = 9999999;
    caminho[12][14]    = 20.8;

    //Aranranguá
    caminho[13][0]     = 9999999;
    caminho[13][1]     = 9999999;
    caminho[13][2]     = 26.6;
    caminho[13][3]     = 37.1;
    caminho[13][4]     = 9999999;
    caminho[13][5]     = 9999999;
    caminho[13][6]     = 9999999;
    caminho[13][7]     = 9999999;
    caminho[13][8]     = 9999999;
    caminho[13][9]     = 9999999;
    caminho[13][10]    = 57.1;
    caminho[13][11]    = 9999999;
    caminho[13][12]    = 9999999;
    caminho[13][13]    = 9999999;
    caminho[13][14]    = 64.4;
    
    //Jaguaruna
    caminho[14][0]     = 9999999;
    caminho[14][1]     = 9999999;
    caminho[14][2]     = 54.3;
    caminho[14][3]     = 37.4;
    caminho[14][4]     = 9999999;
    caminho[14][5]     = 9999999;
    caminho[14][6]     = 9999999;
    caminho[14][7]     = 9999999;
    caminho[14][8]     = 9999999;
    caminho[14][9]     = 9999999;
    caminho[14][10]    = 14.6;
    caminho[14][11]    = 9999999;
    caminho[14][12]    = 20.8;
    caminho[14][13]    = 64.4;
    caminho[14][14]    = 9999999;

    //leitura txt power builder
    ifstream arq1;
    
    arq1.open("destino.txt", ios::in);
    
    if(!arq1.fail())
    {
        while(!arq1.eof())
        {
            arq1>>destino; //variavel inteiro com a cidade destino

        }

        arq1.close();
    }

    criamap();

    dijkstra(caminho);

    //Com o conjunto N pronto

    ofstream arq2;

    arq2.open("menor_caminho.txt", ios::out);
    if(!arq2.fail())
    {
        for(percorrelista = N.begin(); percorrelista != N.end(); percorrelista++)
        {
            arq2<<*percorrelista<<"\n";

        }
        arq2.close();
    }
    
    
    aux = m.find(destino);
    
    arq2.open("kilometragem.txt", ios::out);
    if(!arq2.fail())
    {
                                  arq2<<aux->second.getkilometragem();
    }
    
    arq2.close();

}
		void notify(T data1 = 0, U data2 = 0)
		{
			for(typename list<Callback<T, U>*>::iterator it = listeners.begin(); it != listeners.end(); it++) {
				(*it)->invoke(*this, data1, data2);
			}
		}
Example #29
0
void ZbiorOsob::show()
{
	for (list<Osoba>::iterator it = lista.begin(); it != lista.end(); ++it)
		cout << it->getImie() << " " << it->getNazw() << " " << it->getPesel() << endl;
}; 
Example #30
0
    const string findJars() {

        static list<string> possible;
        if ( ! possible.size() ) {
            possible.push_back( "./" );
            possible.push_back( "../" );
            
            log(2) << "dbExecCommand: " << dbExecCommand << endl;
            
            string dbDir = dbExecCommand;
#ifdef WIN32
            if ( dbDir.find( "\\" ) != string::npos ){
                dbDir = dbDir.substr( 0 , dbDir.find_last_of( "\\" ) );
            }
            else {
                dbDir = ".";
            }
#else
            if ( dbDir.find( "/" ) != string::npos ){
                dbDir = dbDir.substr( 0 , dbDir.find_last_of( "/" ) );
            }
            else {
                bool found = false;
                
                if ( getenv( "PATH" ) ){
                    string s = getenv( "PATH" );
                    s += ":";
                    pcrecpp::StringPiece input( s );
                    string dir;
                    pcrecpp::RE re("(.*?):");
                    while ( re.Consume( &input, &dir ) ){
                        string test = dir + "/" + dbExecCommand;
                        if ( boost::filesystem::exists( test ) ){
                            while ( boost::filesystem::symbolic_link_exists( test ) ){
                                char tmp[2048];
                                int len = readlink( test.c_str() , tmp , 2048 );
                                tmp[len] = 0;
                                log(5) << " symlink " << test << "  -->> " << tmp << endl;
                                test = tmp;
                                
                                dir = test.substr( 0 , test.rfind( "/" ) );
                            }
                            dbDir = dir;
                            found = true;
                            break;
                        }
                    }
                }
                
                if ( ! found )
                    dbDir = ".";
            }
#endif
            
            log(2) << "dbDir [" << dbDir << "]" << endl;
            possible.push_back( ( dbDir + "/../lib/mongo/" ));
            possible.push_back( ( dbDir + "/../lib64/mongo/" ));
            possible.push_back( ( dbDir + "/../lib32/mongo/" ));
            possible.push_back( ( dbDir + "/" ));
            possible.push_back( ( dbDir + "/lib64/mongo/" ));
            possible.push_back( ( dbDir + "/lib32/mongo/" ));
        }

        for ( list<string>::iterator i = possible.begin() ; i != possible.end(); i++ ) {
            const string temp = *i;
            const string jarDir = ((string)temp) + "jars/";
            
            log(5) << "possible jarDir [" << jarDir << "]" << endl;

            path p(jarDir );
            if ( ! boost::filesystem::exists( p) )
                continue;

            log(1) << "found directory for jars : " << jarDir << endl;
            return temp;
        }

        problem() << "ERROR : can't find directory for jars - terminating" << endl;
        exit(44);
        return 0;

    };