<commit_before>/**************************************************************************
 * Copyright(c) 1998-2017, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/*
 *
 *  AliAnalysisTaskSimSpectraLF.cxx
 *
 *  Minimal analysis task meant to be used for on-the-fly simulations in LEGO trains (for generating light falvor particle pt spectra)
 *
 *  Gyula BENCEDI  <Gyula.Bencedi@cern.ch>, WIGNER RCP
 *
 */

//_____ ROOT headers
#include <TList.h>
#include <TTree.h>
#include <TMath.h>
#include <TFile.h>
#include <TTreeStream.h>
#include "TChain.h"
#include <THnSparse.h>
#include <TDatabasePDG.h>
#include "TObjArray.h"
#include <TClonesArray.h>

//_____ ALIROOT headers
#include "AliAnalysisTask.h"
#include "AliAnalysisFilter.h"
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliESDInputHandler.h"
#include "AliESDEvent.h"
#include "AliLog.h"
#include "AliVParticle.h"
#include "AliStack.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliHeader.h"
#include "AliGenPythiaEventHeader.h"
#include "AliAODInputHandler.h"
#include "AliAODHandler.h"
#include "AliAODMCHeader.h"
#include "AliAODEvent.h"
#include "AliAODMCParticle.h"

//_____ Additional includes
#include "AliVEvent.h"
#include "AliGenEventHeader.h"
// #include "AliAnalysisUtils.h"

//_____ AnalysisTask headers
#include "AliAnalysisTaskSE.h"
#include "AliAnalysisTaskSimSpectraLF.h"

//_____ STL includes
#include <iostream>
using namespace std;

ClassImp( AliAnalysisTaskSimSpectraLF )

//_____________________________________________________________________________

AliAnalysisTaskSimSpectraLF::AliAnalysisTaskSimSpectraLF():
  AliAnalysisTaskSE(),
  fMcEvent(0x0),
  fMcHandler(0x0),
  fStack(0),
  fY(0.5),
  fHistEvt(0x0),
  fHistPart(0x0),
  fListOfObjects(0)
{
  // Default constructor (should not be used)
}

//______________________________________________________________________________

AliAnalysisTaskSimSpectraLF::AliAnalysisTaskSimSpectraLF(const char *name):
  AliAnalysisTaskSE(name),
  fMcEvent(0x0),
  fMcHandler(0x0),
  fStack(0),
  fY(0.5),
  fHistEvt(0x0),
  fHistPart(0x0),
  fListOfObjects(0)
{
  DefineInput( 0, TChain::Class());
  DefineOutput(1, TList::Class() ); // Basic output slot
}

//_____________________________________________________________________________

