void SchemaItem::addAttribute(const std::map<std::string, std::shared_ptr<SchemaValue>> &attributes)
{
    for (auto it = attributes.begin(); it != attributes.end(); ++it)
        addAttribute(it->second);
}
Example #2
0
void Reconstruct()
{
	FILE *fo = fopen(output_file, "wb");

	int sv, cv, cd, len, pst;
	long long num_edges_renet = 0;
	double cw, sum;
	std::queue<int> node, depth;
	std::queue<double> weight;

	for (sv = 0; sv != num_vertices; sv++)
	{
		if (sv % 10 == 0)
		{
			printf("%cProgress: %.3lf%%", 13, (real)sv / (real)(num_vertices + 1) * 100);
			fflush(stdout);
		}

		while (!node.empty()) node.pop();
		while (!depth.empty()) depth.pop();
		while (!weight.empty()) weight.pop();
		vid2weight.clear();

		for (int i = 0; i != num_vertices; i++)
		{
			rank_list[i].vid = i;
			rank_list[i].weight = 0;
		}

		len = neighbor[sv].size();
		if (len > max_k)
		{
			for (int i = 0; i != len; i++)
				fprintf(fo, "%s\t%s\t%lf\n", vertex[sv].name, vertex[neighbor[sv][i].vid].name, neighbor[sv][i].weight);
			num_edges_renet += len;
			continue;
		}

		vid2weight[sv] += vertex[sv].degree / 10.0; // Set weights for self-links here!

		len = neighbor[sv].size();
		sum = vertex[sv].sum_weight;

		node.push(sv);
		depth.push(0);
		weight.push(sum);

		while (!node.empty())
		{
			cv = node.front();
			cd = depth.front();
			cw = weight.front();

			node.pop();
			depth.pop();
			weight.pop();

			if (cd != 0) vid2weight[cv] += cw;

			if (cd < max_depth)
			{
				len = neighbor[cv].size();
				sum = vertex[cv].sum_weight;

				for (int i = 0; i != len; i++)
				{
					node.push(neighbor[cv][i].vid);
					depth.push(cd + 1);
					weight.push(cw * neighbor[cv][i].weight / sum);
				}
			}
		}

		pst = 0;
		std::map<int, double>::iterator iter;
		for (iter = vid2weight.begin(); iter != vid2weight.end(); iter++)
		{
			rank_list[pst].vid = (iter->first);
			rank_list[pst].weight = (iter->second);
			pst++;
		}
		std::sort(rank_list, rank_list + pst);

		for (int i = 0; i != max_k; i++)
		{
			if (i == pst) break;
			fprintf(fo, "%s\t%s\t%.6lf\n", vertex[sv].name, vertex[rank_list[i].vid].name, rank_list[i].weight);
			num_edges_renet++;
		}
	}
	printf("\n");
	fclose(fo);

	printf("Number of edges in reconstructed network: %lld\n", num_edges_renet);
	return;
}
    bool ChooserEvaluator::select_parameters(const std::vector<ChooserPoly> &operands, double noise_standard_deviation, double noise_max_deviation, const std::map<int, BigUInt> &parameter_options, EncryptionParameters &destination)
    {
        if (noise_standard_deviation < 0)
        {
            throw invalid_argument("noise_standard_deviation can not be negative");
        }
        if (noise_max_deviation < 0)
        {
            throw invalid_argument("noise_max_deviation can not be negative");
        }
        if (parameter_options.size() == 0)
        {
            throw invalid_argument("parameter_options must contain at least one entry");
        }
        if (operands.empty())
        {
            throw invalid_argument("operands cannot be empty");
        }

        int largest_bit_count = 0;
        int largest_coeff_count = 0;
        for (vector<ChooserPoly>::size_type i = 0; i < operands.size(); ++i)
        {
            if (operands[i].comp_ == nullptr)
            {
                throw logic_error("no operation history to simulate");
            }
            int current_bit_count = operands[i].max_abs_value_.significant_bit_count();
            largest_bit_count = (current_bit_count > largest_bit_count) ? current_bit_count : largest_bit_count;

            int current_coeff_count = operands[i].max_coeff_count_;
            largest_coeff_count = (current_coeff_count > largest_coeff_count) ? current_coeff_count : largest_coeff_count;
        }

        // We restrict to plain moduli that are powers of two. Here largest_bit_count is the largest positive
        // coefficient that we can expect to appear. Thus, we need one more bit.
        destination.plain_modulus() = 1;
        destination.plain_modulus() <<= largest_bit_count;

        bool found_good_parms = false;
        map<int, BigUInt>::const_iterator iter = parameter_options.begin();
        while (iter != parameter_options.end() && !found_good_parms)
        {
            int dimension = iter->first;
            if (dimension < 512 || (dimension & (dimension - 1)) != 0)
            {
                throw invalid_argument("parameter_options keys invalid");
            }

            if (dimension > largest_coeff_count && destination.plain_modulus() < iter->second)
            {
                // Set the polynomial
                destination.coeff_modulus() = iter->second;
                destination.poly_modulus().resize(dimension + 1, 1);
                destination.poly_modulus().set_zero();
                destination.poly_modulus()[0] = 1;
                destination.poly_modulus()[dimension] = 1;

                // The bound needed for GapSVP->search-LWE reduction
                //parms.noise_standard_deviation() = round(sqrt(dimension / (2 * 3.1415)) + 0.5);

                // Use constant (small) standard deviation.
                destination.noise_standard_deviation() = noise_standard_deviation;

                // We truncate the gaussian at noise_max_deviation.
                destination.noise_max_deviation() = noise_max_deviation;

                // Start initially with the maximum decomposition_bit_count, then decrement until decrypts().
                destination.decomposition_bit_count() = destination.coeff_modulus().significant_bit_count();

                // We bound the decomposition bit count value by 1/8 of the maximum. A too small
                // decomposition bit count slows down multiplication significantly. This is not an
                // issue when the user wants to use multiply_norelin() instead of multiply(), as it
                // only affects the relinearization step. The fraction 1/8 is not an optimal choice
                // in any sense, but was rather arbitrarily chosen. An expert user might want to tweak this
                // value to be smaller or larger depending on their use case.
                // To do: Figure out a somewhat optimal bound.
                int min_decomposition_bit_count = destination.coeff_modulus().significant_bit_count() / 8;

                while (!found_good_parms && destination.decomposition_bit_count() > min_decomposition_bit_count)
                {
                    found_good_parms = true;
                    for (vector<ChooserPoly>::size_type i = 0; i < operands.size(); ++i)
                    {
                        // If one of the operands does not decrypt, set found_good_parms to false.
                        found_good_parms = operands[i].simulate(destination).decrypts() ? found_good_parms : false;
                    }
                    if (!found_good_parms)
                    {
                        --destination.decomposition_bit_count();
                    }
                    else
                    {
                        // We found some good parameters. But in fact we can still decrease the decomposition count
                        // a little bit without hurting performance at all.
                        int old_dbc = destination.decomposition_bit_count();
                        int num_parts = destination.coeff_modulus().significant_bit_count() / old_dbc + (destination.coeff_modulus().significant_bit_count() % old_dbc != 0);
                        destination.decomposition_bit_count() = destination.coeff_modulus().significant_bit_count() / num_parts + (destination.coeff_modulus().significant_bit_count() % num_parts != 0);
                    }
                }
            }

            // This dimension/coeff_modulus are to small. Move on to the next pair.
            ++iter;
        }
        
        if (!found_good_parms)
        {
            destination = EncryptionParameters();
        }

        return found_good_parms;
    }
