<commit_before>// $Id: trajectoryFile.C,v 1.3 2000/12/19 15:22:58 anker Exp $

#include <BALL/FORMAT/trajectoryFile.h>

using namespace std;

namespace BALL
{

	TrajectoryFile::TrajectoryFile
		()
		throw()
		:	File()
	{
	}

	TrajectoryFile::TrajectoryFile
		(const TrajectoryFile& file)
		throw()
		:	File(file)
	{
	}

	TrajectoryFile::TrajectoryFile
		(const String& filename, File::OpenMode open_mode)
		throw()
		: File(filename, open_mode)
	{
	}

	TrajectoryFile::~TrajectoryFile
		()
		throw()
	{
		clear();
	}

	const TrajectoryFile& TrajectoryFile::operator =
		(const TrajectoryFile& file)
		throw()
	{
		File::operator = (file);

		return *this;
	}

	void TrajectoryFile::clear()
		throw()
	{
		File::clear();
	}

	bool TrajectoryFile::operator ==
		(const TrajectoryFile& file) const
		throw()
	{
		return File::operator == (file);
	}

	bool TrajectoryFile::readHeader()
		throw()
	{
		Log.error() << "TrajectoryFile::readHeader(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::updateHeader(const SnapShotManager& /* manager */)
		throw()
	{
		Log.error() << "TrajectoryFile::updateHeader(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::writeHeader()
		throw()
	{
		Log.error() << "TrajectoryFile::writeHeader(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::read(SnapShotManager& /* manager */)
		throw(Exception::NotImplemented)
	{
		Log.error() << "TrajectoryFile::read(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::write(const SnapShotManager& /* manager */)
		throw(Exception::NotImplemented)
	{
		Log.error() << "TrajectoryFile::write(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::append(const SnapShot& /* snapshot */)
		throw()
	{
		Log.error() << "TrajectoryFile::append(): "
			<< "This method should not be called" << endl;
		return false;
	}

} // namespace BALL
<commit_msg>removed: updateHeader() added: read(SnapShot&), flushToDisk(const vector<SnapShot>&), getNumberOfSnapShots()<commit_after>// $Id: trajectoryFile.C,v 1.4 2001/03/11 19:41:03 anker Exp $

#include <BALL/FORMAT/trajectoryFile.h>

using namespace std;

namespace BALL
{

	TrajectoryFile::TrajectoryFile
		()
		throw()
		:	File()
	{
	}

	TrajectoryFile::TrajectoryFile
		(const TrajectoryFile& file)
		throw()
		:	File(file)
	{
	}

	TrajectoryFile::TrajectoryFile
		(const String& filename, File::OpenMode open_mode)
		throw()
		: File(filename, open_mode)
	{
	}

	TrajectoryFile::~TrajectoryFile
		()
		throw()
	{
		clear();
	}

	const TrajectoryFile& TrajectoryFile::operator =
		(const TrajectoryFile& file)
		throw()
	{
		File::operator = (file);

		return *this;
	}

	void TrajectoryFile::clear()
		throw()
	{
		File::clear();
	}

	bool TrajectoryFile::operator ==
		(const TrajectoryFile& file) const
		throw()
	{
		return File::operator == (file);
	}

	bool TrajectoryFile::readHeader()
		throw()
	{
		Log.error() << "TrajectoryFile::readHeader(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::writeHeader()
		throw()
	{
		Log.error() << "TrajectoryFile::writeHeader(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::read(SnapShotManager& /* manager */)
		throw(Exception::NotImplemented)
	{
		Log.error() << "TrajectoryFile::read(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::write(const SnapShotManager& /* manager */)
		throw(Exception::NotImplemented)
	{
		Log.error() << "TrajectoryFile::write(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::append(const SnapShot& /* snapshot */)
		throw()
	{
		Log.error() << "TrajectoryFile::append(): "
			<< "This method should not be called" << endl;
		return false;
	}

	bool TrajectoryFile::read(SnapShot& /* snapshot */)
		throw()
	{
		Log.error() << "TrajectoryFile::read(): "
			<< "This method should not be called" << endl;
		return false;
	}

	Size TrajectoryFile::getNumberOfSnapShots() const
		throw()
	{
		return number_of_snapshots_;
	}

	bool TrajectoryFile::flushToDisk(const ::std::vector<SnapShot> /* buffer */)
		throw()
	{
		Log.error() << "TrajectoryFile::flushToDisk(): "
			<< "This method should not be called" << endl;
		return false;
	}

} // namespace BALL
<|endoftext|>


<commit_before>

AliAnalysisTaskESDfilter *AddTaskESDFilter(Bool_t useKineFilter=kTRUE,
                                           Bool_t writeMuonAOD=kFALSE,
                                           Bool_t writeDimuonAOD=kFALSE,
					   Bool_t usePhysicsSelection=kFALSE,
					   Bool_t useCentralityTask=kFALSE)
{
// Creates a filter task and adds it to the analysis manager.

   // Get the pointer to the existing analysis manager via the static access method.
   //==============================================================================
   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddTaskESDFilter", "No analysis manager to connect to.");
      return NULL;
   }

   // This task requires an ESD input handler and an AOD output handler.
   // Check this using the analysis manager.
   //===============================================================================
   TString type = mgr->GetInputEventHandler()->GetDataType();
   if (!type.Contains("ESD")) {
      ::Error("AddTaskESDFilter", "ESD filtering task needs the manager to have an ESD input handler.");
      return NULL;
   }
   // Check if AOD output handler exist.
   AliAODHandler *aod_h = (AliAODHandler*)mgr->GetOutputEventHandler();
   if (!aod_h) {
      ::Error("AddTaskESDFilter", "ESD filtering task needs the manager to have an AOD output handler.");
      return NULL;
   }
   // Check if MC handler is connected in case kine filter requested
   AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();
   if (!mcH && useKineFilter) {
      ::Error("AddTaskESDFilter", "No MC handler connected while kine filtering requested");
      return NULL;
   }

   // Create the task, add it to the manager and configure it.
   //===========================================================================
   // Barrel tracks filter
   AliAnalysisTaskESDfilter *esdfilter = new AliAnalysisTaskESDfilter("ESD Filter");

   // Make the AOD a little bit lighter and filtering faster

   esdfilter->DisableCascades();
   //   esdfilter->DisableV0s();
   esdfilter->DisableKinks();
   //   esdfilter->DisableTracks();
   esdfilter->DisablePmdClusters();
   //   esdfilter->DisableCaloClusters();
   //   esdfilter->DisableCells();
   esdfilter->DisableTracklets();
   esdfilter->SetWriteHybridGlobalConstrainedOnly(kTRUE);

   AliAnalysisTaskAODCentralityMaker* ctask = 0;
   if (useCentralityTask) {
       ctask = new AliAnalysisTaskAODCentralityMaker("AODCentralityMaker");
       ctask->SetDeltaAODFileName("AliAODCentrality.root");
       mgr->AddTask(ctask);
   }

   mgr->AddTask(esdfilter);
   // Muons
   //   AliAnalysisTaskESDMuonFilter *esdmuonfilter = new AliAnalysisTaskESDMuonFilter("ESD Muon Filter");
   //   mgr->AddTask(esdmuonfilter);
   if(usePhysicsSelection){
     esdfilter->SelectCollisionCandidates(AliVEvent::kAny);
     //     esdmuonfilter->SelectCollisionCandidates(AliVEvent::kAny);
   }

   // Filtering of MC particles (decays conversions etc)
   // this task has to go AFTER all other filter tasks
   // since it fills the AODMC array with all
   // selected MC Particles, only this way we have the
   // AODMCparticle information available for following tasks
   AliAnalysisTaskMCParticleFilter *kinefilter = 0;
   if (useKineFilter) {
      kinefilter = new AliAnalysisTaskMCParticleFilter("Particle Kine Filter");
      if(usePhysicsSelection)kinefilter->SelectCollisionCandidates(AliVEvent::kAny);
      mgr->AddTask(kinefilter);
   }

   // Cuts on primary tracks
   AliESDtrackCuts* esdTrackCutsL = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();

   // ITS stand-alone tracks
   AliESDtrackCuts* esdTrackCutsITSsa = new AliESDtrackCuts("ITS stand-alone Track Cuts", "ESD Track Cuts");
   esdTrackCutsITSsa->SetRequireITSStandAlone(kTRUE);

   // Pixel OR necessary for the electrons
   AliESDtrackCuts *itsStrong = new AliESDtrackCuts("ITSorSPD", "pixel requirement for ITS");
   itsStrong->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny);

   // PID for the electrons
   AliESDpidCuts *electronID = new AliESDpidCuts("Electrons", "Electron PID cuts");
   electronID->SetTPCnSigmaCut(AliPID::kElectron, 3.);

   // tighter cuts on primary particles for high pT tracks
   // take the standard cuts, which include already
   // ITSrefit and use only primaries...

   // ITS cuts for new jet analysis
   gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/CreateTrackCutsPWG4.C");
   AliESDtrackCuts* esdTrackCutsHG0 = CreateTrackCutsPWG4(10001001);

   // throw out tracks with too low number of clusters in
   // the first pass (be consistent with TPC only tracks)
   // N.B. the number off crossed rows still acts on the tracks after
   // all iterations if we require tpc standalone, number of clusters
   // and chi2 TPC cuts act on track after the first iteration
   //   esdTrackCutsH0->SetRequireTPCStandAlone(kTRUE);
   //   esdTrackCutsH0->SetMinNClustersTPC(80); // <--- first pass

   // the complement to the one with SPD requirement
   AliESDtrackCuts* esdTrackCutsHG1 = CreateTrackCutsPWG4(10011001);

   // the tracks that must not be taken pass this cut and
   // non HGC1 and HG
   AliESDtrackCuts* esdTrackCutsHG2 = CreateTrackCutsPWG4(10021001);

   // standard cuts also used in R_AA analysis
   gROOT->LoadMacro("$ALICE_ROOT/PWG0/dNdPt/macros/CreatedNdPtTrackCuts.C");
   AliESDtrackCuts* esdTrackCutsH2 = CreatedNdPtTrackCuts(200);
   esdTrackCutsH2->SetMaxChi2PerClusterITS(36.);
   esdTrackCutsH2->SetPtRange(0.15,1E10);

   // TPC only tracks
   AliESDtrackCuts* esdTrackCutsGCOnly = CreateTrackCutsPWG4(10041001);

   // Compose the filter
   AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter");
   // 1, 1<<0
   trackFilter->AddCuts(esdTrackCutsL);
   // 2 1<<1
   trackFilter->AddCuts(esdTrackCutsITSsa);
   // 4 1<<2
   trackFilter->AddCuts(itsStrong);
   itsStrong->SetFilterMask(1);        // AND with Standard track cuts
   // 8 1<<3
   trackFilter->AddCuts(electronID);
   electronID->SetFilterMask(4);       // AND with Pixel Cuts
   // 16 1<<4
   trackFilter->AddCuts(esdTrackCutsHG0);
   // 32 1<<5
   trackFilter->AddCuts(esdTrackCutsHG1);
   // 64 1<<6
   trackFilter->AddCuts(esdTrackCutsHG2);
   // 128 1<<7
   trackFilter->AddCuts(esdTrackCutsHG0); // add once more for tpc only tracks
   // 256 1<<8
   trackFilter->AddCuts(esdTrackCutsGCOnly);
   // 512 1<<9
   trackFilter->AddCuts(esdTrackCutsHG1); // add once more for tpc only tracks
   // 512 1<<10
   trackFilter->AddCuts(esdTrackCutsH2); // add r_aa cuts

   esdfilter->SetGlobalConstrainedFilterMask(1<<8|1<<9); // these tracks are written out as global constrained tracks
   esdfilter->SetHybridFilterMaskGlobalConstrainedGlobal((1<<4)); // these normal global tracks will be marked as hybrid

   // Filter with cuts on V0s
   AliESDv0Cuts*   esdV0Cuts = new AliESDv0Cuts("Standard V0 Cuts pp", "ESD V0 Cuts");
   esdV0Cuts->SetMinRadius(0.2);
   esdV0Cuts->SetMaxRadius(200);
   esdV0Cuts->SetMinDcaPosToVertex(0.05);
   esdV0Cuts->SetMinDcaNegToVertex(0.05);
   esdV0Cuts->SetMaxDcaV0Daughters(1.5);
   esdV0Cuts->SetMinCosinePointingAngle(0.99);
   AliAnalysisFilter* v0Filter = new AliAnalysisFilter("v0Filter");
   v0Filter->AddCuts(esdV0Cuts);

   esdfilter->SetTrackFilter(trackFilter);
   esdfilter->SetV0Filter(v0Filter);

   // Enable writing of Muon AODs
   //   esdmuonfilter->SetWriteMuonAOD(writeMuonAOD);

   // Enable writing of Dimuon AODs
   //   esdmuonfilter->SetWriteDimuonAOD(writeDimuonAOD);

   // Create ONLY the output containers for the data produced by the task.
   // Get and connect other common input/output containers via the manager as below
   //==============================================================================

   mgr->ConnectInput  (esdfilter,  0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput (esdfilter,  0, mgr->GetCommonOutputContainer());

   //   mgr->ConnectInput  (esdmuonfilter, 0, mgr->GetCommonInputContainer());
   if (useKineFilter) {
      mgr->ConnectInput  (kinefilter,  0, mgr->GetCommonInputContainer());
      mgr->ConnectOutput (kinefilter,  0, mgr->GetCommonOutputContainer());
      AliAnalysisDataContainer *coutputEx = mgr->CreateContainer("cFilterList", TList::Class(),
								   AliAnalysisManager::kOutputContainer,"pyxsec_hists.root");
      mgr->ConnectOutput (kinefilter,  1,coutputEx);
   }
  if (useCentralityTask) {
       mgr->ConnectInput (ctask, 0, mgr->GetCommonInputContainer());
       mgr->ConnectOutput(ctask, 0, mgr->GetCommonOutputContainer());
   }

   return esdfilter;
 }

<commit_msg>adding TPC cosntrained tracks back in for comparison<commit_after>

AliAnalysisTaskESDfilter *AddTaskESDFilter(Bool_t useKineFilter=kTRUE,
                                           Bool_t writeMuonAOD=kFALSE,
                                           Bool_t writeDimuonAOD=kFALSE,
					   Bool_t usePhysicsSelection=kFALSE,
					   Bool_t useCentralityTask=kFALSE)
{
// Creates a filter task and adds it to the analysis manager.

   // Get the pointer to the existing analysis manager via the static access method.
   //==============================================================================
   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddTaskESDFilter", "No analysis manager to connect to.");
      return NULL;
   }

   // This task requires an ESD input handler and an AOD output handler.
   // Check this using the analysis manager.
   //===============================================================================
   TString type = mgr->GetInputEventHandler()->GetDataType();
   if (!type.Contains("ESD")) {
      ::Error("AddTaskESDFilter", "ESD filtering task needs the manager to have an ESD input handler.");
      return NULL;
   }
   // Check if AOD output handler exist.
   AliAODHandler *aod_h = (AliAODHandler*)mgr->GetOutputEventHandler();
   if (!aod_h) {
      ::Error("AddTaskESDFilter", "ESD filtering task needs the manager to have an AOD output handler.");
      return NULL;
   }
   // Check if MC handler is connected in case kine filter requested
   AliMCEventHandler *mcH = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();
   if (!mcH && useKineFilter) {
      ::Error("AddTaskESDFilter", "No MC handler connected while kine filtering requested");
      return NULL;
   }

   // Create the task, add it to the manager and configure it.
   //===========================================================================
   // Barrel tracks filter
   AliAnalysisTaskESDfilter *esdfilter = new AliAnalysisTaskESDfilter("ESD Filter");

   // Make the AOD a little bit lighter and filtering faster

   esdfilter->DisableCascades();
   //   esdfilter->DisableV0s();
   esdfilter->DisableKinks();
   //   esdfilter->DisableTracks();
   esdfilter->DisablePmdClusters();
   //   esdfilter->DisableCaloClusters();
   //   esdfilter->DisableCells();
   esdfilter->DisableTracklets();
   esdfilter->SetWriteHybridGlobalConstrainedOnly(kTRUE);

   AliAnalysisTaskAODCentralityMaker* ctask = 0;
   if (useCentralityTask) {
       ctask = new AliAnalysisTaskAODCentralityMaker("AODCentralityMaker");
       ctask->SetDeltaAODFileName("AliAODCentrality.root");
       mgr->AddTask(ctask);
   }

   mgr->AddTask(esdfilter);
   // Muons
   //   AliAnalysisTaskESDMuonFilter *esdmuonfilter = new AliAnalysisTaskESDMuonFilter("ESD Muon Filter");
   //   mgr->AddTask(esdmuonfilter);
   if(usePhysicsSelection){
     esdfilter->SelectCollisionCandidates(AliVEvent::kAny);
     //     esdmuonfilter->SelectCollisionCandidates(AliVEvent::kAny);
   }

   // Filtering of MC particles (decays conversions etc)
   // this task has to go AFTER all other filter tasks
   // since it fills the AODMC array with all
   // selected MC Particles, only this way we have the
   // AODMCparticle information available for following tasks
   AliAnalysisTaskMCParticleFilter *kinefilter = 0;
   if (useKineFilter) {
      kinefilter = new AliAnalysisTaskMCParticleFilter("Particle Kine Filter");
      if(usePhysicsSelection)kinefilter->SelectCollisionCandidates(AliVEvent::kAny);
      mgr->AddTask(kinefilter);
   }

   // Cuts on primary tracks
   AliESDtrackCuts* esdTrackCutsL = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();

   // ITS stand-alone tracks
   AliESDtrackCuts* esdTrackCutsITSsa = new AliESDtrackCuts("ITS stand-alone Track Cuts", "ESD Track Cuts");
   esdTrackCutsITSsa->SetRequireITSStandAlone(kTRUE);

   // Pixel OR necessary for the electrons
   AliESDtrackCuts *itsStrong = new AliESDtrackCuts("ITSorSPD", "pixel requirement for ITS");
   itsStrong->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny);

   // PID for the electrons
   AliESDpidCuts *electronID = new AliESDpidCuts("Electrons", "Electron PID cuts");
   electronID->SetTPCnSigmaCut(AliPID::kElectron, 3.);

   // tighter cuts on primary particles for high pT tracks
   // take the standard cuts, which include already
   // ITSrefit and use only primaries...

   // ITS cuts for new jet analysis
   gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/CreateTrackCutsPWG4.C");
   AliESDtrackCuts* esdTrackCutsHG0 = CreateTrackCutsPWG4(10001004);

   // throw out tracks with too low number of clusters in
   // the first pass (be consistent with TPC only tracks)
   // N.B. the number off crossed rows still acts on the tracks after
   // all iterations if we require tpc standalone, number of clusters
   // and chi2 TPC cuts act on track after the first iteration
   //   esdTrackCutsH0->SetRequireTPCStandAlone(kTRUE);
   //   esdTrackCutsH0->SetMinNClustersTPC(80); // <--- first pass

   // the complement to the one with SPD requirement
   AliESDtrackCuts* esdTrackCutsHG1 = CreateTrackCutsPWG4(10011004);

   // the tracks that must not be taken pass this cut and
   // non HGC1 and HG
   AliESDtrackCuts* esdTrackCutsHG2 = CreateTrackCutsPWG4(10021004);

   // standard cuts also used in R_AA analysis
   gROOT->LoadMacro("$ALICE_ROOT/PWG0/dNdPt/macros/CreatedNdPtTrackCuts.C");
   AliESDtrackCuts* esdTrackCutsH2 = CreatedNdPtTrackCuts(200);
   esdTrackCutsH2->SetMaxChi2PerClusterITS(36.);
   esdTrackCutsH2->SetPtRange(0.15,1E10);

   AliESDtrackCuts* esdTrackCutsGCOnly = CreateTrackCutsPWG4(10041004);

   // TPC only tracks
   AliESDtrackCuts* esdTrackCutsTPCCOnly = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
   esdTrackCutsTPCCOnly->SetMinNClustersTPC(70);

   // Compose the filter
   AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter");
   // 1, 1<<0
   trackFilter->AddCuts(esdTrackCutsL);
   // 2 1<<1
   trackFilter->AddCuts(esdTrackCutsITSsa);
   // 4 1<<2
   trackFilter->AddCuts(itsStrong);
   itsStrong->SetFilterMask(1);        // AND with Standard track cuts
   // 8 1<<3
   trackFilter->AddCuts(electronID);
   electronID->SetFilterMask(4);       // AND with Pixel Cuts
   // 16 1<<4
   trackFilter->AddCuts(esdTrackCutsHG0);
   // 32 1<<5
   trackFilter->AddCuts(esdTrackCutsHG1);
   // 64 1<<6
   trackFilter->AddCuts(esdTrackCutsHG2);
   // 128 1<<7
   trackFilter->AddCuts(esdTrackCutsHG0); // add once more for tpc only tracks
   // 256 1<<8
   trackFilter->AddCuts(esdTrackCutsGCOnly);
   // 512 1<<9
   trackFilter->AddCuts(esdTrackCutsHG1); // add once more for tpc only tracks
   // 1024 1<<10
   trackFilter->AddCuts(esdTrackCutsH2); // add r_aa cuts
   // 2048 1<<11
   trackFilter->AddCuts(esdTrackCutsTPCCOnly); // add QM TPC only track cuts

   esdfilter->SetGlobalConstrainedFilterMask(1<<8|1<<9); // these tracks are written out as global constrained tracks
   esdfilter->SetHybridFilterMaskGlobalConstrainedGlobal((1<<4)); // these normal global tracks will be marked as hybrid

   esdfilter->SetTPCConstrainedFilterMask(1<<11); // these tracks are written out as global constrained tracks

   // Filter with cuts on V0s
   AliESDv0Cuts*   esdV0Cuts = new AliESDv0Cuts("Standard V0 Cuts pp", "ESD V0 Cuts");
   esdV0Cuts->SetMinRadius(0.2);
   esdV0Cuts->SetMaxRadius(200);
   esdV0Cuts->SetMinDcaPosToVertex(0.05);
   esdV0Cuts->SetMinDcaNegToVertex(0.05);
   esdV0Cuts->SetMaxDcaV0Daughters(1.5);
   esdV0Cuts->SetMinCosinePointingAngle(0.99);
   AliAnalysisFilter* v0Filter = new AliAnalysisFilter("v0Filter");
   v0Filter->AddCuts(esdV0Cuts);

   esdfilter->SetTrackFilter(trackFilter);
   esdfilter->SetV0Filter(v0Filter);

   // Enable writing of Muon AODs
   //   esdmuonfilter->SetWriteMuonAOD(writeMuonAOD);

   // Enable writing of Dimuon AODs
   //   esdmuonfilter->SetWriteDimuonAOD(writeDimuonAOD);

   // Create ONLY the output containers for the data produced by the task.
   // Get and connect other common input/output containers via the manager as below
   //==============================================================================

   mgr->ConnectInput  (esdfilter,  0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput (esdfilter,  0, mgr->GetCommonOutputContainer());

   //   mgr->ConnectInput  (esdmuonfilter, 0, mgr->GetCommonInputContainer());
   if (useKineFilter) {
      mgr->ConnectInput  (kinefilter,  0, mgr->GetCommonInputContainer());
      mgr->ConnectOutput (kinefilter,  0, mgr->GetCommonOutputContainer());
      AliAnalysisDataContainer *coutputEx = mgr->CreateContainer("cFilterList", TList::Class(),
								   AliAnalysisManager::kOutputContainer,"pyxsec_hists.root");
      mgr->ConnectOutput (kinefilter,  1,coutputEx);
   }
  if (useCentralityTask) {
       mgr->ConnectInput (ctask, 0, mgr->GetCommonInputContainer());
       mgr->ConnectOutput(ctask, 0, mgr->GetCommonOutputContainer());
   }

   return esdfilter;
 }

<|endoftext|>


<commit_before>#include "manual_recorder.h"

namespace lightstep {
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
ManualRecorder::ManualRecorder(Logger& logger, LightStepTracerOptions options,
                               std::unique_ptr<AsyncTransporter>&& transporter)
    : logger_{logger},
      options_{std::move(options)},
      builder_{options_.access_token, options_.tags},
      transporter_{std::move(transporter)} {
  // If no MetricsObserver was provided, use a default one that does nothing.
  if (options_.metrics_observer == nullptr) {
    options_.metrics_observer.reset(new MetricsObserver{});
  }
}

//------------------------------------------------------------------------------
// RecordSpan
//------------------------------------------------------------------------------
void ManualRecorder::RecordSpan(collector::Span&& span) noexcept try {
  if (builder_.num_pending_spans() >= options_.max_buffered_spans.value()) {
    // If there's no report in flight, flush the recoder. We can only get
    // here if max_buffered_spans was dynamically decreased.
    //
    // Otherwise, drop the span.
    if (!IsReportInProgress()) {
      FlushOne();
    } else {
      dropped_spans_++;
      options_.metrics_observer->OnSpansDropped(1);
      return;
    }
  }
  builder_.AddSpan(std::move(span));
  if (builder_.num_pending_spans() >= options_.max_buffered_spans.value()) {
    FlushOne();
  }
} catch (const std::exception& e) {
  logger_.Error("Failed to record span: ", e.what());
}

//------------------------------------------------------------------------------
// IsReportInProgress
//------------------------------------------------------------------------------
bool ManualRecorder::IsReportInProgress() const noexcept {
  return encoding_seqno_ > 1 + flushed_seqno_;
}

//------------------------------------------------------------------------------
// FlushOne
//------------------------------------------------------------------------------
bool ManualRecorder::FlushOne() noexcept try {
  options_.metrics_observer->OnFlush();

  // If a report is currently in flight, do nothing; and if there are any
  // pending spans, then the flush is considered to have failed.
  if (IsReportInProgress()) {
    return builder_.num_pending_spans() == 0;
  }

  saved_pending_spans_ = builder_.num_pending_spans();
  if (saved_pending_spans_ == 0) {
    return true;
  }
  saved_dropped_spans_ = dropped_spans_;
  builder_.set_pending_client_dropped_spans(dropped_spans_);
  dropped_spans_ = 0;
  std::swap(builder_.pending(), active_request_);
  ++encoding_seqno_;
  transporter_->Send(active_request_, active_response_, *this);
  return true;
} catch (const std::exception& e) {
  logger_.Error("Failed to Flush: ", e.what());
  options_.metrics_observer->OnSpansDropped(saved_pending_spans_);
  dropped_spans_ += saved_pending_spans_;
  active_request_.Clear();
  return false;
}

//------------------------------------------------------------------------------
// FlushWithTimeout
//------------------------------------------------------------------------------
bool ManualRecorder::FlushWithTimeout(
    std::chrono::system_clock::duration /*timeout*/) noexcept {
  return FlushOne();
}

//------------------------------------------------------------------------------
// OnSuccess
//------------------------------------------------------------------------------
void ManualRecorder::OnSuccess() noexcept {
  ++flushed_seqno_;
  active_request_.Clear();
  options_.metrics_observer->OnSpansSent(saved_pending_spans_);
  if (options_.verbose) {
    logger_.Info(R"(Report: resp=")", active_response_.ShortDebugString(),
                 R"(")");
  }
}

//------------------------------------------------------------------------------
// OnFailure
//------------------------------------------------------------------------------
void ManualRecorder::OnFailure(std::error_code error) noexcept {
  ++flushed_seqno_;
  active_request_.Clear();
  options_.metrics_observer->OnSpansDropped(saved_pending_spans_);
  dropped_spans_ += saved_dropped_spans_ + saved_pending_spans_;
  logger_.Error("Failed to send report: ", error.message());
}
}  // namespace lightstep
<commit_msg>Cache max_buffered_spans value.<commit_after>#include "manual_recorder.h"

namespace lightstep {
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
ManualRecorder::ManualRecorder(Logger& logger, LightStepTracerOptions options,
                               std::unique_ptr<AsyncTransporter>&& transporter)
    : logger_{logger},
      options_{std::move(options)},
      builder_{options_.access_token, options_.tags},
      transporter_{std::move(transporter)} {
  // If no MetricsObserver was provided, use a default one that does nothing.
  if (options_.metrics_observer == nullptr) {
    options_.metrics_observer.reset(new MetricsObserver{});
  }
}

//------------------------------------------------------------------------------
// RecordSpan
//------------------------------------------------------------------------------
void ManualRecorder::RecordSpan(collector::Span&& span) noexcept try {
  auto max_buffered_spans = options_.max_buffered_spans.value();
  if (builder_.num_pending_spans() >= max_buffered_spans) {
    // If there's no report in flight, flush the recoder. We can only get
    // here if max_buffered_spans was dynamically decreased.
    //
    // Otherwise, drop the span.
    if (!IsReportInProgress()) {
      FlushOne();
    } else {
      dropped_spans_++;
      options_.metrics_observer->OnSpansDropped(1);
      return;
    }
  }
  builder_.AddSpan(std::move(span));
  if (builder_.num_pending_spans() >= max_buffered_spans) {
    FlushOne();
  }
} catch (const std::exception& e) {
  logger_.Error("Failed to record span: ", e.what());
}

//------------------------------------------------------------------------------
// IsReportInProgress
//------------------------------------------------------------------------------
bool ManualRecorder::IsReportInProgress() const noexcept {
  return encoding_seqno_ > 1 + flushed_seqno_;
}

//------------------------------------------------------------------------------
// FlushOne
//------------------------------------------------------------------------------
bool ManualRecorder::FlushOne() noexcept try {
  options_.metrics_observer->OnFlush();

  // If a report is currently in flight, do nothing; and if there are any
  // pending spans, then the flush is considered to have failed.
  if (IsReportInProgress()) {
    return builder_.num_pending_spans() == 0;
  }

  saved_pending_spans_ = builder_.num_pending_spans();
  if (saved_pending_spans_ == 0) {
    return true;
  }
  saved_dropped_spans_ = dropped_spans_;
  builder_.set_pending_client_dropped_spans(dropped_spans_);
  dropped_spans_ = 0;
  std::swap(builder_.pending(), active_request_);
  ++encoding_seqno_;
  transporter_->Send(active_request_, active_response_, *this);
  return true;
} catch (const std::exception& e) {
  logger_.Error("Failed to Flush: ", e.what());
  options_.metrics_observer->OnSpansDropped(saved_pending_spans_);
  dropped_spans_ += saved_pending_spans_;
  active_request_.Clear();
  return false;
}

//------------------------------------------------------------------------------
// FlushWithTimeout
//------------------------------------------------------------------------------
bool ManualRecorder::FlushWithTimeout(
    std::chrono::system_clock::duration /*timeout*/) noexcept {
  return FlushOne();
}

//------------------------------------------------------------------------------
// OnSuccess
//------------------------------------------------------------------------------
void ManualRecorder::OnSuccess() noexcept {
  ++flushed_seqno_;
  active_request_.Clear();
  options_.metrics_observer->OnSpansSent(saved_pending_spans_);
  if (options_.verbose) {
    logger_.Info(R"(Report: resp=")", active_response_.ShortDebugString(),
                 R"(")");
  }
}

//------------------------------------------------------------------------------
// OnFailure
//------------------------------------------------------------------------------
void ManualRecorder::OnFailure(std::error_code error) noexcept {
  ++flushed_seqno_;
  active_request_.Clear();
  options_.metrics_observer->OnSpansDropped(saved_pending_spans_);
  dropped_spans_ += saved_dropped_spans_ + saved_pending_spans_;
  logger_.Error("Failed to send report: ", error.message());
}
}  // namespace lightstep
<|endoftext|>


<commit_before>/*******************************************************************************
 * c7a/core/reduce_pre_table.hpp
 *
 * Hash table with support for reduce and partitions.
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_CORE_REDUCE_PRE_TABLE_HEADER
#define C7A_CORE_REDUCE_PRE_TABLE_HEADER

#include <c7a/api/function_traits.hpp>
#include <c7a/data/data_manager.hpp>

#include <map>
#include <iostream>
#include <c7a/common/logger.hpp>
#include <string>
#include <vector>
#include <stdexcept>
#include <array>
#include <deque>
#include <utility>

namespace c7a {
namespace core {
template <typename KeyExtractor, typename ReduceFunction, typename EmitterFunction>
class ReducePreTable
{
    static const bool debug = true;

    using key_t = typename FunctionTraits<KeyExtractor>::result_type;

    using value_t = typename FunctionTraits<ReduceFunction>::result_type;

protected:
    struct hash_result
    {
        //! which partition number the item belongs to.
        size_t partition_id;
        //! index within the partition's sub-hashtable of this item
        size_t partition_offset;
        //! index within the whole hashtable
        size_t global_index;

        hash_result(key_t v, const ReducePreTable& ht) {
            size_t hashed = std::hash<key_t>() (v);

            // partition idx
            partition_offset = hashed % ht.num_buckets_per_partition_;

            // partition id
            partition_id = hashed % ht.num_partitions_;

            // global idx
            global_index = partition_id * ht.num_buckets_per_partition_ + partition_offset;
        }
    };

    struct bucket_block {
        // TODO(ms): use a new/delete here instead of a vector, it is faster.
        std::vector<std::pair<key_t, value_t> > items;

        bucket_block                            * next = NULL;

        bucket_block(const ReducePreTable& ht) {
            items.reserve(ht.bucket_block_size_);
        }
    };

public:
    ReducePreTable(size_t num_partitions, size_t num_buckets_init_scale, size_t num_buckets_resize_scale,
                   size_t max_num_items_per_bucket, size_t max_num_items_table,
                   KeyExtractor key_extractor, ReduceFunction reduce_function,
                   std::vector<EmitterFunction> emit)
        : num_partitions_(num_partitions),
          num_buckets_init_scale_(num_buckets_init_scale),
          num_buckets_resize_scale_(num_buckets_resize_scale),
          max_num_items_per_bucket_(max_num_items_per_bucket),
          max_num_items_table_(max_num_items_table),
          key_extractor_(key_extractor),
          reduce_function_(reduce_function),
          emit_(emit) {
        init();
    }

    ReducePreTable(size_t partition_size, KeyExtractor key_extractor,
                   ReduceFunction reduce_function, std::vector<EmitterFunction> emit)
        : num_partitions_(partition_size),
          key_extractor_(key_extractor),
          reduce_function_(reduce_function),
          emit_(emit) {
        init();
    }

    ~ReducePreTable() { }

    void init() {
        sLOG << "creating reducePreTable with" << emit_.size() << "output emiters";
        for (auto& e : emit_)
            emit_stats_.push_back(0);

        num_buckets_ = num_partitions_ * num_buckets_init_scale_;
        if (num_partitions_ > num_buckets_ &&
            num_buckets_ % num_partitions_ != 0) {
            throw std::invalid_argument("partition_size must be less than or equal to num_buckets "
                                        "AND partition_size a divider of num_buckets");
        }
        num_buckets_per_partition_ = num_buckets_ / num_partitions_;

        vector_.resize(num_buckets_, NULL);
        items_per_partition_.resize(num_partitions_, 0);
    }

    /*!
     * Inserts a key/value pair.
     *
     * Optionally, this may be reduce using the reduce function
     * in case the key already exists.
     */
    void Insert(const value_t& p) {
        key_t key = key_extractor_(p);

        hash_result h(key, *this);

        LOG << "key: " << key << " to bucket id: " << h.global_index;

        size_t num_items_bucket = 0;
        bucket_block* current_bucket_block = vector_[h.global_index];
        while (current_bucket_block != NULL)
        {
            for (auto& bucket_item : current_bucket_block->items)
            {
                // if item and key equals
                // then reduce
                if (key == bucket_item.first)
                {
                    LOG << "match of key: " << key << " and " << bucket_item.first << " ... reducing...";
                    bucket_item.second = reduce_function_(bucket_item.second, p);
                    LOG << "...finished reduce!";
                    return;
                }

                // increase num items in bucket for visited item
                num_items_bucket++;
            }

            if (current_bucket_block->next == NULL)
            {
                break;
            }

            current_bucket_block = current_bucket_block->next;
        }

        if (current_bucket_block == NULL)
        {
            current_bucket_block = vector_[h.global_index] = new bucket_block(*this);
        }
        else if (current_bucket_block->items.size() == bucket_block_size_)
        {
            current_bucket_block = current_bucket_block->next = new bucket_block(*this);
        }

        // insert new item in current bucket block
        current_bucket_block->items.push_back(std::pair<key_t, value_t>(key, p));
        // increase counter for partition
        items_per_partition_[h.partition_id]++;
        // increase total counter
        table_size_++;

        // increase num items in bucket for inserted item
        num_items_bucket++;

        if (table_size_ > max_num_items_table_)
        {
            LOG << "spilling in progress";
            FlushLargestPartition();
        }

        if (num_items_bucket > max_num_items_per_bucket_)
        {
            ResizeUp();
        }
    }

    /*!
     * Flushes all items.
     */
    void Flush() {
        LOG << "Flushing all items";

        // retrieve items
        for (size_t i = 0; i < num_partitions_; i++)
        {
            FlushPartition(i);
        }

        LOG << "Flushed all items";
    }

    /*!
     * Retrieves all items belonging to the partition
     * having the most items. Retrieved items are then forward
     * to the provided emitter.
     */
    void FlushLargestPartition() {
        LOG << "Flushing items of largest partition";

        // get partition with max size
        size_t p_size_max = 0;
        size_t p_idx = 0;
        for (size_t i = 0; i < num_partitions_; i++)
        {
            if (items_per_partition_[i] > p_size_max)
            {
                p_size_max = items_per_partition_[i];
                p_idx = i;
            }
        }

        LOG << "currMax: "
            << p_size_max
            << " currentIdx: "
            << p_idx
            << " currentIdx*p_size: "
            << p_idx * num_buckets_per_partition_
            << " CurrentIdx*p_size+p_size-1 "
            << p_idx * num_buckets_per_partition_ + num_buckets_per_partition_ - 1;

        LOG << "Largest patition id: "
            << p_idx;

        FlushPartition(p_idx);

        LOG << "Flushed items of largest partition";
    }

    /*!
     * Flushes all items of a partition.
     */
    void FlushPartition(size_t partition_id) {
        LOG << "Flushing items of partition with id: "
            << partition_id;

        for (size_t i = partition_id * num_buckets_per_partition_;
             i <= partition_id * num_buckets_per_partition_ + num_buckets_per_partition_ - 1; i++)
        {
            bucket_block* current_bucket_block = vector_[i];
            while (current_bucket_block != NULL)
            {
                for (std::pair<key_t, value_t>& bucket_item : current_bucket_block->items)
                {
                    emit_[partition_id](bucket_item.second);
                    emit_stats_[partition_id]++;
                }
                //TODO(ms) call emit_[partition_id].Flush here to ensure elements are acutally pushed via network
                //I could not make the change because there are some instances of this class with std::functions
                //and they don't offer the Flush() mehtod of course.
                bucket_block* tmp_current_bucket_block = current_bucket_block->next;
                delete current_bucket_block;
                current_bucket_block = tmp_current_bucket_block;
            }

            vector_[i] = NULL;
        }

        // reset total counter
        table_size_ -= items_per_partition_[partition_id];
        // reset partition specific counter
        items_per_partition_[partition_id] = 0;

        LOG << "Flushed items of partition with id: "
            << partition_id;
    }

    /*!
     * Returns the total num of items.
     */
    size_t Size() {
        return table_size_;
    }

    /*!
     * Returns the total num of items.
     */
    size_t NumBuckets() {
        return num_buckets_;
    }

    /*!
     * Sets the maximum size of the hash table. We don't want to push 2vt elements before flush happens.
     */
    void SetMaxSize(size_t size) {
        max_num_items_table_ = size;
    }

    /*!
     * Closes all emitter
     */
    void CloseEmitter() {
        sLOG << "emit stats:";
        unsigned int i = 0;
        for (auto& e : emit_) {
            e.Close();
            sLOG << "emiter" << i << "pushed" << emit_stats_[i++];
        }
    }

    /*!
     * Resizes the table by increasing the number of buckets using some
     * resize scale factor. All items are rehashed as part of the operation.
     */
    void ResizeUp() {
        LOG << "Resizing";
        num_buckets_ *= num_buckets_resize_scale_;
        num_buckets_per_partition_ = num_buckets_ / num_partitions_;
        // init new array
        std::vector<bucket_block*> vector_old = vector_;
        std::vector<bucket_block*> vector_new; // TODO(ms): 3 vectors? come on! -> make it happen with one vector only!
        vector_new.resize(num_buckets_, NULL);
        vector_ = vector_new;
        // rehash all items in old array
        for (bucket_block* b_block : vector_old)
        {
            bucket_block* current_bucket_block = b_block;
            while (current_bucket_block != NULL)
            {
                for (std::pair<key_t, value_t>& bucket_item : current_bucket_block->items)
                {
                    Insert(bucket_item.second);
                }
                bucket_block* tmp_current_bucket_block = current_bucket_block->next;
                delete current_bucket_block;
                current_bucket_block = tmp_current_bucket_block;
            }
        }
        LOG << "Resized";
    }

    /*!
     * Removes all items in the table, but NOT flushing them.
     */
    void Clear() {
        LOG << "Clearing";
        std::fill(vector_.begin(), vector_.end(), NULL);
        std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0);
        table_size_ = 0;
        LOG << "Cleared";
    }

    /*!
     * Removes all items in the table, but NOT flushing them.
     */
    void Reset() {
        LOG << "Resetting";
        num_buckets_ = num_partitions_ * num_buckets_init_scale_;
        num_buckets_per_partition_ = num_buckets_ / num_partitions_;
        vector_.resize(num_buckets_, NULL);
        std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0);
        table_size_ = 0;
        LOG << "Resetted";
    }

    /*!
     * Prints content of hash table.
     */
    void Print() {
        LOG << "Printing";

        for (int i = 0; i < num_buckets_; i++)
        {
            if (vector_[i] == NULL)
            {
                LOG << "bucket id: "
                    << i
                    << " empty";
            }
            else
            {
                std::string log = "";

                bucket_block* current_bucket_block = vector_[i];
                while (current_bucket_block != NULL)
                {
                    log += "block: ";

                    for (std::pair<key_t, value_t> bucket_item : current_bucket_block->items)
                    {
                        if (&bucket_item != NULL)
                        {
                            log += "(";
                            log += bucket_item.first;
                            log += ", ";
                            //log += bucket_item.second; // TODO(ms): How to convert value_t to a string?
                            log += ") ";
                        }
                    }
                    current_bucket_block = current_bucket_block->next;
                }

                LOG << "bucket id: "
                    << i
                    << " "
                    << log;
            }
        }

        return;
    }

private:
    size_t num_partitions_;                   // partition size

    size_t num_buckets_;                      // num buckets

    size_t num_buckets_per_partition_;        // num buckets per partition

    size_t num_buckets_init_scale_ = 10;      // set number of buckets per partition based on num_partitions
    // multiplied with some scaling factor, must be equal to or greater than 1

    size_t num_buckets_resize_scale_ = 2;     // resize scale on max_num_items_per_bucket_

    size_t bucket_block_size_ = 32;           // size of bucket blocks

    size_t max_num_items_per_bucket_ = 256;   // max num of items per bucket before resize

    std::vector<size_t> items_per_partition_; // num items per partition

    size_t table_size_ = 0;                   // total number of items

    size_t max_num_items_table_ = 1048576;    // max num of items before spilling of largest partition

    KeyExtractor key_extractor_;

    ReduceFunction reduce_function_;

    std::vector<EmitterFunction> emit_;
    std::vector<int> emit_stats_;

    std::vector<bucket_block*> vector_;
};

} // namespace core
} // namespace c7a

