Example #1
0
void rmFunct(vector<string> files)
{
	vector<string> dirs;

	struct stat name;

	for(unsigned int i = 0; i < files.size(); i++)
	{
		if(-1 == stat(files.at(i).c_str(), &name))
		{
			perror("no");
			exit(1);
		}

		if(S_IFDIR & name.st_mode)
		{
			if(rFlag)
			{
				//cout << "YOLO" << endl;
				//cout << "files: " << files.at(i) << endl;
				if(files.at(i) != "." && files.at(i) != "..") {
					dirs.push_back(files.at(i) + "/");
				}
			} else { 
				cout << "Can't remove directory without -r flag" << endl;
				exit(1);
			}
		}
		else if(S_IFREG & name.st_mode)
		{

			if(files.at(i) != "." && files.at(i) != "..") {
				if(-1 == unlink(files.at(i).c_str()))
				{
					perror("praalam with unlink");
					exit(1);
				}
			}
		
		}
	}

	if(rFlag) {
		//cout << "SWAG" << endl;
		files.clear();
		DIR* dp;

		for(unsigned int i = 0; i < dirs.size(); i++)
		{
			if(!(dp = opendir(dirs.at(i).c_str())))
			{
				perror("cannot open dir");
				exit(1);
			}
			dirent* direntp;
			while((direntp = readdir(dp)) != 0) //extract files from directory
			{
				//cout << "asdfsf " << dirs.at(i) + direntp->d_name << endl;
				string cur = ".";
				string pre = "..";
				if(direntp->d_name != cur && direntp->d_name != pre)
					files.push_back(dirs.at(i) + direntp->d_name);
				
			}
			rmFunct(files);
			if(-1 == rmdir(dirs.at(i).c_str()))
			{
				perror("praalam removing directory");
				exit(1);
			}
		}
	}


}
void TreeCommon::GetNodes(float left, float right, float bottom, float top, float glyph_radius,
    vector<CNode*>& pre_level_nodes, vector<CNode*>& current_level_nodes) {

    if (this->type() == VIEW_DEPENDENT_TREE || this->type() == CLUSTER_PROJECTION_TREE) {
        this->ConstructTree(left, right, bottom, top, glyph_radius);
    }

    // Get nodes according to the average distance among all child nodes!!!
    pre_level_nodes.clear();
    current_level_nodes.clear();

    float expected_radius = glyph_radius * 2;
    float view_center_x = (left + right) / 2;
    float view_center_y = (top + bottom) / 2;
    float view_width = right - left;
    float view_height = top - bottom;

    if (this->type() == HIERARCHICAL_TREE) {
        pre_level_nodes.push_back(root_);
    } else if (this->type() == NCUTS_TREE) {
        int temp_level = 0;
        vector<CNode*> level_nodes;
        do {
            temp_level++;
            GetNodes(temp_level, level_nodes);
        } while (level_nodes.size() < 8);
        GetNodes(temp_level - 1, pre_level_nodes);
    } else {
        queue<CNode*> node_queue;
        node_queue.push(root_);
        while (!node_queue.empty()) {
        CNode* node = node_queue.front();
        node->is_visible = false;
        node_queue.pop();
        if (node->type() != CNode::BRANCH) continue;

        float center_x = node->center_pos[0] * point_dataset_->max_pos_range + point_dataset_->original_pos_ranges[0][0];
        float center_y = node->center_pos[1] * point_dataset_->max_pos_range + point_dataset_->original_pos_ranges[1][0];
        float node_width = (node->right - node->left) * point_dataset_->max_pos_range;
        float node_height = (node->top - node->bottom) * point_dataset_->max_pos_range;


        if (abs(view_center_x - center_x)  < (node_width / 2 + view_width / 2)
            && abs(view_center_y - center_y) < (node_height / 2 + view_height / 2)) {
            node->is_expanded = true;
            if (node->average_dis < expected_radius * 4) {
                pre_level_nodes.push_back(node);
            } else {
                CBranch* branch = (CBranch*)node;
                for (int i = 0; i < branch->linked_nodes.size(); ++i)
                    node_queue.push(branch->linked_nodes[i]);
            }
        }
    }
    }

    for (int i = 0; i < pre_level_nodes.size(); ++i) {
        CBranch* branch = (CBranch*)pre_level_nodes[i];
        bool is_children_leaf = false;
        for (int j = 0; j < branch->linked_nodes.size(); ++j)
            if (branch->linked_nodes[j]->type() == CNode::LEAF) {
                is_children_leaf = true;
                break;
            }
        if (!is_children_leaf) {
            for (int j = 0; j < branch->linked_nodes.size(); ++j) {
                CNode* node = branch->linked_nodes[j];

                float center_x = node->center_pos[0] * point_dataset_->max_pos_range + point_dataset_->original_pos_ranges[0][0];
                float center_y = node->center_pos[1] * point_dataset_->max_pos_range + point_dataset_->original_pos_ranges[1][0];
                float node_width = (node->right - node->left) * point_dataset_->max_pos_range;
                float node_height = (node->top - node->bottom) * point_dataset_->max_pos_range;

                if (abs(view_center_x - center_x)  < (node_width / 2 + view_width / 2)
                    && abs(view_center_y - center_y) < (node_height / 2 + view_height / 2))
                    current_level_nodes.push_back(branch->linked_nodes[j]);
            }
        } else {
            current_level_nodes.push_back(branch);
        }
    }
    for (int i = 0; i < current_level_nodes.size(); ++i) {
        current_level_nodes[i]->is_expanded = false;
        current_level_nodes[i]->is_visible = true;
    }
}
Example #3
0
void refresh()
{
    grid.clear();
    r=0, c=0;
    memset(visited,false,sizeof visited);
}
Example #4
0
 // time++
 void next_step() {
     //virtual nodes
     // starting with v[0] == f[1/2] to v[N] == f[N + 1/2]
     // v[i] == f[i + 1/2]
     vector<vector<double> > v(N + 1, vector<double>(N_xi, 0));
     
     // D
     for (int a = N_xi / 2; a < N_xi; a++) {     // for positive xi(a)
         f[N + 1][a] = approx(f[N][a], f[N - 1][a]);
         v[N][a] = i_plus_half_minmod_positive(f[N - 1][a], f[N][a], f[N + 1][a], xi(a) * dt / h);
     }
     for (int a = 0; a < N_xi / 2; a++) {     // for negative xi(a)
         f[0][a] = approx(f[1][a], f[2][a]);
         v[0][a] = i_plus_half_minmod_negative(f[0][a], f[1][a], f[2][a], xi(a) * dt / h);
     }
     // E
     double sum1 = 0;
     for (b = 0; b < N_xi / 2; b++)
         sum1 += - xi(b) * v[0][b];                                  // here always xi(b) < 0
     for (int a = N_xi / 2; a < N_xi; a++) {
         double e = exp(-m * pow (xi(a), 2) / (2 * k * T1));
         v[0][a] = sum1 * e / sum2;
     }
     
     sum1 = 0;
     for (b = N_xi / 2; b < N_xi; b++)
         sum1 += xi(b) * v[N][b];                                    // here always xi(b) > 0
     for (int a = 0; a < N_xi / 2; a++) {
         double e = exp(-m * pow (xi(a), 2) / (2 * k * T2));
         v[N][a] = sum1 * e / sum2_;
     }
     
     // J
     vector<double> g(N_xi, 0);
     
     sum1 = 0;
     for (b = 0; b < N_xi / 2; b++)
         sum1 += - xi(b) * (f[1][b] - 0.5 * df_i(f[0][b], f[1][b], f[2][b]));
     for (int a = N_xi / 2; a < N_xi; a++) {
         // find g[a]
         double e = exp(-m * pow (xi(a), 2) / (2 * k * T1));
         g[a] = sum1 * e / sum2;
         f[0][a] = approx(g[a], f[1][a]);
         v[1][a] = i_plus_half_minmod_positive(f[0][a], f[1][a], f[2][a], xi(a) * dt / h);
     }
     
     sum1 = 0;
     for (b = N_xi / 2; b < N_xi; b++)
         sum1 += xi(b) * (f[N][b] + 0.5 * df_i(f[N - 1][b], f[N][b], f[N + 1][b]));
     for (int a = 0; a < N_xi / 2; a++) {
         // find g[a]
         double e = exp(-m * pow (xi(a), 2) / (2 * k * T2));
         g[a] = sum1 * e / sum2_;
         f[N + 1][a] = approx(g[a], f[N][a]);
         v[N - 1][a] = i_plus_half_minmod_negative(f[N - 1][a], f[N][a], f[N + 1][a], xi(a) * dt / h);
     }
     
     // we already found elements of v:
     // for xi > 0: v[0][a], v[1][a]     and v[N][a]
     // for xi < 0: v[0][a], v[N - 1][a] and v[N][a]
     // now we seek for all other elements of v
     for (int a = N_xi / 2; a < N_xi; a++) {
         for (int i = 2; i < N; i++) {
             v[i][a] = i_plus_half_minmod_positive(f[i - 1][a], f[i][a], f[i + 1][a], xi(a) * dt / h);
         }
     }
     for (int a = 0; a < N_xi / 2; a++) {
         for (int i = 1; i < N - 1; i++) {
             v[i][a] = i_plus_half_minmod_negative(f[i][a], f[i + 1][a], f[i + 2][a], xi(a) * dt / h);
         }
     }
     
     // now we found all v[][] elements
     // let's find next time-layer
     // auxiliary 2-dim vector
     vector<vector<double> > F(N + 2, vector<double>(N_xi, 0));
     for (int a = 0; a < N_xi; a++) {
         for (int i = 1; i <= N; i++) {
             F[i][a] = f[i][a] - (xi(a) * dt / h) * (v[i][a] - v[i-1][a]);
         }
     }
     f.clear();
     f = F;
     
 }
