Example #1
0
 virtual void OnTerminate ( int pid, int status )
 {
     wxProcessEvent ev(wxID_ANY,pid, status);
     myParent->AddPendingEvent(ev);
 };
Example #2
0
//+++MAIN FUNCTION+++//
void eventLoop_jets(TString reqNumBJets = ""){

  cout << "reqNumBJets is " << reqNumBJets << endl;
  
  assert( (reqNumBJets == "nBJetsLT2") || (reqNumBJets == "nBJetsEQ2") || (reqNumBJets == "nBJetsGT2"));

  //INPUT FILES
  // fileNames.push_back(); //need to add filename
  fwlite::ChainEvent ev(fileNames);

  //OUTPUT FILE
  //TFile fout("histo_ben_FWLite_analyzer.root","recreate");
  TString outfile = "plots_";
  outfile+=sampleid_;
  outfile+="_";
  outfile+=reqNumBJets;
  outfile+=".root";
  TFile fout(outfile,"RECREATE");
  
  int nentries = ev.size();

  //////////////////////
  //DECLARE HISTOGRAMS//
  //////////////////////
  HistHolder histo; 
  
  int nbins=200;
  
  //Ht
  float htmin=0;
  float htmax=2250;
  histo.make("H_HT","HT",nbins,htmin,htmax);

  //Meff
  histo.make("H_Meff","scalar sum of jet ET and MET",nbins,htmin,htmax);
  
  //MET
  histo.make("H_MET","MET",nbins,htmin,htmax);
  histo.make("H_MET_UncorrPT","MET_UncorrPT",nbins,htmin,htmax);
  histo.make("H_MET_SumET","MET_sumET",nbins,htmin,htmax); 

  //Jet Pt
  float jetptmin=0;
  float jetptmax=1000;
  histo.make("H_jetPT", "Jet PT Total",700,jetptmin,7000);   
  histo.make("H_jetPT1","Jet PT 1",nbins,jetptmin,jetptmax);
  histo.make("H_jetPT2","Jet PT 2",nbins,jetptmin,jetptmax);
  histo.make("H_jetPT3","Jet PT 3",nbins,jetptmin,jetptmax);
  histo.make("H_jetPT4","Jet PT 4",nbins,jetptmin,jetptmax);

  //Jet eta
  float maxJetEta = 2.4;
  histo.make("H_jeteta1","eta of lead jet",nbins,-maxJetEta,maxJetEta);

  //Jet multiplicity 
  int nbins_jets=20;
  string xtitle="N Jets";
  histo.make("H_NJets","N Jets",nbins_jets,-0.5,nbins_jets-0.5,xtitle);
  
  //Jet deltaphi
  double pi=4*atan(1.0);
  histo.make("H_DeltaPhi1", "angle between jet1 and MET",nbins,0,pi);
  histo.make("H_DeltaPhi2", "angle between jet2 and MET",nbins,0,pi);
  histo.make("H_DeltaPhi3", "angle between jet3 and MET",nbins,0,pi);
  histo.make("H_DeltaPhi4", "angle between jet4 and MET",nbins,0,pi);
  
  
  //BJets
  histo.make("H_Nbtags","Number of b tags",nbins_jets,-0.5,nbins_jets-0.5);
  histo.make("H_NbjetsMC","Number of MC b jets",nbins_jets,-0.5,nbins_jets-0.5);
  histo.make("H_bjetPT1","pT of lead b jet",nbins,jetptmin,jetptmax);
  histo.make("H_bjetPT2","pT of 2nd b jet",nbins,jetptmin,jetptmax);

  //////////////////////////////////////////////////////////////////////////////////////////

  //LOOP OVER EVENTS
  int cnt = 0;
  for( ev.toBegin(); !ev.atEnd(); ++ev) {
    //cout << "Event " << cnt << endl;
    //Counter output 
    cnt++;
    if( cnt==1 )        std::cout << "     Event " << cnt << std::endl;
    if( cnt%1000==0 && cnt!=1 ) std::cout << "           " << cnt << "\t" 
					    << int(double(cnt)/double(nentries)*100) << "% done" << std::endl;
    //Try the event
    try {

      //HANDLES
      fwlite::Handle<CUeventCollection> h_event;
      h_event.getByLabel(ev,"CUproducer");

      fwlite::Handle<CUelectronCollection> h_electrons;
      h_electrons.getByLabel(ev,"CUproducer","cleanLayer1Electrons");
      CUelectronCollection const &electrons = *h_electrons;

      fwlite::Handle<CUjetCollection> h_jets;
      h_jets.getByLabel(ev,"CUproducer","cleanLayer1JetsAK5");
      CUjetCollection const &jets = *h_jets;

      fwlite::Handle<CUmetCollection> h_met;
      h_met.getByLabel(ev,"CUproducer","layer1METsAK5");

      fwlite::Handle<CUmcparticleCollection> h_mcparticles;
      h_mcparticles.getByLabel(ev,"CUproducer","MCstatus3");
      CUmcparticleCollection const &mcparticles = *h_mcparticles;

      fwlite::Handle<CUmuonCollection> h_muons;
      h_muons.getByLabel(ev,"CUproducer","cleanLayer1Muons");
      CUmuonCollection const &muons = *h_muons;

      fwlite::Handle<CUphotonCollection> h_photons;
      h_photons.getByLabel(ev,"CUproducer","cleanLayer1Photons");
      CUphotonCollection const &photons = *h_photons;

      fwlite::Handle<CUsuperclusterCollection> h_superclusters;
      h_superclusters.getByLabel(ev,"CUproducer","corHybridSCandMulti5x5WithPreshower");
      CUsuperclusterCollection const &scs = *h_superclusters;

      fwlite::Handle<CUtrackCollection> h_tracks;
      h_tracks.getByLabel(ev,"CUproducer","generalTracks");
      CUtrackCollection const &tracks = *h_tracks;

      fwlite::Handle<CUtriggerCollection> h_hlt;
      h_hlt.getByLabel(ev,"CUproducer","HLT");
      CUtriggerCollection const &hlt = *h_hlt;

      fwlite::Handle<CUtriggerCollection> h_l1t_algo;
      h_l1t_algo.getByLabel(ev,"CUproducer","L1Talgo");
      CUtriggerCollection const &l1t_algo = *h_l1t_algo;

      fwlite::Handle<CUtriggerCollection> h_l1t_tech;
      h_l1t_tech.getByLabel(ev,"CUproducer","L1Ttech");
      CUtriggerCollection const &l1t_tech = *h_l1t_tech;

      fwlite::Handle<CUprimaryvertexCollection> h_privertex;
      h_privertex.getByLabel(ev,"CUproducer","offlinePrimaryVertices");
      CUprimaryvertexCollection const &vertices = *h_privertex;

      fwlite::Handle<CUskimbitsCollection> h_skimbits;
      h_skimbits.getByLabel(ev,"CUproducer","SkimBits");


      //FREQUENTLY USED VARIABLES
      double metPT  = h_met->front().pt;
      double metUnCorrPt = h_met->front().Upt;
      double sumET  = h_met->front().sumET;

      //LOOP OVER JETS TO COUNT BJETS 
      int ngoodMCbjets = 0;
      for( JetIter jet = jets.begin(); jet != jets.end(); ++jet ) {
	if( passMCBJetCuts(jet) ) ngoodMCbjets++; 
      }//end loop over jets
      
      TString nBJetsStatus;
      if (ngoodMCbjets < 2 ) nBJetsStatus = "nBJetsLT2";
      else if( ngoodMCbjets == 2 ) nBJetsStatus = "nBJetsEQ2";
      else if( ngoodMCbjets > 2 ) nBJetsStatus = "nBJetsGT2";

      //cout << "0. reqNumBJets:" << reqNumBJets << endl;
      //cout << "1. nBJetsStatus:" << nBJetsStatus << " because ngoodMCbjets=" << ngoodMCbjets << endl;
      
      
      //FILL HISTOGRAMS IF EVENT HAS CORRECT NUMBER OF BJETS
      if(nBJetsStatus == reqNumBJets){
      	
	histo["H_MET"]->Fill(metPT);
	histo["H_MET_UncorrPT"]->Fill(metUnCorrPt);
	histo["H_MET_SumET"]->Fill(sumET);

	//LOOP OVER JETS
	float jetpt = 0, jetpt1=0, jetpt2=0, jetpt3=0, jetpt4=0;
	float bjetpt1=0, bjetpt2=0, bjetpt3=0, bjetpt4=0;
	JetIter jet1= jets.end(), jet2= jets.end(), jet3= jets.end(), jet4= jets.end();
	JetIter bjet1= jets.end(), bjet2= jets.end(), bjet3= jets.end(), bjet4= jets.end();
	int njets = 0, nbtags =0;

	for( JetIter jet = jets.begin(); jet != jets.end(); ++jet ) {
	 
	  //Apply jet cuts
	  if( passJetCuts(jet) ){
	    njets++;
	    jetpt+=jet->pt;

	    //Find leading jets
	    if(jet->pt > jetpt1) {
	      jet4 = jet3;
	      jetpt4 = jetpt3;
	      jet3 = jet2;
	      jetpt3 = jetpt2;
	      jet2 = jet1;
	      jetpt2 = jetpt1;
	      jet1 = jet;
	      jetpt1 = jet->pt;
	    }
	    else if(jet->pt > jetpt2){
	      jet4 = jet3;
	      jetpt4 = jetpt3;
	      jet3 = jet2;
	      jetpt3 = jetpt2;
	      jet2 = jet;
	      jetpt2 = jet->pt;
	    }
	    else if(jet->pt > jetpt3){
	      jet4 = jet3;
	      jetpt4 = jetpt3;
	      jet3 = jet;
	      jetpt3 = jet->pt;
	    }
	    else if(jet->pt > jetpt4){
	      jet4 = jet;
	      jetpt4 = jet->pt;
	    }//end find leading jets
	    
	    //we already know ngoodMCbjets. here we find if it is tagged
	    if ( passBTagCuts(jet) ) nbtags++;
	    
	    //BJet related
	    if (passMCBJetCuts(jet)){
	      
	      //Find leading b jets
	      if(jet->pt > bjetpt1) {
		bjet4 = bjet4;
		bjetpt4 = bjetpt3;
		bjet3 = bjet2;
		bjetpt3 = bjetpt2;
		bjet2 = bjet1;
		bjetpt2 = bjetpt1;
		bjet1 = jet;
		bjetpt1 = jet->pt;
	      }
	      else if(jet->pt > bjetpt2){
		bjet4 = bjet3;
		bjetpt4 = bjetpt3;
		bjet3 = bjet2;
		bjetpt3 = bjetpt2;
		bjet2 = jet;
		bjetpt2 = jet->pt;
	      }
	      else if(jet->pt > bjetpt3){
		bjet4 = bjet3;
		bjetpt4 = bjetpt3;
		bjet3 = jet;
		bjetpt3 = jet->pt;
	      }
	      else if(jet->pt > bjetpt4){
		bjet4 = jet;
		bjetpt4 = jet->pt;
	      }//end find leading b jets
	     
	    }//end pass bjet cuts
	  
	  }//end jet cuts
	
	}//end loop over jets

	//Fill Histograms that depend on jet loop being done
	histo["H_NJets"]->Fill(njets);
	histo["H_jetPT"]->Fill(jetpt);

	if (njets ==1) {
	  histo["H_jetPT1"]->Fill(jetpt1);
	  histo["H_jeteta1"]->Fill(jet1->eta);
	  histo["H_DeltaPhi1"]->Fill( getDeltaPhi(jet1, h_met->front()) );
	}
	else if (njets ==2){
	  histo["H_jeteta1"]->Fill(jet1->eta);
	  histo["H_jetPT1"]->Fill(jetpt1);
	  histo["H_DeltaPhi1"]->Fill( getDeltaPhi(jet1, h_met->front()) );
	  histo["H_jetPT2"]->Fill(jetpt2);
	  histo["H_DeltaPhi2"]->Fill( getDeltaPhi(jet2, h_met->front()) );
	}
	else if (njets ==3){
	  histo["H_jeteta1"]->Fill(jet1->eta);
	  histo["H_jetPT1"]->Fill(jetpt1);
	  histo["H_DeltaPhi1"]->Fill( getDeltaPhi(jet1, h_met->front()) );
	  histo["H_jetPT2"]->Fill(jetpt2);
	  histo["H_DeltaPhi2"]->Fill( getDeltaPhi(jet2, h_met->front()) );
	  histo["H_jetPT3"]->Fill(jetpt3);
	  histo["H_DeltaPhi3"]->Fill( getDeltaPhi(jet3, h_met->front()) );
	}
	else if (njets >3){
	  histo["H_jeteta1"]->Fill(jet1->eta);
	  histo["H_jetPT1"]->Fill(jetpt1);
	  histo["H_DeltaPhi1"]->Fill( getDeltaPhi(jet1, h_met->front()) );
	  histo["H_jetPT2"]->Fill(jetpt2);
	  histo["H_DeltaPhi2"]->Fill( getDeltaPhi(jet2, h_met->front()) );
	  histo["H_jetPT3"]->Fill(jetpt3);
	  histo["H_DeltaPhi3"]->Fill( getDeltaPhi(jet3, h_met->front()) );
	  histo["H_jetPT4"]->Fill(jetpt4);
	  histo["H_DeltaPhi4"]->Fill( getDeltaPhi(jet4, h_met->front()) );
	}

	//Fill Bjet Histograms
	histo["H_Nbtags"]->Fill(nbtags);
	histo["H_NbjetsMC"]->Fill(ngoodMCbjets);
       	if ( ngoodMCbjets==1 ){ 
	  histo["H_bjetPT1"]->Fill(bjetpt1);
	}
	else if ( ngoodMCbjets >1 ){
	  histo["H_bjetPT1"]->Fill(bjetpt1);
	  histo["H_bjetPT2"]->Fill(bjetpt2);
	}
		
      }//correct number of bjets
    }//end try
    catch(std::exception& e) {
      std::cerr << " ==> caught exception " << e.what() << std::endl;
      continue;
    }
    
    //if(cnt == 50) break;//for debugging purposes
    
  }//end loop over events
  cout << "event count: " << cnt << endl;
  fout.Write();
  fout.Close();
}//end eventLoop_jets()
Example #3
0
bool SearchMv::isZugzwangChance(Board& board)
{ 
	Eval ev(&board);
	return ev.isChanceZugzwang(&board);
}
Example #4
0
void DecoderHandler::doOperationStart(const QString &name)
{
    m_op = true;
    DecoderHandlerEvent ev(DecoderHandlerEvent::OperationStart, new QString(name));
    dispatch(ev);
}
Example #5
0
/**
 * Description not yet available.
 * \param
 */