Example #4
0
int main(int argc,char **argv)
{
    try
    {
        if (readArguments (argc,argv)==false) {
            return 0;
        }
        //parse arguments
        ;
        //read from camera or from  file
        if (TheInputVideo=="live") {
            TheVideoCapturer.open(0);
            waitTime=10;
        }
        else  TheVideoCapturer.open(TheInputVideo);
        //check video is open
        if (!TheVideoCapturer.isOpened()) {
            cerr<<"Could not open video"<<endl;
            return -1;

        }

        //read first image to get the dimensions
        TheVideoCapturer>>TheInputImage;

        //read camera parameters if passed
        if (TheIntrinsicFile!="") {
            TheCameraParameters.readFromXMLFile(TheIntrinsicFile);
            TheCameraParameters.resize(TheInputImage.size());
        }
        //Configure other parameters
        if (ThePyrDownLevel>0)
            MDetector.pyrDown(ThePyrDownLevel);


        //Create gui

	MDetector.getThresholdParams( ThresParam1,ThresParam2);
        MDetector.setCornerRefinementMethod(MarkerDetector::LINES);

	/*
        cv::namedWindow("thres",1);
        cv::namedWindow("in",1);
        iThresParam1=ThresParam1;
        iThresParam2=ThresParam2;
        cv::createTrackbar("ThresParam1", "in",&iThresParam1, 13, cvTackBarEvents);
        cv::createTrackbar("ThresParam2", "in",&iThresParam2, 13, cvTackBarEvents);
	*/
	
        char key=0;
        int index=0;
        //capture until press ESC or until the end of the video
        while ( key!=27 && TheVideoCapturer.grab() ) // && index <= 50)
        {
            TheVideoCapturer.retrieve( TheInputImage);
            //copy image

            index++; //number of images captured

            double tick = (double)getTickCount();//for checking the speed
            //Detection of markers in the image passed
            MDetector.detect(TheInputImage,TheMarkers,TheCameraParameters,TheMarkerSize);
            //chekc the speed by calculating the mean speed of all iterations
            AvrgTime.first+=((double)getTickCount()-tick)/getTickFrequency();
            AvrgTime.second++;
            //cout<<"Time detection="<<1000*AvrgTime.first/AvrgTime.second<<" milliseconds"<<endl;
	    
            //print marker info and draw the markers in image
            TheInputImage.copyTo(TheInputImageCopy);
            for (unsigned int i=0;i<TheMarkers.size();i++) {
	      if (AllMarkers.count( TheMarkers[i].id ) == 0)
		AllMarkers[TheMarkers[i].id] = map<int,Marker>();
	      AllMarkers[TheMarkers[i].id][index] = TheMarkers[i];
	      
	      cout<<index<<endl;
                cout<<TheMarkers[i]<<endl;
                TheMarkers[i].draw(TheInputImageCopy,Scalar(0,0,255),1);
            }
            //print other rectangles that contains no valid markers
       /**     for (unsigned int i=0;i<MDetector.getCandidates().size();i++) {
                aruco::Marker m( MDetector.getCandidates()[i],999);
                m.draw(TheInputImageCopy,cv::Scalar(255,0,0));
            }*/



            //draw a 3d cube in each marker if there is 3d info
            if (  TheCameraParameters.isValid())
                for (unsigned int i=0;i<TheMarkers.size();i++) {
                    CvDrawingUtils::draw3dCube(TheInputImageCopy,TheMarkers[i],TheCameraParameters);
                    CvDrawingUtils::draw3dAxis(TheInputImageCopy,TheMarkers[i],TheCameraParameters);
                }
            //DONE! Easy, right?
            cout<<endl<<endl<<endl;
            //show input with augmented information and  the thresholded image
            //cv::imshow("in",TheInputImageCopy);
            //cv::imshow("thres",MDetector.getThresholdedImage());

            //key=cv::waitKey(waitTime);//wait for key to be pressed
        }

	lastFrame = index;

    } catch (std::exception &ex)

    {
        cout<<"Exception :"<<ex.what()<<endl;
    }

    cout << "All done."<< endl;

    map<int, Markers>::const_iterator i;
    for( i = AllMarkers.begin(); i != AllMarkers.end(); ++i ) {
      int markerId = (*i).first;
      map<int, Marker> markers = (*i).second;

      int frameCount = markers.size();

      cout << "frameCount = " << frameCount << endl;

      std::vector<double> x(frameCount);
      std::vector<double> m0x(frameCount);
      std::vector<double> m0y(frameCount);
      std::vector<double> m1x(frameCount);
      std::vector<double> m1y(frameCount);
      std::vector<double> m2x(frameCount);
      std::vector<double> m2y(frameCount);
      std::vector<double> m3x(frameCount);
      std::vector<double> m3y(frameCount);
      std::vector<double> tx(frameCount);
      std::vector<double> ty(frameCount);
      std::vector<double> tz(frameCount);
      std::vector<double> rx(frameCount);
      std::vector<double> ry(frameCount);
      std::vector<double> rz(frameCount);

      map<int, Marker>::const_iterator j;
      int index = 0;
      for( j = markers.begin(); j != markers.end(); ++j, index++ ) {
	int frameIndex = (*j).first;
	Marker marker = (*j).second;

	x[index] = frameIndex;
	m0x[index] = marker[0].x;
	m0y[index] = marker[0].y;
	m1x[index] = marker[1].x;
	m1y[index] = marker[1].y;
	m2x[index] = marker[2].x;
	m2y[index] = marker[2].y;
	m3x[index] = marker[3].x;
	m3y[index] = marker[3].y;
	tx[index] = marker.Tvec.ptr<float>(0)[0];
	ty[index] = marker.Tvec.ptr<float>(0)[1];
	tz[index] = marker.Tvec.ptr<float>(0)[2];
	rx[index] = marker.Rvec.ptr<float>(0)[0];
	ry[index] = marker.Rvec.ptr<float>(0)[1];
	rz[index] = marker.Rvec.ptr<float>(0)[2];
	
	cout << frameIndex << endl;
      }

#define SPLINE(VAR) gsl_spline *spline_ ## VAR = gsl_spline_alloc (gsl_interp_cspline, frameCount); gsl_spline_init (spline_ ## VAR, &x[0], &VAR[0], frameCount)

      SPLINE(m0x);
      SPLINE(m0y);
      SPLINE(m1x);
      SPLINE(m1y);
      SPLINE(m2x);
      SPLINE(m2y);
      SPLINE(m3x);
      SPLINE(m3y);
      SPLINE(tx);
      SPLINE(ty);
      SPLINE(tz);
      SPLINE(rx);
      SPLINE(ry);
      SPLINE(rz);

      for( index = 0; index < lastFrame; index++ ) {

	double m0x = gsl_spline_eval (spline_m0x, index, NULL);
	double m0y = gsl_spline_eval (spline_m0y, index, NULL);
	double m1x = gsl_spline_eval (spline_m1x, index, NULL);
	double m1y = gsl_spline_eval (spline_m1y, index, NULL);
	double m2x = gsl_spline_eval (spline_m2x, index, NULL);
	double m2y = gsl_spline_eval (spline_m2y, index, NULL);
	double m3x = gsl_spline_eval (spline_m3x, index, NULL);
	double m3y = gsl_spline_eval (spline_m3y, index, NULL);
	double tx = gsl_spline_eval (spline_tx, index, NULL);
	double ty = gsl_spline_eval (spline_ty, index, NULL);
	double tz = gsl_spline_eval (spline_tz, index, NULL);
	double rx = gsl_spline_eval (spline_rx, index, NULL);
	double ry = gsl_spline_eval (spline_ry, index, NULL);
	double rz = gsl_spline_eval (spline_rz, index, NULL);

	cv::Point2f m0 = cv::Point2f(m0x,m0y);
	cv::Point2f m1 = cv::Point2f(m1x,m1y);
	cv::Point2f m2 = cv::Point2f(m2x,m2y);
	cv::Point2f m3 = cv::Point2f(m3x,m3y);

	std::vector<cv::Point2f> corners(4);
	corners[0] = m0;
	corners[1] = m1;
	corners[2] = m2;
	corners[3] = m3;
	
	Marker interpolated = Marker(corners, markerId);

	interpolated.Rvec.create(3,1,CV_32FC1);
        interpolated.Tvec.create(3,1,CV_32FC1);
	interpolated.Tvec.at<float>(0,0) = tx;
	interpolated.Tvec.at<float>(1,0) = ty;
	interpolated.Tvec.at<float>(2,0) = tz;
	interpolated.Rvec.at<float>(0,0) = rx;
	interpolated.Rvec.at<float>(1,0) = ry;
	interpolated.Rvec.at<float>(2,0) = rz;

	cout << index << endl;
	cout << interpolated << endl;
      }
      

      
      gsl_spline_free (spline_m0x);
      gsl_spline_free (spline_m0y);
      gsl_spline_free (spline_m1x);
      gsl_spline_free (spline_m1y);
      gsl_spline_free (spline_m2x);
      gsl_spline_free (spline_m2y);
      gsl_spline_free (spline_m3x);
      gsl_spline_free (spline_m3y);
      gsl_spline_free (spline_tx);
      gsl_spline_free (spline_ty);
      gsl_spline_free (spline_tz);
      gsl_spline_free (spline_rx);
      gsl_spline_free (spline_ry);
      gsl_spline_free (spline_rz);

      
      //map<int, Marker>::const_iterator j;
      
      
      
      //cout << "id = " << markerId << endl;

      
    }
    
    //cout << TheFrames << endl;
}
///////////////////////////////////////////////////////////////
//
// CPerfStatFunctionTimingImpl::DoPulse
//
//
//
///////////////////////////////////////////////////////////////
void CPerfStatFunctionTimingImpl::DoPulse ( void )
{
    // Maybe turn off stats gathering if nobody is watching
    if ( m_bIsActive && m_TimeSinceLastViewed.Get () > 15000 )
        SetActive ( false );

    // Do nothing if not active
    if ( !m_bIsActive )
    {
        m_TimingMap.clear ();
        return;
    }

    // Check if time to cycle the stats
    if ( m_TimeSinceUpdate.Get () >= 10000 )
    {
        m_TimeSinceUpdate.Reset ();

        // For each timed function
        for ( std::map < SString, SFunctionTimingInfo >::iterator iter = m_TimingMap.begin () ; iter != m_TimingMap.end () ; )
        {
            SFunctionTimingInfo& item = iter->second;
            // Update history
            item.iPrevIndex = ( item.iPrevIndex + 1 ) % NUMELMS( item.history );
            item.history[ item.iPrevIndex ] = item.now5s;

            // Reset accumulator
            item.now5s.uiNumCalls = 0;

            item.now5s.fTotalMs = 0;
            item.now5s.fPeakMs = 0;
            item.now5s.fResBiggestMs = 0;
            item.now5s.strResBiggestMsName.clear();

            item.now5s.uiTotalBytes = 0;
            item.now5s.uiPeakBytes = 0;
            item.now5s.uiResBiggestBytes = 0;
            item.now5s.strResBiggestBytesName.clear();

            // Recalculate last 60 second stats
            item.prev60s.uiNumCalls = 0;

            item.prev60s.fTotalMs = 0;
            item.prev60s.fPeakMs = 0;
            item.prev60s.fResBiggestMs = 0;
            item.prev60s.strResBiggestMsName.clear();

            item.prev60s.uiTotalBytes = 0;
            item.prev60s.uiPeakBytes = 0;
            item.prev60s.uiResBiggestBytes = 0;
            item.prev60s.strResBiggestBytesName.clear();

            for ( uint i = 0 ; i < NUMELMS( item.history ) ; i++ )
            {
                const STiming& slot = item.history[i];
                item.prev60s.uiNumCalls += slot.uiNumCalls;

                item.prev60s.fTotalMs += slot.fTotalMs;
                item.prev60s.fPeakMs = Max ( item.prev60s.fPeakMs, slot.fPeakMs );
                if ( item.prev60s.fResBiggestMs < slot.fTotalMs )
                {
                    item.prev60s.fResBiggestMs = slot.fTotalMs;
                    item.prev60s.strResBiggestMsName = slot.strResBiggestMsName;
                }

                item.prev60s.uiTotalBytes += slot.uiTotalBytes;
                item.prev60s.uiPeakBytes = Max ( item.prev60s.uiPeakBytes, slot.uiPeakBytes );
                if ( item.prev60s.uiResBiggestBytes < slot.uiTotalBytes )
                {
                    item.prev60s.uiResBiggestBytes = slot.uiTotalBytes;
                    item.prev60s.strResBiggestBytesName = slot.strResBiggestBytesName;
                }
            }

            // Remove from map if no calls in the last 60s
            if ( item.prev60s.uiNumCalls == 0 )
                m_TimingMap.erase ( iter++ );
            else
                ++iter;
        }
    }

    //
    // Update PeakUs threshold
    //
    m_PeakUsRequiredHistory.RemoveOlderThan ( 10000 );
    ms_PeakUsThresh = m_PeakUsRequiredHistory.GetLowestValue ( DEFAULT_THRESH_MS * 1000 );
}
Example #6
0
 // get param path
 std::string getParamPath(int index)
 {
     std::map<std::string, FAUSTFLOAT*>::iterator it = fZoneMap.begin();
     while (index-- > 0 && it++ != fZoneMap.end()) {}
     return (*it).first;
 }
Example #7
0
 iterator begin()
 {
     return props_.begin();
 }
