Example #1
0
void socketProcessThread()
{
  fd_set fds; // set of file descriptors to check.
  int nready = 0; // # fd's ready. 
  int fd = 0;
  int maxfd = 0;  // fd's 0 to maxfd-1 checked.
  list<int>::iterator itrList;
  map<int,ProxySock*>::iterator itrMap;
  ProxySock* pProxySock = 0;
  int result = 0;
  struct timeval tv;

  rmFdList.clear();

  while (!bSysStop)
  {
    // Set up polling.
    FD_ZERO(&fds);
    maxfd = 0;
    itrList = gSockFdList.begin();
    for (; itrList!=gSockFdList.end(); itrList++)
    {
      fd = *itrList;
      FD_SET(fd,&fds);
      if (maxfd < fd)
      {
        maxfd = fd;
      }
    }

    if (0 ==  maxfd)
    {
      //there is no socket connected 
      sleep(1);
      continue;
    }
    
    tv.tv_sec = 0; 
    tv.tv_usec = 500;
    maxfd ++;
    nready = select(maxfd, &fds, (fd_set *) 0, (fd_set *) 0,&tv);
    switch (nready) 
    {  
    case -1:  
      //error
      gOsLog<<"select  error:"<<strerror(errno)<<endl;
            break;
    case 0:  
      //timeout 
      continue;
            break;
    default:  
      break;
    }  
    
    if (nready > 0)
    {
      itrList = gSockFdList.begin();
      for (; itrList!=gSockFdList.end(); itrList++)
      {
        fd = *itrList;
        if (FD_ISSET(fd, &fds))
        {
          //fd have something to read
          itrMap = gProxySockMap.find(fd);
              if (gProxySockMap.end()== itrMap)
              {
                rmFdList.push_back(fd);
                //removeSigSock(fd);
                continue;
              }
              pProxySock = itrMap->second;
              if (0 == pProxySock)
              {
                rmFdList.push_back(fd);
                //removeSigSock(fd);
                continue;
              }
              result = pProxySock->receiveData();
              if (RC_CLOSE_SOCKET == result )
              {
            gOsLog<<"fd="<<fd<<",m_fd="<<pProxySock->getFd()<<endl;             
                rmFdList.push_back(fd);
            //removeSigSock(fd);
              }
        }//end of if (FD_ISSET(fd, &fds))
      }//end of for

      if (!rmFdList.empty())
      {
        removeSigSockList();
        rmFdList.clear();
      }
    }//end of if (nready > 1)
  }//end of while
  gOsLog<<"end proxy thread."<<endl;
  return;
}//end of 
Example #2
0
void NiSequence::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) {
	//--BEGIN PRE-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//

	unsigned int block_num;
	NiObject::Read( in, link_stack, info );
	NifStream( name, in, info );
	if ( info.version <= 0x0A010000 ) {
		NifStream( textKeysName, in, info );
		NifStream( block_num, in, info );
		link_stack.push_back( block_num );
	};
	if ( ( info.version >= 0x14030009 ) && ( info.version <= 0x14030009 ) && ( info.userVersion == 131072 ) ) {
		NifStream( unknownInt4, in, info );
		NifStream( unknownInt5, in, info );
	};
	NifStream( numControlledBlocks, in, info );
	if ( info.version >= 0x0A01006A ) {
		NifStream( unknownInt1, in, info );
	};
	controlledBlocks.resize(numControlledBlocks);
	for (unsigned int i1 = 0; i1 < controlledBlocks.size(); i1++) {
		if ( info.version <= 0x0A010000 ) {
			NifStream( controlledBlocks[i1].targetName, in, info );
			NifStream( block_num, in, info );
			link_stack.push_back( block_num );
		};
		if ( info.version >= 0x0A01006A ) {
			NifStream( block_num, in, info );
			link_stack.push_back( block_num );
			NifStream( block_num, in, info );
			link_stack.push_back( block_num );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( block_num, in, info );
			link_stack.push_back( block_num );
			NifStream( controlledBlocks[i1].unknownShort0, in, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( (info.userVersion >= 10) ) ) {
			NifStream( controlledBlocks[i1].priority, in, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( block_num, in, info );
			link_stack.push_back( block_num );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].nodeName, in, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].nodeName, in, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].nodeNameOffset, in, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].propertyType, in, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].propertyType, in, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].propertyTypeOffset, in, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].controllerType, in, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].controllerType, in, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].controllerTypeOffset, in, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].variable1, in, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].variable1, in, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].variable1Offset, in, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].variable2, in, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].variable2, in, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].variable2Offset, in, info );
		};
	};

	//--BEGIN POST-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//
}
Example #3
0
int main( int argc, char **argv ) {

    if ( argc < 2 ) {
        cout << "something wrong" << endl;
        exit(1);
    }
    else {
        read_parameters(argc,argv);
    }
    Timer initialization_timer;

    rnd = new Random((unsigned) time(&t));

    graph = new UndirectedGraph(i_file);

    init_pheromone_trail();

    register int i = 0;
    register int j = 0;
    register int k = 0;
    register int b = 0;

    cout << endl;
    for (int card_counter = cardb; card_counter <= carde; card_counter++) {
        cardinality = card_counter;
        if ((cardinality == cardb) || (cardinality == carde) || ((cardinality % cardmod) == 0)) {
            printf("begin cardinality %d\n",cardinality);

            if (tfile_is_given) {
                if (times.count(cardinality) == 1) {
                    time_limit = times[cardinality];
                }
            }
            vector<double> results;
            vector<double> times_best_found;
            double biar = 0.0;

            int n_of_ants = (int)(((double)((*graph).edges).size()) / ((double)cardinality));
            if (n_of_ants < 15) {
                n_of_ants = 15;
            }
            if (n_of_ants > 50) {
                n_of_ants = 50;
            }

            if (ants.size() > 0) {
                for (list<KCT_Ant*>::iterator anAnt = ants.begin(); anAnt != ants.end(); anAnt++) {
                    delete(*anAnt);
                }
            }
            ants.clear();

            for (i = 0; i < n_of_ants; i++) {
                KCT_Ant* ant = new KCT_Ant();
                ant->initialize(graph,rnd,pheromone,daemon_action);
                ants.push_back(ant);
            }

            for (int trial_counter = 1; trial_counter <= n_of_trials; trial_counter++) {
                printf("begin try %d\n",trial_counter);

                UndirectedGraph* best = NULL;
                UndirectedGraph* newSol = NULL;
                UndirectedGraph* restartBest = NULL;

                double ib_weight = 0.0;
                double rb_weight = 0.0;
                double gb_weight = 0.0;

                Timer timer;

                if ((!(card_counter == cardb)) || (!(trial_counter == 1))) {
                    reset_pheromone_trail();
                    for (list<KCT_Ant*>::iterator ant = ants.begin(); ant != ants.end(); ant++) {
                        (*ant)->restart_reset();
                    }
                }

                int iter = 1;
                double cf = 0.0;
                bool restart = false;
                bool program_stop = false;
                bool bs_update = false;

                while (program_stop == false) {

                    for (list<KCT_Ant*>::iterator ant = ants.begin(); ant != ants.end(); ant++) {
                        for (k = 0; k < cardinality; k++) {
                            (*ant)->step(0.8);
                        }
                        (*ant)->evaluate();
                    }

                    if (!(newSol == NULL)) {
                        delete(newSol);
                    }
                    if (elite_action == "no") {
                        newSol = getBestDaemonSolutionInIteration();
                    }
                    else {
                        KCT_Ant* bestAnt = getBestDaemonAntInIteration();
                        bestAnt->eliteAction();
                        newSol = new UndirectedGraph();
                        newSol->copy(bestAnt->getCurrentDaemonSolution());
                    }

                    if (iter == 1) {
                        best = new UndirectedGraph();
                        printf("best %f\ttime %f\n",newSol->weight(),timer.elapsed_time(Timer::VIRTUAL));
                        best->copy(newSol);
                        restartBest = new UndirectedGraph(newSol);
                        results.push_back(newSol->weight());
                        times_best_found.push_back(timer.elapsed_time(Timer::VIRTUAL));
                        if (trial_counter == 1) {
                            biar = newSol->weight();
                        }
                        else {
                            if (newSol->weight() < biar) {
                                biar = newSol->weight();
                            }
                        }
                    }
                    else {
                        if (restart) {
                            restart = false;
                            restartBest->copy(newSol);
                            if (newSol->weight() < best->weight()) {
                                printf("best %f\ttime %f\n",newSol->weight(),timer.elapsed_time(Timer::VIRTUAL));
                                best->copy(newSol);
                                results[trial_counter-1] = newSol->weight();
                                times_best_found[trial_counter-1] = timer.elapsed_time(Timer::VIRTUAL);
                                if (newSol->weight() < biar) {
                                    biar = newSol->weight();
                                }
                            }
                        }
                        else {
                            if (newSol->weight() < restartBest->weight()) {
                                restartBest->copy(newSol);
                            }
                            if (newSol->weight() < best->weight()) {
                                printf("best %f\ttime %f\n",newSol->weight(),timer.elapsed_time(Timer::VIRTUAL));
                                best->copy(newSol);
                                results[trial_counter-1] = newSol->weight();
                                times_best_found[trial_counter-1] = timer.elapsed_time(Timer::VIRTUAL);
                                if (newSol->weight() < biar) {
                                    biar = newSol->weight();
                                }
                            }
                        }
                    }

                    cf = get_cf(newSol);
                    //cout << "cf: " << cf << endl;

                    if (bs_update && (cf > 0.99)) {
                        //cout << "doing restart" << endl;
                        bs_update = false;
                        restart = true;
                        cf = 0.0;
                        reset_pheromone_trail();
                    }
                    else {

                        if (cf > 0.99) {
                            bs_update = true;
                        }

                        if (!bs_update) {
                            if (cf < 0.7) {
                                l_rate = 0.15;
                                ib_weight = 2.0/3.0;
                                rb_weight = 1.0/3.0;
                                gb_weight = 0.0;
                            }
                            if ((cf >= 0.7) && (cf < 0.95)) {
                                l_rate = 0.1;
                                ib_weight = 1.0 / 3.0;
                                rb_weight = 2.0 / 3.0;
                                gb_weight = 0.0;
                            }
                            if (cf >= 0.95) {
                                l_rate = 0.05;
                                ib_weight = 0.0;
                                rb_weight = 1.0;
                                gb_weight = 0.0;
                            }
                        }
                        else {
                            // if bs_update = TRUE we use the best_so_far solution for updating the pheromone values
                            l_rate = 0.1;
                            ib_weight = 0.0;
                            rb_weight = 0.0;
                            gb_weight = 1.0;
                        }

                        map<Edge*,double>* trans_best = translate_solution(best);
                        map<Edge*,double>* trans_newSol = translate_solution(newSol);
                        map<Edge*,double>* trans_restartBest = translate_solution(restartBest);
                        map<Edge*,double>* new_pd = new map<Edge*,double>;
                        for (list<Edge*>::iterator e = (graph->edges).begin(); e != (graph->edges).end(); e++) {
                            (*new_pd)[*e] = 0.0;
                            (*new_pd)[*e] = (*new_pd)[*e] + (ib_weight * (*trans_newSol)[*e]) + (rb_weight * (*trans_restartBest)[*e]) + (gb_weight * (*trans_best)[*e]);
                        }
                        for (list<Edge*>::iterator e = (graph->edges).begin(); e != (graph->edges).end(); e++) {
                            (*pheromone)[*e] = (*pheromone)[*e] + (l_rate * ((*new_pd)[*e] - (*pheromone)[*e]));
                            if ((*pheromone)[*e] > tau_max) {
                                (*pheromone)[*e] = tau_max;
                            }
                            if ((*pheromone)[*e] < tau_min) {
                                (*pheromone)[*e] = tau_min;
                            }
                        }
                        delete(trans_best);
                        delete(trans_newSol);
                        delete(trans_restartBest);
                        delete(new_pd);
                    }

                    for (list<KCT_Ant*>::iterator i = ants.begin(); i != ants.end(); i++) {
                        (*i)->reset();
                    }

                    iter = iter + 1;

                    if (tfile_is_given) {
                        if (timer.elapsed_time(Timer::VIRTUAL) > time_limit) {
                            program_stop = true;
                        }
                    }
                    else {
                        if (time_limit_given && iter_limit_given) {
                            if ((timer.elapsed_time(Timer::VIRTUAL) > time_limit) || (iter > n_of_iter)) {
                                program_stop = true;
                            }
                        }
                        else {
                            if (time_limit_given) {
                                if (timer.elapsed_time(Timer::VIRTUAL) > time_limit) {
                                    program_stop = true;
                                }
                            }
                            else {
                                if (iter > n_of_iter) {
                                    program_stop = true;
                                }
                            }
                        }
                    }
                }
                printf("end try %d\n",trial_counter);

                // eturetken 18.09.09. Write the best MST for this cardinality to the file.
                ////////////////////////////////////////////////////////////////////
                if( mstfile_is_given )
                {
                    string MSTFile(mst_file);
                    best->Write2File(concatIntToString(MSTFile, card_counter) + ".mst");
                }
                ////////////////////////////////////////////////////////////////////

                delete(best);
                delete(restartBest);
                delete(newSol);
            }

            double r_mean = 0.0;
            double t_mean = 0.0;
            for (int i = 0; i < results.size(); i++) {
                r_mean = r_mean + results[i];
                t_mean = t_mean + times_best_found[i];
            }
            r_mean = r_mean / ((double)results.size());
            t_mean = t_mean / ((double)times_best_found.size());
            double rsd = 0.0;
            double tsd = 0.0;
            for (int i = 0; i < results.size(); i++) {
                rsd = rsd + pow(results[i]-r_mean,2.0);
                tsd = tsd + pow(times_best_found[i]-t_mean,2.0);
            }
            rsd = rsd / ((double)(results.size()-1.0));
            if (rsd > 0.0) {
                rsd = sqrt(rsd);
            }
            tsd = tsd / ((double)(times_best_found.size()-1.0));
            if (tsd > 0.0) {
                tsd = sqrt(tsd);
            }
            if (output_file_given == true) {
                fout << cardinality << "\t" << r_mean << "\t" << rsd << "\t" << t_mean << "\t" << tsd << endl;
            }
            else {
                printf("statistics\t%d\t%g\t%f\t%f\t%f\t%f\n",cardinality,biar,r_mean,rsd,t_mean,tsd);
            }
            printf("end cardinality %d\n",cardinality);
        }
    }
    if (output_file_given == true) {
        fout.close();
    }
    delete(graph);
    delete rnd;
}
Example #4
0
///-1:失败;0:help;1:成功
int parseArg(int argc, char**argv)
{
	ZkGetOpt cmd_option(argc, argv, "H:n:a:o:v:hr");
    int option;
    while( (option = cmd_option.next()) != -1)
    {
        switch (option)
        {
        case 'h':
            printf("delete zookeeper node.\n");
			printf("%s  -H host:port -n node [-a usr:passwd] [-v verion] [-o output file] [-r]\n", argv[0]);
			printf("-H: zookeeper's host:port\n");
            printf("-n: node name to create, it's full path.\n");
			printf("-a: auth user's user:passwd. it can be multi.\n");
			printf("-v: node's version\n");
			printf("-o: output file, default is stdout\n");
			printf("-r: recursive to delete child.\n");
            printf("-h: help\n");
            return 0;
        case 'H':
            if (!cmd_option.opt_arg() || (*cmd_option.opt_arg() == '-'))
            {
                printf("-H requires an argument.\n");
                return -1;
            }
            g_strHost = cmd_option.opt_arg();
            break;
        case 'n':
            if (!cmd_option.opt_arg() || (*cmd_option.opt_arg() == '-'))
            {
                printf("-n requires an argument.\n");
                return -1;
            }
            g_strNode = cmd_option.opt_arg();
            break;
		case 'a':
			if (!cmd_option.opt_arg() || (*cmd_option.opt_arg() == '-'))
			{
				printf("-a requires an argument.\n");
				return -1;
			}
			g_auth.push_back(cmd_option.opt_arg());
			break;
		case 'v':
			if (!cmd_option.opt_arg() || (*cmd_option.opt_arg() == '-'))
			{
				printf("-l requires an argument.\n");
				return -1;
			}
			g_version = atoi(cmd_option.opt_arg());
			break;
		case 'o':
			if (!cmd_option.opt_arg() || (*cmd_option.opt_arg() == '-'))
			{
				printf("-o requires an argument.\n");
				return -1;
			}
			g_strOut = cmd_option.opt_arg();
			break;
		case 'r':
			g_recursive = true;
			break;
        case ':':
            printf("%c requires an argument.\n", cmd_option.opt_opt ());
            return -1;
        case '?':
            break;
        default:
            printf("Invalid arg %s.\n", argv[cmd_option.opt_ind()-1]);
            return -1;
        }
    }
    if (-1 == option)
    {
        if (cmd_option.opt_ind()  < argc)
        {
            printf("Invalid arg %s.\n", argv[cmd_option.opt_ind()]);
            return -1;
        }
    }
    if (!g_strHost.length())
    {
        printf("No host, set by -H\n");
        return -1;
    }
	if (!g_strNode.length())
	{
		printf("No node, set by -n\n");
		return -1;
	}
    return 1;
}
Example #5
0
void parser(const char* fileName, 
            list<Rec*>& recListx, 
            list<Rec*>& recListy, 
            list<Shape*>& shapeList, 
            string key)
{
    ifstream ifs;
    ifs.open(fileName);
    assert(ifs);

    string sTemp;
    getline(ifs, sTemp);  
    getline(ifs, sTemp);  
    getline(ifs, sTemp);  
    getline(ifs, sTemp);  
    getline(ifs, sTemp);  
    getline(ifs, sTemp);  

    ifs >> sTemp;
    assert(sTemp == key);

    while(sTemp == key)
    {
        getline(ifs, sTemp);
        getline(ifs, sTemp);
        getline(ifs, sTemp);

        ifs >> sTemp >> sTemp;
        assert(sTemp == "5");
        double x1,x2,x3,x4;
        double y1,y2,y3,y4;

        ifs >> x1 >> y1;
        ifs >> x2 >> y2;
        ifs >> x3 >> y3;
        ifs >> x4 >> y4;

        Rec* recTemp = new Rec(x1,x2,x3,x4,y1,y2,y3,y4);
        recListx.push_back(recTemp);
        recListy.push_back(recTemp);

        ifs >> sTemp >> sTemp;
        ifs >> sTemp >> sTemp;
    }

    recListx.sort(compx);
    recListy.sort(compy);

    recIter1 = recListx.begin(); 
    recIter2 = recListx.begin();
    
    //add neighbor in x direction
    while (recIter1 != recListx.end()) 
    {
        ++recIter2;
        while (recIter2 != recListx.end() && 
               (*recIter2) -> get_x1() <= (*recIter1) -> get_x3())
        {
            if(fabs((*recIter1) -> get_y1() - (*recIter2) -> get_y3()) == 0 || 
               fabs((*recIter1) -> get_y3() - (*recIter2) -> get_y1()) == 0)
            {
                (*recIter2) -> addNeighbor(*recIter1);
                (*recIter1) -> addNeighbor(*recIter2);
            }
            ++recIter2;
        }
        ++recIter1;
        recIter2 = recIter1;
    }
    
    recIter1 = recListy.begin();
    recIter2 = recListy.begin();
    
    //add neighbor in y direction
    while (recIter1 != recListy.end())
    {
        ++recIter2;
        while (recIter2 != recListy.end() && 
               (*recIter2) -> get_y1() <= (*recIter1) -> get_y3())
        {
            if(fabs((*recIter1) -> get_x1() - (*recIter2) -> get_x3()) == 0 ||
               fabs((*recIter1) -> get_x3() - (*recIter2) -> get_x1()) == 0)
            {
                (*recIter2) -> addNeighbor(*recIter1);
                (*recIter1) -> addNeighbor(*recIter2);
            }
            ++recIter2;
        }
        ++recIter1;
        recIter2 = recIter1;
    }
    
    //create shape
    queue<Rec*> bfs;
    
    for (recIter1 = recListx.begin(); recIter1 != recListx.end(); recIter1++)
    {
        if ((*recIter1) -> get_visit() == false)
        {
            Shape* stemp;
            stemp = new Shape;
            
            (*recIter1) -> set_visit(true);
            
            stemp -> set_ymin((*recIter1) -> get_y1());
            stemp -> set_ymax((*recIter1) -> get_y3());
            stemp -> set_xmin((*recIter1) -> get_x1());
            stemp -> set_xmax((*recIter1) -> get_x3());
            
            stemp -> addNewRec(*recIter1);
            
            bfs.push((*recIter1));
            long index1=0,index2=1;
            while (bfs.empty() != 1)
            {
                for (int i = 0; i < index2; i++)
                {
                    for (recIter2 = bfs.front() -> getNeighborList().begin(); 
                         recIter2 != bfs.front() -> getNeighborList().end(); 
                         recIter2++)
                    {
                        if ((*recIter2) -> get_visit() == false) {
                            (*recIter2) -> set_visit(true);
                            if ((*recIter2) -> get_y1() < stemp -> get_ymin())
                                stemp -> set_ymin((*recIter2) -> get_y1());
                            if ((*recIter2) -> get_y3() > stemp -> get_ymax())
                                stemp -> set_ymax((*recIter2) -> get_y3());
                            if ((*recIter2) -> get_x1() < stemp -> get_xmin())
                                stemp -> set_xmin((*recIter2) -> get_x1());
                            if ((*recIter2) -> get_x3() > stemp -> get_xmax())
                                stemp -> set_xmax((*recIter2) -> get_x3());
                            
                            bfs.push((*recIter2));
                            stemp -> addNewRec(*recIter2);
                            index1++;
                        }
                    }
                    bfs.pop();
                }
                if(bfs.empty() == 1)break;
                index2 = 0;
                for (int i = 0; i < index1; i++)
                {
                    for (recIter2 = bfs.front() -> getNeighborList().begin(); 
                         recIter2 != bfs.front() -> getNeighborList().end(); 
                         recIter2++)
                    {
                        if ((*recIter2) -> get_visit() == false) {
                            (*recIter2) -> set_visit(true);
                            if ((*recIter2) -> get_y1() < stemp -> get_ymin())
                                stemp -> set_ymin((*recIter2) -> get_y1());
                            if ((*recIter2) -> get_y3() > stemp -> get_ymax())
                                stemp -> set_ymax((*recIter2) -> get_y3());
                            if ((*recIter2) -> get_x1() < stemp -> get_xmin())
                                stemp -> set_xmin((*recIter2) -> get_x1());
                            if ((*recIter2) -> get_x3() > stemp -> get_xmax())
                                stemp -> set_xmax((*recIter2) -> get_x3());
                            
                            bfs.push((*recIter2));
                            stemp -> addNewRec(*recIter2);
                            index2++;
                        }
                    }
                    bfs.pop();
                }
                index1 = 0;
            }
            shapeList.push_back(stemp);
        }
    }
}
Example #6
0
void concatPos(list<int> l1,list<int> &l2){
    for (list<int>::iterator iter = l1.begin();iter != l1.end();iter++){
        l2.push_back(*iter);
    }
}
Example #7
0
bool load_paths_from_db(MYSQL *m, Map *map, const char *zone, list<PathGraph*> &db_paths, list<PathNode*> &end_points) {
	char query[512];
	
	sprintf(query, 
		"SELECT x,y,z,gridid FROM grid_entries,zone "
		"WHERE zone.zoneidnumber=zoneid AND short_name='%s' "
		"ORDER BY gridid,number", zone);
	if(mysql_query(m, query) != 0) {
		printf("Unable to query: %s\n", mysql_error(m));
		return(false);
	}
	
	MYSQL_RES *res = mysql_store_result(m);
	if(res == NULL) {
		printf("Unable to store res: %s\n", mysql_error(m));
		return(false);
	}
	
	MYSQL_ROW row;
	
	PathNode *cur = NULL, *last = NULL, *first = NULL;
	PathGraph *g = NULL;
	int cur_g = -1,last_g = -1;
	
//	int lid = 0;
	
	while((row = mysql_fetch_row(res))) {
		last = cur;
		cur = new PathNode;
//		cur->load_id = lid++;
		cur->x = atof(row[0]);
		cur->y = atof(row[1]);
		cur->z = atof(row[2]);
		cur_g = atoi(row[3]);
		if(cur_g != last_g) {
			if(g != NULL) {
				//if we have a first and last node for this path
				//and they are not the same node, try to connect them.
				if(first != NULL && last != NULL && first != last && last->Dist2(first) < ENDPOINT_CONNECT_MAX_DISTANCE*ENDPOINT_CONNECT_MAX_DISTANCE) {
					if(CheckLOS(map, last, first))
						g->add_edge(last, first);
				}
#ifdef LINK_PATH_ENDPOINTS
				if(first != last && last != NULL)
					end_points.push_back(last);
#endif
				db_paths.push_back(g);
			}
			g = new PathGraph();
			first = cur;
			last_g = cur_g;
			last = NULL;
		}
		
		g->nodes.push_back(cur);
		
#ifdef LINK_PATH_ENDPOINTS
		//this is a begining point
		if(last == NULL)
			end_points.push_back(cur);
#endif
		
		if(last != NULL) {
#ifdef SPLIT_INVALID_PATHS
			if(CheckLOS(map, last, cur)) {
				g->edges.push_back(new PathEdge(last, cur));
			} else {
				//no LOS, split the path into two
				load_split_paths++;
				last_g = -1;	//tell this thing to start over
			}
#else
			g->edges.push_back(new PathEdge(last, cur));
#endif
		}
	}
	
	//handle the last active path
	if(g != NULL) {
		if(first != NULL && cur->Dist2(first) < ENDPOINT_CONNECT_MAX_DISTANCE*ENDPOINT_CONNECT_MAX_DISTANCE) {
			if(CheckLOS(map, cur, first))
				g->add_edge(cur, first);
		}
		db_paths.push_back(g);
	}
	
	mysql_free_result(res);
	return(true);
}
Example #8
0
bool DirNode::genRenameList( list<RenameEl> &renameList, 
	const char *fromP, const char *toP )
{
    uint64_t fromIV = 0, toIV = 0;

    // compute the IV for both paths
    string fromCPart = naming->encodePath( fromP, &fromIV );
    string toCPart = naming->encodePath( toP, &toIV );

    // where the files live before the rename..
    string sourcePath = rootDir + fromCPart;

    // ok..... we wish it was so simple.. should almost never happen
    if(fromIV == toIV)
	return true;

    // generate the real destination path, where we expect to find the files..
    rDebug("opendir %s", sourcePath.c_str() );
	boost::shared_ptr<unix::DIR> dir = boost::shared_ptr<unix::DIR>(
	    unix::opendir( sourcePath.c_str() ), DirDeleter() );
    if(!dir)
	return false;
    
    struct unix::dirent *de = NULL;
    while((de = unix::readdir( dir.get() )) != NULL)
    {
	// decode the name using the oldIV
	uint64_t localIV = fromIV;
	string plainName;

	if((de->d_name[0] == '.') &&
		((de->d_name[1] == '\0') 
		 || ((de->d_name[1] == '.') && (de->d_name[2] == '\0'))))
	{
	    // skip "." and ".."
	    continue;
	}

	try
	{
	    plainName = naming->decodePath( de->d_name, &localIV );
	} catch( rlog::Error &ex )
	{
	    // if filename can't be decoded, then ignore it..
	    continue;
	}

	// any error in the following will trigger a rename failure.
	try
	{
	    // re-encode using the new IV..
	    localIV = toIV;
	    string newName = naming->encodePath( plainName.c_str(), &localIV );
	
    	    // store rename information..
    	    string oldFull = sourcePath + '/' + de->d_name;
    	    string newFull = sourcePath + '/' + newName;

	    RenameEl ren;
	    ren.oldCName = oldFull;
	    ren.newCName = newFull;
	    ren.oldPName = string(fromP) + '/' + plainName;
	    ren.newPName = string(toP) + '/' + plainName;
	    
	    bool isDir;
#if defined(_DIRENT_HAVE_D_TYPE)
	    if(de->d_type != DT_UNKNOWN)
	    {
		isDir = (de->d_type == DT_DIR);
	    } else
#endif
	    {
		isDir = isDirectory( oldFull.c_str() );
	    }

	    ren.isDirectory = isDir;

	    if(isDir)
	    {
		// recurse..  We want to add subdirectory elements before the
		// parent, as that is the logical rename order..
		if(!genRenameList( renameList, 
			    ren.oldPName.c_str(), 
			    ren.newPName.c_str()))
		{
		    return false;
		}
	    }

	    rDebug("adding file %s to rename list",
		    oldFull.c_str());

	    renameList.push_back( ren );

	} catch( rlog::Error &err )
	{
	    // We can't convert this name, because we don't have a valid IV for
	    // it (or perhaps a valid key).. It will be inaccessible..
	    rWarning("Aborting rename: error on file: %s",
		    fromCPart.append(1, '/').append(de->d_name).c_str());
	    err.log( _RLDebugChannel );

	    // abort.. Err on the side of safety and disallow rename, rather
	    // then loosing files..
	    return false;
	}
    }

    return true;
}
Example #9
0
void Options::Parse(int argc, char * argv[])
{
	int lastArgc = 0;
	int currentArgc = 1;
	bool error = true;

	/* Source file */
	if (argc < 2)
		return;
	SourceFile = argv[currentArgc];
	currentArgc++;

	cout << "Found Source " << SourceFile << endl;

	while (lastArgc != currentArgc)
	{
		lastArgc = currentArgc;

		if (argc <= currentArgc)
			break;

		if (string(argv[currentArgc]) == "-o")
		{
			currentArgc++;

			if (argc <= currentArgc)
				break;

			HasOutput = true;
			Output = argv[currentArgc];
			currentArgc++;

			/* All required options have been found */
			error = false;

			cout << "Found Output " << Output << endl;
		}
		else if (string(argv[currentArgc]) == "-q")
		{
			currentArgc++;
			if (argc <= currentArgc)
			{
				error = true;
				break;
			}

			string queryStr(argv[currentArgc]);

			Queries::Query * query = NULL;
			if (queryStr == Queries::Cu::Option)
			{
				query = new Queries::Cu();
				cout << "Found Query CU" << endl;

			}
			else if (queryStr == Queries::Symbol::Option)
			{
				query = new Queries::Symbol();
				cout << "Found Query Symbol" << endl;
			}
			else if (queryStr == Queries::Enum::Option)
			{
				query = new Queries::Enum();
				cout << "Found Query Enum" << endl;
			}
			else
			{
				cout << "Unable to find query for " << queryStr << endl;
			}

			currentArgc++;
			if (query != NULL)
			{
				currentArgc += query->ParseOptions(argc - currentArgc, &argv[currentArgc]);
				Queries.push_back(query);
			}
		}

	}

	if (error)
	{
		cerr << "Unable to parse options" << endl;
		throw exception();
	}
}
Example #10
0
void Select_AutoCaulk(bool bMakeDetail)
{
	Sys_Printf ("Caulking...\n");

	FacesToCaulk.clear();

	int iSystemBrushesSkipped = 0;

	brush_t *next;
	for (brush_t *pSelectedBrush = selected_brushes.next ; pSelectedBrush != &selected_brushes ; pSelectedBrush = next)
	{
		next = pSelectedBrush->next;
		
		if (pSelectedBrush->owner->eclass->fixedsize)
			continue;	// apparently this means it's a model, so skip it...

		// new check, we can't caulk a brush that has any "system/" faces...
		//
		bool bSystemFacePresent = false;
		for (face_t *pSelectedFace = pSelectedBrush->brush_faces; pSelectedFace; pSelectedFace = pSelectedFace->next)
		{				
			if (!strnicmp(pSelectedFace->d_texture->name,"system/",7))
			{
				bSystemFacePresent = true;
				break;
			}
		}
		if (bSystemFacePresent)
		{
			iSystemBrushesSkipped++;
			continue;	// verboten to caulk this.
		}		

		for (int iBrushListToScan = 0; iBrushListToScan<2; iBrushListToScan++)
		{		
			brush_t	*snext;
			for (brush_t *pScannedBrush = (iBrushListToScan?active_brushes.next:selected_brushes.next); pScannedBrush != (iBrushListToScan?&active_brushes:&selected_brushes) ; pScannedBrush = snext)
			{
				snext = pScannedBrush->next;

				if ( pScannedBrush == pSelectedBrush)
					continue;
				
				if (pScannedBrush->owner->eclass->fixedsize || pScannedBrush->patchBrush || pScannedBrush->hiddenBrush)
					continue;

		  		if (FilterBrush(pScannedBrush))
					continue;
				
				//face_t *pFace = pScannedBrush->brush_faces;
				if (pScannedBrush->brush_faces->d_texture->bFromShader && (pScannedBrush->brush_faces->d_texture->nShaderFlags & QER_NOCARVE))
					continue;
				
				// basic-reject first to see if brushes can even possibly touch (coplanar counts as touching)
				//
				for (int i=0 ; i<3 ; i++)
				{
					if (pSelectedBrush->mins[i] > pScannedBrush->maxs[i] ||
						pSelectedBrush->maxs[i] < pScannedBrush->mins[i])
					{
						break;
					}
				}
				if (i != 3)
					continue;	// can't be touching

				// ok, now for the clever stuff, we need to detect only those faces that are both coplanar and smaller
				//	or equal to the face they're coplanar with...
				//
				for (pSelectedFace = pSelectedBrush->brush_faces; pSelectedFace; pSelectedFace = pSelectedFace->next)
				{
					winding_t *pSelectedWinding = pSelectedFace->face_winding;

					if (!pSelectedWinding)
						continue;	// freed face, probably won't happen here, but who knows with this program?

	//				SquaredFace_t SelectedSquaredFace;
	//				WindingToSquaredFace( &SelectedSquaredFace, pSelectedWinding);

					for (face_t *pScannedFace = pScannedBrush->brush_faces; pScannedFace; pScannedFace = pScannedFace->next)
					{
						// don't even try caulking against a system face, because these are often transparent and will leave holes
						//
						if (!strnicmp(pScannedFace->d_texture->name,"system/",7))
							continue;

						// and don't try caulking against something inherently transparent...
						//
						if (pScannedFace->d_texture->nShaderFlags & QER_TRANS)
							continue;

						winding_t *pScannedWinding = pScannedFace->face_winding;

						if (!pScannedWinding)
							continue;	// freed face, probably won't happen here, but who knows with this program?

	//					SquaredFace_t ScannedSquaredFace;
	//					WindingToSquaredFace( &ScannedSquaredFace, pScannedWinding);

	/*					if (VectorCompare(ScannedSquaredFace.v3NormalisedRotationVector, SelectedSquaredFace.v3NormalisedRotationVector)
							&& 
							VectorCompare(ScannedSquaredFace.v3NormalisedElevationVector, SelectedSquaredFace.v3NormalisedElevationVector)
							)
	*/
						{
							// brush faces are in parallel planes to each other, so check that their normals
							//	are opposite, by adding them together and testing for zero...
							// (if normals are opposite, then faces can be against/touching each other?)						
							//
							vec3_t v3ZeroTest;
							static vec3_t v3Zero={0,0,0};
							VectorAdd(pSelectedFace->plane.normal,pScannedFace->plane.normal,v3ZeroTest);
							if (VectorCompare(v3ZeroTest,v3Zero))
							{
								// planes are facing each other...
								//
								// coplanar? (this is some maths of Gil's, which I don't even pretend to understand)
								//
								float fTotalDist = 0;
								for (int _i=0; _i<3; _i++)
								{
									fTotalDist += fabs(	DotProduct(pSelectedFace->plane.normal,pSelectedWinding->points[0]) 
														- 
														DotProduct(pSelectedFace->plane.normal,pScannedWinding->points[i])
														);
								}
								//OutputDebugString(va("Dist = %g\n",fTotalDist));
								
								if (fTotalDist > 0.01)
									continue;

								// every point in the selected face must be within (or equal to) the bounds of the
								//	scanned face...
								//
								// work out the bounds first...
								//
								vec3_t v3ScannedBoundsMins, v3ScannedBoundsMaxs;
								ClearBounds (v3ScannedBoundsMins, v3ScannedBoundsMaxs);
								for (int iPoint=0; iPoint<pScannedWinding->numpoints; iPoint++)
								{
									AddPointToBounds( pScannedWinding->points[iPoint], v3ScannedBoundsMins, v3ScannedBoundsMaxs);
								}
								// floor 'em... (or .001 differences mess things up...
								//
								FloorBounds(v3ScannedBoundsMins, v3ScannedBoundsMaxs);

								
								// now check points from selected face...
								//
								bool bWithin = true;
								for (iPoint=0; iPoint < pSelectedWinding->numpoints; iPoint++)
								{
									for (int iXYZ=0; iXYZ<3; iXYZ++)
									{
										float f = floor(pSelectedWinding->points[iPoint][iXYZ] + 0.5);
										if (!
												(
												f >= v3ScannedBoundsMins[iXYZ] 
												&&
												f <= v3ScannedBoundsMaxs[iXYZ]
												)
											 )
										{
											bWithin = false;
										}
									}
								}

								if (bWithin)
								{
									FacesToCaulk.push_back( pair<face_t*, brush_t*>(pSelectedFace,pSelectedBrush));
									
									/*
									OutputDebugString("Pair:\n");
									OutputDebugString(vtos(pSelectedFace->plane.normal));
									OutputDebugString("\n");
									OutputDebugString(vtos(pScannedFace->plane.normal));
									OutputDebugString("\n");

									int z=1;
									*/
								}
							}
						}
					}
				}			
			}
		}
	}

	
	// apply caulk...
	//
	int iFacesCaulked = 0;
	if (FacesToCaulk.size())
	{
		LPCSTR psCaulkName = "system/caulk";
		qtexture_t *pCaulk = Texture_ForName(psCaulkName);

		if (pCaulk)
		{
			//
			// and call some other junk that Radiant wants so so we can use it later...
			//
			texdef_t tex;
			memset (&tex, 0, sizeof(tex));
			tex.scale[0] = 1;
			tex.scale[1] = 1;
			tex.flags = pCaulk->flags;
			tex.value = pCaulk->value;
			tex.contents = pCaulk->contents;
			strcpy (tex.name, pCaulk->name);

			//Texture_SetTexture (&tex);

			for (list< pair < face_t*, brush_t*> >::iterator it = FacesToCaulk.begin(); it!= FacesToCaulk.end(); ++it)
			{
				face_t *pFace = (*it).first;
				brush_t*pBrush= (*it).second;

				memcpy(&pFace->texdef,&tex,sizeof(tex));

				Face_FitTexture(pFace, 1, 1);	// this doesn't work here for some reason... duh.
				Brush_Build(pBrush);

				iFacesCaulked++;
			}		
		}
		else
		{
			Sys_Printf(" Unable to locate caulk texture at: \"%s\"!\n",psCaulkName);
		}
	}

	Sys_Printf("( %d faces caulked )\n",iFacesCaulked);

	if (iSystemBrushesSkipped)
	{
		Sys_Printf("( %d system-faced brushes skipped )\n",iSystemBrushesSkipped);
	}

	if (bMakeDetail)
	{
		Select_MakeDetail( false );
	}

	Sys_UpdateWindows (W_ALL);
}
BOOL CHandleException::HandleAccessException()//处理访问异常部分  内存断点
{
    BOOL                    bRet;
    DWORD                   dwAccessAddr;       //读写地址
    DWORD                   dwAccessFlag;       //读写标志
    BOOL                    isExceptionFromMemPoint = FALSE;    //异常是否由内存断点设置引起,默认为否
    CCPointInfo*            pPointInfo = NULL;                  //命中的断点
    BOOL                    isHitMemPoint = FALSE;

    //EXCEPTION_ACCESS_VIOLATION
    //If this value is zero, the thread attempted to read the inaccessible data.
    //If this value is 1, the thread attempted to write to an inaccessible address.
    //If this value is 8, the thread causes a user-mode data execution prevention (DEP) violation.

    dwAccessFlag = m_DbgInfo.ExceptionRecord.ExceptionInformation[0];
    dwAccessAddr = m_DbgInfo.ExceptionRecord.ExceptionInformation[1];
    //根据 访问地址 到“断点-分页表”中去查找
    //同一个内存分页可能有多个断点
    //如果没有在“断点-分页表”中查找到,则说明这个异常不是断点引起的
    list<CCPointPage*>::iterator it = g_PointPageList.begin();
    int nSize = g_PointPageList.size();

    //遍历链表中每个节点,将每个匹配的“断点-分页记录”都添加到g_ResetMemBp链表中
    for ( int i = 0; i < nSize; i++ )
    {
        CCPointPage* pPointPage = *it;
        //如果在“断点-分页表”中查找到
        //再根据断点表中信息判断是否符合用户所下断点信息
        if (pPointPage->dwPageAddr == (dwAccessAddr & 0xfffff000))//判断触发异常的地址在不在断点表中
        {
            CCResetMemBp *p = new CCResetMemBp;
            p->dwAddr = pPointPage->dwPageAddr;
            p->nID = pPointPage->nPtNum;
            g_ResetMemBp.push_back(p);

            //暂时恢复内存页原来的属性
            BOOL bDoOnce = FALSE;
            if (!bDoOnce)
            {
                //这些操作只需要执行一次
                bDoOnce = TRUE;
                isExceptionFromMemPoint = TRUE;
                TempResumePageProp(pPointPage->dwPageAddr); //暂时恢复页面属性
                //设置单步,在单步中将断点设回
                UpdateContextFromThread();
                m_Context.EFlags |= TF;
                UpdateContextToThread();
            }

            //先找到断点序号对应的断点
            list<CCPointInfo*>::iterator it2 = g_ptList.begin();
            for ( int j = 0; j < g_ptList.size(); j++ )
            {
                pPointInfo = *it2;
                if (pPointInfo->nPtNum == pPointPage->nPtNum)
                {
                    break;
                }
                it2++;
            }

            //再判断是否符合用户所下断点信息,断点类型和断点范围均相符
            if (isHitMemPoint == FALSE)
            {
                if (dwAccessAddr >= (DWORD)pPointInfo->lpPointAddr &&
                        dwAccessAddr < (DWORD)pPointInfo->lpPointAddr +
                        pPointInfo->dwPointLen)
                {
                    if ( pPointInfo->ptAccess == ACCESS ||
                            (pPointInfo->ptAccess == WRITE && dwAccessFlag == 1) )
                    {
                        isHitMemPoint = TRUE;
                        //                             break;
                    }
                }
            }
        }
        it++;
    }

    //如果异常不是由内存断点设置引起,则调试器不处理
    if (isExceptionFromMemPoint == FALSE)
    {
        return FALSE;
    }

    //如果命中内存断点,则暂停,显示相关信息并等待用户输入
    if (isHitMemPoint)
    {
        ShowBreakPointInfo(pPointInfo);
        //显示反汇编代码
        m_lpDisAsmAddr = m_DbgInfo.ExceptionRecord.ExceptionAddress;
        ShowAsmCode();
        ShowRegValue(NULL);

        //等待用户输入
        bRet = FALSE;
        while (bRet == FALSE)
        {
            bRet = WaitForUserInput();
        }
    }
    return TRUE;
}
Example #12
0
// Main function for the program
int main(int argc, char *argv[]){
  list<Binoculus>::iterator iter;
  char const * filename="bv.ini";

  if (GS.ini(filename,0))
    cout << "Warning: could not open bv.ini, using defaults "<<endl;
  GS.inspect();

  // Output the list values, by repeatedly getting the item from
  // the "front" of the list, outputting it, and removing it
  // from the front of the list.

  Binoculus Alice("Alice",-M_PI/4,0,0,GREEN);
  //Binoculus SS("Shy Seeker",-M_PI/4,.56,-.52,OFF);
  Binoculus April("April",0.523599,-.85,-.85,GREEN); //30degrees
  //Binoculus George("George",-.78,-0.85,0.85,OFF);


  globalBvl.push_back (Alice);
  //globalBvl.push_back (SS);
  globalBvl.push_back (April);
  globalNVselect=globalBvl.begin();/// Need to keep at least one item in the list


  /*
  addbeast(-1.5,-1.0,FIXEDLIGHT);
  addbeast(-1.0,-0.5,SHYLIGHTSEEKER);
  addbeast(-0.5,0.0,AGGRESSLIGHTSEEKER);
  addbeast(0.0,0.5,SHYLIGHTPHOBE);
  addbeast(0.5,1.0,PREY);
  addbeast(-2.0,1.0,BRIGHTPREY);
  addbeast(1.0,1.5,PREDATOR);
  addbeast(0.0,0.0,FIXEDLIGHT);
  addbeast(0.0,2.2,FIXEDLIGHT);
  addbeast(2.0,2.2,FIXEDLIGHT);

  ncvselect=bovalist.begin();/// Need to keep at least one item in the list
  */
  // Create constant iterator for list.

  // Iterate through list and output each element.
  /*
  for (iter=bovalist.begin(); iter != bovalist.end(); iter++)
  {
    (*iter).status(1);
  }
  */
  
  //  dographicsstuff();
  char windowtitle[]="Neuro robots";
   glutMaster   = new GlutMaster();    

   Window = new NRWindow(glutMaster,
			       viewwidth, viewheight,    // width, height
			       10, 0,    // initPosition (x,y)
			       windowtitle); // title
   

   glutMaster->CallGlutMainLoop();

  return EXIT_SUCCESS;
}
Example #13
0
void NRWindow::CallBackKeyboardFunc(unsigned char key, int mx, int my)
{
  switch (key) {
  case 'a':/// Add a light
    {
      float yy=(viewheight/2-my)*cameraZ/830.0+cameraY;
      float xx=(mx-viewwidth/2)*cameraZ/830.0+cameraX;
      cout <<"xx="<<xx<<",yy="<<yy<<endl;
      if (xx>GS.worldboundary)xx=GS.worldboundary;
      if (xx<-GS.worldboundary)xx=-GS.worldboundary;
      if (yy>GS.worldboundary)yy=GS.worldboundary;
      if (yy<-GS.worldboundary)yy=-GS.worldboundary;
      Binoculus newvehicle("A",-3*M_PI/4,xx,yy,GREEN); 
      //newbeast.change(FIXEDLIGHT);
      //newbeast.settheta();
      globalBvl.push_back (newvehicle);
      globalNVselect=globalBvl.end();
      globalNVselect--;
      
      //globalNVselect=globalBvl.end()--;
    }
    break;
  case 'b':// not sure what this is for...
    aerialview=true;
    GLfloat gx,gy;
    gx=(*globalNVselect).getx();
    gy=(*globalNVselect).gety();
    break;
  case 'e':/// Erase/delete NCV
      if (globalBvl.size()>1){
        globalBvl.erase(globalNVselect);
        globalNVselect=globalBvl.begin();
      }
      break;
  case 'f':/// rotate world  counter clockwise
      globalphi +=1;
      break;
  case 'g':/// rotate world clockwise
      globalphi +=-1;
      break;
  case 'h':/// help
    GLdouble pmatrix[16],mvmatrix[16];
    //int i;
    cout << "  Braitenberg Vehicle Simulator\n  -----------------------------\n";
    cout << "Version "<<version <<endl;
    glGetDoublev(GL_PROJECTION_MATRIX,pmatrix);
    glGetDoublev(GL_MODELVIEW_MATRIX,mvmatrix);
    cout << "Projection Matrix"<< endl;
    for(int i=0;i<4;i++)
      cout << pmatrix[i]<<"\t"<<pmatrix[i+4]<<"\t"<<pmatrix[i+8]<<"\t"<<pmatrix[i+12]<<endl;
    cout <<endl;
    cout <<"ModelView Matrix"<<endl;
    for(int i=0;i<4;i++)
      cout << mvmatrix[i]<<"\t"<<mvmatrix[i+4]<<"\t"<<mvmatrix[i+8]<<"\t"<<mvmatrix[i+12]<<endl;
    cout <<endl;
    //cout << "x="<<x<<",y="<<y<<endl;
    break;
  case 'i':/// Information on selected vehicle
    (*globalNVselect).info();
    cout << "loop time (mS) ="<<globallooptime<<endl;
    cout << "elapsed time (mS) ="<<globaltime<<endl;
    break;

  case 'l':/// Reload bv.ini
    if (GS.ini("bv.ini",0))
      cout << "Warning: could not open bv.ini, using defaults "<<endl;
    GS.inspect();
    break;

  case 'm':/// Move a light or beast
      {
	float yy=(viewheight/2-my)*cameraZ/830.0+cameraY;
	float xx=(mx-viewwidth/2)*cameraZ/830.0+cameraX;
	(*globalNVselect).relocate(xx,yy);
      }
      break;

  case 'n':/// Select next vehicle
      if (globalBvl.size()>1){
        globalNVselect++;
        if (globalNVselect==globalBvl.end())globalNVselect=globalBvl.begin();
      }
      break;
  case 'p':/// Select previous vehicle
      if (globalBvl.size()>1){
        if (globalNVselect==globalBvl.begin())globalNVselect=globalBvl.end();
        globalNVselect--;
      }
      break;

  case 'r':/// Reset the world
      globalphi = globaltheta=0;
      cameraX=cameraY=0;
      break;
  case 's':/// Select the nearest NCV 
    {
    float yy=(viewheight/2-my)*cameraZ/830.0+cameraY;
    float xx=(mx-viewwidth/2)*cameraZ/830.0+cameraX;
    list<Binoculus>::iterator iter;
    
    float nearest=9999.0;
    float delx,dely,d2;
    for (iter=globalBvl.begin(); iter != globalBvl.end(); iter++){
      delx=(*iter).getx()-xx;
      dely=(*iter).gety()-yy;
      d2=delx*delx+dely*dely;
      if (d2<nearest){globalNVselect=iter;nearest=d2;}
    }
  }
    break;


  case 'q':/// quit
  case 27:///  quit
    exit(1);
    break;
  case 'o':/// currently identical to 'z'
    cameraZ=cameraZ+1.5;
    //    orthratio=orthratio*1.260;
    //changeview();
    break;
  case 'O':/// currently identical to 'Z'
    cameraZ=cameraZ-1.5;
    //orthratio=orthratio/1.260;
    //changeview();
    break;
  case 't':/// rotate towards
    globaltheta +=1;
    break;

  case 'v':/// rotate away
      globaltheta +=-1;
      break;

  case 'x':/// move camera +ve x
    cameraX=cameraX+.5;
    break;
  case 'X':/// move camera -ve x
    cameraX=cameraX-.5;
    break;
  case 'Y':/// move camera -ve y
    cameraY=cameraY-.5;
    break;
  case 'y':/// move camera +ve y
    cameraY=cameraY+.5;
    break;
  case 'Z':/// Camera out
    cameraZ=cameraZ-2;
    if (cameraZ<0)
      cameraZ=1.5;
    //CallBackDisplayFunc();
//    changeview();
    break;
  case 'z':/// Camera in
    cameraZ=cameraZ+2;
    //CallBackDisplayFunc();
    //changeview();
    break;
  case ' ':/// start simulation
    cout << "setting idle to moving" <<endl;
    Window->StartMoving(glutMaster);   // enable idle function
    break;
  case '>':
    if ((*globalNVselect).vehicletype <7)(*globalNVselect).vehicletype++;
    //      (*ncvselect).incncv();
      break;
  case '<':
    if ((*globalNVselect).vehicletype >0)(*globalNVselect).vehicletype--;
    //(*ncvselect).decncv();
      break;
    break;
  case 'A':/// Two letter command
  case 'B':/// Two letter command
  case 'D':/// Two letter command
  case 'L':/// Save the log files
  case 'M':/// Two letter command
  case 'P':/// Two letter command
  case 'R':/// Two letter command
  case 'S':/// Two letter command
  case 'T':/// Two letter command
  case 'U':/// Two letter command
  case 'V':/// Two letter command
  case '1':/// Two letter command
  case '2':/// Two letter command
  case '3':/// Two letter command
  case '4':/// Two letter command
    {
      //globalkbuf.append(""+key);
      globalkbuf +=key;
      //cout << key<<"->"<<globalkbuf<<endl;
      cout << "->"<<globalkbuf<<endl;
      if(globalkbuf.find("RL")!=std::string::npos){ // Reset to a light
	(*globalNVselect).resetstates();
	makealight();
	globalkbuf.clear();
      }
      if(globalkbuf.find("DUMP")!=std::string::npos){ // Dump a matlab file
	writevehiclelogs("pos1.mat",'p',1);
	writevehiclelogs("eye2.mat",'e',2);
	cout <<"Matlab dump"<<endl;
	globalkbuf.clear();
      }
      if(globalkbuf.find("AP")!=std::string::npos){// Aggressive Phobe
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=AGGRESSLIGHTPHOBE;
	(*globalNVselect).name="Aggressive Phobe";
	(*globalNVselect).setEyeDivergence(GS.AggressPhobe.at(6)*M_PI/180,0,0);
	(*globalNVselect).setcolour(BLUE);
	cout <<"found AP"<<endl;
	globalkbuf.clear();
      }
      if(globalkbuf.find("SS")!=std::string::npos){// Shy Seeker
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=SHYLIGHTSEEKER;
	(*globalNVselect).name="Shy Seeker";
	(*globalNVselect).setEyeDivergence(GS.ShySeeker.at(6)*M_PI/180,.5,.15);
	(*globalNVselect).setcolour(BLUE);
	//makeashyseeker();
	cout <<"found SS"<<endl;
	globalkbuf.clear();
      }
      if(globalkbuf.find("SP")!=std::string::npos){// Shy Phobe
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=SHYLIGHTPHOBE;
	(*globalNVselect).name="Shy Phobe";
	(*globalNVselect).setEyeDivergence(GS.ShyPhobe.at(6)*M_PI/180,0,0);
	(*globalNVselect).setcolour(BLUE);
	cout <<"found SP"<<endl;
	globalkbuf.clear();
      }
      if(globalkbuf.find("AS")!=std::string::npos){// Aggressive Seeker
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=AGGRESSLIGHTSEEKER;
	(*globalNVselect).name="Aggressive Seeker";
	(*globalNVselect).setEyeDivergence(GS.AggressSeeker.at(6)*M_PI/180,0,0);
	(*globalNVselect).setcolour(RED);
	cout <<"found DP"<<endl;
	globalkbuf.clear();
      }

      if(globalkbuf.find("DD")!=std::string::npos){// Agressive Seeker (DD)
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=AGGRESSLIGHTSEEKER;
	makeanagressiveseeker();
	cout <<"found AS"<<endl;
	globalkbuf.clear();
      }





      if(globalkbuf.find("DP")!=std::string::npos){// Dumb Prey
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=PREY;
	(*globalNVselect).name="Dumb Prey";
	(*globalNVselect).setEyeDivergence(GS.Prey.at(6)*M_PI/180,0.5,0.15);
	(*globalNVselect).setcolour(BLUE);
	cout <<"found DP"<<endl;
	globalkbuf.clear();
      }
      if(globalkbuf.find("BP")!=std::string::npos){// Bright Prey
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=BRIGHTPREY;
	(*globalNVselect).name="Bright Prey";
	(*globalNVselect).setEyeDivergence(GS.BrightPrey.at(6)*M_PI/180,0.5,0.15);
	(*globalNVselect).setcolour(BLUE);
	cout <<"found BP"<<endl;
	globalkbuf.clear();
      }
      if(globalkbuf.find("PR")!=std::string::npos){// Predator
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=PREDATOR;
	(*globalNVselect).name="Predator";
	(*globalNVselect).setEyeDivergence(GS.Predator.at(6)*M_PI/180,0,0);
	(*globalNVselect).setcolour(RED);
	cout <<"found PR"<<endl;
	globalkbuf.clear();
      }
      if(globalkbuf.find("MS")!=std::string::npos){// Test Vehicle
	cout <<"Machina Specularix\n";
	(*globalNVselect).resetstates();
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=SPECULATRIX;
	(*globalNVselect).name="M.Speculatrix";
	(*globalNVselect).setEyeDivergence(GS.Predator.at(6)*M_PI/180,0,0);
	cout << "eye field set to "<<GS.Predator.at(6)<<"degrees"<<endl;
	//(*globalNVselect).setcolour(RED);
	(*globalNVselect).setcolour(GREEN);
	(*globalNVselect).lefteye.inituniform(1,60*M_PI/180);

	globalkbuf.clear();
      }
      if(globalkbuf.find("TV")!=std::string::npos){// Test Vehicle
	(*globalNVselect).resetstates();
	(*globalNVselect).vehicletype=TESTVEHICLE;
	(*globalNVselect).name="Test Vehicle";
	(*globalNVselect).setEyeDivergence(GS.TestVehicle.at(6)*M_PI/180,0,0);
	(*globalNVselect).setcolour(BLUE);
	cout <<"found TV"<<endl;
	globalkbuf.clear();
      }

    }
    break;
  default:
    cout << "character  " << key << " at "<< mx <<", "<<my<<endl;
    Window->StopMoving(glutMaster);   // stop idle function
    break;
  }
  glutPostRedisplay();// should not need to do this, but if missing then it does not refresh. 
  NRWindow::CallBackDisplayFunc();
}
Example #14
0
int ProxySock::receiveData()
{
  int result = 0;
  if (m_fd < 1)
  {
    gOsLog<<"m_fd="<<m_fd<<endl;
    m_fd = 0;
    return RC_CLOSE_SOCKET; 
  }

  unsigned char tcpBuff;
  int nread = 0;
  nread = recv(m_fd, &tcpBuff, 1, 0);
  // If error or eof, terminate. 
  if(nread < 0)
  {
    gOsLog<<"m_fd="<<m_fd<<",name="<<m_name<<endl;
    gOsLog<<"recv m_fd error:"<<strerror(errno)<<endl;
    m_isDeleteAble = true;
    return RC_CLOSE_SOCKET;
  }
  else if (0 == nread)
  {
    gOsLog<<"nread=0!,m_fd="<<m_fd<<endl;
    m_isDeleteAble = true;
    return RC_CLOSE_SOCKET;
  }
  
  //gOsLog<<"tcpBuff="<<tcpBuff<<endl;
  if (m_isReadHead)
  {
    if (0 == m_readStep && 3 == tcpBuff)
    {
      m_readStep ++;
    }
    else if (1 == m_readStep && 0 == tcpBuff)
    {
      m_readStep++;
    }
    else if (2 == m_readStep )
    {
      m_readStep ++;
      m_lengHigh = tcpBuff;
      //m_readMsgLen = tcpBuff<<8;
      //gOsLog<<"readStep=2,m_lengHigh="<<(int)m_lengHigh<<endl;
    }
    else if (3 == m_readStep )
    {
      m_readStep =0;
      m_lengLow = tcpBuff;
      m_readBuffLen = (m_lengHigh << 8) + m_lengLow ;
      m_recvedMsgLen = m_readBuffLen;
      m_readMsgLen = m_readBuffLen - 4;//len include 03,00,LH,LL
      m_isReadHead = false;
      //gOsLog<<"readStep=3,m_lengLow="<<(int)m_lengLow<<",readMsgLen="<<m_readMsgLen<<endl;
      if (1 > m_readMsgLen || 99999< m_readMsgLen)
      {
        m_readStep = 0;
        m_readMsgLen = 0;
        m_readBuffLen = 0;
        m_recvedMsgLen = 0;
        m_isReadHead = true;
        return result;
      }
      
      if (0 == m_readBuff)
      {
        m_readBuff = new unsigned char[m_readMsgLen+8];
        m_readBuffLen = m_readMsgLen+8;
      }
      else if (m_readBuffLen < (m_readMsgLen+8))
      {
        delete[] m_readBuff;
        m_readBuff = new unsigned char[m_readMsgLen+8];
        m_readBuffLen = m_readMsgLen+8;
        
      }
      m_pReadBuffTmp = m_readBuff;
      *m_pReadBuffTmp++ = 0x03;
      *m_pReadBuffTmp++ = 0x00;
      *m_pReadBuffTmp++ = m_lengHigh;
      *m_pReadBuffTmp++ = m_lengLow;

      //gOsLog<<"readStep=3,m_lengLow="<<m_lengLow<<",readMsgLen="<<m_readMsgLen<<endl;
    }
    else
    {
      m_readStep = 0;
      m_readMsgLen = 0;
      m_readBuffLen = 0;
      m_recvedMsgLen = 0;
      m_isReadHead = true;
      //no use data read
    }
  }
  else if (m_readMsgLen > 0)
  {
    *m_pReadBuffTmp++ = tcpBuff;
    m_readMsgLen --;
    if (0 == m_readMsgLen)
    {
      //read a packge
      m_readStep = 0;
      m_isReadHead = true;
      printSysTime();
      gOsLog<<"read data from: "<<m_name<<endl;     
      if (false == m_isProxySock)
      {
        //this is listened signal socket
        if (0 == m_pairSock)
        {
          onSetUp();
          if (0 == m_pairSock)
          {
            gOsLog<<"m_pairSock is null,close connected socket."<<endl;
            m_isDeleteAble = true;
            return RC_CLOSE_SOCKET;
          }
        }
        if (RC_CLOSE_SOCKET == m_pairSock->sendData(m_readBuff,m_recvedMsgLen))
        {
          result = RC_CLOSE_SOCKET;
        }
        return result;
      }

      //this is proxy socket
      if ('<' == *(m_readBuff+4) && 'M' == *(m_readBuff+5))
      {
        //this is command   
        if ('\0' != *(m_pReadBuffTmp-1))
        {
          *m_pReadBuffTmp = '\0';
        }
        string sMessage = (const char*)(m_readBuff+4);
        gOsLog<<"read message from "<<m_name<<",get="<<sMessage<<endl;
        string sCommand = getTagContent(sMessage,"<Command>","</Command>");
        if ("Close" == sCommand)
        {
          m_isDeleteAble = true;
          return RC_CLOSE_SOCKET;
        }
        else if ("Start" == sCommand)
        {
          string uid =  getTagContent(sMessage,"<UID>","</UID>");
          ProxySock* pProxySock = 0;
          pProxySock = findProxySockByUid(uid);
          if (pProxySock)
          {
            rmFdList.push_back(pProxySock->getFd());
          }
          m_uid = uid;
        }//end of start
        else
        {
          gOsLog<<"unknow command"<<endl;             
        }
      }//end of command 
      else
      {
        //this is signal
        if (0 == m_pairSock)
        {
          gOsLog<<m_name<<" m_pairSock is null,drop the packge."<<endl;
          return result;
        }
        
        if (RC_CLOSE_SOCKET == m_pairSock->sendData(m_readBuff,m_recvedMsgLen))
        {
          result = RC_CLOSE_SOCKET;
        }
        return result;
      }//end of proxy signal
    }//end of process msg
  }
  else
  {
    m_readStep = 0;
    m_readMsgLen = 0;
    m_readBuffLen = 0;
    m_recvedMsgLen = 0;
    m_isReadHead = true;
  }
  return result;
}
void ScimBridgeAgentClientListenerImpl::push_message (ScimBridgeMessage *message)
{
    received_messages.push_back (message);
}
chrono::microseconds algoritmo(unsigned int n, unsigned int m, unsigned int costoTotal, vector< list<Arista> > aristasDeCadaVertice, vector< list<Arista> > aristasDeCadaVerticeAGM, set<Arista, comparacionArista> aristasGrafo, set<Vertice> verticesAGM, set<Arista, comparacionArista> aristasAGM, set<Arista, comparacionArista> aristasCandidatasAGM, list<Arista> aristasAnillo) 
{
    auto start_time = chrono::high_resolution_clock::now();
    // Arranco poniendo el vértice 0 en verticesAGM, y sus aristas en aristasCandidatasAGM
    verticesAGM.insert(0);
    for(auto it = aristasDeCadaVertice[0].begin(); it != aristasDeCadaVertice[0].end(); it++) {
        aristasCandidatasAGM.insert(*it);
    }
    
    while (aristasAGM.size() < n - 1 && aristasCandidatasAGM.size() > 0 ) {
        auto iterAristaMinima = aristasCandidatasAGM.begin();
        Arista a = *iterAristaMinima;
        aristasCandidatasAGM.erase(iterAristaMinima);           
        pair<bool,Vertice> infoIncidencia = a.incideEnDosVertices(verticesAGM);
        if (infoIncidencia.first) {                             
            continue;
        } else {
            Vertice nuevo = infoIncidencia.second;              
            verticesAGM.insert(nuevo);                          
            aristasGrafo.erase(a);                              
            aristasAGM.insert(a);                               
            Vertice otro = a.dameElOtroVertice(nuevo);
            aristasDeCadaVerticeAGM[nuevo].push_back(a);        
            aristasDeCadaVerticeAGM[otro].push_back(a);
            for(auto it = aristasDeCadaVertice[nuevo].begin(); it != aristasDeCadaVertice[nuevo].end(); it++) {
                if (it->incideEnDosVertices(verticesAGM).first) {
                    continue;                                   
                }
                aristasCandidatasAGM.insert(*it);
            }
        }
    }
    
    if ( (aristasAGM.size() < n - 1) || (aristasGrafo.size() == 0)) {
        // No hay solucion
    } else {
        Arista menor = *aristasGrafo.begin();
        aristasAGM.insert(menor);
        for (auto it = aristasAGM.begin(); it != aristasAGM.end(); it++) {
            costoTotal += it->costo();
        }
        Vertice primero = menor.dameVerticeUno();
        Vertice segundo = menor.dameVerticeDos();
        aristasDeCadaVerticeAGM[primero].push_back(menor);
        aristasDeCadaVerticeAGM[segundo].push_back(menor);
        // Tengo que encontrar el circuito simple, esto es, el anillo
        infoVerticeDFS info[n];
        DFS_visit(aristasDeCadaVerticeAGM, info, primero);
        if (info[primero].backEdges.size() != 1) {
            cout << "Hay algo mal, el vertice deberia tener exactamente un back edge." << endl;
        }
        Arista backEdge = info[primero].backEdges.front();
        aristasAnillo.push_back(backEdge);
        aristasAGM.erase(backEdge);
        Vertice actual = backEdge.dameElOtroVertice(primero);
        while (actual != primero) {
            aristasAGM.erase(info[actual].aristaAnterior);
            aristasAnillo.push_back(info[actual].aristaAnterior);
            actual = info[actual].verticeAnterior;
        }
    }
    
    auto end_time = chrono::high_resolution_clock::now();
    chrono::microseconds tiempo = chrono::duration_cast<chrono::microseconds>(end_time - start_time);
    return tiempo;
}
Example #17
0
void concat(list<int> & l1,list<int> l2){
    for (list<int>::iterator iter = l2.begin();iter != l2.end();iter++){
        l1.push_back(*iter);
    }
}
Example #18
0
int main(int argc, char **argv)
{
  int i,j, rc;
  struct Try_login_arg_by_pwd *workarg = NULL;
  struct ip_node  *pIP = NULL;
  struct user_node *pUser = NULL;
  struct  workarg_queue *record_node = NULL;
  
  if (strcmp(argv[1],"-help") == 0)
  {
    show_help();
    return 0;
  }
  
  if (checkSetting(argc, argv, &setting) < 0)
  {
    fprintf(stderr, "Options Error \n");
    return -1;
  }
  
  if (analysisSetting(&setting, &IP_List, &User_List) < 0)
  {
    return -1;
  }
  
  if (IP_List.count <= 0)
  {
    free_ip_list(&IP_List);
    free_user_list(&User_List);
    
    free_setting(&setting);
    return -1;
  }
  /*
   *    if (pool_init(setting.thread_num) < 0)
   *    {
   *	free_ip_list(&IP_List);
   *        free_user_list(&User_List);
   *        free_setting(&setting);
   *		fprintf(stderr,"Init thread pool error!!\n");
   *		return -2;
}	
*/
  
  (void)signal(SIGINT, ouch);
  gcrypt_fix();
  rc = libssh2_init (0);
  if (rc != 0) {
    free_ip_list(&IP_List);
    free_user_list(&User_List);
    free_setting(&setting);
    fprintf (stderr, "libssh2 initialization failed (%d)\n", rc);       
    return -1;
  }
  workarg = (struct Try_login_arg_by_pwd *)malloc(sizeof(struct Try_login_arg_by_pwd) * IP_List.count* User_List.count);
  
  
  record_node = (struct  workarg_queue *)malloc(sizeof(struct workarg_queue));
  if (record_node == NULL)
  {
    free_ip_list(&IP_List);
    free_user_list(&User_List);
    free_setting(&setting);;
    return -1;
  }
  record_node->level = 1; 
  record_node->point = (void *)workarg;
  
  pthread_mutex_lock(&(setting.setting_mutex));
  
  record_node->next = setting.workarg_list_head;
  setting.workarg_list_head = record_node;
  
  pthread_mutex_unlock(&(setting.setting_mutex));
  
  time_t rawtime;
  struct tm * timeinfo;
  
  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Start Current local time and date: %s\n", asctime (timeinfo) );  
  pUser = User_List.head;
  //int max_conn = 0;
  ip_conn = vector<int>(IP_List.count,0);
  for (i = 0; i < User_List.count; ++i)
  {
    pIP = IP_List.head;
    for (j = 0; j < IP_List.count; ++j)
    {
  
      while (thread_list.size() >= setting.thread_num)
      {
	
	     sleep(1);
      }
      
      pthread_t temp_thread;
      struct Try_login_arg_by_pwd * pWorkarg_node = new Try_login_arg_by_pwd();
      
      pWorkarg_node->port  = setting.port;
      pWorkarg_node->user = (*pUser).user;
      pWorkarg_node->password = (*pUser).password;
      pWorkarg_node->ip = (*pIP).ip;
      pWorkarg_node->setting = &setting;
      pWorkarg_node->thread_list = &thread_list;
      pWorkarg_node->conn_cnt = &ip_conn;
      pWorkarg_node->ip_ind = j;
      pthread_create(&temp_thread,NULL,&try_login_pwd,(void *)  pWorkarg_node);
      pthread_mutex_lock(&setting.complete_mutex);
      thread_list.push_back(temp_thread);
      pthread_mutex_unlock(&setting.complete_mutex);
      
      
      
      pIP = pIP->next;
      
      
    }
    pUser = pUser->next;
     
    
    
  }
  
  while (thread_list.size() > 0)
  {
    sleep(6);
  }
  
  if (recive == 0)
  {
    //pool_destroy();    
    libssh2_exit();
    free_ip_list(&IP_List);
    free_user_list(&User_List);
    free_setting(&setting);
    
  }
  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Finish Current local time and date: %s", asctime (timeinfo) );    
  
  return 0;
}
Example #19
0
 foreachvalue (const Owned<Store>& store, stores) {
   recovers.push_back(store->recover());
 }
