<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//Root includes
#include <TObjArray.h>
#include <TH1F.h>
#include <TString.h>
#include <TMath.h>
#include <TF1.h>
#include <TRandom.h>
#include <TDirectory.h>
#include <TFile.h>
#include "TTreeStream.h"

//AliRoot includes
#include "AliDAQ.h"
#include "AliLog.h"
#include "AliRawReader.h"
#include "AliPMDRawStream.h"
#include "AliPMDddldata.h"
#include "AliBitPacking.h"
//header file
#include "AliPMDCalibPedestal.h"

ClassImp(AliPMDCalibPedestal)

AliPMDCalibPedestal::AliPMDCalibPedestal() :
  TObject(),
  fRunNumber(-1),
  fEventNumber(0)
{
    //
    // default constructor
    //

    for (int i = 0; i < kDet; i++)
    {
	for (int j = 0; j < kMaxSMN; j++)
	{
	    for (int k = 0; k < kMaxRow; k++)
	    {
		for (int l = 0; l < kMaxCol; l++)
		{
		    fPedVal[i][j][k][l]   = 0.;
		    fPedValSq[i][j][k][l] = 0.;
		    fPedCount[i][j][k][l] = 0.;
		}
	    }
	}
    }

    for (int i = 0; i < 6; i++)
    {
	for (int j = 0; j < 51; j++)
	{
	    for (int k = 0; k < 25; k++)
	    {
		for (int l = 0; l < 64; l++)
		{
		    fPedChain[i][j][k][l] = -1;
		}
	    }
	}
    }

}
//_____________________________________________________________________
AliPMDCalibPedestal::AliPMDCalibPedestal(const AliPMDCalibPedestal &ped) :
  TObject(ped),
  fRunNumber(ped.fRunNumber),
  fEventNumber(ped.fEventNumber)
{
    //
    // copy constructor
    //
    for (int i = 0; i < kDet; i++)
    {
	for (int j = 0; j < kMaxSMN; j++)
	{
	    for (int k = 0; k < kMaxRow; k++)
	    {
		for (int l = 0; l < kMaxCol; l++)
		{
		    fPedVal[i][j][k][l]   = ped.fPedVal[i][j][k][l];
		    fPedValSq[i][j][k][l] = ped.fPedValSq[i][j][k][l];
		    fPedCount[i][j][k][l] = ped.fPedCount[i][j][k][l];
		}
	    }
	}
    }

    for (int i = 0; i < 6; i++)
    {
	for (int j = 0; j < 51; j++)
	{
	    for (int k = 0; k < 25; k++)
	    {
		for (int l = 0; l < 64; l++)
		{
		    fPedChain[i][j][k][l] = -1;
		}
	    }
	}
    }

}
//_____________________________________________________________________
AliPMDCalibPedestal& AliPMDCalibPedestal::operator = (const  AliPMDCalibPedestal &source)
{
  //
  // assignment operator
  //
  if (&source == this) return *this;
  new (this) AliPMDCalibPedestal(source);

  return *this;
}
//_____________________________________________________________________
AliPMDCalibPedestal::~AliPMDCalibPedestal()
{
    //
    // destructor
    //
}
//_____________________________________________________________________
Bool_t AliPMDCalibPedestal::ProcessEvent(AliRawReader *rawReader, TObjArray *pmdddlcont)
{
  //
  //  Event processing loop - AliRawReader
  //

    const Int_t kDDL = AliDAQ::NumberOfDdls("PMD");

    UInt_t detsmnrowcol = 0;
    UInt_t pbus = 0, mcm = 0, chno = 0;

    fRunNumber = rawReader->GetRunNumber();

    AliPMDRawStream rawStream(rawReader);

    fEventNumber++;

    Int_t iddl = -1;
    Int_t numberofDDLs = 0;

    while ((iddl = rawStream.DdlData(pmdddlcont)) >=0) {
      numberofDDLs++;
      Int_t ientries = pmdddlcont->GetEntries();
      //printf("iddl = %d ientries = %d\n",iddl, ientries);
      for (Int_t ient = 0; ient < ientries; ient++)
	{
	    AliPMDddldata *pmdddl = (AliPMDddldata*)pmdddlcont->UncheckedAt(ient);

	    Int_t det = pmdddl->GetDetector();
	    Int_t smn = pmdddl->GetSMN();
	    Int_t row = pmdddl->GetRow();
	    Int_t col = pmdddl->GetColumn();
	    Float_t sig = (Float_t) pmdddl->GetSignal();

	    pbus = (UInt_t) pmdddl->GetPatchBusId();
	    mcm  = (UInt_t) pmdddl->GetMCM();
	    chno = (UInt_t) pmdddl->GetChannel();

	    detsmnrowcol = 0;
	    AliBitPacking::PackWord(det,detsmnrowcol,0,7);
	    AliBitPacking::PackWord(smn,detsmnrowcol,8,15);
	    AliBitPacking::PackWord(row,detsmnrowcol,16,23);
	    AliBitPacking::PackWord(col,detsmnrowcol,24,31);

	    if (fPedChain[iddl][pbus][mcm][chno] == -1)
		fPedChain[iddl][pbus][mcm][chno] = (Int_t)detsmnrowcol;

	    fPedVal[det][smn][row][col]   += sig;
	    fPedValSq[det][smn][row][col] += sig*sig;
	    fPedCount[det][smn][row][col]++;
	}
      pmdddlcont->Delete();
    }

    if (numberofDDLs < kDDL)
      return kFALSE;
    return kTRUE;
}
//_____________________________________________________________________