int generation () {
	eagles = rabbits = grasses = grasshoppers = mice = snakes = kookaburras = 0;
	
	generations++;
	eagleLocations.clear();
	kookaburraLocations.clear();
	snakeLocations.clear();
	mouseLocations.clear();
	rabbitLocations.clear();
	grasshopperLocations.clear();
	grassLocations.clear();
	
	//first time is a check before generating
	for (int y = 0; y < width; y++) {
		for (int x = 0; x < width; x++) {
			
			if (grid[y][x] != 0) {
				whichAnimal (y, x);
			}
			
		}
	}
	
	//srand(time(NULL));
	int randX1 = (rand() % width) - 1;
	int randY1 = (rand() % width) - 1;
	if (randX1 < 0) {randX1 = 0;}
	if (randY1 < 0) {randY1 = 0;}
	int randX2 = randX1 + 1;
	int randY2 = randY1 + 1;

	if (eagles == 0) {
		grid[randY1][randX1] = 7; grid[randY2][randX2] = 7;
	}
	if (kookaburras == 0) {
		grid[randY1][randX1] = 6; grid[randY2][randX2] = 6;
	}
	if (snakes == 0) {
		grid[randY1][randX2] = 5; grid[randY2][randX2] = 5;
	}
	if (mice == 0) {
		grid[randY1][randX1] = 4; grid[randY2][randX2] = 4;
	}
	if (rabbits == 0) {
		grid[randY1][randX1] = 3; grid[randY2][randX2] = 3;
	}
	if (grasshoppers == 0) {
		grid[randY1][randX1] = 2; grid[randY2][randX2] = 2;
	}
	if (grasses == 0) {
		grid[randY1][randX1] = 1; grid[randY2][randX2] = 1;
	}
	
	newGrass();
	newMice();
	newRabbits();
	newGrasshoppers();
	newSnakes();
	newKookaburras();
	newEagles();
	
	
	eagles = rabbits = grasses = grasshoppers = mice = snakes = kookaburras = 0;
	
	for (int y = 0; y < width; y++) {
		for (int x = 0; x < width; x++) {
			
			if (grid[y][x] != 0) {
				whichAnimal2 (x, y);
			}
			
		}
	}
	
	howManyOfEach();
	cout << "Generation: " << generations << endl;
}
Example #6
0
bool File::load_VRML(vector<Triangle> &triangles, uint max_triangles)
{

  triangles.clear();
  ustring filename = _file->get_path();
    ifstream file;

    file.open(filename.c_str());

    if(file.fail()) {
      cerr << _("Error: Unable to open vrml file - ") << filename << endl;
      return false;
    }

    file.imbue(std::locale("C"));
    ustring word;
    std::vector<float> vertices;
    std::vector<int> indices;
    bool finished = false;
    vector<Vector3d> points;
    while(!file.eof() && !finished) {
      // while (word!="Shape"  && !file.eof())
      // 	file >> word;
      // while (word!="Appearance" && !file.eof())
      // 	file >> word;
      // while (word!="Coordinate" && !file.eof())
      // 	file >> word;
      points.clear();
      vertices.clear();
      while (word!="coord" && !file.eof()) // only use coord points
	file >> word;
      while (word!="point" && !file.eof())
	file >> word;
      file >> word;
      if (word=="[") {
	double f;
	while (word!="]" && !file.eof()){
	  file >> word;
          if (word.find(",") == word.length()-1) { // remove comma
            word = word.substr(0,word.length()-1);
          }
	  if (word!="]") {
	    if (word.find("#") != 0) { // comment
              f = atof(word.c_str());
	      vertices.push_back(f);
	    } else { // skip rest of line
              file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            }
          }
	}
        if (vertices.size() % 3 == 0)
          for (uint i = 0; i < vertices.size(); i += 3)
            points.push_back(Vector3d(vertices[i], vertices[i+1], vertices[i+2]));
	//cerr << endl;
      }
      indices.clear();
      while (word!="coordIndex"  && !file.eof())
	file >> word;
      file >> word;
      if (word=="[") {
	int c;
	while (word!="]" && !file.eof()){
	  file >> word;
	  if (word!="]")
	    if (word.find("#")!=0) {
	      std::istringstream iss(word);
              iss.precision(20);
	      iss >> c;
	      indices.push_back(c);
	      //cerr << word << "=="<< c << ", ";
	    }
	}
Example #7
0
void clear_scanned()
{
    buildings_scanned = false;
    suspended_buildings.clear();
}
Example #8
0
int main()
{
    c[0]=1;
    for (int i=1;i<37;i++)
        c[i]=c[i-1]*lq;
    int n;
    while (scanf("%d",&n)==1)
    {
        for (int i=0;i<Maxlen;i++)
            for (int j=0;j<mod;j++)
                f[i][j].clear();
        for (int i=1;i<=n;i++)
        {
            scanf("%s",buf);
            int len=strlen(buf);
            a[i].clear();
            string tmp;
            for (int j=1;j<len;j++)
            {
                if (buf[j]=='/')
                {
                    a[i].push_back(tmp);
                    tmp="";
                    continue;
                }
                tmp+=buf[j];
            }
            a[i].push_back(tmp);
            gethash(a[i],i);
        }
        int Q;
        scanf("%d",&Q);
        while (Q--)
        {
            scanf("%s",buf);
            b.clear();
            int len=strlen(buf);
            string tmp;
            for (int i=1;i<len;i++)
            {
                if (buf[i]=='/')
                {
                    b.push_back(tmp);
                    tmp="";
                    continue;
                }
                tmp+=buf[i];
            }
            b.push_back(tmp);
            int t=getans(b);
            if (t==1)
            {
                for (int i=0;i<a[p].size();i++)
                    printf("/%s",a[p][i].c_str());
                printf("\n");
            }
            else
                printf("%d\n",t);
        }
    }
    return(0);
}
Example #9
0
bool input_destroy(){
	gx_joysticks.clear();
	gx_runtime->closeInput( gx_input );
	gx_input=0;
	return true;
}
Example #10
0
void Shoot(Tank & self, World & world, model::Move& move)
{
	 vector<Tank> t = world.tanks();

	/* always keep tower to some enemy */

	Tank * pEnemy = get_need_id(g_lock_id, t);

	if ( EnemyDead(pEnemy) )
	{
		pEnemy = 0;
	}

	/* not locked to anyone, select some, or change target every 300 tick */

	if (!pEnemy || world.tick() % 300 == 0)
	{
		Tank * pOldEnemy = pEnemy;
		pEnemy = get_best_enemy(self, t);

		if (pEnemy != pOldEnemy)
		{
			waves.clear();
			stats.clear();
			stats.resize(30);
		}
	}

	/* still bad luck ? */

	if (!pEnemy)
	{
		/* MoveAlgo */
		return;
	}

	double absBearing = self.GetAngleTo(*pEnemy);

	for (int i=0; i < waves.size(); i++)
	{
		if (waves[i].checkHit(self, pEnemy, world.tick()))
		{
			waves.erase(waves.begin() + i );
			i--;
		}
	}

	double power = 16.7;

	double e_velocity = sqrt( pEnemy->speed_x()*pEnemy->speed_x() + pEnemy->speed_y()*pEnemy->speed_y() );

	WaveBullet newWave( self.x(), self.y(), self.angle(), absBearing, power,
                        direction, world.tick(), &stats );

	int bestindex = 15;	
	for (int i=0; i<30; ++i)
	{
		if (stats[bestindex] < stats[i])
		{
			bestindex = i;
		}
	}
 
	double guessfactor = ( bestindex - ( (double)stats.size() - 1 )/2 ) / ( ( (double)stats.size() - 1) / 2) ;

	if (e_velocity > 0.01)
	{
		if ( sin( pEnemy->angle() - self.angle()  ) < 0 )
		{
			direction = -1;
		}
		else
		{
			direction = 1;
		}
	}

	double angleOffset = direction * guessfactor * newWave.maxEscapeAngle();

	/* got lock? move turret! */

	MoveTurretOrShoot( pEnemy, self, world, move, 0.0 );
	waves.push_back(newWave);
}
/*! @brief Connected Component (CC) and Centroid Finding Function
 * 
 * This function runs through a binary image and finds the blobs
 * centroids using the Connected Component and morphological method
 * 
 * @param binaryImage the binary either (0-255) or (0-1) input image to be CC processed 
 * @param blobs 2D list of 2D points 
 * @param blobCentres list of 2D points representing centroids of each blob
 */
void ossimSDFilter::findBlobsCC(cv::Mat& binaryImage, vector< vector< cv::Point2i > >& blobs, vector< cv::Point2i >& blobCentres)
{
    blobs.clear();
    blobCentres.clear();

    cv::Mat labelImage,binaryImageTemp;
    
    //Perform morphological closing if spacing is not zero
    if(spacing > 0)
     cv::morphologyEx(binaryImage, binaryImage, cv::MORPH_CLOSE, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(spacing,spacing)));
   
    binaryImage.convertTo(binaryImage, CV_8UC1);
    
    //Ensure binary image is in 0 - 1 format rather than 0 - 255 format used usually used
    //when displaying an image (use a LUT)
    cv::Mat lookup(1, 256, CV_8U);
    uchar *p =  lookup.data;
    p[0] = 0; p[1] = 1; p[255] = 1;
    cv::LUT(binaryImage, lookup, binaryImageTemp);
    binaryImageTemp.convertTo(labelImage, CV_32SC1);

    //Start labeling at 2 because 0 and 1 are already used
    int labelCount = 2;
    
    //Run through image 
    for(int y=0; y < labelImage.rows; y++) {
        int *row = (int*)labelImage.ptr(y);
        for(int x=0; x < labelImage.cols; x++) {
            if(row[x] != 1) {
                continue;
            }

            cv::Rect rect;
            cv::floodFill(labelImage, cv::Point(x,y), labelCount, &rect, 0, 0, 8);
	    
            int iCounter = 0, iVal = 0, jCounter = 0, jVal = 0;
            std::vector <cv::Point2i> blob;

            for(int i=rect.y; i < (rect.y+rect.height); i++) {
                int *row2 = (int*)labelImage.ptr(i);
                for(int j=rect.x; j < (rect.x+rect.width); j++) {
                    if(row2[j] != labelCount) {
                        continue;
                    }

                    blob.push_back(cv::Point2i(j,i));
			
  		    //Update centroid stats
		    iCounter++; jCounter++;
		    iVal += i; jVal += j;  		    

                }
            }

	    //Find centroid (nn, add current label to new 'blob' then update the labelCounter;
	    blobCentres.push_back(cv::Point2i(floor((double(jVal)/double(jCounter))+0.5),
					      floor((double(iVal)/double(iCounter))+0.5)));
	    
            blobs.push_back(blob);

            labelCount++;
        }
    }

}
Value getworkex(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "getworkex [data, coinbase]\n"
            "If [data, coinbase] is not specified, returns extended work data.\n"
        );

    if (vNodes.empty())
        throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Catcoin is not connected!");

    if (IsInitialBlockDownload())
        throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Catcoin is downloading blocks...");

    typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
    static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
    static vector<CBlockTemplate*> vNewBlockTemplate;
    static CReserveKey reservekey(pwalletMain);

    if (params.size() == 0)
    {
        // Update block
        static unsigned int nTransactionsUpdatedLast;
        static CBlockIndex* pindexPrev;
        static int64 nStart;
        static CBlockTemplate* pblocktemplate;
        if (pindexPrev != pindexBest ||
            (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
        {
            if (pindexPrev != pindexBest)
            {
                // Deallocate old blocks since they're obsolete now
                mapNewBlock.clear();
                BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
                    delete pblocktemplate;
                vNewBlockTemplate.clear();
            }

            // Clear pindexPrev so future getworks make a new block, despite any failures from here on
            pindexPrev = NULL;

            // Store the pindexBest used before CreateNewBlock, to avoid races
            nTransactionsUpdatedLast = nTransactionsUpdated;
            CBlockIndex* pindexPrevNew = pindexBest;
            nStart = GetTime();

            // Create new block
            pblocktemplate = CreateNewBlockWithKey(*pMiningKey);
            if (!pblocktemplate)
                throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
            vNewBlockTemplate.push_back(pblocktemplate);

            // Need to update only after we know CreateNewBlock succeeded
            pindexPrev = pindexPrevNew;
        }
        CBlock* pblock = &pblocktemplate->block; // pointer for convenience

        // Update nTime
        pblock->UpdateTime(pindexPrev);
        pblock->nNonce = 0;

        // Update nExtraNonce
        static unsigned int nExtraNonce = 0;
        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);

        // Save
        mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);

        // Pre-build hash buffers
        char pmidstate[32];
        char pdata[128];
        char phash1[64];
        FormatHashBuffers(pblock, pmidstate, pdata, phash1);

        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();

        CTransaction coinbaseTx = pblock->vtx[0];
        std::vector<uint256> merkle = pblock->GetMerkleBranch(0);

        Object result;
        result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
        result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));

        CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
        ssTx << coinbaseTx;
        result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));

        Array merkle_arr;

        BOOST_FOREACH(uint256 merkleh, merkle) {
            printf("%s\n", merkleh.ToString().c_str());
            merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
        }

        result.push_back(Pair("merkle", merkle_arr));

        return result;
    }