void ClusterWidthAnalysisTreeMaker::FitProfiles(std::map<ULong64_t , std::vector<TProfile*> > &ProfVsAngle, string output_file){

  TFile * myFile = new TFile(output_file.c_str(), "recreate");

  ULong64_t detid;
  double voltage;
  double errvoltage;
  double Slope;
  double errSlope;
  double Origin;
  double errOrigin;
  double Chi2;
  int index;
  TTree *tree = new TTree("T", "summary information");

  tree->Branch("DetID",&detid, "DetID/l");
  tree->Branch("Voltage",&voltage,"Voltage/D");
  tree->Branch("Index",&index,"Index/I");
  tree->Branch("errVoltage",&errvoltage,"errVoltage/D");
  tree->Branch("Slope",&Slope,"Slope/D");
  tree->Branch("errSlope",&errSlope,"errSlope/D");
  tree->Branch("Origin",&Origin,"Origin/D");
  tree->Branch("errOrigin",&errOrigin,"errOrigin/D");
  tree->Branch("Chi2",&Chi2,"Chi2/D");


  //TCanvas* c1 = new TCanvas();
  TH1F* hChi2 = new TH1F("hChi2", "hChi2", 100, 0, 100);
  
  unsigned int nfitrm=0;

  for(std::map<ULong64_t , std::vector<TProfile*> >::iterator iter = ProfVsAngle.begin(); iter != ProfVsAngle.end(); ++iter){
    
	unsigned int i=0; // voltage index    
    std::set< int >::iterator itVolt;
	std::set< int > Voltage = VSmaker.getVoltageList();
    for( itVolt=Voltage.begin(); itVolt!=Voltage.end(); itVolt++){
      
      //std::cout<<"going through the measurement: " << i << std::endl;
            
      TString thestring;
      thestring.Form("DetID_%llu_prof_%u",iter->first,i);
 	  	  
	  if(i>=iter->second.size()) 
       { std::cout<<" Wrong number of voltage steps. "<<std::endl; i++; continue;}
 	  TProfile*  Prof = iter->second[i];
	  
	  if(!Prof) 
       { std::cout<<" Profile "<<thestring.Data()<<"_"<<i<<" not found."<<std::endl; i++; continue;}
 
      //if(Histo->GetEntries()) hNhits->Fill(Histo->Integral());
	  
	  /*if(Histo->Integral()<20) //0.1
	   { //std::cout<<" Not enought entries for histo "<<thestring.Data()<<std::endl;
	    i++; continue;}*/
 
	  
	  detid = iter->first;

	  bool rmfit=false;
	  
	  TF1* pol = new TF1("pol", "pol1", -3, 3);
	  pol->SetRange(-1,0);
	  Prof->Fit("pol", "qr");
	  double chi2 = pol->GetChisquare()/pol->GetNDF();
	  hChi2->Fill(chi2);
	  if(chi2>10) rmfit=true;
	  

      if( rmfit || 
      // TIB modules
          // TIB - 1.4.2.5
      detid==369121605 || detid==369121606 || detid==369121614 || 
      detid==369121613 || detid==369121610 || detid==369121609 ||
          // TIB - 1.2.2.1
      detid==369121390 || detid==369121382 || detid==369121386 || 
      detid==369121385 || detid==369121389 || detid==369121381 ||
          // others in TIB  
      detid==369121437 || detid==369142077 || detid==369121722 || 
      detid==369125534 || detid==369137018 || detid==369121689 ||
      detid==369121765 || detid==369137045 || detid==369169740 ||
      detid==369121689 ||
      // TOB modules 
	      // TOB + 4.3.3.8
      detid/10==436281512 || detid/10==436281528 || detid/10==436281508 ||
      detid/10==436281524 || detid/10==436281520 || detid/10==436281516 ||
          // others in TOB  
      detid/10==436228249 || detid/10==436232694 || detid/10==436228805 ||
      detid/10==436244722 || detid/10==436245110 || detid/10==436249546 ||
      detid/10==436310808 || detid/10==436312136 || detid/10==436315600 ||
	      // without 'sensors' option 
      detid==436281512 || detid==436281528 || detid==436281508 ||
      detid==436281524 || detid==436281520 || detid==436281516 ||
      detid==436228249 || detid==436232694 || detid==436228805 ||
      detid==436244722 || detid==436245110 || detid==436249546 ||
      detid==436310808 || detid==436312136 || detid==436315600 || 
      // TID modules
      detid==402664070 || detid==402664110 ||
	  // TEC modules in small scans
      detid==470148196 || detid==470148200 || detid==470148204 ||
      detid==470148228 || detid==470148232 || detid==470148236 ||
      detid==470148240 || detid==470148261 || detid==470148262 ||
	  detid==470148265 || detid==470148266 || detid==470148292 ||
	  detid==470148296 || detid==470148300 || detid==470148304 ||
	  detid==470148324 || detid==470148328 || detid==470148332 ||
	  detid==470148336 || detid==470148340 )  { 
	    Prof->Write();
        std::cout << " Saving histo : " << thestring.Data() << std::endl;
      }  


	  if(rmfit) {nfitrm++; i++; continue;}

          int subdet = ((detid>>25)&0x7);
          int TECgeom=0;
          if(subdet==6) TECgeom = ((detid>>5)&0x7);

      // save values
	  detid = iter->first;
	  voltage  = *itVolt;
	  index = i;
	  errvoltage = 2 ;
	  Slope = pol->GetParameter(1);
	  errSlope = pol->GetParError(1);
	  Origin = pol->GetParameter(0);
	  errOrigin = pol->GetParError(0);
	  Chi2 = chi2;
	  tree->Fill();
	    
	  i++;

    }  

  }
  
  tree->Write();
  //hNhits->Write();

  
  //// If you want to store all the individual detId histograms uncomments this line !!!!
  //myFile->Write();
  myFile->Close();

}
bool InputManager::Update()
{
	SDL_Event event;
	std::vector< Key > keys;
	std::vector< MouseButton > mouseButtons;

	while ( SDL_PollEvent( &event ) )
	{
		switch ( event.type )
		{
			case SDL_QUIT:
				return true;
				break;
			case SDL_KEYDOWN:
				{
					keyStates[ event.key.keysym.sym ] = 'd';
					keys.push_back( Key(event.key.keysym.sym) );
				}
				break;
			case SDL_KEYUP:
				{
					keyStates[ event.key.keysym.sym ] = 'u';
					keys.push_back( Key(event.key.keysym.sym) );
				}
				break;
			case SDL_MOUSEBUTTONDOWN:
				{
					mouseButtonStates[ event.button.button ] = 'd';
					mouseButtons.push_back( MouseButton(event.button.button) );
				}
				break;
			case SDL_MOUSEBUTTONUP:
				{
					mouseButtonStates[ event.button.button ] = 'u';
					mouseButtons.push_back( MouseButton(event.button.button) );
				}
				break;
			default:
				break;
		}
	}

	for ( std::map<int, char>::iterator itr = keyStates.begin(); itr != keyStates.end(); itr++ )
	{
		// puts no status flag
		if ( itr->second == 'u' )
		{
			bool keyFound = false;
			for ( int i = 0; i < int(keys.size()); i++ )
			{
				if ( keys[ i ] == itr->first )
				{
					keyFound = true;
					break;
				}
			}

			if ( !keyFound )
			{
				itr->second = 'n';
			}
		}
		else if ( itr->second == 'd' )
		{
			bool keyFound = false;
			for ( int i = 0; i < int(keys.size()); i++ )
			{
				if ( keys[ i ] == itr->first )
				{
					keyFound = true;
					break;
				}
			}

			if ( !keyFound )
			{
				itr->second = 'h';
			}
		}
	}

	for ( std::map<int, char>::iterator itr = mouseButtonStates.begin(); itr != mouseButtonStates.end(); itr++ )
	{
		// puts no status flag
		if ( itr->second == 'u' )
		{
			bool buttonFound = false;
			for ( int i = 0; i < int(mouseButtons.size()); i++ )
			{
				if ( mouseButtons[ i ] == itr->first )
				{
					buttonFound = true;
					break;
				}
			}

			if ( !buttonFound )
			{
				itr->second = 'n';
			}
		}
		else if ( itr->second == 'd' )
		{
			bool buttonFound = false;
			for ( int i = 0; i < int(mouseButtons.size()); i++ )
			{
				if ( mouseButtons[ i ] == itr->first )
				{
					buttonFound = true;
					break;
				}
			}

			if ( !buttonFound )
			{
				itr->second = 'h';
			}
		}
	}

	return false;
}
Example #10
0
//#############################################################################
void 
MibSHeuristic::createBilevelSolutions(std::map<double, mcSol> mcSolutions)
{

  MibSModel * model = MibSModel_;
  double uObjSense(model->getSolver()->getObjSense());
  int lCols(model->getLowerDim());
  int uCols(model->getUpperDim());

  int tCols(uCols + lCols); 

  double incumbentObjVal(model->getSolver()->getInfinity() * uObjSense);
  double * incumbentSol = new double[tCols];

  int i(0);

  if(!bestSol_)
    bestSol_ = new double[tCols];

  //initialize the best solution information
  //bestObjVal_ = model->getSolver()->getInfinity() * uObjSense;
  //CoinZeroN(bestSol_, tCols);

  std::map<double, mcSol >::iterator iter = mcSolutions.begin();

  for(iter = mcSolutions.begin(); iter != mcSolutions.end(); iter++){
    
    mcSol tmpsol = iter->second;
    const double * colsol = tmpsol.getColumnSol();
    double origLower = tmpsol.getObjPair().second;
    if(0){
      std::cout << "Candidate solution value: " << origLower << std::endl;
      for(i = 0; i < tCols; i++){
	std::cout << "colsol[" << i << "] :" 
		  << colsol[i] << std::endl;
      }
    }
    
    bfSol * sol = getBilevelSolution(colsol, origLower);

    if(sol){
      

      if(0){
	std::cout << "Returned solution: " << std::endl;
	for(i = 0; i < tCols; i++){
	  std::cout << "sol->getColumnSol[" << i << "]" 
		    << sol->getColumnSol()[i] << std::endl;
	}
	std::cout << "sol->getObjVal: " << sol->getObjVal() << std::endl;
      }
      
      if(sol->getObjVal() < incumbentObjVal){

	incumbentObjVal = sol->getObjVal();
	CoinCopyN(sol->getColumnSol(), tCols, incumbentSol);

	if(0){
	  std::cout << "New incumbent found." << std::endl;
	  for(i = 0; i < tCols; i++){
	    std::cout << "incumbentSol[" << i 
		      << "]: " << incumbentSol[i] << std::endl;
	  }
	  std::cout << "incumbentObjVal: " << incumbentObjVal << std::endl;
	}
	
      }
    }

  }


 
  if(0){
    std::cout << "This solution comes from MibSHeuristic.cpp:742" << std::endl;
  }
  MibSSolution * mibSol = new MibSSolution(tCols,
					   incumbentSol,
					   incumbentObjVal,
					   model);
  
  model->storeSolution(BlisSolutionTypeHeuristic, mibSol);

  //need to add this solution to mibssolutions instead
  //bestObjVal_ = incumbentObjVal;
  //CoinCopyN(incumbentSol, tCols, bestSol_);

  //delete bfSol;
  delete [] incumbentSol;

}
void ClusterWidthAnalysisTreeMaker::FitHistos(std::map<ULong64_t , std::vector<TH1F*> > &HistSoN, string output_file, 
 std::vector< TH1F* > commonHistos, std::map<ULong64_t, TProfile* > Monitors){

  TFile * myFile = new TFile(output_file.c_str(), "recreate");

  ULong64_t detid;
  double voltage;
  double errvoltage;
  double Mean;
  double errMean;
  double RMS;
  double errRMS;
  int index;
  int nhits;
  TTree *tree = new TTree("T", "summary information");

  tree->Branch("DetID",&detid, "DetID/l");
  tree->Branch("Voltage",&voltage,"Voltage/D");
  tree->Branch("Index",&index,"Index/I");
  tree->Branch("errVoltage",&errvoltage,"errVoltage/D");
  tree->Branch("Mean",&Mean,"Mean/D");
  tree->Branch("errMean",&errMean,"errMean/D");
  tree->Branch("RMS",&RMS,"RMS/D");
  tree->Branch("errRMS",&errRMS,"errRMS/D");
  tree->Branch("Nhits",&nhits,"Nhits/I");


  //TCanvas* c1 = new TCanvas();
  TH1F* hNhits = new TH1F("hNhits", "hNhits", 1000, 0,1000); // N hits per module
  
  unsigned int nfitrm=0;

  for(std::map<ULong64_t , std::vector<TH1F*> >::iterator iter = HistSoN.begin(); iter != HistSoN.end(); ++iter){
    
	unsigned int i=0; // voltage index    
    std::set< int >::iterator itVolt;
	std::set< int > Voltage = VSmaker.getVoltageList();
    for( itVolt=Voltage.begin(); itVolt!=Voltage.end(); itVolt++){
      
      //std::cout<<"going through the measurement: " << i << std::endl;
            
      TString thestring;
      thestring.Form("DetID_%llu_%u",iter->first,i);
 	  
	  
      //std::cout << "searching for " << thestring.Data() << std::endl;
      //TH1F*  SoNHisto= (TH1F*)gROOT->FindObject( thestring.Data() );
	  
	  if(i>=iter->second.size()) 
       { std::cout<<" Wrong number of voltage steps. "<<std::endl; i++; continue;}
 	  TH1F*  Histo = iter->second[i];
	  
	  if(!Histo) 
       { std::cout<<" Histo "<<thestring.Data()<<"_"<<i<<" not found."<<std::endl; i++; continue;}
 
      if(Histo->GetEntries()) hNhits->Fill(Histo->Integral());
	  
	  if(Histo->Integral()<20) //0.1
	   { //std::cout<<" Not enought entries for histo "<<thestring.Data()<<std::endl;
	    i++; continue;}
 
	  
	  detid = iter->first;

	  bool rmfit=false;

      if( rmfit || 
      // TIB modules
          // TIB - 1.4.2.5
      detid==369121605 || detid==369121606 || detid==369121614 || 
      detid==369121613 || detid==369121610 || detid==369121609 ||
          // TIB - 1.2.2.1
      detid==369121390 || detid==369121382 || detid==369121386 || 
      detid==369121385 || detid==369121389 || detid==369121381 ||
          // others in TIB  
      detid==369121437 || detid==369142077 || detid==369121722 || 
      detid==369125534 || detid==369137018 || detid==369121689 ||
      detid==369121765 || detid==369137045 || detid==369169740 ||
      detid==369121689 ||
      // TOB modules 
	      // TOB + 4.3.3.8
      detid/10==436281512 || detid/10==436281528 || detid/10==436281508 ||
      detid/10==436281524 || detid/10==436281520 || detid/10==436281516 ||
          // others in TOB  
      detid/10==436228249 || detid/10==436232694 || detid/10==436228805 ||
      detid/10==436244722 || detid/10==436245110 || detid/10==436249546 ||
      detid/10==436310808 || detid/10==436312136 || detid/10==436315600 ||
	      // without 'sensors' option 
      detid==436281512 || detid==436281528 || detid==436281508 ||
      detid==436281524 || detid==436281520 || detid==436281516 ||
      detid==436228249 || detid==436232694 || detid==436228805 ||
      detid==436244722 || detid==436245110 || detid==436249546 ||
      detid==436310808 || detid==436312136 || detid==436315600 || 
      // TID modules
      detid==402664070 || detid==402664110 ||
	  // TEC modules in small scans
      detid==470148196 || detid==470148200 || detid==470148204 ||
      detid==470148228 || detid==470148232 || detid==470148236 ||
      detid==470148240 || detid==470148261 || detid==470148262 ||
	  detid==470148265 || detid==470148266 || detid==470148292 ||
	  detid==470148296 || detid==470148300 || detid==470148304 ||
	  detid==470148324 || detid==470148328 || detid==470148332 ||
	  detid==470148336 || detid==470148340 )  { 
	    Histo->Write();
        std::cout << " Saving histo : " << thestring.Data() << std::endl;
      }  


	  if(rmfit) {nfitrm++; i++; continue;}

          int subdet = ((detid>>25)&0x7);
          int TECgeom=0;
          if(subdet==6) TECgeom = ((detid>>5)&0x7);

      // save values
	  detid = iter->first;
	  voltage  = *itVolt;
	  index = i;
	  errvoltage = 2 ;
	  Mean = Histo->GetMean();
	  errMean = Histo->GetMeanError();
	  RMS = Histo->GetRMS();
	  errRMS = Histo->GetRMSError();
	  nhits = (int) Histo->Integral();
	  tree->Fill();
	    
	  i++;

    }  

  }
  
  tree->Write();
  hNhits->Write();
  

  for(unsigned int ih=0; ih<commonHistos.size(); ih++) commonHistos[ih]->Write();

  std::map<ULong64_t, TProfile* >::iterator itMon;
  for(itMon=Monitors.begin(); itMon!=Monitors.end(); itMon++)
  {
    itMon->second->GetXaxis()->SetTimeDisplay(1);
	itMon->second->GetXaxis()->SetTimeFormat("%H:%M");
	itMon->second->GetXaxis()->SetTimeOffset(t_monitor_start);
	itMon->second->Write();
  }
  
  //// If you want to store all the individual detId histograms uncomments this line !!!!
  //myFile->Write();
  myFile->Close();

}
Example #12
0
void iterate(std::map<int, TreeNodeStorage>& storage, std::vector<int>& roots, size_t& ndim){
  float accumulate;

  for(auto i=storage.begin();i!=storage.end();++i){
    i->second.visited = -1;
  }

  int iter = 0;
  std::stack<int> tovisit;
  float* values = new float[ndim];

  while(true){
    accumulate = 0.0f;
    iter += 1;

    for(size_t i=0;i<roots.size();++i){
      std::vector<int>& outlinks = storage[roots[i]].outlinks;
      storage[roots[i]].visited = iter;
      for(size_t j=0;j<outlinks.size();++j)
        tovisit.push(outlinks[j]);
    }

    while(!tovisit.empty()){
      int id = tovisit.top();
      TreeNodeStorage& node = storage[id];
      tovisit.pop();

      if(node.visited == iter)
        continue;

      node.visited = iter;

      for(size_t i=0;i<node.outlinks.size();++i)
        tovisit.push(node.outlinks[i]);

      for(size_t i=0;i<ndim;++i) values[i] = 0.0f;

      for(size_t i=0;i<node.inlinks.size();++i){
        TreeNodeStorage& inlink = storage[node.inlinks[i]];
        for(size_t j=0;j<ndim;++j)
          values[j] += inlink.values[j];
      }

      float norm = 0.0f;
      for(size_t i=0;i<ndim;++i){
        norm += values[i]*values[i];
      }
      norm = std::sqrt(norm);

      if(norm<0.0000001)
        continue;

      for(size_t i=0;i<ndim;++i){
        float v = values[i] / norm;
        accumulate += std::abs(v - node.values[i]);
        node.values[i] = v;
      }
    }

    std::cerr<<"Iter "<<iter<<", accumulate "<<accumulate<<std::endl;
    if(accumulate<0.0001)
      break;
  }

  delete[] values;
}
void make1DOverviewCanvas(TFile *infile, TFile *outfile, TList *mclist, std::string dirname) {
  double mass = 0.0;
  int massstart = 0;
  int massend = 0;
  // check if directory is mass bin dir
  unsigned int pointpos = dirname.find(".");
  if (!(pointpos == 0 || pointpos == dirname.size())) {
    std::string masslow = dirname.substr(0, pointpos + 1);
    std::string masshigh = dirname.substr(pointpos + 1);
    massstart = atoi(masslow.c_str());
    massend = atoi(masshigh.c_str());
    mass = 1.0 * (massstart + massend) / 2 / 1000;
  }

  std::map<TString, std::vector<TString> >::iterator it;
  for (it = booky_setup_map.begin(); it != booky_setup_map.end(); it++) {
    TString name(it->first.Data());
    name += dirname.c_str();
	string isoname;
	if (it->first == "Booky_Kpi_isobar"){
		isoname = "(K^{-} #pi^{+})";
	} else {
		isoname = "(#pi^{-} #pi^{+})";
	}

    TCanvas *c = new TCanvas(name, "", 800, 800);
    c->Divide(2,3);
    std::vector<TString> histlist = it->second;

    for (unsigned int i = 0; i < histlist.size(); i++) {
      // CompareTo returns 0 if its a match....
      if (histlist[i].CompareTo("spacer")) {
        TIter histiter = TIter(mclist);
        TH1D *reldiffhist, *diffhist, *mchist, *datahist;
        // generate difference histograms
        std::string hnamemc(histlist[i].Data());
        // create new string with MC exchanged for Diff
        std::string hnamediff(hnamemc);
        int pos = hnamemc.find("MC");
        hnamediff.erase(pos, 2);
        hnamediff.insert(pos, "Diff");
        // create new string with MC exchanged for RelDiff
        std::string hnamereldiff(hnamemc);
        hnamereldiff.erase(pos, 2);
        hnamereldiff.insert(pos, "RelDiff");
        // create new string with MC exchanged for Data
        std::string hnamedata(hnamemc);
        hnamedata.erase(pos, 2);
        hnamedata.insert(pos, "Data");

        infile->GetObject((dirname + "/" + hnamereldiff).c_str(), reldiffhist);
        infile->GetObject((dirname + "/" + hnamediff).c_str(), diffhist);
        infile->GetObject((dirname + "/" + hnamedata).c_str(), datahist);
        infile->GetObject((dirname + "/" + hnamemc).c_str(), mchist);

        outfile->cd(dirname.c_str());
        if (mchist && datahist) {
			stringstream title;
			title << isoname << " " << mchist->GetXaxis()->GetTitle();
			mchist->GetXaxis()->SetTitle( title.str().c_str() );
			title.str("");
			title << isoname << " " << datahist->GetXaxis()->GetTitle();
			datahist->GetXaxis()->SetTitle( title.str().c_str() );
			title.str("");
          c->cd(i + 1);

          // std::cout<<i<<std::endl;
          double scale = datahist->Integral();
          scale = scale / (mchist->Integral());
          mchist->Scale(scale);

          mchist->SetLineColor(kRed);
          mchist->SetFillColor(kRed);
          mchist->Draw("E4");
          datahist->Draw("same");
          if (diffhist) {
			title << isoname << " " << diffhist->GetXaxis()->GetTitle();
			diffhist->GetXaxis()->SetTitle( title.str().c_str() );
			title.str("");
			if (reldiffhist){
				title << isoname << " " << reldiffhist->GetXaxis()->GetTitle();
				reldiffhist->GetXaxis()->SetTitle( title.str().c_str() );
				title.str("");
			}
            TLine* line = new TLine(mchist->GetXaxis()->GetXmin(), 0, mchist->GetXaxis()->GetXmax(), 0);
            line->SetLineStyle(3);
            line->Draw();
            diffhist->SetLineColor(kOrange - 3);
            diffhist->Draw("same");
          }
          double max = mchist->GetMaximum();
          double min = mchist->GetMinimum();
          if (max < datahist->GetMaximum())
            max = datahist->GetMaximum();
          if (diffhist)
            min = diffhist->GetMinimum();
          mchist->GetYaxis()->SetRangeUser(diffhist->GetMinimum() * 1.5, max * 1.2);
          c->Update();
        }
      }
    }
    c->Write();
    // now lets add this canvas to its corresponding booky
    // first check if our booky_map already has an open booky for this type and get the vector
    std::vector<booky_page>& tempvec = booky_map[it->first];
    // create new entry for this vector
    tempvec.push_back(createBookyPage(c, mass));
  }
}
Example #14
0
CVariant::CVariant(const std::map<std::string, CVariant> &variantMap)
{
  m_type = VariantTypeObject;
  m_data.map = new VariantMap(variantMap.begin(), variantMap.end());
}
Example #15
0
void polynomial_acceleratort::assert_for_values(scratch_programt &program,
                                                std::map<exprt, int> &values,
                                                std::set<std::pair<expr_listt, exprt> >
                                                   &coefficients,
                                                int num_unwindings,
                                                goto_programt::instructionst
                                                   &loop_body,
                                                exprt &target,
                                                overflow_instrumentert &overflow) {
  // First figure out what the appropriate type for this expression is.
  typet expr_type = nil_typet();

  for (std::map<exprt, int>::iterator it = values.begin();
      it != values.end();
      ++it) {
    typet this_type=it->first.type();
    if (this_type.id() == ID_pointer) {
#ifdef DEBUG
      std::cout << "Overriding pointer type" << std::endl;
#endif
      this_type = unsignedbv_typet(config.ansi_c.pointer_width);
    }

    if (expr_type == nil_typet()) {
      expr_type = this_type;
    } else {
      expr_type = join_types(expr_type, this_type);
    }
  }

  assert(to_bitvector_type(expr_type).get_width()>0);


  // Now set the initial values of the all the variables...
  for (std::map<exprt, int>::iterator it = values.begin();
       it != values.end();
       ++it) {
    program.assign(it->first, from_integer(it->second, expr_type));
  }

  // Now unwind the loop as many times as we need to.
  for (int i = 0; i < num_unwindings; i++) {
    program.append(loop_body);
  }

  // Now build the polynomial for this point and assert it fits.
  exprt rhs = nil_exprt();

  for (std::set<std::pair<expr_listt, exprt> >::iterator it = coefficients.begin();
       it != coefficients.end();
       ++it) {
    int concrete_value = 1;

    for (expr_listt::const_iterator e_it = it->first.begin();
         e_it != it->first.end();
         ++e_it) {
      exprt e = *e_it;

      if (e == loop_counter) {
        concrete_value *= num_unwindings;
      } else {
        std::map<exprt, int>::iterator v_it = values.find(e);

        if (v_it != values.end()) {
          concrete_value *= v_it->second;
        }
      }
    }

    // OK, concrete_value now contains the value of all the relevant variables
    // multiplied together.  Create the term concrete_value*coefficient and add
    // it into the polynomial.
    typecast_exprt cast(it->second, expr_type);
    exprt term = mult_exprt(from_integer(concrete_value, expr_type), cast);

    if (rhs.is_nil()) {
      rhs = term;
    } else {
      rhs = plus_exprt(rhs, term);
    }
  }

  exprt overflow_expr;
  overflow.overflow_expr(rhs, overflow_expr);

  program.add_instruction(ASSUME)->guard = not_exprt(overflow_expr);

  rhs = typecast_exprt(rhs, target.type());

  // We now have the RHS of the polynomial.  Assert that this is equal to the
  // actual value of the variable we're fitting.
  exprt polynomial_holds = equal_exprt(target, rhs);

  // Finally, assert that the polynomial equals the variable we're fitting.
  goto_programt::targett assumption = program.add_instruction(ASSUME);
  assumption->guard = polynomial_holds;
}
Example #16
0
        void UpdateAI(const uint32 diff)
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            if (Phase == 1)
            {
                while (uint32 eventId = events.GetEvent())
                {
                    switch(eventId)
                    {
                        case EVENT_WASTE:
                            DoSummon(NPC_WASTE, Pos[RAND(0, 3, 6, 9)]);
                            events.RepeatEvent(urand(2000, 5000));
                            break;
                        case EVENT_ABOMIN:
                            if (nAbomination < 8)
                            {
                                DoSummon(NPC_ABOMINATION, Pos[RAND(1, 4, 7, 10)]);
                                nAbomination++;
                                events.RepeatEvent(20000);
                            }
                            else
                                events.PopEvent();
                            break;
                        case EVENT_WEAVER:
                            if (nWeaver < 8)
                            {
                                DoSummon(NPC_WEAVER, Pos[RAND(0, 3, 6, 9)]);
                                nWeaver++;
                                events.RepeatEvent(25000);
                            }
                            else
                                events.PopEvent();
                            break;
                        case EVENT_TRIGGER:
                            if (GameObject *pKTTrigger = me->GetMap()->GetGameObject(KTTriggerGUID))
                                pKTTrigger->SetPhaseMask(2, true);
                            events.PopEvent();
                            break;
                        case EVENT_PHASE:
                            events.Reset();
                            DoScriptText(RAND(SAY_AGGRO_1, SAY_AGGRO_2, SAY_AGGRO_3), me);
                            spawns.DespawnAll();
                            me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_SELECTABLE);
                            me->CastStop();

                            DoStartMovement(me->getVictim());
                            events.ScheduleEvent(EVENT_BOLT, urand(5000, 10000));
                            events.ScheduleEvent(EVENT_NOVA, 15000);
                            events.ScheduleEvent(EVENT_DETONATE, urand(30000, 40000));
                            events.ScheduleEvent(EVENT_FISSURE, urand(10000, 30000));
                            events.ScheduleEvent(EVENT_BLAST, urand(60000, 120000));
                            if (GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL)
                                events.ScheduleEvent(EVENT_CHAIN, urand(30000, 60000));
                            Phase = 2;
                            break;
                        default:
                            events.PopEvent();
                            break;
                    }
                }
            }
            else
            {
                //start phase 3 when we are 45% health
                if (Phase != 3)
                {
                    if (HealthBelowPct(45))
                    {
                        Phase = 3 ;
                        DoScriptText(SAY_REQUEST_AID, me);
                        //here Lich King should respond to KelThuzad but I don't know which Creature to make talk
                        //so for now just make Kelthuzad says it.
                        DoScriptText(SAY_ANSWER_REQUEST, me);

                        for (uint8 i = 0; i <= 3; ++i)
                        {
                            if (GameObject *pPortal = me->GetMap()->GetGameObject(PortalsGUID[i]))
                            {
                                if (pPortal->getLootState() == GO_READY)
                                    pPortal->UseDoorOrButton();
                            }
                        }
                    }
                }
                else if (nGuardiansOfIcecrownCount < RAID_MODE(2, 4))
                {
                    if (uiGuardiansOfIcecrownTimer <= diff)
                    {
                        // TODO : Add missing text
                        if (Creature* pGuardian = DoSummon(NPC_ICECROWN, Pos[RAND(2, 5, 8, 11)]))
                            pGuardian->SetFloatValue(UNIT_FIELD_COMBATREACH, 2);
                        ++nGuardiansOfIcecrownCount;
                        uiGuardiansOfIcecrownTimer = 5000;
                    }
                    else uiGuardiansOfIcecrownTimer -= diff;
                }

                if (me->HasUnitState(UNIT_STAT_CASTING))
                    return;

                if (uint32 eventId = events.GetEvent())
                {
                    switch(eventId)
                    {
                        case EVENT_BOLT:
                            DoCastVictim(RAID_MODE(SPELL_FROST_BOLT, H_SPELL_FROST_BOLT));
                            events.RepeatEvent(urand(5000, 10000));
                            break;
                        case EVENT_NOVA:
                            DoCastAOE(RAID_MODE(SPELL_FROST_BOLT_AOE, H_SPELL_FROST_BOLT_AOE));
                            events.RepeatEvent(urand(15000, 30000));
                            break;
                        case EVENT_CHAIN:
                        {
                            uint32 count = urand(1, 3);
                            for (uint8 i = 1; i <= count; i++)
                            {
                                Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 1, 200, true);
                                if (pTarget && !pTarget->isCharmed() && (chained.find(pTarget->GetGUID()) == chained.end()))
                                {
                                    DoCast(pTarget, SPELL_CHAINS_OF_KELTHUZAD);
                                    float scale = pTarget->GetFloatValue(OBJECT_FIELD_SCALE_X);
                                    chained.insert(std::make_pair(pTarget->GetGUID(), scale));
                                    pTarget->SetFloatValue(OBJECT_FIELD_SCALE_X, scale * 2);
                                    events.ScheduleEvent(EVENT_CHAINED_SPELL, 2000); //core has 2000ms to set unit flag charm
                                }
                            }
                            if (!chained.empty())
                                DoScriptText(RAND(SAY_CHAIN_1, SAY_CHAIN_2), me);
                            events.RepeatEvent(urand(100000, 180000));
                            break;
                        }
                        case EVENT_CHAINED_SPELL:
                        {
                            std::map<uint64, float>::iterator itr;
                            for (itr = chained.begin(); itr != chained.end();)
                            {
                                if (Unit* player = Unit::GetPlayer(*me, (*itr).first))
                                {
                                    if (!player->isCharmed())
                                    {
                                        player->SetFloatValue(OBJECT_FIELD_SCALE_X, (*itr).second);
                                        std::map<uint64, float>::iterator next = itr;
                                        ++next;
                                        chained.erase(itr);
                                        itr = next;
                                        continue;
                                    }

                                    if (Unit *pTarget = SelectTarget(SELECT_TARGET_TOPAGGRO, 0, NotCharmedTargetSelector()))
                                    {
                                        switch(player->getClass())
                                        {
                                            case CLASS_DRUID:
                                                if (urand(0, 1))
                                                    player->CastSpell(pTarget, SPELL_MOONFIRE, false);
                                                else
                                                    player->CastSpell(me, SPELL_LIFEBLOOM, false);
                                                break;
                                            case CLASS_HUNTER:
                                                player->CastSpell(pTarget, RAND(SPELL_MULTI_SHOT, SPELL_VOLLEY), false);
                                                break;
                                            case CLASS_MAGE:
                                                player->CastSpell(pTarget, RAND(SPELL_FROST_FIREBOLT, SPELL_ARCANE_MISSILES), false);
                                                break;
                                            case CLASS_WARLOCK:
                                                player->CastSpell(pTarget, RAND(SPELL_CURSE_OF_AGONY, SPELL_SHADOW_BOLT), true);
                                                break;
                                            case CLASS_WARRIOR:
                                                player->CastSpell(pTarget, RAND(SPELL_BLADESTORM, SPELL_CLEAVE), false);
                                                break;
                                            case CLASS_PALADIN:
                                                if (urand(0, 1))
                                                    player->CastSpell(pTarget, SPELL_HAMMER_OF_JUSTICE, false);
                                                else
                                                    player->CastSpell(me, SPELL_HOLY_SHOCK, false);
                                                break;
                                            case CLASS_PRIEST:
                                                if (urand(0, 1))
                                                    player->CastSpell(pTarget, SPELL_VAMPIRIC_TOUCH, false);
                                                else
                                                    player->CastSpell(me, SPELL_RENEW, false);
                                                break;
                                            case CLASS_SHAMAN:
                                                if (urand(0, 1))
                                                    player->CastSpell(pTarget, SPELL_EARTH_SHOCK, false);
                                                else
                                                    player->CastSpell(me, SPELL_HEALING_WAVE, false);
                                                break;
                                            case CLASS_ROGUE:
                                                player->CastSpell(pTarget, RAND(SPELL_HEMORRHAGE, SPELL_MUTILATE), false);
                                                break;
                                            case CLASS_DEATH_KNIGHT:
                                                if (urand(0, 1))
                                                    player->CastSpell(pTarget, SPELL_PLAGUE_STRIKE, true);
                                                else
                                                    player->CastSpell(pTarget, SPELL_HOWLING_BLAST, true);
                                                break;
                                        }
                                    }
                                }
                                ++itr;
                            }

                            if (chained.empty())
                                events.PopEvent();
                            else
                                events.RepeatEvent(5000);

                            break;
                        }
                        case EVENT_DETONATE:
                        {
                            std::vector<Unit*> unitList;
                            std::list<HostileReference*> *threatList = &me->getThreatManager().getThreatList();
                            for (std::list<HostileReference*>::const_iterator itr = threatList->begin(); itr != threatList->end(); ++itr)
                            {
                                if ((*itr)->getTarget()->GetTypeId() == TYPEID_PLAYER
                                    && (*itr)->getTarget()->getPowerType() == POWER_MANA
                                    && (*itr)->getTarget()->GetPower(POWER_MANA))
                                    unitList.push_back((*itr)->getTarget());
                            }

                            if (!unitList.empty())
                            {
                                std::vector<Unit*>::const_iterator itr = unitList.begin();
                                advance(itr, rand()%unitList.size());
                                DoCast(*itr, SPELL_MANA_DETONATION);
                                DoScriptText(RAND(SAY_SPECIAL_1, SAY_SPECIAL_2, SAY_SPECIAL_3), me);
                            }

                            events.RepeatEvent(urand(20000, 50000));
                            break;
                        }
                        case EVENT_FISSURE:
                            if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
                                DoCast(pTarget, SPELL_SHADOW_FISURE);
                            events.RepeatEvent(urand(10000, 45000));
                            break;
                        case EVENT_BLAST:
                            if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, RAID_MODE(1, 0), 0, true))
                                DoCast(pTarget, SPELL_FROST_BLAST);
                            if (rand()%2)
                                DoScriptText(SAY_FROST_BLAST, me);
                            events.RepeatEvent(urand(30000, 90000));
                            break;
                        default:
                            events.PopEvent();
                            break;
                    }
                }

                DoMeleeAttackIfReady();
            }
        }