void AliPMDCalibPedestal::Analyse(TTree *pedtree)
{
    //
    //  Calculate pedestal Mean and RMS
    //

    UInt_t  detsmnrowcol = 0;
    Int_t   det = 0, sm = 0, row = 0, col = 0;
    Int_t   idet = 0, ism = 0, irow = 0, icol = 0;
    Double_t mean = 0., rms = 0.;
    Double_t meansq = 0., diff = 0.;

    FILE *fpw0 = fopen("pedestal2304.ped","w");
    FILE *fpw1 = fopen("pedestal2305.ped","w");
    FILE *fpw2 = fopen("pedestal2306.ped","w");
    FILE *fpw3 = fopen("pedestal2307.ped","w");
    FILE *fpw4 = fopen("pedestal2308.ped","w");
    FILE *fpw5 = fopen("pedestal2309.ped","w");

    fprintf(fpw0,"//=============================================\n");
    fprintf(fpw0,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw0,"//=============================================\n");
    fprintf(fpw0,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw0,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw0,"//---------------------------------------------\n");
    fprintf(fpw0,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw0,"//---------------------------------------------\n");

    fprintf(fpw1,"//=============================================\n");
    fprintf(fpw1,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw1,"//=============================================\n");
    fprintf(fpw1,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw1,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw1,"//---------------------------------------------\n");
    fprintf(fpw1,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");

    fprintf(fpw2,"//=============================================\n");
    fprintf(fpw2,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw2,"//=============================================\n");
    fprintf(fpw2,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw2,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw2,"//---------------------------------------------\n");
    fprintf(fpw2,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw2,"//---------------------------------------------\n");

    fprintf(fpw3,"//=============================================\n");
    fprintf(fpw3,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw3,"//=============================================\n");
    fprintf(fpw3,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw3,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw3,"//---------------------------------------------\n");
    fprintf(fpw3,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw3,"//---------------------------------------------\n");

    fprintf(fpw4,"//=============================================\n");
    fprintf(fpw4,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw4,"//=============================================\n");
    fprintf(fpw4,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw4,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw4,"//---------------------------------------------\n");
    fprintf(fpw4,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw4,"//---------------------------------------------\n");

    fprintf(fpw5,"//=============================================\n");
    fprintf(fpw5,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw5,"//=============================================\n");
    fprintf(fpw5,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw5,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw5,"//---------------------------------------------\n");
    fprintf(fpw5,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw5,"//---------------------------------------------\n");

    for(Int_t iddl = 0; iddl < 6; iddl++)
      {
	for(Int_t ibus = 1; ibus < 51; ibus++)
	  {
	    for(Int_t imcm = 1; imcm < 25; imcm++)
	      {
		for(Int_t ich = 0; ich < 64; ich++)
		  {

		    if (fPedChain[iddl][ibus][imcm][ich] != -1)
		      {
			detsmnrowcol = (UInt_t)fPedChain[iddl][ibus][imcm][ich];

			idet =  detsmnrowcol & 0x00FF;
			ism  = (detsmnrowcol >> 8) & 0x00FF;
			irow = (detsmnrowcol >> 16) & 0x00FF;
			icol = (detsmnrowcol >> 24) & 0x00FF;

			mean = 0.;
			rms  = 0.;
			if (fPedCount[idet][ism][irow][icol] > 0)
			  {
			    mean = fPedVal[idet][ism][irow][icol]/fPedCount[idet][ism][irow][icol];

			    meansq = fPedValSq[idet][ism][irow][icol]/fPedCount[idet][ism][irow][icol];

			    diff = meansq - mean*mean;
			    if (diff > 0.)
			      {
				rms  = sqrt(diff);
			      }
			    else
			      {
				rms = 0.;
			      }

			    if (iddl == 0)
			      {
				fprintf(fpw0,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 1)
			      {
				fprintf(fpw1,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 2)
			      {
				fprintf(fpw2,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 3)
			      {
				fprintf(fpw3,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 4)
			      {
				fprintf(fpw4,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 5)
			      {
				fprintf(fpw5,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			  }
		      }
		  }
	      }
	  }
      }

    fclose(fpw0);
    fclose(fpw1);
    fclose(fpw2);
    fclose(fpw3);
    fclose(fpw4);
    fclose(fpw5);

    pedtree->Branch("det",&det,"det/I");
    pedtree->Branch("sm",&sm,"sm/I");
    pedtree->Branch("row",&row,"row/I");
    pedtree->Branch("col",&col,"col/I");
    pedtree->Branch("mean",&mean,"mean/F");
    pedtree->Branch("rms",&rms,"rms/F");

    for (idet = 0; idet < kDet; idet++)
      {
	for (ism = 0; ism < kMaxSMN; ism++)
	  {
	    for (irow = 0; irow < kMaxRow; irow++)
	      {
		for (icol = 0; icol < kMaxCol; icol++)
		  {
		    det  = idet;
		    sm   = ism;
		    row  = irow;
		    col  = icol;
		    mean = 0.;
		    rms  = 0.;

		    if (fPedCount[idet][ism][irow][icol] > 0)
		      {
			mean = fPedVal[idet][ism][irow][icol]/fPedCount[idet][ism][irow][icol];

			meansq = fPedValSq[idet][ism][irow][icol]/fPedCount[idet][ism][irow][icol];

			diff = meansq - mean*mean;
			if (diff > 0.)
			  {
			    rms  = sqrt(diff);
			  }
			else
			  {
			    rms = 0.;
			  }
			pedtree->Fill();
		      }

		  }
	      }
	  }
      }
}
// -------------------------------------------------------------------
<commit_msg>Double_t -> Float_t for the variables used in a tree<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//Root includes
#include <TObjArray.h>
#include <TH1F.h>
#include <TString.h>
#include <TMath.h>
#include <TF1.h>
#include <TRandom.h>
#include <TDirectory.h>
#include <TFile.h>
#include "TTreeStream.h"

//AliRoot includes
#include "AliDAQ.h"
#include "AliLog.h"
#include "AliRawReader.h"
#include "AliPMDRawStream.h"
#include "AliPMDddldata.h"
#include "AliBitPacking.h"
//header file
#include "AliPMDCalibPedestal.h"

ClassImp(AliPMDCalibPedestal)

AliPMDCalibPedestal::AliPMDCalibPedestal() :
  TObject(),
  fRunNumber(-1),
  fEventNumber(0)
{
    //
    // default constructor
    //

    for (int i = 0; i < kDet; i++)
    {
	for (int j = 0; j < kMaxSMN; j++)
	{
	    for (int k = 0; k < kMaxRow; k++)
	    {
		for (int l = 0; l < kMaxCol; l++)
		{
		    fPedVal[i][j][k][l]   = 0.;
		    fPedValSq[i][j][k][l] = 0.;
		    fPedCount[i][j][k][l] = 0.;
		}
	    }
	}
    }

    for (int i = 0; i < 6; i++)
    {
	for (int j = 0; j < 51; j++)
	{
	    for (int k = 0; k < 25; k++)
	    {
		for (int l = 0; l < 64; l++)
		{
		    fPedChain[i][j][k][l] = -1;
		}
	    }
	}
    }

}
//_____________________________________________________________________
AliPMDCalibPedestal::AliPMDCalibPedestal(const AliPMDCalibPedestal &ped) :
  TObject(ped),
  fRunNumber(ped.fRunNumber),
  fEventNumber(ped.fEventNumber)
{
    //
    // copy constructor
    //
    for (int i = 0; i < kDet; i++)
    {
	for (int j = 0; j < kMaxSMN; j++)
	{
	    for (int k = 0; k < kMaxRow; k++)
	    {
		for (int l = 0; l < kMaxCol; l++)
		{
		    fPedVal[i][j][k][l]   = ped.fPedVal[i][j][k][l];
		    fPedValSq[i][j][k][l] = ped.fPedValSq[i][j][k][l];
		    fPedCount[i][j][k][l] = ped.fPedCount[i][j][k][l];
		}
	    }
	}
    }

    for (int i = 0; i < 6; i++)
    {
	for (int j = 0; j < 51; j++)
	{
	    for (int k = 0; k < 25; k++)
	    {
		for (int l = 0; l < 64; l++)
		{
		    fPedChain[i][j][k][l] = -1;
		}
	    }
	}
    }

}
//_____________________________________________________________________
AliPMDCalibPedestal& AliPMDCalibPedestal::operator = (const  AliPMDCalibPedestal &source)
{
  //
  // assignment operator
  //
  if (&source == this) return *this;
  new (this) AliPMDCalibPedestal(source);

  return *this;
}
//_____________________________________________________________________
AliPMDCalibPedestal::~AliPMDCalibPedestal()
{
    //
    // destructor
    //
}
//_____________________________________________________________________
Bool_t AliPMDCalibPedestal::ProcessEvent(AliRawReader *rawReader, TObjArray *pmdddlcont)
{
  //
  //  Event processing loop - AliRawReader
  //

    const Int_t kDDL = AliDAQ::NumberOfDdls("PMD");

    UInt_t detsmnrowcol = 0;
    UInt_t pbus = 0, mcm = 0, chno = 0;

    fRunNumber = rawReader->GetRunNumber();

    AliPMDRawStream rawStream(rawReader);

    fEventNumber++;

    Int_t iddl = -1;
    Int_t numberofDDLs = 0;

    while ((iddl = rawStream.DdlData(pmdddlcont)) >=0) {
      numberofDDLs++;
      Int_t ientries = pmdddlcont->GetEntries();
      //printf("iddl = %d ientries = %d\n",iddl, ientries);
      for (Int_t ient = 0; ient < ientries; ient++)
	{
	    AliPMDddldata *pmdddl = (AliPMDddldata*)pmdddlcont->UncheckedAt(ient);

	    Int_t det = pmdddl->GetDetector();
	    Int_t smn = pmdddl->GetSMN();
	    Int_t row = pmdddl->GetRow();
	    Int_t col = pmdddl->GetColumn();
	    Float_t sig = (Float_t) pmdddl->GetSignal();

	    pbus = (UInt_t) pmdddl->GetPatchBusId();
	    mcm  = (UInt_t) pmdddl->GetMCM();
	    chno = (UInt_t) pmdddl->GetChannel();

	    detsmnrowcol = 0;
	    AliBitPacking::PackWord(det,detsmnrowcol,0,7);
	    AliBitPacking::PackWord(smn,detsmnrowcol,8,15);
	    AliBitPacking::PackWord(row,detsmnrowcol,16,23);
	    AliBitPacking::PackWord(col,detsmnrowcol,24,31);

	    if (fPedChain[iddl][pbus][mcm][chno] == -1)
		fPedChain[iddl][pbus][mcm][chno] = (Int_t)detsmnrowcol;

	    fPedVal[det][smn][row][col]   += sig;
	    fPedValSq[det][smn][row][col] += sig*sig;
	    fPedCount[det][smn][row][col]++;
	}
      pmdddlcont->Delete();
    }

    if (numberofDDLs < kDDL)
      return kFALSE;
    return kTRUE;
}
//_____________________________________________________________________

void AliPMDCalibPedestal::Analyse(TTree *pedtree)
{
    //
    //  Calculate pedestal Mean and RMS
    //

    UInt_t  detsmnrowcol = 0;
    Int_t   det = 0, sm = 0, row = 0, col = 0;
    Int_t   idet = 0, ism = 0, irow = 0, icol = 0;
    Float_t mean = 0., rms = 0.;
    Double_t meansq = 0., diff = 0.;

    FILE *fpw0 = fopen("pedestal2304.ped","w");
    FILE *fpw1 = fopen("pedestal2305.ped","w");
    FILE *fpw2 = fopen("pedestal2306.ped","w");
    FILE *fpw3 = fopen("pedestal2307.ped","w");
    FILE *fpw4 = fopen("pedestal2308.ped","w");
    FILE *fpw5 = fopen("pedestal2309.ped","w");

    fprintf(fpw0,"//=============================================\n");
    fprintf(fpw0,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw0,"//=============================================\n");
    fprintf(fpw0,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw0,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw0,"//---------------------------------------------\n");
    fprintf(fpw0,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw0,"//---------------------------------------------\n");

    fprintf(fpw1,"//=============================================\n");
    fprintf(fpw1,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw1,"//=============================================\n");
    fprintf(fpw1,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw1,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw1,"//---------------------------------------------\n");
    fprintf(fpw1,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");

    fprintf(fpw2,"//=============================================\n");
    fprintf(fpw2,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw2,"//=============================================\n");
    fprintf(fpw2,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw2,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw2,"//---------------------------------------------\n");
    fprintf(fpw2,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw2,"//---------------------------------------------\n");

    fprintf(fpw3,"//=============================================\n");
    fprintf(fpw3,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw3,"//=============================================\n");
    fprintf(fpw3,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw3,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw3,"//---------------------------------------------\n");
    fprintf(fpw3,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw3,"//---------------------------------------------\n");

    fprintf(fpw4,"//=============================================\n");
    fprintf(fpw4,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw4,"//=============================================\n");
    fprintf(fpw4,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw4,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw4,"//---------------------------------------------\n");
    fprintf(fpw4,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw4,"//---------------------------------------------\n");

    fprintf(fpw5,"//=============================================\n");
    fprintf(fpw5,"//     Pedestal file Calculated by Online DA\n");
    fprintf(fpw5,"//=============================================\n");
    fprintf(fpw5,"//     RUN             :%d\n",fRunNumber);
    fprintf(fpw5,"//     Statistics      :%d\n",fEventNumber);
    fprintf(fpw5,"//---------------------------------------------\n");
    fprintf(fpw5,"//format:CHAIN_NO  FEE_ID  CHANNEL  MEAN  SIGMA\n");
    fprintf(fpw5,"//---------------------------------------------\n");

    for(Int_t iddl = 0; iddl < 6; iddl++)
      {
	for(Int_t ibus = 1; ibus < 51; ibus++)
	  {
	    for(Int_t imcm = 1; imcm < 25; imcm++)
	      {
		for(Int_t ich = 0; ich < 64; ich++)
		  {

		    if (fPedChain[iddl][ibus][imcm][ich] != -1)
		      {
			detsmnrowcol = (UInt_t)fPedChain[iddl][ibus][imcm][ich];

			idet =  detsmnrowcol & 0x00FF;
			ism  = (detsmnrowcol >> 8) & 0x00FF;
			irow = (detsmnrowcol >> 16) & 0x00FF;
			icol = (detsmnrowcol >> 24) & 0x00FF;

			mean = 0.;
			rms  = 0.;
			if (fPedCount[idet][ism][irow][icol] > 0)
			  {
			    mean = fPedVal[idet][ism][irow][icol]/fPedCount[idet][ism][irow][icol];

			    meansq = fPedValSq[idet][ism][irow][icol]/fPedCount[idet][ism][irow][icol];

			    diff = meansq - mean*mean;
			    if (diff > 0.)
			      {
				rms  = sqrt(diff);
			      }
			    else
			      {
				rms = 0.;
			      }

			    if (iddl == 0)
			      {
				fprintf(fpw0,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 1)
			      {
				fprintf(fpw1,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 2)
			      {
				fprintf(fpw2,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 3)
			      {
				fprintf(fpw3,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 4)
			      {
				fprintf(fpw4,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			    else if (iddl == 5)
			      {
				fprintf(fpw5,"%d %d %d %f %f\n",
					ibus, imcm, ich, mean, rms);
			      }
			  }
		      }
		  }
	      }
	  }
      }

    fclose(fpw0);
    fclose(fpw1);
    fclose(fpw2);
    fclose(fpw3);
    fclose(fpw4);
    fclose(fpw5);

    pedtree->Branch("det",&det,"det/I");
    pedtree->Branch("sm",&sm,"sm/I");
    pedtree->Branch("row",&row,"row/I");
    pedtree->Branch("col",&col,"col/I");
    pedtree->Branch("mean",&mean,"mean/F");
    pedtree->Branch("rms",&rms,"rms/F");

    for (idet = 0; idet < kDet; idet++)
      {
	for (ism = 0; ism < kMaxSMN; ism++)
	  {
	    for (irow = 0; irow < kMaxRow; irow++)
	      {
		for (icol = 0; icol < kMaxCol; icol++)
		  {
		    det  = idet;
		    sm   = ism;
		    row  = irow;
		    col  = icol;
		    mean = 0.;
		    rms  = 0.;

		    if (fPedCount[idet][ism][irow][icol] > 0)
		      {
			mean = fPedVal[idet][ism][irow][icol]/fPedCount[idet][ism][irow][icol];

			meansq = fPedValSq[idet][ism][irow][icol]/fPedCount[idet][ism][irow][icol];

			diff = meansq - mean*mean;
			if (diff > 0.)
			  {
			    rms  = sqrt(diff);
			  }
			else
			  {
			    rms = 0.;
			  }
			pedtree->Fill();
		      }

		  }
	      }
	  }
      }
}
// -------------------------------------------------------------------
<|endoftext|>


<commit_before>/*******************************************************************************/
/* This program reads in clock phase data provided by any of the phase parsers */
/*  and calculates the Total Variance, outputting the results to the standard  */
/*  output in a format that can be used by allanplot to view the data.         */
/*                                                                             */
/*                                                                             */
/* Written by Tim Craddock                                                     */
/* Last Updated March 20, 2008                                                 */
/*******************************************************************************/

#include <iostream>
#include <vector>

#include <stdio.h>
#include <string.h>
#include <math.h>

using namespace std;

double Xstr(vector <double> phaseArray, int N, int index);

int main()
{
	// Structures used to store time and clock phase information
	vector <double> timeArray;
	vector <double> phaseArray;
	long double time, phase;
	long unsigned int numPoints, i;

	// All of the time and clock phase data is read in from the standard input
	i = 0;
	while(!feof(stdin))
	{
		cin >> time >> phase;

		timeArray.resize(i+1);
		phaseArray.resize(i+1);

		timeArray[i] = time;
		phaseArray[i] = phase;
		i++;
	}

	numPoints = i-1;

	/*************
	*************/

	// Variables used in Total Variance calculations
	double Tau, Tau0, sum, Tot;
	int N, m;

	// Ensures there are at least the minimum number of points required to do calculations
	N = numPoints;
	if(N > 1) Tau0 = timeArray[1] - timeArray[0];
	else
	{
		cout << "Not Enough Points to Calculate Tau0" << endl;
		Tau0;
	}

	// Splain tot var
	for(m = 1; m < N; m++)
	{
		Tau = m*Tau0;
		Tot = 0;

		for(i = 1; i < N-1; i++)
		{
			sum = 0;
			sum = Xstr(phaseArray, N, i-m) - 2*Xstr(phaseArray, N, i) + Xstr(phaseArray, N, i+m);
			Tot += sum * sum;
		}

		Tot = Tot / (2.0*Tau*Tau*((double)N-2.0));
		fprintf(stdout, "%.0f %.4e \n", Tau, Tot); // outputs results to the standard output
	}

	/*************
	*************/

	return(0);
}

double Xstr(vector <double> phaseArray, int N, int index)
{

	if(index < 0)
	{
		2.0*phaseArray[0]-phaseArray[abs(index)];
	}
	else if(index > (N-1))
	{
		2.0*phaseArray[N-1]-phaseArray[N-1-index];
	}

	return(phaseArray[index]);
}
<commit_msg>Clock Stability Analysis Tools<commit_after><|endoftext|>


<commit_before>//
//     Copyright 2010, Kay Hayen, mailto:kayhayen@gmx.de
//
//     Part of "Nuitka", an attempt of building an optimizing Python compiler
//     that is compatible and integrates with CPython, but also works on its
//     own.
//
//     If you submit Kay Hayen patches to this software in either form, you
//     automatically grant him a copyright assignment to the code, or in the
//     alternative a BSD license to the code, should your jurisdiction prevent
//     this. Obviously it won't affect code that comes to him indirectly or
//     code you don't submit to him.
//
//     This is to reserve my ability to re-license the code at any time, e.g.
//     the PSF. With this version of Nuitka, using it for Closed Source will
//     not be allowed.
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU General Public License as published by
//     the Free Software Foundation, version 3 of the License.
//
//     This program is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU General Public License for more details.
//
//     You should have received a copy of the GNU General Public License
//     along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//     Please leave the whole of this copyright notice intact.
//
#ifndef __NUITKA_PRINTING_H__
#define __NUITKA_PRINTING_H__

// Helper functions for print. Need to play nice with Python softspace behaviour.

#if PY_MAJOR_VERSION < 3

static void PRINT_ITEM_TO( PyObject *file, PyObject *object )
{
    PyObject *str = PyObject_Str( object );
    PyObject *print;
    bool softspace;

    if ( str == NULL )
    {
        PyErr_Clear();

        print = object;
        softspace = false;
    }
    else
    {
        char *buffer;
        Py_ssize_t length;

        int status = PyString_AsStringAndSize( str, &buffer, &length );
        assert( status != -1 );

        softspace = length > 0 && buffer[length - 1 ] == '\t';

        print = str;
    }

    // Check for soft space indicator, need to hold a reference to the file
    // or else __getattr__ may release "file" in the mean time.
    if ( PyFile_SoftSpace( file, !softspace ) )
    {
        if (unlikely( PyFile_WriteString( " ", file ) == -1 ))
        {
            Py_DECREF( file );
            Py_DECREF( str );
            throw _PythonException();
        }
    }

    if ( unlikely( PyFile_WriteObject( print, file, Py_PRINT_RAW ) == -1 ))
    {
        Py_XDECREF( str );
        throw _PythonException();
    }

    Py_XDECREF( str );

    if ( softspace )
    {
        PyFile_SoftSpace( file, !softspace );
    }
}

static void PRINT_NEW_LINE_TO( PyObject *file )
{
    if (unlikely( PyFile_WriteString( "\n", file ) == -1))
    {
        throw _PythonException();
    }

    PyFile_SoftSpace( file, 0 );
}

#endif

static PyObject *GET_STDOUT()
{
    PyObject *stdout = PySys_GetObject( (char *)"stdout" );

    if (unlikely( stdout == NULL ))
    {
        PyErr_Format( PyExc_RuntimeError, "lost sys.stdout" );
        throw _PythonException();
    }

    return stdout;
}

#if PY_MAJOR_VERSION < 3

template<typename... P>
static void PRINT_ITEMS( bool new_line, PyObject *file, P...eles )
{
    int size = sizeof...(eles);

    if ( file == NULL || file == Py_None )
    {
        file = GET_STDOUT();
    }

    // Need to hold a reference for the case that the printing somehow removes
    // the last reference to "file" while printing.
    Py_INCREF( file );

    PyObject *elements[] = {eles...};

    for( int i = 0; i < size; i++ )
    {
        PRINT_ITEM_TO( file, elements[ i ] );
    }

    if ( new_line )
    {
        PRINT_NEW_LINE_TO( file );
    }

    // TODO: Use of PyObjectTemporary should be possible, this won't be
    // exception safe otherwise
    Py_DECREF( file );
}

static void PRINT_NEW_LINE( void )
{
    PRINT_NEW_LINE_TO( GET_STDOUT() );
}

#endif

#endif
<commit_msg>use a PyObjectTemporary to handle reference<commit_after>//
//     Copyright 2010, Kay Hayen, mailto:kayhayen@gmx.de
//
//     Part of "Nuitka", an attempt of building an optimizing Python compiler
//     that is compatible and integrates with CPython, but also works on its
//     own.
//
//     If you submit Kay Hayen patches to this software in either form, you
//     automatically grant him a copyright assignment to the code, or in the
//     alternative a BSD license to the code, should your jurisdiction prevent
//     this. Obviously it won't affect code that comes to him indirectly or
//     code you don't submit to him.
//
//     This is to reserve my ability to re-license the code at any time, e.g.
//     the PSF. With this version of Nuitka, using it for Closed Source will
//     not be allowed.
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU General Public License as published by
//     the Free Software Foundation, version 3 of the License.
//
//     This program is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU General Public License for more details.
//
//     You should have received a copy of the GNU General Public License
//     along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//     Please leave the whole of this copyright notice intact.
//
#ifndef __NUITKA_PRINTING_H__
#define __NUITKA_PRINTING_H__

// Helper functions for print. Need to play nice with Python softspace behaviour.

#if PY_MAJOR_VERSION < 3

static void PRINT_ITEM_TO( PyObject *file, PyObject *object )
{
    PyObject *str = PyObject_Str( object );
    PyObject *print;
    bool softspace;

    if ( str == NULL )
    {
        PyErr_Clear();

        print = object;
        softspace = false;
    }
    else
    {
        char *buffer;
        Py_ssize_t length;

        int status = PyString_AsStringAndSize( str, &buffer, &length );
        assert( status != -1 );

        softspace = length > 0 && buffer[length - 1 ] == '\t';

        print = str;
    }

    // Check for soft space indicator, need to hold a reference to the file
    // or else __getattr__ may release "file" in the mean time.
    if ( PyFile_SoftSpace( file, !softspace ) )
    {
        if (unlikely( PyFile_WriteString( " ", file ) == -1 ))
        {
            Py_DECREF( file );
            Py_DECREF( str );
            throw _PythonException();
        }
    }

    if ( unlikely( PyFile_WriteObject( print, file, Py_PRINT_RAW ) == -1 ))
    {
        Py_XDECREF( str );
        throw _PythonException();
    }

    Py_XDECREF( str );

    if ( softspace )
    {
        PyFile_SoftSpace( file, !softspace );
    }
}

static void PRINT_NEW_LINE_TO( PyObject *file )
{
    if (unlikely( PyFile_WriteString( "\n", file ) == -1))
    {
        throw _PythonException();
    }

    PyFile_SoftSpace( file, 0 );
}

#endif

static PyObject *GET_STDOUT()
{
    PyObject *stdout = PySys_GetObject( (char *)"stdout" );

    if (unlikely( stdout == NULL ))
    {
        PyErr_Format( PyExc_RuntimeError, "lost sys.stdout" );
        throw _PythonException();
    }

    return stdout;
}

#if PY_MAJOR_VERSION < 3

template<typename... P>
static void PRINT_ITEMS( bool new_line, PyObject *file, P...eles )
{
    int size = sizeof...(eles);

    if ( file == NULL || file == Py_None )
    {
        file = GET_STDOUT();
    }

    // Need to hold a reference for the case that the printing somehow removes
    // the last reference to "file" while printing.
    Py_INCREF( file );
    PyObjectTemporary file_reference( file );

    PyObject *elements[] = {eles...};

    for( int i = 0; i < size; i++ )
    {
        PRINT_ITEM_TO( file, elements[ i ] );
    }

    if ( new_line )
    {
        PRINT_NEW_LINE_TO( file );
    }
}

static void PRINT_NEW_LINE( void )
{
    PRINT_NEW_LINE_TO( GET_STDOUT() );
}

#endif

#endif
<|endoftext|>


<commit_before>// Copyright ***********************************************************
//
// File ecmdClientCapi.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************

// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************

/* $Header$ */

//----------------------------------------------------------------------
//  Includes
//----------------------------------------------------------------------
#include <dlfcn.h>
#include <string>
#include <stdio.h>

#include <ecmdClientCapi.H>
#include <ecmdDllCapi.H>
#include <ecmdUtils.H>

//----------------------------------------------------------------------
//  User Types
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Constants
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Macros
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Internal Function Prototypes
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Global Variables
//----------------------------------------------------------------------

#ifndef ECMD_STATIC_FUNCTIONS
/* These are from ecmdClientCapiFunc.C */
extern void * dlHandle;
#endif

#ifndef ECMD_STRIP_DEBUG
/* @brief This is used to output Debug messages on the Client side */
int ecmdClientDebug = 0;
#endif

//---------------------------------------------------------------------
// Member Function Specifications
//---------------------------------------------------------------------

// Change Log *********************************************************
//
//  Flag Reason   Vers Date     Coder    Description
//  ---- -------- ---- -------- -------- ------------------------------
//                              CENGEL   Initial Creation
//
// End Change Log *****************************************************

int ecmdLoadDll(std::string i_dllName) {

  const char* dlError;
  int rc = ECMD_SUCCESS;

#ifdef ECMD_STRIP_DEBUG
  char* tmpptr = getenv("ECMD_DEBUG");
  if (tmpptr != NULL)
    ecmdClientDebug = atoi(tmpptr);
  else
    ecmdClientDebug = 0;
#endif

#ifndef ECMD_STATIC_FUNCTIONS
#ifdef _AIX
  /* clean up the machine from previous tests */
  system("slibclean");
#endif

  /* --------------------- */
  /* load DLL              */
  /* --------------------- */
  if (i_dllName.size() == 0) {
    /* Let's try to get it from the env var */
    char * tempptr = getenv("ECMD_DLL_FILE");  /* is there a ECMD_DLL_FILE environment variable? */
    if (tempptr != NULL) {
      i_dllName = tempptr;
    } else {
      fprintf(stderr,"ecmdLoadDll: Unable to find DLL to load, you must set ECMD_DLL_FILE\n");
      return ECMD_INVALID_DLL_FILENAME;
    }
  }

  printf("loadDll: loading %s ...\n", i_dllName.c_str());
  dlHandle = dlopen(i_dllName.c_str(), RTLD_LAZY);
  if (!dlHandle) {
    if ((dlError = dlerror()) != NULL) {
      printf("ERROR: loadDll: Problems loading '%s' : %s\n", i_dllName.c_str(), dlError);
      return ECMD_DLL_LOAD_FAILURE;
    }
  } else {
    printf("loadDll: load successful\n");
  }

  /* Now we need to call loadDll on the dll itself so it can initialize */

  int (*Function)(const char *,int) =
      (int(*)(const char *,int))(void*)dlsym(dlHandle, "dllLoadDll");
  if (!Function) {
    fprintf(stderr,"ecmdLoadDll: Unable to find LoadDll function, must be an invalid DLL\n");
    rc = ECMD_DLL_LOAD_FAILURE;
  } else {
    rc = (*Function)(ECMD_CAPI_VERSION, ecmdClientDebug);
  }

#else
  rc = dllLoadDll(ECMD_CAPI_VERSION, ecmdClientDebug);

#endif /* ECMD_STATIC_FUNCTIONS */

  return rc;
}

int ecmdUnloadDll() {

  int rc = ECMD_SUCCESS;
  int c_rc = ECMD_SUCCESS;

#ifdef ECMD_STATIC_FUNCTIONS
  rc = dllUnloadDll();

#else

  if (dlHandle) {
    /* call DLL unload */
    int (*Function)() =
      (int(*)())(void*)dlsym(dlHandle, "dllUnloadDll");
    if (!Function) {
      fprintf(stderr,"ecmdUnloadDll: Unable to find UnloadDll function, must be an invalid DLL\n");
      rc = ECMD_DLL_UNLOAD_FAILURE;
      return rc;
    }
    rc = (*Function)();

    /* release DLL */
    const char* dlError;

    c_rc = dlclose(dlHandle);
    if (c_rc) {
      if ((dlError = dlerror()) != NULL) {
        fprintf(stderr,"ERROR: ecmdUnloadDll: %s\n", dlError);
        return ECMD_DLL_UNLOAD_FAILURE;
      }
    }
  }
  dlHandle = NULL;
#endif

  return rc;
}

int ecmdCommandArgs(int* i_argc, char** i_argv[]) {

  int rc = ECMD_SUCCESS;

#ifdef ECMD_STATIC_FUNCTIONS
  rc = dllCommonCommandArgs(i_argc, i_argv);

#else

  /* call DLL common command args */
  int (*Function)(int*, char***) =
    (int(*)(int*, char***))(void*)dlsym(dlHandle, "dllCommonCommandArgs");
  if (!Function) {
    fprintf(stderr,"ecmdCommandArgs: Unable to find dllCommonCommandArgs function, must be an invalid DLL\n");
    rc = ECMD_DLL_INVALID;
    return rc;
  }
  rc = (*Function)(i_argc, i_argv);

#endif

  return rc;
}

bool ecmdQueryTargetConfigured(ecmdChipTarget i_target, ecmdQueryData * i_queryData) {
  int rc = ECMD_SUCCESS;
  bool ret = false;
  bool myQuery = false;
  ecmdChipTarget queryTarget;

  std::list<ecmdCageData>::iterator ecmdCurCage;
  std::list<ecmdNodeData>::iterator ecmdCurNode;
  std::list<ecmdSlotData>::iterator ecmdCurSlot;
  std::list<ecmdChipData>::iterator ecmdCurChip;
  std::list<ecmdCoreData>::iterator ecmdCurCore;
  std::list<ecmdThreadData>::iterator ecmdCurThread;

  /* Do we need to do our own query ? */
  if (i_queryData == NULL) {
    i_queryData = new ecmdQueryData;
    queryTarget = i_target;
    myQuery = true;

    if (queryTarget.cageState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.cageState = ECMD_TARGET_QUERY_IGNORE;
    }

    if (queryTarget.nodeState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.nodeState = ECMD_TARGET_QUERY_IGNORE;
    }

    if (queryTarget.slotState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.slotState = ECMD_TARGET_QUERY_IGNORE;
    }

    if (queryTarget.chipTypeState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.chipTypeState = ECMD_TARGET_QUERY_IGNORE;
    }

    if (queryTarget.posState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.posState = ECMD_TARGET_QUERY_IGNORE;
    }

    if (queryTarget.coreState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.coreState = ECMD_TARGET_QUERY_IGNORE;
    }

    if (queryTarget.threadState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.threadState = ECMD_TARGET_QUERY_IGNORE;
    }

    rc = ecmdQueryConfig(queryTarget, *i_queryData, ECMD_QUERY_DETAIL_LOW);
    if (rc) {
      delete i_queryData;
      return ret;
    }
  }

  /* Now we have our data, let's start walking the data we have */
  for (ecmdCurCage = i_queryData->cageData.begin(); ecmdCurCage != i_queryData->cageData.end(); ecmdCurCage ++) {
    if (ecmdCurCage->cageId == i_target.cage) {
      if (i_target.nodeState == ECMD_TARGET_FIELD_UNUSED) {
        ret = true;
        break;
      }

      for (ecmdCurNode = ecmdCurCage->nodeData.begin(); ecmdCurNode != ecmdCurCage->nodeData.end(); ecmdCurNode ++) {
        if (ecmdCurNode->nodeId == i_target.node) {
          if (i_target.slotState == ECMD_TARGET_FIELD_UNUSED) {
            ret = true;
            break;
          }

          for (ecmdCurSlot = ecmdCurNode->slotData.begin(); ecmdCurSlot != ecmdCurNode->slotData.end(); ecmdCurSlot ++) {
            if (ecmdCurSlot->slotId == i_target.slot) {
              if (i_target.chipTypeState == ECMD_TARGET_FIELD_UNUSED || i_target.posState == ECMD_TARGET_FIELD_UNUSED) {
                ret = true;
                break;
              }

              for (ecmdCurChip = ecmdCurSlot->chipData.begin(); ecmdCurChip != ecmdCurSlot->chipData.end(); ecmdCurChip ++) {
                if (((ecmdCurChip->chipType == i_target.chipType) || (ecmdCurChip->chipCommonType == i_target.chipType)) &&
                    (ecmdCurChip->pos == i_target.pos)) {
                  if (i_target.coreState == ECMD_TARGET_FIELD_UNUSED) {
                    ret = true;
                    break;
                  }

                  for (ecmdCurCore = ecmdCurChip->coreData.begin(); ecmdCurCore != ecmdCurChip->coreData.end(); ecmdCurCore ++) {
                    if (ecmdCurCore->coreId == i_target.core) {
                      if (i_target.threadState == ECMD_TARGET_FIELD_UNUSED) {
                        ret = true;
                        break;
                      }

                      for (ecmdCurThread = ecmdCurCore->threadData.begin(); ecmdCurThread != ecmdCurCore->threadData.end(); ecmdCurThread ++) {
                        if (ecmdCurThread->threadId == i_target.thread) {
                          ret = true;
                          break;
                        } /* curThreadId == tarThreadId */
                      } /* for ecmdCurThread */

                      if (ret) break;
                    } /* curCoreId == tarCoreId */
                  } /* for ecmdCurCore */

                  if (ret) break;
                } /* curChipType == tarChipType && curChipPos == tarChipPos */
              } /* for ecmdCurChip */

              if (ret) break;
            } /* curSlotId == tarSlotId */
          } /* for ecmdCurSlot */

          if (ret) break;
        } /* curNodeId == tarNodeId */
      } /* for ecmdCurNode */

      if (ret) break;
    } /* curCageId == tarCageId */
  } /* for ecmdCurCage */

  if (myQuery) {
    delete i_queryData;
    i_queryData = NULL;
  }

  return rc;
}
<commit_msg>Fixed queryConfig<commit_after>// Copyright ***********************************************************
//
// File ecmdClientCapi.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************

// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************

/* $Header$ */

//----------------------------------------------------------------------
//  Includes
//----------------------------------------------------------------------
#include <dlfcn.h>
#include <string>
#include <stdio.h>

#include <ecmdClientCapi.H>
#include <ecmdDllCapi.H>
#include <ecmdUtils.H>

//----------------------------------------------------------------------
//  User Types
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Constants
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Macros
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Internal Function Prototypes
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Global Variables
//----------------------------------------------------------------------

#ifndef ECMD_STATIC_FUNCTIONS
/* These are from ecmdClientCapiFunc.C */
extern void * dlHandle;
#endif

#ifndef ECMD_STRIP_DEBUG
/* @brief This is used to output Debug messages on the Client side */
int ecmdClientDebug = 0;
#endif

//---------------------------------------------------------------------
// Member Function Specifications
//---------------------------------------------------------------------

// Change Log *********************************************************
//
//  Flag Reason   Vers Date     Coder    Description
//  ---- -------- ---- -------- -------- ------------------------------
//                              CENGEL   Initial Creation
//
// End Change Log *****************************************************

int ecmdLoadDll(std::string i_dllName) {

  const char* dlError;
  int rc = ECMD_SUCCESS;

#ifdef ECMD_STRIP_DEBUG
  char* tmpptr = getenv("ECMD_DEBUG");
  if (tmpptr != NULL)
    ecmdClientDebug = atoi(tmpptr);
  else
    ecmdClientDebug = 0;
#endif

#ifndef ECMD_STATIC_FUNCTIONS
#ifdef _AIX
  /* clean up the machine from previous tests */
  system("slibclean");
#endif

  /* --------------------- */
  /* load DLL              */
  /* --------------------- */
  if (i_dllName.size() == 0) {
    /* Let's try to get it from the env var */
    char * tempptr = getenv("ECMD_DLL_FILE");  /* is there a ECMD_DLL_FILE environment variable? */
    if (tempptr != NULL) {
      i_dllName = tempptr;
    } else {
      fprintf(stderr,"ecmdLoadDll: Unable to find DLL to load, you must set ECMD_DLL_FILE\n");
      return ECMD_INVALID_DLL_FILENAME;
    }
  }

  printf("loadDll: loading %s ...\n", i_dllName.c_str());
  dlHandle = dlopen(i_dllName.c_str(), RTLD_LAZY);
  if (!dlHandle) {
    if ((dlError = dlerror()) != NULL) {
      printf("ERROR: loadDll: Problems loading '%s' : %s\n", i_dllName.c_str(), dlError);
      return ECMD_DLL_LOAD_FAILURE;
    }
  } else {
    printf("loadDll: load successful\n");
  }

  /* Now we need to call loadDll on the dll itself so it can initialize */

  int (*Function)(const char *,int) =
      (int(*)(const char *,int))(void*)dlsym(dlHandle, "dllLoadDll");
  if (!Function) {
    fprintf(stderr,"ecmdLoadDll: Unable to find LoadDll function, must be an invalid DLL\n");
    rc = ECMD_DLL_LOAD_FAILURE;
  } else {
    rc = (*Function)(ECMD_CAPI_VERSION, ecmdClientDebug);
  }

#else
  rc = dllLoadDll(ECMD_CAPI_VERSION, ecmdClientDebug);

#endif /* ECMD_STATIC_FUNCTIONS */

  return rc;
}

int ecmdUnloadDll() {

  int rc = ECMD_SUCCESS;
  int c_rc = ECMD_SUCCESS;

#ifdef ECMD_STATIC_FUNCTIONS
  rc = dllUnloadDll();

#else

  if (dlHandle) {
    /* call DLL unload */
    int (*Function)() =
      (int(*)())(void*)dlsym(dlHandle, "dllUnloadDll");
    if (!Function) {
      fprintf(stderr,"ecmdUnloadDll: Unable to find UnloadDll function, must be an invalid DLL\n");
      rc = ECMD_DLL_UNLOAD_FAILURE;
      return rc;
    }
    rc = (*Function)();

    /* release DLL */
    const char* dlError;

    c_rc = dlclose(dlHandle);
    if (c_rc) {
      if ((dlError = dlerror()) != NULL) {
        fprintf(stderr,"ERROR: ecmdUnloadDll: %s\n", dlError);
        return ECMD_DLL_UNLOAD_FAILURE;
      }
    }
  }
  dlHandle = NULL;
#endif

  return rc;
}

int ecmdCommandArgs(int* i_argc, char** i_argv[]) {

  int rc = ECMD_SUCCESS;

#ifdef ECMD_STATIC_FUNCTIONS
  rc = dllCommonCommandArgs(i_argc, i_argv);

#else

  /* call DLL common command args */
  int (*Function)(int*, char***) =
    (int(*)(int*, char***))(void*)dlsym(dlHandle, "dllCommonCommandArgs");
  if (!Function) {
    fprintf(stderr,"ecmdCommandArgs: Unable to find dllCommonCommandArgs function, must be an invalid DLL\n");
    rc = ECMD_DLL_INVALID;
    return rc;
  }
  rc = (*Function)(i_argc, i_argv);

#endif

  return rc;
}

bool ecmdQueryTargetConfigured(ecmdChipTarget i_target, ecmdQueryData * i_queryData) {
  int rc = ECMD_SUCCESS;
  bool ret = false;
  bool myQuery = false;
  ecmdChipTarget queryTarget;

  std::list<ecmdCageData>::iterator ecmdCurCage;
  std::list<ecmdNodeData>::iterator ecmdCurNode;
  std::list<ecmdSlotData>::iterator ecmdCurSlot;
  std::list<ecmdChipData>::iterator ecmdCurChip;
  std::list<ecmdCoreData>::iterator ecmdCurCore;
  std::list<ecmdThreadData>::iterator ecmdCurThread;

  /* Do we need to do our own query ? */
  if (i_queryData == NULL) {
    i_queryData = new ecmdQueryData;
    queryTarget = i_target;
    myQuery = true;

    if (queryTarget.cageState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.cageState = ECMD_TARGET_QUERY_IGNORE;
    } else
      queryTarget.cageState = ECMD_TARGET_QUERY_FIELD_VALID;

    if (queryTarget.nodeState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.nodeState = ECMD_TARGET_QUERY_IGNORE;
    } else
      queryTarget.nodeState = ECMD_TARGET_QUERY_FIELD_VALID;

    if (queryTarget.slotState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.slotState = ECMD_TARGET_QUERY_IGNORE;
    } else
      queryTarget.slotState = ECMD_TARGET_QUERY_FIELD_VALID;

    if (queryTarget.chipTypeState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.chipTypeState = ECMD_TARGET_QUERY_IGNORE;
    } else
      queryTarget.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;

    if (queryTarget.posState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.posState = ECMD_TARGET_QUERY_IGNORE;
    } else
      queryTarget.posState = ECMD_TARGET_QUERY_FIELD_VALID;

    if (queryTarget.coreState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.coreState = ECMD_TARGET_QUERY_IGNORE;
    } else
      queryTarget.coreState = ECMD_TARGET_QUERY_FIELD_VALID;

    if (queryTarget.threadState == ECMD_TARGET_FIELD_UNUSED) {
      queryTarget.threadState = ECMD_TARGET_QUERY_IGNORE;
    } else
      queryTarget.threadState = ECMD_TARGET_QUERY_FIELD_VALID;

    rc = ecmdQueryConfig(queryTarget, *i_queryData, ECMD_QUERY_DETAIL_LOW);
    if (rc) {
      delete i_queryData;
      return ret;
    }
  }

  /* Now we have our data, let's start walking the data we have */
  for (ecmdCurCage = i_queryData->cageData.begin(); ecmdCurCage != i_queryData->cageData.end(); ecmdCurCage ++) {
    if (ecmdCurCage->cageId == i_target.cage) {
      if (i_target.nodeState == ECMD_TARGET_FIELD_UNUSED) {
        ret = true;
        break;
      }

      for (ecmdCurNode = ecmdCurCage->nodeData.begin(); ecmdCurNode != ecmdCurCage->nodeData.end(); ecmdCurNode ++) {
        if (ecmdCurNode->nodeId == i_target.node) {
          if (i_target.slotState == ECMD_TARGET_FIELD_UNUSED) {
            ret = true;
            break;
          }

          for (ecmdCurSlot = ecmdCurNode->slotData.begin(); ecmdCurSlot != ecmdCurNode->slotData.end(); ecmdCurSlot ++) {
            if (ecmdCurSlot->slotId == i_target.slot) {
              if (i_target.chipTypeState == ECMD_TARGET_FIELD_UNUSED || i_target.posState == ECMD_TARGET_FIELD_UNUSED) {
                ret = true;
                break;
              }

              for (ecmdCurChip = ecmdCurSlot->chipData.begin(); ecmdCurChip != ecmdCurSlot->chipData.end(); ecmdCurChip ++) {
                if (((ecmdCurChip->chipType == i_target.chipType) || (ecmdCurChip->chipCommonType == i_target.chipType)) &&
                    (ecmdCurChip->pos == i_target.pos)) {
                  if (i_target.coreState == ECMD_TARGET_FIELD_UNUSED) {
                    ret = true;
                    break;
                  }

                  for (ecmdCurCore = ecmdCurChip->coreData.begin(); ecmdCurCore != ecmdCurChip->coreData.end(); ecmdCurCore ++) {
                    if (ecmdCurCore->coreId == i_target.core) {
                      if (i_target.threadState == ECMD_TARGET_FIELD_UNUSED) {
                        ret = true;
                        break;
                      }

                      for (ecmdCurThread = ecmdCurCore->threadData.begin(); ecmdCurThread != ecmdCurCore->threadData.end(); ecmdCurThread ++) {
                        if (ecmdCurThread->threadId == i_target.thread) {
                          ret = true;
                          break;
                        } /* curThreadId == tarThreadId */
                      } /* for ecmdCurThread */

                      if (ret) break;
                    } /* curCoreId == tarCoreId */
                  } /* for ecmdCurCore */

                  if (ret) break;
                } /* curChipType == tarChipType && curChipPos == tarChipPos */
              } /* for ecmdCurChip */

              if (ret) break;
            } /* curSlotId == tarSlotId */
          } /* for ecmdCurSlot */

          if (ret) break;
        } /* curNodeId == tarNodeId */
      } /* for ecmdCurNode */

      if (ret) break;
    } /* curCageId == tarCageId */
  } /* for ecmdCurCage */

  if (myQuery) {
    delete i_queryData;
    i_queryData = NULL;
  }

  return rc;
}
<|endoftext|>


<commit_before>#include "Transformation.h"

map<string,double> Transformation::constantes;

void Transformation::transformer(Programme &programme)
{
    // get map with all constantes and their values for propagation
    vector<Declaration*> declarations = programme.getDeclarations();
    for (auto itDeclaration = declarations.begin() ; itDeclaration != declarations.end(); ++itDeclaration)
    {
        if ((*itDeclaration)->getContenu()->getType() == LC)
        {
            vector<Identifiant *> listeConstante = ((DecConstante*)(*itDeclaration))->getConstantes();
            for (auto itConstantes = listeConstante.begin(); itConstantes != listeConstante.end(); ++itConstantes)
            {
                constantes.insert(make_pair((*itConstantes)->valeur(), (*itConstantes)->eval()));
            }
        }
    }

	  vector<Instruction*> instructions = programme.getInstructions();
	  for(auto it = instructions.begin(); it != instructions.end(); ++it)
	  {
		    if ((*it)->getInstType() == ECR)
		    {
			      InstructionEcriture* inst = (InstructionEcriture*) (*it);
			      inst->setExpression(searchTransformations(inst->getExpression()));
		    }
		    else if ((*it)->getInstType() == AFF)
		    {
			      InstructionAffectation* inst = (InstructionAffectation*) (*it);
			      inst->setExpression(searchTransformations(inst->getExpression()));
		    }
	  }
}

//Fonction appelée récursivement
Expression * Transformation::searchTransformations(Expression * exp)
{
    switch(exp->getExprType())
    {
        case PAR:
            {
                Expression * parExpr = ((ExprPar*)exp)->getExpression();
                exp = searchTransformations(parExpr);
                if (parExpr->getExprType() == VALEUR || parExpr->getExprType() == IDENT)
                {
                    exp = parExpr;
                }
                return exp;
            }
            break;
        case BIN:
            {
                ExprBinaire * expBin = (ExprBinaire*) exp;
                Expression * gauche = expBin->getGauche();
			          Expression * droite = expBin->getDroite();
                if (gauche->getExprType() != VALEUR && gauche->getExprType() != IDENT)
                {
                    gauche = searchTransformations(gauche);
                    expBin->setGauche(gauche);
                }
                if (droite->getExprType() != VALEUR && droite->getExprType() != IDENT)
                {
                    droite = searchTransformations(droite);
                    expBin->setDroite(droite);
                }
                return simplifier(exp);
            }
            break;
        default:
            return exp;
    }
}

// should work as void, no idea why it doesnt ...
Expression * Transformation::simplifier(Expression * exp)
{
    ExprBinaire * exprBin = (ExprBinaire *) exp;
    // both sides are values, can be simplified by evaluating

    if (exprBin->getGauche()->getExprType() == VALEUR && exprBin->getDroite()->getExprType() == VALEUR)
    {
        return (Expression* ) new Val(exprBin->eval());
    }
    // left side is value, possibility of netral element
    else if (exprBin->getGauche()->getExprType() == VALEUR)
    {
        switch(exprBin->operateur())
        {
            case '+':
            case '-':
                if (exprBin->getGauche()->eval() == 0.0)
                {
                    return exprBin->getDroite();
                }
                else if (exprBin->getDroite()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getDroite())->valeur()) != constantes.end()))
                {
                    return (Expression* ) new Val(exprBin->eval());
                }
                return exp;
                break;
            case '*':
            case '/':
                if (exprBin->getGauche()->eval() == 1.0)
                {
                    return exprBin->getDroite();
                }
                else if (exprBin->getDroite()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getDroite())->valeur()) != constantes.end()))
                {
                    return (Expression* ) new Val(exprBin->eval());
                }
                return exp;
                break;
            default:
                cout << "ERROR: Found operator not expecting: " << exprBin->operateur() << endl;
                return exp;
        }
    }
    // right side is value, possibility of netral element
    else if (exprBin->getDroite()->getExprType() == VALEUR)
    {
        switch(exprBin->operateur())
        {
            case '+':
            case '-':
            cout << "Eval" << endl;
                if (exprBin->getDroite()->eval() == 0.0)
                {
                    return exprBin->getGauche();
                }
                else if (exprBin->getGauche()->getExprType() == BIN
                    && ((ExprBinaire*)exprBin->getGauche())->getDroite()->getExprType() == VALEUR)
                {
                    ExprBinaire * exprBinGauche = (ExprBinaire*)exprBin->getGauche();

                    ExprAdd * exprToEval = new ExprAdd(exprBinGauche->getDroite(), new OperateurAdditif(exprBin->operateur()), exprBin->getDroite());
                    Expression * newExpression = (Expression* ) new Val(exprToEval->eval());
                    exprBinGauche->setDroite(newExpression);
                    return exprBinGauche;
                }
                else if (exprBin->getGauche()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getGauche())->valeur()) != constantes.end()))
                {
                    return (Expression* ) new Val(exprBin->eval());
                }
                return exp;
                break;
            case '*':
            case '/':
                if (exprBin->getDroite()->eval() == 1.0)
                {
                    return exprBin->getGauche();
                }
                else if (exprBin->getGauche()->getExprType() == BIN
                    && ((ExprBinaire*)exprBin->getGauche())->getDroite()->getExprType() == VALEUR)
                {
                    ExprBinaire * exprBinGauche = (ExprBinaire*)exprBin->getGauche();

                    ExprMult * exprToEval = new ExprMult(exprBinGauche->getDroite(), new OperateurMultiplicatif(exprBin->operateur()), exprBin->getDroite());
                    Expression * newExpression = (Expression* ) new Val(exprToEval->eval());
                    exprBinGauche->setDroite(newExpression);
                    return exprBinGauche;
                }
                else if (exprBin->getGauche()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getGauche())->valeur()) != constantes.end()))
                {
                    return (Expression* ) new Val(exprBin->eval());
                }
                return exp;
                break;
            default:
                cout << "ERROR: Found operator not expecting: " << exprBin->operateur() << endl;
                return exp;
        }
        // only Identifier found, propagation possible
    } else {
        if (exprBin->getGauche()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getGauche())->valeur()) != constantes.end()) && exprBin->getDroite()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getDroite())->valeur()) != constantes.end()))
        {
            return (Expression* ) new Val(exprBin->eval());
        }
        return exp;
    }
}
<commit_msg>remove cout so that tests work again<commit_after>#include "Transformation.h"