void laplace_approximation_calculator::
  do_newton_raphson_banded(function_minimizer * pfmin,double f_from_1,
  int& no_converge_flag)
{
  //quadratic_prior * tmpptr=quadratic_prior::ptr[0];
  //cout << tmpptr << endl;


  laplace_approximation_calculator::where_are_we_flag=2;
  double maxg=fabs(evaluate_function(uhat,pfmin));


  laplace_approximation_calculator::where_are_we_flag=0;
  dvector uhat_old(1,usize);
  for(int ii=1;ii<=num_nr_iters;ii++)
  {
    // test newton raphson
    switch(hesstype)
    {
    case 3:
      bHess->initialize();
      break;
    case 4:
      Hess.initialize();
      break;
    default:
      cerr << "Illegal value for hesstype here" << endl;
      ad_exit(1);
    }

    grad.initialize();
    //int check=initial_params::stddev_scale(scale,uhat);
    //check=initial_params::stddev_curvscale(curv,uhat);
    //max_separable_g=0.0;
    sparse_count = 0;

    step=get_newton_raphson_info_banded(pfmin);
    //if (bHess)
     // cout << "norm(*bHess) = " << norm(*bHess) << endl;
    //cout << "norm(Hess) = " << norm(Hess) << endl;
    //cout << grad << endl;
    //check_pool_depths();
    if (!initial_params::mc_phase)
      cout << "Newton raphson " << ii << "  ";
    if (quadratic_prior::get_num_quadratic_prior()>0)
    {
      quadratic_prior::get_cHessian_contribution(Hess,xsize);
      quadratic_prior::get_cgradient_contribution(grad,xsize);
    }

    int ierr=0;
    if (hesstype==3)
    {
      if (use_dd_nr==0)
      {
        banded_lower_triangular_dmatrix bltd=choleski_decomp(*bHess,ierr);
        if (ierr && no_converge_flag ==0)
        {
          no_converge_flag=1;
          //break;
        }
        if (ierr)
        {
          double oldval;
          evaluate_function(oldval,uhat,pfmin);
          uhat=banded_calculations_trust_region_approach(uhat,pfmin);
        }
        else
        {
          if (dd_nr_flag==0)
          {
            dvector v=solve(bltd,grad);
            step=-solve_trans(bltd,v);
            //uhat_old=uhat;
            uhat+=step;
          }
          else
          {
#if defined(USE_DD_STUFF)
            int n=grad.indexmax();
            maxg=fabs(evaluate_function(uhat,pfmin));
            uhat=dd_newton_raphson2(grad,*bHess,uhat);
#else
            cerr << "high precision Newton Raphson not implemented" << endl;
            ad_exit(1);
#endif
          }
          maxg=fabs(evaluate_function(uhat,pfmin));
          if (f_from_1< pfmin->lapprox->fmc1.fbest)
          {
            uhat=banded_calculations_trust_region_approach(uhat,pfmin);
            maxg=fabs(evaluate_function(uhat,pfmin));
          }
        }
      }
      else
      {
        cout << "error not used" << endl;
        ad_exit(1);
       /*
        banded_symmetric_ddmatrix bHessdd=banded_symmetric_ddmatrix(*bHess);
        ddvector gradd=ddvector(grad);
        //banded_lower_triangular_ddmatrix bltdd=choleski_decomp(bHessdd,ierr);
        if (ierr && no_converge_flag ==0)
        {
          no_converge_flag=1;
          break;
        }
        if (ierr)
        {
          double oldval;
          evaluate_function(oldval,uhat,pfmin);
          uhat=banded_calculations_trust_region_approach(uhat,pfmin);
          maxg=fabs(evaluate_function(uhat,pfmin));
        }
        else
        {
          ddvector v=solve(bHessdd,gradd);
          step=-make_dvector(v);
          //uhat_old=uhat;
          uhat=make_dvector(ddvector(uhat)+step);
          maxg=fabs(evaluate_function(uhat,pfmin));
          if (f_from_1< pfmin->lapprox->fmc1.fbest)
          {
            uhat=banded_calculations_trust_region_approach(uhat,pfmin);
            maxg=fabs(evaluate_function(uhat,pfmin));
          }
        }
        */
      }

      if (maxg < 1.e-13)
      {
        break;
      }
    }
    else if (hesstype==4)
    {
      dvector step;

#     if defined(USE_ATLAS)
        if (!ad_comm::no_atlas_flag)
        {
          step=-atlas_solve_spd(Hess,grad,ierr);
        }
        else
        {
          dmatrix A=choleski_decomp_positive(Hess,ierr);
          if (!ierr)
          {
            step=-solve(Hess,grad);
            //step=-solve(A*trans(A),grad);
          }
        }
        if (!ierr) break;
#     else
        if (sparse_hessian_flag)
        {
          //step=-solve(*sparse_triplet,Hess,grad,*sparse_symbolic);
          dvector temp=solve(*sparse_triplet2,grad,*sparse_symbolic2,ierr);
          if (ierr)
          {
            step=-temp;
          }
          else
          {
            cerr << "matrix not pos definite in sparse choleski"  << endl;
            pfmin->bad_step_flag=1;

            int on;
            int nopt;
            if ((on=option_match(ad_comm::argc,ad_comm::argv,"-ieigvec",nopt))
              >-1)
            {
              dmatrix M=make_dmatrix(*sparse_triplet2);

              ofstream ofs3("inner-eigvectors");
              ofs3 << "eigenvalues and eigenvectors " << endl;
              dvector v=eigenvalues(M);
              dmatrix ev=trans(eigenvectors(M));
              ofs3 << "eigenvectors" << endl;
              int i;
              for (i=1;i<=ev.indexmax();i++)
               {
                  ofs3 << setw(4) << i  << " "
                   << setshowpoint() << setw(14) << setprecision(10) << v(i)
                   << " "
                   << setshowpoint() << setw(14) << setprecision(10)
                   << ev(i) << endl;
               }
            }
          }
          //cout << norm2(step-tmpstep) << endl;
          //dvector step1=-solve(Hess,grad);
          //cout << norm2(step-step1) << endl;
        }
        else
        {
          step=-solve(Hess,grad);
        }
#     endif
      if (pmin->bad_step_flag)
        break;
      uhat_old=uhat;
      uhat+=step;

      double maxg_old=maxg;
      maxg=fabs(evaluate_function(uhat,pfmin));
      if (maxg>maxg_old)
      {
        uhat=uhat_old;
        evaluate_function(uhat,pfmin);
        break;
      }
      if (maxg < 1.e-13)
      {
        break;
      }
    }

    if (sparse_hessian_flag==0)
    {
      for (int i=1;i<=usize;i++)
      {
        y(i+xsize)=uhat(i);
      }
    }
    else
    {
      for (int i=1;i<=usize;i++)
      {
        value(y(i+xsize))=uhat(i);
      }
    }
  }
}
Example #6
0
void ProcessImpl::requestTerminationImpl(PIDImpl pid)
{
	NamedEvent ev(terminationEventName(pid));
	ev.set();
}
Example #7
0
void DecoderHandler::error(const QString &e)
{
    QString *str = new QString(e);
    DecoderHandlerEvent ev(DecoderHandlerEvent::Error, str);
    dispatch(ev);
}
Example #8
0
	int32 applicationUnPause(void* systemData, void* userData)
	{
		Event ev(Stage::ACTIVATE);
		getStage()->dispatchEvent(&ev);
		return 0;
	}
Example #9
0
		void SDL_handleEvent(SDL_Event &event, bool &done)
		{
			Input *input = &Input::instance;


#ifndef EMSCRIPTEN
			SDL_Window *wnd = SDL_GetWindowFromID(event.window.windowID);			
			void *data = SDL_GetWindowData(wnd, "_");
			spStage stage = (Stage*)data;
#else
			spStage stage = getStage();
#endif
			if (!stage)
				stage = getStage();

			Event ev(Input::event_platform);
			ev.userData = &event;
			Input::instance.dispatchEvent(&ev);

			switch (event.type)
			{
			case SDL_QUIT:
				done = true;
				break;
			case SDL_WINDOWEVENT:
			{
				/*
				if (event.window.event == SDL_WINDOWEVENT_ENTER)
				active = false;
				if (event.window.event == SDL_WINDOWEVENT_LEAVE)
				active = true;
				*/

				if (event.window.event == SDL_WINDOWEVENT_MINIMIZED)
					active = false;
				if (event.window.event == SDL_WINDOWEVENT_RESTORED)
					active = true;

				bool newFocus = focus;
				if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST)
					newFocus = false;
				if (event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED)
					newFocus = true;
				if (focus != newFocus)
				{
					focus = newFocus;
#if HANDLE_FOCUS_LOST

					if (focus)
						focusAcquired();

					log::messageln("focus: %d", (int)focus);
					Event ev(focus ? Stage::ACTIVATE : Stage::DEACTIVATE);
					if (stage)
						stage->dispatchEvent(&ev);

					if (!focus)
						focusLost();
#endif							
				}
				//log::messageln("SDL_SYSWMEVENT %d", (int)event.window.event);
				break;
			}
			case SDL_MOUSEWHEEL:
				input->sendPointerWheelEvent(stage, event.wheel.y, &input->_pointerMouse);
				break;
			case SDL_KEYDOWN:
			{
				KeyEvent ev(KeyEvent::KEY_DOWN, &event.key);
				stage->dispatchEvent(&ev);
			} break;
			case SDL_KEYUP:
			{
				KeyEvent ev(KeyEvent::KEY_UP, &event.key);
				stage->dispatchEvent(&ev);
			} break;
#if SDL_VIDEO_OPENGL
			case SDL_MOUSEMOTION:
				input->sendPointerMotionEvent(stage, (float)event.motion.x, (float)event.motion.y, 1.0f, &input->_pointerMouse);
				break;
			case SDL_MOUSEBUTTONDOWN:
			case SDL_MOUSEBUTTONUP:
			{
				MouseButton b = MouseButton_Left;
				switch (event.button.button)
				{
				case 1: b = MouseButton_Left; break;
				case 2: b = MouseButton_Middle; break;
				case 3: b = MouseButton_Right; break;
				}

				input->sendPointerButtonEvent(stage, b, (float)event.button.x, (float)event.button.y, 1.0f,
					event.type == SDL_MOUSEBUTTONDOWN ? TouchEvent::TOUCH_DOWN : TouchEvent::TOUCH_UP, &input->_pointerMouse);
			}
				break;
#else

			case SDL_FINGERMOTION:
			{
				//log::messageln("SDL_FINGERMOTION");
				Vector2 pos = convertTouch(event);
				input->sendPointerMotionEvent(stage,
					pos.x, pos.y, event.tfinger.pressure,
					input->getTouchByID((int)event.tfinger.fingerId));
			}

				break;
			case SDL_FINGERDOWN:
			case SDL_FINGERUP:
			{
				//log::messageln("SDL_FINGER");
				Vector2 pos = convertTouch(event);
				input->sendPointerButtonEvent(stage, 
					MouseButton_Touch,
					pos.x, pos.y, event.tfinger.pressure,
					event.type == SDL_FINGERDOWN ? TouchEvent::TOUCH_DOWN : TouchEvent::TOUCH_UP,
					input->getTouchByID((int)event.tfinger.fingerId));
			}
				break;
#endif
			}

		}
