<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.                  *
 **************************************************************************/

// Generator for particle pairs in a preset
// kinematic range
// ranges can be set for invariant mass, pair pT, pair rapidity
// and pair azimuth

//
// Comments and suggestions: markus.konrad.kohler@cern.ch
//

#include "TPDGCode.h"
#include <TDatabasePDG.h>
#include "AliGenEventHeader.h"
#include "TF1.h"

#include "AliGenPairFlat.h"

ClassImp(AliGenPairFlat)

//_____________________________________________________________________________
AliGenPairFlat::AliGenPairFlat()
    :AliGenerator(),
     fPairNpart(10),
     fPairYMin(-10.),
     fPairYMax(10.),
     fPairPhiMin(0.),
     fPairPhiMax(TMath::TwoPi()),
     fPairPtMin(0.001),
     fPairPtMax(50.),
     fPairMassMin(0.),
     fPairMassMax(10.),
     fLegPdg1(11),
     fLegPdg2(-11),
     fAlpha(0.),
     fDebug(0)
{
  //
  // Default constructor
  //
}

//_____________________________________________________________________________
void AliGenPairFlat::Generate()
{
  //
  // Generate a random pair of particles
  //

    Float_t polar[3]= {0,0,0};
    Float_t origin[3];
    Float_t time;

    Float_t p[3];
    Int_t i, j, nt;
    Double_t phi, y, mass, mt, e, pt;
    Float_t weight = 1.;
    Double_t  pt1, pt2, y1, y2;

    TLorentzVector mother, dau1, dau2;
    Float_t random[6];

//    TF1* fPol = new TF1("fPol","1.+[0]*x*x",-1.,1.);
    TF1 fPol("fPol","1.+[0]*x*x",-1.,1.);
    fPol.SetParameter(0,fAlpha);

    for (j=0;j<3;j++) origin[j]=fOrigin[j];
    time = fTimeOrigin;
    if(fVertexSmear==kPerEvent) {
	Vertex();
	for (j=0;j<3;j++) origin[j]=fVertex[j];
	time = fTime;
     }

	printf("\n\n------------------GENERATOR SETTINGS------------------\n\n");
	printf("You choosed for the mother the Mass range %f - %f     \n",fPairMassMin,fPairMassMax);
	printf("You choosed for the mother the transverse Momentum range %f - %f \n",fPairPtMin,fPairPtMax);
	printf("You choosed for the mother the Phi range %f - %f \n",fPairPhiMin,fPairPhiMax);
	printf("The Particle will decay in (pdg) %i and %i\n \n",fLegPdg1, fLegPdg2);
	printf("The rest Mass of first daughter (%s) is %f \n",
	TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->GetTitle(),
	TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->Mass());
	printf("The rest Mass of second daughter (%s) is %f \n",
	TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->GetTitle(),
	TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->Mass());
	printf("polarization factor is alpha == %lf \n",fAlpha);
	printf("vertex is at x == %f || y == %f || z == %f   \n",origin[0],origin[1],origin[2]);
	printf("\n----------------------------------------------------------\n");

    for(i=0;i<fPairNpart;i++) {

	// mother properties
	Rndm(random,4);
	mass  	= fPairMassMin+random[0]*(fPairMassMax-fPairMassMin);
	pt	= fPairPtMin+random[1]*(fPairPtMax-fPairPtMin);
	y	= fPairYMin+random[2]*(fPairYMax-fPairYMin);
	phi	= fPairPhiMin+random[3]*(fPairPhiMax-fPairPhiMin);

        mt 	= TMath::Sqrt(pt*pt + mass*mass);
	p[0] 	= pt*TMath::Cos(phi);
	p[1] 	= pt*TMath::Sin(phi);
	p[2] 	= mt*TMath::SinH(y);
	e 	= mt*TMath::CosH(y);

	mother.SetPxPyPzE(p[0],p[1],p[2],e);

         if (fDebug == 2)    printf("p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || y =  %+11.4e || weight=%+11.4e || E= %+11.4e\n",p[0],p[1],p[2],pt, y,weight,e);

	//decay procedure
	if(!Decay(mother,dau1,dau2,fPol))continue;

	pt1 = dau1.Pt();
	pt2 = dau2.Pt();
	y1 = dau1.Rapidity();
	y2 = dau2.Rapidity();

	//first daughter
	p[0] = dau1.Px();
	p[1] = dau1.Py();
	p[2] = dau1.Pz();
	e = dau1.E();

	if(fVertexSmear==kPerTrack) {
	    Rndm(random,6);
	    for (j=0;j<3;j++) {
		origin[j]=fOrigin[j]+fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())*
		    TMath::Sqrt(-2*TMath::Log(random[2*j+1]));
	    }

	    Rndm(random,2);
	    time = fTimeOrigin + fOsigma[2]/TMath::Ccgs()*
	      TMath::Cos(2*random[0]*TMath::Pi())*
	      TMath::Sqrt(-2*TMath::Log(random[1]));
	}

	PushTrack(fTrackIt,-1,fLegPdg1,p,origin,polar,time,kPPrimary,nt, weight);
	if (fDebug == 2) printf("dau1-->id=%+3d, p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || weight=%+11.4e || E= %+11.4e\n",fLegPdg1,p[0],p[1],p[2],pt1,weight,e);

	//second daughter
	p[0] = dau2.Px();
	p[1] = dau2.Py();
	p[2] = dau2.Pz();
	e = dau2.E();

	if(fVertexSmear==kPerTrack) {
	    Rndm(random,6);
	    for (j=0;j<3;j++) {
		origin[j]=fOrigin[j]+fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())*
		    TMath::Sqrt(-2*TMath::Log(random[2*j+1]));
	    }

	    Rndm(random,2);
	    time = fTimeOrigin + fOsigma[2]/TMath::Ccgs()*
	      TMath::Cos(2*random[0]*TMath::Pi())*
	      TMath::Sqrt(-2*TMath::Log(random[1]));
	}

	PushTrack(fTrackIt,-1,fLegPdg2,p,origin,polar,time,kPPrimary,nt,weight);
      if (fDebug == 2) printf("dau2-->id=%+3d, p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || weight=%+11.4e || E= %+11.4e\n",fLegPdg2,p[0],p[1],p[2],pt2, weight,e);

    }//particle loop

}

//_____________________________________________________________________________

void AliGenPairFlat::Init()
{
	//
	// Init
	//

	printf("AliGenPairFlat::Init() not implemented!!!\n");

}

//_____________________________________________________________________________

Bool_t AliGenPairFlat::Decay(TLorentzVector mother, TLorentzVector &dau1, TLorentzVector &dau2, TF1 polfactor)
{
	//
	// decay procedure
	//

	Double_t mp, md1, md2, ed1, ed2, pd1, pd2;
	Double_t costheta, sintheta, phi;

	mp = mother.M();
	md1 = TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->Mass();
	md2 = TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->Mass();

	if(mp < md1+md2){
	printf("Daughters are heavier than Mother!! Check Kinematics!! \n");
	return 0;
	}

  ed1 = (mp*mp + md1*md1 - md2*md2)/(2.*mp);
  ed2 = mp-ed1;
  pd1 = TMath::Sqrt((ed1+md1)*(ed1-md1));
  pd2 = TMath::Sqrt((mp*mp-(md1+md2)*(md1+md2))*(mp*mp -(md1-md2)*(md1-md2)))/(2.*mp);

  costheta = polfactor.GetRandom(); //polarization
  sintheta = TMath::Sqrt((1.+costheta)*(1.-costheta));
  phi      = 2.0*TMath::Pi()*gRandom->Rndm();

	dau1.SetPxPyPzE(pd1*sintheta*TMath::Cos(phi),
		        pd1*sintheta*TMath::Sin(phi),
		        pd1*costheta,
			ed1);

	dau2.SetPxPyPzE((-1.)*pd1*sintheta*TMath::Cos(phi),
			(-1.)*pd1*sintheta*TMath::Sin(phi),
			(-1.)*pd1*costheta,
			ed2);

  	TVector3 boost = mother.BoostVector();

  	dau1.Boost(boost);
  	dau2.Boost(boost);

  return 1;

}

<commit_msg>Fix for coverity 19211<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.                  *
 **************************************************************************/

// Generator for particle pairs in a preset
// kinematic range
// ranges can be set for invariant mass, pair pT, pair rapidity
// and pair azimuth

//
// Comments and suggestions: markus.konrad.kohler@cern.ch
//

#include "TPDGCode.h"
#include <TDatabasePDG.h>
#include "AliGenEventHeader.h"
#include "TF1.h"

#include "AliGenPairFlat.h"

ClassImp(AliGenPairFlat)

//_____________________________________________________________________________
AliGenPairFlat::AliGenPairFlat()
    :AliGenerator(),
     fPairNpart(10),
     fPairYMin(-10.),
     fPairYMax(10.),
     fPairPhiMin(0.),
     fPairPhiMax(TMath::TwoPi()),
     fPairPtMin(0.001),
     fPairPtMax(50.),
     fPairMassMin(0.),
     fPairMassMax(10.),
     fLegPdg1(11),
     fLegPdg2(-11),
     fAlpha(0.),
     fDebug(0)
{
  //
  // Default constructor
  //
}

//_____________________________________________________________________________
void AliGenPairFlat::Generate()
{
  //
  // Generate a random pair of particles
  //

    Float_t polar[3]= {0,0,0};
    Float_t origin[3];
    Float_t time;

    Float_t p[3];
    Int_t i, j, nt;
    Double_t phi, y, mass, mt, e, pt;
    Float_t weight = 1.;
    Double_t  pt1, pt2, y1, y2;

    TLorentzVector mother, dau1, dau2;
    Float_t random[6];

    TF1* pol = new TF1("Pol","1.+[0]*x*x",-1.,1.);
    pol->SetParameter(0, fAlpha);

    for (j=0;j<3;j++) origin[j]=fOrigin[j];
    time = fTimeOrigin;
    if(fVertexSmear==kPerEvent) {
	Vertex();
	for (j=0;j<3;j++) origin[j]=fVertex[j];
	time = fTime;
     }

	printf("\n\n------------------GENERATOR SETTINGS------------------\n\n");
	printf("You choosed for the mother the Mass range %f - %f     \n",fPairMassMin,fPairMassMax);
	printf("You choosed for the mother the transverse Momentum range %f - %f \n",fPairPtMin,fPairPtMax);
	printf("You choosed for the mother the Phi range %f - %f \n",fPairPhiMin,fPairPhiMax);
	printf("The Particle will decay in (pdg) %i and %i\n \n",fLegPdg1, fLegPdg2);
	printf("The rest Mass of first daughter (%s) is %f \n",
	TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->GetTitle(),
	TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->Mass());
	printf("The rest Mass of second daughter (%s) is %f \n",
	TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->GetTitle(),
	TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->Mass());
	printf("polarization factor is alpha == %lf \n",fAlpha);
	printf("vertex is at x == %f || y == %f || z == %f   \n",origin[0],origin[1],origin[2]);
	printf("\n----------------------------------------------------------\n");

    for(i=0;i<fPairNpart;i++) {

	// mother properties
	Rndm(random,4);
	mass  	= fPairMassMin+random[0]*(fPairMassMax-fPairMassMin);
	pt	= fPairPtMin+random[1]*(fPairPtMax-fPairPtMin);
	y	= fPairYMin+random[2]*(fPairYMax-fPairYMin);
	phi	= fPairPhiMin+random[3]*(fPairPhiMax-fPairPhiMin);

        mt 	= TMath::Sqrt(pt*pt + mass*mass);
	p[0] 	= pt*TMath::Cos(phi);
	p[1] 	= pt*TMath::Sin(phi);
	p[2] 	= mt*TMath::SinH(y);
	e 	= mt*TMath::CosH(y);

	mother.SetPxPyPzE(p[0],p[1],p[2],e);

         if (fDebug == 2)    printf("p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || y =  %+11.4e || weight=%+11.4e || E= %+11.4e\n",p[0],p[1],p[2],pt, y,weight,e);

	//decay procedure
	if(!Decay(mother,dau1,dau2,pol))continue;

	pt1 = dau1.Pt();
	pt2 = dau2.Pt();
	y1 = dau1.Rapidity();
	y2 = dau2.Rapidity();

	//first daughter
	p[0] = dau1.Px();
	p[1] = dau1.Py();
	p[2] = dau1.Pz();
	e = dau1.E();

	if(fVertexSmear==kPerTrack) {
	    Rndm(random,6);
	    for (j=0;j<3;j++) {
		origin[j]=fOrigin[j]+fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())*
		    TMath::Sqrt(-2*TMath::Log(random[2*j+1]));
	    }

	    Rndm(random,2);
	    time = fTimeOrigin + fOsigma[2]/TMath::Ccgs()*
	      TMath::Cos(2*random[0]*TMath::Pi())*
	      TMath::Sqrt(-2*TMath::Log(random[1]));
	}

	PushTrack(fTrackIt,-1,fLegPdg1,p,origin,polar,time,kPPrimary,nt, weight);
	if (fDebug == 2) printf("dau1-->id=%+3d, p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || weight=%+11.4e || E= %+11.4e\n",fLegPdg1,p[0],p[1],p[2],pt1,weight,e);

	//second daughter
	p[0] = dau2.Px();
	p[1] = dau2.Py();
	p[2] = dau2.Pz();
	e = dau2.E();

	if(fVertexSmear==kPerTrack) {
	    Rndm(random,6);
	    for (j=0;j<3;j++) {
		origin[j]=fOrigin[j]+fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())*
		    TMath::Sqrt(-2*TMath::Log(random[2*j+1]));
	    }

	    Rndm(random,2);
	    time = fTimeOrigin + fOsigma[2]/TMath::Ccgs()*
	      TMath::Cos(2*random[0]*TMath::Pi())*
	      TMath::Sqrt(-2*TMath::Log(random[1]));
	}

	PushTrack(fTrackIt,-1,fLegPdg2,p,origin,polar,time,kPPrimary,nt,weight);
      if (fDebug == 2) printf("dau2-->id=%+3d, p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || weight=%+11.4e || E= %+11.4e\n",fLegPdg2,p[0],p[1],p[2],pt2, weight,e);

    }//particle loop

}