map<string,double> Transformation::constantes;

void Transformation::transformer(Programme &programme)
{
    // get map with all constantes and their values for propagation
    vector<Declaration*> declarations = programme.getDeclarations();
    for (auto itDeclaration = declarations.begin() ; itDeclaration != declarations.end(); ++itDeclaration)
    {
        if ((*itDeclaration)->getContenu()->getType() == LC)
        {
            vector<Identifiant *> listeConstante = ((DecConstante*)(*itDeclaration))->getConstantes();
            for (auto itConstantes = listeConstante.begin(); itConstantes != listeConstante.end(); ++itConstantes)
            {
                constantes.insert(make_pair((*itConstantes)->valeur(), (*itConstantes)->eval()));
            }
        }
    }

	  vector<Instruction*> instructions = programme.getInstructions();
	  for(auto it = instructions.begin(); it != instructions.end(); ++it)
	  {
		    if ((*it)->getInstType() == ECR)
		    {
			      InstructionEcriture* inst = (InstructionEcriture*) (*it);
			      inst->setExpression(searchTransformations(inst->getExpression()));
		    }
		    else if ((*it)->getInstType() == AFF)
		    {
			      InstructionAffectation* inst = (InstructionAffectation*) (*it);
			      inst->setExpression(searchTransformations(inst->getExpression()));
		    }
	  }
}