#endif // !C7A_CORE_REDUCE_PRE_TABLE_HEADER

/******************************************************************************/
<commit_msg>fix compiler warning in reduce_pre_table.hpp that I introduced<commit_after>/*******************************************************************************
 * c7a/core/reduce_pre_table.hpp
 *
 * Hash table with support for reduce and partitions.
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_CORE_REDUCE_PRE_TABLE_HEADER
#define C7A_CORE_REDUCE_PRE_TABLE_HEADER

#include <c7a/api/function_traits.hpp>
#include <c7a/data/data_manager.hpp>

#include <map>
#include <iostream>
#include <c7a/common/logger.hpp>
#include <string>
#include <vector>
#include <stdexcept>
#include <array>
#include <deque>
#include <utility>

namespace c7a {
namespace core {
template <typename KeyExtractor, typename ReduceFunction, typename EmitterFunction>
class ReducePreTable
{
    static const bool debug = true;

    using key_t = typename FunctionTraits<KeyExtractor>::result_type;

    using value_t = typename FunctionTraits<ReduceFunction>::result_type;

protected:
    struct hash_result
    {
        //! which partition number the item belongs to.
        size_t partition_id;
        //! index within the partition's sub-hashtable of this item
        size_t partition_offset;
        //! index within the whole hashtable
        size_t global_index;

        hash_result(key_t v, const ReducePreTable& ht) {
            size_t hashed = std::hash<key_t>() (v);

            // partition idx
            partition_offset = hashed % ht.num_buckets_per_partition_;

            // partition id
            partition_id = hashed % ht.num_partitions_;

            // global idx
            global_index = partition_id * ht.num_buckets_per_partition_ + partition_offset;
        }
    };

    struct bucket_block {
        // TODO(ms): use a new/delete here instead of a vector, it is faster.
        std::vector<std::pair<key_t, value_t> > items;

        bucket_block                            * next = NULL;

        bucket_block(const ReducePreTable& ht) {
            items.reserve(ht.bucket_block_size_);
        }
    };

public:
    ReducePreTable(size_t num_partitions, size_t num_buckets_init_scale, size_t num_buckets_resize_scale,
                   size_t max_num_items_per_bucket, size_t max_num_items_table,
                   KeyExtractor key_extractor, ReduceFunction reduce_function,
                   std::vector<EmitterFunction> emit)
        : num_partitions_(num_partitions),
          num_buckets_init_scale_(num_buckets_init_scale),
          num_buckets_resize_scale_(num_buckets_resize_scale),
          max_num_items_per_bucket_(max_num_items_per_bucket),
          max_num_items_table_(max_num_items_table),
          key_extractor_(key_extractor),
          reduce_function_(reduce_function),
          emit_(emit) {
        init();
    }

    ReducePreTable(size_t partition_size, KeyExtractor key_extractor,
                   ReduceFunction reduce_function, std::vector<EmitterFunction> emit)
        : num_partitions_(partition_size),
          key_extractor_(key_extractor),
          reduce_function_(reduce_function),
          emit_(emit) {
        init();
    }

    ~ReducePreTable() { }

    void init() {
        sLOG << "creating reducePreTable with" << emit_.size() << "output emiters";
        for (size_t i = 0; i < emit_.size(); i++)
            emit_stats_.push_back(0);

        num_buckets_ = num_partitions_ * num_buckets_init_scale_;
        if (num_partitions_ > num_buckets_ &&
            num_buckets_ % num_partitions_ != 0) {
            throw std::invalid_argument("partition_size must be less than or equal to num_buckets "
                                        "AND partition_size a divider of num_buckets");
        }
        num_buckets_per_partition_ = num_buckets_ / num_partitions_;

        vector_.resize(num_buckets_, NULL);
        items_per_partition_.resize(num_partitions_, 0);
    }

    /*!
     * Inserts a key/value pair.
     *
     * Optionally, this may be reduce using the reduce function
     * in case the key already exists.
     */
    void Insert(const value_t& p) {
        key_t key = key_extractor_(p);

        hash_result h(key, *this);

        LOG << "key: " << key << " to bucket id: " << h.global_index;

        size_t num_items_bucket = 0;
        bucket_block* current_bucket_block = vector_[h.global_index];
        while (current_bucket_block != NULL)
        {
            for (auto& bucket_item : current_bucket_block->items)
            {
                // if item and key equals
                // then reduce
                if (key == bucket_item.first)
                {
                    LOG << "match of key: " << key << " and " << bucket_item.first << " ... reducing...";
                    bucket_item.second = reduce_function_(bucket_item.second, p);
                    LOG << "...finished reduce!";
                    return;
                }

                // increase num items in bucket for visited item
                num_items_bucket++;
            }

            if (current_bucket_block->next == NULL)
            {
                break;
            }

            current_bucket_block = current_bucket_block->next;
        }

        if (current_bucket_block == NULL)
        {
            current_bucket_block = vector_[h.global_index] = new bucket_block(*this);
        }
        else if (current_bucket_block->items.size() == bucket_block_size_)
        {
            current_bucket_block = current_bucket_block->next = new bucket_block(*this);
        }

        // insert new item in current bucket block
        current_bucket_block->items.push_back(std::pair<key_t, value_t>(key, p));
        // increase counter for partition
        items_per_partition_[h.partition_id]++;
        // increase total counter
        table_size_++;

        // increase num items in bucket for inserted item
        num_items_bucket++;

        if (table_size_ > max_num_items_table_)
        {
            LOG << "spilling in progress";
            FlushLargestPartition();
        }

        if (num_items_bucket > max_num_items_per_bucket_)
        {
            ResizeUp();
        }
    }

    /*!
     * Flushes all items.
     */
    void Flush() {
        LOG << "Flushing all items";

        // retrieve items
        for (size_t i = 0; i < num_partitions_; i++)
        {
            FlushPartition(i);
        }

        LOG << "Flushed all items";
    }

    /*!
     * Retrieves all items belonging to the partition
     * having the most items. Retrieved items are then forward
     * to the provided emitter.
     */
    void FlushLargestPartition() {
        LOG << "Flushing items of largest partition";

        // get partition with max size
        size_t p_size_max = 0;
        size_t p_idx = 0;
        for (size_t i = 0; i < num_partitions_; i++)
        {
            if (items_per_partition_[i] > p_size_max)
            {
                p_size_max = items_per_partition_[i];
                p_idx = i;
            }
        }

        LOG << "currMax: "
            << p_size_max
            << " currentIdx: "
            << p_idx
            << " currentIdx*p_size: "
            << p_idx * num_buckets_per_partition_
            << " CurrentIdx*p_size+p_size-1 "
            << p_idx * num_buckets_per_partition_ + num_buckets_per_partition_ - 1;

        LOG << "Largest patition id: "
            << p_idx;

        FlushPartition(p_idx);

        LOG << "Flushed items of largest partition";
    }

    /*!
     * Flushes all items of a partition.
     */
    void FlushPartition(size_t partition_id) {
        LOG << "Flushing items of partition with id: "
            << partition_id;

        for (size_t i = partition_id * num_buckets_per_partition_;
             i <= partition_id * num_buckets_per_partition_ + num_buckets_per_partition_ - 1; i++)
        {
            bucket_block* current_bucket_block = vector_[i];
            while (current_bucket_block != NULL)
            {
                for (std::pair<key_t, value_t>& bucket_item : current_bucket_block->items)
                {
                    emit_[partition_id](bucket_item.second);
                    emit_stats_[partition_id]++;
                }
                //TODO(ms) call emit_[partition_id].Flush here to ensure elements are acutally pushed via network
                //I could not make the change because there are some instances of this class with std::functions
                //and they don't offer the Flush() mehtod of course.
                bucket_block* tmp_current_bucket_block = current_bucket_block->next;
                delete current_bucket_block;
                current_bucket_block = tmp_current_bucket_block;
            }

            vector_[i] = NULL;
        }

        // reset total counter
        table_size_ -= items_per_partition_[partition_id];
        // reset partition specific counter
        items_per_partition_[partition_id] = 0;

        LOG << "Flushed items of partition with id: "
            << partition_id;
    }

    /*!
     * Returns the total num of items.
     */
    size_t Size() {
        return table_size_;
    }

    /*!
     * Returns the total num of items.
     */
    size_t NumBuckets() {
        return num_buckets_;
    }

    /*!
     * Sets the maximum size of the hash table. We don't want to push 2vt elements before flush happens.
     */
    void SetMaxSize(size_t size) {
        max_num_items_table_ = size;
    }

    /*!
     * Closes all emitter
     */
    void CloseEmitter() {
        sLOG << "emit stats:";
        unsigned int i = 0;
        for (auto& e : emit_) {
            e.Close();
            sLOG << "emiter" << i << "pushed" << emit_stats_[i++];
        }
    }

    /*!
     * Resizes the table by increasing the number of buckets using some
     * resize scale factor. All items are rehashed as part of the operation.
     */
    void ResizeUp() {
        LOG << "Resizing";
        num_buckets_ *= num_buckets_resize_scale_;
        num_buckets_per_partition_ = num_buckets_ / num_partitions_;
        // init new array
        std::vector<bucket_block*> vector_old = vector_;
        std::vector<bucket_block*> vector_new; // TODO(ms): 3 vectors? come on! -> make it happen with one vector only!
        vector_new.resize(num_buckets_, NULL);
        vector_ = vector_new;
        // rehash all items in old array
        for (bucket_block* b_block : vector_old)
        {
            bucket_block* current_bucket_block = b_block;
            while (current_bucket_block != NULL)
            {
                for (std::pair<key_t, value_t>& bucket_item : current_bucket_block->items)
                {
                    Insert(bucket_item.second);
                }
                bucket_block* tmp_current_bucket_block = current_bucket_block->next;
                delete current_bucket_block;
                current_bucket_block = tmp_current_bucket_block;
            }
        }
        LOG << "Resized";
    }

    /*!
     * Removes all items in the table, but NOT flushing them.
     */
    void Clear() {
        LOG << "Clearing";
        std::fill(vector_.begin(), vector_.end(), NULL);
        std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0);
        table_size_ = 0;
        LOG << "Cleared";
    }

    /*!
     * Removes all items in the table, but NOT flushing them.
     */
    void Reset() {
        LOG << "Resetting";
        num_buckets_ = num_partitions_ * num_buckets_init_scale_;
        num_buckets_per_partition_ = num_buckets_ / num_partitions_;
        vector_.resize(num_buckets_, NULL);
        std::fill(items_per_partition_.begin(), items_per_partition_.end(), 0);
        table_size_ = 0;
        LOG << "Resetted";
    }

    /*!
     * Prints content of hash table.
     */
    void Print() {
        LOG << "Printing";

        for (int i = 0; i < num_buckets_; i++)
        {
            if (vector_[i] == NULL)
            {
                LOG << "bucket id: "
                    << i
                    << " empty";
            }
            else
            {
                std::string log = "";

                bucket_block* current_bucket_block = vector_[i];
                while (current_bucket_block != NULL)
                {
                    log += "block: ";

                    for (std::pair<key_t, value_t> bucket_item : current_bucket_block->items)
                    {
                        if (&bucket_item != NULL)
                        {
                            log += "(";
                            log += bucket_item.first;
                            log += ", ";
                            //log += bucket_item.second; // TODO(ms): How to convert value_t to a string?
                            log += ") ";
                        }
                    }
                    current_bucket_block = current_bucket_block->next;
                }

                LOG << "bucket id: "
                    << i
                    << " "
                    << log;
            }
        }

        return;
    }