//------------------------------------------------------------------------------
void addDevice(Device *device)
{
    devices.push_back(device);
}
// Helper function used for initial client registration and reregistraion
// of the existing clients. User of the functions have to pass valid
// 'client' reference and 'devName', 'connected' and 'notifier' have to
// be set to valid values.
int pm_register_connect(struct PeripheralManagerClient *client, enum pm_event *state) {
    sp<IServiceManager> sm = defaultServiceManager();
    int64_t devSate, clientId;
    sp<IBinder> service;
    status_t status;

    service = sm->getService(String16("vendor.qcom.PeripheralManager"));
    if (service == NULL) {
        ALOGE("%s get service fail", (const char *)client->devName);
        return -1;
    }

    client->ops = IPeripheralManager::asInterface(service);
    if (client->ops == NULL) {
        ALOGE("%s get interface fail", (const char *)client->devName);
        return -1;
    }

    status = client->ops->registar(client->devName, client->clientName,
                                   client->notifier, &clientId, &devSate);
    if (status != OK) {
        ALOGE("%s registar fail", (const char *)client->devName);
        goto cleanup;
    }

    client->recipient = new ServerDiedNotifier(client);
    if (client->recipient == NULL) {
        ALOGE("%s death notifier fail", (const char *)client->devName);
        goto unregister;
    }

    if (client->ops->asBinder() != NULL) {
            if (client->ops->asBinder()->linkToDeath(client->recipient)) {
                    ALOGE("%s link to binder fail",
                                    (const char *)client->devName);
                    goto unregister;
            }
    }


    // This state track whether client was already successfully
    // connected to server.
    if (client->connected) {
        // Reconnect after server have been restarted
        status = client->ops->connect(clientId);
        if (status != OK) {
            // We will try after a second
            ALOGE("%s connect fail", (const char *)client->devName);
            goto unlink;
        }
    }

    if (state) {
        *state = (enum pm_event) devSate;
    }

    client->id = clientId;

    // Put this client in list of know/valid users.
    mClientsInProcessLock.lock();
    mClientsInProcess.push_back(client);
    mClientsInProcessLock.unlock();

    return 0;

unlink:
    client->ops->asBinder()->unlinkToDeath(client->recipient);
unregister:
    client->ops->unregister(clientId);
cleanup:
    client->id = 0;
    client->ops = NULL;
    client->recipient = NULL;
    return -1;
}
Example #22
0
void extend(vector<vector<char>> &a, list<set<int>> &REZULT, set <int> candidates, set <int> not, set <int> M){
	set <int> K, P;
	int v, SIZE = a[1].size();
	auto theIterator = candidates.begin();
	while ((candidates.size() != 0) && check(a, candidates, not)){
		K.clear();
		P.clear();
		for (auto it = not.begin(); it != not.end(); it++) { P.insert(*it); }
		for (auto it = candidates.begin(); it != candidates.end(); it++) { K.insert(*it); }
		v = *candidates.begin();
		M.insert(v);
		for (int i = 0; i < SIZE; i++)
		{
			if (!a[v][i])
			{
				theIterator = K.find(i);
				if (theIterator != K.end())
				{
					K.erase(theIterator);
				}
				theIterator = P.find(i);
				if (theIterator != P.end())
				{
					P.erase(theIterator);
				}
			}
		}
		theIterator = K.find(v);
		if (theIterator != K.end())
		{
			K.erase(theIterator);
		}
		if ((P.size() == 0) && (K.size() == 0))
		{
			REZULT.push_back(M);
			//if (REZULT.size()%100==0)
			//	cout << M.size() << " ";
			if (M.size() >= max_size){
				max_size = M.size();
				cout << M.size() << " ";
				show_clique(M, nv, nv);
			}
			if (M.size() >= CLIQUE_SIZE)
				stop_flag = 1;
		}
		else{
			if ((REZULT.size() < CLIQUES_COUNT) && (!stop_flag)){
			//if (!stop_flag){
				extend(a, REZULT, K, P, M);
			}
			else{
				break;
			}
		}
		theIterator = candidates.find(v);
		if (theIterator != candidates.end())
		{
			candidates.erase(theIterator);
		}
		theIterator = M.find(v);
		if (theIterator != M.end())
		{
			M.erase(theIterator);
		}
		not.insert(v);
	}
}
Example #23
0
        void advanceAnimation()
        {
            float timeElapsed = gm->elapsedTime();
            float radius = max(1.0f, gm->screenWidth() / gm->screenHeight());

            if (touched)
            {
                if (touchedDist <= s.starLength * 2)
                    touchedDist += timeElapsed * s.speed;
            } else
                PHLowPassFilter(touchedDist, 0.0f, timeElapsed, 5);
            float ss = s.starLength + touchedDist;

            float distance = timeElapsed * s.speed * (ss / s.starLength);

            while (!points.empty())
            {
                point & p = points.front();
                if (p.z - ss < -NEAR_PLANE)
                    break;
                points.pop_front();
            }

            bool reshape = touchedDist > 0.05;
            offset += distance;
            distanceLeft -= distance;
            while (distanceLeft <= 0)
            {
                for (int i = 0; i < chunk; i ++)
                {
                    point p;
                    p.z = -FAR_PLANE - distanceLeft - offset;
                    float r = frand(0.5f, 2.0f) * radius;
                    float angle = frand(0.0f, M_PI * 2.0f);
                    p.up = PHPoint(r, s.starWidth).rotated(angle);
                    p.down = PHPoint(r, -s.starWidth).rotated(angle);
                    distanceLeft += frand(0.5f, 1.0f) * starSpread;
                    points.push_back(p);
                }
                reshape = true;
            }


            if (reshape)
            {
                size_t n = points.size();
                if (!n)
                {
                    vao->disableDrawing();
                    return;
                }
                size_t vertices = n * 4;
                GLfloat * v = new GLfloat[vertices * 5];
                GLfloat * p = v;
                for (list<point>::iterator i = points.begin(); i != points.end(); i++)
                {
                    point & pt = *i;
                    pt.z += offset;

                    p[0] = pt.up.x;
                    p[1] = pt.up.y;
                    p[2] = pt.z;
                    p[3] = 0.0f;
                    p[4] = 0.0f;

                    p[5] = pt.down.x;
                    p[6] = pt.down.y;
                    p[7] = pt.z;
                    p[8] = 0.0f;
                    p[9] = 1.0f;

                    p[10] = pt.up.x;
                    p[11] = pt.up.y;
                    p[12] = pt.z - ss;
                    p[13] = 1.0f;
                    p[14] = 0.0f;

                    p[15] = pt.down.x;
                    p[16] = pt.down.y;
                    p[17] = pt.z - ss;
                    p[18] = 1.0f;
                    p[19] = 1.0f;

                    //PHLog("%f %f %f %f  %f %f", pt.up.x, pt.up.y, pt.down.x, pt.down.y, pt.z, pt.z - s.starLength);

                    p+= 20;
                }
                offset = 0.0f;

                PHGLCheckError();
                vbo->setDataOptimally(v, vertices * 5 * sizeof(GLfloat), PHGLVBO::dynamicDraw);
                delete[] v;

                elements->resize(n, vao);
            }

            PHVector3 pos = _body->position();
            pos.z = offset;
            _body->setPosition(pos);
        }