Example #10
0
void Widget::initTheme()
{
  InitThemeEvent ev(this, m_theme);
  onInitTheme(ev);
}
Example #11
0
void
ase_jni_engine_factory::init_own_vm()
{
    ase_init_flags("ASE_JNI_VERBOSE", util::verbose);
    const char *const *path = env.get_path();
    util::ase_jni_engines eng;
    std::string clpath = ase_jni_find_jarfiles(path, eng);
    std::string uclpath = ase_jni_get_user_classpath();
    if (!uclpath.empty()) {
        if (!clpath.empty()) {
            clpath += ASE_PATH_SEP_STR;
        }
        clpath += uclpath;
    }
    ASE_JNI_VERBOSE_JNI(fprintf(stderr, "new jvm classpath=%s\n",
                                clpath.c_str()));

    std::string jvmpath = get_jvmpath();
    ASE_JNI_VERBOSE_JNI(fprintf(stderr, "jvmpath=%s\n", jvmpath.c_str()));
    asejni_jvm_dll = new ase_auto_dll_handle(jvmpath, true);
    if (!asejni_jvm_dll->get_error().empty()) {
        ase_string s = "JNI: init: " + asejni_jvm_dll->get_error();
        ase_throw_error(s.data());
    }
    void *sym = asejni_jvm_dll->get_symbol(ase_string("JNI_CreateJavaVM"));
    if (!sym) {
        ase_string s = "JNI: symbol JNI_CreateJavaVM not found in "
                       + ase_string(jvmpath.c_str());
        ase_throw_error(s.data());
    }
    typedef jint (JNICALL *jvmini_type)(JavaVM **, void **, void *);
    jvmini_type jvmini = (jvmini_type)(sym);

    std::vector<std::string> java_opts;
    ase_jni_get_javaopts(java_opts);

    JavaVMInitArgs vm_args;
    std::memset(&vm_args, 0, sizeof(vm_args));
    std::vector<JavaVMOption> options;
    std::string c = "-Djava.class.path=" + clpath;
    add_option(options, const_cast<char *>(c.c_str()));
    ASE_JNI_VERBOSE_JNI(add_option(options, "-Xcheck:jni"));
    ASE_JNI_VERBOSE_CLS(add_option(options, "-verbose:class"));
    ASE_JNI_VERBOSE_GC(add_option(options, "-verbose:gc"));
    for (ase_size_type i = 0; i < java_opts.size(); ++i) {
        add_option(options, const_cast<char *>(java_opts[i].c_str()));
    }
    vm_args.version = 0x00010002;
    vm_args.nOptions = static_cast<jint>(options.size());
    vm_args.options = &options[0];
    vm_args.ignoreUnrecognized = JNI_FALSE;
    JNIEnv *env = 0;
    JavaVM *tjvm = 0;
    jint e = (*jvmini)(&tjvm, &reinterpret_cast<void *&>(env), &vm_args);
    /* -fno-strict-aliasing */
    if (e < 0 || env == 0) {
        ase_variant ev(static_cast<ase_int>(e));
        ase_string evs = "failed to create java vm: err=" + ev.get_string();
        ase_throw_error(evs.data());
    }
    asejni_jvm = tjvm;
    asejni_sdata = new util::javastaticdata(asejni_jvm, env, eng);
}
Example #12
0
void CPanelHistory::OnComboBox(wxCommandEvent &)
{
  EnableButtons();
  wxCommandEvent ev(wxEVT_COMMAND_ENTER,GetId());
  ProcessEvent(ev);
}
Example #13
0
void KWCanvasItem::wheelEvent(QGraphicsSceneWheelEvent *event)
{
    QWheelEvent ev(event->pos().toPoint(), event->delta(), event->buttons(), event->modifiers(), event->orientation());
    m_toolProxy->wheelEvent(&ev, m_viewMode->viewToDocument(event->pos() + m_documentOffset));
    event->setAccepted(ev.isAccepted());
}
Example #14
0
void ScrollArea::touchEvent(QTouchEvent *e) {
	if (!e->touchPoints().isEmpty()) {
		_touchPrevPos = _touchPos;
		_touchPos = e->touchPoints().cbegin()->screenPos().toPoint();
	}

	switch (e->type()) {
	case QEvent::TouchBegin:
		if (_touchPress || e->touchPoints().isEmpty()) return;
		_touchPress = true;
		if (_touchScrollState == TouchScrollAuto) {
			_touchScrollState = TouchScrollAcceleration;
			_touchWaitingAcceleration = true;
			_touchAccelerationTime = getms();
			touchUpdateSpeed();
			_touchStart = _touchPos;
		} else {
			_touchScroll = false;
			_touchTimer.start(QApplication::startDragTime());
		}
		_touchStart = _touchPrevPos = _touchPos;
		_touchRightButton = false;
		break;

	case QEvent::TouchUpdate:
		if (!_touchPress) return;
		if (!_touchScroll && (_touchPos - _touchStart).manhattanLength() >= QApplication::startDragDistance()) {
			_touchTimer.stop();
			_touchScroll = true;
			touchUpdateSpeed();
		}
		if (_touchScroll) {
			if (_touchScrollState == TouchScrollManual) {
				touchScrollUpdated(_touchPos);
			} else if (_touchScrollState == TouchScrollAcceleration) {
				touchUpdateSpeed();
				_touchAccelerationTime = getms();
				if (_touchSpeed.isNull()) {
					_touchScrollState = TouchScrollManual;
				}
			}
		}
		break;

	case QEvent::TouchEnd:
		if (!_touchPress) return;
		_touchPress = false;
		if (_touchScroll) {
			if (_touchScrollState == TouchScrollManual) {
				_touchScrollState = TouchScrollAuto;
				_touchPrevPosValid = false;
				_touchScrollTimer.start(15);
				_touchTime = getms();
			} else if (_touchScrollState == TouchScrollAuto) {
				_touchScrollState = TouchScrollManual;
				_touchScroll = false;
				touchResetSpeed();
			} else if (_touchScrollState == TouchScrollAcceleration) {
				_touchScrollState = TouchScrollAuto;
				_touchWaitingAcceleration = false;
				_touchPrevPosValid = false;
			}
		} else if (window()) { // one short tap -- like left mouse click, one long tap -- like right mouse click
			Qt::MouseButton btn(_touchRightButton ? Qt::RightButton : Qt::LeftButton);

			sendSynteticMouseEvent(this, QEvent::MouseMove, Qt::NoButton, _touchStart);
			sendSynteticMouseEvent(this, QEvent::MouseButtonPress, btn, _touchStart);
			sendSynteticMouseEvent(this, QEvent::MouseButtonRelease, btn, _touchStart);

			if (_touchRightButton) {
				auto windowHandle = window()->windowHandle();
				auto localPoint = windowHandle->mapFromGlobal(_touchStart);
				QContextMenuEvent ev(QContextMenuEvent::Mouse, localPoint, _touchStart, QGuiApplication::keyboardModifiers());
				ev.setTimestamp(getms());
				QGuiApplication::sendEvent(windowHandle, &ev);
			}
		}
		_touchTimer.stop();
		_touchRightButton = false;
		break;

	case QEvent::TouchCancel:
		_touchPress = false;
		_touchScroll = false;
		_touchScrollState = TouchScrollManual;
		_touchTimer.stop();
		break;
	}
}
int main (int argc, char** argv) {
  // load framework libraries
  gSystem->Load( "libFWCoreFWLite" );
  //gSystem->Load("libNtupleMakerBEANmaker.so");
  AutoLibraryLoader::enable();
  
  int debug = 0; // levels of debug, 10 is large

  JobParameters myConfig = parseJobOptions(argc, argv);
  
  TFile * outputFile = new TFile (myConfig.outputFileName.c_str(), "RECREATE");

  outputFile->cd();

  TTree * summaryTree = new TTree("summaryTree", "Summary Event Values");

  fwlite::ChainEvent ev(myConfig.inputFileNames);

  HelperLeptonCore lepHelper;

  // setup the analysis 
  // it comes from the lepHelper
  BEANhelper * beanHelper = lepHelper.setupAnalysisParameters("2012_53x", myConfig.sampleName);

  // ---------------------------------------------
  // Note for future development: should these be
  // saved inside the lepHelper somewhere?
  // For now they are ok here
  // ---------------------------------------------

  // when the selections are the same, then everything should be tight not loose
  muonID::muonID muonTightID = muonID::muonSideTightMVA;
  muonID::muonID muonLooseID = muonID::muonSideLooseMVA; 
  muonID::muonID muonPreselectedID = muonID::muonSide; 
  electronID::electronID electronTightID = electronID::electronSideTightMVA;
  electronID::electronID electronLooseID = electronID::electronSideLooseMVA;
  electronID::electronID electronPreselectedID = electronID::electronSide;
  
  // declare your kinematic variables that you want
  // to be written out into the tree
  vector<ArbitraryVariable*> kinVars;
  vector<ArbitraryVariable*> cutVars;

//    NumJets myNjets;
//    myNjets.setCut(2); // parameter is keep events with jets  >= num
//    kinVars.push_back(&myNjets); //save it in the tree
//    cutVars.push_back(&myNjets); //also cut on it

//    NumLeptons myNlep;
//    kinVars.push_back(&myNlep);

   // CSV weights don't exist for jets
   // with a pt < 30
   // 
   //   CSVWeights myCSV(&lepHelper);
   //   kinVars.push_back(&myCSV);

   PUWeights myPU(&lepHelper);
   kinVars.push_back(&myPU);

   TopPtWeights myTopPt(&lepHelper);
   kinVars.push_back(&myTopPt);

   // do these definitions work?
   // yes, it it tight and everything else is loose
   LeptonIDAndIsoScaleFactors myLepIDAndIsoSF(&lepHelper, muonTightID, muonLooseID, electronTightID, electronLooseID);
   kinVars.push_back(&myLepIDAndIsoSF);

   LeptonTriggerScaleFactors myLepTrig( &lepHelper);
   kinVars.push_back(&myLepTrig);

   CleanEventVars myClean (&lepHelper);
   kinVars.push_back(&myClean);

   CheckTwoLepTrigger checkTrig (&lepHelper);
   kinVars.push_back(&checkTrig);

   //MassLepLep mll;
   //kinVars.push_back(&mll);

//   GenericMuonCollectionMember<double, BNmuonCollection> allMuonPt(Reflex::Type::ByName("BNmuon"),  "pt", "muons_by_pt",  KinematicVariableConstants::FLOAT_INIT, 2);
//   kinVars.push_back(&allMuonPt);

//   GenericMuonCollectionMember<double, BNmuonCollection> allMuonEta(Reflex::Type::ByName("BNmuon"),  "eta", "muons_by_pt",  KinematicVariableConstants::FLOAT_INIT, 2);
//   kinVars.push_back(&allMuonEta);

//   GenericJetCollectionMember<double, BNjetCollection> allJetPt(Reflex::Type::ByName("BNjet"),  "pt", "jet_by_pt",  KinematicVariableConstants::FLOAT_INIT, 6);
//   kinVars.push_back(&allJetPt);

//   GenericJetCollectionMember<double, BNjetCollection> allJetEta(Reflex::Type::ByName("BNjet"),  "eta", "jet_by_pt",  KinematicVariableConstants::FLOAT_INIT, 6);
//   kinVars.push_back(&allJetEta);

   int numExtraPartons = -99;
   summaryTree->Branch("numExtraPartons", &numExtraPartons);

//   GenericEventCollectionMember<unsigned, BNeventCollection> runNumber(Reflex::Type::ByName("BNevent"),  "run", "eventInfo",  KinematicVariableConstants::UINT_INIT, 1);
//   kinVars.push_back(&runNumber);

//   GenericEventCollectionMember<unsigned, BNeventCollection> lumiBlock(Reflex::Type::ByName("BNevent"),  "lumi", "eventInfo",  KinematicVariableConstants::UINT_INIT, 1);
//   kinVars.push_back(&lumiBlock);

  // this is a long inside BNevent
  // just using keyword long won't work
  // needs to be Long64_t 
//   GenericEventCollectionMember<Long64_t, BNeventCollection> eventNumber(Reflex::Type::ByName("BNevent"),  "evt", "eventInfo",  KinematicVariableConstants::INT_INIT, 1);
//   kinVars.push_back(&eventNumber);
  // hook up the variables

  if (debug > 9) { cout << "Hooking variables to tree" << endl;}
  for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin();
       iVar != kinVars.end();
       iVar++) {
    
    (*iVar)->attachToTree (summaryTree);
    
  }

  int numEvents = 0;
  int numEventsFailCuts = 0;
  int numEventsPassCuts = 0;

  int printEvery = 1000;

  BEANFileInterface selectedCollections;
  
  for (ev.toBegin(); !ev.atEnd(); ++ev){
    numEvents++;

    if (numEvents > myConfig.maxEvents) break;

    if (numEvents == 1 || numEvents % printEvery == 0 )
      cout << "Processing event.... " << numEvents << endl;

    
    if (debug > 9) cout << "---------->>>>>> Event " << numEvents << endl;
    
    lepHelper.initializeInputCollections(ev, true, selectedCollections);

    /////////////////////////////////////////////////////////////
    //
    //    Apply object ids
    //
    //////////////////////////////////////////////////////////////

    //------------    Jets
    if (debug > 9) cout << "Getting jets "  << endl;
	lepHelper.getTightCorrectedJets(25.0, 2.4, jetID::jetLoose, &selectedCollections);

    //------------  Electrons
    if (debug > 9) cout << "Getting electrons "  << endl;
    lepHelper.getTightLoosePreselectedElectrons(electronTightID, electronLooseID, electronPreselectedID, &selectedCollections);
    
    //-----------    Muons
    if (debug > 9) cout << "Getting muons "  << endl;
    lepHelper.getTightLoosePreselectedMuons(muonTightID, muonLooseID, muonPreselectedID, &selectedCollections);

    //----------    MET
    if (debug > 9) cout << "Getting met "  << endl;
    lepHelper.getCorrectedMet(&selectedCollections);

    //--------- fill up the lepton collections
    if (debug >9) cout << "Filling lepton collections" << endl;
    lepHelper.fillLepCollectionWithSelectedLeptons(&selectedCollections);

    // reset all the vars
    if (debug > 9) cout << "Resetting "  << endl;
    for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin();
         iVar != kinVars.end();
         iVar++) {
      
      (*iVar)->reset();
      (*iVar)->assignCollections(&selectedCollections);
      
    }

    bool passAllCuts = true;

    if (debug > 9) cout << "Checking cuts "  << endl;
    
    for (vector<ArbitraryVariable*>::iterator iCut = cutVars.begin();
         iCut != cutVars.end();
         iCut++ ) {

      (*iCut)->evaluate();
      passAllCuts = passAllCuts && (*iCut)->passCut();

    }

    // do the lepton cut
    passAllCuts = passAllCuts &&  LeptonCutThisAnalysis(&selectedCollections);
    
    
    if (!passAllCuts) {
      numEventsFailCuts++;

      //!!!!    Skip The event  ///////////////
      
      continue;

    } else {
      numEventsPassCuts++;
    }
    
    // Now  evaluate the vars
    if (debug > 9) cout << "Evaluating vars "  << endl;
    
    for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin();
         iVar != kinVars.end();
         iVar++) {
      
      (*iVar)->evaluate();
    }

    if (debug > 9) {
      for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin();
           iVar != kinVars.end();
           iVar++) {
        
        (*iVar)->print();
        cout << endl;
        
      }
    }

    //LeptonVarsThisAnalysis(&selectedCollections, LeptonCutThisAnalysis(&selectedCollections), TwoMuon, TwoElectron, MuonElectron);

    getNumExtraPartons(beanHelper, selectedCollections, numExtraPartons);
    if (myConfig.sampleName.find("_0p") != std::string::npos) { //0 parton samples
      //Cut to require 0 partons
      if (numExtraPartons != 0) {
        numEventsFailCuts++;
        numEventsPassCuts--;
        continue;
      }
    }

    if (debug > 9) cout << "Filling tree "  << endl;
    summaryTree->Fill();
    if (debug > 9) cout << "Done with event  " << numEvents  << endl;
  }// end for each event

  cout << "Num Events processed " << numEvents << endl
       << "Passed cuts " << numEventsPassCuts << endl
       << "Failed cuts " << numEventsFailCuts << endl ;

  outputFile->Write();
  outputFile->Close();

}
Example #16
0
bool ButtonBase::onProcessMessage(Message* msg)
{
  switch (msg->type()) {

    case kFocusEnterMessage:
    case kFocusLeaveMessage:
      if (isEnabled()) {
        if (m_behaviorType == kButtonWidget) {
          // Deselect the widget (maybe the user press the key, but
          // before release it, changes the focus).
          if (isSelected())
            setSelected(false);
        }

        // TODO theme specific stuff
        invalidate();
      }
      break;

    case kKeyDownMessage: {
      KeyMessage* keymsg = static_cast<KeyMessage*>(msg);
      KeyScancode scancode = keymsg->scancode();

      if (isEnabled() && isVisible()) {
        bool mnemonicPressed =
          ((msg->altPressed() || msg->cmdPressed()) &&
           isMnemonicPressed(keymsg));

        // For kButtonWidget
        if (m_behaviorType == kButtonWidget) {
          // Has focus and press enter/space
          if (hasFocus()) {
            if ((scancode == kKeyEnter) ||
                (scancode == kKeyEnterPad) ||
                (scancode == kKeySpace)) {
              setSelected(true);
              return true;
            }
          }

          // Check if the user pressed mnemonic.
          if (mnemonicPressed) {
            setSelected(true);
            return true;
          }
          // Magnetic widget catches ENTERs
          else if (isFocusMagnet() &&
                   ((scancode == kKeyEnter) ||
                    (scancode == kKeyEnterPad))) {
            manager()->setFocus(this);

            // Dispatch focus movement messages (because the buttons
            // process them)
            manager()->dispatchMessages();

            setSelected(true);
            return true;
          }
        }
        // For kCheckWidget or kRadioWidget
        else {
          /* if the widget has the focus and the user press space or
             if the user press Alt+the underscored letter of the button */
          if ((hasFocus() && (scancode == kKeySpace)) || mnemonicPressed) {
            if (m_behaviorType == kCheckWidget) {
              // Swap the select status
              setSelected(!isSelected());
              invalidate();
            }
            else if (m_behaviorType == kRadioWidget) {
              if (!isSelected()) {
                setSelected(true);
              }
            }
            return true;
          }
        }
      }
      break;
    }

    case kKeyUpMessage:
      if (isEnabled()) {
        if (m_behaviorType == kButtonWidget) {
          if (isSelected()) {
            generateButtonSelectSignal();
            return true;
          }
        }
      }
      break;

    case kMouseDownMessage:
      switch (m_behaviorType) {

        case kButtonWidget:
          if (isEnabled()) {
            setSelected(true);

            m_pressedStatus = isSelected();
            captureMouse();
          }
          return true;

        case kCheckWidget:
          if (isEnabled()) {
            setSelected(!isSelected());

            m_pressedStatus = isSelected();
            captureMouse();
          }
          return true;

        case kRadioWidget:
          if (isEnabled()) {
            if (!isSelected()) {
              m_handleSelect = false;
              setSelected(true);
              m_handleSelect = true;

              m_pressedStatus = isSelected();
              captureMouse();
            }
          }
          return true;
      }
      break;

    case kMouseUpMessage:
      if (hasCapture()) {
        releaseMouse();

        if (hasMouseOver()) {
          switch (m_behaviorType) {

            case kButtonWidget:
              generateButtonSelectSignal();
              break;

            case kCheckWidget:
              {
                // Fire onClick() event
                Event ev(this);
                onClick(ev);

                invalidate();
              }
              break;

            case kRadioWidget:
              {
                setSelected(false);
                setSelected(true);

                // Fire onClick() event
                Event ev(this);
                onClick(ev);
              }
              break;
          }
        }
        return true;
      }
      break;

    case kMouseMoveMessage:
      if (isEnabled() && hasCapture()) {
        bool hasMouse = hasMouseOver();

        m_handleSelect = false;

        // Switch state when the mouse go out
        if ((hasMouse && isSelected() != m_pressedStatus) ||
            (!hasMouse && isSelected() == m_pressedStatus)) {
          if (hasMouse)
            setSelected(m_pressedStatus);
          else
            setSelected(!m_pressedStatus);
        }

        m_handleSelect = true;
      }
      break;

    case kMouseEnterMessage:
    case kMouseLeaveMessage:
      // TODO theme stuff
      if (isEnabled())
        invalidate();
      break;
  }

  return Widget::onProcessMessage(msg);
}
void QApplicationPrivate::processMouseEvent(QWindowSystemInterfacePrivate::MouseEvent *e)
{
    if (!e->widget)
       return;

    // qDebug() << "handleMouseEvent" << tlw << ev.pos() << ev.globalPos() << hex << ev.buttons();
    static QWeakPointer<QWidget> implicit_mouse_grabber;

    QEvent::Type type;
    // move first
    Qt::MouseButtons stateChange = e->buttons ^ buttons;
    if (e->globalPos != QPoint(qt_last_x, qt_last_y) && (stateChange != Qt::NoButton)) {
        QWindowSystemInterfacePrivate::MouseEvent * newMouseEvent =
                new QWindowSystemInterfacePrivate::MouseEvent(e->widget.data(), e->timestamp, e->localPos, e->globalPos, e->buttons);
        QWindowSystemInterfacePrivate::windowSystemEventQueue.prepend(newMouseEvent); // just in case the move triggers a new event loop
        stateChange = Qt::NoButton;
    }

    QWidget * tlw = e->widget.data();

    QPoint localPoint = e->localPos;
    QPoint globalPoint = e->globalPos;
    QWidget *mouseWindow = tlw;

    Qt::MouseButton button = Qt::NoButton;


    if (qt_last_x != globalPoint.x() || qt_last_y != globalPoint.y()) {
        type = QEvent::MouseMove;
        qt_last_x = globalPoint.x();
        qt_last_y = globalPoint.y();
        if (qAbs(globalPoint.x() - mousePressX) > mouse_double_click_distance||
            qAbs(globalPoint.y() - mousePressY) > mouse_double_click_distance)
            mousePressButton = Qt::NoButton;
    }
    else { // check to see if a new button has been pressed/released
        for (int check = Qt::LeftButton;
             check <= Qt::XButton2;
             check = check << 1) {
            if (check & stateChange) {
                button = Qt::MouseButton(check);
                break;
            }
        }
        if (button == Qt::NoButton) {
            // Ignore mouse events that don't change the current state
            return;
        }
        buttons = e->buttons;
        if (button & e->buttons) {
            if ((e->timestamp - mousePressTime) < static_cast<ulong>(QApplication::doubleClickInterval()) && button == mousePressButton) {
                type = QEvent::MouseButtonDblClick;
                mousePressButton = Qt::NoButton;
            }
            else {
                type = QEvent::MouseButtonPress;
                mousePressTime = e->timestamp;
                mousePressButton = button;
                mousePressX = qt_last_x;
                mousePressY = qt_last_y;
            }
        }
        else
            type = QEvent::MouseButtonRelease;
    }

    if (self->inPopupMode()) {
        //popup mouse handling is magical...
        mouseWindow = qApp->activePopupWidget();

        implicit_mouse_grabber.clear();
        //### how should popup mode and implicit mouse grab interact?

    } else if (tlw && app_do_modal && !qt_try_modal(tlw, QEvent::MouseButtonRelease) ) {
        //even if we're blocked by modality, we should deliver the mouse release event..
        //### this code is not completely correct: multiple buttons can be pressed simultaneously
        if (!(implicit_mouse_grabber && buttons == Qt::NoButton)) {
            //qDebug() << "modal blocked mouse event to" << tlw;
            return;
        }
    }

    // find the tlw if we didn't get it from the plugin
    if (!mouseWindow) {
        mouseWindow = QApplication::topLevelAt(globalPoint);
    }

    if (!mouseWindow && !implicit_mouse_grabber)
        mouseWindow = QApplication::desktop();

    if (mouseWindow && mouseWindow != tlw) {
        //we did not get a sensible localPoint from the window system, so let's calculate it
        localPoint = mouseWindow->mapFromGlobal(globalPoint);
    }

    // which child should have it?
    QWidget *mouseWidget = mouseWindow;
    if (mouseWindow) {
        QWidget *w =  mouseWindow->childAt(localPoint);
        if (w) {
            mouseWidget = w;
        }
    }

    //handle implicit mouse grab
    if (type == QEvent::MouseButtonPress && !implicit_mouse_grabber) {
        implicit_mouse_grabber = mouseWidget;

        Q_ASSERT(mouseWindow);
        mouseWindow->activateWindow(); //focus
    } else if (implicit_mouse_grabber) {
        mouseWidget = implicit_mouse_grabber.data();
        mouseWindow = mouseWidget->window();
        if (mouseWindow != tlw)
            localPoint = mouseWindow->mapFromGlobal(globalPoint);
    }

    Q_ASSERT(mouseWidget);

    //localPoint is local to mouseWindow, but it needs to be local to mouseWidget
    localPoint = mouseWidget->mapFrom(mouseWindow, localPoint);

    if (buttons == Qt::NoButton) {
        //qDebug() << "resetting mouse grabber";
        implicit_mouse_grabber.clear();
    }

    if (mouseWidget != qt_last_mouse_receiver) {
        dispatchEnterLeave(mouseWidget, qt_last_mouse_receiver);
        qt_last_mouse_receiver = mouseWidget;
    }

    // Remember, we might enter a modal event loop when sending the event,
    // so think carefully before adding code below this point.

    // qDebug() << "sending mouse ev." << ev.type() << localPoint << globalPoint << ev.button() << ev.buttons() << mouseWidget << "mouse grabber" << implicit_mouse_grabber;

    QMouseEvent ev(type, localPoint, globalPoint, button, buttons, QApplication::keyboardModifiers());

    QList<QWeakPointer<QPlatformCursor> > cursors = QPlatformCursorPrivate::getInstances();
    foreach (QWeakPointer<QPlatformCursor> cursor, cursors) {
        if (cursor)
            cursor.data()->pointerEvent(ev);
    }

    int oldOpenPopupCount = openPopupCount;
    QApplication::sendSpontaneousEvent(mouseWidget, &ev);

#ifndef QT_NO_CONTEXTMENU
    if (type == QEvent::MouseButtonPress && button == Qt::RightButton && (openPopupCount == oldOpenPopupCount)) {
        QContextMenuEvent e(QContextMenuEvent::Mouse, localPoint, globalPoint, QApplication::keyboardModifiers());
        QApplication::sendSpontaneousEvent(mouseWidget, &e);
    }
#endif // QT_NO_CONTEXTMENU
}
Example #18
0
void WebView::editDelete()
{
    QKeyEvent ev(QEvent::KeyPress, Qt::Key_Delete, Qt::NoModifier);
    QApplication::sendEvent(this, &ev);
}
Example #19
0
bool QWidgetWindow::event(QEvent *event)
{
    if (m_widget->testAttribute(Qt::WA_DontShowOnScreen)) {
        // \a event is uninteresting for QWidgetWindow, the event was probably
        // generated before WA_DontShowOnScreen was set
        return m_widget->event(event);
    }

    switch (event->type()) {
    case QEvent::Close:
        handleCloseEvent(static_cast<QCloseEvent *>(event));
        return true;

    case QEvent::Enter:
    case QEvent::Leave:
        handleEnterLeaveEvent(event);
        return true;

    // these should not be sent to QWidget, the corresponding events
    // are sent by QApplicationPrivate::notifyActiveWindowChange()
    case QEvent::FocusIn:
    case QEvent::FocusOut: {
#ifndef QT_NO_ACCESSIBILITY
        QAccessible::State state;
        state.active = true;
        QAccessibleStateChangeEvent ev(widget(), state);
        QAccessible::updateAccessibility(&ev);
#endif
        return false; }

    case QEvent::FocusAboutToChange:
        if (QApplicationPrivate::focus_widget) {
            if (QApplicationPrivate::focus_widget->testAttribute(Qt::WA_InputMethodEnabled))
                qApp->inputMethod()->commit();

            QGuiApplication::sendSpontaneousEvent(QApplicationPrivate::focus_widget, event);
        }
        return true;

    case QEvent::KeyPress:
    case QEvent::KeyRelease:
    case QEvent::ShortcutOverride:
        handleKeyEvent(static_cast<QKeyEvent *>(event));
        return true;

    case QEvent::MouseMove:
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseButtonDblClick:
        handleMouseEvent(static_cast<QMouseEvent *>(event));
        return true;

    case QEvent::NonClientAreaMouseMove:
    case QEvent::NonClientAreaMouseButtonPress:
    case QEvent::NonClientAreaMouseButtonRelease:
    case QEvent::NonClientAreaMouseButtonDblClick:
        handleNonClientAreaMouseEvent(static_cast<QMouseEvent *>(event));
        return true;

    case QEvent::TouchBegin:
    case QEvent::TouchUpdate:
    case QEvent::TouchEnd:
    case QEvent::TouchCancel:
        handleTouchEvent(static_cast<QTouchEvent *>(event));
        return true;

    case QEvent::Move:
        handleMoveEvent(static_cast<QMoveEvent *>(event));
        return true;

    case QEvent::Resize:
        handleResizeEvent(static_cast<QResizeEvent *>(event));
        return true;

#ifndef QT_NO_WHEELEVENT
    case QEvent::Wheel:
        handleWheelEvent(static_cast<QWheelEvent *>(event));
        return true;
#endif

#ifndef QT_NO_DRAGANDDROP
    case QEvent::DragEnter:
    case QEvent::DragMove:
        handleDragEnterMoveEvent(static_cast<QDragMoveEvent *>(event));
        return true;
    case QEvent::DragLeave:
        handleDragLeaveEvent(static_cast<QDragLeaveEvent *>(event));
        return true;
    case QEvent::Drop:
        handleDropEvent(static_cast<QDropEvent *>(event));
        return true;
#endif

    case QEvent::Expose:
        handleExposeEvent(static_cast<QExposeEvent *>(event));
        return true;

    case QEvent::WindowStateChange:
        handleWindowStateChangedEvent(static_cast<QWindowStateChangeEvent *>(event));
        return true;

    case QEvent::ThemeChange: {
        QEvent widgetEvent(QEvent::ThemeChange);
        QGuiApplication::sendSpontaneousEvent(m_widget, &widgetEvent);
    }
        return true;

#ifndef QT_NO_TABLETEVENT
    case QEvent::TabletPress:
    case QEvent::TabletMove:
    case QEvent::TabletRelease:
        handleTabletEvent(static_cast<QTabletEvent *>(event));
        return true;
#endif
#ifndef QT_NO_CONTEXTMENU
    case QEvent::ContextMenu:
        handleContextMenuEvent(static_cast<QContextMenuEvent *>(event));
        return true;
#endif

    // Handing show events to widgets (see below) here would cause them to be triggered twice
    case QEvent::Show:
    case QEvent::Hide:
        return QWindow::event(event);

    default:
        break;
    }

    return m_widget->event(event) || QWindow::event(event);
}
void EventDispatcher::dispatchCustomEvent(const std::string &eventName, void *optionalUserData)
{
    EventCustom ev(eventName);
    ev.setUserData(optionalUserData);
    dispatchEvent(&ev);
}
Example #21
0
void DecoderHandler::doInfo(const QString &message)
{
    DecoderHandlerEvent ev(DecoderHandlerEvent::Info, new QString(message));
    dispatch(ev);
}
Example #22
0
bool eigenSolver::solve(int numEigenValues, std::string which)
{
  if(!_A) return false;
  Mat A = _A->getMatrix();
  Mat B = _B ? _B->getMatrix() : PETSC_NULL;

  PetscInt N, M;
  _try(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
  _try(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
  _try(MatGetSize(A, &N, &M));

  PetscInt N2, M2;
  if (_B) {
    _try(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
    _try(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
    _try(MatGetSize(B, &N2, &M2));
  }

  // generalized eigenvalue problem A x - \lambda B x = 0
  EPS eps;
  _try(EPSCreate(PETSC_COMM_WORLD, &eps));
  _try(EPSSetOperators(eps, A, B));
  if(_hermitian)
    _try(EPSSetProblemType(eps, _B ? EPS_GHEP : EPS_HEP));
  else
    _try(EPSSetProblemType(eps, _B ? EPS_GNHEP : EPS_NHEP));

  // set some default options
  _try(EPSSetDimensions(eps, numEigenValues, PETSC_DECIDE, PETSC_DECIDE));
  _try(EPSSetTolerances(eps, 1.e-7, 20));//1.e-7 20
  _try(EPSSetType(eps, EPSKRYLOVSCHUR)); //default
  //_try(EPSSetType(eps, EPSARNOLDI));
  //_try(EPSSetType(eps, EPSARPACK));
  //_try(EPSSetType(eps, EPSPOWER));

  // override these options at runtime, petsc-style
  _try(EPSSetFromOptions(eps));

  // force options specified directly as arguments
  if(numEigenValues)
    _try(EPSSetDimensions(eps, numEigenValues, PETSC_DECIDE, PETSC_DECIDE));
  if(which == "smallest")
    _try(EPSSetWhichEigenpairs(eps, EPS_SMALLEST_MAGNITUDE));
  else if(which == "smallestReal")
    _try(EPSSetWhichEigenpairs(eps, EPS_SMALLEST_REAL));
  else if(which == "largest")
    _try(EPSSetWhichEigenpairs(eps, EPS_LARGEST_MAGNITUDE));

  // print info
  #if (SLEPC_VERSION_RELEASE == 0 || (SLEPC_VERSION_MAJOR > 3 || (SLEPC_VERSION_MAJOR == 3 && SLEPC_VERSION_MINOR >= 4)))
  EPSType type;
  #else
  const EPSType type;
  #endif
  _try(EPSGetType(eps, &type));
  Msg::Debug("SLEPc solution method: %s", type);

  PetscInt nev;
  _try(EPSGetDimensions(eps, &nev, PETSC_NULL, PETSC_NULL));
  Msg::Debug("SLEPc number of requested eigenvalues: %d", nev);
  PetscReal tol;
  PetscInt maxit;
  _try(EPSGetTolerances(eps, &tol, &maxit));
  Msg::Debug("SLEPc stopping condition: tol=%g, maxit=%d", tol, maxit);

  // solve
  Msg::Info("SLEPc solving...");
  double t1 = Cpu();
  _try(EPSSolve(eps));

  // check convergence
  int its;
  _try(EPSGetIterationNumber(eps, &its));
  EPSConvergedReason reason;
  _try(EPSGetConvergedReason(eps, &reason));
  if(reason == EPS_CONVERGED_TOL){
    double t2 = Cpu();
    Msg::Debug("SLEPc converged in %d iterations (%g s)", its, t2-t1);
  }
  else if(reason == EPS_DIVERGED_ITS)
    Msg::Error("SLEPc diverged after %d iterations", its);
  else if(reason == EPS_DIVERGED_BREAKDOWN)
    Msg::Error("SLEPc generic breakdown in method");
#if (SLEPC_VERSION_MAJOR < 3 || (SLEPC_VERSION_MAJOR == 3 && SLEPC_VERSION_MINOR < 2))
  else if(reason == EPS_DIVERGED_NONSYMMETRIC)
    Msg::Error("The operator is nonsymmetric");
#endif

  // get number of converged approximate eigenpairs
  PetscInt nconv;
  _try(EPSGetConverged(eps, &nconv));
  Msg::Debug("SLEPc number of converged eigenpairs: %d", nconv);

  // ignore additional eigenvalues if we get more than what we asked
  if(nconv > nev) nconv = nev;

  if (nconv > 0) {
    Vec xr, xi;
    _try(MatGetVecs(A, PETSC_NULL, &xr));
    _try(MatGetVecs(A, PETSC_NULL, &xi));
    Msg::Debug("         Re[EigenValue]          Im[EigenValue]"
	       "          Relative error");
    for (int i = 0; i < nconv; i++){
      PetscScalar kr, ki;
      _try(EPSGetEigenpair(eps, i, &kr, &ki, xr, xi));
      PetscReal error;
      _try(EPSComputeRelativeError(eps, i, &error));
#if defined(PETSC_USE_COMPLEX)
      PetscReal re = PetscRealPart(kr);
      PetscReal im = PetscImaginaryPart(kr);
#else
      PetscReal re = kr;
      PetscReal im = ki;
#endif
      Msg::Debug("EIG %03d %s%.16e %s%.16e  %3.6e",
		 i, (re < 0) ? "" : " ", re, (im < 0) ? "" : " ", im, error);

      // store eigenvalues and eigenvectors
      _eigenValues.push_back(std::complex<double>(re, im));
      PetscScalar *tmpr, *tmpi;
      _try(VecGetArray(xr, &tmpr));
      _try(VecGetArray(xi, &tmpi));
      std::vector<std::complex<double> > ev(N);
      for(int i = 0; i < N; i++){
#if defined(PETSC_USE_COMPLEX)
        ev[i] = tmpr[i];
#else
        ev[i] = std::complex<double>(tmpr[i], tmpi[i]);
#endif
      }
       _eigenVectors.push_back(ev);
    }
    _try(VecDestroy(&xr));
    _try(VecDestroy(&xi));
  }

  _try(EPSDestroy(&eps));

  if(reason == EPS_CONVERGED_TOL){
    Msg::Debug("SLEPc done");
    return true;
  }
  else{
    Msg::Warning("SLEPc failed");
    return false;
  }

}
Example #23
0
    void run()
    {
        int mask = 0;
        if (owner().eventMask() & DirectoryWatcher::DW_ITEM_ADDED)
            mask |= IN_CREATE;
        if (owner().eventMask() & DirectoryWatcher::DW_ITEM_REMOVED)
            mask |= IN_DELETE;
        if (owner().eventMask() & DirectoryWatcher::DW_ITEM_MODIFIED)
            mask |= IN_MODIFY;
        if (owner().eventMask() & DirectoryWatcher::DW_ITEM_MOVED_FROM)
            mask |= IN_MOVED_FROM;
        if (owner().eventMask() & DirectoryWatcher::DW_ITEM_MOVED_TO)
            mask |= IN_MOVED_TO;
        int wd = inotify_add_watch(_fd, owner().directory().path().c_str(), mask);
        if (wd == -1)
        {
            try
            {
                FileImpl::handleLastErrorImpl(owner().directory().path());
            }
            catch (Poco::Exception& exc)
            {
                owner().scanError(&owner(), exc);
            }
        }

        Poco::Buffer<char> buffer(4096);
        while (!_stopped)
        {
            fd_set fds;
            FD_ZERO(&fds);
            FD_SET(_fd, &fds);

            struct timeval tv;
            tv.tv_sec  = 0;
            tv.tv_usec = 200000;

            if (select(_fd + 1, &fds, NULL, NULL, &tv) == 1)
            {
                int n = read(_fd, buffer.begin(), buffer.size());
                int i = 0;
                if (n > 0)
                {
                    while (n > 0)
                    {
                        struct inotify_event* pEvent = reinterpret_cast<struct inotify_event*>(buffer.begin() + i);

                        if (pEvent->len > 0)
                        {
                            if (!owner().eventsSuspended())
                            {
                                Poco::Path p(owner().directory().path());
                                p.makeDirectory();
                                p.setFileName(pEvent->name);
                                Poco::File f(p.toString());

                                if ((pEvent->mask & IN_CREATE) && (owner().eventMask() & DirectoryWatcher::DW_ITEM_ADDED))
                                {
                                    DirectoryWatcher::DirectoryEvent ev(f, DirectoryWatcher::DW_ITEM_ADDED);
                                    owner().itemAdded(&owner(), ev);
                                }
                                if ((pEvent->mask & IN_DELETE) && (owner().eventMask() & DirectoryWatcher::DW_ITEM_REMOVED))
                                {
                                    DirectoryWatcher::DirectoryEvent ev(f, DirectoryWatcher::DW_ITEM_REMOVED);
                                    owner().itemRemoved(&owner(), ev);
                                }
                                if ((pEvent->mask & IN_MODIFY) && (owner().eventMask() & DirectoryWatcher::DW_ITEM_MODIFIED))
                                {
                                    DirectoryWatcher::DirectoryEvent ev(f, DirectoryWatcher::DW_ITEM_MODIFIED);
                                    owner().itemModified(&owner(), ev);
                                }
                                if ((pEvent->mask & IN_MOVED_FROM) && (owner().eventMask() & DirectoryWatcher::DW_ITEM_MOVED_FROM))
                                {
                                    DirectoryWatcher::DirectoryEvent ev(f, DirectoryWatcher::DW_ITEM_MOVED_FROM);
                                    owner().itemMovedFrom(&owner(), ev);
                                }
                                if ((pEvent->mask & IN_MOVED_TO) && (owner().eventMask() & DirectoryWatcher::DW_ITEM_MOVED_TO))
                                {
                                    DirectoryWatcher::DirectoryEvent ev(f, DirectoryWatcher::DW_ITEM_MOVED_TO);
                                    owner().itemMovedTo(&owner(), ev);
                                }
                            }
                        }

                        i += sizeof(inotify_event) + pEvent->len;
                        n -= sizeof(inotify_event) + pEvent->len;
                    }
                }
            }
        }
    }
int main (int argc, char** argv) {
  // load framework libraries
  gSystem->Load( "libFWCoreFWLite" );
  //gSystem->Load("libNtupleMakerBEANmaker.so");
  AutoLibraryLoader::enable();

  int debug = 0; // levels of debug, 10 is large

  JobParameters myConfig = parseJobOptions(argc, argv);

  TFile * outputFile = new TFile (myConfig.outputFileName.c_str(), "RECREATE");

  outputFile->cd();

  TTree * summaryTree = new TTree("summaryTree", "Summary Event Values");

  fwlite::ChainEvent ev(myConfig.inputFileNames);

  HelperLeptonCore lepHelper;

  // setup the analysis
  // it comes from the lepHelper
  BEANhelper * beanHelper = lepHelper.setupAnalysisParameters("2012_53x", myConfig.sampleName);

  sysType::sysType jetSyst = sysType::NA;
  if (myConfig.jetSyst == "NA") jetSyst = sysType::NA;
  else if (myConfig.jetSyst == "JESUp") jetSyst = sysType::JESup;
  else if (myConfig.jetSyst == "JESDown") jetSyst = sysType::JESdown;
  else std::cout << "No valid JES corrections specified - using nominal" << std::endl;

  // ---------------------------------------------
  // Note for future development: should these be
  // saved inside the lepHelper somewhere?
  // For now they are ok here
  // ---------------------------------------------

  muonID::muonID muonTightID = muonID::muonTight;
  muonID::muonID muonLooseID = muonID::muonLoose;
  muonID::muonID muonPreselectedID = muonID::muonRaw;
  electronID::electronID electronTightID = electronID::electronTight;
  electronID::electronID electronLooseID = electronID::electronLoose;
  electronID::electronID electronPreselectedID = electronID::electronRaw;
  tauID::tauID tauTightID = tauID::tauMedium;
  //  tauID::tauID tauLooseID = tauID::tauVLoose;
  tauID::tauID tauPreselectedID = tauID::tauNonIso;

  // collections
  GenericCollection<BNelectronCollection> tightElectrons(beanHelper);
//   GenericCollection<BNelectronCollection> looseElectrons(beanHelper);
//   GenericCollection<BNelectronCollection> preselectedElectrons(beanHelper);
  GenericCollection<BNelectronCollection> tightLooseElectrons(beanHelper);
//   GenericCollection<BNelectronCollection> loosePreselectedElectrons(beanHelper);
  GenericCollection<BNelectronCollection> tightLoosePreselectedElectrons(beanHelper);

  GenericCollection<BNmuonCollection> tightMuons(beanHelper);
//   GenericCollection<BNmuonCollection> looseMuons(beanHelper);
//   GenericCollection<BNmuonCollection> preselectedMuons(beanHelper);
  GenericCollection<BNmuonCollection> tightLooseMuons(beanHelper);
  GenericCollection<BNmuonCollection> tightLoosePreselectedMuons(beanHelper);

//   GenericCollection<BNleptonCollection> tightLeptons(beanHelper);
//   GenericCollection<BNleptonCollection> looseLeptons(beanHelper);
//   GenericCollection<BNleptonCollection> preselectedLeptons(beanHelper);
//   GenericCollection<BNleptonCollection> tightLooseLeptons(beanHelper);
//   GenericCollection<BNleptonCollection> tightLoosePreselectedLeptons(beanHelper);

// //   GenericCollection<BNleptonCollection> tightLooseLeptons_fromHiggs(beanHelper); //failed to get working 

//   GenericCollection<BNtauCollection> tightTaus(beanHelper);
//   GenericCollection<BNtauCollection> tightLooseTaus(beanHelper);
//   GenericCollection<BNtauCollection> tightLoosePreselectedTaus(beanHelper);

//   GenericCollection<BNjetCollection> jets(beanHelper);
//   GenericCollection<BNjetCollection> jets_30(beanHelper);
//   GenericCollection<BNjetCollection> jetsByCSV(beanHelper);
//   GenericCollection<BNjetCollection> looseCSVJets(beanHelper);
//   GenericCollection<BNjetCollection> mediumCSVJets(beanHelper);
//   GenericCollection<BNjetCollection> notMediumCSVJets(beanHelper);

//   GenericCollection<BNjetCollection> jets_fromHiggs(beanHelper);
//   GenericCollection<BNjetCollection> jets_fromHiggs_30(beanHelper);

//   GenericCollection<BNmetCollection> met(beanHelper);
//   GenericCollection<BNprimaryvertexCollection> primaryVertexes(beanHelper);
//   GenericCollection<BNtriggerCollection> hltCollection(beanHelper);
//   GenericCollection<BNeventCollection> events(beanHelper);
//   GenericCollection<BNmcparticleCollection> mcParticles(beanHelper);

//   GenericCollection<BNmcparticleCollection> genHiggsParticles(beanHelper);
//   GenericCollection<BNmcparticleCollection> genTopParticles(beanHelper);
//   GenericCollection<BNmcparticleCollection> genAntiTopParticles(beanHelper);

  // declare your kinematic variables that you want
  // to be written out into the tree
  vector<ArbitraryVariable*> kinVars;
  vector<ArbitraryVariable*> cutVars;


//   GenericCollectionSizeVariable<BNjetCollection>
//     numJets(&(jets.ptrToItems), "numJets");
//   kinVars.push_back(&numJets);
//   numJets.setCutMin(2);
//   cutVars.push_back(&numJets);

//   GenericCollectionSizeVariable<BNjetCollection>
//     numJets_30(&(jets_30.ptrToItems), "numJets_30");
//   kinVars.push_back(&numJets_30);

//   GenericCollectionSizeVariable<BNjetCollection>
//     numJets_fromHiggs(&(jets_fromHiggs.ptrToItems), "numJets_fromHiggs");
//   kinVars.push_back(&numJets_fromHiggs);

//   GenericCollectionSizeVariable<BNjetCollection>
//     numJets_fromHiggs_30(&(jets_fromHiggs_30.ptrToItems), "numJets_fromHiggs_30");
//   kinVars.push_back(&numJets_fromHiggs_30);

//   GenericCollectionSizeVariable<BNjetCollection>
//     numMediumBJets(&(mediumCSVJets.ptrToItems), "numMediumBJets");
//   kinVars.push_back(&numMediumBJets);

//   GenericCollectionSizeVariable<BNjetCollection>
//     numLooseBJets(&(looseCSVJets.ptrToItems), "numLooseBJets");
//   kinVars.push_back(&numLooseBJets);
  
//   GenericCollectionSizeVariable<BNleptonCollection>
//     numTightLooseLeptons(&(tightLooseLeptons.ptrToItems), "numTightLooseLeptons");
//   kinVars.push_back(&numTightLooseLeptons);
//   numTightLooseLeptons.setCutMin(2);
//   cutVars.push_back(&numTightLooseLeptons);

//   GenericCollectionSizeVariable<BNleptonCollection>
//     numAllLeptons(&(tightLoosePreselectedLeptons.ptrToItems), "numAllLeptons");
//   kinVars.push_back(&numAllLeptons);

//   GenericCollectionSizeVariable<BNleptonCollection>
//     numTightLeptons(&(tightLeptons.ptrToItems), "numTightLeptons");
//   kinVars.push_back(&numTightLeptons);
//   numTightLeptons.setCutMin(1);
//   cutVars.push_back(&numTightLeptons);

//   GenericCollectionSizeVariable<BNmuonCollection>
//     numTightMuons(&(tightMuons.ptrToItems), "numTightMuons");
//   kinVars.push_back(&numTightMuons);

//   GenericCollectionSizeVariable<BNelectronCollection>
//     numTightElectrons(&(tightElectrons.ptrToItems), "numTightElectrons");
//   kinVars.push_back(&numTightElectrons);

//   CSVWeights
//     myCSV(beanHelper, &(jets.ptrToItems), jetSyst);
//   kinVars.push_back(&myCSV);

//   PUWeights
//     myPU(&lepHelper, &(events.ptrToItems));
//   kinVars.push_back(&myPU);

//   TopPtWeights
//     myTopPt(&lepHelper, &(mcParticles.ptrToItems));
//   kinVars.push_back(&myTopPt);

//   LeptonIDAndIsoScaleFactors
//     myLepIDAndIsoSF(&lepHelper, muonTightID, muonLooseID, electronTightID, electronLooseID,
//                     &(tightMuons.ptrToItems), &(looseMuons.ptrToItems),
//                     &(tightElectrons.ptrToItems), &(looseElectrons.ptrToItems));
//   kinVars.push_back(&myLepIDAndIsoSF);
  
//   LeptonTriggerScaleFactors
//     myLepTrig(&lepHelper, &(tightMuons.ptrToItems), &(looseMuons.ptrToItems), &(preselectedMuons.ptrToItems),
//               &(tightElectrons.ptrToItems), &(looseElectrons.ptrToItems), &(preselectedElectrons.ptrToItems));
//   kinVars.push_back(&myLepTrig);
  
//   CleanEventVars
//     myClean(&lepHelper, &(events.ptrToItems), &(primaryVertexes.ptrToItems));
//   kinVars.push_back(&myClean);
  
//   CheckTwoLepTrigger
//     checkTrig(&lepHelper, &(hltCollection.ptrToItems));
//   kinVars.push_back(&checkTrig);
  
//   //DBCorrectedRelIsoDR04s myDBCorrectedRelIsoDR04s(&lepHelper, 2);
//   //kinVars.push_back(&myDBCorrectedRelIsoDR04s);
 
//    HiggsDecayType
//     myHiggsDecayType(&lepHelper, &(mcParticles.ptrToItems));
//   kinVars.push_back(&myHiggsDecayType);
  
//   TwoObjectKinematic<BNleptonCollection,BNleptonCollection>
//     myMassLepLep("mass", "min", "mass_leplep",
//                  &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99,
//                  &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99);
//   kinVars.push_back(&myMassLepLep);
  
//   TwoObjectKinematic<BNleptonCollection,BNleptonCollection>
//     myZmass("mass", "closest_to", "Zmass",
//             &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99,
//             &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99,
//             91.2, "same_flavour");
//   kinVars.push_back(&myZmass);
  
//   TwoObjectKinematic<BNleptonCollection,BNleptonCollection>
//     myDeltaRLepLep("deltaR", "min", "dR_leplep",
//                    &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99,
//                    &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99);
//   kinVars.push_back(&myDeltaRLepLep);

//   TwoObjectKinematic<BNleptonCollection,BNleptonCollection>
//     myDeltaPhiLepLep("deltaPhi", "min", "dPhi_leplep",
//                    &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99,
//                    &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99);
//   kinVars.push_back(&myDeltaPhiLepLep);
  
//   TwoObjectKinematic<BNleptonCollection,BNjetCollection>
//     myMHT("pt", "vector_sum", "mht",
//           &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99,
//           &(jets.ptrToItems), "jets_by_pt", 1, 99);
//   kinVars.push_back(&myMHT);

//   ////////// Variables for BDT //////////
  
//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     myMinDrJets("deltaR", "min", "min_dr_jets",
//                 &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                 &(jets.ptrToItems), "jets_by_pt", 1, 99);
//   kinVars.push_back(&myMinDrJets);
  
//   TwoObjectKinematic<BNleptonCollection,BNjetCollection>
//     mySumPt("pt", "sum", "sum_pt",
//             &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 99,
//             &(jets.ptrToItems), "jets_by_pt", 1, 99);
//   kinVars.push_back(&mySumPt);

//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     mySumJetPt("pt", "sum", "sum_jet_pt",
//                &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                &(jets.ptrToItems), "jets_by_pt", 1, 99);
//   kinVars.push_back(&mySumJetPt);

//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     mySumJetMass("mass", "vector_sum", "sum_jet_mass",
//                  &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                  &(jets.ptrToItems), "jets_by_pt", 1, 99);
//   kinVars.push_back(&mySumJetMass);

//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     mySumNonTaggedJetMass("mass", "vector_sum", "sum_non_tagged_jet_mass",
//                           &(notMediumCSVJets.ptrToItems), "untagged_jets_by_pt", 1, 99,
//                           &(notMediumCSVJets.ptrToItems), "untagged_jets_by_pt", 1, 99);
//   kinVars.push_back(&mySumNonTaggedJetMass);

//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     myWLikeDijetMass81("mass", "closest_to", "WLike_dijet_mass",
//                        &(notMediumCSVJets.ptrToItems), "untagged_jets_by_pt", 1, 99,
//                        &(notMediumCSVJets.ptrToItems), "untagged_jets_by_pt", 1, 99,
//                        81);
//   kinVars.push_back(&myWLikeDijetMass81);

//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     myDeltaPhiJets_FromHiggs("deltaPhi", "min", "dPhi_jets_fromHiggs",
//                              &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99,
//                              &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99);
//   kinVars.push_back(&myDeltaPhiJets_FromHiggs);
  
//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     myDeltaRJets_FromHiggs("deltaR", "min", "dR_jets_fromHiggs",
//                            &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99,
//                            &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99);
//   kinVars.push_back(&myDeltaRJets_FromHiggs);
  
//   TwoObjectKinematic<BNmetCollection,BNleptonCollection>
//     myDeltaPhiMetLep1("deltaPhi", "min", "dPhi_met_lep1",
//                       &(met.ptrToItems), "met", 1, 1,
//                       &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1);
//   kinVars.push_back(&myDeltaPhiMetLep1);
  
//   TwoObjectKinematic<BNmetCollection,BNleptonCollection>
//     myDeltaPhiMetLep2("deltaPhi", "min", "dPhi_met_lep2",
//                       &(met.ptrToItems), "met", 1, 1,
//                       &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2);
//   kinVars.push_back(&myDeltaPhiMetLep2);

//   TwoObjectKinematic<BNmetCollection,BNjetCollection>
//     myMinDeltaPhiMetJet("deltaPhi", "min", "min_dPhi_metjet",
//                         &(met.ptrToItems), "met", 1, 99,
//                         &(jets.ptrToItems), "jets_by_pt", 1, 99);
//   kinVars.push_back(&myMinDeltaPhiMetJet);

//   TwoObjectKinematic<BNmetCollection,BNjetCollection>
//     myMaxDeltaPhiMetJet("deltaPhi", "max", "max_dPhi_metjet",
//                         &(met.ptrToItems), "met", 1, 99,
//                         &(jets.ptrToItems), "jets_by_pt", 1, 99);
//   kinVars.push_back(&myMaxDeltaPhiMetJet);
  
//   TwoObjectKinematic<BNmetCollection,BNjetCollection>
//     myMinDeltaPhiMetJet_fromHiggs("deltaPhi", "min", "min_dPhi_metjet_fromHiggs",
//                         &(met.ptrToItems), "met", 1, 99,
//                         &(jets_fromHiggs.ptrToItems), "jets_fromHiggs_by_pt", 1, 99);
//   kinVars.push_back(&myMinDeltaPhiMetJet_fromHiggs);

//   TwoObjectKinematic<BNmetCollection,BNjetCollection>
//     myMaxDeltaPhiMetJet_fromHiggs("deltaPhi", "max", "max_dPhi_metjet_fromHiggs",
//                         &(met.ptrToItems), "met", 1, 99,
//                         &(jets_fromHiggs.ptrToItems), "jets_by_pt", 1, 99);
//   kinVars.push_back(&myMaxDeltaPhiMetJet_fromHiggs);

//   ThreeObjectKinematic<BNleptonCollection, BNleptonCollection, BNmetCollection>
//     myMassMetLepLep("mass", "min", "mass_met_leplep",
//                     &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1,
//                     &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2,
//                     &(met.ptrToItems), "met", 1, 1);
//   kinVars.push_back(&myMassMetLepLep);
  
//   ThreeObjectKinematic<BNleptonCollection, BNleptonCollection, BNmetCollection>
//     myMTMetLepLep("MT", "min", "MT_met_leplep",
//                     &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1,
//                     &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2,
//                     &(met.ptrToItems), "met", 1, 1);
//   kinVars.push_back(&myMTMetLepLep);
  
//   ThreeObjectKinematic<BNleptonCollection, BNleptonCollection, BNmetCollection>
//     myDeltaRMetLepLep("deltaR", "min", "dR_met_leplep",
//                       &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1,
//                       &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2,
//                       &(met.ptrToItems), "met", 1, 1);
//   kinVars.push_back(&myDeltaRMetLepLep);
  
//   ThreeObjectKinematic<BNleptonCollection, BNleptonCollection, BNmetCollection>
//     myDeltaPhiMetLepLep("deltaPhi", "min", "dPhi_met_leplep",
//                         &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 1, 1,
//                         &(tightLooseLeptons.ptrToItems), "leptons_by_pt", 2, 2,
//                         &(met.ptrToItems), "met", 1, 1);
//   kinVars.push_back(&myDeltaPhiMetLepLep);
  
//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     myGenHiggsDijetMass("mass", "min", "genHiggs_dijet_mass",
//                         &(jets_fromHiggs.ptrToItems), "jets_by_pt", 1, 1,
//                         &(jets_fromHiggs.ptrToItems), "jets_by_pt", 2, 2);
//   kinVars.push_back(&myGenHiggsDijetMass);
  
//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     myHiggsLikeDijetMass("mass", "closest_to", "higgsLike_dijet_mass",
//                          &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                          &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                          115.0);
//   kinVars.push_back(&myHiggsLikeDijetMass);
  
//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     myHiggsLikeDijetMass2("mass", "second_closest_to", "higgsLike_dijet_mass2",
//                           &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                           &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                           115.0);
//   kinVars.push_back(&myHiggsLikeDijetMass2);

//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     myNumJetsFloat("eta", "num_within", "numJets_float",
//                    &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                    &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                    0.0, "", "", 5.0);
//   kinVars.push_back(&myNumJetsFloat);

//   TwoObjectKinematic<BNjetCollection,BNjetCollection>
//     myNumHiggsLikeDijet15("mass", "num_within", "numHiggsLike_dijet_15_float",
//                           &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                           &(jets.ptrToItems), "jets_by_pt", 1, 99,
//                           115.0, "", "", 15.0);
//   kinVars.push_back(&myNumHiggsLikeDijet15);
  
//   TwoJetVariables
//     myAvgBtagDiscBtags("CSV", "avg", "avg_btag_disc_btags",
//                        &(mediumCSVJets.ptrToItems), "medium_bjets_by_pt", 1, 99,
//                        &(mediumCSVJets.ptrToItems), "medium_bjets_by_pt", 1, 99);
//   kinVars.push_back(&myAvgBtagDiscBtags);
  
//   TwoJetVariables
//     myAvgBtagDiscNonBtags("CSV", "avg", "avg_btag_disc_non_btags",
//                           &(notMediumCSVJets.ptrToItems), "not_medium_bjets_by_pt", 1, 99,
//                           &(notMediumCSVJets.ptrToItems), "not_medium_bjets_by_pt", 1, 99);
//   kinVars.push_back(&myAvgBtagDiscNonBtags);

//   ////////// all leptons //////////
//   GenericCollectionMember<double, BNleptonCollection>
//     allLeptonPt(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems),
//                 "pt", "leptons_by_pt",  KinematicVariableConstants::FLOAT_INIT, 2);
//   kinVars.push_back(&allLeptonPt);
  
//   GenericCollectionMember<double, BNleptonCollection>
//     allLeptonEta(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems),
//                  "eta", "leptons_by_pt",  KinematicVariableConstants::FLOAT_INIT, 2);
//   kinVars.push_back(&allLeptonEta);
  
//   GenericCollectionMember<int, BNleptonCollection>
//     allLeptonTkCharge(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems),
//                       "tkCharge", "leptons_by_pt",  KinematicVariableConstants::INT_INIT, 2);
//   kinVars.push_back(&allLeptonTkCharge);

//   GenericCollectionMember<int, BNleptonCollection>
//     allLeptonGenMotherId(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems),
//                          "genMotherId", "leptons_by_pt",  KinematicVariableConstants::INT_INIT, 2);
//   kinVars.push_back(&allLeptonGenMotherId);

//   GenericCollectionMember<int, BNleptonCollection>
//     allLeptonGenGrandMotherId(Reflex::Type::ByName("BNlepton"), &(tightLooseLeptons.ptrToItems),
//                               "genGrandMother00Id", "leptons_by_pt",  KinematicVariableConstants::INT_INIT, 2);
//   kinVars.push_back(&allLeptonGenGrandMotherId);
  
  // NECESSARY TO FILL LEPTON VALUES - DO NOT COMMENT OUT //
  GenericCollectionMember<double, BNmuonCollection>
    allMuonPt(Reflex::Type::ByName("BNmuon"), &(tightLooseMuons.ptrToItems),
              "pt", "muons_by_pt",  KinematicVariableConstants::FLOAT_INIT, 2);
  kinVars.push_back(&allMuonPt);
  
  GenericCollectionMember<double, BNelectronCollection>
    allElectronPt(Reflex::Type::ByName("BNelectron"), &(tightLooseElectrons.ptrToItems),
                  "pt", "electrons_by_pt",  KinematicVariableConstants::FLOAT_INIT, 2);
  kinVars.push_back(&allElectronPt);
  
  ////////// all jets //////////
//   GenericCollectionMember<double, BNjetCollection>
//     allJetPt(Reflex::Type::ByName("BNjet"), &(jets.ptrToItems),
//              "pt", "jets_by_pt",  KinematicVariableConstants::FLOAT_INIT, 4);
//   kinVars.push_back(&allJetPt);

//   GenericCollectionMember<double, BNjetCollection>
//     allJetEta(Reflex::Type::ByName("BNjet"), &(jets.ptrToItems),
//               "eta", "jets_by_pt",  KinematicVariableConstants::FLOAT_INIT, 4);
//   kinVars.push_back(&allJetEta);

//   GenericCollectionMember<double, BNjetCollection>
//     allJetCSV(Reflex::Type::ByName("BNjet"),  &(jets.ptrToItems),
//               "btagCombinedSecVertex", "jets_by_pt",  KinematicVariableConstants::FLOAT_INIT, 4);
//   kinVars.push_back(&allJetCSV);

//   ////////// met //////////
//   GenericCollectionMember<double, BNmetCollection>
//     metPt(Reflex::Type::ByName("BNmet"),  &(met.ptrToItems),
//           "pt", "met",  KinematicVariableConstants::FLOAT_INIT, 1);
//   kinVars.push_back(&metPt);

  ////////// manual variables //////////
//   int TwoMuon = 0;
//   int TwoElectron = 0;
//   int MuonElectron = 0;
//   int PassTwoLepton = 0;
//   Char_t *dataset = (Char_t *)lepHelper.dataset.c_str();

//   int sampleNumber = (int)lepHelper.sampleNumber;
//   double weight_Xsec = (double)lepHelper.weight_Xsec;
//   int nGen = (int)lepHelper.nGen;
//   double Xsec = (double)lepHelper.Xsec;
//   summaryTree->Branch("sampleNumber", &sampleNumber);
//   summaryTree->Branch("weight_Xsec", &weight_Xsec);
//   summaryTree->Branch("nGen", &nGen);
//   summaryTree->Branch("Xsec", &Xsec);

//   summaryTree->Branch("TwoMuon", &TwoMuon);
//   summaryTree->Branch("TwoElectron", &TwoElectron);
//   summaryTree->Branch("MuonElectron", &MuonElectron);
//   summaryTree->Branch("PassTwoLepton", &PassTwoLepton);
//   summaryTree->Branch("dataset", (void*)dataset, "dataset/C");

//   int numExtraPartons = -99;
//   summaryTree->Branch("numExtraPartons", &numExtraPartons);

  bool ttPlusHFKeepEventBool = false;
  
  ////////// event info //////////
//   GenericCollectionMember<unsigned, BNeventCollection>
//     runNumber(Reflex::Type::ByName("BNevent"), &(events.ptrToItems),
//               "run", "eventInfo",  KinematicVariableConstants::UINT_INIT, 1);
//   kinVars.push_back(&runNumber);

//   GenericCollectionMember<unsigned, BNeventCollection>
//     lumiBlock(Reflex::Type::ByName("BNevent"), &(events.ptrToItems),
//               "lumi", "eventInfo",  KinematicVariableConstants::UINT_INIT, 1);
//   kinVars.push_back(&lumiBlock);
  
  // this is a long inside BNevent
  // just using keyword long won't work
  // needs to be Long64_t 
//   GenericCollectionMember<Long64_t, BNeventCollection>
//     eventNumber(Reflex::Type::ByName("BNevent"),  &(events.ptrToItems),
//                 "evt", "eventInfo",  KinematicVariableConstants::INT_INIT, 1);
//   kinVars.push_back(&eventNumber);

  ////////// variables from functions //////////
//   PassZmask myPassZmask(&myZmass, &myMHT, &metPt);
//   kinVars.push_back(&myPassZmask);
//   myPassZmask.setCut("PassZmask_mht");
//   cutVars.push_back(&myPassZmask);

//  FinalBDT_OS_2012 myFinalBDT_OS_2012(&myMinDrJets, &mySumPt, &myAvgBtagDiscBtags, &myAvgBtagDiscNonBtags,
//                                      &myHiggsLikeDijetMass, &myHiggsLikeDijetMass2, &myNumJetsFloat, &myNumHiggsLikeDijet15);
//  kinVars.push_back(&myFinalBDT_OS_2012);

  if (debug > 9) { cout << "Hooking variables to tree" << endl;}
  for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin();
       iVar != kinVars.end();
       iVar++) {

    (*iVar)->attachToTree (summaryTree);
  }

  int numEvents = 0;
  int numEventsFailCuts = 0;
  int numEventsPassCuts = 0;
  int printEvery = 1000;

  for (ev.toBegin(); !ev.atEnd(); ++ev){
    numEvents++;

    if ((numEvents > myConfig.maxEvents) && myConfig.maxEvents != -1) break;

    if (numEvents == 1 || numEvents % printEvery == 0 )
      cout << "Processing event.... " << numEvents << endl;

    if (debug > 9) cout << "---------->>>>>> Event " << numEvents << endl;


    /////////////////////////////////////////////////////////////
    //
    //    Initialize collections and apply object ids
    //
    //////////////////////////////////////////////////////////////   
    tightLoosePreselectedElectrons.initializeRawItemsSortedByPt(ev, "BNproducer","selectedPatElectronsPFlow");
    tightLoosePreselectedMuons.initializeRawItemsSortedByPt(ev, "BNproducer","selectedPatMuonsPFlow");
    
    tightLoosePreselectedElectrons.keepSelectedParticles(electronPreselectedID);
//     tightElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems);
//     tightElectrons.keepSelectedParticles(electronTightID);
    tightLooseElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems);
    tightLooseElectrons.keepSelectedParticles(electronLooseID);
//     looseElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems);
//     looseElectrons.keepSelectedDifference(electronLooseID, electronTightID);
//     preselectedElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems);
//     preselectedElectrons.keepSelectedDifference(electronPreselectedID, electronLooseID);
//     loosePreselectedElectrons.initializeRawItems(tightLoosePreselectedElectrons.rawItems);
//     loosePreselectedElectrons.addUnion({looseElectrons.items, preselectedElectrons.items});

    tightLoosePreselectedMuons.keepSelectedParticles(muonPreselectedID);
//     tightMuons.initializeRawItems(tightLoosePreselectedMuons.rawItems);
//     tightMuons.keepSelectedParticles(muonTightID);
//     looseMuons.initializeRawItems(tightLoosePreselectedMuons.rawItems);
//     looseMuons.keepSelectedDifference(muonLooseID, muonTightID);
//     preselectedMuons.initializeRawItems(tightLoosePreselectedMuons.rawItems);
//     preselectedMuons.keepSelectedDifference(muonPreselectedID, muonLooseID);
    tightLooseMuons.initializeRawItems(tightLoosePreselectedMuons.rawItems);
    tightLooseMuons.keepSelectedParticles(muonLooseID);

// // Require reset before first pushback to avoid keeping leptons from previous event
//     tightLeptons.resetAndPushBack(tightElectrons.items);
//     tightLeptons.pushBackAndSort(tightMuons.items);
//     looseLeptons.resetAndPushBack(looseElectrons.items);
//     looseLeptons.pushBackAndSort(looseMuons.items);
//     preselectedLeptons.resetAndPushBack(preselectedElectrons.items);
//     preselectedLeptons.pushBackAndSort(preselectedMuons.items);
//     tightLooseLeptons.resetAndPushBack(tightLooseElectrons.items);
//     tightLooseLeptons.pushBackAndSort(tightLooseMuons.items);
//     tightLoosePreselectedLeptons.resetAndPushBack(tightLoosePreselectedElectrons.items);
//     tightLoosePreselectedLeptons.pushBackAndSort(tightLoosePreselectedMuons.items);

//     tightTaus.initializeRawItemsSortedByPt(ev, "BNproducer","selectedPatTaus");
//     tightTaus.keepSelectedParticles(tauTightID);
//     tightLooseTaus.initializeRawItems(tightTaus.rawItems);
//     tightLooseTaus.keepSelectedParticles(tauTightID);
//     tightLoosePreselectedTaus.initializeRawItems(tightTaus.rawItems);
//     tightLoosePreselectedTaus.keepSelectedParticles(tauPreselectedID);

//     jets.initializeRawItemsSortedByPt(ev, "BNproducer","selectedPatJetsPFlow");
//     jets.cleanJets(tightLoosePreselectedLeptons.items);
//     jets.correctRawJets(jetSyst);
//     jets.keepSelectedJets(25.0, 2.4, jetID::jetLoose, '-');
//     jetsByCSV.initializeRawItemsSortedByCSV(jets.items);
//     looseCSVJets.initializeRawItems(jets.rawItems);
//     looseCSVJets.keepSelectedJets(25.0, 2.4, jetID::jetLoose, 'L');
//     mediumCSVJets.initializeRawItems(jets.rawItems);
//     mediumCSVJets.keepSelectedJets(25.0, 2.4, jetID::jetLoose, 'M');
//     notMediumCSVJets.initializeRawItems(beanHelper->GetDifference(jets.items, mediumCSVJets.items));

//     jets_30.initializeRawItems(jets.items);
//     jets_30.keepSelectedJets(30.0, 2.4, jetID::jetLoose, '-');
//     jets_fromHiggs.initializeRawItems(jets.items);
//     auto jetGenPartonMotherId = [] (BNjet j) { return (j.genPartonMotherId == 25); };
//     jets_fromHiggs.keepSelectedParticles(jetGenPartonMotherId);
//     jets_fromHiggs_30.initializeRawItems(jets_30.items);
//     jets_fromHiggs_30.keepSelectedParticles(jetGenPartonMotherId);

//     met.initializeRawItems(ev, "BNproducer","patMETsPFlow");
//     met.getCorrectedMet(jets);
//     events.initializeRawItems(ev, "BNproducer", "");
//     mcParticles.initializeRawItems(ev, "BNproducer", "MCstatus3");
//     primaryVertexes.initializeRawItems(ev, "BNproducer","offlinePrimaryVertices");
//     hltCollection.initializeRawItems(ev, "BNproducer", "HLT");

//     genHiggsParticles.initializeRawItems(mcParticles.rawItems);
//     auto higgsPDGID = [] (BNmcparticle p) { return (p.id == 25); };
//     genHiggsParticles.keepSelectedParticles(higgsPDGID);
//     genTopParticles.initializeRawItems(mcParticles.rawItems);
//     auto topPDGID = [] (BNmcparticle p) { return (p.id == 6); };
//     genTopParticles.keepSelectedParticles(topPDGID);
//     genAntiTopParticles.initializeRawItems(mcParticles.rawItems);
//     auto antitopPDGID = [] (BNmcparticle p) { return (p.id == -6); };


    // reset all the vars
    if (debug > 9) cout << "Resetting "  << endl;
    for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin();
         iVar != kinVars.end();
         iVar++) {

      (*iVar)->reset();
    }

    bool passAllCuts = true;

    if (debug > 9) cout << "Checking cuts "  << endl;

    for (vector<ArbitraryVariable*>::iterator iCut = cutVars.begin();
         iCut != cutVars.end();
         iCut++ ) {

      (*iCut)->evaluate();
      passAllCuts = passAllCuts && (*iCut)->passCut();

    }

    if (!passAllCuts) {
      numEventsFailCuts++;
      continue; //!!!!    Skip The event  ///////////////

    } else {
      numEventsPassCuts++;
    }

    // Now  evaluate the vars
    if (debug > 9) cout << "Evaluating vars "  << endl;

    for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin();
         iVar != kinVars.end();
         iVar++) {

      (*iVar)->evaluate();
    }

    if (debug > 9) {
      for (vector<ArbitraryVariable*>::iterator iVar = kinVars.begin();
           iVar != kinVars.end();
           iVar++) {

        (*iVar)->print();
        cout << endl;
      }
    }

    // Get manual variables
    //    LeptonVarsThisAnalysis(tightMuons.items, tightLooseMuons.items, tightElectrons.items, tightLooseElectrons.items,
    //                           TwoMuon, TwoElectron, MuonElectron, PassTwoLepton);

    //    getNumExtraPartons(beanHelper, mcParticles.items, numExtraPartons);
    //    if (myConfig.sampleName.find("_0p") != std::string::npos) { //0 parton samples
      //Cut to require 0 partons
//       if (numExtraPartons != 0) {
//         numEventsFailCuts++;
//         numEventsPassCuts--;
//         continue; //Don't go on to fill tree with this event
//       }
//    }

    if (myConfig.sampleName == "ttbar" || myConfig.sampleName.find("ttbar_") != std::string::npos ) { //ttbar samples
      //ttPlusHFKeepEventFunction(beanHelper, mcParticles.items, jets.items, ttPlusHFKeepEventBool);
      if (!ttPlusHFKeepEventBool) {
        numEventsFailCuts++;
        numEventsPassCuts--;
        continue; //Don't go on to fill tree with this event
      }
    }
    
    // Fill the trees
    if (debug > 9) cout << "Filling tree "  << endl;
    summaryTree->Fill();
    if (debug > 9) cout << "Done with event  " << numEvents  << endl;
  }// end for each event

  cout << "Num Events processed " << numEvents << endl
       << "Passed cuts " << numEventsPassCuts << endl
       << "Failed cuts " << numEventsFailCuts << endl ;

  outputFile->Write();
  outputFile->Close();
}
Example #25
0
void MidiDevice::handleStop()
{
  // If the device is not in use by a port, don't bother it.
  if(_port == -1)
    return;
    
  MidiPort* mp = &MusEGlobal::midiPorts[_port];
  
  //---------------------------------------------------
  //    send midi stop
  //---------------------------------------------------
  
  // Don't send if external sync is on. The master, and our sync routing system will take care of that.   
  if(!MusEGlobal::extSyncFlag.value())
  {
    // Shall we check open flags? DELETETHIS 4?
    //if(!(dev->rwFlags() & 0x1) || !(dev->openFlags() & 1))
    //if(!(dev->openFlags() & 1))
    //  return;
          
    MidiSyncInfo& si = mp->syncInfo();
    if(si.MMCOut())
      mp->sendMMCStop();
    
    if(si.MRTOut()) 
    {
      mp->sendStop();
      //DELETETHIS 5?
      // Added check of option send continue not start. Hmm, is this required? Seems to make other devices unhappy.
      // (Could try now that this is in MidiDevice.)
      //if(!si.sendContNotStart())
      //  mp->sendSongpos(MusEGlobal::audio->tickPos() * 4 / MusEGlobal::config.division);
    }
  }  

  //---------------------------------------------------
  //    Clear all notes and flush out any stuck notes
  //     which were put directly to the device
  //---------------------------------------------------

  setStopFlag(true);
  for(iMPEvent i = _stuckNotes.begin(); i != _stuckNotes.end(); ++i) 
  {
    MidiPlayEvent ev(*i);
    ev.setTime(0);  // Immediate processing. TODO Use curFrame?
    //ev.setTime(MusEGlobal::audio->midiQueueTimeStamp(ev.time()));
        putEvent(ev, MidiDevice::NotLate);
  }
  _stuckNotes.clear();
  
  //------------------------------------------------------------
  //    Flush out any track-related playback stuck notes (NOT 'live' notes)
  //     which were not put directly to the device
  //------------------------------------------------------------
  
  for(ciMidiTrack imt = MusEGlobal::song->midis()->begin(); imt != MusEGlobal::song->midis()->end(); ++imt)
  {
    MPEventList& mel = (*imt)->stuckNotes;
    for(iMPEvent i = mel.begin(), i_next = i; i != mel.end(); i = i_next) 
    {
      ++i_next;

      if((*i).port() != _port)
        continue;
      MidiPlayEvent ev(*i);
      ev.setTime(0);  // Immediate processing. TODO Use curFrame?
      //ev.setTime(MusEGlobal::audio->midiQueueTimeStamp(ev.time()));
      putEvent(ev, MidiDevice::NotLate);
            
      mel.erase(i);
    }
  }
  
  //---------------------------------------------------
  //    reset sustain
  //---------------------------------------------------
  
  for(int ch = 0; ch < MusECore::MUSE_MIDI_CHANNELS; ++ch) 
  {
    if(mp->hwCtrlState(ch, CTRL_SUSTAIN) == 127) 
    {
      MidiPlayEvent ev(0, _port, ch, ME_CONTROLLER, CTRL_SUSTAIN, 0); // Immediate processing. TODO Use curFrame?
      //ev.setTime(MusEGlobal::audio->midiQueueTimeStamp(ev.time()));
      putEvent(ev, MidiDevice::NotLate);
    }
  }
}
Example #26
0
LRESULT CALLBACK Widget::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	MsgProcResult result;
	switch(msg)
	{
	case WM_PAINT:
		{
			PAINTSTRUCT ps;
			HDC hDC;
			if(wParam == 0) hDC = BeginPaint(hWnd, &ps);
			else hDC = (HDC)wParam;
			Gdiplus::Graphics g(hDC);
			OnPaint(&g, ps.rcPaint);
			if(wParam == 0) EndPaint(hWnd, &ps);
		} break;


	case WM_LBUTTONDOWN:
	case WM_RBUTTONDOWN:
	case WM_MBUTTONDOWN:
	{
		mIsMouseDown = true;
		SetCapture(hWnd);
		mMouseLastPos = POINT{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
		MouseEvent ev(this, mMouseLastPos, 1, wParam,
					  msg == WM_LBUTTONDOWN ? MouseButton::Left :
					  msg == WM_RBUTTONDOWN ? MouseButton::Right :
					  msg == WM_MBUTTONDOWN ? MouseButton::Middle :
					  MouseButton::None);
		SignalMouseDown.emit(ev);
		OnMouseDown(ev);
	} break;

	case WM_LBUTTONUP:
	case WM_RBUTTONUP:
	case WM_MBUTTONUP:
	{
		mIsMouseDown = false;
		ReleaseCapture();
		mMouseLastPos = POINT{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
		MouseEvent ev(this, mMouseLastPos, 1, wParam,
					  msg == WM_LBUTTONUP ? MouseButton::Left :
					  msg == WM_RBUTTONUP ? MouseButton::Right :
					  msg == WM_MBUTTONUP ? MouseButton::Middle :
					  MouseButton::None);
		SignalMouseUp.emit(ev);
		OnMouseUp(ev);

		if(!mHasDragged)
		{
			SignalMouseClick.emit(ev);
			OnMouseClick(ev);
		}
		else
			mHasDragged = false;
	} break;

	case WM_LBUTTONDBLCLK:
	case WM_MBUTTONDBLCLK:
	case WM_RBUTTONDBLCLK:
	{
		MouseEvent ev(this, POINT{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)}, 2, wParam,
					  msg == WM_LBUTTONDBLCLK ? MouseButton::Left :
					  msg == WM_MBUTTONDBLCLK ? MouseButton::Right :
					  msg == WM_RBUTTONDBLCLK ? MouseButton::Middle :
					  MouseButton::None);
		SignalMouseDoubleClick.emit(ev);
		OnMouseDoubleClick(ev);
	} break;

	case WM_MOUSEMOVE:
	{
		POINT mouseNewPos = POINT{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
		MouseEvent ev(this, mouseNewPos, 0, wParam, MouseButton::None, mMouseLastPos);
		mMouseLastPos = mouseNewPos;
		if(mIsMouseDown)
		{
			mHasDragged = true;
			SignalMouseDrag.emit(ev);
			OnMouseDrag(ev);
		}
		else
		{
			SignalMouseMove.emit(ev);
			OnMouseMove(ev);
		}
	} break;

	case WM_MOUSEWHEEL:
	{
		POINT pt = POINT{GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
		ScreenToClient(mhWnd, &pt);
		MouseEvent ev(this, pt, 0, GET_KEYSTATE_WPARAM(wParam), MouseButton::None, mMouseLastPos, GET_WHEEL_DELTA_WPARAM(wParam)/WHEEL_DELTA);
		SignalMouseWheel.emit(ev);
		OnMouseWheel(ev);
	} break;

	case WM_SIZE:
	{
		int width = LOWORD(lParam);
		int height = HIWORD(lParam);
		SignalResize.emit(width, height);
		if(mLayout)
			mLayout->Apply(this);
		OnResize(width, height);
	} break;

	case WM_COMMAND:
	{
		HWND hCtrl = reinterpret_cast<HWND>(lParam);
		if(hCtrl != nullptr)
		{
			Widget* child = Widget::FromHandle(hCtrl);
			if(child != nullptr)				
				child->OnCommand(HIWORD(wParam));
		}
	} break;

	case WM_NOTIFY:
	{
		LPNMHDR lpnmhdr = reinterpret_cast<LPNMHDR>(lParam);
		Widget* child = Widget::FromHandle(lpnmhdr->hwndFrom);
		if(child != nullptr)
			result = child->OnNotify(lpnmhdr);
	} break;

	}

	if(result.ReturnDefault())
		return CallDefaultProc(hWnd, msg, wParam, lParam);
	else
		return result.Value();
}
Example #27
0
// return a score for the current board position.
int SearchMv::evaluate(Board& board)
{
	Eval ev(&board);
	return ev.evalBoard(&board);
}
Example #28
0
void MidiDevice::handleSeek()
{
  // If the device is not in use by a port, don't bother it.
  if(_port == -1)
    return;
  
  MidiPort* mp = &MusEGlobal::midiPorts[_port];
  MidiInstrument* instr = mp->instrument();
  MidiCtrlValListList* cll = mp->controller();
  unsigned pos = MusEGlobal::audio->tickPos();
  
  //---------------------------------------------------
  //    Send STOP 
  //---------------------------------------------------
    
  // Don't send if external sync is on. The master, and our sync routing system will take care of that.  
  if(!MusEGlobal::extSyncFlag.value())
  {
    if(mp->syncInfo().MRTOut())
    {
      // Shall we check for device write open flag to see if it's ok to send?...
      //if(!(rwFlags() & 0x1) || !(openFlags() & 1))
      //if(!(openFlags() & 1))
      //  continue;
      mp->sendStop();
    }    
  }

  //---------------------------------------------------
  //    If playing, clear all notes and flush out any
  //     stuck notes which were put directly to the device
  //---------------------------------------------------
  
  if(MusEGlobal::audio->isPlaying()) 
  {
    _playEvents.clear();
    for(iMPEvent i = _stuckNotes.begin(); i != _stuckNotes.end(); ++i) 
    {
      MidiPlayEvent ev(*i);
      ev.setTime(0);
      putEvent(ev);  // For immediate playback try putEvent, putMidiEvent, or sendEvent (for the optimizations).
    }
    _stuckNotes.clear();
  }
  
  //---------------------------------------------------
  //    Send new controller values
  //---------------------------------------------------
    
  // Find channels on this port used in the song...
  bool usedChans[MIDI_CHANNELS];
  int usedChanCount = 0;
  for(int i = 0; i < MIDI_CHANNELS; ++i)
    usedChans[i] = false;
  if(MusEGlobal::song->click() && MusEGlobal::clickPort == _port)
  {
    usedChans[MusEGlobal::clickChan] = true;
    ++usedChanCount;
  }
  bool drum_found = false;
  for(ciMidiTrack imt = MusEGlobal::song->midis()->begin(); imt != MusEGlobal::song->midis()->end(); ++imt)
  {
    //------------------------------------------------------------
    //    While we are at it, flush out any track-related playback stuck notes
    //     (NOT 'live' notes) which were not put directly to the device
    //------------------------------------------------------------
    MPEventList& mel = (*imt)->stuckNotes;
    for(iMPEvent i = mel.begin(), i_next = i; i != mel.end(); i = i_next)
    {
      ++i_next;

      if((*i).port() != _port)
        continue;
      MidiPlayEvent ev(*i);
      ev.setTime(0);
      putEvent(ev); // For immediate playback try putEvent, putMidiEvent, or sendEvent (for the optimizations).
      mel.erase(i);
    }
    
    if((*imt)->type() == MusECore::Track::DRUM)
    {
      if(!drum_found)
      {
        drum_found = true; 
        for(int i = 0; i < DRUM_MAPSIZE; ++i)
        {
          // Default to track port if -1 and track channel if -1.
          int mport = MusEGlobal::drumMap[i].port;
          if(mport == -1)
            mport = (*imt)->outPort();
          int mchan = MusEGlobal::drumMap[i].channel;
          if(mchan == -1)
            mchan = (*imt)->outChannel();
          if(mport != _port || usedChans[mchan])
            continue;
          usedChans[mchan] = true;
          ++usedChanCount;
          if(usedChanCount >= MIDI_CHANNELS)
            break;  // All are used, done searching.
        }
      }
    }
    else
    {
      if((*imt)->outPort() != _port || usedChans[(*imt)->outChannel()])
        continue;
      usedChans[(*imt)->outChannel()] = true;
      ++usedChanCount;
    }

    if(usedChanCount >= MIDI_CHANNELS)
      break;    // All are used. Done searching.
  }   
  
  for(iMidiCtrlValList ivl = cll->begin(); ivl != cll->end(); ++ivl) 
  {
    MidiCtrlValList* vl = ivl->second;
    int chan = ivl->first >> 24;
    if(!usedChans[chan])  // Channel not used in song?
      continue;
    int ctlnum = vl->num();

    // Find the first non-muted value at the given tick...
    bool values_found = false;
    bool found_value = false;
    
    iMidiCtrlVal imcv = vl->lower_bound(pos);
    if(imcv != vl->end() && imcv->first == (int)pos)
    {
      for( ; imcv != vl->end() && imcv->first == (int)pos; ++imcv)
      {
        const Part* p = imcv->second.part;
        if(!p)
          continue;
        // Ignore values that are outside of the part.
        if(pos < p->tick() || pos >= (p->tick() + p->lenTick()))
          continue;
        values_found = true;
        // Ignore if part or track is muted or off.
        if(p->mute())
          continue;
        const Track* track = p->track();
        if(track && (track->isMute() || track->off()))
          continue;
        found_value = true;
        break;
      }
    }
    else
    {
      while(imcv != vl->begin())
      {
        --imcv;
        const Part* p = imcv->second.part;
        if(!p)
          continue;
        // Ignore values that are outside of the part.
        unsigned t = imcv->first;
        if(t < p->tick() || t >= (p->tick() + p->lenTick()))
          continue;
        values_found = true;
        // Ignore if part or track is muted or off.
        if(p->mute())
          continue;
        const Track* track = p->track();
        if(track && (track->isMute() || track->off()))
          continue;
        found_value = true;
        break;
      }
    }

    if(found_value)
    {
      // Don't bother sending any sustain values if not playing. Just set the hw state.
      if(ctlnum == CTRL_SUSTAIN && !MusEGlobal::audio->isPlaying())
        mp->setHwCtrlState(chan, CTRL_SUSTAIN, imcv->second.val);
      else
        // Use sendEvent to get the optimizations and limiting. But force if there's a value at this exact position.
        // NOTE: Why again was this forced? There was a reason. Think it was RJ in response to bug rep, then I modded.
        // A reason not to force: If a straight line is drawn on graph, multiple identical events are stored
        //  (which must be allowed). So seeking through them here sends them all redundantly, not good. // REMOVE Tim.
        mp->sendEvent(MidiPlayEvent(0, _port, chan, ME_CONTROLLER, ctlnum, imcv->second.val), false); //, imcv->first == pos);
        //mp->sendEvent(MidiPlayEvent(0, _port, chan, ME_CONTROLLER, ctlnum, imcv->second.val), pos == 0 || imcv->first == pos);
    }

    // Either no value was found, or they were outside parts, or pos is in the unknown area before the first value.
    // Send instrument default initial values.  NOT for syntis. Use midiState and/or initParams for that. 
    //if((imcv == vl->end() || !done) && !MusEGlobal::song->record() && instr && !isSynti()) 
    // Hmm, without refinement we can only do this at position 0, due to possible 'skipped' values outside parts, above.
    if(!values_found && MusEGlobal::config.midiSendCtlDefaults && !MusEGlobal::song->record() && pos == 0 && instr && !isSynti())
    {
      MidiControllerList* mcl = instr->controller();
      ciMidiController imc = mcl->find(vl->num());
      if(imc != mcl->end())
      {
        MidiController* mc = imc->second;
        if(mc->initVal() != CTRL_VAL_UNKNOWN)
          // Use sendEvent to get the optimizations and limiting. No force sending. Note the addition of bias.
          mp->sendEvent(MidiPlayEvent(0, _port, chan, ME_CONTROLLER, ctlnum, mc->initVal() + mc->bias()), false);
      }
    }
  }
  
  //---------------------------------------------------
  //    reset sustain
  //---------------------------------------------------
  
  for(int ch = 0; ch < MIDI_CHANNELS; ++ch) 
  {
    if(mp->hwCtrlState(ch, CTRL_SUSTAIN) == 127) 
    {
      const MidiPlayEvent ev(0, _port, ch, ME_CONTROLLER, CTRL_SUSTAIN, 0);
      putEvent(ev);
    }
  }
  
  //---------------------------------------------------
  //    Send STOP and "set song position pointer"
  //---------------------------------------------------
    
  // Don't send if external sync is on. The master, and our sync routing system will take care of that.  
  if(!MusEGlobal::extSyncFlag.value())
  {
    if(mp->syncInfo().MRTOut())
    {
      //mp->sendStop();   // Moved above
      int beat = (pos * 4) / MusEGlobal::config.division;
      mp->sendSongpos(beat);
    }    
  }
}
Example #29
0
int main(int argc, char **argv) {

	Renderer* r = NULL;
	try {
		r = new Renderer(800, 600);
	
		EventQueue ev(r);
	
		CharacterManager cm;
		r->SetCharManager(&cm);

		Player player = Player(10, 10, "Dann Von Veigar");
		player.SetEventQueue(&ev);

		Item it = Item("Insígnia do MC Bin Laden", "insignia do mestre Bin Laden", 3000);
		player.AddItem(&it);

		Sprite s = Sprite("..\\characters\\dann.png", 1.5f, 0);
		player.SetSprite(&s);

		Asura asu = Asura{ 0,0 };
		Akhbran ahk = Akhbran{ 0,0 };

		CharFactory* cf = new CharFactory(&cm);

		Tree t = Tree(20, 20);
		Sprite stree = Sprite("..\\characters\\arvore1.png", 1, 60, 80);
		t.SetSprite(&stree);

		cf->RegisterCharacter(t.GetTypeID(), &t);


		cm.AddCharacter(&player);
		cm.SetPlayer(&player);

		
		/*
		cm.AddCharacter(cf->PutCharacter(t.GetTypeID(), 3, 8));
		cm.AddCharacter(cf->PutCharacter(t.GetTypeID(), 6, 11));
		cm.AddCharacter(cf->PutCharacter(t.GetTypeID(), 9, 20));
		cm.AddCharacter(cf->PutCharacter(t.GetTypeID(), 12, 25));
		cm.AddCharacter(cf->PutCharacter(t.GetTypeID(), 15, 20));
		cm.AddCharacter(cf->PutCharacter(t.GetTypeID(), 18, 11));
		cm.AddCharacter(cf->PutCharacter(t.GetTypeID(), 21, 8));
		cm.AddCharacter(cf->PutCharacter(t.GetTypeID(), 24, 11));
		cm.AddCharacter(cf->PutCharacter(t.GetTypeID(), 27, 20));
		*/

		cm.AddCharacter(&asu);
		cm.AddCharacter(&ahk);

		Map* m;
		Map::LoadTiles();

		MapOpener mpop;
		m = mpop.Open("..\\maps\\map2.map");		

		if (!m) {
			char strmaperr[32];
			sprintf_s(strmaperr, 32, "Erro ao abrir o mapa!");
			throw std::runtime_error(strmaperr);
		}


		int px, py;
		m->GetInitialPlayerPos(px, py);

		float fx = px, fy = py;
		player.SetPosition(fx, fy);


		std::vector<CharacterData>* chd = m->GetCharData();

		if (chd->size() > 0) {
			for (auto i = chd->begin(); i != chd->end(); i++) {
				cm.AddCharacter(cf->PutCharacter(i->Type, i->XPos, i->YPos));
			}

		}

		r->SetMap(m);
		cm.SetMap(m);

		HUD* hud = new HUD(&player);
		r->SetHUD(hud);

	

		bool render = true;

		double fps = (1/60), start_time, end_time;

		float start_animations = al_get_time();
		float start_events = al_get_time();

		float playerdx = 0, playerdy = 0;

		start_time = al_get_time();

		while (render) {
			
			//Run events in 15fps.
			float end_events = al_get_time();
			if ((end_events - start_events) >= 1/15.0f){
				cm.DoAllEvents();
				start_events - end_events;
			}

			//Processa eventos
			if (!ev.CheckEvents()) {
				render = false;
			}


			player.Control(m);
			Event e;

			if (ev.PopEvent(e)) {

				switch (e.keycode) {

				case ALLEGRO_KEY_I:

					if (e.keyletter != 'i') continue;

					//Enumera os itens no inventário do player.
					std::vector<Item*>* list;
					player.GetAllItems(&list);

					std::stringstream line;

					for (auto i = list->begin();
					i != list->end();
						i++) {
						std::string name;
						(*i)->GetName(name);
						line << (*i)->GetID() << " - " << name << " - " << (*i)->GetValue() << " money" << std::endl;
					
					}

					MessageBoxA(al_get_win_window_handle(r->GetDisplay()), line.str().c_str(), "Inventário", 0);

					break;


				}

				
			}

			float end_animations = al_get_time();
			/* Run animations in 5 fps by default. */
			if ((end_animations - start_animations) >= 1/5.0f) {
				player.Andar(playerdx, playerdy);
				asu.Andar(playerdx, playerdy);
				ahk.Andar(playerdx, playerdy);
				playerdx = 0;
				playerdy = 0;
				start_animations = end_animations;

			}

			cm.DoAllEvents();
			
			//Os renderiza
			r->Render();


			end_time = al_get_time();

			if ((end_time - start_time) < fps) {
				double delta = (end_time - start_time);
				Sleep((fps - delta) * 1000);
				
			}
			//printf("\r%.5f ms", end_time - start_time);
			
			start_time = al_get_time();

			frames++;
		}


	}
	catch (std::runtime_error& e) {
		if (r)
			MessageBoxA(r->GetDisplay() ? al_get_win_window_handle(r->GetDisplay()) : NULL,
				e.what(), "Dois Demônios - Erro", MB_ICONERROR);
		else
			MessageBoxA(NULL, e.what(), "Dois Demônios - Erro", MB_ICONERROR);
		return -1;
	}

	delete r;
	return 0;
}
Example #30
0
    static void gtk_collapsiblepane_expanded_callback (GObject    *object,
            GParamSpec *param_spec,
            wxCollapsiblePane *p)
    {
        // NB: unlike for the "activate" signal, when this callback is called, if
        //     we try to query the "collapsed" status through p->IsCollapsed(), we
        //     get the right value. I.e. here p->IsCollapsed() will return false if
        //     this callback has been called at the end of a collapsed->expanded
        //     transition and viceversa. Inside the "activate" signal callback
        //     p->IsCollapsed() would return the wrong value!

        wxSize sz;
        if ( p->IsExpanded() )
        {
            // NB: we cannot use the p->GetBestSize() or p->GetMinSize() functions
            //     here as they would return the size for the collapsed expander
            //     even if the collapsed->expanded transition has already been
            //     completed; we solve this problem doing:

            sz = p->m_szCollapsed;

            wxSize panesz = p->GetPane()->GetBestSize();
            sz.x = wxMax(sz.x, panesz.x);
            sz.y += gtk_expander_get_spacing(GTK_EXPANDER(p->m_widget)) + panesz.y;
        }
        else // collapsed
        {
            // same problem described above: using p->Get[Best|Min]Size() here we
            // would get the size of the control when it is expanded even if the
            // expanded->collapsed transition should be complete now...
            // So, we use the size cached at control-creation time...
            sz = p->m_szCollapsed;
        }

        // VERY IMPORTANT:
        // just calling
        //          p->OnStateChange(sz);
        // here would work work BUT:
        //     1) in the expanded->collapsed transition it provokes a lot of flickering
        //     2) in the collapsed->expanded transition using the "Change status" wxButton
        //        in samples/collpane application some strange warnings would be generated
        //        by the "clearlooks" theme, if that's your theme.
        //
        // So we prefer to use some GTK+ native optimized calls, which prevent too many resize
        // calculations to happen. Note that the following code has been very carefully designed
        // and tested - be VERY careful when changing it!

        // 1) need to update our size hints
        // NB: this function call won't actually do any long operation
        //     (redraw/relayouting/resizing) so that it's flicker-free
        p->SetMinSize(sz);

        if (p->HasFlag(wxCP_NO_TLW_RESIZE))
        {
            // fire an event
            wxCollapsiblePaneEvent ev(p, p->GetId(), p->IsCollapsed());
            p->GetEventHandler()->ProcessEvent(ev);

            // the user asked to explicitely handle the resizing itself...
            return;
        }

        wxTopLevelWindow *
        top = wxDynamicCast(wxGetTopLevelParent(p), wxTopLevelWindow);
        if ( top && top->GetSizer() )
        {
            // 2) recalculate minimal size of the top window
            wxSize sz = top->GetSizer()->CalcMin();

            if (top->m_mainWidget)
            {
                // 3) MAGIC HACK: if you ever used GtkExpander in a GTK+ program you know
                //    that this magic call is required to make it possible to shrink the
                //    top level window in the expanded->collapsed transition.
                //    This may be sometimes undesired but *is* necessary and if you look
                //    carefully, all GTK+ programs using GtkExpander perform this trick
                //    (e.g. the standard "open file" dialog of GTK+>=2.4 is not resizeable
                //     when the expander is collapsed!)
                gtk_window_set_resizable (GTK_WINDOW (top->m_widget), p->IsExpanded());

                // 4) set size hints: note that this code has been taken and adapted
                //    from src/gtk/toplevel.cpp
                GdkGeometry geom;

                geom.min_width = sz.x;
                geom.min_height = sz.y;

                gtk_window_set_geometry_hints( GTK_WINDOW(top->m_widget),
                                               (GtkWidget*) NULL,
                                               &geom,
                                               GDK_HINT_MIN_SIZE );

                // 5) set size: also this code has been adapted from src/gtk/toplevel.cpp
                //    to do the size changes immediately and not delaying them in the idle
                //    time
                top->m_width = sz.x;
                top->m_height = sz.y;

                int client_x = top->m_miniEdge;
                int client_y = top->m_miniEdge + top->m_miniTitle;
                int client_w = top->m_width - 2*top->m_miniEdge;
                int client_h = top->m_height - 2*top->m_miniEdge - top->m_miniTitle;
                if (client_w < 0)
                    client_w = 0;
                if (client_h < 0)
                    client_h = 0;

                gtk_pizza_set_size( GTK_PIZZA(top->m_mainWidget),
                                    top->m_wxwindow,
                                    client_x, client_y, client_w, client_h );

                gtk_widget_set_size_request( top->m_wxwindow, sz.x, sz.y );

            }
        }

        if ( p->m_bIgnoreNextChange )
        {
            // change generated programmatically - do not send an event!
            p->m_bIgnoreNextChange = false;
            return;
        }

        // fire an event
        wxCollapsiblePaneEvent ev(p, p->GetId(), p->IsCollapsed());
        p->GetEventHandler()->ProcessEvent(ev);
    }