//_____________________________________________________________________________

void AliGenPairFlat::Init()
{
	//
	// Init
	//

	printf("AliGenPairFlat::Init() not implemented!!!\n");

}

//_____________________________________________________________________________

Bool_t AliGenPairFlat::Decay(TLorentzVector mother, TLorentzVector &dau1, TLorentzVector &dau2, TF1* polfactor)
{
	//
	// decay procedure
	//

	Double_t mp, md1, md2, ed1, ed2, pd1, pd2;
	Double_t costheta, sintheta, phi;

	mp = mother.M();
	md1 = TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->Mass();
	md2 = TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->Mass();

	if(mp < md1+md2){
	printf("Daughters are heavier than Mother!! Check Kinematics!! \n");
	return 0;
	}

  ed1 = (mp*mp + md1*md1 - md2*md2)/(2.*mp);
  ed2 = mp-ed1;
  pd1 = TMath::Sqrt((ed1+md1)*(ed1-md1));
  pd2 = TMath::Sqrt((mp*mp-(md1+md2)*(md1+md2))*(mp*mp -(md1-md2)*(md1-md2)))/(2.*mp);

  costheta = polfactor->GetRandom(); //polarization
  sintheta = TMath::Sqrt((1.+costheta)*(1.-costheta));
  phi      = 2.0*TMath::Pi()*gRandom->Rndm();

	dau1.SetPxPyPzE(pd1*sintheta*TMath::Cos(phi),
		        pd1*sintheta*TMath::Sin(phi),
		        pd1*costheta,
			ed1);

	dau2.SetPxPyPzE((-1.)*pd1*sintheta*TMath::Cos(phi),
			(-1.)*pd1*sintheta*TMath::Sin(phi),
			(-1.)*pd1*costheta,
			ed2);

  	TVector3 boost = mother.BoostVector();

  	dau1.Boost(boost);
  	dau2.Boost(boost);

  return 1;

}

<|endoftext|>


<commit_before><commit_msg>replace memcmp with MagicCmp that supports '.' for single character of anything and add webp BUG=67987 TEST=omnibox can show webp from filer or harddrive when mimetype or extension is wrong<commit_after><|endoftext|>


<commit_before>
#include "test.h"
#include "include/agg_array.h"
#include "src/include/data_vector.h"
#include "timeuse.h"

using namespace picasso;

struct data_test
{
    int i;
    float f;
    double d;
};

volatile int tmp;
static int dummy[4096000];
static void clear_cache(void)
{
    int sum = 0;
    for(int i=0; i<4096000; i++)
        dummy[i] = 2;
    for(int i=0; i<4096000; i++)
        sum += dummy[i];

    tmp = sum;
}

TEST(Pod_Vector, CreateAndDestroy)
{
    pod_vector<unsigned int> iv;

    pod_vector<unsigned int> sv = iv;

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(0, (int)iv.capacity());

    EXPECT_EQ(0, (int)sv.size());
    EXPECT_EQ(0, (int)sv.capacity());

    EXPECT_NE(&iv , &sv);

    pod_vector<data_test> dv(10);

    EXPECT_EQ(0, (int)dv.size());
    EXPECT_EQ(10, (int)dv.capacity());
}

TEST(Pod_Vector, PushAndInsert)
{
    pod_vector<unsigned int> iv;
    pod_vector<unsigned int> sv;

    iv.resize(3);
    sv.resize(5);

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(3, (int)iv.capacity());

    EXPECT_EQ(0, (int)sv.size());
    EXPECT_EQ(5, (int)sv.capacity());

    bool b;
    b = iv.push_back(10);
    EXPECT_EQ(true, b);

    b = iv.push_back(11);
    EXPECT_EQ(true, b);

    b = iv.push_back(12);
    EXPECT_EQ(true, b);

    b = iv.push_back(13);
    EXPECT_EQ(false, b);

    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("copy vector iv to sv\n");
    sv = iv;

    EXPECT_EQ(3, (int)sv.size());
    EXPECT_EQ(5, (int)sv.capacity());

    EXPECT_EQ(true, sv.is_full());
    EXPECT_EQ(true, iv.is_full());

    for(unsigned int i = 0; i < sv.size(); i++)
        printf("sv: integer vector[%d] = %d\n",i, sv[i]);

    printf("resize iv to 6\n");
    iv.resize(6);
    for(unsigned int i = 0; i < iv.size(); i++) {
        EXPECT_EQ(sv[i], iv[i]);
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);
    }

    EXPECT_EQ(false, iv.is_full());
    EXPECT_EQ(3, (int)iv.size());
    EXPECT_EQ(6, (int)iv.capacity());

    printf("insert value to index 2\n");
    b = iv.insert_at(2, 15);
    EXPECT_EQ(true, b);
    EXPECT_EQ(4, (int)iv.size());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("insert value to index 15\n");
    b = iv.insert_at(15, 15);
    EXPECT_EQ(false, b);
    EXPECT_EQ(4, (int)iv.size());

    EXPECT_NE(iv.data(), sv.data());

    printf("reset capacity sv\n");
    sv.capacity(1);
    EXPECT_EQ(0, (int)sv.size());
    EXPECT_EQ(5, (int)sv.capacity());

    sv.capacity(10);
    EXPECT_EQ(0, (int)sv.size());
    EXPECT_EQ(10, (int)sv.capacity());

    printf("cut at index 2\n");
    iv.cut_at(2);
    EXPECT_EQ(2, (int)iv.size());
    EXPECT_EQ(6, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("set data!\n");
    unsigned int data[] = {100, 200, 300};
    iv.set_data(3, data);
    EXPECT_EQ(3, (int)iv.size());
    EXPECT_EQ(6, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("set data!\n");
    unsigned int data2[] = {50, 150, 250, 350, 450, 550 ,650, 750};
    iv.set_data(8, data2);
    EXPECT_EQ(3, (int)iv.size());
    EXPECT_EQ(6, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    iv.resize(8);
    iv.set_data(8, data2);
    EXPECT_EQ(8, (int)iv.size());
    EXPECT_EQ(8, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("clear iv\n");
    iv.clear();

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(8, (int)iv.capacity());
}

TEST(Pod_Vector, SpeedCompareWithAgg)
{
    clocktime_t t1, t2;
    double u1, u2;

    pod_vector<unsigned int> pv;
    pod_vector<data_test> pdv;
    data_test d = {1,1,1};

    printf("pod_vector speed testing...\n");
    clear_cache();
    // picasso data vector speed.
    t1 = get_clock();

    pv.resize(10000);
    for(unsigned int i = 0; i < pv.size(); i++)
        pv.push_back(i);
    pv.clear();

    pdv.resize(10000);
    for(unsigned int i = 0; i < pdv.size(); i++)
        pdv.push_back(d);
    pdv.clear();
    t2 = get_clock();
    u1 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "picasso pod_vector use %f ms\n", u1);

    clear_cache();

    agg::pod_vector<unsigned int> av;
    agg::pod_vector<data_test> adv;
    // agg data vector speed.
    t1 = get_clock();

    av.resize(10000);
    for(unsigned int i = 0; i < av.size(); i++)
        av.push_back(i);
    av.clear();

    adv.resize(10000);
    for(unsigned int i = 0; i < adv.size(); i++)
        adv.push_back(d);
    adv.clear();

    t2 = get_clock();
    u2 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "agg pod_vector use %f ms\n", u2);

    clear_cache();

    EXPECT_EQ(true, u1<=u2);
    if (u1 <= u2)
        fprintf (stderr, "picasso is faster!\n");
    else
        fprintf (stderr, "agg is faster!\n");

}

TEST(Pod_BVector, SpeedCompareWithAgg)
{
    clocktime_t t1, t2;
    double u1, u2;

    clear_cache();

    pod_bvector<unsigned int> pv;
    pod_bvector<data_test> pdv;
    data_test d = {1,1,1};

    printf("pod_bvector speed testing...\n");
    // picasso data vector speed.
    t1 = get_clock();

    for(unsigned int i = 0; i < 1000; i++)
        pv.add(i);
    pv.clear();

    for(unsigned int i = 0; i < 1000; i++)
        pdv.add(d);
    pdv.clear();

    t2 = get_clock();
    u1 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "picasso pod_bvector use %f ms\n", u1);

    clear_cache();

    agg::pod_bvector<unsigned int> av;
    agg::pod_bvector<data_test> pav;
    // agg data vector speed.
    t1 = get_clock();

    for(unsigned int i = 0; i < 1000; i++)
        av.add(i);
    av.remove_all();

    for(unsigned int i = 0; i < 1000; i++)
        pav.add(d);
    pav.remove_all();

    t2 = get_clock();
    u2 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "agg pod_bvector use %f ms\n", u2);

    clear_cache();

    EXPECT_EQ(true, u1<=u2);
    if (u1 <= u2)
        fprintf (stderr, "picasso is faster!\n");
    else
        fprintf (stderr, "agg is faster!\n");
}