//Fonction appelée récursivement
Expression * Transformation::searchTransformations(Expression * exp)
{
    switch(exp->getExprType())
    {
        case PAR:
            {
                Expression * parExpr = ((ExprPar*)exp)->getExpression();
                exp = searchTransformations(parExpr);
                if (parExpr->getExprType() == VALEUR || parExpr->getExprType() == IDENT)
                {
                    exp = parExpr;
                }
                return exp;
            }
            break;
        case BIN:
            {
                ExprBinaire * expBin = (ExprBinaire*) exp;
                Expression * gauche = expBin->getGauche();
			          Expression * droite = expBin->getDroite();
                if (gauche->getExprType() != VALEUR && gauche->getExprType() != IDENT)
                {
                    gauche = searchTransformations(gauche);
                    expBin->setGauche(gauche);
                }
                if (droite->getExprType() != VALEUR && droite->getExprType() != IDENT)
                {
                    droite = searchTransformations(droite);
                    expBin->setDroite(droite);
                }
                return simplifier(exp);
            }
            break;
        default:
            return exp;
    }
}

// should work as void, no idea why it doesnt ...
Expression * Transformation::simplifier(Expression * exp)
{
    ExprBinaire * exprBin = (ExprBinaire *) exp;
    // both sides are values, can be simplified by evaluating

    if (exprBin->getGauche()->getExprType() == VALEUR && exprBin->getDroite()->getExprType() == VALEUR)
    {
        return (Expression* ) new Val(exprBin->eval());
    }
    // left side is value, possibility of netral element
    else if (exprBin->getGauche()->getExprType() == VALEUR)
    {
        switch(exprBin->operateur())
        {
            case '+':
            case '-':
                if (exprBin->getGauche()->eval() == 0.0)
                {
                    return exprBin->getDroite();
                }
                else if (exprBin->getDroite()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getDroite())->valeur()) != constantes.end()))
                {
                    return (Expression* ) new Val(exprBin->eval());
                }
                return exp;
                break;
            case '*':
            case '/':
                if (exprBin->getGauche()->eval() == 1.0)
                {
                    return exprBin->getDroite();
                }
                else if (exprBin->getDroite()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getDroite())->valeur()) != constantes.end()))
                {
                    return (Expression* ) new Val(exprBin->eval());
                }
                return exp;
                break;
            default:
                cout << "ERROR: Found operator not expecting: " << exprBin->operateur() << endl;
                return exp;
        }
    }
    // right side is value, possibility of netral element
    else if (exprBin->getDroite()->getExprType() == VALEUR)
    {
        switch(exprBin->operateur())
        {
            case '+':
            case '-':
                if (exprBin->getDroite()->eval() == 0.0)
                {
                    return exprBin->getGauche();
                }
                else if (exprBin->getGauche()->getExprType() == BIN
                    && ((ExprBinaire*)exprBin->getGauche())->getDroite()->getExprType() == VALEUR)
                {
                    ExprBinaire * exprBinGauche = (ExprBinaire*)exprBin->getGauche();

                    ExprAdd * exprToEval = new ExprAdd(exprBinGauche->getDroite(), new OperateurAdditif(exprBin->operateur()), exprBin->getDroite());
                    Expression * newExpression = (Expression* ) new Val(exprToEval->eval());
                    exprBinGauche->setDroite(newExpression);
                    return exprBinGauche;
                }
                else if (exprBin->getGauche()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getGauche())->valeur()) != constantes.end()))
                {
                    return (Expression* ) new Val(exprBin->eval());
                }
                return exp;
                break;
            case '*':
            case '/':
                if (exprBin->getDroite()->eval() == 1.0)
                {
                    return exprBin->getGauche();
                }
                else if (exprBin->getGauche()->getExprType() == BIN
                    && ((ExprBinaire*)exprBin->getGauche())->getDroite()->getExprType() == VALEUR)
                {
                    ExprBinaire * exprBinGauche = (ExprBinaire*)exprBin->getGauche();

                    ExprMult * exprToEval = new ExprMult(exprBinGauche->getDroite(), new OperateurMultiplicatif(exprBin->operateur()), exprBin->getDroite());
                    Expression * newExpression = (Expression* ) new Val(exprToEval->eval());
                    exprBinGauche->setDroite(newExpression);
                    return exprBinGauche;
                }
                else if (exprBin->getGauche()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getGauche())->valeur()) != constantes.end()))
                {
                    return (Expression* ) new Val(exprBin->eval());
                }
                return exp;
                break;
            default:
                cout << "ERROR: Found operator not expecting: " << exprBin->operateur() << endl;
                return exp;
        }
        // only Identifier found, propagation possible
    } else {
        if (exprBin->getGauche()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getGauche())->valeur()) != constantes.end()) && exprBin->getDroite()->getExprType() == IDENT && (constantes.find(((Identifiant*)exprBin->getDroite())->valeur()) != constantes.end()))
        {
            return (Expression* ) new Val(exprBin->eval());
        }
        return exp;
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <QDebug>
#include <QDBusConnection>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QFile>
#include <QLibraryInfo>
#include <QSettings>
#include <QTimer>
#include <QUrl>
#include <MGConfItem>

