<commit_before>/***************************************************************************
    Modified by himani.bhatt@cern.ch  - last modified on 30/04/2018

   priyanka.sett@cern.ch - last modified on 27/10/2016

  for L* in pp 13 TeV analysis

// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
//  1) flag to know if running on MC or data
//  2) path where all configs are stored
// ---
// Returns:
//  kTRUE  --> initialization successful
//  kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
enum pairYCutSet { kPairDefault=0,
		   kCentral //=1
                 };
enum eventCutSet { kDefaultVtx = 0,
		   kDefaultVtx9, //=1
		   kDefaultVtx8, //=2
		   kDefaultVtx12, //=3
		   kDefaultVtx11,  //=4
		   kNoPileUpCut, //=5
		   kNoEvtSel, //=6   //No event selection, only INEL events
		   kSpecial2,//=7   // No Vz cut on vtx, f_vtx = kSpecial2/default_data
		   kSpecial3 //= 8  // No event selection, INEL events with Vz cut on vtx  kSpecial3/default_MC = f_SL
};

enum eventMixConfig { kDisabled = -1,
		      k5Evts5Cent, //=0 //5 events, Dvz = 1cm, DC = 5
		      kMixDefault, //=1 //10 events, Dvz = 1cm, DC = 10
		      k5Evts, //=2 //5 events, Dvz = 1cm, DC = 10
		      k5Cent  //=3 //10 events, Dvz = 1cm, DC = 5

};

AliRsnMiniAnalysisTask * AddTaskLstar13TeVpp_II
(
 Bool_t      isMC = kFALSE,
 Bool_t      isPP = kTRUE,
 Int_t       aodFilterBit = 5,
 Int_t       pairCutSetID=0,
 Int_t       evtCutSetID = 0,
 Int_t       mixingConfigID = 0,
 Int_t       MultBins = 0,// default for V0_M and MultBins = 2 for RefMult0_8
 Int_t       customQualityCutsID=1, // for default
 Float_t     nsigmaPr = 2.0,
 Float_t     nsigmaKa = 2.0,
 Bool_t      enableMonitor = kTRUE,
 Bool_t      IsMcTrueOnly = kFALSE,
 TString     outNameSuffix = "Default"
 )

{

  AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPrCandidate = AliRsnCutSetDaughterParticle::kTPCTOFpidLstar13ppTeV;
  AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate = AliRsnCutSetDaughterParticle::kTPCTOFpidLstar13ppTeV;

  Int_t       signedPdg = 3124;
  TString     monitorOpt = "NoSIGN";  //Flag for AddMonitorOutput.C e.g."NoSIGN"
  Bool_t      useCrossedRows = kTRUE;
  const char *yaxisVar = "";  //yaxisVar = "PtDaughter_PDaughter_cent"
  Bool_t      useMixLS = 0;
  //-------------------------------------------
  // event cuts
  //-------------------------------------------

  UInt_t      triggerMask = AliVEvent::kINT7;
  if(evtCutSetID>=100){
    triggerMask=AliVEvent::kHighMultV0;
    evtCutSetID=evtCutSetID%100;
  }

  Bool_t      rejectPileUp=kTRUE;
  if(!isPP || isMC || MultBins) rejectPileUp=kFALSE;

  Double_t  vtxZcut = 10.0;//default cut on vtx z

  if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx11) vtxZcut=11.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx9) vtxZcut=9.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
  if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;
  if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;//off

  //-------------------------------------------
  //mixing settings
  //-------------------------------------------
  Int_t       nmix=10;
  Float_t     maxDiffVzMix=1.;
  Float_t     maxDiffMultMix=10.;

  if(mixingConfigID==eventMixConfig::kMixDefault) nmix=10;
  if(mixingConfigID==eventMixConfig::k5Evts) nmix=5;
  if(mixingConfigID==eventMixConfig::k5Cent) maxDiffMultMix=5;
  if(mixingConfigID==eventMixConfig::k5Evts5Cent) { maxDiffMultMix=5; nmix = 5;}

//-------------------------------------------
  //pair cuts
  //-------------------------------------------
  Double_t    minYlab=-0.5;
  Double_t    maxYlab= 0.5;

  if(pairCutSetID==pairYCutSet::kCentral){//|y_cm|<0.3
    minYlab=-0.3; maxYlab=0.3;
  }

  //
  // -- INITIALIZATION ----------------------------------------------------------------------------
  // retrieve analysis manager
  //

  TString outputFileName = Form("%s", AliAnalysisManager::GetCommonFileName());
  // Objects name

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddAnalysisTaskTPCLStarSyst", "No analysis manager to connect to.");
    return NULL;
  }

  // create the task and configure
  TString taskName = outNameSuffix.Data();
  AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);

  task->UseESDTriggerMask(triggerMask);  // for ESD
  // task->SelectCollisionCandidates(triggerMask);  // Priyanka used for AODs

  if(isPP){
    if(MultBins==1) task->UseMultiplicity("AliMultSelection_V0M");
    else if(MultBins==2) task->UseMultiplicity("AliMultSelection_RefMult08");
    else task->UseMultiplicity("QUALITY");
  }else task->UseCentrality("V0M");

  // set event mixing options
  task->UseContinuousMix();
  //task->UseBinnedMix();
  task->SetNMix(nmix);
  task->SetMaxDiffVz(maxDiffVzMix);
  task->SetMaxDiffMult(maxDiffMultMix);
  //if (!isPP) task->SetMaxDiffAngle(maxDiffAngleMixDeg*TMath::DegToRad()); //set angle diff in rad
  ::Info("AddAnalysisTasLStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n ", nmix, maxDiffVzMix, maxDiffMultMix));

  mgr->AddTask(task);

  //
  // -- EVENT CUTS (same for all configs) ---------------------------------------------------------
  //
  // cut on primary vertex:
  // - 2nd argument --> |Vz| range
  // - 3rd argument --> minimum required number of contributors
  // - 4th argument --> tells if TPC stand-alone vertexes must be accepted

  // vertex cuts

  Bool_t rejectPileUp=kTRUE;
  if (!isPP && !isMC) rejectPileUp=kFALSE;
  AliRsnCutPrimaryVertex* cutVertex=0;
  if(evtCutSetID!=eventCutSet::kNoEvtSel &&  (MultBins == 0 || fabs(vtxZcut-10.)>1.e-10))
    { // passes the vertex quality cut
      cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);
      if(MultBins == 0 && evtCutSetID!=eventCutSet::kSpecial3){
	cutVertex->SetCheckZResolutionSPD();
	cutVertex->SetCheckDispersionSPD();
	cutVertex->SetCheckZDifferenceSPDTrack();
      }
      if(evtCutSetID==eventCutSet::kSpecial3) cutVertex->SetCheckGeneratedVertexZ();  // only Vz cut on vtx for INEL events
    }

  // other event selection cuts
  AliRsnCutEventUtils* cutEventUtils=0;
  if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3)
    {
      cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
      if(MultBins == 0){
	cutEventUtils->SetCheckIncompleteDAQ();
	cutEventUtils->SetCheckSPDClusterVsTrackletBG();
      }else{
	cutEventUtils->SetRemovePileUppA2013(kFALSE);
	cutEventUtils->SetCheckAcceptedMultSelection();
      }
    }

  // set the check for pileup
  if(isPP && (!isMC) && cutVertex){
    cutVertex->SetCheckPileUp(rejectPileUp);
    ::Info("AddAnalysisTaskLStar", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
  }

  // define and fill cut set for event cuts
  AliRsnCutSet* eventCuts=0;
  if(cutEventUtils || cutVertex){
    eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);

    if(cutEventUtils && cutVertex){
      eventCuts->AddCut(cutEventUtils);
      eventCuts->AddCut(cutVertex);
      eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
    }else if(cutEventUtils && !cutVertex){
      eventCuts->AddCut(cutEventUtils);
      eventCuts->SetCutScheme(Form("%s",cutEventUtils->GetName()));
    }else if(!cutEventUtils && cutVertex){
      eventCuts->AddCut(cutVertex);
      eventCuts->SetCutScheme(Form("%s",cutVertex->GetName()));
    }

    task->SetEventCuts(eventCuts);
  }

  //
  // -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
  //
  //vertex
  Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
  AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
  outVtx->AddAxis(vtxID, 400, -20.0, 20.0);

  //multiplicity or centrality
  Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
  AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
  if (isPP && !MultBins)   outMult->AddAxis(multID, 400, 0.0, 400.0);
  else  outMult->AddAxis(multID, 110, 0.0, 110.0);

  Double_t multbins[200];
  int j,nmult=0;
  for(j=0;j<10;j++){multbins[nmult]=0.0001*j; nmult++;}
  for(j=1;j<10;j++){multbins[nmult]=0.001*j; nmult++;}
  for(j=1;j<50;j++){multbins[nmult]=0.01*j; nmult++;}
  for(j=5;j<10;j++){multbins[nmult]=0.1*j; nmult++;}
  for(j=1;j<=100;j++){multbins[nmult]=j; nmult++;}
  nmult--;

  TH1F* hEventsVsMulti=new TH1F("hAEventsVsMulti","",nmult,multbins);
  // task->SetEventQAHist("EventsVsMulti",hEventsVsMulti);//custom binning for fHAEventsVsMulti

  TH2F* hvz=new TH2F("hVzVsCent","",110,0.,110., 240,-12.0,12.0);
  task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member

  double ybins[500];
  for(j=0;j<=401;j++) ybins[j]=j-0.5;

  TH2F* hmc=new TH2F("MultiVsCent","", nmult,multbins, 401,ybins);
  hmc->GetYaxis()->SetTitle("QUALITY");
  task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

  //  <<==============

  //
  // -- PAIR CUTS  -------------------------------------------------------------------------------
  //
  AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair("cutRapidity",AliRsnCutMiniPair::kRapidityRange);
  cutY->SetRangeD(minYlab,maxYlab);

  AliRsnCutSet* cutsPair=new AliRsnCutSet("pairCuts",AliRsnTarget::kMother);
  cutsPair->AddCut(cutY);
  cutsPair->SetCutScheme(cutY->GetName());

  //
  // -- CONFIG ANALYSIS --------------------------------------------------------------------------

  //for systematic checks
  {

    // gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigureLstar13TeVpp_II.C");
    gROOT->LoadMacro("ConfigureLstar13TeVpp_II.C");
    if (!ConfigureLstar13TeVpp_II(task, isMC, isPP, "", cutsPair, aodFilterBit, customQualityCutsID, cutPrCandidate, cutKaCandidate, nsigmaPr, nsigmaKa,  enableMonitor, isMC&IsMcTrueOnly, signedPdg, monitorOpt, useCrossedRows, yaxisVar ,useMixLS))
      return 0x0;
  }

  //
  // -- CONTAINERS --------------------------------------------------------------------------------
  //
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  Printf("AddAnalysisTaskLstar13TeVpp - Set OutputFileName : \n %s\n", outputFileName.Data() );

  AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),TList::Class(),AliAnalysisManager::kOutputContainer, outputFileName);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, output);
  cout<<" taskname  =  "<<taskName.Data()<<endl;
  return task;
}
<commit_msg>Change on event selections for Lambda(1520) analysis in pp collisions at 13 TeV<commit_after>/***************************************************************************
    Modified by himani.bhatt@cern.ch  - last modified on 30/04/2018

   priyanka.sett@cern.ch - last modified on 27/10/2016

  for L* in pp 13 TeV analysis

// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
//  1) flag to know if running on MC or data
//  2) path where all configs are stored
// ---
// Returns:
//  kTRUE  --> initialization successful
//  kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
enum pairYCutSet { kPairDefault=0,
		   kCentral //=1
                 };
enum eventCutSet { kDefaultVtx = 0,
		   kDefaultVtx9, //=1
		   kDefaultVtx8, //=2
		   kDefaultVtx12, //=3
		   kDefaultVtx11,  //=4
		   kNoPileUpCut, //=5
		   kNoEvtSel, //=6   //No event selection, only INEL events
		   kSpecial2,//=7   // No Vz cut on vtx, f_vtx = kSpecial2/default_data
		   kSpecial3, //= 8  // No event selection, INEL events with Vz cut on vtx  kSpecial3/default_MC = f_SL
		   kTriggered, //=6
};

enum eventMixConfig { kDisabled = -1,
		      k5Evts5Cent, //=0 //5 events, Dvz = 1cm, DC = 5
		      kMixDefault, //=1 //10 events, Dvz = 1cm, DC = 10
		      k5Evts, //=2 //5 events, Dvz = 1cm, DC = 10
		      k5Cent  //=3 //10 events, Dvz = 1cm, DC = 5

};

AliRsnMiniAnalysisTask * AddTaskLstar13TeVpp_II
(
 Bool_t      isMC = kFALSE,
 Bool_t      isPP = kTRUE,
 Int_t       aodFilterBit = 5,
 Int_t       pairCutSetID=0,
 Int_t       evtCutSetID = 0,
 Int_t       mixingConfigID = 0,
 Int_t       MultBins = 0,// default for V0_M and MultBins = 2 for RefMult0_8
 Int_t       customQualityCutsID=1, // for default
 Float_t     nsigmaPr = 2.0,
 Float_t     nsigmaKa = 2.0,
 Bool_t      enableMonitor = kTRUE,
 Bool_t      IsMcTrueOnly = kFALSE,
 TString     outNameSuffix = "Default"
 )

{

  AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPrCandidate = AliRsnCutSetDaughterParticle::kTPCTOFpidLstar13ppTeV;
  AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate = AliRsnCutSetDaughterParticle::kTPCTOFpidLstar13ppTeV;

  //-------------------------------------------
  // event cuts
  //-------------------------------------------

  UInt_t      triggerMask = AliVEvent::kINT7;
  if(evtCutSetID>=100){
    triggerMask=AliVEvent::kHighMultV0;
    evtCutSetID=evtCutSetID%100;
  }

  Bool_t      rejectPileUp=kTRUE;
  Double_t    vtxZcut = 10.0;//default cut on vtx z
  //Int_t       MultBins = aodFilterBit/100;

  if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx11) vtxZcut=11.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx9) vtxZcut=9.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
  if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;
  if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;//off

   if(!isPP || isMC || MultBins) rejectPileUp=kFALSE;

  //-------------------------------------------
  //mixing settings
  //-------------------------------------------
  Int_t       nmix=0;
  Float_t     maxDiffVzMix=1.;
  Float_t     maxDiffMultMix=10.;

  if(mixingConfigID==eventMixConfig::kMixDefault) nmix=10;
  if(mixingConfigID==eventMixConfig::k5Evts) nmix=5;
  if(mixingConfigID==eventMixConfig::k5Cent) maxDiffMultMix=5;
  if(mixingConfigID==eventMixConfig::k5Evts5Cent) { maxDiffMultMix=5; nmix = 5;}

//-------------------------------------------
  //pair cuts
  //-------------------------------------------
  Double_t    minYlab=-0.5;
  Double_t    maxYlab= 0.5;

  if(pairCutSetID==pairYCutSet::kCentral){//|y_cm|<0.3
    minYlab=-0.3; maxYlab=0.3;
  }
  Bool_t CheckDecay=true;
  if(customQualityCutsID==99){customQualityCutsID=1; CheckDecay=false;}
  //
  // -- INITIALIZATION ----------------------------------------------------------------------------
  // retrieve analysis manager
  //

  TString outputFileName = Form("%s", AliAnalysisManager::GetCommonFileName());
  // Objects name

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskLstar13TeVpp_II", "No analysis manager to connect to.");
    return NULL;
  }

  // create the task and configure
  TString taskName = outNameSuffix.Data();
  AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);

  if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3){
    task->UseESDTriggerMask(triggerMask);  // for ESD
    //task->SelectCollisionCandidates(triggerMask); //AOD
  }
  if(isPP){
    if(MultBins==1) task->UseMultiplicity("AliMultSelection_V0M");
    else if(MultBins==2) task->UseMultiplicity("AliMultSelection_RefMult08");
    else task->UseMultiplicity("QUALITY");
  }else task->UseCentrality("V0M");

  // set event mixing options
  task->UseContinuousMix();
  //task->UseBinnedMix();
  task->SetNMix(nmix);
  task->SetMaxDiffVz(maxDiffVzMix);
  task->SetMaxDiffMult(maxDiffMultMix);
  //if (!isPP) task->SetMaxDiffAngle(maxDiffAngleMixDeg*TMath::DegToRad()); //set angle diff in rad
  ::Info("AddTaskLstar13TeVpp_II", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n ", nmix, maxDiffVzMix, maxDiffMultMix));

  mgr->AddTask(task);

  //
  // -- EVENT CUTS (same for all configs) ---------------------------------------------------------
  //
  // cut on primary vertex:
  // - 2nd argument --> |Vz| range
  // - 3rd argument --> minimum required number of contributors
  // - 4th argument --> tells if TPC stand-alone vertexes must be accepted

  // vertex cuts

  //Bool_t rejectPileUp=kTRUE;
  //if (!isPP && !isMC) rejectPileUp=kFALSE;

  AliRsnCutPrimaryVertex* cutVertex=0;

  if(evtCutSetID!=eventCutSet::kNoEvtSel &&  evtCutSetID!=eventCutSet::kTriggered)
    { // passes the vertex quality cut
      cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);
      cutVertex->SetCheckGeneratedVertexZ();
      if(MultBins == 0 && evtCutSetID!=eventCutSet::kSpecial3){
	cutVertex->SetCheckZResolutionSPD();
	cutVertex->SetCheckDispersionSPD();
	cutVertex->SetCheckZDifferenceSPDTrack();
      }
      if(evtCutSetID==eventCutSet::kSpecial3) cutVertex->SetCheckGeneratedVertexZ();  // only Vz cut on vtx for INEL events
    }

  // other event selection cuts
  AliRsnCutEventUtils* cutEventUtils=0;
  if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3)
    {
      cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
      if(MultBins == 0){
	cutEventUtils->SetCheckIncompleteDAQ();
	cutEventUtils->SetCheckSPDClusterVsTrackletBG();
      }else{
	cutEventUtils->SetRemovePileUppA2013(kFALSE);
	if(evtCutSetID!=eventCutSet::kTriggered) cutEventUtils->SetCheckAcceptedMultSelection();
	//cutEventUtils->SetCheckAcceptedMultSelection();
      }
    }

  // set the check for pileup
  if(isPP && (!isMC) && cutVertex){
    cutVertex->SetCheckPileUp(rejectPileUp);
    ::Info("AddTaskLstar13TeVpp_II", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
  }

  // define and fill cut set for event cuts
  AliRsnCutSet* eventCuts=0;
  if(cutEventUtils || cutVertex){
    eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);

    if(cutEventUtils && cutVertex){
      eventCuts->AddCut(cutEventUtils);
      eventCuts->AddCut(cutVertex);
      eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
    }else if(cutEventUtils && !cutVertex){
      eventCuts->AddCut(cutEventUtils);
      eventCuts->SetCutScheme(Form("%s",cutEventUtils->GetName()));
    }else if(!cutEventUtils && cutVertex){
      eventCuts->AddCut(cutVertex);
      eventCuts->SetCutScheme(Form("%s",cutVertex->GetName()));
    }

    task->SetEventCuts(eventCuts);
  }

  //
  // -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
  //
  //vertex
  Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
  AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
  outVtx->AddAxis(vtxID, 400, -20.0, 20.0);

  //multiplicity or centrality
  Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
  AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
  if (isPP && !MultBins)   outMult->AddAxis(multID, 400, 0.5, 400.5);
  else  outMult->AddAxis(multID, 110, 0.0, 110.0);

  Double_t multbins[200];
  int j,nmult=0;
  for(j=0;j<10;j++){multbins[nmult]=0.0001*j; nmult++;}
  for(j=1;j<10;j++){multbins[nmult]=0.001*j; nmult++;}
  for(j=1;j<50;j++){multbins[nmult]=0.01*j; nmult++;}
  for(j=5;j<10;j++){multbins[nmult]=0.1*j; nmult++;}
  for(j=1;j<=100;j++){multbins[nmult]=j; nmult++;}
  nmult--;

  TH1F* hEventsVsMulti=new TH1F("hAEventsVsMulti","",nmult,multbins);
  task->SetEventQAHist("EventsVsMulti",hEventsVsMulti);//custom binning for fHAEventsVsMulti

  TH2F* hvz=new TH2F("hVzVsCent","",110,0.,110., 240,-12.0,12.0);
  task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member

  double ybins[500];
  for(j=0;j<=401;j++) ybins[j]=j-0.5;

  TH2F* hmc=new TH2F("MultiVsCent","", nmult,multbins, 401,ybins);
  hmc->GetYaxis()->SetTitle("QUALITY");
  task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

  //  <<==============

  //
  // -- PAIR CUTS  -------------------------------------------------------------------------------
  //
  AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair("cutRapidity",AliRsnCutMiniPair::kRapidityRange);
  cutY->SetRangeD(minYlab,maxYlab);

  AliRsnCutSet* cutsPair=new AliRsnCutSet("pairCuts",AliRsnTarget::kMother);
  cutsPair->AddCut(cutY);
  cutsPair->SetCutScheme(cutY->GetName());

  task->SetCheckDecay(CheckDecay);

  //
  // -- CONFIG ANALYSIS --------------------------------------------------------------------------

  //for systematic checks

     gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigureLstar13TeVpp_II.C");
    //gROOT->LoadMacro("ConfigureLstar13TeVpp_II.C");
    if (!ConfigureLstar13TeVpp_II(task, isMC, isPP, "", cutsPair, aodFilterBit, customQualityCutsID, cutPrCandidate, cutKaCandidate, nsigmaPr, nsigmaKa,  enableMonitor, isMC&IsMcTrueOnly))
      return 0x0;

  //
  // -- CONTAINERS --------------------------------------------------------------------------------
  //
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  Printf("AddAnalysisTaskLstar13TeVpp - Set OutputFileName : \n %s\n", outputFileName.Data() );

  AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),TList::Class(),AliAnalysisManager::kOutputContainer, outputFileName);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, output);
  //cout<<" taskname  =  "<<taskName.Data()<<endl;
  return task;
}
<|endoftext|>


<commit_before>//---
//
// License: MIT
//
// File: ossim-foo.cpp
//
// Description: Contains application definition "ossim-foo" app.
//
// NOTE:  This is supplied for simple quick test. DO NOT checkin your test to
//        the svn repository.  Simply edit ossim-foo.cpp and run your test.
//        After completion you can do a "git checkout -- ossimfoo.cpp" if
//        you want to keep your working repository up to snuff.
//
// $Id$
//---

// ossim includes:  These are here just to save time/typing...
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimArgumentParser.h>
#include <ossim/base/ossimConnectableObject.h>
#include <ossim/base/ossimCsvFile.h>
#include <ossim/base/ossimDate.h>
#include <ossim/base/ossimDpt.h>
#include <ossim/base/ossimDrect.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimFilename.h>
#include <ossim/base/ossimIpt.h>
#include <ossim/base/ossimIrect.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimObjectFactory.h>
#include <ossim/base/ossimObjectFactoryRegistry.h>
#include <ossim/base/ossimProperty.h>
#include <ossim/base/ossimRefPtr.h>
#include <ossim/base/ossimString.h>
#include <ossim/base/ossimScalarTypeLut.h>
#include <ossim/base/ossimStdOutProgress.h>
#include <ossim/base/ossimStreamFactoryRegistry.h>
#include <ossim/base/ossimStringProperty.h>
#include <ossim/base/ossimTrace.h>
#include <ossim/base/ossimUrl.h>
#include <ossim/base/ossimVisitor.h>
#include <ossim/base/ossimEcefPoint.h>
#include <ossim/base/ossimEcefVector.h>
#include <ossim/base/ossim2dBilinearTransform.h>

#include <ossim/imaging/ossimNitfTileSource.h>
#include <ossim/imaging/ossimBrightnessContrastSource.h>
#include <ossim/imaging/ossimBumpShadeTileSource.h>
#include <ossim/imaging/ossimFilterResampler.h>
#include <ossim/imaging/ossimFusionCombiner.h>
#include <ossim/imaging/ossimImageData.h>
#include <ossim/imaging/ossimImageFileWriter.h>
#include <ossim/imaging/ossimImageGeometry.h>
#include <ossim/imaging/ossimImageHandler.h>
#include <ossim/imaging/ossimImageMosaic.h>
#include <ossim/imaging/ossimImageRenderer.h>
#include <ossim/imaging/ossimImageSource.h>
#include <ossim/imaging/ossimImageSourceFilter.h>
#include <ossim/imaging/ossimImageToPlaneNormalFilter.h>
#include <ossim/imaging/ossimImageWriterFactoryRegistry.h>
#include <ossim/imaging/ossimIndexToRgbLutFilter.h>
#include <ossim/imaging/ossimRectangleCutFilter.h>
#include <ossim/imaging/ossimScalarRemapper.h>
#include <ossim/imaging/ossimSFIMFusion.h>
#include <ossim/imaging/ossimTwoColorView.h>
#include <ossim/imaging/ossimImageSourceFactoryRegistry.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>

#include <ossim/init/ossimInit.h>

#include <ossim/projection/ossimEquDistCylProjection.h>
#include <ossim/projection/ossimImageViewAffineTransform.h>
#include <ossim/projection/ossimMapProjection.h>
#include <ossim/projection/ossimProjection.h>
#include <ossim/projection/ossimProjectionFactoryRegistry.h>
#include <ossim/projection/ossimUtmProjection.h>

#include <ossim/support_data/ossimSrcRecord.h>
#include <ossim/support_data/ossimWkt.h>

// Put your includes here:

// System includes:
#include <cmath>
#include <memory>
#include <sstream>
#include <iostream>
using namespace std;

/*
void getOverlappingPatchCenters(std::vector<ossimGpt>& patchCenters,
                           ossimRefPtr<ossimImageGeometry> geom1,
                           ossimRefPtr<ossimImageGeometry> geom2,
                           ossim_uint32 size=256)
{
   ossimDrect rect1;
   ossimDrect rect2;
   geom1->getBoundingRect(rect1);
   geom2->getBoundingRect(rect2);
   ossim_uint32 halfSize = size>>1;
   ossimDpt halfPoint(halfSize, halfSize);
   ossimIpt originTop    = rect1.ul() + halfPoint;
   ossimIpt originBottom = rect1.lr() - halfPoint;
   ossimIpt iteratePoint = originTop;
   ossimIpt destTop    = rect2.ul() + halfPoint;
   ossimIpt destBottom = rect2.lr() - halfPoint;
   ossimDrect originRect(originTop, originBottom);
   ossimDrect testRect(destTop, destBottom);

   if(originRect.completely_within(rect1))
   {
      for(ossim_uint32 y = originTop.y; y < originBottom.y;y+=size)
      {
         for(ossim_uint32 x = originTop.x; x < originBottom.x;x+=size)
         {
            ossimDpt destImagePt;
            ossimGpt gpt;
            geom1->localToWorld(ossimDpt(x,y), gpt);
            geom2->worldToLocal(gpt, destImagePt);
            ossimDpt ul = destImagePt - halfPoint;
            ossimDpt lr = ul + ossimDpt(size-1, size-1);
            ossimDrect patchRect(ul, lr);
            if(patchRect.completely_within(testRect))
            {
               patchCenters.push_back(gpt);
            }
         }
      }
   }
   else
   {
      std::cout << "Patch size is too big for it exceeds the bounds of the image\n";
   }

}
*/
int main(int argc, char *argv[])
{
   int returnCode = 0;

   ossimArgumentParser ap(&argc, argv);
   ossimInit::instance()->addOptions(ap);
   ossimInit::instance()->initialize(ap);

   try
   {
      ossimKeywordlist kwl;
      ossimRefPtr<ossimImageHandler> ih = ossimImageHandlerRegistry::instance()->open(ossimFilename(argv[1]));

      ossimRefPtr<ossimImageGeometry> geom = ih->getImageGeometry();
      if(geom.valid())
      {
         ossimDrect rect;
         ossimDpt dpt;
         geom->getBoundingRect(rect);
         dpt = rect.midPoint();
         std::cout << rect << "\n";

         std::cout << "UP IS UP " << geom->upIsUpAngle(dpt) << "\n";

         ossimGpt gpt;
         geom->localToWorld(dpt, gpt);
         ossimEcefPoint ecefPoint(gpt);

         ossimGpt gpt2 = gpt;
         gpt2.height(gpt2.height()+10);

         ossimEcefPoint ecefPoint2(gpt2);

         std::cout << "ecef: " << ecefPoint << "\n";
         std::cout << "ecef2: " << ecefPoint2 << "\n";
         ossimEcefVector v(ecefPoint2-ecefPoint);
         std::cout << "ecef v: " << v << "\n";
         std::cout << "LENGTH: " << v.normalize() << "\n";
         std::cout << "NORM: " << v << "\n";

      }

      /*
      if(argc > 2)
      {
         ossim_uint32 patchSize = 512;
         ossimRefPtr<ossimImageHandler> ih1 = ossimImageHandlerRegistry::instance()->open(ossimFilename(argv[1]));
         ossimRefPtr<ossimImageHandler> ih2 = ossimImageHandlerRegistry::instance()->open(ossimFilename(argv[2]));
         if(argc > 3)
         {
            patchSize = ossimString(argv[3]).toUInt32();
         }
         if(ih1.valid()&&ih2.valid())
         {
            std::vector<ossimGpt> points;
            ossimPolyArea2d poly1;
            ossimPolyArea2d poly2;
            ossimRefPtr<ossimImageGeometry> geom1 = ih1->getImageGeometry();
            ossimRefPtr<ossimImageGeometry> geom2 = ih2->getImageGeometry();

            getOverlappingPatchCenters(points, geom1, geom2, patchSize);

            ossim_uint32 idx = 0;
            for(idx=0;idx < points.size(); ++idx)
            {

               std::cout << points[idx].latd() <<  " " << points[idx].lond() << "\n";
            }
         }
      }
      else
      {
         std::cout << "Arguments must be <image 1> <image 2> <tile_size>\n";
         std::cout << "  where tile_size is optional\n";
      }
*/
      // Put your code here.
   }
   catch(const ossimException& e)
   {
      ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl;
      returnCode = 1;
   }
   catch( ... )
   {
      ossimNotify(ossimNotifyLevel_WARN)
         << "ossim-foo caught unhandled exception!" << std::endl;
      returnCode = 1;
   }

   return returnCode;
}
<commit_msg>Somehow the ossim-foo got checked in<commit_after>//---
//
// License: MIT
//
// File: ossim-foo.cpp
//
// Description: Contains application definition "ossim-foo" app.
//
// NOTE:  This is supplied for simple quick test. DO NOT checkin your test to
//        the svn repository.  Simply edit ossim-foo.cpp and run your test.
//        After completion you can do a "git checkout -- ossimfoo.cpp" if
//        you want to keep your working repository up to snuff.
//
// $Id$
//---