TEST(Pod_BVector, BlockAndAutoSizeVector)
{
    printf("create bvector size 0, capacity 0\n");
    pod_bvector<unsigned int> iv;
    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(0, (int)iv.capacity());

    printf("add datas\n");
    iv.add(10);
    iv.add(11);
    iv.add(12);

    printf("bvector size 3, capacity 32\n");
    EXPECT_EQ(3, (int)iv.size());
    EXPECT_EQ(32, (int)iv.capacity());

    printf("add datas\n");
    iv.add(13);
    iv.add(14);

    printf("bvector size 5, capacity 32\n");
    EXPECT_EQ(5, (int)iv.size());
    EXPECT_EQ(32, (int)iv.capacity());

    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("remove last \n");
    iv.remove_last();

    printf("bvector size 4, capacity 32\n");
    EXPECT_EQ(4, (int)iv.size());
    EXPECT_EQ(32, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("remove all \n");
    iv.remove_all();

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(0, (int)iv.capacity());

}

TEST(Block_Allocater, BlockBaseAllocater)
{
    printf("create a block allocater\n");
    block_allocator alloc(16384-16);

    printf("alloc 100 elements aligment 4\n");
    data_test* ds = (data_test*)alloc.allocate(sizeof(data_test)*256, 4);
    EXPECT_EQ(true, ds!=0);

    printf("block memsize %d \n", alloc.all_mem_used());

    data_test* ss = (data_test*)alloc.allocate(sizeof(data_test), 8);
    EXPECT_EQ(true, ss!=0);
    printf("block memsize %d \n", alloc.all_mem_used());

    printf("free all memory\n");
    alloc.remove_all();

    printf("block memsize %d \n", alloc.all_mem_used());
}

TEST(Pod_Array, CreateAndInitialize)
{
    pod_array<unsigned int> iv;
    pod_array<unsigned int> sv = iv;

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(0, (int)sv.size());

    EXPECT_NE(&iv , &sv);

    pod_array<data_test> dv(10);
    EXPECT_EQ(10, (int)dv.size());
}

TEST(Pod_Array, SpeedCompareWithAgg)
{
    clocktime_t t1, t2;
    double u1, u2;
    pod_array<unsigned int> pv;

    printf("pod_array speed testing...\n");
    clear_cache();

    t1 = get_clock();

    for (int i = 1; i < 10000000; i++) {
        int s = (i%10) * 1024;
        pv.resize(s);
        pv[s-1] = i;
    }

    t2 = get_clock();
    u1 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "picasso pod_array use %f ms\n", u1);

    agg::pod_array<unsigned int> av;
    clear_cache();

    t1 = get_clock();

    for (int i = 1; i < 10000000; i++) {
        int s = (i%10) * 1024;
        av.resize(s);
        av[s-1] = i;
    }

    t2 = get_clock();
    u2 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "agg pod_array use %f ms\n", u1);

    clear_cache();

    EXPECT_EQ(true, u1<=u2);
    if (u1 <= u2)
        fprintf (stderr, "picasso is faster!\n");
    else
        fprintf (stderr, "agg is faster!\n");
}
<commit_msg>fix code<commit_after>
#include "test.h"
#include "src/include/data_vector.h"
#include "timeuse.h"

using namespace picasso;

struct data_test
{
    int i;
    float f;
    double d;
};

volatile int tmp;
static int dummy[4096000];
static void clear_cache(void)
{
    int sum = 0;
    for(int i=0; i<4096000; i++)
        dummy[i] = 2;
    for(int i=0; i<4096000; i++)
        sum += dummy[i];

    tmp = sum;
}

TEST(Pod_Vector, CreateAndDestroy)
{
    pod_vector<unsigned int> iv;

    pod_vector<unsigned int> sv = iv;

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(0, (int)iv.capacity());

    EXPECT_EQ(0, (int)sv.size());
    EXPECT_EQ(0, (int)sv.capacity());

    EXPECT_NE(&iv , &sv);

    pod_vector<data_test> dv(10);

    EXPECT_EQ(0, (int)dv.size());
    EXPECT_EQ(10, (int)dv.capacity());
}

TEST(Pod_Vector, PushAndInsert)
{
    pod_vector<unsigned int> iv;
    pod_vector<unsigned int> sv;

    iv.resize(3);
    sv.resize(5);

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(3, (int)iv.capacity());

    EXPECT_EQ(0, (int)sv.size());
    EXPECT_EQ(5, (int)sv.capacity());

    bool b;
    b = iv.push_back(10);
    EXPECT_EQ(true, b);

    b = iv.push_back(11);
    EXPECT_EQ(true, b);

    b = iv.push_back(12);
    EXPECT_EQ(true, b);

    b = iv.push_back(13);
    EXPECT_EQ(false, b);

    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("copy vector iv to sv\n");
    sv = iv;

    EXPECT_EQ(3, (int)sv.size());
    EXPECT_EQ(5, (int)sv.capacity());

    EXPECT_EQ(true, sv.is_full());
    EXPECT_EQ(true, iv.is_full());

    for(unsigned int i = 0; i < sv.size(); i++)
        printf("sv: integer vector[%d] = %d\n",i, sv[i]);

    printf("resize iv to 6\n");
    iv.resize(6);
    for(unsigned int i = 0; i < iv.size(); i++) {
        EXPECT_EQ(sv[i], iv[i]);
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);
    }

    EXPECT_EQ(false, iv.is_full());
    EXPECT_EQ(3, (int)iv.size());
    EXPECT_EQ(6, (int)iv.capacity());

    printf("insert value to index 2\n");
    b = iv.insert_at(2, 15);
    EXPECT_EQ(true, b);
    EXPECT_EQ(4, (int)iv.size());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("insert value to index 15\n");
    b = iv.insert_at(15, 15);
    EXPECT_EQ(false, b);
    EXPECT_EQ(4, (int)iv.size());

    EXPECT_NE(iv.data(), sv.data());

    printf("reset capacity sv\n");
    sv.capacity(1);
    EXPECT_EQ(0, (int)sv.size());
    EXPECT_EQ(5, (int)sv.capacity());

    sv.capacity(10);
    EXPECT_EQ(0, (int)sv.size());
    EXPECT_EQ(10, (int)sv.capacity());

    printf("cut at index 2\n");
    iv.cut_at(2);
    EXPECT_EQ(2, (int)iv.size());
    EXPECT_EQ(6, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("set data!\n");
    unsigned int data[] = {100, 200, 300};
    iv.set_data(3, data);
    EXPECT_EQ(3, (int)iv.size());
    EXPECT_EQ(6, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("set data!\n");
    unsigned int data2[] = {50, 150, 250, 350, 450, 550 ,650, 750};
    iv.set_data(8, data2);
    EXPECT_EQ(3, (int)iv.size());
    EXPECT_EQ(6, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    iv.resize(8);
    iv.set_data(8, data2);
    EXPECT_EQ(8, (int)iv.size());
    EXPECT_EQ(8, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("clear iv\n");
    iv.clear();

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(8, (int)iv.capacity());
}

TEST(Pod_Vector, SpeedCompareWithAgg)
{
    clocktime_t t1, t2;
    double u1, u2;

    pod_vector<unsigned int> pv;
    pod_vector<data_test> pdv;
    data_test d = {1,1,1};

    printf("pod_vector speed testing...\n");
    clear_cache();
    // picasso data vector speed.
    t1 = get_clock();

    pv.resize(10000);
    for(unsigned int i = 0; i < pv.size(); i++)
        pv.push_back(i);
    pv.clear();

    pdv.resize(10000);
    for(unsigned int i = 0; i < pdv.size(); i++)
        pdv.push_back(d);
    pdv.clear();
    t2 = get_clock();
    u1 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "picasso pod_vector use %f ms\n", u1);

    clear_cache();

    agg::pod_vector<unsigned int> av;
    agg::pod_vector<data_test> adv;
    // agg data vector speed.
    t1 = get_clock();

    av.resize(10000);
    for(unsigned int i = 0; i < av.size(); i++)
        av.push_back(i);
    av.clear();

    adv.resize(10000);
    for(unsigned int i = 0; i < adv.size(); i++)
        adv.push_back(d);
    adv.clear();

    t2 = get_clock();
    u2 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "agg pod_vector use %f ms\n", u2);

    clear_cache();

    EXPECT_EQ(true, u1<=u2);
    if (u1 <= u2)
        fprintf (stderr, "picasso is faster!\n");
    else
        fprintf (stderr, "agg is faster!\n");

}

TEST(Pod_BVector, SpeedCompareWithAgg)
{
    clocktime_t t1, t2;
    double u1, u2;

    clear_cache();

    pod_bvector<unsigned int> pv;
    pod_bvector<data_test> pdv;
    data_test d = {1,1,1};

    printf("pod_bvector speed testing...\n");
    // picasso data vector speed.
    t1 = get_clock();

    for(unsigned int i = 0; i < 1000; i++)
        pv.add(i);
    pv.clear();

    for(unsigned int i = 0; i < 1000; i++)
        pdv.add(d);
    pdv.clear();

    t2 = get_clock();
    u1 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "picasso pod_bvector use %f ms\n", u1);

    clear_cache();

    agg::pod_bvector<unsigned int> av;
    agg::pod_bvector<data_test> pav;
    // agg data vector speed.
    t1 = get_clock();

    for(unsigned int i = 0; i < 1000; i++)
        av.add(i);
    av.remove_all();

    for(unsigned int i = 0; i < 1000; i++)
        pav.add(d);
    pav.remove_all();

    t2 = get_clock();
    u2 = get_clock_used_ms(t1, t2);
    fprintf (stderr, "agg pod_bvector use %f ms\n", u2);

    clear_cache();

    EXPECT_EQ(true, u1<=u2);
    if (u1 <= u2)
        fprintf (stderr, "picasso is faster!\n");
    else
        fprintf (stderr, "agg is faster!\n");
}

TEST(Pod_BVector, BlockAndAutoSizeVector)
{
    printf("create bvector size 0, capacity 0\n");
    pod_bvector<unsigned int> iv;
    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(0, (int)iv.capacity());

    printf("add datas\n");
    iv.add(10);
    iv.add(11);
    iv.add(12);

    printf("bvector size 3, capacity 32\n");
    EXPECT_EQ(3, (int)iv.size());
    EXPECT_EQ(32, (int)iv.capacity());

    printf("add datas\n");
    iv.add(13);
    iv.add(14);

    printf("bvector size 5, capacity 32\n");
    EXPECT_EQ(5, (int)iv.size());
    EXPECT_EQ(32, (int)iv.capacity());

    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("remove last \n");
    iv.remove_last();

    printf("bvector size 4, capacity 32\n");
    EXPECT_EQ(4, (int)iv.size());
    EXPECT_EQ(32, (int)iv.capacity());
    for(unsigned int i = 0; i < iv.size(); i++)
        printf("iv: integer vector[%d] = %d\n",i, iv[i]);

    printf("remove all \n");
    iv.remove_all();

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(0, (int)iv.capacity());

}

TEST(Block_Allocater, BlockBaseAllocater)
{
    printf("create a block allocater\n");
    block_allocator alloc(16384-16);

    printf("alloc 100 elements aligment 4\n");
    data_test* ds = (data_test*)alloc.allocate(sizeof(data_test)*256, 4);
    EXPECT_EQ(true, ds!=0);

    printf("block memsize %d \n", alloc.all_mem_used());

    data_test* ss = (data_test*)alloc.allocate(sizeof(data_test), 8);
    EXPECT_EQ(true, ss!=0);
    printf("block memsize %d \n", alloc.all_mem_used());

    printf("free all memory\n");
    alloc.remove_all();

    printf("block memsize %d \n", alloc.all_mem_used());
}

TEST(Pod_Array, CreateAndInitialize)
{
    pod_array<unsigned int> iv;
    pod_array<unsigned int> sv = iv;

    EXPECT_EQ(0, (int)iv.size());
    EXPECT_EQ(0, (int)sv.size());

    EXPECT_NE(&iv , &sv);

    pod_array<data_test> dv(10);
    EXPECT_EQ(10, (int)dv.size());
}

<|endoftext|>