#include "application.h"
#include "dialog.h"
#include "alarmcontrol.h"

Application::Application(int & argc, char ** argv) :
    QApplication(argc, argv),
    m_orientation(1),
    m_orientationSensorAvailable(false),
    m_dialog(NULL),
    m_primaryPlayer(NULL),
    m_secondaryPlayer(NULL),
    m_currentRequest(NULL),
    m_activeIncomingCall(false)
{
    setApplicationName("meego-ux-alarms");

    setQuitOnLastWindowClosed(false);

    if (QSensor::sensorsForType("QOrientationSensor").length() > 0)
    {
        m_orientationSensorAvailable = true;
        connect(&m_orientationSensor, SIGNAL(readingChanged()), SLOT(updateOrientation()));
    }

    QString theme = MGConfItem("/meego/ux/theme").value().toString();
    QString themeFile = QString("/usr/share/themes/") + theme + "/theme.ini";
    if(!QFile::exists(themeFile))
    {
        // fallback
        themeFile = QString("/usr/share/themes/1024-600-10/theme.ini");
    }
    themeConfig = new QSettings(themeFile, QSettings::NativeFormat, this);

    setFont(QFont(themeConfig->value("fontFamily").toString(), themeConfig->value("fontPixelSizeMedium").toInt()));

    m_translator.load("qt_meego-ux-alarms.qm", QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    installTranslator(&m_translator);

    m_secondaryRingerItem = new MGConfItem("/meego/ux/SecondaryRinger", this);
    connect(m_secondaryRingerItem, SIGNAL(valueChanged()), SLOT(updateSecondaryRinger()));
    updateSecondaryRinger();

    m_incomingCallPathItem = new MGConfItem("/meego/ux/IncomingCallPath", this);
    connect(m_incomingCallPathItem, SIGNAL(valueChanged()), SLOT(updateIncomingCallPath()));
    updateIncomingCallPath();

    new AlarmControl(this);
    QDBusConnection::sessionBus().registerService("org.meego.alarms");
    QDBusConnection::sessionBus().registerObject("/incomingCall", this);
}

Application::~Application()
{
}

void Application::updateOrientation()
{
    switch (m_orientationSensor.reading()->orientation())
    {
    case QOrientationReading::LeftUp:
        m_orientation = 2;
        break;
    case QOrientationReading::TopDown:
        m_orientation = 3;
        break;
    case QOrientationReading::RightUp:
        m_orientation = 0;
        break;
    case QOrientationReading::TopUp:
        m_orientation = 1;
        break;
    default:
        return;
    }

    emit orientationChanged();
}

int Application::foregroundWindow()
{
    // By definition our window is the foreground window
    if (m_dialog)
    {
        return m_dialog->winId();
    }

    return 0;
}

void Application::incomingCall(QString summary,
                               QString body,
                               QString acceptAction,
                               QString rejectAction,
                               QString sound,
                               QString imageURI)
{
    qDebug() << "XXX incomingCall" << m_dialog;

    if (m_currentRequest)
    {
        if (m_currentRequest->getType() == AlarmRequest::IncomingCall)
        {
            // This shouldn't happen since we would expect a dropCall
            // before getting another request, so log about it and assume
            // this new request is the currect request
            qCritical("Recieved two incoming calls on top of each other!");
        }
        else
        {
            // incoming calls always take priority
            m_requestQueue.push_front(m_currentRequest);
        }
        m_currentRequest = NULL;
        cleanupDialog(false);
    }

    m_currentRequest = new AlarmRequest(summary, body, acceptAction,
                                        rejectAction, imageURI, sound,
                                        AlarmRequest::IncomingCall);
    showCurrentRequest();

    // If any other types of notification are waiting in the queue,
    // and if the platform has a secondary ringer configured, then
    // play the secondary ringer at the same time
    if (!m_requestQueue.isEmpty())
    {
        if (!m_secondaryRinger.isNull() &&
           (!m_secondaryPlayer ||
            m_secondaryPlayer->state() != QMediaPlayer::PlayingState))
        {
            m_secondaryPlayer = new QMediaPlayer(this, QMediaPlayer::LowLatency);
            connect(m_secondaryPlayer, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), SLOT(mediaStatusChanged(QMediaPlayer::MediaStatus)));
            m_secondaryPlayer->setMedia(QUrl::fromLocalFile(m_secondaryRinger));
            m_secondaryPlayer->play();
        }
    }
}