// ossim includes:  These are here just to save time/typing...
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimArgumentParser.h>
#include <ossim/base/ossimConnectableObject.h>
#include <ossim/base/ossimCsvFile.h>
#include <ossim/base/ossimDate.h>
#include <ossim/base/ossimDpt.h>
#include <ossim/base/ossimDrect.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimFilename.h>
#include <ossim/base/ossimIpt.h>
#include <ossim/base/ossimIrect.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimObjectFactory.h>
#include <ossim/base/ossimObjectFactoryRegistry.h>
#include <ossim/base/ossimProperty.h>
#include <ossim/base/ossimRefPtr.h>
#include <ossim/base/ossimString.h>
#include <ossim/base/ossimScalarTypeLut.h>
#include <ossim/base/ossimStdOutProgress.h>
#include <ossim/base/ossimStreamFactoryRegistry.h>
#include <ossim/base/ossimStringProperty.h>
#include <ossim/base/ossimTrace.h>
#include <ossim/base/ossimUrl.h>
#include <ossim/base/ossimVisitor.h>
#include <ossim/base/ossimEcefPoint.h>
#include <ossim/base/ossimEcefVector.h>
#include <ossim/base/ossim2dBilinearTransform.h>

#include <ossim/imaging/ossimNitfTileSource.h>
#include <ossim/imaging/ossimBrightnessContrastSource.h>
#include <ossim/imaging/ossimBumpShadeTileSource.h>
#include <ossim/imaging/ossimFilterResampler.h>
#include <ossim/imaging/ossimFusionCombiner.h>
#include <ossim/imaging/ossimImageData.h>
#include <ossim/imaging/ossimImageFileWriter.h>
#include <ossim/imaging/ossimImageGeometry.h>
#include <ossim/imaging/ossimImageHandler.h>
#include <ossim/imaging/ossimImageMosaic.h>
#include <ossim/imaging/ossimImageRenderer.h>
#include <ossim/imaging/ossimImageSource.h>
#include <ossim/imaging/ossimImageSourceFilter.h>
#include <ossim/imaging/ossimImageToPlaneNormalFilter.h>
#include <ossim/imaging/ossimImageWriterFactoryRegistry.h>
#include <ossim/imaging/ossimIndexToRgbLutFilter.h>
#include <ossim/imaging/ossimRectangleCutFilter.h>
#include <ossim/imaging/ossimScalarRemapper.h>
#include <ossim/imaging/ossimSFIMFusion.h>
#include <ossim/imaging/ossimTwoColorView.h>
#include <ossim/imaging/ossimImageSourceFactoryRegistry.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>