AliAnalysisTaskSimSpectraLF::~AliAnalysisTaskSimSpectraLF(){
  // Destructor
  // histograms are in the output list and deleted when the output
  // list is deleted by the TSelector dtor

  if (fHistEvt) { delete fHistEvt; fHistEvt=0x0; }
  if (fHistPart) { delete fHistPart; fHistPart=0x0; }
  if (fListOfObjects) { delete fListOfObjects; fListOfObjects=0x0; }
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::UserCreateOutputObjects(){

  // ### Analysis output
  fListOfObjects = new TList();
  fListOfObjects->SetOwner(kTRUE);

  TString pidNames[11] = { "Pion", "Kaon", "Proton", "K0Short", "Lambda", "Xi", "Omega", "Phi", "KStar", "KStarPM", "SigmaZero" };

  // ### Create histograms
  fHistEvt = new TH1I("fHistEvt","fHistEvt",2,0,2) ;
  fHistEvt->GetXaxis()->SetBinLabel(1,"All events");
  fHistEvt->GetXaxis()->SetBinLabel(2,"All particles");
  fHistEvt->Sumw2();
  fListOfObjects->Add(fHistEvt);

  InitHisto<TH1F>("fHistMultPrimary","Multiplicity Primary", 100, 0., 2000., "N_{prim.}", "Entries");
  InitHisto<TH1F>("fHistEta","Eta Distr.", 200, -1., 1., "#eta", "N_{part}");
  InitHisto<TH1F>("fHistY", "Y Distr.", 200, -1., 1., "#it{y}", "N_{part}");

  for(Int_t i=0; i<11; i++)
    InitHisto<TH1F>(Form("fHistPt_%s",pidNames[i].Data()), "Generated #it{p}_{T} distribution",2000,0.,20., "#it{p}_{T} (GeV/#it{c})", "Entries");

  // ### List of outputs
  PostData(1, fListOfObjects);

}

//______________________________________________________________________________

inline void AliAnalysisTaskSimSpectraLF::FillHisto(const char* objkey, Double_t x)
{
  TH1* hTmp = static_cast<TH1*>(fListOfObjects->FindObject(objkey));
  if(!hTmp){
    AliError(Form("Cannot find histogram: %s",objkey)) ;
    return;
  }
  hTmp->Fill(x);
}

//______________________________________________________________________________

template <class T> T* AliAnalysisTaskSimSpectraLF::InitHisto(const char* hname, const char* htitle, Int_t nxbins, Double_t xmin, Double_t xmax, const char* xtitle, const char* ytitle)
{
  T* hTmp = new T(hname, htitle, nxbins, xmin, xmax);
  hTmp->GetXaxis()->SetTitle(xtitle);
  hTmp->GetYaxis()->SetTitle(ytitle);
  hTmp->SetMarkerStyle(kFullCircle);
  hTmp->Sumw2();
  fListOfObjects->Add(hTmp);

  return hTmp;
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::Init(){
  //
  fMcHandler = dynamic_cast<AliInputEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::UserExec(Option_t *){

  // ### Initialize
  Init();

  // ### MC handler
  if(fMcHandler)
    fMcEvent = fMcHandler->MCEvent();
  else { if(fDebug > 1) printf("AliAnalysisTaskSimSpectraLF::Handler() fMcHandler = NULL\n"); return; }

  // ### MC event
  if( !fMcEvent ) { if(fDebug > 1) printf("AliAnalysisTaskSimSpectraLF::UserExec() fMcEvent = NULL \n"); return; }

  fStack = ((AliMCEvent*)fMcEvent)->Stack();
  if (!fStack) {
    Printf("ERROR: Could not retrieve MC stack \n");
    cout << "Name of the file with pb :" <<  fInputHandler->GetTree()->GetCurrentFile()->GetName() << endl;
    return;
  }

  // ### MC event selection
  Bool_t isEventMCSelected = IsMCEventSelected(fMcEvent);
  if( !isEventMCSelected ) return;

  // ### Event and particle selection
  EventSel( fMcEvent );
  ParticleSel( fMcEvent );

  // ### Post data for all output slots
  PostData(1, fListOfObjects);

  return;
}

//______________________________________________________________________________

Bool_t AliAnalysisTaskSimSpectraLF::IsMCEventSelected(TObject* obj){

  Bool_t isSelected = kTRUE;

  AliMCEvent *event = 0x0;
  event = dynamic_cast<AliMCEvent*>(obj);
  if( !event )
    isSelected = kFALSE;

  if( isSelected )
    FillHisto("fHistEvt",0.5);

  return isSelected;
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::EventSel(TObject* obj){

  if( !obj ) return;
  AliMCEvent *event = dynamic_cast<AliMCEvent*>(obj);
  if( !event ) return;

  Int_t multPrimary = fStack->GetNprimary();
  FillHisto("fHistMultPrimary",multPrimary);

}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::ParticleSel(TObject* obj){

  TString pidNames[11] = { "Pion", "Kaon", "Proton", "K0Short", "Lambda", "Xi", "Omega", "Phi", "KStar", "KStarPM", "SigmaZero" };

  if ( !obj ) return;

  AliMCEvent *event = dynamic_cast<AliMCEvent*>(obj);
  if ( !event ) return;

  Bool_t isPrimary[11] = { kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kFALSE, kFALSE, kFALSE, kFALSE };

  Int_t pidCodeMC = 0;
  Double_t ipt = 0.;

  Bool_t isPhysPrim = kFALSE;

  // ### particle loop
  for (Int_t ipart = 0; ipart < event->GetNumberOfTracks(); ipart++) {

    TParticle* mcPart         = 0x0;
    mcPart                    = (TParticle *)event->Particle(ipart);
    if (!mcPart) continue;

    FillHisto("fHistEvt",1.5);

    Int_t pPDG = TMath::Abs(mcPart->GetPdgCode());
    pidCodeMC = GetPidCode(pPDG);

    Bool_t isSelectedPart = kTRUE;
    for(Int_t i=0; i<11; i++)
      if( pidCodeMC == i )
	isSelectedPart = kFALSE;
    if ( isSelectedPart ) continue;

    FillHisto("fHistEta",mcPart->Eta());

    if (!(TMath::Abs(mcPart->Energy()-mcPart->Pz())>0.)) continue;
    Double_t myY = (mcPart->Energy()+mcPart->Pz())/(mcPart->Energy()-mcPart->Pz());
    if( myY <= 0 ) continue;

    Double_t y = 0.5*TMath::Log(myY);

    ipt = mcPart->Pt();

    isPhysPrim = event->IsPhysicalPrimary(ipart);

    for(Int_t i=0; i<11; i++)
    {
      if( pidCodeMC == i && TMath::Abs(y) < fY)
      {
	if( isPrimary[i] == kTRUE && isPhysPrim == kFALSE )
	  continue;

	if(!i) FillHisto("fHistY",y);
	FillHisto(Form("fHistPt_%s",pidNames[i].Data()),ipt);

      }
    }

  } // particle loop
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::Terminate(Option_t*){

  fListOfObjects = dynamic_cast<TList*> (GetOutputData(1));
  if (!fListOfObjects) { Printf("ERROR: Output list not available"); return; }

  return;
}

//_____________________________________________________________________________

Int_t AliAnalysisTaskSimSpectraLF::GetPidCode(Int_t pdgCode) const  {

  Int_t pidCode = 999;

  switch (TMath::Abs(pdgCode)) {
    case 211:
      pidCode = 0; // pion
    break;
    case 321:
      pidCode = 1; // kaon
    break;
    case 2212:
      pidCode = 2; // proton
    break;
    case 310:
      pidCode = 3; // K0s
    break;
    case 3122:
      pidCode = 4; // Lambda
    break;
    case 3312:
      pidCode = 5; // Xi-
    break;
    case 3334:
      pidCode = 6; // Omega-
    break;
    case 333:
      pidCode = 7; // phi(1020)
    break;
    case 313:
      pidCode = 8; // K*(892)0
    break;
    case 323:
      pidCode = 9; // K*(892) +-
    break;
    case 3212:
      pidCode = 10; // Sigma 0
    break;
    default:
    break;
  };

  return pidCode;
}

<commit_msg>Adding particle Lambda(1520)<commit_after>/**************************************************************************
 * Copyright(c) 1998-2017, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/*
 *
 *  AliAnalysisTaskSimSpectraLF.cxx
 *
 *  Minimal analysis task meant to be used for on-the-fly simulations in LEGO trains (for generating light falvor particle pt spectra)
 *
 *  Gyula BENCEDI  <Gyula.Bencedi@cern.ch>, WIGNER RCP
 *
 */

//_____ ROOT headers
#include <TList.h>
#include <TTree.h>
#include <TMath.h>
#include <TFile.h>
#include <TTreeStream.h>
#include "TChain.h"
#include <THnSparse.h>
#include <TDatabasePDG.h>
#include "TObjArray.h"
#include <TClonesArray.h>

//_____ ALIROOT headers
#include "AliAnalysisTask.h"
#include "AliAnalysisFilter.h"
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliESDInputHandler.h"
#include "AliESDEvent.h"
#include "AliLog.h"
#include "AliVParticle.h"
#include "AliStack.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliHeader.h"
#include "AliGenPythiaEventHeader.h"
#include "AliAODInputHandler.h"
#include "AliAODHandler.h"
#include "AliAODMCHeader.h"
#include "AliAODEvent.h"
#include "AliAODMCParticle.h"

//_____ Additional includes
#include "AliVEvent.h"
#include "AliGenEventHeader.h"
// #include "AliAnalysisUtils.h"

//_____ AnalysisTask headers
#include "AliAnalysisTaskSE.h"
#include "AliAnalysisTaskSimSpectraLF.h"

//_____ STL includes
#include <iostream>
using namespace std;

ClassImp( AliAnalysisTaskSimSpectraLF )

//_____________________________________________________________________________

AliAnalysisTaskSimSpectraLF::AliAnalysisTaskSimSpectraLF():
  AliAnalysisTaskSE(),
  fMcEvent(0x0),
  fMcHandler(0x0),
  fStack(0),
  fY(0.5),
  fHistEvt(0x0),
  fHistPart(0x0),
  fListOfObjects(0)
{
  // Default constructor (should not be used)
}

//______________________________________________________________________________

AliAnalysisTaskSimSpectraLF::AliAnalysisTaskSimSpectraLF(const char *name):
  AliAnalysisTaskSE(name),
  fMcEvent(0x0),
  fMcHandler(0x0),
  fStack(0),
  fY(0.5),
  fHistEvt(0x0),
  fHistPart(0x0),
  fListOfObjects(0)
{
  DefineInput( 0, TChain::Class());
  DefineOutput(1, TList::Class() ); // Basic output slot
}

//_____________________________________________________________________________

AliAnalysisTaskSimSpectraLF::~AliAnalysisTaskSimSpectraLF(){
  // Destructor
  // histograms are in the output list and deleted when the output
  // list is deleted by the TSelector dtor

  if (fHistEvt) { delete fHistEvt; fHistEvt=0x0; }
  if (fHistPart) { delete fHistPart; fHistPart=0x0; }
  if (fListOfObjects) { delete fListOfObjects; fListOfObjects=0x0; }
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::UserCreateOutputObjects(){

  // ### Analysis output
  fListOfObjects = new TList();
  fListOfObjects->SetOwner(kTRUE);

  TString pidNames[12] = { "Pion", "Kaon", "Proton", "K0Short", "Lambda", "Xi", "Omega", "Phi", "KStar", "KStarPM", "SigmaZero", "LambdaStar" };

  // ### Create histograms
  fHistEvt = new TH1I("fHistEvt","fHistEvt",2,0,2) ;
  fHistEvt->GetXaxis()->SetBinLabel(1,"All events");
  fHistEvt->GetXaxis()->SetBinLabel(2,"All particles");
  fHistEvt->Sumw2();
  fListOfObjects->Add(fHistEvt);

  InitHisto<TH1F>("fHistMultPrimary","Multiplicity Primary", 100, 0., 2000., "N_{prim.}", "Entries");
  InitHisto<TH1F>("fHistEta","Eta Distr.", 200, -1., 1., "#eta", "N_{part}");
  InitHisto<TH1F>("fHistY", "Y Distr.", 200, -1., 1., "#it{y}", "N_{part}");

  for(Int_t i=0; i<12; i++)
    InitHisto<TH1F>(Form("fHistPt_%s",pidNames[i].Data()), "Generated #it{p}_{T} distribution",2000,0.,20., "#it{p}_{T} (GeV/#it{c})", "Entries");

  // ### List of outputs
  PostData(1, fListOfObjects);

}

//______________________________________________________________________________

inline void AliAnalysisTaskSimSpectraLF::FillHisto(const char* objkey, Double_t x)
{
  TH1* hTmp = static_cast<TH1*>(fListOfObjects->FindObject(objkey));
  if(!hTmp){
    AliError(Form("Cannot find histogram: %s",objkey)) ;
    return;
  }
  hTmp->Fill(x);
}

//______________________________________________________________________________

template <class T> T* AliAnalysisTaskSimSpectraLF::InitHisto(const char* hname, const char* htitle, Int_t nxbins, Double_t xmin, Double_t xmax, const char* xtitle, const char* ytitle)
{
  T* hTmp = new T(hname, htitle, nxbins, xmin, xmax);
  hTmp->GetXaxis()->SetTitle(xtitle);
  hTmp->GetYaxis()->SetTitle(ytitle);
  hTmp->SetMarkerStyle(kFullCircle);
  hTmp->Sumw2();
  fListOfObjects->Add(hTmp);

  return hTmp;
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::Init(){
  //
  fMcHandler = dynamic_cast<AliInputEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler());
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::UserExec(Option_t *){

  // ### Initialize
  Init();

  // ### MC handler
  if(fMcHandler)
    fMcEvent = fMcHandler->MCEvent();
  else { if(fDebug > 1) printf("AliAnalysisTaskSimSpectraLF::Handler() fMcHandler = NULL\n"); return; }

  // ### MC event
  if( !fMcEvent ) { if(fDebug > 1) printf("AliAnalysisTaskSimSpectraLF::UserExec() fMcEvent = NULL \n"); return; }

  fStack = ((AliMCEvent*)fMcEvent)->Stack();
  if (!fStack) {
    Printf("ERROR: Could not retrieve MC stack \n");
    cout << "Name of the file with pb :" <<  fInputHandler->GetTree()->GetCurrentFile()->GetName() << endl;
    return;
  }

  // ### MC event selection
  Bool_t isEventMCSelected = IsMCEventSelected(fMcEvent);
  if( !isEventMCSelected ) return;

  // ### Event and particle selection
  EventSel( fMcEvent );
  ParticleSel( fMcEvent );

  // ### Post data for all output slots
  PostData(1, fListOfObjects);

  return;
}

//______________________________________________________________________________

Bool_t AliAnalysisTaskSimSpectraLF::IsMCEventSelected(TObject* obj){

  Bool_t isSelected = kTRUE;

  AliMCEvent *event = 0x0;
  event = dynamic_cast<AliMCEvent*>(obj);
  if( !event )
    isSelected = kFALSE;

  if( isSelected )
    FillHisto("fHistEvt",0.5);

  return isSelected;
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::EventSel(TObject* obj){

  if( !obj ) return;
  AliMCEvent *event = dynamic_cast<AliMCEvent*>(obj);
  if( !event ) return;

  Int_t multPrimary = fStack->GetNprimary();
  FillHisto("fHistMultPrimary",multPrimary);

}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::ParticleSel(TObject* obj){

  TString pidNames[12] = { "Pion", "Kaon", "Proton", "K0Short", "Lambda", "Xi", "Omega", "Phi", "KStar", "KStarPM", "SigmaZero", "LambdaStar" };

  if ( !obj ) return;

  AliMCEvent *event = dynamic_cast<AliMCEvent*>(obj);
  if ( !event ) return;

  Bool_t isPrimary[12] = { kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kTRUE, kFALSE, kFALSE, kFALSE, kFALSE, kFALSE };

  Int_t pidCodeMC = 0;
  Double_t ipt = 0.;

  Bool_t isPhysPrim = kFALSE;

  // ### particle loop
  for (Int_t ipart = 0; ipart < event->GetNumberOfTracks(); ipart++) {

    TParticle* mcPart         = 0x0;
    mcPart                    = (TParticle *)event->Particle(ipart);
    if (!mcPart) continue;

    FillHisto("fHistEvt",1.5);

    Int_t pPDG = TMath::Abs(mcPart->GetPdgCode());
    pidCodeMC = GetPidCode(pPDG);

    Bool_t isSelectedPart = kTRUE;
    for(Int_t i=0; i<12; i++)
      if( pidCodeMC == i )
	isSelectedPart = kFALSE;
    if ( isSelectedPart ) continue;

    FillHisto("fHistEta",mcPart->Eta());

    if (!(TMath::Abs(mcPart->Energy()-mcPart->Pz())>0.)) continue;
    Double_t myY = (mcPart->Energy()+mcPart->Pz())/(mcPart->Energy()-mcPart->Pz());
    if( myY <= 0 ) continue;

    Double_t y = 0.5*TMath::Log(myY);

    ipt = mcPart->Pt();

    isPhysPrim = event->IsPhysicalPrimary(ipart);

    for(Int_t i=0; i<12; i++)
    {
      if( pidCodeMC == i && TMath::Abs(y) < fY)
      {
	if( isPrimary[i] == kTRUE && isPhysPrim == kFALSE )
	  continue;

	if(!i) FillHisto("fHistY",y);
	FillHisto(Form("fHistPt_%s",pidNames[i].Data()),ipt);

      }
    }

  } // particle loop
}

//______________________________________________________________________________

void AliAnalysisTaskSimSpectraLF::Terminate(Option_t*){

  fListOfObjects = dynamic_cast<TList*> (GetOutputData(1));
  if (!fListOfObjects) { Printf("ERROR: Output list not available"); return; }

  return;
}

//_____________________________________________________________________________

Int_t AliAnalysisTaskSimSpectraLF::GetPidCode(Int_t pdgCode) const  {

  Int_t pidCode = 999;

  switch (TMath::Abs(pdgCode)) {
    case 211:
      pidCode = 0; // pion
    break;
    case 321:
      pidCode = 1; // kaon
    break;
    case 2212:
      pidCode = 2; // proton
    break;
    case 310:
      pidCode = 3; // K0s
    break;
    case 3122:
      pidCode = 4; // Lambda
    break;
    case 3312:
      pidCode = 5; // Xi-
    break;
    case 3334:
      pidCode = 6; // Omega-
    break;
    case 333:
      pidCode = 7; // phi(1020)
    break;
    case 313:
      pidCode = 8; // K*(892)0
    break;
    case 323:
      pidCode = 9; // K*(892) +-
    break;
    case 3212:
      pidCode = 10; // Sigma 0
    break;
    case 3124:
      pidCode = 11; // Lambda(1520)
    break;
    default:
    break;
  };

  return pidCode;
}

<|endoftext|>


<commit_before>/***************************************************************************
 //            Modified by Kishora Nayak - 14/06/2016
 //            Modified by Enrico Fragiacomo - 15/01/2014
 //            Modified by Kunal Garg - 13/05/2018 (kgarg@cern.ch)
               Modified by Sudipan De - 01/04/2019 (sde@cern.ch)
               Modified by Dukhishyam Mallick- 01/04/2019 (dmallick@cern.ch)
	       Modified by Prottay           -31/08/2020
	       //Based on AddAnalysisTaskRsnMini
	       //pPb specific settings from AddTaskKStarPPB.C
	       //
	       // Macro to configure the KStarPlusMinus 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) collision system, whether pp, pPb or PbPb
	       // --
	       // Returns:
	       //  kTRUE  --> initialization successful
	       //  kFALSE --> initialization failed (some config gave errors)
	       //
	       ****************************************************************************/

//enum ERsnCollType_t { kPP=0,      kPPb,      kPbPb};

enum pairYCutSet { kPairDefault,    // USED ONLY FOR pA
    kNegative,       // USED ONLY FOR pA
    kCentral         // USED ONLY FOR pA
};

enum eventCutSet { kEvtDefault=0,
    kNoPileUpCut, //=1
    kDefaultVtx12,//=2
    kDefaultVtx8, //=3
    kDefaultVtx5, //=4
    kMCEvtDefault, //=5
    kSpecial1, //=6
    kSpecial2, //=7
    kNoEvtSel, //=8
    kSpecial3, //=9
    kSpecial4, //=10
    kSpecial5 //=11
};

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

AliRsnMiniAnalysisTask *AddTaskKStarPlusMinusPbPb2018
(
 Bool_t      isMC,
 Bool_t      enableMonitor=kTRUE,
 TString     monitorOpt="PbPb",
 Float_t     piPIDCut = 2.0,
 Float_t     nsigmaTOF = 3.0,
 Float_t     cutV = 10.0,
 Int_t       customQualityCutsID=1,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 Float_t     pi_k0s_PIDCut = 3.0,
 Bool_t      rejectPileUp=kTRUE,
 Bool_t      UseArmentousCut = kFALSE,
 Float_t     ArmentousParameter = 0.2,
 Float_t     massTol = 0.03,
 Float_t     massTolVeto = 0.0043,
 Int_t       tol_switch = 1,
 Double_t    tol_sigma = 6,
 Float_t     pLife = 12,
 Float_t     radiuslow = 5,
 Bool_t      Switch = kTRUE,
 Float_t     k0sDCA = 0.3,
 Float_t     k0sCosPoinAn = 0.99,
 Float_t     k0sDaughDCA = 0.3,
 Int_t       NTPCcluster = 70,
 TString     outNameSuffix = "KStarPlusMinus_V0Mass_Pt",
 Float_t     DCAxy = 0.1,
 Bool_t      enableSys = kFALSE,
 Float_t     crossedRows = 70,
 Int_t       Sys= 0,
 UInt_t      triggerMask=AliVEvent::kINT7,
 Int_t       nmix=10,
 Int_t                    imbin,
 Float_t                  limbin,
 Float_t                  himbin,
 Int_t                    ptbin,
 Float_t                  lptbin,
 Float_t                  hptbin,
 Int_t                    multbin,
 Float_t                  lmultbin,
 Float_t                  hmultbin,
 Bool_t    timeRangeCut      = kTRUE

 )
{
    //-------------------------------------------
    // event cuts
    //-------------------------------------------

  Float_t     maxDiffAngleMixDeg = 20.0;
  Float_t     maxDiffVzMix = 1.0;
  Float_t     maxDiffMultMix = 5.0;
  Bool_t      isPP=0;
  Float_t     v0rapidity= 0.5;
  Float_t     rowsbycluster = 0.8;
  Int_t aodFilterBit=0;

  Int_t       MultBins=aodFilterBit/100;
    //   cout<<"EVENTCUTID is    "<<evtCutSetID<<endl;

    /*if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
    if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
    if(evtCutSetID==eventCutSet::kDefaultVtx5) vtxZcut=5.0; //cm
    if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;
    */

    //if(isMC) rejectPileUp=kFALSE;

    //-------------------------------------------
    //mixing settings
    //-------------------------------------------

    //Int_t       nmix = 10;
    /*if (mixingConfigID == eventMixConfig::kMixDefault) nmix = 10;
    if (mixingConfigID == eventMixConfig::k5Evts)      nmix = 5;
    if (mixingConfigID == eventMixConfig::k5Cent)      maxDiffMultMix = 5;
    */
    //
    // -- INITIALIZATION ----------------------------------------------------------------------------
    // retrieve analysis manager
    //

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

    // create the task and configure
    TString taskName = Form("KStarPlusMinus%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));
        AliRsnMiniAnalysisTask* task = new AliRsnMiniAnalysisTask(taskName.Data(),isMC);
    //    task->SelectCollisionCandidates(AliVEvent::kMB);
	task->UseESDTriggerMask(triggerMask);
       if (isPP)
	 task->UseMultiplicity("QUALITY");
       else
	 task->UseMultiplicity("AliMultSelection_V0M");//Only for RunII

    //  task->UseMultiplicity("AliMultSelection_V0A");

    // task->UseCentrality("V0M");
    // task->UseMultiplicity("");

     // 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
    task->SetUseTimeRangeCut(timeRangeCut);
    task->UseMC(isMC);

    ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %\5.3f",  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

  AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
   cutEventUtils->SetCheckAcceptedMultSelection();
   AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
   eventCuts->AddCut(cutEventUtils);
   eventCuts->SetCutScheme(Form("%s",cutEventUtils->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
    Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
    AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT");
    if(isPP)
    outMult->AddAxis(multID,400,0.5,400.5);
    else outMult->AddAxis(multID,100,0.,100.);

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

    TH2F* hmc=new TH2F("MultiVsCent","", 100,0.,100., 100,0.5,100.5);
    hmc->GetYaxis()->SetTitle("QUALITY");
    task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

    //
    // -- PAIR CUTS (common to all resonances) ------------------------------------------------------
    //    Double_t    minYlab =  -0.465;
    // Double_t    maxYlab =  0.035;

    Double_t    minYlab = -0.5;
    Double_t    maxYlab = 0.5;

    AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
    cutY->SetRangeD(-0.5,0.5);

    AliRsnCutMiniPair* cutV0=new AliRsnCutMiniPair("cutV0", AliRsnCutMiniPair::kContainsV0Daughter);

    AliRsnCutSet* PairCutsSame=new AliRsnCutSet("PairCutsSame",AliRsnTarget::kMother);
    PairCutsSame->AddCut(cutY);
    PairCutsSame->AddCut(cutV0);
    PairCutsSame->SetCutScheme(TString::Format("%s&(!%s)",cutY->GetName(),cutV0->GetName()).Data());
    //note the use of the ! operator in this cut scheme

    AliRsnCutSet* PairCutsMix=new AliRsnCutSet("PairCutsMix",AliRsnTarget::kMother);
    PairCutsMix->AddCut(cutY);
    PairCutsMix->SetCutScheme(cutY->GetName());
    //
    // -- CONFIG ANALYSIS --------------------------------------------------------------------------
    //        gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinuspPbRun2.C");
    //gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusPbPb2018.C");
    //gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusPbPb2018.C");
    //gROOT->LoadMacro("ConfigKStarPlusMinuspPbRun2.C");
    gROOT->LoadMacro("ConfigKStarPlusMinusPbPb2018.C");

     if (isMC) {
       Printf("========================== MC analysis - PID cuts not used");
    } else
       Printf("========================== DATA analysis - PID cuts used");

     //    if(!ConfigKStarPlusMinuspPbRun2(task, isMC, isPP,isGT,isRotate,piPIDCut,nsigmaTOF,customQualityCutsID, cutPiCandidate, pi_k0s_PIDCut, aodFilterBit, enableMonitor, monitorOpt.Data(), massTol, massTolVeto, tol_switch, tol_sigma, pLife, radiuslow, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", PairCutsSame,PairCutsMix, DCAxy, enableSys, crossedRows, rowsbycluster, v0rapidity, Sys)) return 0x0;
     if(!ConfigKStarPlusMinusPbPb2018(task, isMC, piPIDCut,nsigmaTOF,customQualityCutsID, cutPiCandidate, pi_k0s_PIDCut, enableMonitor, monitorOpt.Data(), UseArmentousCut, ArmentousParameter, massTol, massTolVeto, tol_switch, tol_sigma, pLife, radiuslow, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", PairCutsSame,PairCutsMix, DCAxy, enableSys, crossedRows, rowsbycluster, Sys, imbin, limbin, himbin, ptbin, lptbin, hptbin, multbin, lmultbin, hmultbin)) return 0x0;

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

     AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s_%.1f_%.1f_%.1f_%.2f_%.3f_%.f_%.f_%.f_%.1f_%.2f_%.1f_%.3f_%.1f_%.2f", outNameSuffix.Data(),piPIDCut,nsigmaTOF,customQualityCutsID,pi_k0s_PIDCut,massTol,massTolVeto,pLife,radiuslow, k0sDCA,k0sCosPoinAn,k0sDaughDCA, DCAxy, Sys), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);

    mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(task, 1, output);

    return task;
}

<commit_msg>Change path for Config macro for Charged KStar analysis in Pb-Pb<commit_after>/***************************************************************************
 //            Modified by Kishora Nayak - 14/06/2016
 //            Modified by Enrico Fragiacomo - 15/01/2014
 //            Modified by Kunal Garg - 13/05/2018 (kgarg@cern.ch)
               Modified by Sudipan De - 01/04/2019 (sde@cern.ch)
               Modified by Dukhishyam Mallick- 01/04/2019 (dmallick@cern.ch)
	       Modified by Prottay           -31/08/2020
	       //Based on AddAnalysisTaskRsnMini
	       //pPb specific settings from AddTaskKStarPPB.C
	       //
	       // Macro to configure the KStarPlusMinus 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) collision system, whether pp, pPb or PbPb
	       // --
	       // Returns:
	       //  kTRUE  --> initialization successful
	       //  kFALSE --> initialization failed (some config gave errors)
	       //
	       ****************************************************************************/

//enum ERsnCollType_t { kPP=0,      kPPb,      kPbPb};

enum pairYCutSet { kPairDefault,    // USED ONLY FOR pA
    kNegative,       // USED ONLY FOR pA
    kCentral         // USED ONLY FOR pA
};

enum eventCutSet { kEvtDefault=0,
    kNoPileUpCut, //=1
    kDefaultVtx12,//=2
    kDefaultVtx8, //=3
    kDefaultVtx5, //=4
    kMCEvtDefault, //=5
    kSpecial1, //=6
    kSpecial2, //=7
    kNoEvtSel, //=8
    kSpecial3, //=9
    kSpecial4, //=10
    kSpecial5 //=11
};

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

AliRsnMiniAnalysisTask *AddTaskKStarPlusMinusPbPb2018
(
 Bool_t      isMC,
 Bool_t      enableMonitor=kTRUE,
 TString     monitorOpt="PbPb",
 Float_t     piPIDCut = 2.0,
 Float_t     nsigmaTOF = 3.0,
 Float_t     cutV = 10.0,
 Int_t       customQualityCutsID=1,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 Float_t     pi_k0s_PIDCut = 3.0,
 Bool_t      rejectPileUp=kTRUE,
 Bool_t      UseArmentousCut = kFALSE,
 Float_t     ArmentousParameter = 0.2,
 Float_t     massTol = 0.03,
 Float_t     massTolVeto = 0.0043,
 Int_t       tol_switch = 1,
 Double_t    tol_sigma = 6,
 Float_t     pLife = 12,
 Float_t     radiuslow = 5,
 Bool_t      Switch = kTRUE,
 Float_t     k0sDCA = 0.3,
 Float_t     k0sCosPoinAn = 0.99,
 Float_t     k0sDaughDCA = 0.3,
 Int_t       NTPCcluster = 70,
 TString     outNameSuffix = "KStarPlusMinus_V0Mass_Pt",
 Float_t     DCAxy = 0.1,
 Bool_t      enableSys = kFALSE,
 Float_t     crossedRows = 70,
 Int_t       Sys= 0,
 UInt_t      triggerMask=AliVEvent::kINT7,
 Int_t       nmix=10,
 Int_t                    imbin,
 Float_t                  limbin,
 Float_t                  himbin,
 Int_t                    ptbin,
 Float_t                  lptbin,
 Float_t                  hptbin,
 Int_t                    multbin,
 Float_t                  lmultbin,
 Float_t                  hmultbin,
 Bool_t    timeRangeCut      = kTRUE

 )
{
    //-------------------------------------------
    // event cuts
    //-------------------------------------------

  Float_t     maxDiffAngleMixDeg = 20.0;
  Float_t     maxDiffVzMix = 1.0;
  Float_t     maxDiffMultMix = 5.0;
  Bool_t      isPP=0;
  Float_t     v0rapidity= 0.5;
  Float_t     rowsbycluster = 0.8;
  Int_t aodFilterBit=0;

  Int_t       MultBins=aodFilterBit/100;
    //   cout<<"EVENTCUTID is    "<<evtCutSetID<<endl;

    /*if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
    if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
    if(evtCutSetID==eventCutSet::kDefaultVtx5) vtxZcut=5.0; //cm
    if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;
    */

    //if(isMC) rejectPileUp=kFALSE;

    //-------------------------------------------
    //mixing settings
    //-------------------------------------------

    //Int_t       nmix = 10;
    /*if (mixingConfigID == eventMixConfig::kMixDefault) nmix = 10;
    if (mixingConfigID == eventMixConfig::k5Evts)      nmix = 5;
    if (mixingConfigID == eventMixConfig::k5Cent)      maxDiffMultMix = 5;
    */
    //
    // -- INITIALIZATION ----------------------------------------------------------------------------
    // retrieve analysis manager
    //

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

    // create the task and configure
    TString taskName = Form("KStarPlusMinus%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));
        AliRsnMiniAnalysisTask* task = new AliRsnMiniAnalysisTask(taskName.Data(),isMC);
    //    task->SelectCollisionCandidates(AliVEvent::kMB);
	task->UseESDTriggerMask(triggerMask);
       if (isPP)
	 task->UseMultiplicity("QUALITY");
       else
	 task->UseMultiplicity("AliMultSelection_V0M");//Only for RunII

    //  task->UseMultiplicity("AliMultSelection_V0A");

    // task->UseCentrality("V0M");
    // task->UseMultiplicity("");

     // 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
    task->SetUseTimeRangeCut(timeRangeCut);
    task->UseMC(isMC);

    ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %\5.3f",  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

  AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
   cutEventUtils->SetCheckAcceptedMultSelection();
   AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
   eventCuts->AddCut(cutEventUtils);
   eventCuts->SetCutScheme(Form("%s",cutEventUtils->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
    Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
    AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT");
    if(isPP)
    outMult->AddAxis(multID,400,0.5,400.5);
    else outMult->AddAxis(multID,100,0.,100.);

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

    TH2F* hmc=new TH2F("MultiVsCent","", 100,0.,100., 100,0.5,100.5);
    hmc->GetYaxis()->SetTitle("QUALITY");
    task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

    //
    // -- PAIR CUTS (common to all resonances) ------------------------------------------------------
    //    Double_t    minYlab =  -0.465;
    // Double_t    maxYlab =  0.035;

    Double_t    minYlab = -0.5;
    Double_t    maxYlab = 0.5;

    AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
    cutY->SetRangeD(-0.5,0.5);

    AliRsnCutMiniPair* cutV0=new AliRsnCutMiniPair("cutV0", AliRsnCutMiniPair::kContainsV0Daughter);

    AliRsnCutSet* PairCutsSame=new AliRsnCutSet("PairCutsSame",AliRsnTarget::kMother);
    PairCutsSame->AddCut(cutY);
    PairCutsSame->AddCut(cutV0);
    PairCutsSame->SetCutScheme(TString::Format("%s&(!%s)",cutY->GetName(),cutV0->GetName()).Data());
    //note the use of the ! operator in this cut scheme

    AliRsnCutSet* PairCutsMix=new AliRsnCutSet("PairCutsMix",AliRsnTarget::kMother);
    PairCutsMix->AddCut(cutY);
    PairCutsMix->SetCutScheme(cutY->GetName());
    //
    // -- CONFIG ANALYSIS --------------------------------------------------------------------------
    //        gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinuspPbRun2.C");
    //gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusPbPb2018.C");
    gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusPbPb2018.C");
    //gROOT->LoadMacro("ConfigKStarPlusMinuspPbRun2.C");
    //gROOT->LoadMacro("ConfigKStarPlusMinusPbPb2018.C");

     if (isMC) {
       Printf("========================== MC analysis - PID cuts not used");
    } else
       Printf("========================== DATA analysis - PID cuts used");

     //    if(!ConfigKStarPlusMinuspPbRun2(task, isMC, isPP,isGT,isRotate,piPIDCut,nsigmaTOF,customQualityCutsID, cutPiCandidate, pi_k0s_PIDCut, aodFilterBit, enableMonitor, monitorOpt.Data(), massTol, massTolVeto, tol_switch, tol_sigma, pLife, radiuslow, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", PairCutsSame,PairCutsMix, DCAxy, enableSys, crossedRows, rowsbycluster, v0rapidity, Sys)) return 0x0;
     if(!ConfigKStarPlusMinusPbPb2018(task, isMC, piPIDCut,nsigmaTOF,customQualityCutsID, cutPiCandidate, pi_k0s_PIDCut, enableMonitor, monitorOpt.Data(), UseArmentousCut, ArmentousParameter, massTol, massTolVeto, tol_switch, tol_sigma, pLife, radiuslow, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", PairCutsSame,PairCutsMix, DCAxy, enableSys, crossedRows, rowsbycluster, Sys, imbin, limbin, himbin, ptbin, lptbin, hptbin, multbin, lmultbin, hmultbin)) return 0x0;

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

     AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s_%.1f_%.1f_%.1f_%.2f_%.3f_%.f_%.f_%.f_%.1f_%.2f_%.1f_%.3f_%.1f_%.2f", outNameSuffix.Data(),piPIDCut,nsigmaTOF,customQualityCutsID,pi_k0s_PIDCut,massTol,massTolVeto,pLife,radiuslow, k0sDCA,k0sCosPoinAn,k0sDaughDCA, DCAxy, Sys), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);

    mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(task, 1, output);

    return task;
}

<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "VehicleWheelQueryResult.h"

VehicleWheelQueryResult^ VehicleWheelQueryResult::ToManaged(PxWheelQueryResult* unmanaged)
{
	auto managed = gcnew VehicleWheelQueryResult();

	managed->SuspensionLineStart = MathUtil::PxVec3ToVector3(unmanaged->suspLineStart);
	managed->SuspensionLineDirection = MathUtil::PxVec3ToVector3(unmanaged->suspLineDir);
	managed->SuspensionLineLength = unmanaged->suspLineLength;
	managed->IsInAir = unmanaged->isInAir;
	// TODO: Could be NULL
	managed->TireContactActor = ObjectTable::GetObject<Actor^>((intptr_t)unmanaged->tireContactActor);
	// TODO: Could be NULL
	managed->TireContactShape = ObjectTable::GetObject<Shape^>((intptr_t)unmanaged->tireContactShape);
	// TODO: Could be NULL
	managed->TireSurfaceMaterial = ObjectTable::GetObject<Material^>((intptr_t)unmanaged->tireSurfaceMaterial);
	managed->TireSurfaceType = unmanaged->tireSurfaceType;
	managed->TireContactPoint = MathUtil::PxVec3ToVector3(unmanaged->tireContactPoint);
	managed->TireContactNormal = MathUtil::PxVec3ToVector3(unmanaged->tireContactNormal);
	managed->TireFriction = unmanaged->tireFriction;
	managed->SuspensionJounce = unmanaged->suspJounce;
	managed->SuspensionSpringForce = unmanaged->suspSpringForce;
	managed->TireLongitudinalDirection = MathUtil::PxVec3ToVector3(unmanaged->tireLongitudinalDir);
	managed->TireLateralDirection = MathUtil::PxVec3ToVector3(unmanaged->tireLateralDir);
	managed->LongitudinalSlip = unmanaged->longitudinalSlip;
	managed->LateralSlip = unmanaged->lateralSlip;
	managed->SteerAngle = unmanaged->steerAngle;
	managed->LocalPose = MM(&unmanaged->localPose);

	return managed;
}<commit_msg>Null check in VehicleWheelQueryResult<commit_after>#include "StdAfx.h"
#include "VehicleWheelQueryResult.h"

VehicleWheelQueryResult^ VehicleWheelQueryResult::ToManaged(PxWheelQueryResult* unmanaged)
{
	auto managed = gcnew VehicleWheelQueryResult();

	managed->SuspensionLineStart = MathUtil::PxVec3ToVector3(unmanaged->suspLineStart);
	managed->SuspensionLineDirection = MathUtil::PxVec3ToVector3(unmanaged->suspLineDir);
	managed->SuspensionLineLength = unmanaged->suspLineLength;
	managed->IsInAir = unmanaged->isInAir;
	managed->TireContactActor = unmanaged->tireContactActor == NULL ? nullptr : ObjectTable::GetObject<Actor^>((intptr_t)unmanaged->tireContactActor);
	managed->TireContactShape = unmanaged->tireContactShape == NULL ? nullptr : ObjectTable::GetObject<Shape^>((intptr_t)unmanaged->tireContactShape);
	managed->TireSurfaceMaterial = unmanaged->tireSurfaceMaterial == NULL ? nullptr : ObjectTable::GetObject<Material^>((intptr_t)unmanaged->tireSurfaceMaterial);
	managed->TireSurfaceType = unmanaged->tireSurfaceType;
	managed->TireContactPoint = MathUtil::PxVec3ToVector3(unmanaged->tireContactPoint);
	managed->TireContactNormal = MathUtil::PxVec3ToVector3(unmanaged->tireContactNormal);
	managed->TireFriction = unmanaged->tireFriction;
	managed->SuspensionJounce = unmanaged->suspJounce;
	managed->SuspensionSpringForce = unmanaged->suspSpringForce;
	managed->TireLongitudinalDirection = MathUtil::PxVec3ToVector3(unmanaged->tireLongitudinalDir);
	managed->TireLateralDirection = MathUtil::PxVec3ToVector3(unmanaged->tireLateralDir);
	managed->LongitudinalSlip = unmanaged->longitudinalSlip;
	managed->LateralSlip = unmanaged->lateralSlip;
	managed->SteerAngle = unmanaged->steerAngle;
	managed->LocalPose = MM(&unmanaged->localPose);

	return managed;
}<|endoftext|>


<commit_before>/**********************************************************************/
/* Copyright 2014 RCF                                                 */
/*                                                                    */
/* Licensed under the Apache License, Version 2.0 (the "License");    */
/* you may not use this file except in compliance with the License.   */
/* You may obtain a copy of the License at                            */
/*                                                                    */
/*     http://www.apache.org/licenses/LICENSE-2.0                     */
/*                                                                    */
/* Unless required by applicable law or agreed to in writing,         */
/* software distributed under the License is distributed on an        */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,       */
/* either express or implied.                                         */
/* See the License for the specific language governing permissions    */
/* and limitations under the License.                                 */
/**********************************************************************/

#ifndef TCC_GRAPH_ARC_DEFINED
#define TCC_GRAPH_ARC_DEFINED

// Libraries
#include "Vertex.tcc"

namespace graph
{
    template<
        typename Vertex     = graph::Vertex<>,
        typename Properties = no_property,
        typename Directed   = directed
    >class Arc
    {
        private:
            const Vertex *beg_ptr;
            const Vertex *end_ptr;

        public:
            using vertex_type   = Vertex;
            using property_type = Properties;

            property_type properties {};

            explicit
            Arc(const Vertex& beg, const Vertex& end,
                const property_type properties = {})
                : beg_ptr{&beg}, end_ptr{&end},
                  properties{properties} {}

            // Vertex& beg() { return *(this->beg_ptr); }
            // Vertex& end() { return *(this->end_ptr); }

            const Vertex& beg() const { return *(this->beg_ptr); }
            const Vertex& end() const { return *(this->end_ptr); }

            bool operator==(const Arc& a) const
            {
                return this->beg()      == a.beg()
                    && this->end()      == a.end()
                    && this->properties == a.properties;
            }

            bool operator!=(const Arc& a) const
            {
                return !operator==(a);
            }

            friend std::ostream&
            operator<<(std::ostream& os, const Arc& a)
            {
                os << "{ beg:" << a.beg() << ", end:" << a.end();
                os << ", properties:" << a.properties << " }";
                return os;
            }
    };
}

#endif
<commit_msg>Removing useless getter<commit_after>/**********************************************************************/
/* Copyright 2014 RCF                                                 */
/*                                                                    */
/* Licensed under the Apache License, Version 2.0 (the "License");    */
/* you may not use this file except in compliance with the License.   */
/* You may obtain a copy of the License at                            */
/*                                                                    */
/*     http://www.apache.org/licenses/LICENSE-2.0                     */
/*                                                                    */
/* Unless required by applicable law or agreed to in writing,         */
/* software distributed under the License is distributed on an        */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,       */
/* either express or implied.                                         */
/* See the License for the specific language governing permissions    */
/* and limitations under the License.                                 */
/**********************************************************************/

#ifndef TCC_GRAPH_ARC_DEFINED
#define TCC_GRAPH_ARC_DEFINED

// Libraries
#include "Vertex.tcc"

namespace graph
{
    template<
        typename Vertex     = graph::Vertex<>,
        typename Properties = no_property,
        typename Directed   = directed
    >class Arc
    {
        private:
            const Vertex *beg_ptr;
            const Vertex *end_ptr;

        public:
            using vertex_type   = Vertex;
            using property_type = Properties;

            property_type properties {};

            explicit
            Arc(const Vertex& beg, const Vertex& end,
                const property_type properties = {})
                : beg_ptr{&beg}, end_ptr{&end},
                  properties{properties} {}

            const Vertex& beg() const { return *(this->beg_ptr); }
            const Vertex& end() const { return *(this->end_ptr); }

            bool operator==(const Arc& a) const
            {
                return this->beg()      == a.beg()
                    && this->end()      == a.end()
                    && this->properties == a.properties;
            }

            bool operator!=(const Arc& a) const
            {
                return !operator==(a);
            }

            friend std::ostream&
            operator<<(std::ostream& os, const Arc& a)
            {
                os << "{ beg:" << a.beg() << ", end:" << a.end();
                os << ", properties:" << a.properties << " }";
                return os;
            }
    };
}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008, 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/platform/graphics/GlyphPageTreeNode.h"

#include "core/platform/graphics/SimpleFontData.h"

#include "SkPaint.h"
#include "SkTemplates.h"
#include "SkUtils.h"

namespace WebCore {

bool GlyphPage::fill(unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData* fontData)
{
    if (SkUTF16_IsHighSurrogate(buffer[bufferLength-1])) {
        SkDebugf("%s last char is high-surrogate", __FUNCTION__);
        return false;
    }

    SkPaint paint;
    fontData->platformData().setupPaint(&paint);
    paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);

#if OS(WIN)
    // FIXME: For some reason SkAutoSTMalloc fails to link on Windows.
    // SkAutoSTArray works fine though...
    SkAutoSTArray<GlyphPage::size, uint16_t> glyphStorage(length);
#else
    SkAutoSTMalloc<GlyphPage::size, uint16_t> glyphStorage(length);
#endif

    uint16_t* glyphs = glyphStorage.get();
    // textToGlyphs takes a byte count, not a glyph count so we multiply by two.
    unsigned count = paint.textToGlyphs(buffer, bufferLength * 2, glyphs);
    if (count != length) {
        SkDebugf("%s count != length\n", __FUNCTION__);
        return false;
    }

    unsigned allGlyphs = 0; // track if any of the glyphIDs are non-zero
    for (unsigned i = 0; i < length; i++) {
        setGlyphDataForIndex(offset + i, glyphs[i], glyphs[i] ? fontData : NULL);
        allGlyphs |= glyphs[i];
    }

    return allGlyphs != 0;
}

}  // namespace WebCore
<commit_msg>call typeface instead of paint to convert char->glyph<commit_after>/*
 * Copyright (c) 2008, 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/platform/graphics/GlyphPageTreeNode.h"

#include "core/platform/graphics/SimpleFontData.h"

#include "SkPaint.h"
#include "SkTemplates.h"
#include "SkTypeface.h"
#include "SkUtils.h"

namespace WebCore {

bool GlyphPage::fill(unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData* fontData)
{
    if (SkUTF16_IsHighSurrogate(buffer[bufferLength-1])) {
        SkDebugf("%s last char is high-surrogate", __FUNCTION__);
        return false;
    }

#if OS(WIN)
    // FIXME: For some reason SkAutoSTMalloc fails to link on Windows.
    // SkAutoSTArray works fine though...
    SkAutoSTArray<GlyphPage::size, uint16_t> glyphStorage(length);
#else
    SkAutoSTMalloc<GlyphPage::size, uint16_t> glyphStorage(length);
#endif

    uint16_t* glyphs = glyphStorage.get();
    SkTypeface* typeface = fontData->platformData().typeface();
    typeface->charsToGlyphs(buffer, SkTypeface::kUTF16_Encoding, glyphs, length);

    unsigned allGlyphs = 0; // track if any of the glyphIDs are non-zero
    for (unsigned i = 0; i < length; i++) {
        setGlyphDataForIndex(offset + i, glyphs[i], glyphs[i] ? fontData : NULL);
        allGlyphs |= glyphs[i];
    }

    return allGlyphs != 0;
}

}  // namespace WebCore
<|endoftext|>


<commit_before>#include "test_helper.h"
#include "uTensor/loaders/tensorIdxImporter.hpp"

#include <iostream>
using std::cout;
using std::endl;

TensorIdxImporter t_import;
Context ctx;

void test_core_ntoh32(void) {

  uint32_t input = 63;

  uint32_t result = ntoh32(input);

  EXPECT_EQ(result, 1056964608);
}

void test_core_importUchar(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.ubyte_import("/fs/constants/idxImport/uint8_4d_power2.idx");

  double result = sum<unsigned char>(t);
  EXPECT_EQ(result, 4518);
  delete t;
}

void test_core_importShort(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.short_import("/fs/constants/idxImport/int16_4d_power2.idx");

  double result = sum<short>(t);
  EXPECT_EQ(result, 270250);
  delete t;
}

void test_core_importInt(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.int_import("/fs/constants/idxImport/int32_4d_power2.idx");

  double result = sum<int>(t);
  EXPECT_EQ((int)result, 7158278745);
  delete t;
}

void test_core_importFloat(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.float_import("/fs/constants/idxImport/float_4d_power2.idx");

  double result = sum<float>(t);

  DEBUG("***floating point test yielded: %.8e\r\n", (float)result);
  EXPECT_EQ((float)result, -1.0f);
  delete t;
}

// First configure the uTensor test runner
UTENSOR_TEST_CONFIGURE()

// Second declare tests to run
UTENSOR_TEST(core, ntoh32, "test ntoh32")
UTENSOR_TEST(core, importUchar, "Test unsigned char import")
UTENSOR_TEST(core, importShort, "Test short inport")
UTENSOR_TEST(core, importInt, "Test import Int")
UTENSOR_TEST(core, importFloat, "Test import float")

// Third, run like hell
UTENSOR_TEST_RUN()

<commit_msg>Removed Int import test for now<commit_after>#include "test_helper.h"
#include "uTensor/loaders/tensorIdxImporter.hpp"

#include <iostream>
using std::cout;
using std::endl;

TensorIdxImporter t_import;
Context ctx;

void test_core_ntoh32(void) {

  uint32_t input = 63;

  uint32_t result = ntoh32(input);

  EXPECT_EQ(result, 1056964608);
}

void test_core_importUchar(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.ubyte_import("/fs/constants/idxImport/uint8_4d_power2.idx");

  double result = sum<unsigned char>(t);
  EXPECT_EQ(result, 4518);
  delete t;
}

void test_core_importShort(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.short_import("/fs/constants/idxImport/int16_4d_power2.idx");

  double result = sum<short>(t);
  EXPECT_EQ(result, 270250);
  delete t;
}

void test_core_importInt(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.int_import("/fs/constants/idxImport/int32_4d_power2.idx");

  double result = sum<int>(t);
  EXPECT_EQ((int)result, 7158278745);
  delete t;
}

void test_core_importFloat(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.float_import("/fs/constants/idxImport/float_4d_power2.idx");

  double result = sum<float>(t);

  DEBUG("***floating point test yielded: %.8e\r\n", (float)result);
  EXPECT_EQ((float)result, -1.0f);
  delete t;
}

// First configure the uTensor test runner
UTENSOR_TEST_CONFIGURE()

// Second declare tests to run
UTENSOR_TEST(core, ntoh32, "test ntoh32")
UTENSOR_TEST(core, importUchar, "Test unsigned char import")
UTENSOR_TEST(core, importShort, "Test short inport")
//UTENSOR_TEST(core, importInt, "Test import Int")
UTENSOR_TEST(core, importFloat, "Test import float")

// Third, run like hell
UTENSOR_TEST_RUN()

<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/renderer/application_native_module.h"

#include "base/logging.h"
#include "content/public/child/v8_value_converter.h"
#include "content/public/renderer/render_view.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebView.h"

namespace xwalk {
namespace application {

namespace {

// This is the key used in the data object passed to our callbacks to store a
// pointer back to ApplicationNativeModule.
const char* kApplicationNativeModule = "kApplicationNativeModule";

}  // namespace

void ApplicationNativeModule::GetViewByIDCallback(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  info.GetReturnValue().SetUndefined();
  if (info.Length() != 1 || !info[0]->IsInt32())
    return;

  int main_routing_id = info[0]->ToInt32()->Value();
  content::RenderView* render_view =
    content::RenderView::FromRoutingID(main_routing_id);
  if (!render_view)
    return;

  blink::WebView* webview = render_view->GetWebView();
  v8::Handle<v8::Context> context =
    webview->mainFrame()->mainWorldScriptContext();
  v8::Handle<v8::Value> window = context->Global();
  info.GetReturnValue().Set(window);
}

void ApplicationNativeModule::GetCurrentRoutingIDCallback(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  blink::WebLocalFrame* webframe =
    blink::WebLocalFrame::frameForCurrentContext();
  DCHECK(webframe);

  blink::WebView* webview = webframe->view();
  DCHECK(webview);

  content::RenderView* render_view = content::RenderView::FromWebView(webview);
  info.GetReturnValue().Set(render_view->GetRoutingID());
}

ApplicationNativeModule::ApplicationNativeModule() {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::HandleScope handle_scope(isolate);
  v8::Handle<v8::Object> function_data = v8::Object::New(isolate);
  function_data->Set(
      v8::String::NewFromUtf8(isolate, kApplicationNativeModule),
      v8::External::New(isolate, this));

  // Register native function templates to object template here.
  v8::Handle<v8::ObjectTemplate> object_template = v8::ObjectTemplate::New();
  object_template->Set(
      isolate,
      "getViewByID",
      v8::FunctionTemplate::New(isolate,
                                &ApplicationNativeModule::GetViewByIDCallback,
                                function_data));
  object_template->Set(
      isolate,
      "getCurrentRoutingID",
      v8::FunctionTemplate::New(
          isolate,
          &ApplicationNativeModule::GetCurrentRoutingIDCallback,
          function_data));

  function_data_.Reset(isolate, function_data);
  object_template_.Reset(isolate, object_template);
}

ApplicationNativeModule::~ApplicationNativeModule() {
  object_template_.Reset();
  function_data_.Reset();
}

v8::Handle<v8::Object> ApplicationNativeModule::NewInstance() {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::EscapableHandleScope handle_scope(isolate);
  v8::Handle<v8::ObjectTemplate> object_template =
      v8::Local<v8::ObjectTemplate>::New(isolate, object_template_);
  return handle_scope.Escape(object_template->NewInstance());
}

}  // namespace application
}  // namespace xwalk
<commit_msg>application_native_module: Stop using deprecated V8 API.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/renderer/application_native_module.h"

#include "base/logging.h"
#include "content/public/child/v8_value_converter.h"
#include "content/public/renderer/render_view.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebView.h"

namespace xwalk {
namespace application {

namespace {

// This is the key used in the data object passed to our callbacks to store a
// pointer back to ApplicationNativeModule.
const char* kApplicationNativeModule = "kApplicationNativeModule";

}  // namespace

void ApplicationNativeModule::GetViewByIDCallback(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  info.GetReturnValue().SetUndefined();
  if (info.Length() != 1 || !info[0]->IsInt32())
    return;

  int main_routing_id = info[0]->ToInt32(info.GetIsolate())->Value();
  content::RenderView* render_view =
    content::RenderView::FromRoutingID(main_routing_id);
  if (!render_view)
    return;

  blink::WebView* webview = render_view->GetWebView();
  v8::Handle<v8::Context> context =
    webview->mainFrame()->mainWorldScriptContext();
  v8::Handle<v8::Value> window = context->Global();
  info.GetReturnValue().Set(window);
}

void ApplicationNativeModule::GetCurrentRoutingIDCallback(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  blink::WebLocalFrame* webframe =
    blink::WebLocalFrame::frameForCurrentContext();
  DCHECK(webframe);

  blink::WebView* webview = webframe->view();
  DCHECK(webview);

  content::RenderView* render_view = content::RenderView::FromWebView(webview);
  info.GetReturnValue().Set(render_view->GetRoutingID());
}

ApplicationNativeModule::ApplicationNativeModule() {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::HandleScope handle_scope(isolate);
  v8::Handle<v8::Object> function_data = v8::Object::New(isolate);
  function_data->Set(
      v8::String::NewFromUtf8(isolate, kApplicationNativeModule),
      v8::External::New(isolate, this));

  // Register native function templates to object template here.
  v8::Handle<v8::ObjectTemplate> object_template =
      v8::ObjectTemplate::New(isolate);
  object_template->Set(
      isolate,
      "getViewByID",
      v8::FunctionTemplate::New(isolate,
                                &ApplicationNativeModule::GetViewByIDCallback,
                                function_data));
  object_template->Set(
      isolate,
      "getCurrentRoutingID",
      v8::FunctionTemplate::New(
          isolate,
          &ApplicationNativeModule::GetCurrentRoutingIDCallback,
          function_data));

  function_data_.Reset(isolate, function_data);
  object_template_.Reset(isolate, object_template);
}

ApplicationNativeModule::~ApplicationNativeModule() {
  object_template_.Reset();
  function_data_.Reset();
}

v8::Handle<v8::Object> ApplicationNativeModule::NewInstance() {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::EscapableHandleScope handle_scope(isolate);
  v8::Handle<v8::ObjectTemplate> object_template =
      v8::Local<v8::ObjectTemplate>::New(isolate, object_template_);
  return handle_scope.Escape(object_template->NewInstance());
}

}  // namespace application
}  // namespace xwalk
<|endoftext|>


<commit_before>#ifndef OBJ_HPP
#define OBJ_HPP

#include <vector>
#include <memory>
#include <GL/gl3w.h>

namespace Model {
	/*! An enumeration of supported types */
	typedef enum {
		e_el_c=0,  ///< \ref element_t
		e_el_f,    ///< \ref face_t
		e_el_g,    ///< \ref group_t
		e_el_l,    ///< \ref line_t
		e_el_m,    ///< \ref mtllib_t
		e_el_o,    ///< \ref object_t
		e_el_u,    ///< \ref usemtl_t
		e_el_v,    ///< \ref vertex_t
		e_el_vn,   ///< \ref vertex_norm_t
		e_el_vp,   ///< \ref vertex_param_t
		e_el_total ///< The total number of supported types
	} e_el;

	struct obj_t;
	/// The abstract base of each obj element
	template<e_el type>
	struct element_t {
		static constexpr const char *prefix = "";
		virtual ~element_t(void) {}
	};

	/// A comment, used only for storage
	template<> struct element_t<e_el_c> {
		static constexpr const char *prefix = "#";
	};

	/// A set of vertices with or without texture coordinates
	template<> struct element_t<e_el_f> {
		static constexpr const char *prefix = "f";
	};

	/// A collection of faces, lines, and vertices
	template<> struct element_t<e_el_g> {
		static constexpr const char *prefix = "g";
	};

	/// A pair of vertex indices
	template<> struct element_t<e_el_l> {
		static constexpr const char *prefix = "l";
	};

	/// A material library file
	template<> struct element_t<e_el_m> {
		static constexpr const char *prefix = "mtllib";
	};

	/// An object; see \ref group_t
	template<> struct element_t<e_el_o> {
		static constexpr const char *prefix = "o";
	};

	/// A reference to a loaded material
	template<> struct element_t<e_el_u> {
		static constexpr const char *prefix = "usemtl";
	};

	/// A single point, containing at least x, y, z coordinates
	template<> struct element_t<e_el_v> {
		static constexpr const char *prefix = "v";
	};

	/// A normal vector; coordinates x, y, z
	template<> struct element_t<e_el_vn> {
		static constexpr const char *prefix = "vn";
	};

	/// A single point in parameter space; coordinates u[, v [,w]]
	template<> struct element_t<e_el_vp> {
		static constexpr const char *prefix = "vp";
	};

	inline std::ostream& operator<<(std::ostream& lhs, e_el const& rhs) {
		return lhs << std::string(rhs == e_el_c ?
				element_t<e_el_c>::prefix : rhs == e_el_f ?
				element_t<e_el_f>::prefix : rhs == e_el_g ?
				element_t<e_el_g>::prefix : rhs == e_el_l ?
				element_t<e_el_l>::prefix : rhs == e_el_m ?
				element_t<e_el_m>::prefix : rhs == e_el_o ?
				element_t<e_el_o>::prefix : rhs == e_el_u ?
				element_t<e_el_u>::prefix : rhs == e_el_v ?
				element_t<e_el_v>::prefix : rhs == e_el_vn ?
				element_t<e_el_vn>::prefix :
				element_t<e_el_vp>::prefix);
	}

	/// An object
	struct obj_t {
		/*! The enumeration and count of possible states */
		typedef enum {
			e_ok=0,        ///< Parsing status is OK
			e_err_io,      ///< An IO exception has occurred
			e_err_unknown, ///< An unknown exception has occurred
			e_err_total    ///< The total number of statuses
		} e_status;

		static constexpr const unsigned int
			mask_has_floats = (1<<e_el_v) | (1<<e_el_vn) | (1<<e_el_vp),
			mask_has_ints = (1<<e_el_f) | (1<<e_el_l),
			mask_has_strings = (1<<e_el_c) | (1<<e_el_g)
				| (1<<e_el_m) | (1<<e_el_o) | (e_el_u);

		/** Loads an obj file with the given path into a vector of elements
		 * @param fname The path to the obj file
		 * @param elements The destination, a vector of elements
		 * @return e_status_ok (0) if and only if the load was successful
		 */
		static e_status load(const char *fname, obj_t &elements);
		static e_el parse_type(std::string word);
		e_status parse(std::string line, const char *delim = " ");

		std::vector<std::string> strings;
		std::vector<GLint> ints;
		std::vector<GLfloat> floats;
		std::vector<GLuint> nStrings, nInts, nFloats;
		std::vector<e_el> types;
	};

}

#endif
<commit_msg>Fixed bug with printing enums due to non-inline stream insertion<commit_after>#ifndef OBJ_HPP
#define OBJ_HPP

#include <vector>
#include <memory>
#include <GL/gl3w.h>

namespace Model {
	/*! An enumeration of supported types */
	typedef enum {
		e_el_c=0,  ///< \ref element_t
		e_el_f,    ///< \ref face_t
		e_el_g,    ///< \ref group_t
		e_el_l,    ///< \ref line_t
		e_el_m,    ///< \ref mtllib_t
		e_el_o,    ///< \ref object_t
		e_el_u,    ///< \ref usemtl_t
		e_el_v,    ///< \ref vertex_t
		e_el_vn,   ///< \ref vertex_norm_t
		e_el_vp,   ///< \ref vertex_param_t
		e_el_total ///< The total number of supported types
	} e_el;

	/// The abstract base of each obj element
	template<e_el type>
	struct element_t {
		static constexpr const char *prefix = "";
		virtual ~element_t(void) {}
	};

	/// A comment, used only for storage
	template<> struct element_t<e_el_c> {
		static constexpr const char *prefix = "#";
	};

	/// A set of vertices with or without texture coordinates
	template<> struct element_t<e_el_f> {
		static constexpr const char *prefix = "f";
	};

	/// A collection of faces, lines, and vertices
	template<> struct element_t<e_el_g> {
		static constexpr const char *prefix = "g";
	};

	/// A pair of vertex indices
	template<> struct element_t<e_el_l> {
		static constexpr const char *prefix = "l";
	};

	/// A material library file
	template<> struct element_t<e_el_m> {
		static constexpr const char *prefix = "mtllib";
	};

	/// An object; see \ref group_t
	template<> struct element_t<e_el_o> {
		static constexpr const char *prefix = "o";
	};

	/// A reference to a loaded material
	template<> struct element_t<e_el_u> {
		static constexpr const char *prefix = "usemtl";
	};

	/// A single point, containing at least x, y, z coordinates
	template<> struct element_t<e_el_v> {
		static constexpr const char *prefix = "v";
	};

	/// A normal vector; coordinates x, y, z
	template<> struct element_t<e_el_vn> {
		static constexpr const char *prefix = "vn";
	};

	/// A single point in parameter space; coordinates u[, v [,w]]
	template<> struct element_t<e_el_vp> {
		static constexpr const char *prefix = "vp";
	};

	inline std::ostream& operator<<(std::ostream& lhs, e_el const& rhs) {
		return lhs << std::string(rhs == e_el_c ?
				element_t<e_el_c>::prefix : rhs == e_el_f ?
				element_t<e_el_f>::prefix : rhs == e_el_g ?
				element_t<e_el_g>::prefix : rhs == e_el_l ?
				element_t<e_el_l>::prefix : rhs == e_el_m ?
				element_t<e_el_m>::prefix : rhs == e_el_o ?
				element_t<e_el_o>::prefix : rhs == e_el_u ?
				element_t<e_el_u>::prefix : rhs == e_el_v ?
				element_t<e_el_v>::prefix : rhs == e_el_vn ?
				element_t<e_el_vn>::prefix : element_t<e_el_vp>::prefix);
	}

	/// An object
	struct obj_t {
		/*! The enumeration and count of possible states */
		typedef enum {
			e_ok=0,        ///< Parsing status is OK
			e_err_io,      ///< An IO exception has occurred
			e_err_unknown, ///< An unknown exception has occurred
			e_err_total    ///< The total number of statuses
		} e_status;

		static constexpr const unsigned int
			mask_has_floats = (1<<e_el_v) | (1<<e_el_vn) | (1<<e_el_vp),
			mask_has_ints = (1<<e_el_f) | (1<<e_el_l),
			mask_has_strings = (1<<e_el_c) | (1<<e_el_g)
				| (1<<e_el_m) | (1<<e_el_o) | (e_el_u);

		/** Loads an obj file with the given path into a vector of elements
		 * @param fname The path to the obj file
		 * @param elements The destination, a vector of elements
		 * @return e_status_ok (0) if and only if the load was successful
		 */
		static e_status load(const char *fname, obj_t &elements);
		static e_el parse_type(std::string word);
		e_status parse(std::string line, const char *delim = " ");

		std::vector<std::string> strings;
		std::vector<GLint> ints;
		std::vector<GLfloat> floats;
		std::vector<GLuint> nStrings, nInts, nFloats;
		std::vector<e_el> types;
	};

}

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_hoofs/posix_wrapper/named_pipe.hpp"
#include "iceoryx_hoofs/cxx/helplets.hpp"
#include "iceoryx_hoofs/posix_wrapper/posix_call.hpp"

#include <thread>

namespace iox
{
namespace posix
{
constexpr const char NamedPipe::NAMED_PIPE_PREFIX[];
constexpr units::Duration NamedPipe::BLOCKING_TIMEOUT;

NamedPipe::NamedPipe() noexcept
{
    this->m_isInitialized = false;
    this->m_errorValue = IpcChannelError::NOT_INITIALIZED;
}

NamedPipe::NamedPipe(const IpcChannelName_t& name,
                     const IpcChannelSide channelSide,
                     const size_t maxMsgSize,
                     const uint64_t maxMsgNumber) noexcept
{
    if (name.size() + strlen(NAMED_PIPE_PREFIX) > MAX_MESSAGE_SIZE)
    {
        std::cerr << "The named pipe name: \"" << name
                  << "\" is too long. Maxium name length is: " << MAX_MESSAGE_SIZE - strlen(NAMED_PIPE_PREFIX)
                  << std::endl;
        m_isInitialized = false;
        m_errorValue = IpcChannelError::INVALID_CHANNEL_NAME;
        return;
    }

    // leading slash is allowed even though it is not a valid file name
    if (!cxx::isValidFileName(name) && !(!name.empty() && name.c_str()[0] == '/'))
    {
        std::cerr << "The named pipe name: \"" << name << "\" is not a valid file path name." << std::endl;
        m_isInitialized = false;
        m_errorValue = IpcChannelError::INVALID_CHANNEL_NAME;
        return;
    }

    if (maxMsgSize > MAX_MESSAGE_SIZE)
    {
        std::cerr << "A message size of " << maxMsgSize << " exceeds the maximum message size for named pipes of "
                  << MAX_MESSAGE_SIZE << std::endl;
        m_isInitialized = false;
        m_errorValue = IpcChannelError::MAX_MESSAGE_SIZE_EXCEEDED;
        return;
    }

    if (maxMsgNumber > MAX_NUMBER_OF_MESSAGES)
    {
        std::cerr << "A message amount of " << maxMsgNumber
                  << " exceeds the maximum number of messages for named pipes of " << MAX_NUMBER_OF_MESSAGES
                  << std::endl;
        m_isInitialized = false;
        m_errorValue = IpcChannelError::MAX_MESSAGE_SIZE_EXCEEDED;
        return;
    }

    auto sharedMemory = SharedMemoryObject::create(
        convertName(name),
        sizeof(MessageQueue_t) + alignof(MessageQueue_t),
        AccessMode::READ_WRITE,
        (channelSide == IpcChannelSide::SERVER) ? OwnerShip::MINE : OwnerShip::OPEN_EXISTING_SHM,
        iox::posix::SharedMemoryObject::NO_ADDRESS_HINT);

    if (sharedMemory.has_error())
    {
        std::cerr << "Unable to open shared memory: \"" << convertName(name) << "\" for named pipe \"" << name << "\""
                  << std::endl;
        m_isInitialized = false;
        m_errorValue = (channelSide == IpcChannelSide::CLIENT) ? IpcChannelError::NO_SUCH_CHANNEL
                                                               : IpcChannelError::INTERNAL_LOGIC_ERROR;
        return;
    }

    m_sharedMemory.emplace(std::move(sharedMemory.value()));
    m_messages = static_cast<MessageQueue_t*>(m_sharedMemory->getBaseAddress());

    if (channelSide == IpcChannelSide::SERVER)
    {
        new (m_messages) MessageQueue_t();
    }
    m_isInitialized = true;
}

NamedPipe::NamedPipe(NamedPipe&& rhs) noexcept
{
    *this = std::move(rhs);
}

NamedPipe& NamedPipe::operator=(NamedPipe&& rhs) noexcept
{
    if (this != &rhs)
    {
        destroy();
    }
    CreationPattern_t::operator=(std::move(rhs));

    m_sharedMemory = std::move(rhs.m_sharedMemory);
    m_messages = std::move(rhs.m_messages);
    rhs.m_messages = nullptr;

    return *this;
}

NamedPipe::~NamedPipe() noexcept
{
    destroy();
}

IpcChannelName_t NamedPipe::convertName(const IpcChannelName_t& name) noexcept
{
    return IpcChannelName_t(
        cxx::TruncateToCapacity,
        cxx::concatenate(NAMED_PIPE_PREFIX, (name.c_str()[0] == '/') ? *name.substr(1) : name).c_str());
}

cxx::expected<IpcChannelError> NamedPipe::destroy() noexcept
{
    if (m_isInitialized)
    {
        m_isInitialized = false;
        m_errorValue = IpcChannelError::NOT_INITIALIZED;

        m_sharedMemory.reset();
        m_messages = nullptr;
    }
    return cxx::success<>();
}

cxx::expected<bool, IpcChannelError> NamedPipe::isOutdated() noexcept
{
    return cxx::success<bool>(false);
}

cxx::expected<bool, IpcChannelError> NamedPipe::unlinkIfExists(const IpcChannelName_t& name) noexcept
{
    constexpr int ERROR_CODE = -1;
    auto unlinkCall =
        posixCall(shm_unlink)(convertName(name).c_str()).failureReturnValue(ERROR_CODE).ignoreErrnos(ENOENT).evaluate();
    if (!unlinkCall.has_error())
    {
        return cxx::success<bool>(unlinkCall->errnum != ENOENT);
    }
    else
    {
        return cxx::error<IpcChannelError>(IpcChannelError::INTERNAL_LOGIC_ERROR);
    }
}

cxx::expected<IpcChannelError> NamedPipe::send(const std::string& message) const noexcept
{
    return timedSend(message, BLOCKING_TIMEOUT);
}

cxx::expected<IpcChannelError> NamedPipe::timedSend(const std::string& message,
                                                    const units::Duration& timeout) const noexcept
{
    if (!m_isInitialized)
    {
        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);
    }

    if (message.size() > MAX_MESSAGE_SIZE)
    {
        return cxx::error<IpcChannelError>(IpcChannelError::MESSAGE_TOO_LONG);
    }

    units::Duration remainingTime = timeout;
    do
    {
        if (m_messages->tryPush(Message_t(cxx::TruncateToCapacity, message)))
        {
            return cxx::success<>();
        }

        std::this_thread::sleep_for(std::chrono::nanoseconds(CYCLE_TIME.toNanoseconds()));
        remainingTime = remainingTime - CYCLE_TIME;
    } while (remainingTime.toNanoseconds() > 0U);

    return cxx::error<IpcChannelError>(IpcChannelError::TIMEOUT);
}

cxx::expected<std::string, IpcChannelError> NamedPipe::receive() const noexcept
{
    return timedReceive(BLOCKING_TIMEOUT);
}

cxx::expected<std::string, IpcChannelError> NamedPipe::timedReceive(const units::Duration& timeout) const noexcept
{
    if (!m_isInitialized)
    {
        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);
    }

    units::Duration remainingTime = timeout;
    do
    {
        auto message = m_messages->pop();
        if (message.has_value())
        {
            return cxx::success<std::string>(message->c_str());
        }

        std::this_thread::sleep_for(std::chrono::nanoseconds(CYCLE_TIME.toNanoseconds()));
        remainingTime = remainingTime - CYCLE_TIME;
    } while (remainingTime.toNanoseconds() > 0U);

    return cxx::error<IpcChannelError>(IpcChannelError::TIMEOUT);
}

} // namespace posix
} // namespace iox
<commit_msg>iox-#33 discarding result of destroy, fixed constexpr linker issue<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_hoofs/posix_wrapper/named_pipe.hpp"
#include "iceoryx_hoofs/cxx/helplets.hpp"
#include "iceoryx_hoofs/posix_wrapper/posix_call.hpp"

#include <thread>

namespace iox
{
namespace posix
{
constexpr const char NamedPipe::NAMED_PIPE_PREFIX[];
constexpr units::Duration NamedPipe::BLOCKING_TIMEOUT;
constexpr units::Duration NamedPipe::CYCLE_TIME;

NamedPipe::NamedPipe() noexcept
{
    this->m_isInitialized = false;
    this->m_errorValue = IpcChannelError::NOT_INITIALIZED;
}

NamedPipe::NamedPipe(const IpcChannelName_t& name,
                     const IpcChannelSide channelSide,
                     const size_t maxMsgSize,
                     const uint64_t maxMsgNumber) noexcept
{
    if (name.size() + strlen(NAMED_PIPE_PREFIX) > MAX_MESSAGE_SIZE)
    {
        std::cerr << "The named pipe name: \"" << name
                  << "\" is too long. Maxium name length is: " << MAX_MESSAGE_SIZE - strlen(NAMED_PIPE_PREFIX)
                  << std::endl;
        m_isInitialized = false;
        m_errorValue = IpcChannelError::INVALID_CHANNEL_NAME;
        return;
    }

    // leading slash is allowed even though it is not a valid file name
    if (!cxx::isValidFileName(name) && !(!name.empty() && name.c_str()[0] == '/'))
    {
        std::cerr << "The named pipe name: \"" << name << "\" is not a valid file path name." << std::endl;
        m_isInitialized = false;
        m_errorValue = IpcChannelError::INVALID_CHANNEL_NAME;
        return;
    }

    if (maxMsgSize > MAX_MESSAGE_SIZE)
    {
        std::cerr << "A message size of " << maxMsgSize << " exceeds the maximum message size for named pipes of "
                  << MAX_MESSAGE_SIZE << std::endl;
        m_isInitialized = false;
        m_errorValue = IpcChannelError::MAX_MESSAGE_SIZE_EXCEEDED;
        return;
    }

    if (maxMsgNumber > MAX_NUMBER_OF_MESSAGES)
    {
        std::cerr << "A message amount of " << maxMsgNumber
                  << " exceeds the maximum number of messages for named pipes of " << MAX_NUMBER_OF_MESSAGES
                  << std::endl;
        m_isInitialized = false;
        m_errorValue = IpcChannelError::MAX_MESSAGE_SIZE_EXCEEDED;
        return;
    }

    auto sharedMemory = SharedMemoryObject::create(
        convertName(name),
        sizeof(MessageQueue_t) + alignof(MessageQueue_t),
        AccessMode::READ_WRITE,
        (channelSide == IpcChannelSide::SERVER) ? OwnerShip::MINE : OwnerShip::OPEN_EXISTING_SHM,
        iox::posix::SharedMemoryObject::NO_ADDRESS_HINT);

    if (sharedMemory.has_error())
    {
        std::cerr << "Unable to open shared memory: \"" << convertName(name) << "\" for named pipe \"" << name << "\""
                  << std::endl;
        m_isInitialized = false;
        m_errorValue = (channelSide == IpcChannelSide::CLIENT) ? IpcChannelError::NO_SUCH_CHANNEL
                                                               : IpcChannelError::INTERNAL_LOGIC_ERROR;
        return;
    }

    m_sharedMemory.emplace(std::move(sharedMemory.value()));
    m_messages = static_cast<MessageQueue_t*>(m_sharedMemory->getBaseAddress());

    if (channelSide == IpcChannelSide::SERVER)
    {
        new (m_messages) MessageQueue_t();
    }
    m_isInitialized = true;
}

NamedPipe::NamedPipe(NamedPipe&& rhs) noexcept
{
    *this = std::move(rhs);
}

NamedPipe& NamedPipe::operator=(NamedPipe&& rhs) noexcept
{
    if (this != &rhs)
    {
        IOX_DISCARD_RESULT(destroy());
    }
    CreationPattern_t::operator=(std::move(rhs));

    m_sharedMemory = std::move(rhs.m_sharedMemory);
    m_messages = std::move(rhs.m_messages);
    rhs.m_messages = nullptr;

    return *this;
}

NamedPipe::~NamedPipe() noexcept
{
    IOX_DISCARD_RESULT(destroy());
}

IpcChannelName_t NamedPipe::convertName(const IpcChannelName_t& name) noexcept
{
    return IpcChannelName_t(
        cxx::TruncateToCapacity,
        cxx::concatenate(NAMED_PIPE_PREFIX, (name.c_str()[0] == '/') ? *name.substr(1) : name).c_str());
}

cxx::expected<IpcChannelError> NamedPipe::destroy() noexcept
{
    if (m_isInitialized)
    {
        m_isInitialized = false;
        m_errorValue = IpcChannelError::NOT_INITIALIZED;

        m_sharedMemory.reset();
        m_messages = nullptr;
    }
    return cxx::success<>();
}

cxx::expected<bool, IpcChannelError> NamedPipe::isOutdated() noexcept
{
    return cxx::success<bool>(false);
}

cxx::expected<bool, IpcChannelError> NamedPipe::unlinkIfExists(const IpcChannelName_t& name) noexcept
{
    constexpr int ERROR_CODE = -1;
    auto unlinkCall =
        posixCall(shm_unlink)(convertName(name).c_str()).failureReturnValue(ERROR_CODE).ignoreErrnos(ENOENT).evaluate();
    if (!unlinkCall.has_error())
    {
        return cxx::success<bool>(unlinkCall->errnum != ENOENT);
    }
    else
    {
        return cxx::error<IpcChannelError>(IpcChannelError::INTERNAL_LOGIC_ERROR);
    }
}

cxx::expected<IpcChannelError> NamedPipe::send(const std::string& message) const noexcept
{
    return timedSend(message, BLOCKING_TIMEOUT);
}

cxx::expected<IpcChannelError> NamedPipe::timedSend(const std::string& message,
                                                    const units::Duration& timeout) const noexcept
{
    if (!m_isInitialized)
    {
        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);
    }

    if (message.size() > MAX_MESSAGE_SIZE)
    {
        return cxx::error<IpcChannelError>(IpcChannelError::MESSAGE_TOO_LONG);
    }

    units::Duration remainingTime = timeout;
    do
    {
        if (m_messages->tryPush(Message_t(cxx::TruncateToCapacity, message)))
        {
            return cxx::success<>();
        }

        std::this_thread::sleep_for(std::chrono::nanoseconds(CYCLE_TIME.toNanoseconds()));
        remainingTime = remainingTime - CYCLE_TIME;
    } while (remainingTime.toNanoseconds() > 0U);

    return cxx::error<IpcChannelError>(IpcChannelError::TIMEOUT);
}

cxx::expected<std::string, IpcChannelError> NamedPipe::receive() const noexcept
{
    return timedReceive(BLOCKING_TIMEOUT);
}

cxx::expected<std::string, IpcChannelError> NamedPipe::timedReceive(const units::Duration& timeout) const noexcept
{
    if (!m_isInitialized)
    {
        return cxx::error<IpcChannelError>(IpcChannelError::NOT_INITIALIZED);
    }

    units::Duration remainingTime = timeout;
    do
    {
        auto message = m_messages->pop();
        if (message.has_value())
        {
            return cxx::success<std::string>(message->c_str());
        }

        std::this_thread::sleep_for(std::chrono::nanoseconds(CYCLE_TIME.toNanoseconds()));
        remainingTime = remainingTime - CYCLE_TIME;
    } while (remainingTime.toNanoseconds() > 0U);

    return cxx::error<IpcChannelError>(IpcChannelError::TIMEOUT);
}

} // namespace posix
} // namespace iox
<|endoftext|>