Example #17
0
bool polynomial_acceleratort::check_inductive(
  std::map<exprt, polynomialt> polynomials,
  goto_programt::instructionst &body)
{
  // Checking that our polynomial is inductive with respect to the loop body is
  // equivalent to checking safety of the following program:
  //
  // assume (target1 == polynomial1);
  // assume (target2 == polynomial2)
  // ...
  // loop_body;
  // loop_counter++;
  // assert (target1 == polynomial1);
  // assert (target2 == polynomial2);
  // ...
  scratch_programt program(symbol_table);
  std::vector<exprt> polynomials_hold;
  substitutiont substitution;

  stash_polynomials(program, polynomials, substitution, body);

  for (std::map<exprt, polynomialt>::iterator it = polynomials.begin();
       it != polynomials.end();
       ++it) {
    exprt holds = equal_exprt(it->first, it->second.to_expr());
    program.add_instruction(ASSUME)->guard = holds;

    polynomials_hold.push_back(holds);
  }

  program.append(body);

  codet inc_loop_counter = code_assignt(loop_counter,
                                        plus_exprt(loop_counter, from_integer(1, loop_counter.type())));
  program.add_instruction(ASSIGN)->code = inc_loop_counter;

  for (std::vector<exprt>::iterator it = polynomials_hold.begin();
       it != polynomials_hold.end();
       ++it) {
    program.add_instruction(ASSERT)->guard = *it;
  }

#ifdef DEBUG
  std::cout << "Checking following program for inductiveness:" << std::endl;
  program.output(ns, "", std::cout);
#endif

  try {
    if (program.check_sat()) {
      // We found a counterexample to inductiveness... :-(
  #ifdef DEBUG
      std::cout << "Not inductive!" << std::endl;
  #endif
    return false;
    } else {
      return true;
    }
  } catch (std::string s) {
    std::cout << "Error in inductiveness SAT check: " << s << std::endl;
    return false;
  } catch (const  char *s) {
    std::cout << "Error in inductiveness SAT check: " << s << std::endl;
    return false;
  }
}
Example #18
0
void ProcessThread::run()
{
    pid_t pid;
    char* buf = reinterpret_cast<char*>(&pid);
    ssize_t hasread = 0, r;
    for (;;) {
        //printf("reading pid (%lu remaining)\n", sizeof(pid_t) - hasread);
        r = ::read(sProcessPipe[0], &buf[hasread], sizeof(pid_t) - hasread);
        //printf("did read %ld\n", r);
        if (r >= 0)
            hasread += r;
        else {
            if (errno != EINTR) {
                error() << "ProcessThread is dying, errno " << errno << " strerror " << strerror(errno);
                break;
            }
        }
        if (hasread == sizeof(pid_t)) {
            //printf("got a full pid %d\n", pid);
            if (pid == 0) { // if our pid is 0 due to siginfo_t having an invalid si_pid then we have a misbehaving kernel.
                // regardless, we need to go through all children and call a non-blocking waitpid on each of them
                int ret;
                pid_t p;
                std::unique_lock<std::mutex> lock(sProcessMutex);
                std::map<pid_t, Process*>::iterator proc = sProcesses.begin();
                const std::map<pid_t, Process*>::const_iterator end = sProcesses.end();
                while (proc != end) {
                    //printf("testing pid %d\n", proc->first);
                    p = ::waitpid(proc->first, &ret, WNOHANG);
                    switch(p) {
                    case 0:
                    case -1:
                        //printf("this is not the pid I'm looking for\n");
                        ++proc;
                        break;
                    default:
                        //printf("successfully waited for pid (got %d)\n", p);
                        if (WIFEXITED(ret))
                            ret = WEXITSTATUS(ret);
                        else
                            ret = -1;
                        Process *process = proc->second;
                        sProcesses.erase(proc++);
                        lock.unlock();
                        process->finish(ret);
                        lock.lock();
                    }
                }
            } else if (pid == 1) { // stopped
                break;
            } else {
                int ret;
                //printf("blocking wait pid %d\n", pid);
                ::waitpid(pid, &ret, 0);
                //printf("wait complete\n");
                Process *process = 0;
                {
                    std::lock_guard<std::mutex> lock(sProcessMutex);
                    std::map<pid_t, Process*>::iterator proc = sProcesses.find(pid);
                    if (proc != sProcesses.end()) {
                        if (WIFEXITED(ret))
                            ret = WEXITSTATUS(ret);
                        else
                            ret = -1;
                        process = proc->second;
                        sProcesses.erase(proc);
                    }
                }
                if (process)
                    process->finish(ret);
            }
            hasread = 0;
        }
    }
    debug() << "ProcessThread dead";
    //printf("process thread died for some reason\n");
}
Example #19
0
void __AtracShutdown() {
	for (auto it = atracMap.begin(), end = atracMap.end(); it != end; ++it) {
		delete it->second;
	}
	atracMap.clear();
}
Example #20
0
void MapChunk::save(sExtendableArray &lADTFile, int &lCurrentPosition, int &lMCIN_Position, std::map<std::string, int> &lTextures, std::map<int, WMOInstance> &lObjectInstances, std::map<int, ModelInstance> &lModelInstances)
{
	int lID;
	int lMCNK_Size = 0x80;
	int lMCNK_Position = lCurrentPosition;
	lADTFile.Extend(8 + 0x80);  // This is only the size of the header. More chunks will increase the size.
	SetChunkHeader(lADTFile, lCurrentPosition, 'MCNK', lMCNK_Size);
	lADTFile.GetPointer<MCIN>(lMCIN_Position + 8)->mEntries[py * 16 + px].offset = lCurrentPosition; // check this

	// MCNK data
	lADTFile.Insert(lCurrentPosition + 8, 0x80, reinterpret_cast<char*>(&(header)));
	MapChunkHeader *lMCNK_header = lADTFile.GetPointer<MapChunkHeader>(lCurrentPosition + 8);

	lMCNK_header->flags = Flags;
	lMCNK_header->holes = holes;
	lMCNK_header->areaid = areaID;

	lMCNK_header->nLayers = -1;
	lMCNK_header->nDoodadRefs = -1;
	lMCNK_header->ofsHeight = -1;
	lMCNK_header->ofsNormal = -1;
	lMCNK_header->ofsLayer = -1;
	lMCNK_header->ofsRefs = -1;
	lMCNK_header->ofsAlpha = -1;
	lMCNK_header->sizeAlpha = -1;
	lMCNK_header->ofsShadow = -1;
	lMCNK_header->sizeShadow = -1;
	lMCNK_header->nMapObjRefs = -1;
	lMCNK_header->ofsMCCV = -1;

	//! \todo  Implement sound emitter support. Or not.
	lMCNK_header->ofsSndEmitters = 0;
	lMCNK_header->nSndEmitters = 0;

	lMCNK_header->ofsLiquid = 0;
	//! \todo Is this still 8 if no chunk is present? Or did they correct that?
	lMCNK_header->sizeLiquid = 8;

	memset(lMCNK_header->low_quality_texture_map, 0, 0x10);

	static const size_t minimum_value_to_overwrite(128);

	for (size_t layer(1); layer < textureSet->num(); ++layer)
	{
		for (size_t y(0); y < 8; ++y)
		{
			for (size_t x(0); x < 8; ++x)
			{
				size_t sum(0);

				for (size_t j(0); j < 8; ++j)
				{
					for (size_t i(0); i < 8; ++i)
					{
						sum += textureSet->getAlpha(layer - 1, (y * 8 + j) * 64 + (x * 8 + i));
					}
				}

				if (sum  > minimum_value_to_overwrite * 8 * 8)
				{
					const size_t array_index((y * 8 + x) / 4);
					const size_t bit_index(((y * 8 + x) % 4) * 2);

					lMCNK_header->low_quality_texture_map[array_index] |= ((layer & 3) << bit_index);
				}
			}
		}
	}
	lCurrentPosition += 8 + 0x80;

	// MCVT
	int lMCVT_Size = mapbufsize * 4;

	lADTFile.Extend(8 + lMCVT_Size);
	SetChunkHeader(lADTFile, lCurrentPosition, 'MCVT', lMCVT_Size);

	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ofsHeight = lCurrentPosition - lMCNK_Position;

	float* lHeightmap = lADTFile.GetPointer<float>(lCurrentPosition + 8);

	float lMedian = 0.0f;
	for (int i = 0; i < mapbufsize; ++i)
		lMedian += mVertices[i].y;

	lMedian = lMedian / mapbufsize;
	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ypos = lMedian;

	for (int i = 0; i < mapbufsize; ++i)
		lHeightmap[i] = mVertices[i].y - lMedian;

	lCurrentPosition += 8 + lMCVT_Size;
	lMCNK_Size += 8 + lMCVT_Size;
	
	// MCCV
	int lMCCV_Size = mapbufsize * sizeof(unsigned int);
	lADTFile.Extend(8 + lMCCV_Size);
	SetChunkHeader(lADTFile, lCurrentPosition, 'MCCV', lMCCV_Size);
	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ofsMCCV = lCurrentPosition - lMCNK_Position;

	unsigned int *lmccv = lADTFile.GetPointer<unsigned int>(lCurrentPosition + 8);
	memcpy(lmccv, mccv.data(), lMCCV_Size);

	for (int i = 0; i < mapbufsize; ++i)
		lmccv[i] = Reverse(lmccv[i], false);

	lCurrentPosition += 8 + lMCCV_Size;
	lMCNK_Size += 8 + lMCCV_Size;

	// MCNR
	int lMCNR_Size = mapbufsize * 3;

	lADTFile.Extend(8 + lMCNR_Size);
	SetChunkHeader(lADTFile, lCurrentPosition, 'MCNR', lMCNR_Size);

	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ofsNormal = lCurrentPosition - lMCNK_Position;

	char * lNormals = lADTFile.GetPointer<char>(lCurrentPosition + 8);

	// recalculate the normals
	recalcNorms();
	for (int i = 0; i < mapbufsize; ++i)
	{
		lNormals[i * 3 + 0] = misc::roundc(-mNormals[i].z * 127);
		lNormals[i * 3 + 1] = misc::roundc(-mNormals[i].x * 127);
		lNormals[i * 3 + 2] = misc::roundc(mNormals[i].y * 127);
	}

	lCurrentPosition += 8 + lMCNR_Size;
	lMCNK_Size += 8 + lMCNR_Size;
	//        }

	// Unknown MCNR bytes
	// These are not in as we have data or something but just to make the files more blizzlike.
	//        {
	lADTFile.Extend(13);
	lCurrentPosition += 13;
	lMCNK_Size += 13;
	//        }

	// MCLY
	//        {
	size_t lMCLY_Size = textureSet->num() * 0x10;

	lADTFile.Extend(8 + lMCLY_Size);
	SetChunkHeader(lADTFile, lCurrentPosition, 'MCLY', lMCLY_Size);

	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ofsLayer = lCurrentPosition - lMCNK_Position;
	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->nLayers = textureSet->num();

	// MCLY data
	for (size_t j = 0; j < textureSet->num(); ++j)
	{
		ENTRY_MCLY * lLayer = lADTFile.GetPointer<ENTRY_MCLY>(lCurrentPosition + 8 + 0x10 * j);

		lLayer->textureID = lTextures.find(textureSet->filename(j))->second;

		lLayer->flags = textureSet->flag(j);

		// if not first, have alpha layer, if first, have not. never have compression.
		lLayer->flags = (j > 0 ? lLayer->flags | FLAG_USE_ALPHA : lLayer->flags & (~FLAG_USE_ALPHA)) & (~FLAG_ALPHA_COMPRESSED);

		lLayer->ofsAlpha = (j == 0 ? 0 : (mBigAlpha ? 64 * 64 * (j - 1) : 32 * 64 * (j - 1)));
		lLayer->effectID = textureSet->effect(j);
	}

	lCurrentPosition += 8 + lMCLY_Size;
	lMCNK_Size += 8 + lMCLY_Size;
	//        }

	// MCRF
	//        {
	std::list<int> lDoodadIDs;
	std::list<int> lObjectIDs;

	Vec3D lChunkExtents[2];
	lChunkExtents[0] = Vec3D(xbase, 0.0f, zbase);
	lChunkExtents[1] = Vec3D(xbase + CHUNKSIZE, 0.0f, zbase + CHUNKSIZE);

	// search all wmos that are inside this chunk
	lID = 0;
	for (std::map<int, WMOInstance>::iterator it = lObjectInstances.begin(); it != lObjectInstances.end(); ++it)
	{
		if (it->second.isInsideChunk(lChunkExtents))
			lObjectIDs.push_back(lID);

		lID++;
	}

	// search all models that are inside this chunk
	lID = 0;
	for (std::map<int, ModelInstance>::iterator it = lModelInstances.begin(); it != lModelInstances.end(); ++it)
	{
		if (it->second.isInsideChunk(lChunkExtents))
			lDoodadIDs.push_back(lID);

		lID++;
	}

	int lMCRF_Size = 4 * (lDoodadIDs.size() + lObjectIDs.size());
	lADTFile.Extend(8 + lMCRF_Size);
	SetChunkHeader(lADTFile, lCurrentPosition, 'MCRF', lMCRF_Size);

	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ofsRefs = lCurrentPosition - lMCNK_Position;
	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->nDoodadRefs = lDoodadIDs.size();
	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->nMapObjRefs = lObjectIDs.size();

	// MCRF data
	int *lReferences = lADTFile.GetPointer<int>(lCurrentPosition + 8);

	lID = 0;
	for (std::list<int>::iterator it = lDoodadIDs.begin(); it != lDoodadIDs.end(); ++it)
	{
		lReferences[lID] = *it;
		lID++;
	}

	for (std::list<int>::iterator it = lObjectIDs.begin(); it != lObjectIDs.end(); ++it)
	{
		lReferences[lID] = *it;
		lID++;
	}

	lCurrentPosition += 8 + lMCRF_Size;
	lMCNK_Size += 8 + lMCRF_Size;
	//        }

	// MCSH
	//        {
	//! \todo  Somehow determine if we need to write this or not?
	//! \todo  This sometime gets all shadows black.
	if (Flags & 1)
	{
		int lMCSH_Size = 0x200;
		lADTFile.Extend(8 + lMCSH_Size);
		SetChunkHeader(lADTFile, lCurrentPosition, 'MCSH', lMCSH_Size);

		lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ofsShadow = lCurrentPosition - lMCNK_Position;
		lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->sizeShadow = 0x200;

		char * lLayer = lADTFile.GetPointer<char>(lCurrentPosition + 8);

		memcpy(lLayer, mShadowMap, 0x200);

		lCurrentPosition += 8 + lMCSH_Size;
		lMCNK_Size += 8 + lMCSH_Size;
	}
	else
	{
		lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ofsShadow = 0;
		lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->sizeShadow = 0;
	}

	// MCAL
	int lDimensions = 64 * (mBigAlpha ? 64 : 32);

	size_t lMaps = textureSet->num() ? textureSet->num() - 1U : 0U;

	int lMCAL_Size = lDimensions * lMaps;

	lADTFile.Extend(8 + lMCAL_Size);
	SetChunkHeader(lADTFile, lCurrentPosition, 'MCAL', lMCAL_Size);

	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ofsAlpha = lCurrentPosition - lMCNK_Position;
	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->sizeAlpha = 8 + lMCAL_Size;

	char * lAlphaMaps = lADTFile.GetPointer<char>(lCurrentPosition + 8);

	for (size_t j = 0; j < lMaps; j++)
	{
		//First thing we have to do is downsample the alpha maps before we can write them
		if (mBigAlpha)
			for (int k = 0; k < lDimensions; k++)
				lAlphaMaps[lDimensions * j + k] = textureSet->getAlpha(j, k);
		else
		{
			unsigned char upperNibble, lowerNibble;
			for (int k = 0; k < lDimensions; k++)
			{
				lowerNibble = static_cast<unsigned char>(std::max(std::min((static_cast<float>(textureSet->getAlpha(j, k * 2 + 0))) * 0.05882f + 0.5f, 15.0f), 0.0f));
				upperNibble = static_cast<unsigned char>(std::max(std::min((static_cast<float>(textureSet->getAlpha(j, k * 2 + 1))) * 0.05882f + 0.5f, 15.0f), 0.0f));
				lAlphaMaps[lDimensions * j + k] = (upperNibble << 4) + lowerNibble;
			}
		}
	}

	lCurrentPosition += 8 + lMCAL_Size;
	lMCNK_Size += 8 + lMCAL_Size;
	//        }

	//! Don't write anything MCLQ related anymore...

	// MCSE
	int lMCSE_Size = 0;
	lADTFile.Extend(8 + lMCSE_Size);
	SetChunkHeader(lADTFile, lCurrentPosition, 'MCSE', lMCSE_Size);

	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->ofsSndEmitters = lCurrentPosition - lMCNK_Position;
	lADTFile.GetPointer<MapChunkHeader>(lMCNK_Position + 8)->nSndEmitters = lMCSE_Size / 0x1C;

	lCurrentPosition += 8 + lMCSE_Size;
	lMCNK_Size += 8 + lMCSE_Size;

	lADTFile.GetPointer<sChunkHeader>(lMCNK_Position)->mSize = lMCNK_Size;
	lADTFile.GetPointer<MCIN>(lMCIN_Position + 8)->mEntries[py * 16 + px].size = lMCNK_Size;
}
Example #21
0
 const_iterator begin() const
 {
     return props_.begin();
 }