#include <ossim/init/ossimInit.h>

#include <ossim/projection/ossimEquDistCylProjection.h>
#include <ossim/projection/ossimImageViewAffineTransform.h>
#include <ossim/projection/ossimMapProjection.h>
#include <ossim/projection/ossimProjection.h>
#include <ossim/projection/ossimProjectionFactoryRegistry.h>
#include <ossim/projection/ossimUtmProjection.h>

#include <ossim/support_data/ossimSrcRecord.h>
#include <ossim/support_data/ossimWkt.h>

// Put your includes here:

// System includes:
#include <cmath>
#include <memory>
#include <sstream>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
   int returnCode = 0;

   ossimArgumentParser ap(&argc, argv);
   ossimInit::instance()->addOptions(ap);
   ossimInit::instance()->initialize(ap);

   try
   {
      // Put your code here.
   }
   catch(const ossimException& e)
   {
      ossimNotify(ossimNotifyLevel_WARN) << e.what() << std::endl;
      returnCode = 1;
   }
   catch( ... )
   {
      ossimNotify(ossimNotifyLevel_WARN)
         << "ossim-foo caught unhandled exception!" << std::endl;
      returnCode = 1;
   }

   return returnCode;
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file stateOriginal.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * State test functions.
 */

#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>
#include <secp256k1/secp256k1.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/State.h>
#include <libethereum/Farm.h>
#include <libethereum/Defaults.h>
#include "TestHelper.h"
using namespace std;
using namespace dev;
using namespace dev::eth;