<commit_before>/* --- Unitary test symmetric.cpp This code tests and compares three ways of
 * expressing symmetric matrices. In addition to the unitary validation (test
 * of the basic operations), the code is validating the computation
 * performances of each methods.
 *
 * The three methods are:
 * - Eigen SelfAdjoint (a mask atop of a classical dense matrix) ==> the least efficient.
 * - Metapod Symmetric with LTI factorization.
 * - Pinocchio rewritting of Metapod code with LTI factor as well and minor improvement.
 *
 * Expected time scores on a I7 2.1GHz:
 * - Eigen: 2.5us
 * - Metapod: 4us
 * - Pinocchio: 6us
 */

#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/se3.hpp"
#include "pinocchio/tools/timer.hpp"

#include <boost/random.hpp>
#include <assert.h>

#include "pinocchio/spatial/symmetric3.hpp"

#include <Eigen/StdVector>
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::Matrix3d);
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(se3::Symmetric3);

/* --- PINOCCHIO ------------------------------------------------------------ */
/* --- PINOCCHIO ------------------------------------------------------------ */
/* --- PINOCCHIO ------------------------------------------------------------ */
void timeSym3(const se3::Symmetric3 & S,
	      const se3::Symmetric3::Matrix3 & R,
	      se3::Symmetric3 & res)
{
  res = S.rotate(R);
}

void testSym3()
{
  using namespace se3;
  typedef Symmetric3::Matrix3 Matrix3;
  typedef Symmetric3::Vector3 Vector3;

  {
    // op(Matrix3)
    {
      Matrix3 M = Matrix3::Random(); M = M*M.transpose();
      Symmetric3 S(M);
      assert( S.matrix().isApprox(M) );
    }

    // S += S
    {
      Symmetric3
	S = Symmetric3::Random(),
	S2 = Symmetric3::Random();
      Symmetric3 Scopy = S;
      S+=S2;
      assert( S.matrix().isApprox( S2.matrix()+Scopy.matrix()) );
    }

    // S + M
    {
      Symmetric3 S = Symmetric3::Random();
      Matrix3 M = Matrix3::Random(); M = M*M.transpose();

      Symmetric3 S2 = S + M;
      assert( S2.matrix().isApprox( S.matrix()+M ));

      S2 = S - M;
      assert( S2.matrix().isApprox( S.matrix()-M ));
    }

    // S*v
    {
      Symmetric3 S = Symmetric3::Random();
      Vector3 v = Vector3::Random();
      Vector3 Sv = S*v;
      assert( Sv.isApprox( S.matrix()*v ));
    }

    // Random
    for(int i=0;i<100;++i )
      {
	Matrix3 M = Matrix3::Random(); M = M*M.transpose();
	Symmetric3 S = Symmetric3::RandomPositive();
	Vector3 v = Vector3::Random();
	assert( (v.transpose()*(S*v))[0] > 0);
      }

    // Identity
    {
      assert( Symmetric3::Identity().matrix().isApprox( Matrix3::Identity() ) );
    }

    // Skew2
    {
      Vector3 v = Vector3::Random();
      Symmetric3 vxvx = Symmetric3::SkewSquare(v);

      Vector3 p = Vector3::UnitX();
      assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));
      p = Vector3::UnitY();
      assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));
      p = Vector3::UnitZ();
      assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));

      Matrix3 vx = skew(v);
      Matrix3 vxvx2 = (vx*vx).eval();
      assert( vxvx.matrix().isApprox(vxvx2) );

      Symmetric3 S = Symmetric3::RandomPositive();
      assert( (S-Symmetric3::SkewSquare(v)).matrix()
	      .isApprox( S.matrix()-vxvx2 ) );
      double m = Eigen::internal::random<double>()+1;
      assert( (S-m*Symmetric3::SkewSquare(v)).matrix()
	      .isApprox( S.matrix()-m*vxvx2 ) );

      Symmetric3 S2 = S;
      S -= Symmetric3::SkewSquare(v);
      assert(S.matrix().isApprox( S2.matrix()-vxvx2 ) );
      S = S2; S -= m*Symmetric3::SkewSquare(v);
      assert(S.matrix().isApprox( S2.matrix()-m*vxvx2 ) );

    }

    // (i,j)
    {
	Matrix3 M = Matrix3::Random(); M = M*M.transpose();
	Symmetric3 S(M);
	for(int i=0;i<3;++i)
	  for(int j=0;j<3;++j)
	    assert( S(i,j) == M(i,j) );
    }
  }

  // SRS
  {
    Symmetric3 S = Symmetric3::RandomPositive();
    Matrix3 R = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();

    Symmetric3 RSRt = S.rotate(R);
    assert( RSRt.matrix().isApprox( R*S.matrix()*R.transpose() ));

    Symmetric3 RtSR = S.rotate(R.transpose());
    assert( RtSR.matrix().isApprox( R.transpose()*S.matrix()*R ));
  }

  // Time test
  {
    const int NBT = 100000;
    Symmetric3 S = Symmetric3::RandomPositive();

    std::vector<Symmetric3> Sres (NBT);
    std::vector<Matrix3> Rs (NBT);
    for(int i=0;i<NBT;++i)
      Rs[i] = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();

    std::cout << "Pinocchio: ";
    StackTicToc timer(StackTicToc::US); timer.tic();
    SMOOTH(NBT)
      {
	timeSym3(S,Rs[_smooth],Sres[_smooth]);
      }
    timer.toc(std::cout,NBT);
  }
}

/* --- METAPOD -------------------------------------------------------------- */
/* --- METAPOD -------------------------------------------------------------- */
/* --- METAPOD -------------------------------------------------------------- */

#ifdef WITH_METAPOD

#include <metapod/tools/spatial/lti.hh>
#include <metapod/tools/spatial/rm-general.hh>

EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::ltI<double>);
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::RotationMatrixTpl<double>);

void timeLTI(const metapod::Spatial::ltI<double>& S,
	     const metapod::Spatial::RotationMatrixTpl<double>& R,
	     metapod::Spatial::ltI<double> & res)
{
  res = R.rotTSymmetricMatrix(S);
}

void testLTI()
{
  using namespace metapod::Spatial;

  typedef ltI<double> Sym3;
  typedef Eigen::Matrix3d Matrix3;
  typedef RotationMatrixTpl<double> R3;

  Matrix3 M = Matrix3::Random();
  Sym3 S(M),S2;

  R3 R; R.randomInit();

  R.rotTSymmetricMatrix(S);
  timeLTI(S,R,S2);
  assert( S2.toMatrix().isApprox( R.toMatrix().transpose()*S.toMatrix()*R.toMatrix()) );

  const int NBT = 100000;
  std::vector<Sym3> Sres (NBT);
  std::vector<R3> Rs (NBT);
  for(int i=0;i<NBT;++i)
    Rs[i].randomInit();

  std::cout << "Metapod: ";
  StackTicToc timer(StackTicToc::US); timer.tic();
  SMOOTH(NBT)
    {
      timeLTI(S,Rs[_smooth],Sres[_smooth]);
    }
  timer.toc(std::cout,NBT);
}

#else // #ifdef WITH_METAPOD

void testLTI()
{
  std::cout << "Metapod is not installed ... skipping this test. " << std::endl;
}

#endif // #ifdef WITH_METAPOD

/* --- EIGEN SYMMETRIC ------------------------------------------------------ */
/* --- EIGEN SYMMETRIC ------------------------------------------------------ */
/* --- EIGEN SYMMETRIC ------------------------------------------------------ */
void timeSelfAdj( const Eigen::Matrix3d & A,
		  const Eigen::Matrix3d & Sdense,
		  Eigen::Matrix3d & ASA )
{
  typedef Eigen::SelfAdjointView<Eigen::Matrix3d,Eigen::Upper> Sym3;
  Sym3 S(Sdense);
  ASA.triangularView<Eigen::Upper>()
    = A * S * A.transpose();
}

void testSelfAdj()
{
  using namespace se3;
  typedef Eigen::Matrix3d Matrix3;
  typedef Eigen::SelfAdjointView<Matrix3,Eigen::Upper> Sym3;

  Matrix3 M = Matrix3::Random();
  Sym3 S(M);
  {
    Matrix3 Scp = S;
    assert( Scp-Scp.transpose()==Matrix3::Zero());
  }

  Matrix3 M2 = Matrix3::Random();
  M.triangularView<Eigen::Upper>() = M2;

  Matrix3 A = Matrix3::Random(), ASA1, ASA2;
  ASA1.triangularView<Eigen::Upper>() = A * S * A.transpose();
  timeSelfAdj(A,M,ASA2);

  {
    Matrix3 Masa1 = ASA1.selfadjointView<Eigen::Upper>();
    Matrix3 Masa2 = ASA2.selfadjointView<Eigen::Upper>();
    assert(Masa1.isApprox(Masa2));
  }

  const int NBT = 100000;
  std::vector<Eigen::Matrix3d> Sres (NBT);
  std::vector<Eigen::Matrix3d> Rs (NBT);
  for(int i=0;i<NBT;++i)
    Rs[i] = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();

  std::cout << "Eigen: ";
  StackTicToc timer(StackTicToc::US); timer.tic();
  SMOOTH(NBT)
    {
      timeSelfAdj(Rs[_smooth],M,Sres[_smooth]);
    }
  timer.toc(std::cout,NBT);
}

int main()
{
  testSelfAdj();
  testLTI();
  testSym3();

  return 0;
}
<commit_msg>[Debug] Correct bug in Symmectric test that was preventing tests to compile (at least on ubutun 14.04 LTS)<commit_after>/* --- Unitary test symmetric.cpp This code tests and compares three ways of
 * expressing symmetric matrices. In addition to the unitary validation (test
 * of the basic operations), the code is validating the computation
 * performances of each methods.
 *
 * The three methods are:
 * - Eigen SelfAdjoint (a mask atop of a classical dense matrix) ==> the least efficient.
 * - Metapod Symmetric with LTI factorization.
 * - Pinocchio rewritting of Metapod code with LTI factor as well and minor improvement.
 *
 * Expected time scores on a I7 2.1GHz:
 * - Eigen: 2.5us
 * - Metapod: 4us
 * - Pinocchio: 6us
 */

#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/se3.hpp"
#include "pinocchio/tools/timer.hpp"

#include <boost/random.hpp>
#include <assert.h>

#include "pinocchio/spatial/symmetric3.hpp"

#include <Eigen/StdVector>
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::Matrix3d);
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(se3::Symmetric3);

/* --- PINOCCHIO ------------------------------------------------------------ */
/* --- PINOCCHIO ------------------------------------------------------------ */
/* --- PINOCCHIO ------------------------------------------------------------ */
void timeSym3(const se3::Symmetric3 & S,
	      const se3::Symmetric3::Matrix3 & R,
	      se3::Symmetric3 & res)
{
  res = S.rotate(R);
}