void Application::updateSecondaryRinger()
{
    if (m_secondaryRingerItem->value().isValid())
    {
        m_secondaryRinger = m_secondaryRingerItem->value().toString();
    }
}

void Application::dropCall()
{
    qDebug() << "XXX dropCall" << m_dialog;
    if (!m_currentRequest ||
            m_currentRequest->getType() != AlarmRequest::IncomingCall)
        return;
    cleanupDialog();
}

void Application::mediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    qDebug() << "mediaStatuschanged" << status;
    if (status == QMediaPlayer::EndOfMedia)
    {
        QMediaPlayer *p = static_cast<QMediaPlayer *>(sender());
        p->play();
    }
}

void Application::updateIncomingCallPath()
{
    if (!m_incomingCallPathItem->value().isValid())
    {
        m_incomingCallPath = "/usr/share/meego-ux-alarms/incomingcall.qml";
    }
    else
    {
        m_incomingCallPath = m_incomingCallPathItem->value().toString();
    }
}

void Application::triggerAction(QString action)
{
    if (!action.isEmpty())
    {
        // call it
    }
}

void Application::cancelAlarm()
{
    if (!m_currentRequest ||
            m_currentRequest->getType() != AlarmRequest::AlarmClock)
        return;

    // TODO: Use data from m_currentRequest to make a request
    //       via libealarm to cancel/stop the alarm

    cleanupDialog();
}