namespace dev
{
namespace test
{

int stateTest();

BOOST_AUTO_TEST_SUITE(StateIntegration)

BOOST_AUTO_TEST_CASE(Basic)
{
	State s;
}

BOOST_AUTO_TEST_CASE(Complex)
{
	cnote << "Testing State...";

	KeyPair me = sha3("Gav Wood");
	KeyPair myMiner = sha3("Gav's Miner");
//	KeyPair you = sha3("123");

	Defaults::setDBPath(boost::filesystem::temp_directory_path().string() + "/" + toString(chrono::system_clock::now().time_since_epoch().count()));

	OverlayDB stateDB = State::openDB();
	CanonBlockChain bc;
	cout << bc;

	State s(stateDB, BaseState::Empty, myMiner.address());
	cout << s;

	// Sync up - this won't do much until we use the last state.
	s.sync(bc);

	cout << s;

	// Mine to get some ether!
	mine(s, bc);

	bc.attemptImport(s.blockData(), stateDB);

	cout << bc;

	s.sync(bc);

	cout << s;

	// Inject a transaction to transfer funds from miner to me.
	Transaction t(1000, 10000, 10000, me.address(), bytes(), s.transactionsFrom(myMiner.address()), myMiner.secret());
	assert(t.sender() == myMiner.address());
	s.execute(bc.lastHashes(), t);

	cout << s;

	// Mine to get some ether and set in stone.
	s.commitToMine(bc);
	s.commitToMine(bc);
	mine(s, bc);
	bc.attemptImport(s.blockData(), stateDB);

	cout << bc;

	s.sync(bc);

	cout << s;
}

BOOST_AUTO_TEST_SUITE_END()

}
}
<commit_msg>Minor fix for integration tests.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file stateOriginal.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 * State test functions.
 */

#include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp>
#include <secp256k1/secp256k1.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/State.h>
#include <libethereum/Farm.h>
#include <libethereum/Defaults.h>
#include "TestHelper.h"
using namespace std;
using namespace dev;
using namespace dev::eth;

namespace dev
{
namespace test
{

int stateTest();

BOOST_AUTO_TEST_SUITE(StateIntegration)

BOOST_AUTO_TEST_CASE(Basic)
{
	State s;
}

BOOST_AUTO_TEST_CASE(Complex)
{
	cnote << "Testing State...";

	KeyPair me = sha3("Gav Wood");
	KeyPair myMiner = sha3("Gav's Miner");
//	KeyPair you = sha3("123");

	Defaults::setDBPath(boost::filesystem::temp_directory_path().string() + "/" + toString(chrono::system_clock::now().time_since_epoch().count()));

	OverlayDB stateDB = State::openDB();
	CanonBlockChain bc;
	cout << bc;

	State s(stateDB, BaseState::CanonGenesis, myMiner.address());
	cout << s;

	// Sync up - this won't do much until we use the last state.
	s.sync(bc);

	cout << s;

	// Mine to get some ether!
	mine(s, bc);

	bc.attemptImport(s.blockData(), stateDB);

	cout << bc;

	s.sync(bc);

	cout << s;

	// Inject a transaction to transfer funds from miner to me.
	Transaction t(1000, 10000, 100000, me.address(), bytes(), s.transactionsFrom(myMiner.address()), myMiner.secret());
	assert(t.sender() == myMiner.address());
	s.execute(bc.lastHashes(), t);

	cout << s;

	// Mine to get some ether and set in stone.
	s.commitToMine(bc);
	s.commitToMine(bc);
	mine(s, bc);
	bc.attemptImport(s.blockData(), stateDB);

	cout << bc;

	s.sync(bc);

	cout << s;
}

BOOST_AUTO_TEST_SUITE_END()

}
}
<|endoftext|>


<commit_before>//===--- CGComplexExpr.cpp - Emit LLVM Code for Complex Exprs -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code to emit Expr nodes with complex types as LLVM code.
//
//===----------------------------------------------------------------------===//

#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/AST.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Support/Compiler.h"
using namespace clang;
using namespace CodeGen;

//===----------------------------------------------------------------------===//
//                        Complex Expression Emitter
//===----------------------------------------------------------------------===//

typedef CodeGenFunction::ComplexPairTy ComplexPairTy;

namespace  {
class VISIBILITY_HIDDEN ComplexExprEmitter
  : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
  CodeGenFunction &CGF;
  llvm::LLVMBuilder &Builder;
public:
  ComplexExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
  }

  //===--------------------------------------------------------------------===//
  //                               Utilities
  //===--------------------------------------------------------------------===//

  /// EmitLoadOfLValue - Given an expression with complex type that represents a
  /// value l-value, this method emits the address of the l-value, then loads
  /// and returns the result.
  ComplexPairTy EmitLoadOfLValue(const Expr *E) {
    LValue LV = CGF.EmitLValue(E);
    // FIXME: Volatile
    return EmitLoadOfComplex(LV.getAddress(), false);
  }

  /// EmitLoadOfComplex - Given a pointer to a complex value, emit code to load
  /// the real and imaginary pieces.
  ComplexPairTy EmitLoadOfComplex(llvm::Value *SrcPtr, bool isVolatile);

  /// EmitStoreOfComplex - Store the specified real/imag parts into the
  /// specified value pointer.
  void EmitStoreOfComplex(ComplexPairTy Val, llvm::Value *ResPtr, bool isVol);

  //===--------------------------------------------------------------------===//
  //                            Visitor Methods
  //===--------------------------------------------------------------------===//

  ComplexPairTy VisitStmt(Stmt *S) {
    fprintf(stderr, "Unimplemented agg expr!\n");
    S->dump();
    return ComplexPairTy();
  }
  ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}

  // l-values.
  ComplexPairTy VisitDeclRefExpr(DeclRefExpr *DRE) {
    return EmitLoadOfLValue(DRE);
  }
  //  case Expr::ArraySubscriptExprClass:

  // Operators.
  //  case Expr::UnaryOperatorClass:
  //  case Expr::ImplicitCastExprClass:
  //  case Expr::CastExprClass:
  //  case Expr::CallExprClass:
  ComplexPairTy VisitBinaryOperator(const BinaryOperator *BO);
  ComplexPairTy VisitBinMul        (const BinaryOperator *E);
  ComplexPairTy VisitBinAdd        (const BinaryOperator *E);
  // FIXME: div/rem
  // GCC rejects and/or/xor for integer complex.
  // Logical and/or always return int, never complex.

  // No comparisons produce a complex result.
  ComplexPairTy VisitBinAssign     (const BinaryOperator *E);

  ComplexPairTy VisitBinComma      (const BinaryOperator *E);

  ComplexPairTy VisitConditionalOperator(const ConditionalOperator *CO);
  //  case Expr::ChooseExprClass:
};
}  // end anonymous namespace.

//===----------------------------------------------------------------------===//
//                                Utilities
//===----------------------------------------------------------------------===//

/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
/// load the real and imaginary pieces, returning them as Real/Imag.
ComplexPairTy ComplexExprEmitter::EmitLoadOfComplex(llvm::Value *SrcPtr,
                                                    bool isVolatile) {
  llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
  llvm::Constant *One  = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
  // FIXME: It would be nice to make this "Ptr->getName()+realp"
  llvm::Value *RealPtr = Builder.CreateGEP(SrcPtr, Zero, Zero, "realp");
  llvm::Value *ImagPtr = Builder.CreateGEP(SrcPtr, Zero, One, "imagp");

  // FIXME: It would be nice to make this "Ptr->getName()+real"
  llvm::Value *Real = Builder.CreateLoad(RealPtr, isVolatile, "real");
  llvm::Value *Imag = Builder.CreateLoad(ImagPtr, isVolatile, "imag");
  return ComplexPairTy(Real, Imag);
}

/// EmitStoreOfComplex - Store the specified real/imag parts into the
/// specified value pointer.
void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, llvm::Value *Ptr,
                                            bool isVolatile) {
  llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
  llvm::Constant *One  = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
  llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "real");
  llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imag");

  Builder.CreateStore(Val.first, RealPtr, isVolatile);
  Builder.CreateStore(Val.second, ImagPtr, isVolatile);
}

//===----------------------------------------------------------------------===//
//                            Visitor Methods
//===----------------------------------------------------------------------===//

ComplexPairTy ComplexExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
  fprintf(stderr, "Unimplemented complex binary expr!\n");
  E->dump();
  return ComplexPairTy();
}

ComplexPairTy ComplexExprEmitter::VisitBinAdd(const BinaryOperator *E) {
  ComplexPairTy LHS = Visit(E->getLHS());
  ComplexPairTy RHS = Visit(E->getRHS());

  llvm::Value *ResR = Builder.CreateAdd(LHS.first,  RHS.first,  "add.r");
  llvm::Value *ResI = Builder.CreateAdd(LHS.second, RHS.second, "add.i");

  return ComplexPairTy(ResR, ResI);
}

ComplexPairTy ComplexExprEmitter::VisitBinMul(const BinaryOperator *E) {
  ComplexPairTy LHS = Visit(E->getLHS());
  ComplexPairTy RHS = Visit(E->getRHS());

  llvm::Value *ResRl = Builder.CreateMul(LHS.first, RHS.first, "mul.rl");
  llvm::Value *ResRr = Builder.CreateMul(LHS.second, RHS.second, "mul.rr");
  llvm::Value *ResR  = Builder.CreateSub(ResRl, ResRr, "mul.r");

  llvm::Value *ResIl = Builder.CreateMul(LHS.second, RHS.first, "mul.il");
  llvm::Value *ResIr = Builder.CreateMul(LHS.first, RHS.second, "mul.ir");
  llvm::Value *ResI  = Builder.CreateAdd(ResIl, ResIr, "mul.i");

  return ComplexPairTy(ResR, ResI);
}

ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  assert(E->getLHS()->getType().getCanonicalType() ==
         E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
  // Emit the RHS.
  ComplexPairTy Val = Visit(E->getRHS());

  // Compute the address to store into.
  LValue LHS = CGF.EmitLValue(E->getLHS());

  // Store into it.
  // FIXME: Volatility!
  EmitStoreOfComplex(Val, LHS.getAddress(), false);
  return Val;
}

ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
  CGF.EmitStmt(E->getLHS());
  return Visit(E->getRHS());
}

ComplexPairTy ComplexExprEmitter::
VisitConditionalOperator(const ConditionalOperator *E) {
  llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
  llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
  llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");

  llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
  Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);

  CGF.EmitBlock(LHSBlock);

  // Handle the GNU extension for missing LHS.
  assert(E->getLHS() && "Must have LHS for complex value");

  ComplexPairTy LHS = Visit(E->getLHS());
  Builder.CreateBr(ContBlock);
  LHSBlock = Builder.GetInsertBlock();

  CGF.EmitBlock(RHSBlock);

  ComplexPairTy RHS = Visit(E->getRHS());
  Builder.CreateBr(ContBlock);
  RHSBlock = Builder.GetInsertBlock();

  CGF.EmitBlock(ContBlock);

  // Create a PHI node for the real part.
  llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), "cond.r");
  RealPN->reserveOperandSpace(2);
  RealPN->addIncoming(LHS.first, LHSBlock);
  RealPN->addIncoming(RHS.first, RHSBlock);

  // Create a PHI node for the imaginary part.
  llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), "cond.i");
  ImagPN->reserveOperandSpace(2);
  ImagPN->addIncoming(LHS.second, LHSBlock);
  ImagPN->addIncoming(RHS.second, RHSBlock);

  return ComplexPairTy(RealPN, ImagPN);
}