private:
    size_t num_partitions_;                   // partition size

    size_t num_buckets_;                      // num buckets

    size_t num_buckets_per_partition_;        // num buckets per partition

    size_t num_buckets_init_scale_ = 10;      // set number of buckets per partition based on num_partitions
    // multiplied with some scaling factor, must be equal to or greater than 1

    size_t num_buckets_resize_scale_ = 2;     // resize scale on max_num_items_per_bucket_

    size_t bucket_block_size_ = 32;           // size of bucket blocks

    size_t max_num_items_per_bucket_ = 256;   // max num of items per bucket before resize

    std::vector<size_t> items_per_partition_; // num items per partition

    size_t table_size_ = 0;                   // total number of items

    size_t max_num_items_table_ = 1048576;    // max num of items before spilling of largest partition

    KeyExtractor key_extractor_;

    ReduceFunction reduce_function_;

    std::vector<EmitterFunction> emit_;
    std::vector<int> emit_stats_;

    std::vector<bucket_block*> vector_;
};

} // namespace core
} // namespace c7a

#endif // !C7A_CORE_REDUCE_PRE_TABLE_HEADER

/******************************************************************************/
<|endoftext|>


<commit_before>#include "logger.h"
#include "functions.h"

#ifdef QT_DEBUG
	#include <QDebug>