void Application::cleanupDialog(bool loadNextRequest)
{
    qDebug() << "XXX cleanupDialog" << m_dialog;
    if (m_dialog)
    {
        // For some reason, at least on 964 and 945 graphics, repeatedly
        // opening and closing a gl window will segfault deep down in egl
        // code.  A work around is to not completely free the window till
        // we instantiate a new window, so in this call we just close the
        // dialog, and only delete this instance once we have a request
        // for a new dialog.
        m_dialog->close();
    }
    if (m_primaryPlayer)
    {
        m_primaryPlayer->stop();
        delete m_primaryPlayer;
        m_primaryPlayer = NULL;
    }
    if (m_secondaryPlayer)
    {
        m_secondaryPlayer->stop();
        delete m_secondaryPlayer;
        m_secondaryPlayer = NULL;
    }

    delete m_currentRequest;
    m_currentRequest = NULL;

    if (loadNextRequest && !m_requestQueue.isEmpty())
        enqueue(m_requestQueue.takeFirst());
}

void Application::enqueue(AlarmRequest *request)
{
    if (m_currentRequest)
    {
        m_requestQueue << request;
        return;
    }

    // No active notification so show this one
    m_currentRequest = request;
    showCurrentRequest();
}

void Application::showCurrentRequest()
{
    if (m_dialog)
    {
        m_dialog->deleteLater();
    }

    m_dialog = new Dialog();
    connect(m_dialog->engine(), SIGNAL(quit()), SLOT(cleanupDialog()));
    m_dialog->rootContext()->setContextProperty("currentRequest", m_currentRequest);
    switch(m_currentRequest->getType())
    {
    case AlarmRequest::TaskReminder:
        m_dialog->setSource(QUrl::fromLocalFile("/usr/share/meego-ux-alarms/taskreminder.qml"));
        break;
    case AlarmRequest::EventReminder:
        m_dialog->setSource(QUrl::fromLocalFile("/usr/share/meego-ux-alarms/eventreminder.qml"));
        break;
    case AlarmRequest::AlarmClock:
        m_dialog->setSource(QUrl::fromLocalFile("/usr/share/meego-ux-alarms/alarmclock.qml"));
        break;
    case AlarmRequest::IncomingCall:
        m_dialog->setSource(QUrl::fromLocalFile("/usr/share/meego-ux-alarms/incomingcall.qml"));
        break;
    }
    m_dialog->show();

    if (!m_currentRequest->getSound().isEmpty())
    {
        m_primaryPlayer = new QMediaPlayer(this, QMediaPlayer::LowLatency);
        connect(m_primaryPlayer, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), SLOT(mediaStatusChanged(QMediaPlayer::MediaStatus)));
        m_primaryPlayer->setMedia(QUrl::fromLocalFile(m_currentRequest->getSound()));
        m_primaryPlayer->play();
    }
}
<commit_msg>change gconf key for secondary sound to match what chat is using<commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <QDebug>
#include <QDBusConnection>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QFile>
#include <QLibraryInfo>
#include <QSettings>
#include <QTimer>
#include <QUrl>
#include <MGConfItem>