//===----------------------------------------------------------------------===//
//                         Entry Point into this File
//===----------------------------------------------------------------------===//

/// EmitComplexExpr - Emit the computation of the specified expression of
/// complex type, ignoring the result.
ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E) {
  assert(E && E->getType()->isComplexType() &&
         "Invalid complex expression to emit");

  return ComplexExprEmitter(*this).Visit(const_cast<Expr*>(E));
}

<commit_msg>implement support for complex subscripts.<commit_after>//===--- CGComplexExpr.cpp - Emit LLVM Code for Complex Exprs -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code to emit Expr nodes with complex types as LLVM code.
//
//===----------------------------------------------------------------------===//

#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/AST.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Support/Compiler.h"
using namespace clang;
using namespace CodeGen;

//===----------------------------------------------------------------------===//
//                        Complex Expression Emitter
//===----------------------------------------------------------------------===//

typedef CodeGenFunction::ComplexPairTy ComplexPairTy;

namespace  {
class VISIBILITY_HIDDEN ComplexExprEmitter
  : public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
  CodeGenFunction &CGF;
  llvm::LLVMBuilder &Builder;
public:
  ComplexExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
  }

  //===--------------------------------------------------------------------===//
  //                               Utilities
  //===--------------------------------------------------------------------===//

  /// EmitLoadOfLValue - Given an expression with complex type that represents a
  /// value l-value, this method emits the address of the l-value, then loads
  /// and returns the result.
  ComplexPairTy EmitLoadOfLValue(const Expr *E) {
    LValue LV = CGF.EmitLValue(E);
    // FIXME: Volatile
    return EmitLoadOfComplex(LV.getAddress(), false);
  }

  /// EmitLoadOfComplex - Given a pointer to a complex value, emit code to load
  /// the real and imaginary pieces.
  ComplexPairTy EmitLoadOfComplex(llvm::Value *SrcPtr, bool isVolatile);

  /// EmitStoreOfComplex - Store the specified real/imag parts into the
  /// specified value pointer.
  void EmitStoreOfComplex(ComplexPairTy Val, llvm::Value *ResPtr, bool isVol);

  //===--------------------------------------------------------------------===//
  //                            Visitor Methods
  //===--------------------------------------------------------------------===//

  ComplexPairTy VisitStmt(Stmt *S) {
    fprintf(stderr, "Unimplemented agg expr!\n");
    S->dump();
    return ComplexPairTy();
  }
  ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}

  // l-values.
  ComplexPairTy VisitDeclRefExpr(Expr *E) { return EmitLoadOfLValue(E); }
  ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }

  // Operators.
  //  case Expr::UnaryOperatorClass:
  //  case Expr::ImplicitCastExprClass:
  //  case Expr::CastExprClass:
  //  case Expr::CallExprClass:
  ComplexPairTy VisitBinaryOperator(const BinaryOperator *BO);
  ComplexPairTy VisitBinMul        (const BinaryOperator *E);
  ComplexPairTy VisitBinAdd        (const BinaryOperator *E);
  // FIXME: div/rem
  // GCC rejects and/or/xor for integer complex.
  // Logical and/or always return int, never complex.

  // No comparisons produce a complex result.
  ComplexPairTy VisitBinAssign     (const BinaryOperator *E);

  ComplexPairTy VisitBinComma      (const BinaryOperator *E);

  ComplexPairTy VisitConditionalOperator(const ConditionalOperator *CO);
  //  case Expr::ChooseExprClass:
};
}  // end anonymous namespace.

//===----------------------------------------------------------------------===//
//                                Utilities
//===----------------------------------------------------------------------===//

/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
/// load the real and imaginary pieces, returning them as Real/Imag.
ComplexPairTy ComplexExprEmitter::EmitLoadOfComplex(llvm::Value *SrcPtr,
                                                    bool isVolatile) {
  llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
  llvm::Constant *One  = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
  // FIXME: It would be nice to make this "Ptr->getName()+realp"
  llvm::Value *RealPtr = Builder.CreateGEP(SrcPtr, Zero, Zero, "realp");
  llvm::Value *ImagPtr = Builder.CreateGEP(SrcPtr, Zero, One, "imagp");

  // FIXME: It would be nice to make this "Ptr->getName()+real"
  llvm::Value *Real = Builder.CreateLoad(RealPtr, isVolatile, "real");
  llvm::Value *Imag = Builder.CreateLoad(ImagPtr, isVolatile, "imag");
  return ComplexPairTy(Real, Imag);
}

/// EmitStoreOfComplex - Store the specified real/imag parts into the
/// specified value pointer.
void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, llvm::Value *Ptr,
                                            bool isVolatile) {
  llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
  llvm::Constant *One  = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
  llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "real");
  llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imag");

  Builder.CreateStore(Val.first, RealPtr, isVolatile);
  Builder.CreateStore(Val.second, ImagPtr, isVolatile);
}

//===----------------------------------------------------------------------===//
//                            Visitor Methods
//===----------------------------------------------------------------------===//

ComplexPairTy ComplexExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
  fprintf(stderr, "Unimplemented complex binary expr!\n");
  E->dump();
  return ComplexPairTy();
}

ComplexPairTy ComplexExprEmitter::VisitBinAdd(const BinaryOperator *E) {
  ComplexPairTy LHS = Visit(E->getLHS());
  ComplexPairTy RHS = Visit(E->getRHS());

  llvm::Value *ResR = Builder.CreateAdd(LHS.first,  RHS.first,  "add.r");
  llvm::Value *ResI = Builder.CreateAdd(LHS.second, RHS.second, "add.i");

  return ComplexPairTy(ResR, ResI);
}

ComplexPairTy ComplexExprEmitter::VisitBinMul(const BinaryOperator *E) {
  ComplexPairTy LHS = Visit(E->getLHS());
  ComplexPairTy RHS = Visit(E->getRHS());

  llvm::Value *ResRl = Builder.CreateMul(LHS.first, RHS.first, "mul.rl");
  llvm::Value *ResRr = Builder.CreateMul(LHS.second, RHS.second, "mul.rr");
  llvm::Value *ResR  = Builder.CreateSub(ResRl, ResRr, "mul.r");

  llvm::Value *ResIl = Builder.CreateMul(LHS.second, RHS.first, "mul.il");
  llvm::Value *ResIr = Builder.CreateMul(LHS.first, RHS.second, "mul.ir");
  llvm::Value *ResI  = Builder.CreateAdd(ResIl, ResIr, "mul.i");

  return ComplexPairTy(ResR, ResI);
}

ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  assert(E->getLHS()->getType().getCanonicalType() ==
         E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
  // Emit the RHS.
  ComplexPairTy Val = Visit(E->getRHS());

  // Compute the address to store into.
  LValue LHS = CGF.EmitLValue(E->getLHS());

  // Store into it.
  // FIXME: Volatility!
  EmitStoreOfComplex(Val, LHS.getAddress(), false);
  return Val;
}

ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
  CGF.EmitStmt(E->getLHS());
  return Visit(E->getRHS());
}

ComplexPairTy ComplexExprEmitter::
VisitConditionalOperator(const ConditionalOperator *E) {
  llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
  llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
  llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");

  llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
  Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);

  CGF.EmitBlock(LHSBlock);

  // Handle the GNU extension for missing LHS.
  assert(E->getLHS() && "Must have LHS for complex value");

  ComplexPairTy LHS = Visit(E->getLHS());
  Builder.CreateBr(ContBlock);
  LHSBlock = Builder.GetInsertBlock();

  CGF.EmitBlock(RHSBlock);

  ComplexPairTy RHS = Visit(E->getRHS());
  Builder.CreateBr(ContBlock);
  RHSBlock = Builder.GetInsertBlock();

  CGF.EmitBlock(ContBlock);

  // Create a PHI node for the real part.
  llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), "cond.r");
  RealPN->reserveOperandSpace(2);
  RealPN->addIncoming(LHS.first, LHSBlock);
  RealPN->addIncoming(RHS.first, RHSBlock);

  // Create a PHI node for the imaginary part.
  llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), "cond.i");
  ImagPN->reserveOperandSpace(2);
  ImagPN->addIncoming(LHS.second, LHSBlock);
  ImagPN->addIncoming(RHS.second, RHSBlock);

  return ComplexPairTy(RealPN, ImagPN);
}

//===----------------------------------------------------------------------===//
//                         Entry Point into this File
//===----------------------------------------------------------------------===//

/// EmitComplexExpr - Emit the computation of the specified expression of
/// complex type, ignoring the result.
ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E) {
  assert(E && E->getType()->isComplexType() &&
         "Invalid complex expression to emit");

  return ComplexExprEmitter(*this).Visit(const_cast<Expr*>(E));
}

<|endoftext|>


<commit_before>#ifndef TOKENPASSSEARCH_HH
#define TOKENPASSSEARCH_HH

#include "fsalm/LM.hh"
#include "WordGraph.hh"
#include "TPLexPrefixTree.hh"
#include "TreeGram.hh"
#include "Acoustics.hh"

#define MAX_WC_COUNT 200
#define MAX_LEX_TREE_DEPTH 60

typedef std::vector<TPLexPrefixTree::LMHistory*> HistoryVector;

class TokenPassSearch {
public:
  TokenPassSearch(TPLexPrefixTree &lex, Vocabulary &vocab,
                  Acoustics *acoustics);

  // Resets search and creates the initial token
  void reset_search(int start_frame);
  void set_end_frame(int end_frame) { m_end_frame = end_frame; }

  // Proceeds decoding one frame
  bool run(void);

  // Print the best path
  void write_word_history(FILE *file = stdout, bool get_best_path = true);
  void print_lm_history(FILE *file = stdout, bool get_best_path = true);
  TPLexPrefixTree::Token *get_best_token();
  void print_state_history(FILE *file = stdout);
  std::string state_history_string();
  void get_state_history(std::vector<TPLexPrefixTree::StateHistory*> &stack);
  void get_path(HistoryVector &vec, bool use_best_token,
                TPLexPrefixTree::LMHistory *limit);

  // Options
  void set_acoustics(Acoustics *acoustics) { m_acoustics = acoustics; }
  void set_global_beam(float beam) { m_global_beam = beam; if (m_word_end_beam > m_global_beam) m_word_end_beam = beam; }
  void set_word_end_beam(float beam) { m_word_end_beam = beam; }
  void set_eq_depth_beam(float beam) { m_eq_depth_beam = beam; }
  void set_eq_word_count_beam(float beam) { m_eq_wc_beam = beam; }
  void set_fan_in_beam(float beam) { m_fan_in_beam = beam; }
  void set_fan_out_beam(float beam) { m_fan_out_beam = beam; }
  void set_state_beam(float beam) { m_state_beam = beam; }