#endif

void Logger::setLogFile(const QString &path)
{
	m_logFile.setFileName(path);
	m_logFile.open(QFile::Append | QFile::Text | QFile::Truncate);
}

void Logger::setLogLevel(LogLevel level)
{
	m_level = level;
}

void Logger::messageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message)
{
	static QMap<QtMsgType, LogLevel> messageTypes
	{
		{ QtMsgType::QtDebugMsg, Logger::Debug },
		{ QtMsgType::QtInfoMsg, Logger::Info },
		{ QtMsgType::QtWarningMsg, Logger::Warning },
		{ QtMsgType::QtCriticalMsg, Logger::Error },
		{ QtMsgType::QtFatalMsg, Logger::Error },
		{ QtMsgType::QtSystemMsg, Logger::Error },
	};

	QString label = "[Qt]";
	QString category(context.category);
	if (!category.isEmpty())
		label += "[" + category + "]";
	#if defined QT_MESSAGELOGCONTEXT && defined QT_DEBUG && 0
		label += QString("[%1(%2)::%3]").arg(context.file).arg(context.line).arg(context.function);
	#endif

	Logger::getInstance().log(QString("%1 %2").arg(label, message), messageTypes[type]);
}

void Logger::noMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message)
{
	Q_UNUSED(type);
	Q_UNUSED(context);
	Q_UNUSED(message);
}