void testSym3()
{
  using namespace se3;
  typedef Symmetric3::Matrix3 Matrix3;
  typedef Symmetric3::Vector3 Vector3;

  {
    // op(Matrix3)
    {
      Matrix3 M = Matrix3::Random(); M = M*M.transpose();
      Symmetric3 S(M);
      assert( S.matrix().isApprox(M) );
    }

    // S += S
    {
      Symmetric3
	S = Symmetric3::Random(),
	S2 = Symmetric3::Random();
      Symmetric3 Scopy = S;
      S+=S2;
      assert( S.matrix().isApprox( S2.matrix()+Scopy.matrix()) );
    }

    // S + M
    {
      Symmetric3 S = Symmetric3::Random();
      Matrix3 M = Matrix3::Random(); M = M*M.transpose();

      Symmetric3 S2 = S + M;
      assert( S2.matrix().isApprox( S.matrix()+M ));

      S2 = S - M;
      assert( S2.matrix().isApprox( S.matrix()-M ));
    }

    // S*v
    {
      Symmetric3 S = Symmetric3::Random();
      Vector3 v = Vector3::Random();
      Vector3 Sv = S*v;
      assert( Sv.isApprox( S.matrix()*v ));
    }

    // Random
    for(int i=0;i<100;++i )
      {
	Matrix3 M = Matrix3::Random(); M = M*M.transpose();
	Symmetric3 S = Symmetric3::RandomPositive();
	Vector3 v = Vector3::Random();
	assert( (v.transpose()*(S*v))[0] > 0);
      }

    // Identity
    {
      assert( Symmetric3::Identity().matrix().isApprox( Matrix3::Identity() ) );
    }

    // Skew2
    {
      Vector3 v = Vector3::Random();
      Symmetric3 vxvx = Symmetric3::SkewSquare(v);

      Vector3 p = Vector3::UnitX();
      assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));
      p = Vector3::UnitY();
      assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));
      p = Vector3::UnitZ();
      assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));

      Matrix3 vx = skew(v);
      Matrix3 vxvx2 = (vx*vx).eval();
      assert( vxvx.matrix().isApprox(vxvx2) );

      Symmetric3 S = Symmetric3::RandomPositive();
      assert( (S-Symmetric3::SkewSquare(v)).matrix()
	      .isApprox( S.matrix()-vxvx2 ) );
      double m = Eigen::internal::random<double>()+1;
      assert( (S-m*Symmetric3::SkewSquare(v)).matrix()
	      .isApprox( S.matrix()-m*vxvx2 ) );

      Symmetric3 S2 = S;
      S -= Symmetric3::SkewSquare(v);
      assert(S.matrix().isApprox( S2.matrix()-vxvx2 ) );
      S = S2; S -= m*Symmetric3::SkewSquare(v);
      assert(S.matrix().isApprox( S2.matrix()-m*vxvx2 ) );

    }

    // (i,j)
    {
	Matrix3 M = Matrix3::Random(); M = M*M.transpose();
	Symmetric3 S(M);
	for(int i=0;i<3;++i)
	  for(int j=0;j<3;++j)
	    assert( S(i,j) == M(i,j) );
    }
  }

  // SRS
  {
    Symmetric3 S = Symmetric3::RandomPositive();
    Matrix3 R = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();

    Symmetric3 RSRt = S.rotate(R);
    assert( RSRt.matrix().isApprox( R*S.matrix()*R.transpose() ));

    Symmetric3 RtSR = S.rotate(R.transpose());
    assert( RtSR.matrix().isApprox( R.transpose()*S.matrix()*R ));
  }

  // Time test
  {
    const int NBT = 100000;
    Symmetric3 S = Symmetric3::RandomPositive();

    std::vector<Symmetric3> Sres (NBT);
    std::vector<Matrix3> Rs (NBT);
    for(int i=0;i<NBT;++i)
      Rs[i] = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();

    std::cout << "Pinocchio: ";
    StackTicToc timer(StackTicToc::US); timer.tic();
    SMOOTH(NBT)
      {
	timeSym3(S,Rs[_smooth],Sres[_smooth]);
      }
    timer.toc(std::cout,NBT);
  }
}

/* --- METAPOD -------------------------------------------------------------- */
/* --- METAPOD -------------------------------------------------------------- */
/* --- METAPOD -------------------------------------------------------------- */

#ifdef WITH_METAPOD

#include <metapod/tools/spatial/lti.hh>
#include <metapod/tools/spatial/rm-general.hh>

EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::ltI<double>);
EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::RotationMatrixTpl<double>);

void timeLTI(const metapod::Spatial::ltI<double>& S,
	     const metapod::Spatial::RotationMatrixTpl<double>& R,
	     metapod::Spatial::ltI<double> & res)
{
  res = R.rotTSymmetricMatrix(S);
}

void testLTI()
{
  using namespace metapod::Spatial;

  typedef ltI<double> Sym3;
  typedef Eigen::Matrix3d Matrix3;
  typedef RotationMatrixTpl<double> R3;

  Matrix3 M = Matrix3::Random();
  Sym3 S(M),S2;

  R3 R; R.randomInit();

  R.rotTSymmetricMatrix(S);
  timeLTI(S,R,S2);
  assert( S2.toMatrix().isApprox( R.toMatrix().transpose()*S.toMatrix()*R.toMatrix()) );

  const int NBT = 100000;
  std::vector<Sym3> Sres (NBT);
  std::vector<R3> Rs (NBT);
  for(int i=0;i<NBT;++i)
    Rs[i].randomInit();

  std::cout << "Metapod: ";
  StackTicToc timer(StackTicToc::US); timer.tic();
  SMOOTH(NBT)
    {
      timeLTI(S,Rs[_smooth],Sres[_smooth]);
    }
  timer.toc(std::cout,NBT);
}

#else // #ifdef WITH_METAPOD

void testLTI()
{
  std::cout << "Metapod is not installed ... skipping this test. " << std::endl;
}

#endif // #ifdef WITH_METAPOD

/* --- EIGEN SYMMETRIC ------------------------------------------------------ */
/* --- EIGEN SYMMETRIC ------------------------------------------------------ */
/* --- EIGEN SYMMETRIC ------------------------------------------------------ */
void timeSelfAdj( const Eigen::Matrix3d & A,
		  const Eigen::Matrix3d & Sdense,
		  Eigen::Matrix3d & ASA )
{
  typedef Eigen::SelfAdjointView<const Eigen::Matrix3d,Eigen::Upper> Sym3;
  Sym3 S(Sdense);
  ASA.triangularView<Eigen::Upper>()
    = A * S * A.transpose();
}

void testSelfAdj()
{
  using namespace se3;
  typedef Eigen::Matrix3d Matrix3;
  typedef Eigen::SelfAdjointView<Matrix3,Eigen::Upper> Sym3;

  Matrix3 M = Matrix3::Random();
  Sym3 S(M);
  {
    Matrix3 Scp = S;
    assert( Scp-Scp.transpose()==Matrix3::Zero());
  }

  Matrix3 M2 = Matrix3::Random();
  M.triangularView<Eigen::Upper>() = M2;

  Matrix3 A = Matrix3::Random(), ASA1, ASA2;
  ASA1.triangularView<Eigen::Upper>() = A * S * A.transpose();
  timeSelfAdj(A,M,ASA2);

  {
    Matrix3 Masa1 = ASA1.selfadjointView<Eigen::Upper>();
    Matrix3 Masa2 = ASA2.selfadjointView<Eigen::Upper>();
    assert(Masa1.isApprox(Masa2));
  }

  const int NBT = 100000;
  std::vector<Eigen::Matrix3d> Sres (NBT);
  std::vector<Eigen::Matrix3d> Rs (NBT);
  for(int i=0;i<NBT;++i)
    Rs[i] = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();

  std::cout << "Eigen: ";
  StackTicToc timer(StackTicToc::US); timer.tic();
  SMOOTH(NBT)
    {
      timeSelfAdj(Rs[_smooth],M,Sres[_smooth]);
    }
  timer.toc(std::cout,NBT);
}

int main()
{
  testSelfAdj();
  testLTI();
  testSym3();

  return 0;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Randolph Voorhies, Shane Grant
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of cereal nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "common.hpp"
#include <boost/test/unit_test.hpp>

template <class IArchive, class OArchive>
void test_valarray()
{
	std::random_device rd;
	std::mt19937 gen(rd());

	for (int ii = 0; ii<100; ++ii)
	{
		std::valarray<int> o_podvalarray(100);
		for (auto & elem : o_podvalarray)
			elem = random_value<int>(gen);

		std::valarray<StructInternalSerialize> o_iservalarray(100);
		for (auto & elem : o_iservalarray)
			elem = StructInternalSerialize(random_value<int>(gen), random_value<int>(gen));

		std::valarray<StructInternalSplit> o_isplvalarray(100);
		for (auto & elem : o_isplvalarray)
			elem = StructInternalSplit(random_value<int>(gen), random_value<int>(gen));

		std::valarray<StructExternalSerialize> o_eservalarray(100);
		for (auto & elem : o_eservalarray)
			elem = StructExternalSerialize(random_value<int>(gen), random_value<int>(gen));

		std::valarray<StructExternalSplit> o_esplvalarray(100);
		for (auto & elem : o_esplvalarray)
			elem = StructExternalSplit(random_value<int>(gen), random_value<int>(gen));

		std::ostringstream os;
		{
			OArchive oar(os);

			oar(o_podvalarray);
			oar(o_iservalarray);
			oar(o_isplvalarray);
			oar(o_eservalarray);
			oar(o_esplvalarray);
		}

		std::valarray<int> i_podvalarray;
		std::valarray<StructInternalSerialize> i_iservalarray;
		std::valarray<StructInternalSplit>     i_isplvalarray;
		std::valarray<StructExternalSerialize> i_eservalarray;
		std::valarray<StructExternalSplit>     i_esplvalarray;

		std::istringstream is(os.str());
		{
			IArchive iar(is);

			iar(i_podvalarray);
			iar(i_iservalarray);
			iar(i_isplvalarray);
			iar(i_eservalarray);
			iar(i_esplvalarray);
		}

		BOOST_CHECK_EQUAL(i_podvalarray.size(), o_podvalarray.size());
		BOOST_CHECK_EQUAL(i_iservalarray.size(), o_iservalarray.size());
		BOOST_CHECK_EQUAL(i_isplvalarray.size(), o_isplvalarray.size());
		BOOST_CHECK_EQUAL(i_eservalarray.size(), o_eservalarray.size());
		BOOST_CHECK_EQUAL(i_esplvalarray.size(), o_esplvalarray.size());

		BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_podvalarray), std::end(i_podvalarray), std::begin(o_podvalarray), std::end(o_podvalarray));
		BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_iservalarray), std::end(i_iservalarray), std::begin(o_iservalarray), std::end(o_iservalarray));
		BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_isplvalarray), std::end(i_isplvalarray), std::begin(o_isplvalarray), std::end(o_isplvalarray));
		BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_eservalarray), std::end(i_eservalarray), std::begin(o_eservalarray), std::end(o_eservalarray));
		BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_esplvalarray), std::end(i_esplvalarray), std::begin(o_esplvalarray), std::end(o_esplvalarray));
	}
}

BOOST_AUTO_TEST_CASE(binary_valarray)
{
	test_valarray<cereal::BinaryInputArchive, cereal::BinaryOutputArchive>();
}

BOOST_AUTO_TEST_CASE(portable_binary_valarray)
{
	test_valarray<cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive>();
}

BOOST_AUTO_TEST_CASE(xml_valarray)
{
	test_valarray<cereal::XMLInputArchive, cereal::XMLOutputArchive>();
}