  void set_similar_lm_history_span(int n) { m_similar_lm_hist_span = n; }
  void set_lm_scale(float lm_scale) { m_lm_scale = lm_scale; }
  void set_duration_scale(float dur_scale) { m_duration_scale = dur_scale; }
  void set_transition_scale(float trans_scale) { m_transition_scale = trans_scale; }
  void set_max_num_tokens(int tokens) { m_max_num_tokens = tokens; }
  void set_print_probs(bool value) { m_print_probs = value; }
  void set_print_text_result(int print) { m_print_text_result = print; }
  void set_print_state_segmentation(int print)
  {
    m_print_state_segmentation = print;
    m_keep_state_segmentation = print;
  }
  void set_keep_state_segmentation(int value)
  {
    m_keep_state_segmentation = value;
  }
  void set_verbose(int verbose) { m_verbose = verbose; }
  void set_word_boundary(const std::string &word);
  void set_lm_lookahead(int order) { m_lm_lookahead = order; }
  void set_insertion_penalty(float ip) { m_insertion_penalty = ip; }

  void set_require_sentence_end(bool s) { m_require_sentence_end = s; }

  void set_sentence_boundary(const std::string &start,
                             const std::string &end);

  void set_ngram(TreeGram *ngram);

  /// \brief Sets a finite-state automaton language model.
  void set_fsa_lm(fsalm::LM *lm);

  void set_lookahead_ngram(TreeGram *ngram);
  void set_generate_word_graph(bool value) { m_generate_word_graph = value; }
  void set_use_lm_cache(bool value) { m_use_lm_cache = value; }

  int frame(void) { return m_frame; }

  void write_word_graph(const std::string &file_name);
  void write_word_graph(FILE *file);

  void debug_ensure_all_paths_contain_history(
    TPLexPrefixTree::LMHistory *limit);

private:
  void add_sentence_end_to_hypotheses(void);
  void propagate_tokens(void);
  void update_final_tokens();
  void copy_word_graph_info(TPLexPrefixTree::Token *src_token,
			    TPLexPrefixTree::Token *tgt_token);
  void build_word_graph_aux(TPLexPrefixTree::Token *new_token,
			    TPLexPrefixTree::WordHistory *word_history);
  void build_word_graph(TPLexPrefixTree::Token *new_token);
  void propagate_token(TPLexPrefixTree::Token *token);
  void move_token_to_node(TPLexPrefixTree::Token *token,
                          TPLexPrefixTree::Node *node,
                          float transition_score);
  void prune_tokens(void);

#ifdef PRUNING_MEASUREMENT
  void analyze_tokens(void);
#endif

  TPLexPrefixTree::Token*
  find_similar_fsa_token(int fsa_lm_node, TPLexPrefixTree::Token *token_list);

  TPLexPrefixTree::Token* find_similar_lm_history(
    TPLexPrefixTree::LMHistory *wh, int lm_hist_code,
    TPLexPrefixTree::Token *token_list);
  bool is_similar_lm_history(TPLexPrefixTree::LMHistory *wh1,
                               TPLexPrefixTree::LMHistory *wh2);
  int compute_lm_hist_hash_code(TPLexPrefixTree::LMHistory *wh);
  float compute_lm_log_prob(TPLexPrefixTree::LMHistory *lm_hist);
  float get_lm_score(TPLexPrefixTree::LMHistory *lm_hist,
                     int lm_hist_code);
  float get_lm_lookahead_score(TPLexPrefixTree::LMHistory *lm_hist,
                                TPLexPrefixTree::Node *node, int depth);
  float get_lm_bigram_lookahead(int prev_word_id,
                                TPLexPrefixTree::Node *node, int depth);
  float get_lm_trigram_lookahead(int w1, int w2,
                                 TPLexPrefixTree::Node *node, int depth);

  void clear_active_node_token_lists(void);

  inline float get_token_log_prob(float am_score, float lm_score) {
    return (am_score + m_lm_scale * lm_score); }

  TPLexPrefixTree::Token* acquire_token(void);
  void release_token(TPLexPrefixTree::Token *token);

  void save_token_statistics(int count);
  //void print_token_path(TPLexPrefixTree::PathHistory *hist);

public:

  /** The word graph of best hypotheses created during the recognition. */
  WordGraph word_graph;

private:
  TPLexPrefixTree &m_lexicon;
  TPLexPrefixTree::Node *m_root, *m_start_node;
  Vocabulary &m_vocabulary;
  Acoustics *m_acoustics;

  std::vector<TPLexPrefixTree::Token*> *m_active_token_list;
  std::vector<TPLexPrefixTree::Token*> *m_new_token_list;

  std::vector<TPLexPrefixTree::Token*> *m_word_end_token_list;

  std::vector<TPLexPrefixTree::Token*> m_token_pool;

  std::vector<TPLexPrefixTree::Node*> m_active_node_list;

  class LMLookaheadScoreList {
  public:
    int index;
    std::vector<float> lm_scores;
  };
  HashCache<LMLookaheadScoreList*> lm_lookahead_score_list;

  class LMScoreInfo {
  public:
    float lm_score;
    std::vector<int> lm_hist;
  };
  HashCache<LMScoreInfo*> m_lm_score_cache;

  int m_end_frame;
  int m_frame; // Current frame

  float m_best_log_prob; // The best total_log_prob in active tokens
  float m_worst_log_prob;
  float m_best_we_log_prob;

  struct WordGraphInfo {
    struct Item {
      Item() : lex_node_id(-1), graph_node_id(-1) { }
      int lex_node_id;
      int graph_node_id;
    };
    WordGraphInfo() : frame(-1) { }
    int frame;
    std::vector<Item> items;
  };
  std::vector<WordGraphInfo> m_recent_word_graph_info;
  TPLexPrefixTree::Token *m_best_final_token;

  // Ngram
  TreeGram *m_ngram;
  fsalm::LM *m_fsa_lm;
  std::vector<int> m_lex2lm;
  std::vector<int> m_lex2lookaheadlm;
  TreeGram::Gram m_history_lm; // Temporary variable
  TreeGram *m_lookahead_ngram;

  // Options
  float m_print_probs;
  int m_print_text_result;
  bool m_print_state_segmentation;
  bool m_keep_state_segmentation;
  float m_global_beam;
  float m_word_end_beam;
  int m_similar_lm_hist_span;
  float m_lm_scale;
  float m_duration_scale;
  float m_transition_scale; // Temporary scaling used for self transitions
  int m_max_num_tokens;
  int m_verbose;
  int m_word_boundary_id;
  int m_word_boundary_lm_id;
  int m_lm_lookahead; // 0=none, 1=bigram, 2=trigram
  int m_max_lookahead_score_list_size;
  int m_max_node_lookahead_buffer_size;
  float m_insertion_penalty;

  int m_sentence_start_id;
  int m_sentence_start_lm_id;
  int m_sentence_end_id;
  int m_sentence_end_lm_id;
  bool m_use_sentence_boundary;
  bool m_generate_word_graph;
  bool m_require_sentence_end;
  bool m_use_lm_cache;

  float m_current_glob_beam;
  float m_current_we_beam;
  float m_eq_depth_beam;
  float m_eq_wc_beam;
  float m_fan_in_beam;
  float m_fan_out_beam;
  float m_state_beam;

  int filecount;

  float m_wc_llh[MAX_WC_COUNT];
  float m_depth_llh[MAX_LEX_TREE_DEPTH/2];
  int m_min_word_count;

  float m_fan_in_log_prob;
  float m_fan_out_log_prob;
  float m_fan_out_last_log_prob;

  bool m_lm_lookahead_initialized;

  int lm_la_cache_count[MAX_LEX_TREE_DEPTH];
  int lm_la_cache_miss[MAX_LEX_TREE_DEPTH];
  int lm_la_word_cache_count;
  int lm_la_word_cache_miss;

  // FIXME: remove debug
public:
  void debug_print_best_lm_history();
  void debug_print_token_lm_history(FILE *file, TPLexPrefixTree::Token *token);

};

#endif // TOKENPASSSEARCH_HH
<commit_msg>Added Doxygen comments.<commit_after>#ifndef TOKENPASSSEARCH_HH
#define TOKENPASSSEARCH_HH

#include "fsalm/LM.hh"
#include "WordGraph.hh"
#include "TPLexPrefixTree.hh"
#include "TreeGram.hh"
#include "Acoustics.hh"

#define MAX_WC_COUNT 200
#define MAX_LEX_TREE_DEPTH 60

typedef std::vector<TPLexPrefixTree::LMHistory*> HistoryVector;

class TokenPassSearch {
public:
  TokenPassSearch(TPLexPrefixTree &lex, Vocabulary &vocab,
                  Acoustics *acoustics);

  // Resets search and creates the initial token
  void reset_search(int start_frame);
  void set_end_frame(int end_frame) { m_end_frame = end_frame; }

  // Proceeds decoding one frame
  bool run(void);

  // Print the best path
  void write_word_history(FILE *file = stdout, bool get_best_path = true);
  void print_lm_history(FILE *file = stdout, bool get_best_path = true);
  TPLexPrefixTree::Token *get_best_token();
  void print_state_history(FILE *file = stdout);
  std::string state_history_string();
  void get_state_history(std::vector<TPLexPrefixTree::StateHistory*> &stack);
  void get_path(HistoryVector &vec, bool use_best_token,
                TPLexPrefixTree::LMHistory *limit);

  // Options
  void set_acoustics(Acoustics *acoustics) { m_acoustics = acoustics; }
  void set_global_beam(float beam) { m_global_beam = beam; if (m_word_end_beam > m_global_beam) m_word_end_beam = beam; }
  void set_word_end_beam(float beam) { m_word_end_beam = beam; }
  void set_eq_depth_beam(float beam) { m_eq_depth_beam = beam; }
  void set_eq_word_count_beam(float beam) { m_eq_wc_beam = beam; }
  void set_fan_in_beam(float beam) { m_fan_in_beam = beam; }
  void set_fan_out_beam(float beam) { m_fan_out_beam = beam; }
  void set_state_beam(float beam) { m_state_beam = beam; }

  void set_similar_lm_history_span(int n) { m_similar_lm_hist_span = n; }
  void set_lm_scale(float lm_scale) { m_lm_scale = lm_scale; }
  void set_duration_scale(float dur_scale) { m_duration_scale = dur_scale; }
  void set_transition_scale(float trans_scale) { m_transition_scale = trans_scale; }
  void set_max_num_tokens(int tokens) { m_max_num_tokens = tokens; }
  void set_print_probs(bool value) { m_print_probs = value; }
  void set_print_text_result(int print) { m_print_text_result = print; }
  void set_print_state_segmentation(int print)
  {
    m_print_state_segmentation = print;
    m_keep_state_segmentation = print;
  }
  void set_keep_state_segmentation(int value)
  {
    m_keep_state_segmentation = value;
  }
  void set_verbose(int verbose) { m_verbose = verbose; }
  void set_word_boundary(const std::string &word);
  void set_lm_lookahead(int order) { m_lm_lookahead = order; }
  void set_insertion_penalty(float ip) { m_insertion_penalty = ip; }

  void set_require_sentence_end(bool s) { m_require_sentence_end = s; }

  void set_sentence_boundary(const std::string &start,
                             const std::string &end);

  void set_ngram(TreeGram *ngram);

  /// \brief Sets a finite-state automaton language model.
  void set_fsa_lm(fsalm::LM *lm);

  void set_lookahead_ngram(TreeGram *ngram);
  void set_generate_word_graph(bool value) { m_generate_word_graph = value; }
  void set_use_lm_cache(bool value) { m_use_lm_cache = value; }

  int frame(void) { return m_frame; }

  /// \brief Writes nodes and arcs from word_graph to a Standard Lattice Format
  /// file.
  ///
  void write_word_graph(const std::string &file_name);
  void write_word_graph(FILE *file);