void Group::backTrack(list<Group> & ans, int n)
{
    if (n==(int)elements.size()){
        newElements.clear();
        for(int i=0; i<n; i++){
            if (isPresent[i]==1) newElements.push_back(elements[i]);
        }
        Group H(newElements);
        if (H.isValidGroup()) ans.push_back(H);
        return;
    }

    if (isPresent[n]!=0){
        backTrack(ans, n+1);
        return;
    }

    isPresent[n]=-1;
    backTrack(ans, n+1);

    stack<int> & toRemove = toRemoveVec[n];
    stack<int> & dfs = dfsVec[n];

    isPresent[n]=1;
    clearStack(toRemove); toRemove.push(n);
    clearStack(dfs); dfs.push(n);

    int newToAdd, current;
    bool possible = true;

    while(!dfs.empty()){
        current = dfs.top();
        dfs.pop();
        for(int i=0; possible && i<(int)elements.size(); i++){
            if (isPresent[i]==1)
            {
                newToAdd = findIndexOf((elements[i]+elements[current]).carac);
                if (newToAdd == -1)
                {
                    printf("Erro, operação não fechada\n");
                    return;
                }
                if (isPresent[newToAdd]==-1) possible = false;
                if (isPresent[newToAdd]==0){
                    toRemove.push(newToAdd);
                    dfs.push(newToAdd);
                    isPresent[newToAdd]=1;
                }
                newToAdd = findIndexOf((elements[current]*elements[i]).carac);
                if (newToAdd == -1)
                {
                    printf("Erro, operação não fechada\n");
                    return;
                }
                if (isPresent[newToAdd]==-1) possible = false;
                if (isPresent[newToAdd]==0){
                    toRemove.push(newToAdd);
                    dfs.push(newToAdd);
                    isPresent[newToAdd]=1;
                }
            }
        }
    }

    if (possible) backTrack(ans, n+1);

    while(!toRemove.empty()){
        isPresent[toRemove.top()]=0;
        toRemove.pop();
    }
}
Example #25
0
void NiSequence::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const {
	//--BEGIN PRE-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiObject::Write( out, link_map, missing_link_stack, info );
	numControlledBlocks = (unsigned int)(controlledBlocks.size());
	NifStream( name, out, info );
	if ( info.version <= 0x0A010000 ) {
		NifStream( textKeysName, out, info );
		if ( info.version < VER_3_3_0_13 ) {
			WritePtr32( &(*textKeys), out );
		} else {
			if ( textKeys != NULL ) {
				map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(textKeys) );
				if (it != link_map.end()) {
					NifStream( it->second, out, info );
					missing_link_stack.push_back( NULL );
				} else {
					NifStream( 0xFFFFFFFF, out, info );
					missing_link_stack.push_back( textKeys );
				}
			} else {
				NifStream( 0xFFFFFFFF, out, info );
				missing_link_stack.push_back( NULL );
			}
		}
	};
	if ( ( info.version >= 0x14030009 ) && ( info.version <= 0x14030009 ) && ( info.userVersion == 131072 ) ) {
		NifStream( unknownInt4, out, info );
		NifStream( unknownInt5, out, info );
	};
	NifStream( numControlledBlocks, out, info );
	if ( info.version >= 0x0A01006A ) {
		NifStream( unknownInt1, out, info );
	};
	for (unsigned int i1 = 0; i1 < controlledBlocks.size(); i1++) {
		if ( info.version <= 0x0A010000 ) {
			NifStream( controlledBlocks[i1].targetName, out, info );
			if ( info.version < VER_3_3_0_13 ) {
				WritePtr32( &(*controlledBlocks[i1].controller), out );
			} else {
				if ( controlledBlocks[i1].controller != NULL ) {
					map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(controlledBlocks[i1].controller) );
					if (it != link_map.end()) {
						NifStream( it->second, out, info );
						missing_link_stack.push_back( NULL );
					} else {
						NifStream( 0xFFFFFFFF, out, info );
						missing_link_stack.push_back( controlledBlocks[i1].controller );
					}
				} else {
					NifStream( 0xFFFFFFFF, out, info );
					missing_link_stack.push_back( NULL );
				}
			}
		};
		if ( info.version >= 0x0A01006A ) {
			if ( info.version < VER_3_3_0_13 ) {
				WritePtr32( &(*controlledBlocks[i1].interpolator), out );
			} else {
				if ( controlledBlocks[i1].interpolator != NULL ) {
					map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(controlledBlocks[i1].interpolator) );
					if (it != link_map.end()) {
						NifStream( it->second, out, info );
						missing_link_stack.push_back( NULL );
					} else {
						NifStream( 0xFFFFFFFF, out, info );
						missing_link_stack.push_back( controlledBlocks[i1].interpolator );
					}
				} else {
					NifStream( 0xFFFFFFFF, out, info );
					missing_link_stack.push_back( NULL );
				}
			}
			if ( info.version < VER_3_3_0_13 ) {
				WritePtr32( &(*controlledBlocks[i1].controller), out );
			} else {
				if ( controlledBlocks[i1].controller != NULL ) {
					map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(controlledBlocks[i1].controller) );
					if (it != link_map.end()) {
						NifStream( it->second, out, info );
						missing_link_stack.push_back( NULL );
					} else {
						NifStream( 0xFFFFFFFF, out, info );
						missing_link_stack.push_back( controlledBlocks[i1].controller );
					}
				} else {
					NifStream( 0xFFFFFFFF, out, info );
					missing_link_stack.push_back( NULL );
				}
			}
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			if ( info.version < VER_3_3_0_13 ) {
				WritePtr32( &(*controlledBlocks[i1].unknownLink2), out );
			} else {
				if ( controlledBlocks[i1].unknownLink2 != NULL ) {
					map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(controlledBlocks[i1].unknownLink2) );
					if (it != link_map.end()) {
						NifStream( it->second, out, info );
						missing_link_stack.push_back( NULL );
					} else {
						NifStream( 0xFFFFFFFF, out, info );
						missing_link_stack.push_back( controlledBlocks[i1].unknownLink2 );
					}
				} else {
					NifStream( 0xFFFFFFFF, out, info );
					missing_link_stack.push_back( NULL );
				}
			}
			NifStream( controlledBlocks[i1].unknownShort0, out, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( (info.userVersion >= 10) ) ) {
			NifStream( controlledBlocks[i1].priority, out, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			if ( info.version < VER_3_3_0_13 ) {
				WritePtr32( &(*controlledBlocks[i1].stringPalette), out );
			} else {
				if ( controlledBlocks[i1].stringPalette != NULL ) {
					map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(controlledBlocks[i1].stringPalette) );
					if (it != link_map.end()) {
						NifStream( it->second, out, info );
						missing_link_stack.push_back( NULL );
					} else {
						NifStream( 0xFFFFFFFF, out, info );
						missing_link_stack.push_back( controlledBlocks[i1].stringPalette );
					}
				} else {
					NifStream( 0xFFFFFFFF, out, info );
					missing_link_stack.push_back( NULL );
				}
			}
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].nodeName, out, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].nodeName, out, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].nodeNameOffset, out, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].propertyType, out, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].propertyType, out, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].propertyTypeOffset, out, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].controllerType, out, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].controllerType, out, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].controllerTypeOffset, out, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].variable1, out, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].variable1, out, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].variable1Offset, out, info );
		};
		if ( ( info.version >= 0x0A01006A ) && ( info.version <= 0x0A01006A ) ) {
			NifStream( controlledBlocks[i1].variable2, out, info );
		};
		if ( info.version >= 0x14010003 ) {
			NifStream( controlledBlocks[i1].variable2, out, info );
		};
		if ( ( info.version >= 0x0A020000 ) && ( info.version <= 0x14000005 ) ) {
			NifStream( controlledBlocks[i1].variable2Offset, out, info );
		};
	};

	//--BEGIN POST-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//
}
Example #26
0
 unsigned int run(mytime length){
   RNGScope scope;
   if(mean_stay<=0) throw runtime_error("mean_stay not a positive value.");
   double drate = 1/mean_stay;
   double arate = drate*balance*current.maxSize();
   mytime now=end;
   end += length;
   while(now<end){
     possibleStep step=snone;
     mytime 
       t=0,
       next=time_unknown;
     
     if(lambda>0 && current.nSusceptible()!=0 && current.nInfected()!=0){
       next=t=rexp(1, lambda * current.nSusceptible() * current.nInfected() )[0];
       step=sinfect;
     }
     if(!current.full()){
       t=rexp(1, arate)[0];
       if(t<next){
         next=t;
         step=sadmit;
       }
     }
     if(!current.empty()){
       t=rexp(1,drate*current.size())[0];
       if(t<next){
         next=t;
         step=sdischarge;
       }
     }
     if(!current.empty() && test_rate>0){
       t=rexp(1,test_perpd ? (test_rate * current.size()) : test_rate)[0];
       if(t<next){
         next=t;
         step=stest;
       }
     }
     now+=next;
     switch(step){
       case sadmit:
         {
           pp pat = new patient(now);
           if(runif(1,0,1)[0]<importation) pat->infect(now);
           current.add(pat);
           all.push_back(pat);
         }
         break;
       case sdischarge:
         current.dischargeRandom(now);
         break;
       case sinfect:
         current.infectRandom(now);
         break;
       case stest:
         current.testSomeone(now, false_negative_rate, false_positive_rate);
         break;
       default:
         break;
     }
   }
   end = now;
   return all.size();
 }
Example #27
0
	void add_element(Base* element){
		treeList.push_back(element);
	}
Example #28
0
 void ReplSetImpl::_getTargets(list<Target>& L, int& configVersion) {
     configVersion = config().version;
     for( Member *m = head(); m; m=m->next() )
         if( m->hbinfo().maybeUp() )
             L.push_back( Target(m->fullName()) );
 }
Example #29
0
File: main.cpp Project: CCJY/coliru
bool ThreadedList::addJob(const string job)
{
    scoped_lock<boost::mutex> locker(m_mutex);
    m_jobLst.push_back(job);
}
Example #30
0
 Exp *add() {
   sub.push_back(Exp(this));
   return &(sub.back());
 }