void Logger::setupMessageOutput(bool log)
{
	qInstallMessageHandler(log ? Logger::messageOutput : Logger::noMessageOutput);
}

/**
 * Append text in the log in a new line.
 * @param	l	The message to append.
 */
void Logger::log(const QString &l, LogLevel level)
{
	if (level < m_level)
		return;

	if (!m_logFile.isOpen())
		setLogFile(savePath("main.log", false, true));

	static const QStringList levels = QStringList() << "Debug" << "Info" << "Warning" << "Error";
	static const QStringList colors = QStringList() << "#999" << "" << "orange" << "red";
	QString levelStr = levels[level];
	QDateTime time = QDateTime::currentDateTime();

	// Write ASCII log to file
	m_logFile.write(QString("["+time.toString("hh:mm:ss.zzz")+"]["+levelStr+"] "+stripTags(l)+"\n").toUtf8());
	m_logFile.flush();

	// Emit colored HTML log
	QString levelColor = colors[level];
	QString msg = "[" + time.toString("hh:mm:ss.zzz") + "][" + levelStr + "] " + l;
	if (!levelColor.isEmpty())
		msg = QString("%2").arg(levelColor, msg);
	emit newLog(msg);

	#ifdef QT_DEBUG
		qDebug() << time.toString("hh:mm:ss.zzz") << levelStr << l;
	#endif
}