  void debug_ensure_all_paths_contain_history(
    TPLexPrefixTree::LMHistory *limit);

private:
  void add_sentence_end_to_hypotheses(void);
  void propagate_tokens(void);
  void update_final_tokens();
  void copy_word_graph_info(TPLexPrefixTree::Token *src_token,
			    TPLexPrefixTree::Token *tgt_token);
  void build_word_graph_aux(TPLexPrefixTree::Token *new_token,
			    TPLexPrefixTree::WordHistory *word_history);
  void build_word_graph(TPLexPrefixTree::Token *new_token);
  void propagate_token(TPLexPrefixTree::Token *token);
  void move_token_to_node(TPLexPrefixTree::Token *token,
                          TPLexPrefixTree::Node *node,
                          float transition_score);
  void prune_tokens(void);

#ifdef PRUNING_MEASUREMENT
  void analyze_tokens(void);
#endif

  TPLexPrefixTree::Token*
  find_similar_fsa_token(int fsa_lm_node, TPLexPrefixTree::Token *token_list);

  TPLexPrefixTree::Token* find_similar_lm_history(
    TPLexPrefixTree::LMHistory *wh, int lm_hist_code,
    TPLexPrefixTree::Token *token_list);
  bool is_similar_lm_history(TPLexPrefixTree::LMHistory *wh1,
                               TPLexPrefixTree::LMHistory *wh2);
  int compute_lm_hist_hash_code(TPLexPrefixTree::LMHistory *wh);
  float compute_lm_log_prob(TPLexPrefixTree::LMHistory *lm_hist);
  float get_lm_score(TPLexPrefixTree::LMHistory *lm_hist,
                     int lm_hist_code);
  float get_lm_lookahead_score(TPLexPrefixTree::LMHistory *lm_hist,
                                TPLexPrefixTree::Node *node, int depth);
  float get_lm_bigram_lookahead(int prev_word_id,
                                TPLexPrefixTree::Node *node, int depth);
  float get_lm_trigram_lookahead(int w1, int w2,
                                 TPLexPrefixTree::Node *node, int depth);

  void clear_active_node_token_lists(void);

  inline float get_token_log_prob(float am_score, float lm_score) {
    return (am_score + m_lm_scale * lm_score); }

  TPLexPrefixTree::Token* acquire_token(void);
  void release_token(TPLexPrefixTree::Token *token);

  void save_token_statistics(int count);
  //void print_token_path(TPLexPrefixTree::PathHistory *hist);

public:

  /** The word graph of best hypotheses created during the recognition. */
  WordGraph word_graph;

private:
  TPLexPrefixTree &m_lexicon;
  TPLexPrefixTree::Node *m_root, *m_start_node;
  Vocabulary &m_vocabulary;
  Acoustics *m_acoustics;

  std::vector<TPLexPrefixTree::Token*> *m_active_token_list;
  std::vector<TPLexPrefixTree::Token*> *m_new_token_list;

  std::vector<TPLexPrefixTree::Token*> *m_word_end_token_list;

  std::vector<TPLexPrefixTree::Token*> m_token_pool;

  std::vector<TPLexPrefixTree::Node*> m_active_node_list;

  class LMLookaheadScoreList {
  public:
    int index;
    std::vector<float> lm_scores;
  };
  HashCache<LMLookaheadScoreList*> lm_lookahead_score_list;

  class LMScoreInfo {
  public:
    float lm_score;
    std::vector<int> lm_hist;
  };
  HashCache<LMScoreInfo*> m_lm_score_cache;

  int m_end_frame;
  int m_frame; // Current frame

  float m_best_log_prob; // The best total_log_prob in active tokens
  float m_worst_log_prob;
  float m_best_we_log_prob;

  struct WordGraphInfo {
    struct Item {
      Item() : lex_node_id(-1), graph_node_id(-1) { }
      int lex_node_id;
      int graph_node_id;
    };
    WordGraphInfo() : frame(-1) { }
    int frame;
    std::vector<Item> items;
  };
  std::vector<WordGraphInfo> m_recent_word_graph_info;
  TPLexPrefixTree::Token *m_best_final_token;

  // Ngram
  TreeGram *m_ngram;
  fsalm::LM *m_fsa_lm;
  std::vector<int> m_lex2lm;
  std::vector<int> m_lex2lookaheadlm;
  TreeGram::Gram m_history_lm; // Temporary variable
  TreeGram *m_lookahead_ngram;

  // Options
  float m_print_probs;
  int m_print_text_result;
  bool m_print_state_segmentation;
  bool m_keep_state_segmentation;
  float m_global_beam;
  float m_word_end_beam;
  int m_similar_lm_hist_span;
  float m_lm_scale;
  float m_duration_scale;
  float m_transition_scale; // Temporary scaling used for self transitions
  int m_max_num_tokens;
  int m_verbose;
  int m_word_boundary_id;
  int m_word_boundary_lm_id;
  int m_lm_lookahead; // 0=none, 1=bigram, 2=trigram
  int m_max_lookahead_score_list_size;
  int m_max_node_lookahead_buffer_size;
  float m_insertion_penalty;

  int m_sentence_start_id;
  int m_sentence_start_lm_id;
  int m_sentence_end_id;
  int m_sentence_end_lm_id;
  bool m_use_sentence_boundary;
  bool m_generate_word_graph;
  bool m_require_sentence_end;
  bool m_use_lm_cache;

  float m_current_glob_beam;
  float m_current_we_beam;
  float m_eq_depth_beam;
  float m_eq_wc_beam;
  float m_fan_in_beam;
  float m_fan_out_beam;
  float m_state_beam;

  int filecount;

  float m_wc_llh[MAX_WC_COUNT];
  float m_depth_llh[MAX_LEX_TREE_DEPTH/2];
  int m_min_word_count;

  float m_fan_in_log_prob;
  float m_fan_out_log_prob;
  float m_fan_out_last_log_prob;

  bool m_lm_lookahead_initialized;

  int lm_la_cache_count[MAX_LEX_TREE_DEPTH];
  int lm_la_cache_miss[MAX_LEX_TREE_DEPTH];
  int lm_la_word_cache_count;
  int lm_la_word_cache_miss;

  // FIXME: remove debug
public:
  void debug_print_best_lm_history();
  void debug_print_token_lm_history(FILE *file, TPLexPrefixTree::Token *token);

};

#endif // TOKENPASSSEARCH_HH
<|endoftext|>