Example #13
0
void init()
{
    for(int i=0;i<maxn;i++) G[i].clear() ;
    edge.clear() ;
}
Example #14
0
 void     clear_interactors()           { _cur_states.clear();   }
Example #15
0
/******************************************************************
* Function: 获得包含站号的STATION_VALUE_PROP在stationList容器中的下标
* Parameters: stationList,nStationId
* Return: null
******************************************************************/
bool DataCenter::getReadData(ADDR_TARGET_PROP mAddr, STATION_VALUE_PROP &readDataList, vector<ADDR_BIT_VALUE_PROP > &nResultList)
{
    /* 如果寄存器没添加,则初始化寄存器数据存储 */
    while(readDataList.regBitList.size() < MAX_BIT_REG_NUN)
    {
        vector<ADDR_BIT_VALUE_PROP > mTmpValueList;
        readDataList.regBitList.push_back(mTmpValueList);
    }

    while(readDataList.regWordList.size() < MAX_WORD_REG_NUN)
    {
        vector<ADDR_WORD_VALUE_PROP > mTmpValueList;
        readDataList.regWordList.push_back(mTmpValueList);
    }

    while(readDataList.regDoubleWordList.size() < MAX_DWORD_REG_NUN)
    {
        vector<ADDR_DOUBLE_WORD_PROP > mTmpValueList;
        readDataList.regDoubleWordList.push_back(mTmpValueList);
    }
    /* 初始化结束 */

    nResultList.clear();

    /*容器不够时,添加这个对象*/
    ADDR_BIT_VALUE_PROP emptyBitValue;
    emptyBitValue.nValue = 0;
    emptyBitValue.eErrorStatus = READ_DATA_FAIL;

    ADDR_WORD_VALUE_PROP emptyWordValue;
    emptyWordValue.nValue = 0;
    emptyWordValue.eErrorStatus = READ_DATA_FAIL;

    ADDR_DOUBLE_WORD_PROP emptyDoubleWordValue;
    emptyDoubleWordValue.nValue = 0;
    emptyDoubleWordValue.eErrorStatus = READ_DATA_FAIL;

    ADDR_BIT_VALUE_PROP mTmpValueProp;

    /*把数据保存到对应的容器中*/
    REG_TYPE_INDEX eRegType = PlcProtocol::getRegTypeFromInt(mAddr.nRegIndex);
    switch(eRegType)
    {
    case REG_TYPE_P:
    case REG_TYPE_M:
    case REG_TYPE_K:
    case REG_TYPE_L:
    case REG_TYPE_F:
        {
            int nValueListSize = (mAddr.nAddrValue + mAddr.nAddrLen)/16 +1;

            /*数据存储区的容器不够则重新分配空间*/
            int nSize = readDataList.regWordList[eRegType].size();
            if(nSize < nValueListSize)
            {
                readDataList.regWordList[eRegType].resize(nValueListSize, emptyWordValue);
            }

            /*赋值*/
            int nStartPos = 0;
            int nBitPost = 0;
            ushort nTmpValue = 0;
            for(int i = 0; i < mAddr.nAddrLen; i++)
            {
                nStartPos = (mAddr.nAddrValue + i)/16;
                nBitPost = (mAddr.nAddrValue + i)%16;

                /*设置状态*/
                mTmpValueProp.eErrorStatus = readDataList.regWordList[eRegType].at(nStartPos).eErrorStatus;

                /*设置值*/
                nTmpValue = readDataList.regWordList[eRegType].at(nStartPos).nValue;
                if(nTmpValue & (1 << nBitPost))
                {
                    mTmpValueProp.nValue = 1;
                }
                else
                {
                    mTmpValueProp.nValue = 0;
                }
                nResultList.push_back(mTmpValueProp);
            }
            break;
        }
    case REG_TYPE_T:
    case REG_TYPE_C:
        {
            /*数据存储区的容器不够则重新分配空间*/
            int nSize = readDataList.regBitList[eRegType - 5].size();
            if(nSize < mAddr.nAddrValue + mAddr.nAddrLen)
            {
                readDataList.regBitList[eRegType - 5].resize(mAddr.nAddrValue + mAddr.nAddrLen, emptyBitValue);
            }

            /*赋值*/
            for(int i = 0; i < mAddr.nAddrLen; i++)
            {
                mTmpValueProp = readDataList.regBitList[eRegType - 5].at(mAddr.nAddrValue + i);
                nResultList.push_back(mTmpValueProp);
            }
            break;
        }
    case REG_TYPE_PW:
    case REG_TYPE_MW:
    case REG_TYPE_KW:
    case REG_TYPE_LW:
    case REG_TYPE_FW:
    case REG_TYPE_D:
    case REG_TYPE_S:
    case REG_TYPE_TV:
    case REG_TYPE_CV:
        {
            /*数据存储区的容器不够则重新分配空间*/
            int nSize = readDataList.regWordList[eRegType - 7].size();
            if(nSize < mAddr.nAddrValue + mAddr.nAddrLen)
            {
                readDataList.regWordList[eRegType - 7].resize(mAddr.nAddrValue + mAddr.nAddrLen, emptyWordValue);
            }

            /*赋值*/
            ushort nTmpValue = 0;
            for(int i = 0; i < mAddr.nAddrLen; i++)
            {
                /*设置状态*/
                mTmpValueProp.eErrorStatus = readDataList.regWordList[eRegType - 7].at(mAddr.nAddrValue + i).eErrorStatus;

                /*设置值*/
                nTmpValue = readDataList.regWordList[eRegType - 7].at(mAddr.nAddrValue + i).nValue;

                mTmpValueProp.nValue = nTmpValue & 0xff;
                nResultList.push_back(mTmpValueProp);

                mTmpValueProp.nValue = (nTmpValue >> 8) & 0xff;
                nResultList.push_back(mTmpValueProp);
            }
            break;
        }
    default:
        {
            return false;
            break;
        }
    }

    return true;
}
Example #16
0
size_t Matrix::eigenValuesJacobi(vector<double> &eigenValues, vector< vector<double> > &eigenVector, size_t itLimit /*= 1000*/) const
{
    GlobalLog << "####JACOBI METHOD####" << std::endl << std::endl;

    Matrix Ai(*this), B(n, true);

    size_t it;
    for (it = 0; it < itLimit; it++)
    {
        GlobalLog << "Iteration #" << it << std::endl;
        GlobalLog << "Matrix:" << std::endl << Ai << std::endl;

        size_t i, j;
        Ai.findMax(i, j);

        double fi = (abs(Ai[i][i] - Ai[j][j]) > eps) ? 0.5 * atan(2 * Ai[i][j] / (Ai[i][i] - Ai[j][j])) : M_PI / 4;

        GlobalLog << "Maximal element is: " << Ai[i][j] << " which is in position (" << i << "," << j << ")" << std::endl << std::endl;
        GlobalLog << "alpha=a[i][i]=" << Ai[i][i] << std::endl
            << "beta=a[j][j]=" << Ai[j][j] << std::endl
            << "gamma=a[i][j]=" << Ai[i][j] << std::endl << std::endl;
        GlobalLog << "fi=" << fi << std::endl
            << "cos(fi)=" << cos(fi) << std::endl
            << "sin(fi)=" << sin(fi) << std::endl << std::endl;
        GlobalLog << "sigma=" << Ai.sigma() << std::endl
            << "omega=" << Ai.omega() << std::endl
            << "sum=" << Ai.sigma() + 2 * Ai.omega() << std::endl << std::endl;

        if (pow(Ai.omega(), 0.5) < eps)
            break;

        Matrix U(n, 0.0);

        for (size_t _i = 0; _i < n; _i++)
            U[_i][_i] = (_i != i && _i != j) ? 1 : 0;

        U[i][i] = cos(fi);
        U[j][j] = cos(fi);
        U[i][j] = -sin(fi);
        U[j][i] = sin(fi);

        // iteration
        Ai = U.Trans() * Ai * U;
        B = B * U;
    }

    eigenValues.clear();
    for (size_t i = 0; i < n; i++)
    {
        eigenValues.push_back(Ai[i][i]);
        eigenVector.push_back(B.GetColumn(i));
    }

    GlobalLog << "---RESULTS---" << std::endl
        << "Finished in " << it << " iterations" << std::endl << std::endl;

    for (size_t i = 0; i < eigenValues.size(); i++)
    {
        GlobalLog << "Eigen value #" << i + 1 << ": Value=" << eigenValues[i] << "\tVector: " << eigenVector[i] << std::endl
            << "Error=" << *this * eigenVector[i] - eigenValues[i] * eigenVector[i] << std::endl << std::endl;
    }

    return it;
}
Example #17
0
void ofApp::setGUI(){
    float xInit = OFX_UI_GLOBAL_WIDGET_SPACING;
    float w = 300 - xInit * 2;
    float vertH = 40;
    float h = 8;
    
    if (guiAlloc) {
        ofRemoveListener(gui->newGUIEvent, this, &ofApp::guiEvent);
        ambslider.clear();
        spotspecslider.clear();
        spotDiffSlider.clear();
        dirspecslider.clear();
        dirDiffSlider.clear();
        pointspecslider.clear();
        pointDiffSlider.clear();
        matDiffSlider.clear();
        matSpecSlider.clear();
        matEmSlider.clear();
        
        delete gui;
    }
    
    gui = new ofxUICanvas(0, 0, w + xInit * 2, ofGetHeight());
    gui->addWidgetDown(new ofxUILabel("LIGHT CONTROL", OFX_UI_FONT_MEDIUM));
    
    gui->addSlider("Radius", 5, 1000, radius, w, h);
    
    gui->addSpacer(w, 2);
    gui->addWidgetDown(new ofxUILabel("Spot Light Control", OFX_UI_FONT_MEDIUM));
    gui->addWidgetRight(new ofxUIToggle("Spot Source", showSpotSource, 10, 15));
    gui->addWidgetDown(new ofxUILabel("Spot Location", OFX_UI_FONT_SMALL));
    
    gui->addSlider("SX_POS", -500, 500, spot.getPosition().x, w, h);
    gui->addSlider("SY_POS", -500, 500, spot.getPosition().y, w, h);
    gui->addSlider("SZ_POS", -500, 500, spot.getPosition().z, w, h);
    
    gui->addWidgetDown(new ofxUILabel("Spot Orientation", OFX_UI_FONT_SMALL));
    gui->addSlider("SX_ORI", -180, 180, spot.getOrientationEuler().x, w, h);
    gui->addSlider("SY_ORI", -180, 180, spot.getOrientationEuler().y, w, h);
    gui->addSlider("SZ_ORI", -180, 180, spot.getOrientationEuler().z, w, h);
    
    gui->addWidgetDown(new ofxUILabel("Spot Param", OFX_UI_FONT_SMALL));
    gui->addSlider("Cutoff", 0.0, 90.0, spot.getSpotlightCutOff(), w, h);
    gui->addSlider("Cons", 0.0, 128.0, spot.getSpotConcentration(), w, h);
    
    gui->addWidgetDown(new ofxUILabel("Spot Diffuse/Specular Color", OFX_UI_FONT_SMALL));
    ofColor c = spot.getDiffuseColor();
    spotDiffSlider.push_back(gui->addSlider("SDR", 0, 255, c.r, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
    spotDiffSlider.push_back(gui->addSlider("SDG", 0, 255, c.g, h, vertH));
    spotDiffSlider.push_back(gui->addSlider("SDB", 0, 255, c.b, h, vertH));
    //    gui->addSlider("SDA", 0, 255, c.a, h, vertH);
    
    gui->addSpacer(2, vertH+10);
    
    c = spot.getSpecularColor();
    spotspecslider.push_back(gui->addSlider("SSR", 0, 255, c.r, h, vertH));
    spotspecslider.push_back(gui->addSlider("SSG", 0, 255, c.g, h, vertH));
    spotspecslider.push_back(gui->addSlider("SSB", 0, 255, c.b, h, vertH));
    //    spotspecslider.push_back(gui->addSlider("SSA", 0, 255, c.a, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
    
    gui->addSpacer(w, 2);
    gui->addWidgetDown(new ofxUILabel("Directional Light Control", OFX_UI_FONT_MEDIUM));
    gui->addWidgetRight(new ofxUIToggle("Dir Source", showDirSource, 10, 15));
    
    gui->addWidgetDown(new ofxUILabel("Directional Orientation", OFX_UI_FONT_SMALL));
    
    gui->addSlider("DIR_XORI", -180, 180, dir.getOrientationEuler().x, w, h);
    gui->addSlider("DIR_YORI", -180, 180, dir.getOrientationEuler().y, w, h);
    gui->addSlider("DIR_ZORI", -180, 180, dir.getOrientationEuler().z, w, h);
    
    gui->addWidgetDown(new ofxUILabel("Directional Diffuse/Specular Color", OFX_UI_FONT_SMALL));
    c = dir.getDiffuseColor();
    dirDiffSlider.push_back(gui->addSlider("DDR", 0, 255, c.r, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
    dirDiffSlider.push_back(gui->addSlider("DDG", 0, 255, c.g, h, vertH));
    dirDiffSlider.push_back(gui->addSlider("DDB", 0, 255, c.b, h, vertH));
    
    gui->addSpacer(2, vertH+10);
    c = dir.getSpecularColor();
    dirspecslider.push_back(gui->addSlider("DSR", 0, 255, c.r, h, vertH));
    dirspecslider.push_back(gui->addSlider("DSG", 0, 255, c.g, h, vertH));
    dirspecslider.push_back(gui->addSlider("DSB", 0, 255, c.b, h, vertH));
    //    dirspecslider.push_back(gui->addSlider("DSA", 0, 255, c.a, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
    
    gui->addSpacer(w, 2);
    gui->addWidgetDown(new ofxUILabel("Point Light Control", OFX_UI_FONT_MEDIUM));
    gui->addWidgetRight(new ofxUIToggle("Point Source", showPointSource, 10, 15));
    gui->addWidgetDown(new ofxUILabel("Point Diffuse/Specular Color", OFX_UI_FONT_SMALL));
    c = point.getDiffuseColor();
    pointDiffSlider.push_back(gui->addSlider("PDR", 0, 255, c.r, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
    pointDiffSlider.push_back(gui->addSlider("PDG", 0, 255, c.g, h, vertH));
    pointDiffSlider.push_back(gui->addSlider("PDB", 0, 255, c.b, h, vertH));
    //    gui->addSlider("PDA", 0, 255, c.a, h, vertH);
    
    gui->addSpacer(2, vertH+10);
    c = point.getSpecularColor();
    pointspecslider.push_back(gui->addSlider("PSR", 0, 255, c.r, h, vertH));
    pointspecslider.push_back(gui->addSlider("PSG", 0, 255, c.g, h, vertH));
    pointspecslider.push_back(gui->addSlider("PSB", 0, 255, c.b, h, vertH));
    //    pointspecslider.push_back(gui->addSlider("PSA", 0, 255, c.a, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
    
    gui->addToggle("Auto Move", autoRotatePoint);
    
    gui->addSpacer(w, 2);
    gui->addWidgetDown(new ofxUILabel("Ambient Light Control", OFX_UI_FONT_MEDIUM));
    gui->addWidgetDown(new ofxUILabel("Ambient Light Color", OFX_UI_FONT_SMALL));
    
    c = amb.getAmbientColor();
    ambslider.push_back(gui->addSlider("AR", 0, 255.0, c.r, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
    ambslider.push_back(gui->addSlider("AG", 0, 255.0, c.g, h, vertH));
    ambslider.push_back(gui->addSlider("AB", 0, 255.0, c.b, h, vertH));
    //    ambslider.push_back(gui->addSlider("AA", 0, 255, c.a, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
    
    //Material Control
    
    gui->addSpacer(w, 2);
    gui->addWidgetDown(new ofxUILabel("Material Control", OFX_UI_FONT_MEDIUM));
    gui->addSlider("MAT SHINE", 0, 128, material.getShininess(), w, h);
    gui->addWidgetDown(new ofxUILabel("Material Diffuse/Emissive/Specular Color", OFX_UI_FONT_SMALL));
    
    c = material.getDiffuseColor();
    matDiffSlider.push_back(gui->addSlider("MDR", 0, 255, c.r, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
    matDiffSlider.push_back(gui->addSlider("MDG", 0, 255, c.g, h, vertH));
    matDiffSlider.push_back(gui->addSlider("MDB", 0, 255, c.b, h, vertH));
    //    gui->addSlider("MDA", 0, 255, c.a, h, vertH);
    
    gui->addSpacer(2, vertH+10);
    c = material.getEmissiveColor();
    matEmSlider.push_back(gui->addSlider("MER", 0, 255, c.r, h, vertH));
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
    matEmSlider.push_back(gui->addSlider("MEG", 0, 255, c.g, h, vertH));
    matEmSlider.push_back(gui->addSlider("MEB", 0, 255, c.b, h, vertH));
    //    gui->addSlider("MDA", 0, 255, c.a, h, vertH);
    
    gui->addSpacer(2, vertH+10);
    c = material.getSpecularColor();
    matSpecSlider.push_back(gui->addSlider("MSR", 0, 255, c.r, h, vertH));
    matSpecSlider.push_back(gui->addSlider("MSG", 0, 255, c.g, h, vertH));
    matSpecSlider.push_back(gui->addSlider("MSB", 0, 255, c.b, h, vertH));
    //    gui->addSlider("MSA", 0, 255, c.a, h, vertH);
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
    
    gui->addSpacer(w, 2);
    gui->addToggle("cull", cull);
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT);
    gui->addToggle("spot", useSpot);
    gui->addToggle("point", usePoint);
    gui->addToggle("dir", useDir);
    gui->addToggle("ambient", useAmb);
    gui->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN);
    
    gui->addSpacer(w, 2);
    gui->addLabelButton("RESET", false);
    
    ofAddListener(gui->newGUIEvent, this, &ofApp::guiEvent);
    guiAlloc = true;
}
void initSet(int n){
	id.clear();	id.resize(n);
	cant_hijos.clear();	cant_hijos.resize(n,1);
	for(int i=0;i<n;i++)	id[i]=i;
}
Example #19
0
void init(){
	i = 0; x = "";
	isstring = 1;
	st.clear(); num.clear();
}
Example #20
0
//___________________________________________________________________________
Double_t* IfitBin(TH1F* dataInput, TH1F* sigTemplate, TH1F* bkgTemplate, 
	       int fit_data=1)
{

  cout << "Input files are " << dataInput->GetName() << "\t" << sigTemplate->GetName() << "\t" << bkgTemplate->GetName() << endl;

  TCanvas *c1 = new TCanvas("HF1", "Histos1", 0, 0, 600, 600);
  dataCollBin.clear();
  sigCollBin.clear();
  bkgCollBin.clear();

  Double_t* fitted = new Double_t[8];
  fitted[0] = fitted[1] = fitted[2] = fitted[3] = fitted[4] = fitted[5] = fitted[6] = fitted[7] = 0.0;

  TH1F *hsum = new TH1F();
  float ntemplate = 1.;
  float sigfrac = 0.1;
  TH1F *hsum_norm = new TH1F();
  TH1F *hdata;
  TH1F *hsig  = (TH1F*)sigTemplate->Clone();
  hsig->SetName("hsig");
  hsig->Rebin(6);

  TH1F *hbkg  = (TH1F*)bkgTemplate->Clone();
  hbkg->SetName("hbkg");
  hbkg->Rebin(6);

  float ndata=0;
  if ( fit_data>0 ) {
    hdata = (TH1F*)dataInput->Clone();
    hdata -> SetName("hdata");
    ndata = hdata->Integral();
  }else {
    hsum = (TH1F*)hsig->Clone();
    hsum->Add(hbkg,1);
    cout << "For histogram " << sigTemplate->GetName() << " and " << bkgTemplate->GetName() << " sum = " << 
      hsum->Integral() << endl;

    if (hsum->Integral()>1.) ntemplate = hsum->Integral();
    sigfrac = hsig->Integral()/ntemplate;

    hsum_norm = (TH1F*)hsum->Clone();  
    hsum_norm->Scale(1./hsum->Integral());

    hdata = (TH1F*)hsum_norm->Clone();
    hdata -> SetName("hdata");
    ndata=ntemplate;
    hdata->FillRandom(hsum_norm, ndata);
  }
  if(ndata==0) {
    printf(" ---  no events in the fit \n");
    return fitted;
  }
    
  printf(" --------- before the fit ------------- \n");
  printf("Nsig %2.3f, Nbg %2.3f, Ntemplate %3.3f \n", hsig->Integral(), hbkg->Integral(), ntemplate);
//   printf("Purity %2.3f, init size %4.3f,  test sample size %4d\n", hsig->Integral()/hsum->Integral(), hsum->Integral(), ndata);
  printf(" -------------------------------------- \n");

  hdata->Rebin(6);
  int nbins = hdata->GetNbinsX();

  hsig->Scale(1./hsig->Integral());
  hbkg->Scale(1./hbkg->Integral());  

  for (int ibin=1; ibin<=nbins; ibin++) {
    dataCollBin.push_back(hdata->GetBinContent(ibin));
    sigCollBin.push_back(hsig->GetBinContent(ibin));
    bkgCollBin.push_back(hbkg->GetBinContent(ibin));    
  }
  printf( " -----  Got %d, %d, %d events for fit ----- \n ", dataCollBin.size(),
	  sigCollBin.size(), bkgCollBin.size() );  
  if ( dataCollBin.size() != sigCollBin.size() || sigCollBin.size()!=bkgCollBin.size() ) {
    printf(" error ...  inconsistent hit collection size \n");
    return fitted;
  }

  //--------------------------------------------------
  //init parameters for fit
  Double_t vstart[10] = {1., 1.};
  vstart[0] = sigfrac*ndata;
  vstart[1] = (1-sigfrac)*ndata;
 
  TMinuit *gMinuit = new TMinuit(NPARBIN);  
  gMinuit->Command("SET STR 1");
  gMinuit->SetFCN(fcnBin);
  Double_t arglist[10];
  Int_t ierflg = 0;
  
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
  arglist[0] = 1;
  gMinuit->mnexcm("SET PRINT", arglist ,1,ierflg);

  Double_t step[] = { 0.1, 0.1,};

  gMinuit->mnparm(0,  "Signal yield"  , vstart[0],  step[0], 0., ndata*2.  , ierflg);
  gMinuit->mnparm(1,  "background yield"  , vstart[1],  step[1], 0., ndata*2. , ierflg);
  
  printf(" --------------------------------------------------------- \n");
  printf(" Now ready for minimization step \n --------------------------------------------------------- \n");
  
  arglist[0] = 2000; // number of iteration
  arglist[1] = 1.;
  gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg);
  printf (" -------------------------------------------- \n");
  printf("Finished.  ierr = %d \n", ierflg);

  infoBin.clear();
  infoBin_err.clear();

  double para[NPARBIN+1],errpara[NPARBIN+1];
  if ( ierflg == 0 ) 
    {
      for(int j=0; j<=NPARBIN-1;j++) {
        gMinuit->GetParameter(j, para[j],errpara[j]);
        para[NPARBIN] = dataCollBin.size();
        infoBin.push_back(para[j]);
        infoBin_err.push_back(errpara[j]);
        printf("Parameter (yeild) %d = %f +- %f\n",j,para[j],errpara[j]);
	
      }
      printf(" fitted yield %2.3f \n", (para[0]+para[1])/ndata );
      infoBin.push_back(sigCollBin.size());

    }
  else {
    printf(" *********** Fit failed! ************\n");
    gMinuit->GetParameter(0, para[0],errpara[0]);
    gMinuit->GetParameter(1, para[1],errpara[1]);
    para[0]=0.; errpara[0]=0.;
  }

  
  // Print results
  Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;
  gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  gMinuit->mnprin(1,amin);  
  gMinuit->mnmatu(1);
  printf(" ========= happy ending !? =========================== \n");
  
  printf("FCN =  %3.3f \n", amin);

  double yerr[20];
  for(int i=0;i<20;i++){
    yerr[i] = 0.;
  }

  hsig->Scale(para[0]);
  hbkg->Scale(para[1]);
  TH1F *hfit = (TH1F*)hsig->Clone();
  hfit->Add(hbkg);


  hsig->SetLineColor(1);
  hsig->SetFillColor(5);
  hsig->SetFillStyle(3001);

  hbkg->SetLineWidth(2);
  // plot
  c1->Draw();  
  //gPad->SetLogy();
  hdata->SetLineColor(1);
  hdata->SetNdivisions(505,"XY");
  hdata->SetXTitle("Iso_{ECAL}+Iso_{HCAL}+Iso_{TRK} (GeV)");
  hdata->SetYTitle("Entries");
  hdata->SetTitle("");
  hdata->SetMarkerStyle(8);
  hdata->SetMinimum(0.);
  hdata->SetMaximum(hdata->GetMaximum()*1.5);
  hdata->Draw("p e");
  hsig->Draw("hist same");
  hbkg->SetMarkerStyle(0);
  hbkg->SetFillColor(8);
  hbkg->SetLineWidth(1);
  hbkg->SetFillStyle(3013);
  hbkg->SetError(yerr);
  hbkg->Draw("hist same");
  hfit->SetMarkerStyle(0);
  hfit->SetLineColor(1);
  hfit->SetLineWidth(2);
  hfit->SetError(yerr);
  hfit->Draw("hist same");

  double chi2ForThisBin=0;
  int nbinForThisBin=0;
  chi2NbinsHisto(hfit, hdata, chi2ForThisBin, nbinForThisBin);
  TPaveText *pavetex = new TPaveText(0.43, 0.87, 0.90, 0.92,"NDCBR");
  pavetex->SetBorderSize(0);
  pavetex->SetFillColor(0);
  pavetex->SetFillStyle(0);
  pavetex->SetLineWidth(3);
  pavetex->SetTextAlign(12);
  pavetex->SetTextSize(0.03);
  pavetex->AddText(Form("#chi^{2}/NDF=%.1f/%d",chi2ForThisBin, nbinForThisBin));
  pavetex->Draw();


  char text[1000];
  TLegend *tleg = new TLegend(0.43, 0.60, 0.90, 0.87);
  tleg->SetHeader(dataInput->GetTitle());

  tleg->SetTextSize(0.03);
  tleg->SetFillColor(0);
  tleg->SetShadowColor(0);
  tleg->SetBorderSize(0);
  sprintf(text,"Data %5.1f events",hdata->Integral());
  tleg->AddEntry(hdata,text,"pl");
  sprintf(text,"Fitted %5.1f events",hfit->Integral());
  tleg->AddEntry(hfit,text,"l");
  sprintf(text,"SIG %5.1f #pm %5.1f events",para[0], errpara[0]);
  tleg->AddEntry(hsig,text,"f");
  sprintf(text,"BKG %5.1f #pm %5.1f events",para[1], errpara[1]);
  tleg->AddEntry(hbkg,text,"f");
  tleg->Draw();

  gPad->RedrawAxis();


  cout << dataInput->GetName() << endl;
  char fname[300];
  sprintf(fname,"plots/Ifit_%s.eps",dataInput->GetName());
  c1->SaveAs(fname);
  sprintf(fname,"plots/Ifit_%s.gif",dataInput->GetName());
  c1->SaveAs(fname);

  printf("----- fit results with signal projection   ----------- \n");

  //   ftemplate->Close();
  
  int purityMaxBin = hsig->FindBin(5.0)-1;
  Double_t scale_signal = hsig->Integral(1,purityMaxBin)/hsig->Integral();
  Double_t scale_background = hbkg->Integral(1,purityMaxBin)/hbkg->Integral();
  
  fitted[0] = para[0];
  fitted[1] = errpara[0];
  fitted[2] = para[1];
  fitted[3] = errpara[1];

  // for integral up to 5 GeV
  fitted[4] = para[0]*scale_signal;
  fitted[5] = errpara[0]*scale_signal;
  fitted[6] = para[1]*scale_background;
  fitted[7] = errpara[1]*scale_background;

  return fitted;
}
int main()
{
	int i,j;
	int k;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(i=0;i<n;i++)
		{
			scanf("%s",s[i]);
		}
		for(i=0;i<30;i++)
		{
			flag[i]=-1;
			y[i][0]=x[i][0]=1000;
			y[i][1]=x[i][1]=0;
			in[i]=0;
			for(j=0;j<30;j++) a[i][j]=0;
		}
		for(i=0;i<n;i++)
		{
			for(j=0;j<m;j++)
			{
				if(s[i][j]>='A'&&s[i][j]<='Z') 
				{
					k=s[i][j]-'A';
					flag[k]=1;
					if(x[k][0]>i) x[k][0]=i;
					if(x[k][1]<i) x[k][1]=i;
					if(y[k][0]>j) y[k][0]=j;
					if(y[k][1]<j) y[k][1]=j;
				}
			}
		}
		for(i=0;i<26;i++)
		{
			if(flag[i]==-1) continue;
			for(j=x[i][0];j<=x[i][1];j++)
			{
				if(s[j][y[i][0]]!='A'+i) a[s[j][y[i][0]]-'A'][i]=1;
				if(s[j][y[i][1]]!='A'+i) a[s[j][y[i][1]]-'A'][i]=1;
			}	
			for(j=y[i][0];j<=y[i][1];j++)
			{
				if(s[x[i][0]][j]!='A'+i) a[s[x[i][0]][j]-'A'][i]=1;
				if(s[x[i][1]][j]!='A'+i) a[s[x[i][1]][j]-'A'][i]=1;
			}
		}
		cnt=0;
		for(i=0;i<26;i++)
		{
			if(flag[i]==1) cnt++;
			for(j=0;j<26;j++) if(a[i][j]) in[j]++;
		}
		string str;
		ans.clear();
		str="";
		dfs(str);
		sort(ans.begin(),ans.end());
		for(i=0;i<ans.size();i++) printf("%s\n",ans[i].c_str());
	}
	return 0;
}
Example #22
0
	Node():val(INT_MAX),visited(false){ others.clear(); }
int whichAnimal (int y, int x) {
	temp.clear();
	temp.push_back(x);
	temp.push_back(y);
	bool food = false;
	bool mate = false;
	if (grid[y][x] == 1) {
		grasses++;
		if (grid[y - 1][x] == 1 || grid[y + 1][x] == 1 || grid[y][x + 1] == 1 || grid[y][x - 1] == 1 || grid[y - 1][x - 1] == 1 || grid[y - 1][x + 1] == 1 || grid[y + 1][x - 1] == 1 || grid[y + 1][x + 1] == 1) {
			grassLocations.push_back(temp);
		}
		
		//grassLocations.push_back(temp);
	} else if (grid[y][x] == 2) {
		grasshoppers++;
		for (int i = y - grasshopper.radius; i < y + grasshopper.radius; i++) {
			for (int z = x - grasshopper.radius; z < x + grasshopper.radius; z++) {
				if (grid[i][z] == 1 && food == false) {
					food = true;
					grid[i][z] = 0;
				} else if (grid[i][z] == 2) {
					mate = true;
				} 
				if (mate && food) {
					grasshopperLocations.push_back(temp);
					i = 100000;
					z = 100000;
				} else if ( (i == y + grasshopper.radius - 1 && z == x + grasshopper.radius - 1) || (i == width - 1 || z == width - 1)) {
					grid[y][x] = 0;
				}
			}
		}
	} else if (grid[y][x] == 3) {
		rabbits++;
		for (int i = y - rabbit.radius; i < y + rabbit.radius && i < width; i++) {
			for (int z = x - rabbit.radius; z < x + rabbit.radius && z < width; z++) {
				if (i < 0) {
					i = 0;
				}
				if (z < 0) {
					z = 0;
				}
				
				if (grid[i][z] == 1 && food == false) {
					food = true;
					grid[i][z] = 0;
				} else if (grid[i][z] == 3) {
					mate = true;
				} 
				if (mate && food) {
					rabbitLocations.push_back(temp);
					i = 100000;
					z = 100000;
				} else if ((i == y + rabbit.radius - 1 && z == x + rabbit.radius - 1) || (i == width - 1 || z == width - 1)) {
					grid[y][x] = 0;
				}
			}
		}
	} else if (grid[y][x] == 4) {
		mice++;
		for (int i = y - mouse.radius; i < y + mouse.radius && i < width; i++) {
			for (int z = x - mouse.radius; z < x + mouse.radius && z < width; z++) {
				if (i < 0) {
					i = 0;
				}
				if (z < 0) {
					z = 0;
				}
				
				if (grid[i][z] == 1 && food == false) {
					food = true;
					grid[i][z] = 0;
				} else if (grid[i][z] == 4) {
					mate = true;
				} 
				if (mate && food) {
					mouseLocations.push_back(temp);
					i = 100000;
					z = 100000;
				} else if ((i == y + mouse.radius - 1 && z == x + mouse.radius - 1) || (i == width - 1 || z == width - 1)) {
					grid[y][x] = 0;
				}
			}
		}
		//mouseLocations.push_back(temp);
	} else if (grid[y][x] == 5) {
		snakes++;
		for (int i = y - snake.radius; i < y + snake.radius && i < width; i++) {
			for (int z = x - snake.radius; z < x + snake.radius && z < width; z++) {
				if (i < 0) {
					i = 0;
				}
				if (z < 0) {
					z = 0;
				}
				
				if ( (grid[i][z] == 4 || grid[i][z] == 3) && food == false) {
					food = true;
					grid[i][z] = 0;
				} else if (grid[i][z] == 5) {
					mate = true;
				} 
				if (mate && food) {
					snakeLocations.push_back(temp);
					i = 100000;
					z = 100000;
				} else if ((i == y + snake.radius - 1 && z == x + snake.radius - 1) || (i == width - 1 || z == width - 1)) {
					grid[y][x] = 0;
				}
			}
		}
		//snakeLocations.push_back(temp);
	} else if (grid[y][x] == 6) {
		kookaburras++;
		//kookaburras are capable of eating much more than 1 animal per gen, so we will set it to eat a max of 3. But, they must eat at least 2 to stay alive
		int kookaDigested = 0;
		for (int i = y - kookaburra.radius; i < y + kookaburra.radius && i < width; i++) {
			for (int z = x - kookaburra.radius; z < x + kookaburra.radius && z < width; z++) {
				if (i < 0) {
					i = 0;
				}
				if (z < 0) {
					z = 0;
				}
				
				if ( (grid[i][z] == 4 || grid[i][z] == 5 || grid[i][z] == 2) && kookaDigested < 3) {
					grid[i][z] = 0;
					kookaDigested++;
					if (kookaDigested >= 2) {
						food = true;
					}
					
				} else if (grid[i][z] == 6) {
					mate = true;
				} 
				if (mate && food) {
					kookaburraLocations.push_back(temp);
					i = 100000;
					z = 100000;
				} else if ((i == y + kookaburra.radius - 1 && z == x + kookaburra.radius - 1) || (i == width - 1 || z == width - 1)) {
					grid[y][x] = 0;
				}
			}
		}
		//kookaburraLocations.push_back(temp);
	} else if (grid[y][x] == 7) {
		eagles++;
		//eagle are capable of eating much more than 1 animal per gen, so we will set it to eat a max of 2. But, they must eat at least 1 to stay alive
		int eagleDigested = 0;
		for (int i = y - eagle.radius; i < y + eagle.radius && i < width; i++) {
			for (int z = x - eagle.radius; z < x + eagle.radius && z < width; z++) {
				if (i < 0) {
					i = 0;
				}
				if (z < 0) {
					z = 0;
				}
				
				if ( (grid[i][z] == 6 || grid[i][z] == 5 /*|| grid[i][z] == 3*/) && eagleDigested < 1) {
					grid[i][z] = 0;
					eagleDigested++;
					if (eagleDigested >= 1) {
						food = true;
					}
					
				} else if (grid[i][z] == 7) {
					mate = true;
				} 
				if (mate && food) {
					eagleLocations.push_back(temp);
					i = 100000;
					z = 100000;
				} else if ((i == y + eagle.radius - 1 && z == x + eagle.radius - 1) || (i == width - 1 || z == width - 1)) {
					grid[y][x] = 0;
				}
			}
		}
		//eagleLocations.push_back(temp);
	}
}
int main (int argc, char * const argv[]) {
  cv::Mat img(650, 650, CV_8UC3);
  char code = (char)-1;

  cv::namedWindow("mouse particle");
  cv::setMouseCallback("mouse particle", on_mouse, 0);

  cv::Mat_<float> measurement(2,1);
  measurement.setTo(cv::Scalar(0));

  int dim = 2;
  int nParticles = 25;
  float xRange = 650.0;
  float yRange = 650.0;

  float minRange[] = { 0, 0 };
  float maxRange[] = { xRange, yRange };
  CvMat LB, UB;
  cvInitMatHeader(&LB, 2, 1, CV_32FC1, minRange);
  cvInitMatHeader(&UB, 2, 1, CV_32FC1, maxRange);

  CvConDensation* condens = cvCreateConDensation(dim, dim, nParticles);

  cvConDensInitSampleSet(condens, &LB, &UB);

  // The OpenCV documentation doesn't tell you to initialize this
  // transition matrix, but you have to do it.  For this 2D example,
  // we're just using a 2x2 identity matrix.  I'm sure there's a slicker
  // way to do this, left as an exercise for the reader.
  condens->DynamMatr[0] = 1.0;
  condens->DynamMatr[1] = 0.0;
  condens->DynamMatr[2] = 0.0;
  condens->DynamMatr[3] = 1.0;

  for(;;) {

    if (mouse_info.x < 0 || mouse_info.y < 0) {
      imshow("mouse particle", img);
      cv::waitKey(30);
      continue;
    }

    mouseV.clear();
    particleV.clear();

    for(;;) {
      code = (char)cv::waitKey(100);

      if( code > 0 )
    break;

#ifdef CLICK
      if (counter++ > 0) {
    continue;
      }
#endif

      measurement(0) = mouse_info.x;
      measurement(1) = mouse_info.y;

      cv::Point measPt(measurement(0),measurement(1));
      mouseV.push_back(measPt);

      // Clear screen
      img = cv::Scalar::all(100);

      for (int i = 0; i < condens->SamplesNum; i++) {

    float diffX = (measurement(0) - condens->flSamples[i][0])/xRange;
    float diffY = (measurement(1) - condens->flSamples[i][1])/yRange;

    condens->flConfidence[i] = 1.0 / (sqrt(diffX * diffX + diffY * diffY));

    // plot particles
#ifdef PLOT_PARTICLES
    cv::Point partPt(condens->flSamples[i][0], condens->flSamples[i][1]);
    drawCross(partPt , cv::Scalar(255,0,255), 2);
#endif

      }

      cvConDensUpdateByTime(condens);

      cv::Point statePt(condens->State[0], condens->State[1]);
      particleV.push_back(statePt);

      // plot points
      drawCross( statePt, cv::Scalar(255,255,255), 5 );
      drawCross( measPt, cv::Scalar(0,0,255), 5 );

      for (int i = 0; i < mouseV.size() - 1; i++) {
    line(img, mouseV[i], mouseV[i+1], cv::Scalar(255,255,0), 1);
      }
      for (int i = 0; i < particleV.size() - 1; i++) {
    line(img, particleV[i], particleV[i+1], cv::Scalar(0,255,0), 1);
      }
      //line(img,mouseV[mouseV.size()-2],mouseV[mouseV.size()-1],cv::Scalar(255,255,0),1);
      //line(img,particleV[particleV.size()-2],particleV[particleV.size()-1],cv::Scalar(0,255,0),1);
      imshow( "mouse particle", img );
      //mouseV.clear();
      //particleV.clear();

    }

    if( code == 27 || code == 'q' || code == 'Q' )
      break;
  }

  return 0;
}
void TreeCommon::GetNodePoints(int node_id, vector<int>& point_ids) {
    point_ids.clear();

    CNode* node = this->GetNode(node_id);
    if (node != NULL) this->GetNodePoints(node, point_ids);
}
/**********************************************************************************
* AUTHOR		: Deepu V.
* DATE			: 09-MAR-2005
* NAME			: computeChannelStatistics
* DESCRIPTION	: This is a generic function that computes the statistics of channels of
*                 an LTKTraceGroup object passed to it.   
* ARGUMENTS		: traceGroup        - The TraceGroup whose statistics need to be computed                  channelNames      - Names of channels in the traceGroup for which 
*			      channelNames      - channels for which statistics have to be comptued
*		          properties        - The names of the statistics to be computed
*			      channelStatistics - output vector containing results
*			      channelStatistics[i][j] the statistics properties[j] for channelname
*			      channelNames[i]
*
* RETURNS		:  SUCCESS/FAILURE
* NOTES			:
* CHANGE HISTROY
* Author			Date				Description of change
*************************************************************************************/
int LTKInkUtils::computeChannelStatistics(const LTKTraceGroup& traceGroup,
               const vector<string>& channelNames,  const vector<ELTKTraceGroupStatistics>& properties,
			   vector<vector<float> >& channelStatistics)
{
	LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << 
		  " Entering: LTKInkUtils::computeChannelStatistics()" << endl;
	
	vector<float> tempVec; //temporary vector

	int numChannels = channelNames.size(); //num of channels for which statistics need to be computed

	int numFeatures = properties.size();   //number of properties to be calculated

	int numTraces = traceGroup.getNumTraces(); //number of traces in each tracegroup

	int numPoints;              //number of points in a stroke


	int totalNumPoints=0;  //each channel is of equal length

	float currVal;              //value of current point in the channel

	int traceIndex, channelIndex, pointIndex, featureIndex;

	// Clear the output vector
	channelStatistics.clear();

	//Make an initial vector
	tempVec.clear();
	for (featureIndex= 0 ; featureIndex <numFeatures; ++featureIndex)
	{
		switch(properties[featureIndex])
		{
		//initializing max
		case TG_MAX:tempVec.push_back(-FLT_MAX);
			break;
		//initializing min
		case TG_MIN:tempVec.push_back(FLT_MAX);
			break;
		//initializing avg
		case TG_AVG:tempVec.push_back(0);
			break;

		default: LOG(LTKLogger::LTK_LOGLEVEL_ERR)
				       <<"Error: LTKInkUtils::computeChannelStatistics()"<<endl;

			LTKReturnError(EUNSUPPORTED_STATISTICS);
		}
	}
	
	//Initialization Every channel has the same value
	for(channelIndex =0; channelIndex<numChannels; ++channelIndex)
	{
		channelStatistics.push_back(tempVec);

		//initialize total number of points for each channel to zero
	}


	//Iterating through all the strokes
	for (traceIndex = 0; traceIndex <numTraces; ++traceIndex)
	{
		LTKTrace trace;
		traceGroup.getTraceAt(traceIndex, trace);

		//Iterating through all the channels in a stroke
		for (channelIndex =0; channelIndex<numChannels; ++channelIndex)
		{
			//get the current channel values
			floatVector currChannel;
			trace.getChannelValues(channelNames[channelIndex], currChannel);

			//get the current output vector to be updated
			floatVector& currStats = channelStatistics.at(channelIndex);

			//number of points in this channel
			numPoints = currChannel.size();

			if(channelIndex==0)
			{
				totalNumPoints += numPoints;
			}

			//iterate through all points in the channel
			for(pointIndex = 0; pointIndex <numPoints; ++pointIndex)
			{
				currVal = currChannel[pointIndex];

				//updating all features as we iterate through each point;
				for (featureIndex =0; featureIndex<numFeatures; featureIndex++)
				{
					switch(properties[featureIndex])
					{

					//updating the maximum
					case TG_MAX:
						if(currVal > currStats[featureIndex])
							currStats[featureIndex] = currVal;
						break;

					//updating the minimum
					case TG_MIN:
						if(currVal < currStats[featureIndex])
							currStats[featureIndex] = currVal;
						break;

					//accumulating the sum
					case TG_AVG:
						currStats[featureIndex] += currVal;
						break;

					default: LOG(LTKLogger::LTK_LOGLEVEL_ERR)
							        <<"Error: LTKInkUtils::computeChannelStatistics()"<<endl;

						LTKReturnError(EUNSUPPORTED_STATISTICS);

					}

				}

			}
			
		}

	}

	//Finalization Step
	for (channelIndex= 0 ; channelIndex<numChannels; ++channelIndex)
	{

		floatVector& currStats = channelStatistics.at(channelIndex);

		//total number of points in this channel
		numPoints = totalNumPoints; 

		for(featureIndex = 0; featureIndex<numFeatures; ++featureIndex)
		{
			switch(properties[featureIndex])
			{
			//finding the average
			case TG_AVG:
					currStats[featureIndex] /= numPoints;
				break;
			}
		}
	}

	LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << 
		  " Exiting: LTKInkUtils::computeChannelStatistics()" << endl;

	return SUCCESS;
}
Example #27
0
Value getworkex(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "getworkex [data, coinbase]\n"
            "If [data, coinbase] is not specified, returns extended work data.\n"
        );

    if (vNodes.empty())
        throw JSONRPCError(-9, "AndroidToken is not connected!");

    if (IsInitialBlockDownload())
        throw JSONRPCError(-10, "AndroidToken is downloading blocks...");

    typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
    static mapNewBlock_t mapNewBlock;
    static vector<CBlock*> vNewBlock;
    static CReserveKey reservekey(pwalletMain);

    if (params.size() == 0)
    {
        // Update block
        static unsigned int nTransactionsUpdatedLast;
        static CBlockIndex* pindexPrev;
        static int64 nStart;
        static CBlock* pblock;
        if (pindexPrev != pindexBest ||
            (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
        {
            if (pindexPrev != pindexBest)
            {
                // Deallocate old blocks since they're obsolete now
                mapNewBlock.clear();
                BOOST_FOREACH(CBlock* pblock, vNewBlock)
                    delete pblock;
                vNewBlock.clear();
            }
            nTransactionsUpdatedLast = nTransactionsUpdated;
            pindexPrev = pindexBest;
            nStart = GetTime();

            // Create new block
            pblock = CreateNewBlock(pwalletMain);
            if (!pblock)
                throw JSONRPCError(-7, "Out of memory");
            vNewBlock.push_back(pblock);
        }

        // Update nTime
        pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
        pblock->nNonce = 0;

        // Update nExtraNonce
        static unsigned int nExtraNonce = 0;
        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);

        // Save
        mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);

        // Prebuild hash buffers
        char pmidstate[32];
        char pdata[128];
        char phash1[64];
        FormatHashBuffers(pblock, pmidstate, pdata, phash1);

        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();

        CTransaction coinbaseTx = pblock->vtx[0];
        std::vector<uint256> merkle = pblock->GetMerkleBranch(0);

        Object result;
        result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
        result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));

        CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
        ssTx << coinbaseTx;
        result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));

        Array merkle_arr;

        BOOST_FOREACH(uint256 merkleh, merkle) {
            merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
        }

        result.push_back(Pair("merkle", merkle_arr));


        return result;
    }
Example #28
0
int main() {
// The problem consist of a ACM ICPC scoreboard. Every line of input has this
// format: C P T L
// C: Contestant Number
// P: Problem Index
// T: Time of Submission
// L: Type of Submission
// ... C: Correct
// ... I: Incorrect
// ... R: Request for Clarification
// ... U: Unjudged
// ... E: Erroneous Submission
// The last 3 types of submission have no effect on scoring. An user's score
// for a given problem is the time it took to send a correct submission, plus
// 20 minutes of penalty for every previous incorrect submission of that pro-
// blem. There's no penalty for problems not submitted, or for problems with
// incorrect submissions that never had a correct submission at the end. Then
// whats the scoreboard in the format C P T?
// C: Contestant Number
// P: Problems Solved
// T: Total Time (with Penalties)
    int n;
    // The number of test cases to be read
    cin >> n;
    getchar();
    // Get the linebreak that cin ignores after reading the test cases number
    string line;
    getline(cin, line);
    // Get the original empty line after test cases number and inputs
    for(int z = 0; z < n; z++) {
        finalRanking.clear();
        initContestants();
        while(getline(cin, line)) {
        // Read lines until EOF or...
            if(line == "" || line == " ") {
            // ..until a newline is read which marks the end of the test case
                break;
            }
            stringstream submission(line);
            int cNumber;
            // The number of the contestant
            int pIndex;
            // The index of the problem
            int sTime;
            // The time of submission
            string sType;
            // The type of submission
            submission >> cNumber >> pIndex >> sTime >> sType;
            Contestant c = contestants[cNumber];
            c.submitted = true;
            // Mark this contestant/team as having submitted anything. Having
            // submitted anything is important because it lets us know that the
            // contestant exists, so even if they don't have any accepted sub-
            // mission, they'll show up at the final scoreboard.
            if(sType == "R" || sType == "U" || sType == "E") {
            // We don't care about these kind of submissions for the scoreboard
                contestants[cNumber] = c;
                continue;
            }
            Problem p = c.problems[pIndex];
            if(!p.accepted) {
            // Submissions after the first accepted one won't have any effect
            // on the scoreboard, so leave that thing alone!
                p.lastSubmissionTime = sTime;
                // Renew the last submission time
                p.submissions++;
                // Increase the number of submissions for this problem
                if(sType == "C") {
                // If the problem was correct, change its status to accepted
                    p.accepted = true;
                }
            }
            c.problems[pIndex] = p;
            contestants[cNumber] = c;
        }
        // After this, all the scoreboard has been read, now lets get ready to
        // compute the total time for everyone!
        getTotalTimes();
        // Now that we have for every contestant their total running times and
        // amount of problems solved...
        sortContestants();
        // ... lets sort them using the explained sorting rules!
        for(int k = 0; k < finalRanking.size(); k++) {
        // Now, lets print the scoreboard!
            Contestant c = finalRanking[k];
            printf("%d %d %d\n", c.contestantIndex, 
                                 c.problemsSolved, 
                                 c.totalTime
            );
        }
        if(z + 1 < n) {
            puts("");
        }
    }
}
Example #29
0
void input(){
	cache.clear();
	getline(cin, line);
}
Example #30
0
//try to find the mono-pmz from a initial mz and ch, and try to find all possible pmzs 
//in the isolotion window, generally it is +/-2.0Da
//The IW will be extracted from the raw file directly
bool CalScan::ExtendFindISO(vector<CalData> &PIso,double pmz,double IW)
{
	//for debug
	//if(ScanNum==5919)
	//{
	//	ScanNum=5919;
	//}
	//end
	double CurrentBestGD=0;
	vector<sPeak> tmpPKL;
	size_t pnum=PKL.size();
	if(pnum<=0) return false;
	int begin=TFindL(0,pnum-1,pmz-IW);
	if(begin==-1) return false;
	while(begin<pnum)
	{
		if(PKL[begin].dMass>=pmz-IW) break;
		begin++;
	}
	int end=TFindH(0,pnum-1,pmz+IW);
	if(end==-1) return false;
	while(end>begin)
	{
		if(PKL[end].dMass<=pmz+IW) break;
		end--;
	}

	sPeak pt;
	vector<sPeak> tmpPKL1;

	int k,i=begin-1;	
	//extend according the iso pair rules
	bool IsAdd=false;
	double K=Pre_dm/1e6;
	for(;i>0;i--)
	{
		if(PKL[begin].dMass-PKL[i].dMass>ISO_DIFF[1]) break;
		for(k=begin;k<=end;k++)
		{
			double delt=PKL[k].dMass-PKL[i].dMass;
			int ch;
			for(ch=MAX_CHARGE;ch>=1;ch--)
			{
				if(fabs(delt*ch-ISO_DIFF[1])<K*PKL[i].dMass)
				{
					IsAdd=true;
					break;
				}
			}
		}
		if(IsAdd) 
		{
			//begin=i;//adjust the begin
			pt=PKL[i];
			tmpPKL1.push_back(pt);
			IsAdd=false;
		}
	}
	k=tmpPKL1.size()-1;
	for(;k>=0;k--)
	{
		tmpPKL.push_back(tmpPKL1[k]);
	}
	for(i=begin;i<=end;i++) 
	{
		pt=PKL[i];
		tmpPKL.push_back(pt);
	}
	i=end+1;
	for(;i<pnum;i++)
	{
		if(PKL[i].dMass-PKL[end].dMass>ISO_DIFF[1]) break;
		for(k=begin;k<=end;k++)
		{
			double delt=PKL[i].dMass-PKL[k].dMass;
			int ch;
			for(ch=MAX_CHARGE;ch>=1;ch--)
			{
				if(fabs(delt*ch-ISO_DIFF[1])<K*PKL[i].dMass)
				{
					IsAdd=true;
					break;
				}
			}
		}
		if(IsAdd) 
		{
			//end=i;//adjust the begin
			pt=PKL[i];
			tmpPKL.push_back(pt);
			IsAdd=false;
		}
	}
	
	//int CT=0;	
	int bT=FindIsoCPmz(tmpPKL,PIso);
	//if(bT==FIND_ONE)CT++;
	while(bT!=NO_PEAKS) 
	{	
		bT=FindIsoCPmz(tmpPKL,PIso);
		//if(bT==FIND_ONE)CT++;
		//printf("\r%d",CT);
	}	
	pnum=PIso.size();	
	//here more filteration may be provide for t he addtional pmzs
	vector<CalData> tmpPIso;
	for(i=0;i<pnum;i++)
	{
		if(!PIso[i].IspmzIn(pmz,Pre_dm))
		{
			if(PIso[i].GetIsoNum()>MIN_H_ISO_NUM
				&&PIso[i].IsotopicE[0]>BaseInt*R_INT_CUT_H
				&&PIso[i].ch!=CH_UNKNOWN
				&&PIso[i].goodness>GD_CUT_H) 
			{
				tmpPIso.push_back(PIso[i]);
			}

		}
		else tmpPIso.push_back(PIso[i]);
	}
	/////////////////
	PIso.clear();
	pnum=tmpPIso.size();
	for(i=0;i<pnum;i++) PIso.push_back(tmpPIso[i]);
	for(i=0;i<pnum;i++)	PackageIt(PIso[i]);
	return true;	
}