BOOST_AUTO_TEST_CASE(json_valarray)
{
	test_valarray<cereal::JSONInputArchive, cereal::JSONOutputArchive>();
}
<commit_msg>more tab spacing fixes<commit_after>/*
Copyright (c) 2014, Randolph Voorhies, Shane Grant
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of cereal nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "common.hpp"
#include <boost/test/unit_test.hpp>

template <class IArchive, class OArchive>
void test_valarray()
{
  std::random_device rd;
  std::mt19937 gen(rd());

  for (int ii = 0; ii<100; ++ii)
  {
    std::valarray<int> o_podvalarray(100);
    for (auto & elem : o_podvalarray)
      elem = random_value<int>(gen);

    std::valarray<StructInternalSerialize> o_iservalarray(100);
    for (auto & elem : o_iservalarray)
      elem = StructInternalSerialize(random_value<int>(gen), random_value<int>(gen));

    std::valarray<StructInternalSplit> o_isplvalarray(100);
    for (auto & elem : o_isplvalarray)
      elem = StructInternalSplit(random_value<int>(gen), random_value<int>(gen));

    std::valarray<StructExternalSerialize> o_eservalarray(100);
    for (auto & elem : o_eservalarray)
      elem = StructExternalSerialize(random_value<int>(gen), random_value<int>(gen));

    std::valarray<StructExternalSplit> o_esplvalarray(100);
    for (auto & elem : o_esplvalarray)
      elem = StructExternalSplit(random_value<int>(gen), random_value<int>(gen));

    std::ostringstream os;
    {
      OArchive oar(os);

      oar(o_podvalarray);
      oar(o_iservalarray);
      oar(o_isplvalarray);
      oar(o_eservalarray);
      oar(o_esplvalarray);
    }

    std::valarray<int> i_podvalarray;
    std::valarray<StructInternalSerialize> i_iservalarray;
    std::valarray<StructInternalSplit>     i_isplvalarray;
    std::valarray<StructExternalSerialize> i_eservalarray;
    std::valarray<StructExternalSplit>     i_esplvalarray;

    std::istringstream is(os.str());
    {
      IArchive iar(is);

      iar(i_podvalarray);
      iar(i_iservalarray);
      iar(i_isplvalarray);
      iar(i_eservalarray);
      iar(i_esplvalarray);
    }

    BOOST_CHECK_EQUAL(i_podvalarray.size(), o_podvalarray.size());
    BOOST_CHECK_EQUAL(i_iservalarray.size(), o_iservalarray.size());
    BOOST_CHECK_EQUAL(i_isplvalarray.size(), o_isplvalarray.size());
    BOOST_CHECK_EQUAL(i_eservalarray.size(), o_eservalarray.size());
    BOOST_CHECK_EQUAL(i_esplvalarray.size(), o_esplvalarray.size());

    BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_podvalarray), std::end(i_podvalarray), std::begin(o_podvalarray), std::end(o_podvalarray));
    BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_iservalarray), std::end(i_iservalarray), std::begin(o_iservalarray), std::end(o_iservalarray));
    BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_isplvalarray), std::end(i_isplvalarray), std::begin(o_isplvalarray), std::end(o_isplvalarray));
    BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_eservalarray), std::end(i_eservalarray), std::begin(o_eservalarray), std::end(o_eservalarray));
    BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_esplvalarray), std::end(i_esplvalarray), std::begin(o_esplvalarray), std::end(o_esplvalarray));
  }
}

BOOST_AUTO_TEST_CASE(binary_valarray)
{
  test_valarray<cereal::BinaryInputArchive, cereal::BinaryOutputArchive>();
}

BOOST_AUTO_TEST_CASE(portable_binary_valarray)
{
  test_valarray<cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive>();
}

BOOST_AUTO_TEST_CASE(xml_valarray)
{
  test_valarray<cereal::XMLInputArchive, cereal::XMLOutputArchive>();
}

BOOST_AUTO_TEST_CASE(json_valarray)
{
  test_valarray<cereal::JSONInputArchive, cereal::JSONOutputArchive>();
}
<|endoftext|>


<commit_before>#pragma once
/**
	@file
	@brief a class to get top n score
	@author MITSUNARI Shigeo(@herumi)
*/
#include <vector>

namespace cybozu { namespace nlp {

/*
	T is int, size_t or pointer to object
*/
template<class T, class Double = double>
class TopScore {
public:
	struct Pair {
		Double score;
		T idx;
	};
	typedef std::vector<Pair> Table;
private:
	const size_t maxSize_;
	size_t size_;
	mutable Table tbl_;
	TopScore(const TopScore&);
	void operator=(const TopScore&);
public:
	explicit TopScore(size_t maxSize = 10)
		: maxSize_(maxSize)
		, size_(0)
	{
		tbl_.resize(maxSize_);
	}
	void setSize(size_t maxSize)
	{
		maxSize_ = maxSize;
		size_ = 0;
		tbl_.clear();
	}
	void add(Double score, T idx)
	{
		// short cut
		if (size_ == maxSize_ && score <= tbl_[size_ - 1].score) {
			return;
		}
		int pos = -1;
		if (size_ > 0) {
			for (size_t i = 0; i < size_; i++) {
				if (score > tbl_[i].score) {
					int end = (int)std::min(maxSize_ - 2, size_ - 1);
					for (int j = end; j >= (int)i; j--) {
						tbl_[j + 1] = tbl_[j];
					}
					pos = (int)i;
					break;
				}
			}
		}
		if (size_ < maxSize_) {
			if (pos < 0) pos = (int)size_;
			size_++;
		}
		if (pos == -1) return;
		tbl_[pos].score = score;
		tbl_[pos].idx = idx;
	}
	const Table& getTable() const
	{
		tbl_.resize(size_);
		return tbl_;
	}
};

} } // cybozu::nlp
<commit_msg>remove const<commit_after>#pragma once
/**
	@file
	@brief a class to get top n score
	@author MITSUNARI Shigeo(@herumi)
*/
#include <vector>

namespace cybozu { namespace nlp {

/*
	T is int, size_t or pointer to object
*/
template<class T, class Double = double>
class TopScore {
public:
	struct Pair {
		Double score;
		T idx;
	};
	typedef std::vector<Pair> Table;
private:
	size_t maxSize_;
	size_t size_;
	mutable Table tbl_;
	TopScore(const TopScore&);
	void operator=(const TopScore&);
public:
	explicit TopScore(size_t maxSize = 10)
		: maxSize_(maxSize)
		, size_(0)
	{
		tbl_.resize(maxSize_);
	}
	void setSize(size_t maxSize)
	{
		maxSize_ = maxSize;
		size_ = 0;
		tbl_.clear();
	}
	void add(Double score, T idx)
	{
		// short cut
		if (size_ == maxSize_ && score <= tbl_[size_ - 1].score) {
			return;
		}
		int pos = -1;
		if (size_ > 0) {
			for (size_t i = 0; i < size_; i++) {
				if (score > tbl_[i].score) {
					int end = (int)std::min(maxSize_ - 2, size_ - 1);
					for (int j = end; j >= (int)i; j--) {
						tbl_[j + 1] = tbl_[j];
					}
					pos = (int)i;
					break;
				}
			}
		}
		if (size_ < maxSize_) {
			if (pos < 0) pos = (int)size_;
			size_++;
		}
		if (pos == -1) return;
		tbl_[pos].score = score;
		tbl_[pos].idx = idx;
	}
	const Table& getTable() const
	{
		tbl_.resize(size_);
		return tbl_;
	}
};

} } // cybozu::nlp
<|endoftext|>


<commit_before>/*

Copyright (c) 2015, Project OSRM contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef JSON_LOGGER_HPP
#define JSON_LOGGER_HPP

#include <osrm/json_container.hpp>

#include <boost/thread.hpp>

namespace osrm
{
namespace json
{

// Used to append additional debugging information to the JSON response in a
// thread safe manner.
class Logger
{
    using MapT = std::unordered_map<std::string, osrm::json::Value>;

  public:
    static Logger* get()
    {
        static Logger logger;

        bool return_logger = true;
#ifdef NDEBUG
        return_logger = false;
#endif
#ifdef ENABLE_JSON_LOGGING
        return_logger = true;
#endif

        if (return_logger)
        {
            return &logger;
        }

        return nullptr;
    }

    void initialize(const std::string& name)
    {
        if (!map.get())
        {
            map.reset(new MapT());
        }
        (*map)[name] = Object();
    }

    void render(const std::string& name, Object& obj) const
    {
        obj.values["debug"] = map->at(name);
    }

    boost::thread_specific_ptr<MapT> map;
};

}
}

#endif /* JSON_LOGGER_HPP */
<commit_msg>Do not include Boost.Thread is a sub-header is good enough.<commit_after>/*

Copyright (c) 2015, Project OSRM contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef JSON_LOGGER_HPP
#define JSON_LOGGER_HPP

#include <osrm/json_container.hpp>

#include <boost/thread/tss.hpp>

#include <string>
#include <unordered_map>

namespace osrm
{
namespace json
{

// Used to append additional debugging information to the JSON response in a
// thread safe manner.
class Logger
{
    using MapT = std::unordered_map<std::string, osrm::json::Value>;

  public:
    static Logger* get()
    {
        static Logger logger;

        bool return_logger = true;
#ifdef NDEBUG
        return_logger = false;
#endif
#ifdef ENABLE_JSON_LOGGING
        return_logger = true;
#endif

        if (return_logger)
        {
            return &logger;
        }

        return nullptr;
    }

    void initialize(const std::string& name)
    {
        if (!map.get())
        {
            map.reset(new MapT());
        }
        (*map)[name] = Object();
    }

    void render(const std::string& name, Object& obj) const
    {
        obj.values["debug"] = map->at(name);
    }

    boost::thread_specific_ptr<MapT> map;
};

}
}

#endif /* JSON_LOGGER_HPP */
<|endoftext|>


<commit_before>#ifndef HERMIT_TASK_REMAPPER_HPP
#define HERMIT_TASK_REMAPPER_HPP

#include <boost/config.hpp>

#include <vector>
#include <exception>
#include <boost/asio.hpp>
#include <boost/asio/system_timer.hpp>
#include <boost/tr1/memory.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

#ifdef BOOST_NO_0X_HDR_FUTURE
#include <boost/tr1/functional.hpp>
#include <boost/thread.hpp>
#include <boost/ref.hpp>
#else
# ifdef BOOST_NO_LAMBDAS
#include <boost/tr1/functional.hpp>
# endif
#include <future>
#endif

namespace hermit {
  class poller_core {
    public:
      template< typename Func >
        poller_core( boost::asio::io_service &service, Func func,
            boost::posix_time::milliseconds time
            ) : timer( service ), task( func ), interval( time ) {
          timer.expires_from_now( interval );
          timer.async_wait( boost::bind( &poller_core::timeout, this, boost::asio::placeholders::error ) );
        }
      void timeout( const boost::system::error_code &error ) {
        if( !error ) {
          task();
          timer.expires_from_now( interval );
          timer.async_wait( boost::bind( &poller_core::timeout, this, boost::asio::placeholders::error ) );
        }
      }
    private:
      boost::asio::deadline_timer timer;
      std::function< void() > task;
      boost::posix_time::milliseconds interval;
  };

  class poller {
    public:
      template< typename Func >
        poller( boost::asio::io_service &service_, Func func,
            boost::posix_time::milliseconds time
            ) : core( new poller_core( service_, func, time ) ) {}
    private:
      std::shared_ptr< poller_core > core;
  };

  class task_remapper {
    public:
      task_remapper( size_t size ) {
        work.reset( new boost::asio::io_service::work( task_queue ) );
        for( int count = 0; count != size; ++count ) {
#ifdef BOOST_NO_0X_HDR_FUTURE
          end_sync.create_thread( std::bind( &task_remapper::run, this ) );
#else
# ifdef BOOST_NO_LAMBDAS
          end_sync.push_back( std::async( std::launch::async, std::bind( &task_remapper::run, this ) ) );
# else
          end_sync.push_back( std::async( std::launch::async, [&]() { this->run(); } ) );
# endif
#endif
        }
      }
#ifdef BOOST_NO_DELETED_FUNCTIONS
    private:
      task_remapper( const task_remapper& );
      task_remapper& operator=( const task_remapper& );
    public:
#else
      task_remapper( const task_remapper& ) = delete;
      task_remapper& operator=( const task_remapper& ) = delete;
#endif
      ~task_remapper() {
        work.reset();
#ifdef BOOST_NO_0X_HDR_FUTURE
        end_sync.join_all();
#else
        for( auto &elem: end_sync )
          elem.get();
#endif
      }
      template< typename T >
        void post( T func ) {
          task_queue.post( func );
        }
      template< typename T, typename Time >
        poller post( T func, Time time ) {
          return poller( task_queue, func, time );
        }
      template< typename T >
        void set_epilogue( T func ) {
          epilogue.post( func );
        }
      void sync() {
#ifdef BOOST_NO_0X_HDR_FUTURE
        std::shared_ptr< boost::thread::promise< void > > signal( new boost::thread::promise< void >() );
#else
        std::shared_ptr< std::promise< void > > signal( new std::promise< void >() );
#endif
        task_queue.post( [=](){ signal->set_value(); } );
        signal->get_future().wait();
      }
    private:
      static void null_epilogue() {}
      void run() noexcept {
        try {
          std::cout << "hoge" << std::endl;
          task_queue.run();
          epilogue.run();
        } catch ( std::exception &e ) {
          std::cerr << "An exception was thrown from queued tasks. : " << e.what() << std::endl;
          std::cerr << "Aborting." << std::endl;
          std::abort();
        } catch ( ... ) {
          std::cerr << "An exception was thrown from queued tasks." << std::endl;
          std::cerr << "Aborting." << std::endl;
          std::abort();
        }
      }
      std::unique_ptr<boost::asio::io_service::work> work;
      boost::asio::io_service task_queue;
      boost::asio::io_service epilogue;
#ifdef BOOST_NO_0X_HDR_FUTURE
      boost::thread_group end_sync;
#else
      std::vector< std::future< void > > end_sync;
#endif
  };
}