void Logger::logCommand(const QString &l)
{
	if (!m_fCommandsLog.isOpen())
	{
		m_fCommandsLog.setFileName(savePath("commands.log", false, true));
		m_fCommandsLog.open(QFile::Append | QFile::Text | QFile::Truncate);
	}

	m_fCommandsLog.write(QString(l+"\r\n").toUtf8());
	m_fCommandsLog.flush();
}

void Logger::logCommandSql(const QString &l)
{
	if (!m_fCommandsSqlLog.isOpen())
	{
		m_fCommandsSqlLog.setFileName(savePath("commands.sql", false, true));
		m_fCommandsSqlLog.open(QFile::Append | QFile::Text | QFile::Truncate);
	}

	m_fCommandsSqlLog.write(QString(l+"\r\n").toUtf8());
	m_fCommandsSqlLog.flush();
}

/**
 * Append text in the log at the end of the current line.
 * @param	l	The message to append.
 */
void Logger::logUpdate(const QString &l)
{
	Q_UNUSED(l);

	/*QDateTime date = _log.keys().at(_log.count()-1);
	QString message = _log.value(date)+l;
	_log.insert(date, message);
	_mainwindow->logShow();

	qDebug() << l;*/
}

void log(const QString &l, Logger::LogLevel level)
{
	LOG(l, level);
}
<commit_msg>Fix build on Qt 5.5.0-<commit_after>#include "logger.h"
#include "functions.h"

#ifdef QT_DEBUG
	#include <QDebug>
#endif

void Logger::setLogFile(const QString &path)
{
	m_logFile.setFileName(path);
	m_logFile.open(QFile::Append | QFile::Text | QFile::Truncate);
}

void Logger::setLogLevel(LogLevel level)
{
	m_level = level;
}

void Logger::messageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message)
{
	static QMap<QtMsgType, LogLevel> messageTypes
	{
		{ QtMsgType::QtDebugMsg, Logger::Debug },
		#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
			{ QtMsgType::QtInfoMsg, Logger::Info },
		#endif
		{ QtMsgType::QtWarningMsg, Logger::Warning },
		{ QtMsgType::QtCriticalMsg, Logger::Error },
		{ QtMsgType::QtFatalMsg, Logger::Error },
		{ QtMsgType::QtSystemMsg, Logger::Error },
	};

	QString label = "[Qt]";
	QString category(context.category);
	if (!category.isEmpty())
		label += "[" + category + "]";
	#if defined QT_MESSAGELOGCONTEXT && defined QT_DEBUG && 0
		label += QString("[%1(%2)::%3]").arg(context.file).arg(context.line).arg(context.function);
	#endif

	Logger::getInstance().log(QString("%1 %2").arg(label, message), messageTypes[type]);
}

void Logger::noMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message)
{
	Q_UNUSED(type);
	Q_UNUSED(context);
	Q_UNUSED(message);
}

void Logger::setupMessageOutput(bool log)
{
	qInstallMessageHandler(log ? Logger::messageOutput : Logger::noMessageOutput);
}

/**
 * Append text in the log in a new line.
 * @param	l	The message to append.
 */
void Logger::log(const QString &l, LogLevel level)
{
	if (level < m_level)
		return;

	if (!m_logFile.isOpen())
		setLogFile(savePath("main.log", false, true));

	static const QStringList levels = QStringList() << "Debug" << "Info" << "Warning" << "Error";
	static const QStringList colors = QStringList() << "#999" << "" << "orange" << "red";
	QString levelStr = levels[level];
	QDateTime time = QDateTime::currentDateTime();

	// Write ASCII log to file
	m_logFile.write(QString("["+time.toString("hh:mm:ss.zzz")+"]["+levelStr+"] "+stripTags(l)+"\n").toUtf8());
	m_logFile.flush();

	// Emit colored HTML log
	QString levelColor = colors[level];
	QString msg = "[" + time.toString("hh:mm:ss.zzz") + "][" + levelStr + "] " + l;
	if (!levelColor.isEmpty())
		msg = QString("%2").arg(levelColor, msg);
	emit newLog(msg);

	#ifdef QT_DEBUG
		qDebug() << time.toString("hh:mm:ss.zzz") << levelStr << l;
	#endif
}

void Logger::logCommand(const QString &l)
{
	if (!m_fCommandsLog.isOpen())
	{
		m_fCommandsLog.setFileName(savePath("commands.log", false, true));
		m_fCommandsLog.open(QFile::Append | QFile::Text | QFile::Truncate);
	}

	m_fCommandsLog.write(QString(l+"\r\n").toUtf8());
	m_fCommandsLog.flush();
}

void Logger::logCommandSql(const QString &l)
{
	if (!m_fCommandsSqlLog.isOpen())
	{
		m_fCommandsSqlLog.setFileName(savePath("commands.sql", false, true));
		m_fCommandsSqlLog.open(QFile::Append | QFile::Text | QFile::Truncate);
	}

	m_fCommandsSqlLog.write(QString(l+"\r\n").toUtf8());
	m_fCommandsSqlLog.flush();
}

/**
 * Append text in the log at the end of the current line.
 * @param	l	The message to append.
 */
void Logger::logUpdate(const QString &l)
{
	Q_UNUSED(l);

	/*QDateTime date = _log.keys().at(_log.count()-1);
	QString message = _log.value(date)+l;
	_log.insert(date, message);
	_mainwindow->logShow();

	qDebug() << l;*/
}