#include "application.h"
#include "dialog.h"
#include "alarmcontrol.h"

Application::Application(int & argc, char ** argv) :
    QApplication(argc, argv),
    m_orientation(1),
    m_orientationSensorAvailable(false),
    m_dialog(NULL),
    m_primaryPlayer(NULL),
    m_secondaryPlayer(NULL),
    m_currentRequest(NULL),
    m_activeIncomingCall(false)
{
    setApplicationName("meego-ux-alarms");

    setQuitOnLastWindowClosed(false);

    if (QSensor::sensorsForType("QOrientationSensor").length() > 0)
    {
        m_orientationSensorAvailable = true;
        connect(&m_orientationSensor, SIGNAL(readingChanged()), SLOT(updateOrientation()));
    }

    QString theme = MGConfItem("/meego/ux/theme").value().toString();
    QString themeFile = QString("/usr/share/themes/") + theme + "/theme.ini";
    if(!QFile::exists(themeFile))
    {
        // fallback
        themeFile = QString("/usr/share/themes/1024-600-10/theme.ini");
    }
    themeConfig = new QSettings(themeFile, QSettings::NativeFormat, this);

    setFont(QFont(themeConfig->value("fontFamily").toString(), themeConfig->value("fontPixelSizeMedium").toInt()));

    m_translator.load("qt_meego-ux-alarms.qm", QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    installTranslator(&m_translator);

    m_secondaryRingerItem = new MGConfItem("/meego/chat/short-videocall-sound", this);
    connect(m_secondaryRingerItem, SIGNAL(valueChanged()), SLOT(updateSecondaryRinger()));
    updateSecondaryRinger();

    m_incomingCallPathItem = new MGConfItem("/meego/ux/IncomingCallPath", this);
    connect(m_incomingCallPathItem, SIGNAL(valueChanged()), SLOT(updateIncomingCallPath()));
    updateIncomingCallPath();

    new AlarmControl(this);
    QDBusConnection::sessionBus().registerService("org.meego.alarms");
    QDBusConnection::sessionBus().registerObject("/incomingCall", this);
}

Application::~Application()
{
}

void Application::updateOrientation()
{
    switch (m_orientationSensor.reading()->orientation())
    {
    case QOrientationReading::LeftUp:
        m_orientation = 2;
        break;
    case QOrientationReading::TopDown:
        m_orientation = 3;
        break;
    case QOrientationReading::RightUp:
        m_orientation = 0;
        break;
    case QOrientationReading::TopUp:
        m_orientation = 1;
        break;
    default:
        return;
    }

    emit orientationChanged();
}

int Application::foregroundWindow()
{
    // By definition our window is the foreground window
    if (m_dialog)
    {
        return m_dialog->winId();
    }

    return 0;
}

void Application::incomingCall(QString summary,
                               QString body,
                               QString acceptAction,
                               QString rejectAction,
                               QString sound,
                               QString imageURI)
{
    qDebug() << "XXX incomingCall" << m_dialog;

    if (m_currentRequest)
    {
        if (m_currentRequest->getType() == AlarmRequest::IncomingCall)
        {
            // This shouldn't happen since we would expect a dropCall
            // before getting another request, so log about it and assume
            // this new request is the currect request
            qCritical("Recieved two incoming calls on top of each other!");
        }
        else
        {
            // incoming calls always take priority
            m_requestQueue.push_front(m_currentRequest);
        }
        m_currentRequest = NULL;
        cleanupDialog(false);
    }

    m_currentRequest = new AlarmRequest(summary, body, acceptAction,
                                        rejectAction, imageURI, sound,
                                        AlarmRequest::IncomingCall);
    showCurrentRequest();

    // If any other types of notification are waiting in the queue,
    // and if the platform has a secondary ringer configured, then
    // play the secondary ringer at the same time
    if (!m_requestQueue.isEmpty())
    {
        if (!m_secondaryRinger.isNull() &&
           (!m_secondaryPlayer ||
            m_secondaryPlayer->state() != QMediaPlayer::PlayingState))
        {
            m_secondaryPlayer = new QMediaPlayer(this, QMediaPlayer::LowLatency);
            connect(m_secondaryPlayer, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), SLOT(mediaStatusChanged(QMediaPlayer::MediaStatus)));
            m_secondaryPlayer->setMedia(QUrl::fromLocalFile(m_secondaryRinger));
            m_secondaryPlayer->play();
        }
    }
}

void Application::updateSecondaryRinger()
{
    if (m_secondaryRingerItem->value().isValid())
    {
        m_secondaryRinger = m_secondaryRingerItem->value().toString();
    }
}

void Application::dropCall()
{
    qDebug() << "XXX dropCall" << m_dialog;
    if (!m_currentRequest ||
            m_currentRequest->getType() != AlarmRequest::IncomingCall)
        return;
    cleanupDialog();
}

void Application::mediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    qDebug() << "mediaStatuschanged" << status;
    if (status == QMediaPlayer::EndOfMedia)
    {
        QMediaPlayer *p = static_cast<QMediaPlayer *>(sender());
        p->play();
    }
}

void Application::updateIncomingCallPath()
{
    if (!m_incomingCallPathItem->value().isValid())
    {
        m_incomingCallPath = "/usr/share/meego-ux-alarms/incomingcall.qml";
    }
    else
    {
        m_incomingCallPath = m_incomingCallPathItem->value().toString();
    }
}

void Application::triggerAction(QString action)
{
    if (!action.isEmpty())
    {
        // call it
    }
}

void Application::cancelAlarm()
{
    if (!m_currentRequest ||
            m_currentRequest->getType() != AlarmRequest::AlarmClock)
        return;

    // TODO: Use data from m_currentRequest to make a request
    //       via libealarm to cancel/stop the alarm

    cleanupDialog();
}

void Application::cleanupDialog(bool loadNextRequest)
{
    qDebug() << "XXX cleanupDialog" << m_dialog;
    if (m_dialog)
    {
        // For some reason, at least on 964 and 945 graphics, repeatedly
        // opening and closing a gl window will segfault deep down in egl
        // code.  A work around is to not completely free the window till
        // we instantiate a new window, so in this call we just close the
        // dialog, and only delete this instance once we have a request
        // for a new dialog.
        m_dialog->close();
    }
    if (m_primaryPlayer)
    {
        m_primaryPlayer->stop();
        delete m_primaryPlayer;
        m_primaryPlayer = NULL;
    }
    if (m_secondaryPlayer)
    {
        m_secondaryPlayer->stop();
        delete m_secondaryPlayer;
        m_secondaryPlayer = NULL;
    }

    delete m_currentRequest;
    m_currentRequest = NULL;

    if (loadNextRequest && !m_requestQueue.isEmpty())
        enqueue(m_requestQueue.takeFirst());
}

void Application::enqueue(AlarmRequest *request)
{
    if (m_currentRequest)
    {
        m_requestQueue << request;
        return;
    }

    // No active notification so show this one
    m_currentRequest = request;
    showCurrentRequest();
}

void Application::showCurrentRequest()
{
    if (m_dialog)
    {
        m_dialog->deleteLater();
    }

    m_dialog = new Dialog();
    connect(m_dialog->engine(), SIGNAL(quit()), SLOT(cleanupDialog()));
    m_dialog->rootContext()->setContextProperty("currentRequest", m_currentRequest);
    switch(m_currentRequest->getType())
    {
    case AlarmRequest::TaskReminder:
        m_dialog->setSource(QUrl::fromLocalFile("/usr/share/meego-ux-alarms/taskreminder.qml"));
        break;
    case AlarmRequest::EventReminder:
        m_dialog->setSource(QUrl::fromLocalFile("/usr/share/meego-ux-alarms/eventreminder.qml"));
        break;
    case AlarmRequest::AlarmClock:
        m_dialog->setSource(QUrl::fromLocalFile("/usr/share/meego-ux-alarms/alarmclock.qml"));
        break;
    case AlarmRequest::IncomingCall:
        m_dialog->setSource(QUrl::fromLocalFile("/usr/share/meego-ux-alarms/incomingcall.qml"));
        break;
    }
    m_dialog->show();

    if (!m_currentRequest->getSound().isEmpty())
    {
        m_primaryPlayer = new QMediaPlayer(this, QMediaPlayer::LowLatency);
        connect(m_primaryPlayer, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), SLOT(mediaStatusChanged(QMediaPlayer::MediaStatus)));
        m_primaryPlayer->setMedia(QUrl::fromLocalFile(m_currentRequest->getSound()));
        m_primaryPlayer->play();
    }
}
<|endoftext|>