#endif
<commit_msg>task_remapperのC++03対応<commit_after>#ifndef HERMIT_TASK_REMAPPER_HPP
#define HERMIT_TASK_REMAPPER_HPP

#include <boost/config.hpp>

#include <vector>
#include <exception>
#include <boost/asio.hpp>
#include <boost/asio/system_timer.hpp>
#include <boost/tr1/memory.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

#ifdef BOOST_NO_0X_HDR_FUTURE
#include <boost/tr1/functional.hpp>
#include <boost/thread.hpp>
#include <boost/ref.hpp>
#else
# ifdef BOOST_NO_LAMBDAS
#include <boost/tr1/functional.hpp>
# endif
#include <future>
#endif

namespace hermit {
  class poller_core {
    public:
      template< typename Func >
        poller_core( boost::asio::io_service &service, Func func,
            boost::posix_time::milliseconds time
            ) : timer( service ), task( func ), interval( time ) {
          timer.expires_from_now( interval );
          timer.async_wait( boost::bind( &poller_core::timeout, this, boost::asio::placeholders::error ) );
        }
      void timeout( const boost::system::error_code &error ) {
        if( !error ) {
          task();
          timer.expires_from_now( interval );
          timer.async_wait( boost::bind( &poller_core::timeout, this, boost::asio::placeholders::error ) );
        }
      }
    private:
      boost::asio::deadline_timer timer;
      std::function< void() > task;
      boost::posix_time::milliseconds interval;
  };

  class poller {
    public:
      template< typename Func >
        poller( boost::asio::io_service &service_, Func func,
            boost::posix_time::milliseconds time
            ) : core( new poller_core( service_, func, time ) ) {}
    private:
      std::shared_ptr< poller_core > core;
  };

  class task_remapper {
    public:
      task_remapper( size_t size ) {
        work.reset( new boost::asio::io_service::work( task_queue ) );
        for( int count = 0; count != size; ++count ) {
#ifdef BOOST_NO_0X_HDR_FUTURE
          end_sync.create_thread( std::bind( &task_remapper::run, this ) );
#else
# ifdef BOOST_NO_LAMBDAS
          end_sync.push_back( std::async( std::launch::async, std::bind( &task_remapper::run, this ) ) );
# else
          end_sync.push_back( std::async( std::launch::async, [&]() { this->run(); } ) );
# endif
#endif
        }
      }
#ifdef BOOST_NO_DELETED_FUNCTIONS
    private:
      task_remapper( const task_remapper& );
      task_remapper& operator=( const task_remapper& );
    public:
#else
      task_remapper( const task_remapper& ) = delete;
      task_remapper& operator=( const task_remapper& ) = delete;
#endif
      ~task_remapper() {
        work.reset();
#ifdef BOOST_NO_0X_HDR_FUTURE
        end_sync.join_all();
#else
        for(
          std::vector< std::future< void > >::iterator iter = end_sync.begin();
          iter != end_sync.end(); ++iter
        ) iter->get();
#endif
      }
      template< typename T >
        void post( T func ) {
          task_queue.post( func );
        }
      template< typename T, typename Time >
        poller post( T func, Time time ) {
          return poller( task_queue, func, time );
        }
      template< typename T >
        void set_epilogue( T func ) {
          epilogue.post( func );
        }
      void sync() {
#ifdef BOOST_NO_0X_HDR_FUTURE
        std::shared_ptr< boost::thread::promise< void > > signal( new boost::thread::promise< void >() );
#else
        std::shared_ptr< std::promise< void > > signal( new std::promise< void >() );
#endif
#ifdef BOOST_NO_LAMBDAS
# ifdef BOOST_NO_0X_HDR_FUTURE
        task_queue.post( std::bind( &boost::thread::promise< void >::set_value, signal ) );
# else
        task_queue.post( std::bind( &std::promise< void >::set_value, signal ) );
#else
        task_queue.post( [=](){ signal->set_value(); } );
#endif
        signal->get_future().wait();
      }
    private:
      static void null_epilogue() {}
#ifdef BOOST_NO_NOEXCEPT
      void run() {
#else
      void run() noexcept {
#endif
        try {
          task_queue.run();
          epilogue.run();
        } catch ( std::exception &e ) {
          std::cerr << "An exception was thrown from queued tasks. : " << e.what() << std::endl;
          std::cerr << "Aborting." << std::endl;
          std::abort();
        } catch ( ... ) {
          std::cerr << "An exception was thrown from queued tasks." << std::endl;
          std::cerr << "Aborting." << std::endl;
          std::abort();
        }
      }
      std::unique_ptr<boost::asio::io_service::work> work;
      boost::asio::io_service task_queue;
      boost::asio::io_service epilogue;
#ifdef BOOST_NO_0X_HDR_FUTURE
      boost::thread_group end_sync;
#else
      std::vector< std::future< void > > end_sync;
#endif
  };
}

#endif
<|endoftext|>


<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_XML_PARSE_HPP
#define TORRENT_XML_PARSE_HPP

#include <cctype>
#include <cstring>

#include "libtorrent/escape_string.hpp"

namespace libtorrent
{
	enum
	{
		xml_start_tag,
		xml_end_tag,
		xml_empty_tag,
		xml_declaration_tag,
		xml_string,
		xml_attribute,
		xml_comment,
		xml_parse_error
	};

	// callback(int type, char const* name, char const* val)
	// str2 is only used for attributes. name is element or attribute
	// name and val is attribute value

	template <class CallbackType>
	void xml_parse(char* p, char* end, CallbackType callback)
	{
		for(;p != end; ++p)
		{
			char const* start = p;
			char const* val_start = 0;
			int token;
			// look for tag start
			for(; *p != '<' && p != end; ++p);

			if (p != start)
			{
				if (p != end)
				{
					TORRENT_ASSERT(*p == '<');
					*p = 0;
				}
				token = xml_string;
				callback(token, start, val_start);
				if (p != end) *p = '<';
			}

			if (p == end) break;

			// skip '<'
			++p;
			if (p != end && p+8 < end && string_begins_no_case("![CDATA[", p))
			{
				// CDATA. match '![CDATA['
				p += 8;
				start = p;
				while (p != end && !string_begins_no_case("]]>", p-2)) ++p;

				// parse error
				if (p == end)
				{
					token = xml_parse_error;
					start = "unexpected end of file";
					callback(token, start, val_start);
					break;
				}

				token = xml_string;
				char tmp = p[-2];
				p[-2] = 0;
				callback(token, start, val_start);
				p[-2] = tmp;
				continue;
			}

			// parse the name of the tag.
			for (start = p; p != end && *p != '>' && !is_space(*p); ++p);

			char* tag_name_end = p;

			// skip the attributes for now
			for (; p != end && *p != '>'; ++p);

			// parse error
			if (p == end)
			{
				token = xml_parse_error;
				start = "unexpected end of file";
				callback(token, start, val_start);
				break;
			}

			TORRENT_ASSERT(*p == '>');
			// save the character that terminated the tag name
			// it could be both '>' and ' '.
			char save = *tag_name_end;
			*tag_name_end = 0;

			char* tag_end = p;
			if (*start == '/')
			{
				++start;
				token = xml_end_tag;
				callback(token, start, val_start);
			}
			else if (*(p-1) == '/')
			{
				*(p-1) = 0;
				token = xml_empty_tag;
				callback(token, start, val_start);
				*(p-1) = '/';
				tag_end = p - 1;
			}
			else if (*start == '?' && *(p-1) == '?')
			{
				*(p-1) = 0;
				++start;
				token = xml_declaration_tag;
				callback(token, start, val_start);
				*(p-1) = '?';
				tag_end = p - 1;
			}
			else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0)
			{
				start += 3;
				*(p-2) = 0;
				token = xml_comment;
				callback(token, start, val_start);
				*(p-2) = '-';
				tag_end = p - 2;
			}
			else
			{
				token = xml_start_tag;
				callback(token, start, val_start);
			}

			*tag_name_end = save;

			// parse attributes
			for (char* i = tag_name_end; i < tag_end; ++i)
			{
				// find start of attribute name
				for (; i != tag_end && isspace(*i); ++i);
				if (i == tag_end) break;
				start = i;
				// find end of attribute name
				for (; i != tag_end && *i != '=' && !isspace(*i); ++i);
				char* name_end = i;

				// look for equality sign
				for (; i != tag_end && *i != '='; ++i);

				if (i == tag_end)
				{
					token = xml_parse_error;
					val_start = 0;
					start = "garbage inside element brackets";
					callback(token, start, val_start);
					break;
				}

				++i;
				for (; i != tag_end && isspace(*i); ++i);
				// check for parse error (values must be quoted)
				if (i == tag_end || (*i != '\'' && *i != '\"'))
				{
					token = xml_parse_error;
					val_start = 0;
					start = "unquoted attribute value";
					callback(token, start, val_start);
					break;
				}
				char quote = *i;
				++i;
				val_start = i;
				for (; i != tag_end && *i != quote; ++i);
				// parse error (missing end quote)
				if (i == tag_end)
				{
					token = xml_parse_error;
					val_start = 0;
					start = "missing end quote on attribute";
					callback(token, start, val_start);
					break;
				}
				save = *i;
				*i = 0;
				*name_end = 0;
				token = xml_attribute;
				callback(token, start, val_start);
				*name_end = '=';
				*i = save;
			}
		}
	}

}

#endif

<commit_msg>replace calls to isspace() with is_space() to avoid asserts in the CRT<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_XML_PARSE_HPP
#define TORRENT_XML_PARSE_HPP

#include <cctype>
#include <cstring>

#include "libtorrent/escape_string.hpp"

namespace libtorrent
{
	enum
	{
		xml_start_tag,
		xml_end_tag,
		xml_empty_tag,
		xml_declaration_tag,
		xml_string,
		xml_attribute,
		xml_comment,
		xml_parse_error
	};

	// callback(int type, char const* name, char const* val)
	// str2 is only used for attributes. name is element or attribute
	// name and val is attribute value