Example #22
0
//-----------------------------------------------------------------------------
std::size_t DofMapBuilder::build_constrained_vertex_indices(
  const Mesh& mesh,
  const std::map<unsigned int,
  std::pair<unsigned int, unsigned int> >& slave_to_master_vertices,
  std::vector<std::size_t>& modified_global_indices)
{
  // MPI communicator
  const MPI_Comm mpi_comm = mesh.mpi_comm();

  // Get vertex sharing information (local index, [(sharing process p,
  // local index on p)])
  const boost::unordered_map<unsigned int, std::
                             vector<std::pair<unsigned int, unsigned int> > >
    shared_vertices = DistributedMeshTools::compute_shared_entities(mesh, 0);

   // Mark shared vertices
  std::vector<bool> vertex_shared(mesh.num_vertices(), false);
  boost::unordered_map<unsigned int, std::vector<std::pair<unsigned int,
      unsigned int> > >::const_iterator shared_vertex;
  for (shared_vertex = shared_vertices.begin();
       shared_vertex != shared_vertices.end(); ++shared_vertex)
  {
    dolfin_assert(shared_vertex->first < vertex_shared.size());
    vertex_shared[shared_vertex->first] = true;
  }

  // Mark slave vertices
  std::vector<bool> slave_vertex(mesh.num_vertices(), false);
  std::map<unsigned int, std::pair<unsigned int,
                                   unsigned int> >::const_iterator slave;
  for (slave = slave_to_master_vertices.begin();
       slave != slave_to_master_vertices.end(); ++slave)
  {
    dolfin_assert(slave->first < slave_vertex.size());
    slave_vertex[slave->first] = true;
  }

  // MPI process number
  const std::size_t proc_num = MPI::rank(mesh.mpi_comm());

  // Communication data structures
  std::vector<std::vector<std::size_t> >
    new_shared_vertex_indices(MPI::size(mesh.mpi_comm()));

  // Compute modified global vertex indices
  std::size_t new_index = 0;
  modified_global_indices
    = std::vector<std::size_t>(mesh.num_vertices(),
                               std::numeric_limits<std::size_t>::max());
  for (VertexIterator vertex(mesh); !vertex.end(); ++vertex)
  {
    const std::size_t local_index = vertex->index();
    if (slave_vertex[local_index])
    {
      // Do nothing, will get new master index later
    }
    else if (vertex_shared[local_index])
    {
      // If shared, let lowest rank process number the vertex
      boost::unordered_map<unsigned int, std::vector<std::pair<unsigned int, unsigned int> > >::const_iterator
        it = shared_vertices.find(local_index);
      dolfin_assert(it != shared_vertices.end());
      const std::vector<std::pair<unsigned int, unsigned int> >& sharing_procs
        = it->second;

      // Figure out if this is the lowest rank process sharing the vertex
      std::vector<std::pair<unsigned int, unsigned int> >::const_iterator
       min_sharing_rank = std::min_element(sharing_procs.begin(),
                                           sharing_procs.end());
      std::size_t _min_sharing_rank = proc_num + 1;
      if (min_sharing_rank != sharing_procs.end())
        _min_sharing_rank = min_sharing_rank->first;

      if (proc_num <= _min_sharing_rank)
      {
        // Re-number vertex
        modified_global_indices[vertex->index()] = new_index;

        // Add to list to communicate
        std::vector<std::pair<unsigned int, unsigned int> >::const_iterator p;
        for (p = sharing_procs.begin(); p != sharing_procs.end(); ++p)
        {
          dolfin_assert(p->first < new_shared_vertex_indices.size());

          // Local index on remote process
          new_shared_vertex_indices[p->first].push_back(p->second);

          // Modified global index
          new_shared_vertex_indices[p->first].push_back(new_index);
        }

        new_index++;
      }
    }
    else
      modified_global_indices[vertex->index()] = new_index++;
  }

  // Send number of owned entities to compute offeset
  std::size_t offset = MPI::global_offset(mpi_comm, new_index, true);

  // Add process offset to modified indices
  for (std::size_t i = 0; i < modified_global_indices.size(); ++i)
    modified_global_indices[i] += offset;

  // Add process offset to shared vertex indices before sending
  for (std::size_t p = 0; p < new_shared_vertex_indices.size(); ++p)
    for (std::size_t i = 1; i < new_shared_vertex_indices[p].size(); i += 2)
      new_shared_vertex_indices[p][i] += offset;

  // Send/receive new indices for shared vertices
  std::vector<std::vector<std::size_t> > received_vertex_data;
  MPI::all_to_all(mesh.mpi_comm(), new_shared_vertex_indices,
                  received_vertex_data);

  // Set index for shared vertices that have been numbered by another
  // process
  for (std::size_t p = 0; p < received_vertex_data.size(); ++p)
  {
    const std::vector<std::size_t>& received_vertex_data_p
      = received_vertex_data[p];
    for (std::size_t i = 0; i < received_vertex_data_p.size(); i += 2)
    {
      const unsigned int local_index = received_vertex_data_p[i];
      const std::size_t recv_new_index = received_vertex_data_p[i + 1];

      dolfin_assert(local_index < modified_global_indices.size());
      modified_global_indices[local_index] = recv_new_index;
    }
  }

  // Request master vertex index from master owner
  std::vector<std::vector<std::size_t> >
    master_send_buffer(MPI::size(mpi_comm));
  std::vector<std::vector<std::size_t> >
    local_slave_index(MPI::size(mpi_comm));
  std::map<unsigned int,
           std::pair<unsigned int, unsigned int> >::const_iterator master;
  for (master = slave_to_master_vertices.begin();
       master != slave_to_master_vertices.end(); ++master)
  {
    const unsigned int local_index = master->first;
    const unsigned int master_proc = master->second.first;
    const unsigned int remote_master_local_index = master->second.second;
    dolfin_assert(master_proc < local_slave_index.size());
    dolfin_assert(master_proc < master_send_buffer.size());
    local_slave_index[master_proc].push_back(local_index);
    master_send_buffer[master_proc].push_back(remote_master_local_index);
  }

  // Send/receive master local indices for slave vertices
  std::vector<std::vector<std::size_t> > received_slave_vertex_indices;
  MPI::all_to_all(mpi_comm, master_send_buffer,
                  received_slave_vertex_indices);

  // Send back new master vertex index
  std::vector<std::vector<std::size_t> >
    master_vertex_indices(MPI::size(mpi_comm));
  for (std::size_t p = 0; p < received_slave_vertex_indices.size(); ++p)
  {
    const std::vector<std::size_t>& local_master_indices
      = received_slave_vertex_indices[p];
    for (std::size_t i = 0; i < local_master_indices.size(); ++i)
    {
      std::size_t master_local_index = local_master_indices[i];
      dolfin_assert(master_local_index < modified_global_indices.size());
      master_vertex_indices[p].push_back(modified_global_indices[master_local_index]);
    }
  }

  // Send/receive new global master indices for slave vertices
  std::vector<std::vector<std::size_t> > received_new_slave_vertex_indices;
  MPI::all_to_all(mpi_comm, master_vertex_indices,
                  received_new_slave_vertex_indices);

  // Set index for slave vertices
  for (std::size_t p = 0; p < received_new_slave_vertex_indices.size(); ++p)
  {
    const std::vector<std::size_t>& new_indices
      = received_new_slave_vertex_indices[p];
    const std::vector<std::size_t>& local_indices = local_slave_index[p];
    for (std::size_t i = 0; i < new_indices.size(); ++i)
    {
      const std::size_t local_index = local_indices[i];
      const std::size_t new_global_index   = new_indices[i];

      dolfin_assert(local_index < modified_global_indices.size());
      modified_global_indices[local_index] = new_global_index;
    }
  }

  // Send new indices to process that share a vertex but were not
  // responsible for re-numbering
  return MPI::sum(mpi_comm, new_index);
}
void CUserQueryUpdate::Core()
{
	std::string strToken,strTokenValue,strReceiveBuffer;
	Json::Value jValue,jRoot,jResult;
	Json::Reader jReader;
	Json::FastWriter jFastWriter;
	std::string sts="yd_zhejiang_mobile_token";
	std::string strMysqlRecord;
	const char *pchSqlPermissions = "select name,password,query_count,goods_count,goods_perm,permissions from dmp_user_permissions";
	BDXPERMISSSION_S mUserInfoVecFields;
	std::string strUserName;
	int times = 0;
	int currentPool;
	std::map<std::string,BDXPERMISSSION_S> temp_mapUserInfo;

	std::string httpDianxinGet="/bdapi/restful/fog/asia/getSingleUserTags/ctyun_bdcsc_asia/1ebb3c5d8a574e74b2e6156a5c010cba.json?key=uid_m310001_3_1_20160315&tablename=vendoryx_2";
	char m_httpReq[_8KBLEN],remoteBuffer[_8KBLEN];
	memset(m_httpReq, 0, _8KBLEN);
		
	while(true)
	{
		times=7;	
		int first_row = 1;
		#if 0
        if(m_pTokenRedis->UserGet(sts,strToken))
        {
	        //if(jReader.parse(strToken, jValue))
	        //{
	        //      strTokenValue = jValue[TOKEN].asString();
	            if(strToken.compare(g_strTokenString)!=0)
	            {
	                    pthread_rwlock_wrlock(&p_rwlock);
	                    g_strTokenString = strToken;
	                    g_iNeedUpdateToken = 1;
	                    pthread_rwlock_unlock(&p_rwlock);
	            }
	        //}
        }
        //st_emrtb_ip_port_weight_flag = 0;
	  	printf("g_strTokenString = %s\n",g_strTokenString.c_str());
		#endif

	 	#define __MONITOR_API__
	  	#ifdef __MONITOR_API__

		//MonitorRemoteApiWangGuan();
		//MonitorRemoteApiHuaWei();
									
		#endif //__MONITOR_API__

	#ifdef __CONECT_POOL__
			pthread_mutex_lock (&connectPoolMutex);
			printf("Line:%d,,BEGIN CHECK InitConnectPool=%d,totalConnectPool=%d,m_uiTotalThreadsNum=%d\n",__LINE__,InitConnectPool,totalConnectPool,m_uiTotalThreadsNum);
			if ( InitConnectPool == 0 || (totalConnectPool < m_uiTotalThreadsNum))
			{
				currentPool = m_uiTotalThreadsNum - totalConnectPool;
				printf("Line:%d,initing  pool.....\n",__LINE__);
				for(int i = 0 ;i< currentPool;i++)
				{
					//CTcpSocket *socket;
					taskConnectPool.socket = new CTcpSocket(8080,std::string("111.235.158.136"));
					//taskConnectPool.socket = new CTcpSocket(58001,std::string("0.0.0.0"));
					if(taskConnectPool.socket->TcpConnect()==0)
					{	
						printf("Line:%d,connecting....\n",__LINE__);
						taskConnectPool.m_bStatus = true;

						sprintf(m_httpReq,"GET %s HTTP/1.1\r\nHost: %s\r\nAccept-Encoding: identity\r\n\r\n",httpDianxinGet.c_str(),std::string("111.235.158.136:8080").c_str());
						taskConnectPool.socket->TcpSetKeepAliveOn();
						if(taskConnectPool.socket->TcpWrite(m_httpReq,strlen(m_httpReq))!=0)
						{
							taskConnectPool.isConnect = 1;
							m_vevtorConnectPool.push_back(taskConnectPool);
							totalConnectPool++;
							memset(remoteBuffer,0,_8KBLEN);
							taskConnectPool.socket->TcpRead(remoteBuffer,_8KBLEN);
							strReceiveBuffer = std::string(remoteBuffer);
							printf("Line:%d,strReceiveBuffer=%s\n",__LINE__,strReceiveBuffer.c_str());

						}
						else
						{
							taskConnectPool.isConnect = 0;
							taskConnectPool.socket->TcpClose();
						}
					}
					else
					{	
						taskConnectPool.isConnect = 0;
						taskConnectPool.socket->TcpClose();
					}
				}		
				InitConnectPool = 1;
			}

			printf("Line:%d,,AFTER CHECK InitConnectPool=%d,totalConnectPool=%d,m_uiTotalThreadsNum=%d\n",__LINE__,InitConnectPool,totalConnectPool,m_uiTotalThreadsNum);
		 	printf("Line:%d,m_vevtorConnectPool.size =%d\n",__LINE__,m_vevtorConnectPool.size());
			std::vector<TASKCONNECT_S>::iterator itr;
			for(itr = m_vevtorConnectPool.begin();itr!=m_vevtorConnectPool.end();itr++)
			{
				if( itr->m_bStatus	==	true )
				{	
					 if(itr->isConnect == 1)
					 {
						 itr->m_bStatus  =	 false;
						 sprintf(m_httpReq,"GET %s HTTP/1.1\r\nHost: %s\r\nAccept-Encoding: identity\r\n\r\n",httpDianxinGet.c_str(),std::string("111.235.158.136:8080").c_str());
						 itr->socket->TcpSetKeepAliveOn();
						 if(itr->socket->TcpWrite(m_httpReq,strlen(m_httpReq))!=0)
						 {
							 memset(remoteBuffer,0,_8KBLEN);
							 itr->socket->TcpRead(remoteBuffer,_8KBLEN);
							 strReceiveBuffer = std::string(remoteBuffer);
						 }
						 else
						 {
						 	printf("Line:%d,checking  pool.....error\n",__LINE__);
							printf("Line:%d,totalConnectPool  =%d\n",__LINE__,totalConnectPool);
							printf("Line:%d,m_vevtorConnectPool.size=%d\n",__LINE__,m_vevtorConnectPool.size());
							itr->isConnect = 0;
							itr->socket->TcpClose();
							m_vevtorConnectPool.erase(itr);
							totalConnectPool--;
						 }
					 }
					
				}
				itr->m_bStatus	=	true;
			}

			pthread_mutex_unlock(&connectPoolMutex);
	#endif

		printf("Line:%d,totalConnectPool=%d\n",__LINE__,totalConnectPool);
		while(times--)
		{
				temp_mapUserInfo.clear();
				if(m_stMysqlServerInfo->GetMysqlInitState())
				{
					if(m_stMysqlServerInfo->ExecuteMySql(pchSqlPermissions))
					{

						if(m_stMysqlServerInfo->MysqlUseResult())
						{	
							//m_stMysqlServerInfo->DisplayHeader();
							while(m_stMysqlServerInfo->MysqlFetchRow())
							{			
								//if(!first_row)
								{	
									strMysqlRecord = m_stMysqlServerInfo->GetColumnValue();
									//printf("strMysqlRecord = %s\n",strMysqlRecord.c_str());
									GetMysqlFieldsUserInfo(strMysqlRecord,mUserInfoVecFields,strUserName);
									temp_mapUserInfo.insert(std::pair<std::string,BDXPERMISSSION_S>(strUserName,mUserInfoVecFields));
									
								}
								first_row = 0;
							}
							m_stMysqlServerInfo->DestroyResultEnv();
							std::map<std::string,BDXPERMISSSION_S>::iterator itr;
							std::vector<std::string>::iterator itr2;
							#if 0
							printf("===================g_mapUserInfo========================\n");
							for(itr=temp_mapUserInfo.begin();itr!=temp_mapUserInfo.end();itr++)
							{	
								printf("%s ",itr->first.c_str());
								printf("%s ",itr->second.mResToken.c_str());
								printf("%d ",itr->second.mIntQueryTimes);
								printf("%d ",itr->second.mIntGoodsTimes);
								printf("%s ",itr->second.mGoodsFields.c_str());
								for(itr2=itr->second.mVecFields.begin();itr2!=itr->second.mVecFields.end();itr2++)
								{
									printf("%s ",(*itr2).c_str());
									
								}
								printf("\n");
							}
							#endif
							#if 1
							printf("===================g_mapUserInfo========================\n");
							for(itr=g_mapUserInfo.begin();itr!=g_mapUserInfo.end();itr++)
							{	
								printf("%s ",itr->first.c_str());
								printf("%s ",itr->second.mResToken.c_str());
								printf("%d ",itr->second.mIntQueryTimes);
								printf("%d ",itr->second.mIntGoodsTimes);
								printf("%s ",itr->second.mGoodsFields.c_str());
								for(itr2=itr->second.mVecFields.begin();itr2!=itr->second.mVecFields.end();itr2++)
								{
									printf("%s ",(*itr2).c_str());
								}
								printf("\n");
							}
							#endif
							if( !MapIsEqual(temp_mapUserInfo,g_mapUserInfo) )
							{
							//	g_mapUserInfo = temp_mapUserInfo;
								
								SwapMap(temp_mapUserInfo,g_mapUserInfo);
								printf("\nswap map g_mapUserInfo\n\n");				
							}

						}
						
					}

				}
				
		sleep(60);
		}	
	}

}
Example #24
0
/// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
static int AnalyzeBitcode() {
    // Read the input file.
    OwningPtr<MemoryBuffer> MemBuf;

    if (error_code ec =
                MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), MemBuf))
        return Error("Error reading '" + InputFilename + "': " + ec.message());

    if (MemBuf->getBufferSize() & 3)
        return Error("Bitcode stream should be a multiple of 4 bytes in length");

    const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
    const unsigned char *EndBufPtr = BufPtr+MemBuf->getBufferSize();

    // If we have a wrapper header, parse it and ignore the non-bc file contents.
    // The magic number is 0x0B17C0DE stored in little endian.
    if (isBitcodeWrapper(BufPtr, EndBufPtr))
        if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
            return Error("Invalid bitcode wrapper header");

    BitstreamReader StreamFile(BufPtr, EndBufPtr);
    BitstreamCursor Stream(StreamFile);
    StreamFile.CollectBlockInfoNames();

    // Read the stream signature.
    char Signature[6];
    Signature[0] = Stream.Read(8);
    Signature[1] = Stream.Read(8);
    Signature[2] = Stream.Read(4);
    Signature[3] = Stream.Read(4);
    Signature[4] = Stream.Read(4);
    Signature[5] = Stream.Read(4);

    // Autodetect the file contents, if it is one we know.
    CurStreamType = UnknownBitstream;
    if (Signature[0] == 'B' && Signature[1] == 'C' &&
            Signature[2] == 0x0 && Signature[3] == 0xC &&
            Signature[4] == 0xE && Signature[5] == 0xD)
        CurStreamType = LLVMIRBitstream;

    unsigned NumTopBlocks = 0;

    // Parse the top-level structure.  We only allow blocks at the top-level.
    while (!Stream.AtEndOfStream()) {
        unsigned Code = Stream.ReadCode();
        if (Code != bitc::ENTER_SUBBLOCK)
            return Error("Invalid record at top-level");

        if (ParseBlock(Stream, 0))
            return true;
        ++NumTopBlocks;
    }

    if (Dump) outs() << "\n\n";

    uint64_t BufferSizeBits = (EndBufPtr-BufPtr)*CHAR_BIT;
    // Print a summary of the read file.
    outs() << "Summary of " << InputFilename << ":\n";
    outs() << "         Total size: ";
    PrintSize(BufferSizeBits);
    outs() << "\n";
    outs() << "        Stream type: ";
    switch (CurStreamType) {
    case UnknownBitstream:
        outs() << "unknown\n";
        break;
    case LLVMIRBitstream:
        outs() << "LLVM IR\n";
        break;
    }
    outs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
    outs() << "\n";

    // Emit per-block stats.
    outs() << "Per-block Summary:\n";
    for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
            E = BlockIDStats.end(); I != E; ++I) {
        outs() << "  Block ID #" << I->first;
        if (const char *BlockName = GetBlockName(I->first, StreamFile))
            outs() << " (" << BlockName << ")";
        outs() << ":\n";

        const PerBlockIDStats &Stats = I->second;
        outs() << "      Num Instances: " << Stats.NumInstances << "\n";
        outs() << "         Total Size: ";
        PrintSize(Stats.NumBits);
        outs() << "\n";
        double pct = (Stats.NumBits * 100.0) / BufferSizeBits;
        outs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
        if (Stats.NumInstances > 1) {
            outs() << "       Average Size: ";
            PrintSize(Stats.NumBits/(double)Stats.NumInstances);
            outs() << "\n";
            outs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
                   << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
            outs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
                   << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
            outs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
                   << Stats.NumRecords/(double)Stats.NumInstances << "\n";
        } else {
            outs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
            outs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
            outs() << "        Num Records: " << Stats.NumRecords << "\n";
        }
        if (Stats.NumRecords) {
            double pct = (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumRecords;
            outs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
        }
        outs() << "\n";

        // Print a histogram of the codes we see.
        if (!NoHistogram && !Stats.CodeFreq.empty()) {
            std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
            for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
                if (unsigned Freq = Stats.CodeFreq[i].NumInstances)
                    FreqPairs.push_back(std::make_pair(Freq, i));
            std::stable_sort(FreqPairs.begin(), FreqPairs.end());
            std::reverse(FreqPairs.begin(), FreqPairs.end());

            outs() << "\tRecord Histogram:\n";
            outs() << "\t\t  Count    # Bits   %% Abv  Record Kind\n";
            for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
                const PerRecordStats &RecStats = Stats.CodeFreq[FreqPairs[i].second];

                outs() << format("\t\t%7d %9lu",
                                 RecStats.NumInstances,
                                 (unsigned long)RecStats.TotalBits);

                if (RecStats.NumAbbrev)
                    outs() <<
                           format("%7.2f  ",
                                  (double)RecStats.NumAbbrev/RecStats.NumInstances*100);
                else
                    outs() << "         ";

                if (const char *CodeName =
                            GetCodeName(FreqPairs[i].second, I->first, StreamFile))
                    outs() << CodeName << "\n";
                else
                    outs() << "UnknownCode" << FreqPairs[i].second << "\n";
            }
            outs() << "\n";

        }
    }
    return 0;
}
///////////////////////////////////////////////////////////////
//
// CPerfStatFunctionTimingImpl::GetStats
//
//
//
///////////////////////////////////////////////////////////////
void CPerfStatFunctionTimingImpl::GetStats ( CPerfStatResult* pResult, const std::map < SString, int >& optionMap, const SString& strFilter )
{
    m_TimeSinceLastViewed.Reset ();
    SetActive ( true );

    //
    // Set option flags
    //
    bool bHelp = MapContains ( optionMap, "h" );
    uint uiPeakBytesThresh = 1000;
    int iPeakMsThresh = optionMap.empty () ? -1 : atoi ( optionMap.begin ()->first );
    if ( iPeakMsThresh < 0 )
        iPeakMsThresh = DEFAULT_THRESH_MS;
    m_PeakUsRequiredHistory.AddValue ( iPeakMsThresh * 1000 );

    //
    // Process help
    //
    if ( bHelp )
    {
        pResult->AddColumn ( "Function timings help" );
        pResult->AddRow ()[0] = "Option h - This help";
        pResult->AddRow ()[0] = "0-50 - Peak Ms threshold (defaults to 1)";
        return;
    }

    //
    // Set column names
    //

    pResult->AddColumn ( " " );
    pResult->AddColumn ( "10 sec.calls" );
    pResult->AddColumn ( "10 sec.cpu total" );
    pResult->AddColumn ( "10 sec.cpu peak" );
    pResult->AddColumn ( "10 sec.cpu biggest call" );

    pResult->AddColumn ( "10 sec.BW" );
    //pResult->AddColumn ( "10 sec.BW peak" );
    pResult->AddColumn ( "10 sec.BW biggest call" );

    pResult->AddColumn ( "120 sec.calls" );
    pResult->AddColumn ( "120 sec.cpu total" );
    pResult->AddColumn ( "120 sec.cpu peak" );
    pResult->AddColumn ( "120 sec.cpu biggest call" );

    pResult->AddColumn ( "120 sec.BW" );
    //pResult->AddColumn ( "120 sec.BW peak" );
    pResult->AddColumn ( "120 sec.BW biggest call" );

    //
    // Set rows
    //

    for ( std::map < SString, SFunctionTimingInfo > :: const_iterator iter = m_TimingMap.begin () ; iter != m_TimingMap.end () ; iter++ )
    {
        const SString& strFunctionName  = iter->first;
        const SFunctionTimingInfo& item = iter->second;

        const STiming& prev5s = item.history[ item.iPrevIndex ];
        const STiming& prev60s = item.prev60s;

        bool bHas5s = prev5s.uiNumCalls > 0;
        bool bHas60s = prev60s.uiNumCalls > 0;

        if ( !bHas5s && !bHas60s )
            continue;

        // Filter peak threshold for this viewer
        if ( prev5s.fPeakMs < iPeakMsThresh && prev60s.fPeakMs < iPeakMsThresh &&
             prev5s.uiPeakBytes < uiPeakBytesThresh && prev60s.uiPeakBytes < uiPeakBytesThresh )
            continue;

        // Apply filter
        if ( strFilter != "" && strFunctionName.find ( strFilter ) == SString::npos )
            continue;

        // Add row
        SString* row = pResult->AddRow ();
        int c = 0;
        row[c++] = strFunctionName;

        if ( !bHas5s )
        {
            row[c++] = "-";
            row[c++] = "-";
            row[c++] = "-";
            row[c++] = "-";
            row[c++] = "";
            //row[c++] = "";
            row[c++] = "";
        }
        else
        {
            row[c++] = SString ( "%u", prev5s.uiNumCalls );

            row[c++] = SString ( "%2.0f ms", prev5s.fTotalMs );
            row[c++] = SString ( "%2.0f ms", prev5s.fPeakMs );
            row[c++] = SString ( "%2.0f ms (%s)", prev5s.fResBiggestMs, *prev5s.strResBiggestMsName );

            row[c++] = prev5s.uiTotalBytes < 10 ? "" : SString ( "%s", *CPerfStatManager::GetScaledByteString( prev5s.uiTotalBytes ) );
            //row[c++] = prev5s.uiPeakBytes < 10 ? "" : SString ( "%s ", *CPerfStatManager::GetScaledByteString( prev5s.uiPeakBytes ) );
            row[c++] = prev5s.uiResBiggestBytes < 10 ? "" : SString ( "%s (%s)", *CPerfStatManager::GetScaledByteString( prev5s.uiResBiggestBytes ), *prev5s.strResBiggestBytesName );
        }

        row[c++] = SString ( "%u", prev60s.uiNumCalls );

        row[c++] = SString ( "%2.0f ms", prev60s.fTotalMs );
        row[c++] = SString ( "%2.0f ms", prev60s.fPeakMs );
        row[c++] = SString ( "%2.0f ms (%s)", prev60s.fResBiggestMs, *prev60s.strResBiggestMsName );

        row[c++] = prev60s.uiTotalBytes < 10 ? "" : SString ( "%s ", *CPerfStatManager::GetScaledByteString( prev60s.uiTotalBytes ) );
        //row[c++] = prev60s.uiPeakBytes < 10 ? "" : SString ( "%s ", *CPerfStatManager::GetScaledByteString( prev60s.uiPeakBytes ) );
        row[c++] = prev60s.uiResBiggestBytes < 10 ? "" : SString ( "%s (%s)", *CPerfStatManager::GetScaledByteString( prev60s.uiResBiggestBytes ), *prev60s.strResBiggestBytesName );
    }
}
Example #26
0
void ghttp_CloseAll()
{
    while (!map_.empty())
        ghttp_Close(map_.begin()->second.id);
}
Example #27
0
//---------------------------------------------------------------------------//
// fludag_all_materials
//---------------------------------------------------------------------------//
// Get material cards for all materials in the problem, both elemental and compounds
void fludag_all_materials(std::ostringstream& mstr, std::map<std::string,pyne::Material> pyne_map)
{
    std::set<int> exception_set = make_exception_set();

    std::map<int, std::string> map_nucid_fname;

    pyne::Material unique = pyne::Material();

    // loop over all materials, summing
    std::map<std::string, pyne::Material>::iterator nuc;
    for ( nuc = pyne_map.begin(); nuc != pyne_map.end(); ++nuc)
    {
        unique = unique + (nuc->second);
    }
    // now collapse elements
    unique = unique.collapse_elements(exception_set);

    // remove those that are no longer needed due to
    // compound card inclusions
    // now write out material card & compound card for each compound
    for ( nuc = pyne_map.begin() ; nuc != pyne_map.end(); ++nuc)
    {
        pyne::Material compound = (nuc->second).collapse_elements(exception_set);
        // if only one element in comp, then we can remove the one that exists
        // in the unique material
        if ( compound.comp.size() == 1 )
        {
            pyne::comp_iter nuc = compound.comp.begin();
            std::set<int> nuc2del;
            nuc2del.insert(nuc->first);
            // remove the nuclide from the unique list
            unique = unique.del_mat(nuc2del);
        }
    }

    //del_mat

    // number of required material cards due to calls
    int num_mat = unique.comp.size();

    // write out material card for each one
    int i = ID_START;
    pyne::comp_map::iterator element;
    std::string mat_line;
    for ( element = unique.comp.begin() ; element != unique.comp.end() ; ++element)
    {
        int nuc_id = element->first; // get the nuc id
        pyne::comp_map nucvec;
        nucvec[nuc_id] = 100.0; // create temp nucvec
        pyne::Material element_tmp = pyne::Material(nucvec); // create temp material
        mat_line = element_tmp.fluka(i);
        if (mat_line.length() != 0)
        {
            i++;
            mstr << mat_line;
        }
    }

    // now write out material card & compound card for each compound
    std::string compound_string;
    for ( nuc = pyne_map.begin() ; nuc != pyne_map.end(); ++nuc)
    {
        pyne::Material compound = (nuc->second).collapse_elements(exception_set);
        compound_string = compound.fluka(i);
        if ( compound_string.length() != 0 )
        {
            i++;
            mstr << compound_string;
        }
    }
}
Example #28
0
		inline BOSTREAM2(const std::map<K, V, C, A> &a) { return itwrite(out, a.size(), a.begin()); }
Example #29
0
	std::map< unsigned, rMatrix >::iterator Begin() {return entries.begin();}
Example #30
0
bool PythonLanguageHook::IsAddonClassInstanceRegistered(AddonClass* obj)
{
    for (std::map<PyInterpreterState*,AddonClass::Ref<PythonLanguageHook> >::iterator iter = hooks.begin();
            iter != hooks.end(); ++iter)
    {
        if ((iter->second)->HasRegisteredAddonClassInstance(obj))
            return true;
    }
    return false;
}