<commit_before>/*
    This file is part of the kolab resource - the implementation of the
    Kolab storage format. See www.kolab.org for documentation on this.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "resourcekolabbase.h"
#include "kmailconnection.h"

#include <klocale.h>
#include <kstandarddirs.h>
#include <kinputdialog.h>
#include <kurl.h>
#include <ktempfile.h>
#include <kmessagebox.h>
#include <qtextstream.h>
#include <kdebug.h>

using namespace Kolab;

static unsigned int uniquifier = 0;

ResourceKolabBase::ResourceKolabBase( const QCString& objId )
  : mSilent( false )
{
  KGlobal::locale()->insertCatalogue( "kres_kolab" );
  QString uniqueObjId = QString( objId ) + QString::number( uniquifier++ );
  mConnection = new KMailConnection( this, uniqueObjId.utf8() );
}

ResourceKolabBase::~ResourceKolabBase()
{
  delete mConnection;
}

bool ResourceKolabBase::kmailSubresources( QValueList<KMailICalIface::SubResource>& lst,
                                           const QString& contentsType ) const
{
  return mConnection->kmailSubresources( lst, contentsType );
}

bool ResourceKolabBase::kmailIncidencesCount( int &count,
                                              const QString& mimetype,
                                              const QString& resource ) const
{
  return mConnection->kmailIncidencesCount( count, mimetype, resource );
}

bool ResourceKolabBase::kmailIncidences( QMap<Q_UINT32, QString>& lst,
                                         const QString& mimetype,
                                         const QString& resource,
                                         int startIndex,
                                         int nbMessages ) const
{
  return mConnection->kmailIncidences( lst, mimetype, resource, startIndex, nbMessages );
}

bool ResourceKolabBase::kmailGetAttachment( KURL& url, const QString& resource,
                                            Q_UINT32 sernum,
                                            const QString& filename ) const
{
  return mConnection->kmailGetAttachment( url, resource, sernum, filename );
}

bool ResourceKolabBase::kmailDeleteIncidence( const QString& resource,
                                              Q_UINT32 sernum )
{
  return mSilent || mConnection->kmailDeleteIncidence( resource, sernum );
}

static QString plainTextBody()
{
  const char * firstPartTextToTranslate = I18N_NOOP(
    "This is a Kolab Groupware object.\nTo view this object you"
    " will need an email client that can understand the Kolab"
    " Groupware format.\nFor a list of such email clients please"
    " visit\n%1" );
  const char * url = "http://www.kolab.org/kolab2-clients.html";
  QString firstPartTextUntranslated = QString::fromLatin1( firstPartTextToTranslate ).arg( url );
  QString firstPartText = i18n( firstPartTextToTranslate ).arg( url );
  if ( firstPartText != firstPartTextUntranslated ) {
    firstPartText.append("\n\n-----------------------------------------------------\n\n");
    firstPartText.append( firstPartTextUntranslated );
  }
  return firstPartText;
}

bool ResourceKolabBase::kmailUpdate( const QString& resource,
                                     Q_UINT32& sernum,
                                     const QString& xml,
                                     const QString& mimetype,
                                     const QString& subject,
                                     const CustomHeaderMap& _customHeaders,
                                     const QStringList& _attachmentURLs,
                                     const QStringList& _attachmentMimetypes,
                                     const QStringList& _attachmentNames,
                                     const QStringList& deletedAttachments )
{
  if ( mSilent )
    return true;

  // Save the xml file. Will be deleted at the end of this method
  KTempFile file;
  file.setAutoDelete( true );
  QTextStream* stream = file.textStream();
  stream->setEncoding( QTextStream::UnicodeUTF8 );
  *stream << xml;
  file.close();

  // Add the xml file as an attachment
  QStringList attachmentURLs = _attachmentURLs;
  QStringList attachmentMimeTypes = _attachmentMimetypes;
  QStringList attachmentNames = _attachmentNames;
  KURL url;
  url.setPath( file.name() );
  url.setFileEncoding( "UTF-8" );
  attachmentURLs.prepend( url.url() );
  attachmentMimeTypes.prepend( mimetype );
  attachmentNames.prepend( "kolab.xml" );

  QString subj = subject;
  if ( subj.isEmpty() )
    subj = i18n("Internal kolab data: Do not delete this mail.");

  CustomHeaderMap customHeaders( _customHeaders );
  customHeaders.insert( "X-Kolab-Type", mimetype );

  return mConnection->kmailUpdate( resource, sernum, subj, plainTextBody(), customHeaders,
                                   attachmentURLs, attachmentMimeTypes, attachmentNames,
                                   deletedAttachments );
}

QString ResourceKolabBase::configFile( const QString& type ) const
{
  return locateLocal( "config",
                      QString( "kresources/kolab/%1rc" ).arg( type ) );
}

bool ResourceKolabBase::connectToKMail() const
{
  return mConnection->connectToKMail();
}

QString ResourceKolabBase::findWritableResource( const ResourceMap& resources )
{
  // I have to use the label (shown in the dialog) as key here. But given how the
  // label is made up, it should be unique. If it's not, well the dialog would suck anyway...
  QMap<QString, QString> possible;
  QStringList labels;
  ResourceMap::ConstIterator it;
  for ( it = resources.begin(); it != resources.end(); ++it ) {
    if ( it.data().writable() && it.data().active() ) {
      // Writable and active possibility
      possible[ it.data().label() ] = it.key();
    }
  }

  if ( possible.isEmpty() ) { // None found!!
    kdWarning(5650) << "No writable resource found!" << endl;
    KMessageBox::error( 0, i18n( "No writable resource was found, saving will not be possible. Reconfigure KMail first." ) );
    return QString::null;
  }
  if ( possible.count() == 1 )
    // Just one found
    return possible.begin().data(); // yes this is the subresource key, i.e. location

  // Several found, ask the user
  QString chosenLabel = KInputDialog::getItem( i18n( "Select Resource Folder" ),
                                               i18n( "You have more than one writable resource folder. "
                                                     "Please select the one you want to write to." ),
                                               possible.keys() );
  if ( chosenLabel.isEmpty() ) // cancelled
    return QString::null;
  return possible[chosenLabel];
}

<commit_msg>Insert libkcal catalogue - might not be loaded if korganizerpart isn't loaded yet. https://intevation.de/roundup/kolab/issue550<commit_after>/*
    This file is part of the kolab resource - the implementation of the
    Kolab storage format. See www.kolab.org for documentation on this.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "resourcekolabbase.h"
#include "kmailconnection.h"

#include <klocale.h>
#include <kstandarddirs.h>
#include <kinputdialog.h>
#include <kurl.h>
#include <ktempfile.h>
#include <kmessagebox.h>
#include <qtextstream.h>
#include <kdebug.h>

using namespace Kolab;

static unsigned int uniquifier = 0;

ResourceKolabBase::ResourceKolabBase( const QCString& objId )
  : mSilent( false )
{
  KGlobal::locale()->insertCatalogue( "kres_kolab" );
  KGlobal::locale()->insertCatalogue( "libkcal" );
  QString uniqueObjId = QString( objId ) + QString::number( uniquifier++ );
  mConnection = new KMailConnection( this, uniqueObjId.utf8() );
}

ResourceKolabBase::~ResourceKolabBase()
{
  delete mConnection;
}

bool ResourceKolabBase::kmailSubresources( QValueList<KMailICalIface::SubResource>& lst,
                                           const QString& contentsType ) const
{
  return mConnection->kmailSubresources( lst, contentsType );
}

bool ResourceKolabBase::kmailIncidencesCount( int &count,
                                              const QString& mimetype,
                                              const QString& resource ) const
{
  return mConnection->kmailIncidencesCount( count, mimetype, resource );
}

bool ResourceKolabBase::kmailIncidences( QMap<Q_UINT32, QString>& lst,
                                         const QString& mimetype,
                                         const QString& resource,
                                         int startIndex,
                                         int nbMessages ) const
{
  return mConnection->kmailIncidences( lst, mimetype, resource, startIndex, nbMessages );
}

bool ResourceKolabBase::kmailGetAttachment( KURL& url, const QString& resource,
                                            Q_UINT32 sernum,
                                            const QString& filename ) const
{
  return mConnection->kmailGetAttachment( url, resource, sernum, filename );
}

bool ResourceKolabBase::kmailDeleteIncidence( const QString& resource,
                                              Q_UINT32 sernum )
{
  return mSilent || mConnection->kmailDeleteIncidence( resource, sernum );
}

static QString plainTextBody()
{
  const char * firstPartTextToTranslate = I18N_NOOP(
    "This is a Kolab Groupware object.\nTo view this object you"
    " will need an email client that can understand the Kolab"
    " Groupware format.\nFor a list of such email clients please"
    " visit\n%1" );
  const char * url = "http://www.kolab.org/kolab2-clients.html";
  QString firstPartTextUntranslated = QString::fromLatin1( firstPartTextToTranslate ).arg( url );
  QString firstPartText = i18n( firstPartTextToTranslate ).arg( url );
  if ( firstPartText != firstPartTextUntranslated ) {
    firstPartText.append("\n\n-----------------------------------------------------\n\n");
    firstPartText.append( firstPartTextUntranslated );
  }
  return firstPartText;
}

bool ResourceKolabBase::kmailUpdate( const QString& resource,
                                     Q_UINT32& sernum,
                                     const QString& xml,
                                     const QString& mimetype,
                                     const QString& subject,
                                     const CustomHeaderMap& _customHeaders,
                                     const QStringList& _attachmentURLs,
                                     const QStringList& _attachmentMimetypes,
                                     const QStringList& _attachmentNames,
                                     const QStringList& deletedAttachments )
{
  if ( mSilent )
    return true;

  // Save the xml file. Will be deleted at the end of this method
  KTempFile file;
  file.setAutoDelete( true );
  QTextStream* stream = file.textStream();
  stream->setEncoding( QTextStream::UnicodeUTF8 );
  *stream << xml;
  file.close();

  // Add the xml file as an attachment
  QStringList attachmentURLs = _attachmentURLs;
  QStringList attachmentMimeTypes = _attachmentMimetypes;
  QStringList attachmentNames = _attachmentNames;
  KURL url;
  url.setPath( file.name() );
  url.setFileEncoding( "UTF-8" );
  attachmentURLs.prepend( url.url() );
  attachmentMimeTypes.prepend( mimetype );
  attachmentNames.prepend( "kolab.xml" );

  QString subj = subject;
  if ( subj.isEmpty() )
    subj = i18n("Internal kolab data: Do not delete this mail.");

  CustomHeaderMap customHeaders( _customHeaders );
  customHeaders.insert( "X-Kolab-Type", mimetype );

  return mConnection->kmailUpdate( resource, sernum, subj, plainTextBody(), customHeaders,
                                   attachmentURLs, attachmentMimeTypes, attachmentNames,
                                   deletedAttachments );
}

QString ResourceKolabBase::configFile( const QString& type ) const
{
  return locateLocal( "config",
                      QString( "kresources/kolab/%1rc" ).arg( type ) );
}

bool ResourceKolabBase::connectToKMail() const
{
  return mConnection->connectToKMail();
}

QString ResourceKolabBase::findWritableResource( const ResourceMap& resources )
{
  // I have to use the label (shown in the dialog) as key here. But given how the
  // label is made up, it should be unique. If it's not, well the dialog would suck anyway...
  QMap<QString, QString> possible;
  QStringList labels;
  ResourceMap::ConstIterator it;
  for ( it = resources.begin(); it != resources.end(); ++it ) {
    if ( it.data().writable() && it.data().active() ) {
      // Writable and active possibility
      possible[ it.data().label() ] = it.key();
    }
  }

  if ( possible.isEmpty() ) { // None found!!
    kdWarning(5650) << "No writable resource found!" << endl;
    KMessageBox::error( 0, i18n( "No writable resource was found, saving will not be possible. Reconfigure KMail first." ) );
    return QString::null;
  }
  if ( possible.count() == 1 )
    // Just one found
    return possible.begin().data(); // yes this is the subresource key, i.e. location

  // Several found, ask the user
  QString chosenLabel = KInputDialog::getItem( i18n( "Select Resource Folder" ),
                                               i18n( "You have more than one writable resource folder. "
                                                     "Please select the one you want to write to." ),
                                               possible.keys() );
  if ( chosenLabel.isEmpty() ) // cancelled
    return QString::null;
  return possible[chosenLabel];
}

<|endoftext|>


<commit_before>#include <cppcutter.h>
#include "tuishogi.cpp"

namespace tuishogi {

void
test_showState(void)
{
  // Arrange
  using namespace osl;
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  const char* expected = "\
P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\
P2 * -HI *  *  *  *  * -KA * \n\
P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\
P4 *  *  *  *  *  *  *  *  * \n\
P5 *  *  *  *  *  *  *  *  * \n\
P6 *  *  *  *  *  *  *  *  * \n\
P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\
P8 * +KA *  *  *  *  * +HI * \n\
P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\
+\n\
\n";

  // Act
  showState(state);

  std::cout << std::flush;
  std::cout.rdbuf(std_out);

  // TODO assert it as a std::string
  std::string str = string_out.str();
  const char* actual = str.c_str();

  // Assert
  cut_assert_equal_string(expected, actual);
}

void
test_isMated(void)
{
  using namespace osl;
  NumEffectState state((SimpleState(HIRATE)));
  bool mated = isMated(state);
  cut_assert_false(mated);
}

void
test_computerOperate(void)
{
  using namespace osl;
  // TODO cleanup
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  bool ended = computerOperate(state);
  std::cout << std::flush;
  std::cout.rdbuf(std_out);
  cut_assert_false(ended);
}

void
test_playerOperate_valid(void)
{
  using namespace osl;
  // TODO cleanup
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  bool failed = playerOperate(state, "+7776FU");
  std::cout << std::flush;
  std::cout.rdbuf(std_out);
  cut_assert_false(failed);
}

void
test_playerOperate_invalid(void)
{
  using namespace osl;
  // TODO cleanup
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  bool failed = playerOperate(state, "+5251FU");
  std::cout << std::flush;
  std::cout.rdbuf(std_out);
  cut_assert_true(failed);
}

}  // namespace tuishogi
<commit_msg>Add an assertion for playerOperate()<commit_after>#include <cppcutter.h>
#include "tuishogi.cpp"

namespace tuishogi {

void
test_showState(void)
{
  // Arrange
  using namespace osl;
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  const char* expected = "\
P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\
P2 * -HI *  *  *  *  * -KA * \n\
P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\
P4 *  *  *  *  *  *  *  *  * \n\
P5 *  *  *  *  *  *  *  *  * \n\
P6 *  *  *  *  *  *  *  *  * \n\
P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\
P8 * +KA *  *  *  *  * +HI * \n\
P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\
+\n\
\n";

  // Act
  showState(state);

  std::cout << std::flush;
  std::cout.rdbuf(std_out);

  // TODO assert it as a std::string
  std::string str = string_out.str();
  const char* actual = str.c_str();

  // Assert
  cut_assert_equal_string(expected, actual);
}

void
test_isMated(void)
{
  using namespace osl;
  NumEffectState state((SimpleState(HIRATE)));
  bool mated = isMated(state);
  cut_assert_false(mated);
}

void
test_computerOperate(void)
{
  using namespace osl;
  // TODO cleanup
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  bool ended = computerOperate(state);
  std::cout << std::flush;
  std::cout.rdbuf(std_out);
  cut_assert_false(ended);
}

void
test_playerOperate_valid(void)
{
  // Arrange
  using namespace osl;
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  const char* expected = "\
P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\
P2 * -HI *  *  *  *  * -KA * \n\
P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\
P4 *  *  *  *  *  *  *  *  * \n\
P5 *  *  *  *  *  *  *  *  * \n\
P6 *  * +FU *  *  *  *  *  * \n\
P7+FU+FU * +FU+FU+FU+FU+FU+FU\n\
P8 * +KA *  *  *  *  * +HI * \n\
P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\
-\n\
\n\
+7776FU\n";

  // Act
  bool failed = playerOperate(state, "+7776FU");

  std::cout << std::flush;
  std::cout.rdbuf(std_out);

  // TODO assert it as a std::string
  std::string str = string_out.str();
  const char* actual = str.c_str();

  // Assert
  cut_assert_false(failed);
  cut_assert_equal_string(expected, actual);
}

void
test_playerOperate_invalid(void)
{
  using namespace osl;
  // TODO cleanup
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  bool failed = playerOperate(state, "+5251FU");
  std::cout << std::flush;
  std::cout.rdbuf(std_out);
  cut_assert_true(failed);
}

}  // namespace tuishogi
<|endoftext|>