	template <class CallbackType>
	void xml_parse(char* p, char* end, CallbackType callback)
	{
		for(;p != end; ++p)
		{
			char const* start = p;
			char const* val_start = 0;
			int token;
			// look for tag start
			for(; *p != '<' && p != end; ++p);

			if (p != start)
			{
				if (p != end)
				{
					TORRENT_ASSERT(*p == '<');
					*p = 0;
				}
				token = xml_string;
				callback(token, start, val_start);
				if (p != end) *p = '<';
			}

			if (p == end) break;

			// skip '<'
			++p;
			if (p != end && p+8 < end && string_begins_no_case("![CDATA[", p))
			{
				// CDATA. match '![CDATA['
				p += 8;
				start = p;
				while (p != end && !string_begins_no_case("]]>", p-2)) ++p;

				// parse error
				if (p == end)
				{
					token = xml_parse_error;
					start = "unexpected end of file";
					callback(token, start, val_start);
					break;
				}

				token = xml_string;
				char tmp = p[-2];
				p[-2] = 0;
				callback(token, start, val_start);
				p[-2] = tmp;
				continue;
			}

			// parse the name of the tag.
			for (start = p; p != end && *p != '>' && !is_space(*p); ++p);

			char* tag_name_end = p;

			// skip the attributes for now
			for (; p != end && *p != '>'; ++p);

			// parse error
			if (p == end)
			{
				token = xml_parse_error;
				start = "unexpected end of file";
				callback(token, start, val_start);
				break;
			}

			TORRENT_ASSERT(*p == '>');
			// save the character that terminated the tag name
			// it could be both '>' and ' '.
			char save = *tag_name_end;
			*tag_name_end = 0;

			char* tag_end = p;
			if (*start == '/')
			{
				++start;
				token = xml_end_tag;
				callback(token, start, val_start);
			}
			else if (*(p-1) == '/')
			{
				*(p-1) = 0;
				token = xml_empty_tag;
				callback(token, start, val_start);
				*(p-1) = '/';
				tag_end = p - 1;
			}
			else if (*start == '?' && *(p-1) == '?')
			{
				*(p-1) = 0;
				++start;
				token = xml_declaration_tag;
				callback(token, start, val_start);
				*(p-1) = '?';
				tag_end = p - 1;
			}
			else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0)
			{
				start += 3;
				*(p-2) = 0;
				token = xml_comment;
				callback(token, start, val_start);
				*(p-2) = '-';
				tag_end = p - 2;
			}
			else
			{
				token = xml_start_tag;
				callback(token, start, val_start);
			}

			*tag_name_end = save;

			// parse attributes
			for (char* i = tag_name_end; i < tag_end; ++i)
			{
				// find start of attribute name
				for (; i != tag_end && is_space(*i); ++i);
				if (i == tag_end) break;
				start = i;
				// find end of attribute name
				for (; i != tag_end && *i != '=' && !is_space(*i); ++i);
				char* name_end = i;

				// look for equality sign
				for (; i != tag_end && *i != '='; ++i);

				if (i == tag_end)
				{
					token = xml_parse_error;
					val_start = 0;
					start = "garbage inside element brackets";
					callback(token, start, val_start);
					break;
				}

				++i;
				for (; i != tag_end && is_space(*i); ++i);
				// check for parse error (values must be quoted)
				if (i == tag_end || (*i != '\'' && *i != '\"'))
				{
					token = xml_parse_error;
					val_start = 0;
					start = "unquoted attribute value";
					callback(token, start, val_start);
					break;
				}
				char quote = *i;
				++i;
				val_start = i;
				for (; i != tag_end && *i != quote; ++i);
				// parse error (missing end quote)
				if (i == tag_end)
				{
					token = xml_parse_error;
					val_start = 0;
					start = "missing end quote on attribute";
					callback(token, start, val_start);
					break;
				}
				save = *i;
				*i = 0;
				*name_end = 0;
				token = xml_attribute;
				callback(token, start, val_start);
				*name_end = '=';
				*i = save;
			}
		}
	}

}

#endif

<|endoftext|>


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

#include <iostream>
#include <stdio.h>
#include <thread>
#include <atomic>
#include <iomanip>
#include <map>
#include <mutex>
#include <vector>
#include <sstream>
#include <fstream>
#include <stdarg.h>
#include <time.h>
#include <string.h>
#include <signal.h>
#include "buildincmd.h"

#include "../libuuu/libuuu.h"

#ifndef _MSC_VER
#include <unistd.h>
#include <limits.h>
#else
#include <Windows.h>
#endif

void linux_auto_arg(const char *space = " ", const char * filter = "")
{
	string str = filter;

	const char *param[] = { "-b", "-d", "-v", "-V", "-s", NULL };
	int i = 0;

	for (int i = 0; param[i]; i++)
	{
		if (str.find(param[i]) == string::npos)
			cout << param[i] << space << endl;
	}
}

int linux_autocomplete_ls(const char *path, void *p)
{
	cout << path + 2 << endl;
	return 0;
}

void linux_autocomplete(int argc, char **argv)
{
	string last = argv[3];
	string cur = argv[2];

	if (argv[2][0] == '-')
	{
		if (cur.size() == 1)
			linux_auto_arg();
		else
			cout << cur << " " << endl;

		return;
	}

	if (last.size()>=3)
	{
		if (last.substr(last.size() - 3) == "uuu" &&(cur.empty() || cur[0] == '-'))
		{
			linux_auto_arg();
			cout << cur << endl;
		}

	}else if(last.empty())
	{
		linux_auto_arg();
	}
	else if (last == "-b")
	{
		return g_BuildScripts.PrintAutoComplete(cur);

	}else if(last[0] == '-')
	{
		linux_auto_arg();
	}

	uuu_for_each_ls_file(linux_autocomplete_ls, cur.c_str(), NULL);
}

string get_next_word(string str, size_t &pos)
{
	size_t start = 0;
	start = str.find(' ', pos);
	string sub = str.substr(pos, start - pos);
	pos = start == string::npos ? start : start + 1;
	return sub;
}

void power_shell_autocomplete(const char *p)
{
	string pstr = p;
	size_t pos = 0;

	string file;

	vector<string> argv; string params;
	while (pos != string::npos && pos < pstr.size())
	{
		file = get_next_word(pstr, pos);
		argv.push_back(file);

		if (file.size() && file[0] == '-')
			params += " " + file;
	}

	string last = argv[argv.size() - 1];
	string prev = argv.size() > 1 ? argv[argv.size() - 2] : "";
	if (last == "-b" || prev == "-b")
	{
		string cur;
		if (prev == "-b")
			cur = last;

		if (g_BuildScripts.find(cur) == g_BuildScripts.end())
			g_BuildScripts.PrintAutoComplete(cur, "");

		last.clear();
	}
	else
	{
		if (last[0] == '-' || argv.size() == 1)
			linux_auto_arg("", params.c_str());
	}

	if (argv.size() == 1)
		last.clear();

	uuu_for_each_ls_file(linux_autocomplete_ls, last.c_str(), NULL);
}

int auto_complete(int argc, char**argv)
{
	if (argc == 4)
	{
		string str = argv[1];
		if (str.size() >= 3)
			if (str.substr(str.size() - 3) == "uuu")
			{
				linux_autocomplete(argc, argv);
				return 0;
			}
	}

	if (argc >= 2)
	{
		string str = argv[1];
		if (str == "-autocomplete")
		{
			power_shell_autocomplete(argc == 2 ? "" : argv[2]);
			return 0;
		}
	}

	return 1;
}

void print_autocomplete_help()
{

#ifndef _MSC_VER
	{
		cout << "Enjoy auto [tab] command complete by run below command" << endl;
		char result[PATH_MAX];
		memset(result, 0, PATH_MAX);
		ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
		cout << "  complete -o nospace -C " << result << " uuu" << endl << endl;
	}
#else
	{
		printf("Powershell: Enjoy auto [tab] command complete by run below command\n");

		HMODULE hModule = GetModuleHandleA(NULL);
		char path[MAX_PATH];
		GetModuleFileNameA(hModule, path, MAX_PATH);

		printf("   Register-ArgumentCompleter -CommandName uuu -ScriptBlock {param($commandName,$parameterName,$wordToComplete,$commandAst,$fakeBoundParameter); %s -autocomplete $parameterName }\n",
			path);
	}
#endif

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

#include <iostream>
#include <stdio.h>
#include <thread>
#include <atomic>
#include <iomanip>
#include <map>
#include <mutex>
#include <vector>
#include <sstream>
#include <fstream>
#include <stdarg.h>
#include <time.h>
#include <string.h>
#include <signal.h>
#include "buildincmd.h"

#include "../libuuu/libuuu.h"

#ifndef _MSC_VER
#include <unistd.h>
#include <limits.h>
#else
#include <Windows.h>
#endif

void linux_auto_arg(const char *space = " ", const char * filter = "")
{
	string str = filter;

	const char *param[] = { "-b", "-d", "-v", "-V", "-s", NULL };
	int i = 0;

	for (int i = 0; param[i]; i++)
	{
		if (str.find(param[i]) == string::npos)
			cout << param[i] << space << endl;
	}
}

int linux_autocomplete_ls(const char *path, void *p)
{
	cout << path + 2 << endl;
	return 0;
}

void linux_autocomplete(int argc, char **argv)
{
	string last = argv[3];
	string cur = argv[2];

	if (argv[2][0] == '-')
	{
		if (cur.size() == 1)
			linux_auto_arg();
		else
			cout << cur << " " << endl;

		return;
	}

	if (last.size()>=3)
	{
		if (last.substr(last.size() - 3) == "uuu" &&(cur.empty() || cur[0] == '-'))
		{
			linux_auto_arg();
			cout << cur << endl;
		}

	}else if(last.empty())
	{
		linux_auto_arg();
	}
	else if (last == "-b")
	{
		return g_BuildScripts.PrintAutoComplete(cur);

	}else if(last[0] == '-')
	{
		linux_auto_arg();
	}

	uuu_for_each_ls_file(linux_autocomplete_ls, cur.c_str(), NULL);
}

string get_next_word(string str, size_t &pos)
{
	size_t start = 0;
	start = str.find(' ', pos);
	string sub = str.substr(pos, start - pos);
	pos = start == string::npos ? start : start + 1;
	return sub;
}

void power_shell_autocomplete(const char *p)
{
	string pstr = p;
	size_t pos = 0;

	string file;

	vector<string> argv; string params;
	while (pos != string::npos && pos < pstr.size())
	{
		file = get_next_word(pstr, pos);
		argv.push_back(file);

		if (file.size() && file[0] == '-')
			params += " " + file;
	}

	string last = argv[argv.size() - 1];
	string prev = argv.size() > 1 ? argv[argv.size() - 2] : "";
	if (last == "-b" || prev == "-b")
	{
		string cur;
		if (prev == "-b")
			cur = last;

		if (g_BuildScripts.find(cur) == g_BuildScripts.end())
			g_BuildScripts.PrintAutoComplete(cur, "");

		last.clear();
	}
	else
	{
		if (last[0] == '-' || argv.size() == 1)
			linux_auto_arg("", params.c_str());
	}

	if (argv.size() == 1)
		last.clear();

	uuu_for_each_ls_file(linux_autocomplete_ls, last.c_str(), NULL);
}

int auto_complete(int argc, char**argv)
{
	if (argc == 4)
	{
		string str = argv[1];
		if (str.size() >= 3)
			if (str.substr(str.size() - 3) == "uuu")
			{
				linux_autocomplete(argc, argv);
				return 0;
			}
	}

	if (argc >= 2)
	{
		string str = argv[1];
		if (str == "-autocomplete")
		{
			power_shell_autocomplete(argc == 2 ? "" : argv[2]);
			return 0;
		}
	}

	return 1;
}

void print_autocomplete_help()
{

#ifndef _MSC_VER
	{
		cout << "Enjoy auto [tab] command complete by run below command" << endl;
		char result[PATH_MAX];
		memset(result, 0, PATH_MAX);
		ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
		cout << "  complete -o nospace -C " << result << " uuu" << endl << endl;
	}
#else
	{
		printf("Powershell: Enjoy auto [tab] command complete by run below command\n");

		HMODULE hModule = GetModuleHandleA(NULL);
		char path[MAX_PATH];
		GetModuleFileNameA(hModule, path, MAX_PATH);

		printf("   Register-ArgumentCompleter -CommandName uuu -ScriptBlock {param($commandName,$parameterName,$wordToComplete,$commandAst,$fakeBoundParameter); %s -autocomplete $parameterName }\n\n",
			path);
	}
#endif

}
<|endoftext|>


<commit_before><commit_msg>Wrap "" in OUString: error: conversion from const char* to non-scalar...<commit_after><|endoftext|>