void log(const QString &l, Logger::LogLevel level)
{
	LOG(l, level);
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. 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.
 *****************************************************************************/

#include "modules/canbus/common/canbus_gflags.h"

// System gflags
DEFINE_string(canbus_node_name, "chassis", "The chassis module name in proto");
DEFINE_string(canbus_module_name, "canbus", "Module name");

DEFINE_string(canbus_adapter_config_filename,
              "modules/canbus/conf/adapter.conf", "The adapter config file");

// data file
DEFINE_string(canbus_conf_file, "modules/canbus/conf/canbus_conf.pb.txt",
              "Default canbus conf file");

// Canbus gflags
DEFINE_double(chassis_freq, 100, "Chassis feedback timer frequency.");
DEFINE_int64(min_cmd_interval, 5, "Minimum control command interval in us.");

// chassis_detail message publish
DEFINE_bool(enable_chassis_detail_pub, false, "Chassis Detail message publish");

// canbus test files
DEFINE_string(canbus_test_file, "modules/canbus/testdata/canbus_test.pb.txt",
              "canbus tester input test file, in ControlCommand pb format.");
<commit_msg>Update canbus_gflags.cc<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. 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.
 *****************************************************************************/

#include "modules/canbus/common/canbus_gflags.h"

// System gflags
DEFINE_string(canbus_node_name, "chassis", "The chassis module name in proto");
DEFINE_string(canbus_module_name, "canbus", "Module name");

DEFINE_string(canbus_adapter_config_filename,
              "modules/canbus/conf/adapter.conf", "The adapter config file");

// data file
DEFINE_string(canbus_conf_file, "modules/canbus/conf/canbus_conf.pb.txt",
              "Default canbus conf file");

// Canbus gflags
DEFINE_double(chassis_freq, 100, "Chassis feedback timer frequency.");
DEFINE_int64(min_cmd_interval, 5, "Minimum control command interval in ms.");

// chassis_detail message publish
DEFINE_bool(enable_chassis_detail_pub, false, "Chassis Detail message publish");

// canbus test files
DEFINE_string(canbus_test_file, "modules/canbus/testdata/canbus_test.pb.txt",
              "canbus tester input test file, in ControlCommand pb format.");
<|endoftext|>


<commit_before><commit_msg>build<commit_after><|endoftext|>


<commit_before>// ------------------------------------------------------------------------------------------------
#include "Library/Chrono/Date.hpp"
#include "Library/Chrono/Date.hpp"
#include "Library/Chrono/Datetime.hpp"
#include "Base/Shared.hpp"

// ------------------------------------------------------------------------------------------------
namespace SqMod {

// ------------------------------------------------------------------------------------------------
SQChar Date::Delimiter = '-';

// ------------------------------------------------------------------------------------------------
const Uint8 Date::MonthLengths[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// ------------------------------------------------------------------------------------------------
SQInteger Date::Typename(HSQUIRRELVM vm)
{
    static SQChar name[] = _SC("SqChronoDate");
    sq_pushstring(vm, name, sizeof(name));
    return 1;
}

// ------------------------------------------------------------------------------------------------
Date Date::operator + (const Date & o) const
{
    return Date(o);
}

// ------------------------------------------------------------------------------------------------
Date Date::operator - (const Date & o) const
{
    return Date(o);
}

// ------------------------------------------------------------------------------------------------
Date Date::operator * (const Date & o) const
{
    return Date(o);
}

// ------------------------------------------------------------------------------------------------
Date Date::operator / (const Date & o) const
{
    return Date(o);
}

// ------------------------------------------------------------------------------------------------
void Date::Set(Uint16 year, Uint8 month, Uint8 day)
{
    if (!ValidDate(year, month, day))
    {
        STHROWF("Invalid date: %04u%c%02u%c%02u%c%u"
            , m_Delimiter, m_Year
            , m_Delimiter, m_Month
            , m_Delimiter, m_Day
        );
    }
}

// ------------------------------------------------------------------------------------------------
CSStr Date::GetStr() const
{
    return ToString();
}

// ------------------------------------------------------------------------------------------------
void Date::SetStr(CSStr str)
{
    // The format specifications that will be used to scan the string
    static SQChar fs[] = _SC(" %u , %u , %u,");
    // Is the specified string empty?
    if (!str || *str == '\0')
    {
        // Clear the values
        m_Year = 0;
        m_Month = 0;
        m_Day = 0;
        // We're done here
        return;
    }
    // Assign the specified delimiter
    fs[4] = m_Delimiter;
    fs[9] = m_Delimiter;
    // The sscanf function requires at least 32 bit integers
    Uint32 year = 0, month = 0, day = 0;
    // Attempt to extract the component values from the specified string
    sscanf(str, fs, &year, &month, &day);
    // Clamp the extracted values to the boundaries of associated type and assign them
    Set(ClampL< Uint32, Uint8 >(year),
        ClampL< Uint32, Uint8 >(month),
        ClampL< Uint32, Uint8 >(day)
    );
}

// ------------------------------------------------------------------------------------------------
Int32 Date::Compare(const Date & o) const
{
    if (m_Year < o.m_Year)
    {
        return -1;
    }
    else if (m_Year > o.m_Year)
    {
        return 1;
    }
    else if (m_Month < o.m_Month)
    {
        return -1;
    }
    else if (m_Month > o.m_Month)
    {
        return 1;
    }
    else if (m_Day < o.m_Day)
    {
        return -1;
    }
    else if (m_Day > o.m_Day)
    {
        return 1;
    }
    // They're equal
    return 0;
}

// ------------------------------------------------------------------------------------------------
CSStr Date::ToString() const
{
    return ToStrF("%04u%c%02u%c%02u%c%u"
        , m_Delimiter, m_Year
        , m_Delimiter, m_Month
        , m_Delimiter, m_Day
    );
}

// ------------------------------------------------------------------------------------------------
void Date::SetYear(Uint16 year)
{

}

// ------------------------------------------------------------------------------------------------
void Date::SetMonth(Uint8 month)
{

}

// ------------------------------------------------------------------------------------------------
void Date::SetDay(Uint8 day)
{

}

// ------------------------------------------------------------------------------------------------
Date Date::AddYears(Int32 years)
{
    return Date(*this);
}

// ------------------------------------------------------------------------------------------------
Date Date::AddMonths(Int32 months)
{
    return Date(*this);
}

// ------------------------------------------------------------------------------------------------
Date Date::AddDays(Int32 days)
{
    return Date(*this);
}

// ------------------------------------------------------------------------------------------------
bool Date::ValidDate(Uint16 year, Uint8 month, Uint8 day)
{
    // Is this a valid date?
    if (year == 0 || month == 0 || day == 0)
    {
        return false;
    }
    // Is the month within range?
    else if (month > 12)
    {
        return false;
    }
    // Return whether the day inside the month
    return day <= DaysInMonth(year, month);
}

// ------------------------------------------------------------------------------------------------
Uint8 Date::DaysInMonth(Uint16 year, Uint8 month)
{
    // Is the specified month within range?
    if (month > 12)
    {
        STHROWF("Month value is out of range: %u > 12", month);
    }
    // Obtain the days in this month
    Uint8 days = MonthLengths[month - 1];
    // Should we account for January?
    if (month == 2 && IsLeapYear(year))
    {
        ++days;
    }
    // Return the resulted days
    return days;
}

// ------------------------------------------------------------------------------------------------
Uint16 Date::DayOfYear(Uint16 year, Uint8 month, Uint8 day)
{
    // Start with 0 days
    Uint16 doy = 0;
    // Cumulate the days in months
    for (Uint8 m = 1; m < month; ++month)
    {
        doy += DaysInMonth(year, m);
    }
    // Add the specified days
    doy += day;
    // Return the result
    return doy;
}

// ================================================================================================
void Register_ChronoDate(HSQUIRRELVM vm, Table & /*cns*/)
{
    RootTable(vm).Bind(_SC("SqDate"), Class< Date >(vm, _SC("SqChronoDate"))
        // Constructors
        .Ctor()
        .Ctor< Uint16 >()
        .Ctor< Uint16, Uint8 >()
        .Ctor< Uint16, Uint8, Uint8 >()
        // Static Properties
        .SetStaticValue(_SC("GlobalDelimiter"), &Date::Delimiter)
        // Core Metamethods
        .Func(_SC("_tostring"), &Date::ToString)
        .SquirrelFunc(_SC("_typename"), &Date::Typename)
        .Func(_SC("_cmp"), &Date::Cmp)
        // Metamethods
        .Func< Date (Date::*)(const Date &) const >(_SC("_add"), &Date::operator +)
        .Func< Date (Date::*)(const Date &) const >(_SC("_sub"), &Date::operator -)
        .Func< Date (Date::*)(const Date &) const >(_SC("_mul"), &Date::operator *)
        .Func< Date (Date::*)(const Date &) const >(_SC("_div"), &Date::operator /)
        // Properties
        .Prop(_SC("Year"), &Date::GetYear, &Date::SetYear)
        .Prop(_SC("Month"), &Date::GetMonth, &Date::SetMonth)
        .Prop(_SC("Day"), &Date::GetDay, &Date::SetDay)
        .Prop(_SC("Str"), &Date::GetStr, &Date::SetStr)
        .Prop(_SC("Delimiter"), &Date::GetDelimiter, &Date::SetDelimiter)
        .Prop(_SC("LeapYear"), &Date::IsThisLeapYear)
        .Prop(_SC("YearDays"), &Date::GetYearDays)
        .Prop(_SC("MonthDays"), &Date::GetMonthDays)
        // Member Methods
        .Func(_SC("AddYears"), &Date::AddYears)
        .Func(_SC("AddMonths"), &Date::AddMonths)
        .Func(_SC("AddDays"), &Date::AddDays)
        // Overloaded Methods
        .Overload< void (Date::*)(Uint16) >(_SC("Set"), &Date::Set)
        .Overload< void (Date::*)(Uint16, Uint8) >(_SC("Set"), &Date::Set)
        .Overload< void (Date::*)(Uint16, Uint8, Uint8) >(_SC("Set"), &Date::Set)
    );
}

} // Namespace:: SqMod
<commit_msg>Avoid GCC error "array subscript is above array bounds" which probably considers that the unsigned char could underflow and access an element out of the months range.<commit_after>// ------------------------------------------------------------------------------------------------
#include "Library/Chrono/Date.hpp"
#include "Library/Chrono/Date.hpp"
#include "Library/Chrono/Datetime.hpp"
#include "Base/Shared.hpp"

// ------------------------------------------------------------------------------------------------
namespace SqMod {

// ------------------------------------------------------------------------------------------------
SQChar Date::Delimiter = '-';

// ------------------------------------------------------------------------------------------------
const Uint8 Date::MonthLengths[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// ------------------------------------------------------------------------------------------------
SQInteger Date::Typename(HSQUIRRELVM vm)
{
    static SQChar name[] = _SC("SqChronoDate");
    sq_pushstring(vm, name, sizeof(name));
    return 1;
}

// ------------------------------------------------------------------------------------------------
Date Date::operator + (const Date & o) const
{
    return Date(o);
}

// ------------------------------------------------------------------------------------------------
Date Date::operator - (const Date & o) const
{
    return Date(o);
}

// ------------------------------------------------------------------------------------------------
Date Date::operator * (const Date & o) const
{
    return Date(o);
}

// ------------------------------------------------------------------------------------------------
Date Date::operator / (const Date & o) const
{
    return Date(o);
}

// ------------------------------------------------------------------------------------------------
void Date::Set(Uint16 year, Uint8 month, Uint8 day)
{
    if (!ValidDate(year, month, day))
    {
        STHROWF("Invalid date: %04u%c%02u%c%02u%c%u"
            , m_Delimiter, m_Year
            , m_Delimiter, m_Month
            , m_Delimiter, m_Day
        );
    }
}

// ------------------------------------------------------------------------------------------------
CSStr Date::GetStr() const
{
    return ToString();
}

// ------------------------------------------------------------------------------------------------
void Date::SetStr(CSStr str)
{
    // The format specifications that will be used to scan the string
    static SQChar fs[] = _SC(" %u , %u , %u,");
    // Is the specified string empty?
    if (!str || *str == '\0')
    {
        // Clear the values
        m_Year = 0;
        m_Month = 0;
        m_Day = 0;
        // We're done here
        return;
    }
    // Assign the specified delimiter
    fs[4] = m_Delimiter;
    fs[9] = m_Delimiter;
    // The sscanf function requires at least 32 bit integers
    Uint32 year = 0, month = 0, day = 0;
    // Attempt to extract the component values from the specified string
    sscanf(str, fs, &year, &month, &day);
    // Clamp the extracted values to the boundaries of associated type and assign them
    Set(ClampL< Uint32, Uint8 >(year),
        ClampL< Uint32, Uint8 >(month),
        ClampL< Uint32, Uint8 >(day)
    );
}

// ------------------------------------------------------------------------------------------------
Int32 Date::Compare(const Date & o) const
{
    if (m_Year < o.m_Year)
    {
        return -1;
    }
    else if (m_Year > o.m_Year)
    {
        return 1;
    }
    else if (m_Month < o.m_Month)
    {
        return -1;
    }
    else if (m_Month > o.m_Month)
    {
        return 1;
    }
    else if (m_Day < o.m_Day)
    {
        return -1;
    }
    else if (m_Day > o.m_Day)
    {
        return 1;
    }
    // They're equal
    return 0;
}

// ------------------------------------------------------------------------------------------------
CSStr Date::ToString() const
{
    return ToStrF("%04u%c%02u%c%02u%c%u"
        , m_Delimiter, m_Year
        , m_Delimiter, m_Month
        , m_Delimiter, m_Day
    );
}

// ------------------------------------------------------------------------------------------------
void Date::SetYear(Uint16 year)
{

}

// ------------------------------------------------------------------------------------------------
void Date::SetMonth(Uint8 month)
{

}

// ------------------------------------------------------------------------------------------------
void Date::SetDay(Uint8 day)
{

}

// ------------------------------------------------------------------------------------------------
Date Date::AddYears(Int32 years)
{
    return Date(*this);
}

// ------------------------------------------------------------------------------------------------
Date Date::AddMonths(Int32 months)
{
    return Date(*this);
}

// ------------------------------------------------------------------------------------------------
Date Date::AddDays(Int32 days)
{
    return Date(*this);
}

// ------------------------------------------------------------------------------------------------
bool Date::ValidDate(Uint16 year, Uint8 month, Uint8 day)
{
    // Is this a valid date?
    if (year == 0 || month == 0 || day == 0)
    {
        return false;
    }
    // Is the month within range?
    else if (month > 12)
    {
        return false;
    }
    // Return whether the day inside the month
    return day <= DaysInMonth(year, month);
}

// ------------------------------------------------------------------------------------------------
Uint8 Date::DaysInMonth(Uint16 year, Uint8 month)
{
    // Is the specified month within range?
    if (month > 12)
    {
        STHROWF("Month value is out of range: %u > 12", month);
    }
    // Obtain the days in this month
    Uint8 days = *(MonthLengths + month);
    // Should we account for January?
    if (month == 2 && IsLeapYear(year))
    {
        ++days;
    }
    // Return the resulted days
    return days;
}

// ------------------------------------------------------------------------------------------------
Uint16 Date::DayOfYear(Uint16 year, Uint8 month, Uint8 day)
{
    // Start with 0 days
    Uint16 doy = 0;
    // Cumulate the days in months
    for (Uint8 m = 1; m < month; ++month)
    {
        doy += DaysInMonth(year, m);
    }
    // Add the specified days
    doy += day;
    // Return the result
    return doy;
}

// ================================================================================================
void Register_ChronoDate(HSQUIRRELVM vm, Table & /*cns*/)
{
    RootTable(vm).Bind(_SC("SqDate"), Class< Date >(vm, _SC("SqChronoDate"))
        // Constructors
        .Ctor()
        .Ctor< Uint16 >()
        .Ctor< Uint16, Uint8 >()
        .Ctor< Uint16, Uint8, Uint8 >()
        // Static Properties
        .SetStaticValue(_SC("GlobalDelimiter"), &Date::Delimiter)
        // Core Metamethods
        .Func(_SC("_tostring"), &Date::ToString)
        .SquirrelFunc(_SC("_typename"), &Date::Typename)
        .Func(_SC("_cmp"), &Date::Cmp)
        // Metamethods
        .Func< Date (Date::*)(const Date &) const >(_SC("_add"), &Date::operator +)
        .Func< Date (Date::*)(const Date &) const >(_SC("_sub"), &Date::operator -)
        .Func< Date (Date::*)(const Date &) const >(_SC("_mul"), &Date::operator *)
        .Func< Date (Date::*)(const Date &) const >(_SC("_div"), &Date::operator /)
        // Properties
        .Prop(_SC("Year"), &Date::GetYear, &Date::SetYear)
        .Prop(_SC("Month"), &Date::GetMonth, &Date::SetMonth)
        .Prop(_SC("Day"), &Date::GetDay, &Date::SetDay)
        .Prop(_SC("Str"), &Date::GetStr, &Date::SetStr)
        .Prop(_SC("Delimiter"), &Date::GetDelimiter, &Date::SetDelimiter)
        .Prop(_SC("LeapYear"), &Date::IsThisLeapYear)
        .Prop(_SC("YearDays"), &Date::GetYearDays)
        .Prop(_SC("MonthDays"), &Date::GetMonthDays)
        // Member Methods
        .Func(_SC("AddYears"), &Date::AddYears)
        .Func(_SC("AddMonths"), &Date::AddMonths)
        .Func(_SC("AddDays"), &Date::AddDays)
        // Overloaded Methods
        .Overload< void (Date::*)(Uint16) >(_SC("Set"), &Date::Set)
        .Overload< void (Date::*)(Uint16, Uint8) >(_SC("Set"), &Date::Set)
        .Overload< void (Date::*)(Uint16, Uint8, Uint8) >(_SC("Set"), &Date::Set)
    );
}

} // Namespace:: SqMod
<|endoftext|>


<commit_before>/*
 +----------------------------------------------------------------------+
 | PHP-OpenCV                                                           |
 +----------------------------------------------------------------------+
 | This source file is subject to version 2.0 of the Apache license,    |
 | that is bundled with this package in the file LICENSE, and is        |
 | available through the world-wide-web at the following url:           |
 | http://www.apache.org/licenses/LICENSE-2.0.html                      |
 | If you did not receive a copy of the Apache2.0 license and are unable|
 | to obtain it through the world-wide-web, please send a note to       |
 | hihozhou@gmail.com so we can mail you a copy immediately.            |
 +----------------------------------------------------------------------+
 | Author: HaiHao Zhou  <hihozhou@gmail.com>                            |
 +----------------------------------------------------------------------+
 */

#include "../../php_opencv.h"
#include "opencv_highgui.h"
#include "core/opencv_mat.h"
#include "../../opencv_exception.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

/**
 * //todo only cli can call this function
 * CV\imshow
 * @param execute_data
 * @param return_value
 */
PHP_FUNCTION(opencv_imshow){
    char *window_name;
    long window_name_len;
    zval *object;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sO", &window_name, &window_name_len, &object,opencv_mat_ce) == FAILURE) {
        RETURN_NULL();
    }
    opencv_mat_object *obj = Z_PHP_MAT_OBJ_P(object);
//    namedWindow(window_name);
    imshow(window_name,*(obj->mat));
    RETURN_NULL();
}

/**
 * CV\waitKey
 * @param execute_data
 * @param return_value
 */
PHP_FUNCTION(opencv_wait_key){
    long delay = 0;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &delay) == FAILURE) {
        RETURN_NULL();
    }
    int key = waitKey((int)delay);//millisecond
    RETURN_LONG(key);
}

/**
 * php namedWindow flags to c++ namedWindow flags
 * @param flags
 * @return
 */
int php_window_flags_to_c_flags(int flags){
    if(flags == 1){
        return WINDOW_NORMAL;
    }else if(flags==2){
        return WINDOW_AUTOSIZE;
    }else if(flags==3){
        return WINDOW_OPENGL;
    }else if(flags==4){
        return WINDOW_FULLSCREEN;
    }else if(flags==5){
        return WINDOW_FREERATIO;
    }else if(flags==6){
        return WINDOW_GUI_EXPANDED;
    }else if(flags==7){
        return WINDOW_GUI_NORMAL;
    }
    return WINDOW_AUTOSIZE;
}

/**
 * CV\namedWindow
 * @param window_name
 * @param flags
 */
PHP_FUNCTION(opencv_named_window){
    char *window_name;
    long window_name_len;
    long flags = 2;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|l", &window_name, &window_name_len, &flags) == FAILURE) {
        RETURN_NULL();
    }
    namedWindow(window_name,php_window_flags_to_c_flags((int)flags));
    RETURN_NULL();
}

struct opencv_fcall_info_struct{
    zend_fcall_info *fci;
    zend_fcall_info_cache *fci_cache;
};

void opencv_create_trackbar_callback(int pos, void* userdata){
    opencv_fcall_info_struct *fci_s=(opencv_fcall_info_struct*)userdata;

    zval retval;
    zval args[1];
    ZVAL_LONG(&args[0], (long)pos);
    fci_s->fci->param_count = 1;
    fci_s->fci->params = args;
    fci_s->fci->retval = &retval;

    //todo zend_call_function: Assertion `((zend_object*)func->op_array.prototype)->gc.u.v.type == 8' failed.
    zend_call_function(fci_s->fci, fci_s->fci_cache);
    zval_ptr_dtor(&args[0]);
}

/**
 * //todo c++ createTrackbar 跳转事件调用php传入的闭包:1php全局变量，2c++闭包
 * CV\createTrackbar
 * @param execute_data
 * @param return_value
 */
PHP_FUNCTION(opencv_create_trackbar){
    char *trackbarname, *winname;
    long value, count, trackbarname_len,winname_len;
    zval retval;

    zend_fcall_info *fci = new zend_fcall_info;
    zend_fcall_info_cache *fci_cache = new zend_fcall_info_cache;
    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssll|f",
                              &trackbarname, &trackbarname_len,
                              &winname,&winname_len,
                              &value,&count,
                              fci, fci_cache) == FAILURE) {
        return;
    }

    int *trackbar_value_ptr = new int(value);

    opencv_fcall_info_struct *fci_s = new opencv_fcall_info_struct;
    fci_s->fci=fci;
    fci_s->fci_cache = fci_cache;
    createTrackbar(trackbarname, winname, trackbar_value_ptr, (int)count,opencv_create_trackbar_callback,fci_s);
    opencv_create_trackbar_callback(*trackbar_value_ptr,fci_s);
//    createTrackbar(trackbarname, winname, trackbar_value_ptr, (int)count);
//    zend_call_function(fci_s->fci, fci_s->fci_cache);
    RETURN_NULL();

//    if (zend_call_function(fci, fci_cache) == SUCCESS && Z_TYPE(retval) != IS_UNDEF) {
//        zval_ptr_dtor(&args[0]);
//        RETURN_ZVAL(&retval,1,1);
//        ZVAL_COPY_VALUE(return_value, &retval);
//    } else {
//        RETURN_FALSE;
//    }

}

PHP_FUNCTION(opencv_destroy_window){
    char *winname;
    long winname_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &winname,&winname_len) == FAILURE) {
        return;
    }

    try{
        destroyWindow(winname);
    }catch (Exception e){
        opencv_throw_exception(e.what());
    }

    RETURN_NULL();

}

void opencv_highgui_init(int module_number)
{
    /**
     * ! ! Flags for CV\namedWindow
     */
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_NORMAL", 1, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_AUTOSIZE", 2, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_OPENGL", 3, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_FULLSCREEN", 4, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_FREERATIO", 5, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_GUI_EXPANDED", 6, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_GUI_NORMAL", 7, CONST_CS | CONST_PERSISTENT);
}<commit_msg>CV\createTrackbar callback<commit_after>/*
 +----------------------------------------------------------------------+
 | PHP-OpenCV                                                           |
 +----------------------------------------------------------------------+
 | This source file is subject to version 2.0 of the Apache license,    |
 | that is bundled with this package in the file LICENSE, and is        |
 | available through the world-wide-web at the following url:           |
 | http://www.apache.org/licenses/LICENSE-2.0.html                      |
 | If you did not receive a copy of the Apache2.0 license and are unable|
 | to obtain it through the world-wide-web, please send a note to       |
 | hihozhou@gmail.com so we can mail you a copy immediately.            |
 +----------------------------------------------------------------------+
 | Author: HaiHao Zhou  <hihozhou@gmail.com>                            |
 +----------------------------------------------------------------------+
 */

#include "../../php_opencv.h"
#include "opencv_highgui.h"
#include "core/opencv_mat.h"
#include "../../opencv_exception.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

/**
 * //todo only cli can call this function
 * CV\imshow
 * @param execute_data
 * @param return_value
 */
PHP_FUNCTION(opencv_imshow){
    char *window_name;
    long window_name_len;
    zval *object;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sO", &window_name, &window_name_len, &object,opencv_mat_ce) == FAILURE) {
        RETURN_NULL();
    }
    opencv_mat_object *obj = Z_PHP_MAT_OBJ_P(object);
//    namedWindow(window_name);
    imshow(window_name,*(obj->mat));
    RETURN_NULL();
}

/**
 * CV\waitKey
 * @param execute_data
 * @param return_value
 */
PHP_FUNCTION(opencv_wait_key){
    long delay = 0;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &delay) == FAILURE) {
        RETURN_NULL();
    }
    int key = waitKey((int)delay);//millisecond
    RETURN_LONG(key);
}

/**
 * php namedWindow flags to c++ namedWindow flags
 * @param flags
 * @return
 */
int php_window_flags_to_c_flags(int flags){
    if(flags == 1){
        return WINDOW_NORMAL;
    }else if(flags==2){
        return WINDOW_AUTOSIZE;
    }else if(flags==3){
        return WINDOW_OPENGL;
    }else if(flags==4){
        return WINDOW_FULLSCREEN;
    }else if(flags==5){
        return WINDOW_FREERATIO;
    }else if(flags==6){
        return WINDOW_GUI_EXPANDED;
    }else if(flags==7){
        return WINDOW_GUI_NORMAL;
    }
    return WINDOW_AUTOSIZE;
}

/**
 * CV\namedWindow
 * @param window_name
 * @param flags
 */
PHP_FUNCTION(opencv_named_window){
    char *window_name;
    long window_name_len;
    long flags = 2;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|l", &window_name, &window_name_len, &flags) == FAILURE) {
        RETURN_NULL();
    }
    namedWindow(window_name,php_window_flags_to_c_flags((int)flags));
    RETURN_NULL();
}

struct opencv_fcall_info_cb{
    zend_fcall_info *fci;
    zend_fcall_info_cache *fci_cache;
};

opencv_fcall_info_cb * opencv_fcall_info_cb_create(zend_fcall_info *fci_ptr, zend_fcall_info_cache *fci_cache_ptr) {
    opencv_fcall_info_cb *cb = new opencv_fcall_info_cb;
    cb->fci = new zend_fcall_info;
    cb->fci_cache = new zend_fcall_info_cache;

    memcpy(cb->fci, fci_ptr, sizeof(zend_fcall_info));
    memcpy(cb->fci_cache, fci_cache_ptr, sizeof(zend_fcall_info_cache));
    Z_TRY_ADDREF(cb->fci->function_name);
    cb->fci->param_count = 0;
    cb->fci->no_separation = 1;
    cb->fci->retval = NULL;

    return cb;
}

void opencv_create_trackbar_callback(int pos, void* userdata){
    opencv_fcall_info_cb *fci_s=(opencv_fcall_info_cb*)userdata;

    zval retval;
    zval args[1];
    ZVAL_LONG(&args[0], (long)pos);//将滑动条滑动的值传入到闭包参数中
    fci_s->fci->param_count = 1;
    fci_s->fci->params = args;
    fci_s->fci->retval = &retval;

    zend_call_function(fci_s->fci, fci_s->fci_cache);
    zval_ptr_dtor(&args[0]);
}

/**
 * todo Total 1 memory leaks detected
 * CV\createTrackbar
 * @param execute_data
 * @param return_value
 */
PHP_FUNCTION(opencv_create_trackbar){
    char *trackbarname, *winname;
    long value, count, trackbarname_len,winname_len;
    zval retval;

    zend_fcall_info fci;
    zend_fcall_info_cache fci_cache;
    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssll|f",
                              &trackbarname, &trackbarname_len,
                              &winname,&winname_len,
                              &value,&count,
                              &fci, &fci_cache) == FAILURE) {
        return;
    }

    int *trackbar_value_ptr = new int(value);

    opencv_fcall_info_cb *cb = opencv_fcall_info_cb_create(&fci, &fci_cache);
    createTrackbar(trackbarname, winname, trackbar_value_ptr, (int)count,opencv_create_trackbar_callback,cb);
    RETURN_NULL();
}

PHP_FUNCTION(opencv_destroy_window){
    char *winname;
    long winname_len;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &winname,&winname_len) == FAILURE) {
        return;
    }

    try{
        destroyWindow(winname);
    }catch (Exception e){
        opencv_throw_exception(e.what());
    }

    RETURN_NULL();

}

void opencv_highgui_init(int module_number)
{
    /**
     * ! ! Flags for CV\namedWindow
     */
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_NORMAL", 1, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_AUTOSIZE", 2, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_OPENGL", 3, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_FULLSCREEN", 4, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_FREERATIO", 5, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_GUI_EXPANDED", 6, CONST_CS | CONST_PERSISTENT);
    REGISTER_NS_LONG_CONSTANT(OPENCV_NS, "WINDOW_GUI_NORMAL", 7, CONST_CS | CONST_PERSISTENT);
}<|endoftext|>