<commit_before>// $Header$

#include "PMDModule.h"

#include "AliPMDdigit.h"
#include "AliPMDddldata.h"

using namespace Reve;
using namespace Alieve;

const Float_t PMDModule::fgkRad     = 0.25;
const Float_t PMDModule::fgkSqRoot3 = 1.732050808;
const Float_t PMDModule::fgkZpos    = 0.;
//______________________________________________________________________
// PMDModule
//

ClassImp(PMDModule)

PMDModule::PMDModule():
  fX(0.),
  fY(0.),
  fZ(0.),
  fNPads(0)
{

}
// -------------------------------------------------------------------- //
void PMDModule::DisplayInit(Int_t ism)
{
  TString smodule = "Module";
  smodule+= ism;

  Float_t xism =0, yism = 0;
  Float_t dxism =0, dyism = 0;

  GenerateBox(ism,xism,yism,dxism,dyism);

  Reve::FrameBox *pmdModBox = new FrameBox();
  pmdModBox->SetAAQuadXY(xism, yism, 0, dxism, dyism);
  pmdModBox->SetFrameColor((Color_t) 31);

  Reve::RGBAPalette *pmdModPalette  = new RGBAPalette(20, 1000);
  pmdModPalette->SetLimits(0, 1000);

  //  Reve::QuadSet* q = this;
  SetName(smodule.Data());
  SetOwnIds(kTRUE);
  Reset(Reve::QuadSet::QT_HexagonXY, kFALSE, 32);

  SetFrame(pmdModBox);
  SetPalette(pmdModPalette);

}
// -------------------------------------------------------------------- //
void PMDModule::DisplayDigitsData(Int_t ism, TTree *pmdt)
{

  DisplayInit(ism);

  Int_t det, smn, irow, icol, adc;
  Int_t xpad = 0, ypad = 0;
  Float_t xpos, ypos;

  TClonesArray *digits = new TClonesArray("AliPMDdigit", 0);

  TBranch *branch = pmdt->GetBranch("PMDDigit");
  branch->SetAddress(&digits);

  AliPMDdigit  *pmddigit;

  branch->GetEntry(ism);
  Int_t nentries = digits->GetLast();
  //printf("%d\n", nentries);

  for (Int_t ient = 0; ient < nentries+1; ient++)
    {
      pmddigit = (AliPMDdigit*)digits->UncheckedAt(ient);

      det    = pmddigit->GetDetector();
      smn    = pmddigit->GetSMNumber();
      irow   = pmddigit->GetRow();
      icol   = pmddigit->GetColumn();
      adc    = (Int_t) pmddigit->GetADC();

      if(smn <12)
	{
	  xpad = icol;
	  ypad = irow;
	}
      else if(smn >=12 && smn < 24)
	{
	  xpad = irow;
	  ypad = icol;
	}

      RectGeomCellPos(smn, xpad, ypad, xpos, ypos);

      AddHexagon(xpos, ypos, fgkZpos, fgkRad);

      QuadValue(adc);

      QuadId(new AliPMDdigit(*pmddigit));
      // new TNamed(Form("Quad with idx=%d", ient),
      //  "This title is not confusing."));

      ++fNPads;
    }

  RefitPlex();

  fHMTrans.SetPos(fX, fY, fZ);

  delete digits;
}
// -------------------------------------------------------------------- //

void PMDModule::DisplayRawData(Int_t ism, TObjArray *ddlcont)
{

  if (ism > 23) ism -= 24;

  DisplayInit(ism);

  Int_t det, smn, irow, icol, adc;
  Int_t xpad = 0, ypad = 0;
  Float_t xpos, ypos;

  Int_t nentries = ddlcont->GetEntries();
  //printf("%d\n", nentries);

  for (Int_t ient = 0; ient < nentries; ient++)
    {
      AliPMDddldata *pmdddl = (AliPMDddldata*)ddlcont->UncheckedAt(ient);

      det    = pmdddl->GetDetector();
      smn    = pmdddl->GetSMN();
      if (smn != ism) continue;
      irow   = pmdddl->GetRow();
      icol   = pmdddl->GetColumn();
      adc    = pmdddl->GetSignal();

      if(smn <12)
	{
	  xpad = icol;
	  ypad = irow;
	}
      else if(smn >=12 && smn < 24)
	{
	  xpad = irow;
	  ypad = icol;
	}

      RectGeomCellPos(smn, xpad, ypad, xpos, ypos);

      AddHexagon(xpos, ypos, fgkZpos, fgkRad);

      QuadValue(adc);

      QuadId(new AliPMDddldata(*pmdddl));
      //new TNamed(Form("Quad with idx=%d", ient),
      //  "This title is not confusing."));

      ++fNPads;
    }

  RefitPlex();

  fHMTrans.SetPos(fX, fY, fZ);

}
// -------------------------------------------------------------------- //

void PMDModule::RectGeomCellPos(Int_t ism, Int_t xpad, Int_t ypad,
				Float_t &xpos, Float_t &ypos)
{
  // This routine finds the cell eta,phi for the new PMD rectangular
  // geometry in ALICE
  // Authors : Bedanga Mohanty and Dipak Mishra - 29.4.2003
  // modified by B. K. Nandi for change of coordinate sys
  //
  // SMA  ---> Supermodule Type A           ( SM - 0)
  // SMAR ---> Supermodule Type A ROTATED   ( SM - 1)
  // SMB  ---> Supermodule Type B           ( SM - 2)
  // SMBR ---> Supermodule Type B ROTATED   ( SM - 3)
  //
  // ism   : Serial module number from 0 to 23 for each plane

  // Corner positions (x,y) of the 24 unit moudles in ALICE PMD

  const Double_t kXcorner[24] =
    {
      74.8833,  53.0045, 31.1255,    //Type-A
      74.8833,  53.0045, 31.1255,    //Type-A
      -74.8833, -53.0044, -31.1255,  //Type-AR
      -74.8833, -53.0044, -31.1255,  //Type-AR
      8.9165, -33.7471,            //Type-B
      8.9165, -33.7471,            //Type-B
      8.9165, -33.7471,            //Type-B
      -8.9165, 33.7471,            //Type-BR
      -8.9165, 33.7471,            //Type-BR
      -8.9165, 33.7471,            //Type-BR
    };

  const Double_t kYcorner[24] =
    {
      86.225,  86.225,  86.225,      //Type-A
      37.075,  37.075,  37.075,      //Type-A
      -86.225, -86.225, -86.225,     //Type-AR
      -37.075, -37.075, -37.075,     //Type-AR
      86.225,  86.225,               //Type-B
      61.075,  61.075,               //Type-B
      35.925,  35.925,               //Type-B
      -86.225, -86.225,              //Type-BR
      -61.075, -61.075,              //Type-BR
      -35.925, -35.925               //Type-BR
    };

  //  const Float_t kSqroot3      = 1.732050808;  // sqrt(3.);
  //  const Float_t kCellRadius   = 0.25;

  //
  //Every even row of cells is shifted and placed
  //in geant so this condition
  //
  Float_t shift = 0.0;
  if(ypad%2 == 0)
    {
      shift = 0.0;
    }
  else
    {
      shift = 0.25;
    }

  if(ism < 6)
    {
      ypos = kYcorner[ism] - (Float_t) xpad*fgkRad*2.0 - shift;
      xpos = kXcorner[ism] - (Float_t) ypad*fgkSqRoot3*fgkRad;
    }
  else if(ism >=6 && ism < 12)
    {
      ypos = kYcorner[ism] + (Float_t) xpad*fgkRad*2.0 + shift;
      xpos = kXcorner[ism] + (Float_t) ypad*fgkSqRoot3*fgkRad;
    }
  else if(ism >= 12 && ism < 18)
    {
      ypos = kYcorner[ism] - (Float_t) xpad*fgkRad*2.0 - shift;
      xpos = kXcorner[ism] - (Float_t) ypad*fgkSqRoot3*fgkRad;
    }
  else if(ism >= 18 && ism < 24)
    {
      ypos = kYcorner[ism] + (Float_t) xpad*fgkRad*2.0 + shift;
      xpos = kXcorner[ism] + (Float_t) ypad*fgkSqRoot3*fgkRad;
    }

}
// -------------------------------------------------------------------- //
void PMDModule::GenerateBox(Int_t ism, Float_t &xism, Float_t &yism,
			    Float_t &dxism, Float_t &dyism)
{
  const Float_t kDia     = 0.50;

  const Double_t kXcorner[24] =
    {
      74.8833,  53.0045, 31.1255,    //Type-A
      74.8833,  53.0045, 31.1255,    //Type-A
      -74.8833, -53.0044, -31.1255,  //Type-AR
      -74.8833, -53.0044, -31.1255,  //Type-AR
      8.9165, -33.7471,            //Type-B
      8.9165, -33.7471,            //Type-B
      8.9165, -33.7471,            //Type-B
      -8.9165, 33.7471,            //Type-BR
      -8.9165, 33.7471,            //Type-BR
      -8.9165, 33.7471,            //Type-BR
    };

  const Double_t kYcorner[24] =
    {
      86.225,  86.225,  86.225,      //Type-A
      37.075,  37.075,  37.075,      //Type-A
      -86.225, -86.225, -86.225,     //Type-AR
      -37.075, -37.075, -37.075,     //Type-AR
      86.225,  86.225,               //Type-B
      61.075,  61.075,               //Type-B
      35.925,  35.925,               //Type-B
      -86.225, -86.225,              //Type-BR
      -61.075, -61.075,              //Type-BR
      -35.925, -35.925               //Type-BR
    };

  if (ism > 23) ism -= 24;

  if (ism < 6)
    {
      xism  = kXcorner[ism] + fgkRad;
      yism  = kYcorner[ism] + fgkRad;
      dxism = -fgkRad*fgkSqRoot3*48.;
      dyism = -kDia*96. - fgkRad;
  }
  if (ism >= 6 && ism < 12)
    {
      xism  = kXcorner[ism] - fgkRad;
      yism  = kYcorner[ism] - fgkRad;
      dxism = fgkRad*fgkSqRoot3*48.;
      dyism = kDia*96. + fgkRad;
  }
  if (ism >= 12 && ism < 18)
    {
      xism  = kXcorner[ism] + fgkRad;
      yism  = kYcorner[ism] + fgkRad;
      dxism = -fgkRad*fgkSqRoot3*96.;
      dyism = -kDia*48. - fgkRad;
  }
  if (ism >= 18 && ism < 24)
    {
      xism  = kXcorner[ism] - fgkRad;
      yism  = kYcorner[ism] - fgkRad;
      dxism = fgkRad*fgkSqRoot3*96.;
      dyism = kDia*48. + fgkRad;
  }

}

// -------------------------------------------------------------------- //

void PMDModule::SetPosition(Float_t x, Float_t y, Float_t z)
{
  fX = x;
  fY = y;
  fZ = z;
}

// -------------------------------------------------------------------- //
<commit_msg>Include needed by Root v5-15-02<commit_after>// $Header$

#include "PMDModule.h"

#include "AliPMDdigit.h"
#include "AliPMDddldata.h"

#include <TClonesArray.h>

using namespace Reve;
using namespace Alieve;

const Float_t PMDModule::fgkRad     = 0.25;
const Float_t PMDModule::fgkSqRoot3 = 1.732050808;
const Float_t PMDModule::fgkZpos    = 0.;
//______________________________________________________________________
// PMDModule
//

ClassImp(PMDModule)

PMDModule::PMDModule():
  fX(0.),
  fY(0.),
  fZ(0.),
  fNPads(0)
{

}
// -------------------------------------------------------------------- //
void PMDModule::DisplayInit(Int_t ism)
{
  TString smodule = "Module";
  smodule+= ism;

  Float_t xism =0, yism = 0;
  Float_t dxism =0, dyism = 0;

  GenerateBox(ism,xism,yism,dxism,dyism);

  Reve::FrameBox *pmdModBox = new FrameBox();
  pmdModBox->SetAAQuadXY(xism, yism, 0, dxism, dyism);
  pmdModBox->SetFrameColor((Color_t) 31);

  Reve::RGBAPalette *pmdModPalette  = new RGBAPalette(20, 1000);
  pmdModPalette->SetLimits(0, 1000);

  //  Reve::QuadSet* q = this;
  SetName(smodule.Data());
  SetOwnIds(kTRUE);
  Reset(Reve::QuadSet::QT_HexagonXY, kFALSE, 32);

  SetFrame(pmdModBox);
  SetPalette(pmdModPalette);

}
// -------------------------------------------------------------------- //
void PMDModule::DisplayDigitsData(Int_t ism, TTree *pmdt)
{

  DisplayInit(ism);

  Int_t det, smn, irow, icol, adc;
  Int_t xpad = 0, ypad = 0;
  Float_t xpos, ypos;

  TClonesArray *digits = new TClonesArray("AliPMDdigit", 0);

  TBranch *branch = pmdt->GetBranch("PMDDigit");
  branch->SetAddress(&digits);

  AliPMDdigit  *pmddigit;

  branch->GetEntry(ism);
  Int_t nentries = digits->GetLast();
  //printf("%d\n", nentries);

  for (Int_t ient = 0; ient < nentries+1; ient++)
    {
      pmddigit = (AliPMDdigit*)digits->UncheckedAt(ient);

      det    = pmddigit->GetDetector();
      smn    = pmddigit->GetSMNumber();
      irow   = pmddigit->GetRow();
      icol   = pmddigit->GetColumn();
      adc    = (Int_t) pmddigit->GetADC();

      if(smn <12)
	{
	  xpad = icol;
	  ypad = irow;
	}
      else if(smn >=12 && smn < 24)
	{
	  xpad = irow;
	  ypad = icol;
	}

      RectGeomCellPos(smn, xpad, ypad, xpos, ypos);

      AddHexagon(xpos, ypos, fgkZpos, fgkRad);

      QuadValue(adc);

      QuadId(new AliPMDdigit(*pmddigit));
      // new TNamed(Form("Quad with idx=%d", ient),
      //  "This title is not confusing."));

      ++fNPads;
    }

  RefitPlex();

  fHMTrans.SetPos(fX, fY, fZ);

  delete digits;
}
// -------------------------------------------------------------------- //

void PMDModule::DisplayRawData(Int_t ism, TObjArray *ddlcont)
{

  if (ism > 23) ism -= 24;

  DisplayInit(ism);

  Int_t det, smn, irow, icol, adc;
  Int_t xpad = 0, ypad = 0;
  Float_t xpos, ypos;

  Int_t nentries = ddlcont->GetEntries();
  //printf("%d\n", nentries);

  for (Int_t ient = 0; ient < nentries; ient++)
    {
      AliPMDddldata *pmdddl = (AliPMDddldata*)ddlcont->UncheckedAt(ient);

      det    = pmdddl->GetDetector();
      smn    = pmdddl->GetSMN();
      if (smn != ism) continue;
      irow   = pmdddl->GetRow();
      icol   = pmdddl->GetColumn();
      adc    = pmdddl->GetSignal();

      if(smn <12)
	{
	  xpad = icol;
	  ypad = irow;
	}
      else if(smn >=12 && smn < 24)
	{
	  xpad = irow;
	  ypad = icol;
	}

      RectGeomCellPos(smn, xpad, ypad, xpos, ypos);

      AddHexagon(xpos, ypos, fgkZpos, fgkRad);

      QuadValue(adc);

      QuadId(new AliPMDddldata(*pmdddl));
      //new TNamed(Form("Quad with idx=%d", ient),
      //  "This title is not confusing."));

      ++fNPads;
    }

  RefitPlex();

  fHMTrans.SetPos(fX, fY, fZ);

}
// -------------------------------------------------------------------- //

void PMDModule::RectGeomCellPos(Int_t ism, Int_t xpad, Int_t ypad,
				Float_t &xpos, Float_t &ypos)
{
  // This routine finds the cell eta,phi for the new PMD rectangular
  // geometry in ALICE
  // Authors : Bedanga Mohanty and Dipak Mishra - 29.4.2003
  // modified by B. K. Nandi for change of coordinate sys
  //
  // SMA  ---> Supermodule Type A           ( SM - 0)
  // SMAR ---> Supermodule Type A ROTATED   ( SM - 1)
  // SMB  ---> Supermodule Type B           ( SM - 2)
  // SMBR ---> Supermodule Type B ROTATED   ( SM - 3)
  //
  // ism   : Serial module number from 0 to 23 for each plane

  // Corner positions (x,y) of the 24 unit moudles in ALICE PMD

  const Double_t kXcorner[24] =
    {
      74.8833,  53.0045, 31.1255,    //Type-A
      74.8833,  53.0045, 31.1255,    //Type-A
      -74.8833, -53.0044, -31.1255,  //Type-AR
      -74.8833, -53.0044, -31.1255,  //Type-AR
      8.9165, -33.7471,            //Type-B
      8.9165, -33.7471,            //Type-B
      8.9165, -33.7471,            //Type-B
      -8.9165, 33.7471,            //Type-BR
      -8.9165, 33.7471,            //Type-BR
      -8.9165, 33.7471,            //Type-BR
    };

  const Double_t kYcorner[24] =
    {
      86.225,  86.225,  86.225,      //Type-A
      37.075,  37.075,  37.075,      //Type-A
      -86.225, -86.225, -86.225,     //Type-AR
      -37.075, -37.075, -37.075,     //Type-AR
      86.225,  86.225,               //Type-B
      61.075,  61.075,               //Type-B
      35.925,  35.925,               //Type-B
      -86.225, -86.225,              //Type-BR
      -61.075, -61.075,              //Type-BR
      -35.925, -35.925               //Type-BR
    };

  //  const Float_t kSqroot3      = 1.732050808;  // sqrt(3.);
  //  const Float_t kCellRadius   = 0.25;

  //
  //Every even row of cells is shifted and placed
  //in geant so this condition
  //
  Float_t shift = 0.0;
  if(ypad%2 == 0)
    {
      shift = 0.0;
    }
  else
    {
      shift = 0.25;
    }

  if(ism < 6)
    {
      ypos = kYcorner[ism] - (Float_t) xpad*fgkRad*2.0 - shift;
      xpos = kXcorner[ism] - (Float_t) ypad*fgkSqRoot3*fgkRad;
    }
  else if(ism >=6 && ism < 12)
    {
      ypos = kYcorner[ism] + (Float_t) xpad*fgkRad*2.0 + shift;
      xpos = kXcorner[ism] + (Float_t) ypad*fgkSqRoot3*fgkRad;
    }
  else if(ism >= 12 && ism < 18)
    {
      ypos = kYcorner[ism] - (Float_t) xpad*fgkRad*2.0 - shift;
      xpos = kXcorner[ism] - (Float_t) ypad*fgkSqRoot3*fgkRad;
    }
  else if(ism >= 18 && ism < 24)
    {
      ypos = kYcorner[ism] + (Float_t) xpad*fgkRad*2.0 + shift;
      xpos = kXcorner[ism] + (Float_t) ypad*fgkSqRoot3*fgkRad;
    }

}
// -------------------------------------------------------------------- //
void PMDModule::GenerateBox(Int_t ism, Float_t &xism, Float_t &yism,
			    Float_t &dxism, Float_t &dyism)
{
  const Float_t kDia     = 0.50;

  const Double_t kXcorner[24] =
    {
      74.8833,  53.0045, 31.1255,    //Type-A
      74.8833,  53.0045, 31.1255,    //Type-A
      -74.8833, -53.0044, -31.1255,  //Type-AR
      -74.8833, -53.0044, -31.1255,  //Type-AR
      8.9165, -33.7471,            //Type-B
      8.9165, -33.7471,            //Type-B
      8.9165, -33.7471,            //Type-B
      -8.9165, 33.7471,            //Type-BR
      -8.9165, 33.7471,            //Type-BR
      -8.9165, 33.7471,            //Type-BR
    };

  const Double_t kYcorner[24] =
    {
      86.225,  86.225,  86.225,      //Type-A
      37.075,  37.075,  37.075,      //Type-A
      -86.225, -86.225, -86.225,     //Type-AR
      -37.075, -37.075, -37.075,     //Type-AR
      86.225,  86.225,               //Type-B
      61.075,  61.075,               //Type-B
      35.925,  35.925,               //Type-B
      -86.225, -86.225,              //Type-BR
      -61.075, -61.075,              //Type-BR
      -35.925, -35.925               //Type-BR
    };

  if (ism > 23) ism -= 24;

  if (ism < 6)
    {
      xism  = kXcorner[ism] + fgkRad;
      yism  = kYcorner[ism] + fgkRad;
      dxism = -fgkRad*fgkSqRoot3*48.;
      dyism = -kDia*96. - fgkRad;
  }
  if (ism >= 6 && ism < 12)
    {
      xism  = kXcorner[ism] - fgkRad;
      yism  = kYcorner[ism] - fgkRad;
      dxism = fgkRad*fgkSqRoot3*48.;
      dyism = kDia*96. + fgkRad;
  }
  if (ism >= 12 && ism < 18)
    {
      xism  = kXcorner[ism] + fgkRad;
      yism  = kYcorner[ism] + fgkRad;
      dxism = -fgkRad*fgkSqRoot3*96.;
      dyism = -kDia*48. - fgkRad;
  }
  if (ism >= 18 && ism < 24)
    {
      xism  = kXcorner[ism] - fgkRad;
      yism  = kYcorner[ism] - fgkRad;
      dxism = fgkRad*fgkSqRoot3*96.;
      dyism = kDia*48. + fgkRad;
  }

}

// -------------------------------------------------------------------- //

void PMDModule::SetPosition(Float_t x, Float_t y, Float_t z)
{
  fX = x;
  fY = y;
  fZ = z;
}

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


<commit_before><commit_msg>Added logic for multiple cones<commit_after><|endoftext|>


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

#include "sample.h"
#include "proxyImpl.h"

#include "w3c/html5.h"

#include <math.h>

namespace
{

void drawCharts(es::HTMLDocument* document)
{
    std::string title = document->getTitle();
    printf("title = %s\n", title.c_str());

    es::Element* element = document->createElement("div");
    if (element)
    {
        if (es::Node* node = document->createTextNode("hello, world."))
        {
            element->appendChild(node);
            node->release();
        }
        if (es::HTMLElement* body = document->getBody())
        {
            body->appendChild(element);
            body->release();
        }
        element->release();
    }

    es::HTMLCanvasElement* canvas = dynamic_cast<es::HTMLCanvasElement*>(document->getElementById("canvas"));
    if (!canvas)
    {
        return;
    }

    es::CanvasRenderingContext2D* context = dynamic_cast<es::CanvasRenderingContext2D*>(canvas->getContext("2d"));
    if (!context)
    {
        canvas->release();
        return;
    }

    context->setFillStyle("white");
    context->fillRect(0, 0, 1024, 768);

    // Bar graph
    float top = 50.0f;
    float bottom = 250.0f;

    float width = 20.0f;
    float height;
    float x;
    float y;

    context->setStrokeStyle("rgb(0, 0, 0)");

    height = 100.0f;
    x = 100.0f;
    context->setLineWidth(3);
    context->setFillStyle("rgb(255, 0, 0)");

    context->fillRect(x, bottom - height, width, height);

    x += 50.0f;
    height = 200.0f;
    context->setFillStyle("rgb(0, 255, 0)");
    context->fillRect(x, bottom - height, width, height);

    x += 50.0f;
    height = 80.0f;
    context->setFillStyle("rgb(0, 0, 255)");
    context->fillRect(x, bottom - height, width, height);

    x += 50.0f;
    height = 50.0f;
    context->setFillStyle("rgb(255, 255, 0)");
    context->fillRect(x, bottom - height, width, height);

    x += 50.0f;
    height = 30.0f;
    context->setFillStyle("rgb(0, 255, 255)");
    context->fillRect(x, bottom - height, width, height);

    context->moveTo(80.0f, top);
    context->lineTo(80.0f, bottom);
    context->lineTo(350.0f, bottom);
    context->setLineWidth(4);
    context->stroke();

    // Circle graph
    float r = 100.0f;  // radius
    float cx = 180.0f; // center
    float cy = 450.0f; // center
    // angle
    float s = 270.0f/180.0f;
    float e = 120.0f/180.0f;

    context->setFillStyle("rgb(255, 0, 0)");
    context->beginPath();
    context->arc(cx, cy, r, M_PI * s, M_PI * e, 0);
    context->lineTo(cx, cy);
    context->closePath();
    context->fill();

    s = e;
    e = 240.0f/180.0f;
    context->setFillStyle("rgb(0, 255, 0)");
    context->beginPath();
    context->arc(cx, cy, r, M_PI * s, M_PI * e, 0);
    context->lineTo(cx, cy);
    context->closePath();
    context->fill();

    s = e;
    e = 260.0f/180.0f;
    context->setFillStyle("rgb(0, 0, 255)");
    context->beginPath();
    context->arc(cx, cy, r, M_PI * s, M_PI * e, 0);
    context->lineTo(cx, cy);
    context->closePath();
    context->fill();

    s = e;
    e = 270.0f/180.0f;
    context->setFillStyle("rgb(255, 255, 0)");
    context->beginPath();
    context->arc(cx, cy, r, M_PI * s, M_PI * e, 0);
    context->lineTo(cx, cy);
    context->closePath();
    context->fill();

    context->release();
    canvas->release();
}

}  // namespace

void PluginInstance::test()
{
    NPVariant document;
    VOID_TO_NPVARIANT(document);
    NPN_GetProperty(npp, window, NPN_GetStringIdentifier("document"), &document);
    if (NPVARIANT_IS_OBJECT(document))
    {
        std::string interfaceName = getInterfaceName(npp, NPVARIANT_TO_OBJECT(document));
        printf("'%s'\n", interfaceName.c_str());
        drawCharts(static_cast<es::HTMLDocument*>(createProxy(npp, NPVARIANT_TO_OBJECT(document))));
    }
    NPN_ReleaseVariantValue(&document);
}<commit_msg>Clean up.<commit_after>/*
 * Copyright 2008, 2009 Google Inc.
 * Copyright 2006, 2007 Nintendo Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "sample.h"
#include "proxyImpl.h"

#include "w3c/html5.h"

#include <math.h>

namespace
{

void drawCharts(es::HTMLDocument* document)
{
    std::string title = document->getTitle();
    printf("title = %s\n", title.c_str());

    es::Element* element = document->createElement("div");
    if (element)
    {
        if (es::Node* node = document->createTextNode("hello, world."))
        {
            element->appendChild(node);
            node->release();
        }
        if (es::HTMLElement* body = document->getBody())
        {
            body->appendChild(element);
            body->release();
        }
        element->release();
    }

    es::HTMLCanvasElement* canvas = dynamic_cast<es::HTMLCanvasElement*>(document->getElementById("canvas"));
    if (!canvas)
    {
        return;
    }

    es::CanvasRenderingContext2D* context = dynamic_cast<es::CanvasRenderingContext2D*>(canvas->getContext("2d"));
    if (!context)
    {
        canvas->release();
        return;
    }

    context->setFillStyle("white");
    context->fillRect(0, 0, 1024, 768);

    // Bar graph
    float top = 50.0f;
    float bottom = 250.0f;

    float width = 20.0f;
    float height;
    float x;
    float y;

    context->setStrokeStyle("rgb(0, 0, 0)");

    height = 100.0f;
    x = 100.0f;
    context->setLineWidth(3);
    context->setFillStyle("rgb(255, 0, 0)");

    context->fillRect(x, bottom - height, width, height);

    x += 50.0f;
    height = 200.0f;
    context->setFillStyle("rgb(0, 255, 0)");
    context->fillRect(x, bottom - height, width, height);

    x += 50.0f;
    height = 80.0f;
    context->setFillStyle("rgb(0, 0, 255)");
    context->fillRect(x, bottom - height, width, height);

    x += 50.0f;
    height = 50.0f;
    context->setFillStyle("rgb(255, 255, 0)");
    context->fillRect(x, bottom - height, width, height);

    x += 50.0f;
    height = 30.0f;
    context->setFillStyle("rgb(0, 255, 255)");
    context->fillRect(x, bottom - height, width, height);

    context->moveTo(80.0f, top);
    context->lineTo(80.0f, bottom);
    context->lineTo(350.0f, bottom);
    context->setLineWidth(4);
    context->stroke();

    // Circle graph
    float r = 100.0f;  // radius
    float cx = 180.0f; // center
    float cy = 450.0f; // center
    // angle
    float s = 270.0f/180.0f;
    float e = 120.0f/180.0f;

    context->setFillStyle("rgb(255, 0, 0)");
    context->beginPath();
    context->arc(cx, cy, r, M_PI * s, M_PI * e, 0);
    context->lineTo(cx, cy);
    context->closePath();
    context->fill();

    s = e;
    e = 240.0f/180.0f;
    context->setFillStyle("rgb(0, 255, 0)");
    context->beginPath();
    context->arc(cx, cy, r, M_PI * s, M_PI * e, 0);
    context->lineTo(cx, cy);
    context->closePath();
    context->fill();

    s = e;
    e = 260.0f/180.0f;
    context->setFillStyle("rgb(0, 0, 255)");
    context->beginPath();
    context->arc(cx, cy, r, M_PI * s, M_PI * e, 0);
    context->lineTo(cx, cy);
    context->closePath();
    context->fill();

    s = e;
    e = 270.0f/180.0f;
    context->setFillStyle("rgb(255, 255, 0)");
    context->beginPath();
    context->arc(cx, cy, r, M_PI * s, M_PI * e, 0);
    context->lineTo(cx, cy);
    context->closePath();
    context->fill();

    context->release();
    canvas->release();
}

}  // namespace

void PluginInstance::test()
{
    NPVariant document;
    VOID_TO_NPVARIANT(document);
    NPN_GetProperty(npp, window, NPN_GetStringIdentifier("document"), &document);
    if (NPVARIANT_IS_OBJECT(document))
    {
        std::string interfaceName = getInterfaceName(npp, NPVARIANT_TO_OBJECT(document));
        printf("'%s'\n", interfaceName.c_str());
        drawCharts(static_cast<es::HTMLDocument*>(createProxy(npp, NPVARIANT_TO_OBJECT(document))));
    }
    NPN_ReleaseVariantValue(&document);
}
<|endoftext|>


<commit_before>#ifndef CTHREADQUEUE
#define CTHREADQUEUE
#include<condition_variable>
#include<cstddef>
#include<queue>
#include<mutex>
#include<utility>	//forward, move

namespace nThread
{
	template<class T>
	class CThreadQueue	//a thread-safe std::queue
	{
	public:
		typedef typename std::queue<T>::size_type size_type;
		typedef T value_type;
	private:
		std::condition_variable push_;
		std::mutex pushMut_;
		std::queue<value_type> queue_;
	public:
		template<class ... Args>
		void emplace(Args &&...args)
		{
			std::lock_guard<std::mutex> lock{pushMut_};
			queue_.emplace(std::forward<Args>(args)...);
			if(1==size())
				push_.notify_all();
		}
		inline size_type size() const noexcept
		{
			return queue_.size();
		}
		value_type wait_and_pop()
		{
			std::unique_lock<std::mutex> lock{pushMut_};
			push_.wait(lock,[this]{return size();});
			const auto temp{std::move(queue_.front())};
			queue_.pop();
			lock.unlock();
			return temp;
		}
	};
}

#endif<commit_msg>add init_emplace<commit_after>#ifndef CTHREADQUEUE
#define CTHREADQUEUE
#include<condition_variable>
#include<cstddef>
#include<queue>
#include<mutex>
#include<utility>	//forward, move

namespace nThread
{
	template<class T>
	class CThreadQueue	//a thread-safe std::queue
	{
	public:
		typedef typename std::queue<T>::size_type size_type;
		typedef T value_type;
	private:
		std::condition_variable push_;
		std::mutex pushMut_;
		std::queue<value_type> queue_;
	public:
		template<class ... Args>
		void emplace(Args &&...args)
		{
			std::lock_guard<std::mutex> lock{pushMut_};
			queue_.emplace(std::forward<Args>(args)...);
			if(1==size())
				push_.notify_all();
		}
		template<class ... Args>
		inline void init_emplace(Args &&...args)
		{
			queue_.emplace(std::forward<Args>(args)...);
		}
		inline size_type size() const noexcept
		{
			return queue_.size();
		}
		value_type wait_and_pop()
		{
			std::unique_lock<std::mutex> lock{pushMut_};
			push_.wait(lock,[this]{return size();});
			const auto temp{std::move(queue_.front())};
			queue_.pop();
			lock.unlock();
			return temp;
		}
	};
}

#endif<|endoftext|>


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

#include <pcl/outofcore/outofcore_node_data.h>

#include <pcl/console/print.h>

#include <iostream>
#include <fstream>
#include <sstream>

namespace pcl
{
  namespace outofcore
  {

    OutofcoreOctreeNodeMetadata::OutofcoreOctreeNodeMetadata ()
      : min_bb_ (),
        max_bb_ (),
        binary_point_filename_ (),
        midpoint_xyz_ (),
        directory_ (),
        metadata_filename_ ()
    {
    }

////////////////////////////////////////////////////////////////////////////////

    OutofcoreOctreeNodeMetadata::~OutofcoreOctreeNodeMetadata ()
    {
    }

////////////////////////////////////////////////////////////////////////////////

    Eigen::Vector3d
    OutofcoreOctreeNodeMetadata::getBoundingBoxMin () const
    {
      return (min_bb_);
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::setBoundingBoxMin (const Eigen::Vector3d min_bb)
    {
      min_bb_ = min_bb;
      this->updateVoxelCenter ();
    }

////////////////////////////////////////////////////////////////////////////////

    Eigen::Vector3d
    OutofcoreOctreeNodeMetadata::getBoundingBoxMax () const
    {
      return (max_bb_);
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::setBoundingBoxMax (const Eigen::Vector3d max_bb)
    {
      max_bb_ = max_bb;
      this->updateVoxelCenter ();
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::getBoundingBox (Eigen::Vector3d &min_bb, Eigen::Vector3d &max_bb) const
    {
      min_bb = min_bb_;
      max_bb = max_bb_;
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::setBoundingBox (const Eigen::Vector3d min_bb, const Eigen::Vector3d max_bb)
    {
      min_bb_ = min_bb;
      max_bb_ = max_bb;
      this->updateVoxelCenter ();
    }

////////////////////////////////////////////////////////////////////////////////

    boost::filesystem::path
    OutofcoreOctreeNodeMetadata::getDirectoryPathname () const
    {
      return (directory_);
    }

////////////////////////////////////////////////////////////////////////////////
    void
    OutofcoreOctreeNodeMetadata::setDirectoryPathname (const boost::filesystem::path directory_pathname)
    {
      directory_ = directory_pathname;
    }

////////////////////////////////////////////////////////////////////////////////

    boost::filesystem::path
    OutofcoreOctreeNodeMetadata::getPCDFilename () const
    {
      return (binary_point_filename_);
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::setPCDFilename (const boost::filesystem::path point_filename)
    {
      binary_point_filename_ = point_filename;
    }

////////////////////////////////////////////////////////////////////////////////

    int
    OutofcoreOctreeNodeMetadata::getOutofcoreVersion () const
    {
      return (outofcore_version_);
    }

////////////////////////////////////////////////////////////////////////////////

    void OutofcoreOctreeNodeMetadata::setOutofcoreVersion (const int version)
    {
      outofcore_version_ = version;
    }

////////////////////////////////////////////////////////////////////////////////

    boost::filesystem::path OutofcoreOctreeNodeMetadata::getMetadataFilename () const
    {
      return (metadata_filename_);
    }

////////////////////////////////////////////////////////////////////////////////

    void OutofcoreOctreeNodeMetadata::setMetadataFilename (const boost::filesystem::path path_to_metadata)
    {
      directory_ = path_to_metadata.parent_path ();
      metadata_filename_ = path_to_metadata;
    }

////////////////////////////////////////////////////////////////////////////////

    Eigen::Vector3d OutofcoreOctreeNodeMetadata::getVoxelCenter () const
    {
      return (midpoint_xyz_);
    }

////////////////////////////////////////////////////////////////////////////////

    void OutofcoreOctreeNodeMetadata::serializeMetadataToDisk ()
    {
      boost::shared_ptr<cJSON> idx (cJSON_CreateObject (), cJSON_Delete);

      cJSON* cjson_outofcore_version = cJSON_CreateNumber (outofcore_version_);

      double min_array[3];
      double max_array[3];

      for(int i=0; i<3; i++)
      {
        min_array[i] = min_bb_[i];
        max_array[i] = max_bb_[i];
      }

      cJSON* cjson_bb_min = cJSON_CreateDoubleArray (min_array, 3);
      cJSON* cjson_bb_max = cJSON_CreateDoubleArray (max_array, 3);

      cJSON* cjson_bin_point_filename = cJSON_CreateString (static_cast<const char*>(binary_point_filename_.filename ().c_str ()));

      cJSON_AddItemToObject (idx.get (), "version", cjson_outofcore_version);
      cJSON_AddItemToObject (idx.get (), "bb_min", cjson_bb_min);
      cJSON_AddItemToObject (idx.get (), "bb_max", cjson_bb_max);
      cJSON_AddItemToObject (idx.get (), "bin", cjson_bin_point_filename);

      char* idx_txt = cJSON_Print (idx.get ());

      std::ofstream f (metadata_filename_.c_str (), std::ios::out | std::ios::trunc);
      f << idx_txt;
      f.close ();

      free (idx_txt);
    }

////////////////////////////////////////////////////////////////////////////////

    int OutofcoreOctreeNodeMetadata::loadMetadataFromDisk ()
    {
      if(directory_ != metadata_filename_.parent_path ())
      {
        PCL_ERROR ("directory_ is not set correctly\n");
      }

      //if the file to load doesn't exist, return failure
      if (!boost::filesystem::exists (metadata_filename_))
      {
        PCL_ERROR ("[pcl::outofcore::OutofcoreOctreeNodeMetadata] Can not find index metadata at %s.\n", metadata_filename_.c_str ());
        return (0);
      }
      else if(boost::filesystem::is_directory (metadata_filename_))
      {
        PCL_ERROR ("[pcl::outofcore::OutofcoreOctreeNodeMetadata] Got a directory, but no oct_idx metadata?\n");
        return (0);
      }

      //load CJSON
      std::vector<char> idx_input;
      boost::uintmax_t len = boost::filesystem::file_size (metadata_filename_);
      idx_input.resize (len + 1);

      std::ifstream f (metadata_filename_.c_str (), std::ios::in);
      f.read (&(idx_input.front ()), len);
      idx_input.back () = '\0';

      //Parse
      boost::shared_ptr<cJSON> idx (cJSON_Parse (&(idx_input.front ())), cJSON_Delete);

      cJSON* cjson_outofcore_version = cJSON_GetObjectItem (idx.get (), "version");
      cJSON* cjson_bb_min = cJSON_GetObjectItem (idx.get (), "bb_min");
      cJSON* cjson_bb_max = cJSON_GetObjectItem (idx.get (), "bb_max");
      cJSON* cjson_bin_point_filename = cJSON_GetObjectItem (idx.get (), "bin");

      for (int i = 0; i < 3; i++)
      {
        min_bb_[i] = cJSON_GetArrayItem (cjson_bb_min, i)->valuedouble;
        max_bb_[i] = cJSON_GetArrayItem (cjson_bb_max, i)->valuedouble;
      }
      outofcore_version_ = cjson_outofcore_version->valueint;

      binary_point_filename_= directory_ / cjson_bin_point_filename->valuestring;
      midpoint_xyz_ = (max_bb_+min_bb_)/static_cast<double>(2.0);

      //return success
      return (1);
    }

////////////////////////////////////////////////////////////////////////////////

    int OutofcoreOctreeNodeMetadata::loadMetadataFromDisk (const boost::filesystem::path path_to_metadata)
    {
      this->setMetadataFilename (path_to_metadata);
      this->setDirectoryPathname (path_to_metadata.parent_path ());
      return (this->loadMetadataFromDisk ());
    }

////////////////////////////////////////////////////////////////////////////////

    void OutofcoreOctreeNodeMetadata::updateVoxelCenter ()
    {
      midpoint_xyz_ = (this->max_bb_ + this->min_bb_)/static_cast<double>(2.0);
    }

////////////////////////////////////////////////////////////////////////////////
  }//namespace outofcore
}//namespace pcl

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

#include <pcl/outofcore/outofcore_node_data.h>

#include <pcl/console/print.h>

#include <iostream>
#include <fstream>
#include <sstream>

namespace pcl
{
  namespace outofcore
  {

    OutofcoreOctreeNodeMetadata::OutofcoreOctreeNodeMetadata ()
      : min_bb_ (),
        max_bb_ (),
        binary_point_filename_ (),
        midpoint_xyz_ (),
        directory_ (),
        metadata_filename_ ()
    {
    }

////////////////////////////////////////////////////////////////////////////////

    OutofcoreOctreeNodeMetadata::~OutofcoreOctreeNodeMetadata ()
    {
    }

////////////////////////////////////////////////////////////////////////////////

    Eigen::Vector3d
    OutofcoreOctreeNodeMetadata::getBoundingBoxMin () const
    {
      return (min_bb_);
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::setBoundingBoxMin (const Eigen::Vector3d min_bb)
    {
      min_bb_ = min_bb;
      this->updateVoxelCenter ();
    }

////////////////////////////////////////////////////////////////////////////////

    Eigen::Vector3d
    OutofcoreOctreeNodeMetadata::getBoundingBoxMax () const
    {
      return (max_bb_);
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::setBoundingBoxMax (const Eigen::Vector3d max_bb)
    {
      max_bb_ = max_bb;
      this->updateVoxelCenter ();
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::getBoundingBox (Eigen::Vector3d &min_bb, Eigen::Vector3d &max_bb) const
    {
      min_bb = min_bb_;
      max_bb = max_bb_;
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::setBoundingBox (const Eigen::Vector3d min_bb, const Eigen::Vector3d max_bb)
    {
      min_bb_ = min_bb;
      max_bb_ = max_bb;
      this->updateVoxelCenter ();
    }

////////////////////////////////////////////////////////////////////////////////

    boost::filesystem::path
    OutofcoreOctreeNodeMetadata::getDirectoryPathname () const
    {
      return (directory_);
    }

////////////////////////////////////////////////////////////////////////////////
    void
    OutofcoreOctreeNodeMetadata::setDirectoryPathname (const boost::filesystem::path directory_pathname)
    {
      directory_ = directory_pathname;
    }

////////////////////////////////////////////////////////////////////////////////

    boost::filesystem::path
    OutofcoreOctreeNodeMetadata::getPCDFilename () const
    {
      return (binary_point_filename_);
    }

////////////////////////////////////////////////////////////////////////////////

    void
    OutofcoreOctreeNodeMetadata::setPCDFilename (const boost::filesystem::path point_filename)
    {
      binary_point_filename_ = point_filename;
    }

////////////////////////////////////////////////////////////////////////////////

    int
    OutofcoreOctreeNodeMetadata::getOutofcoreVersion () const
    {
      return (outofcore_version_);
    }

////////////////////////////////////////////////////////////////////////////////

    void OutofcoreOctreeNodeMetadata::setOutofcoreVersion (const int version)
    {
      outofcore_version_ = version;
    }

////////////////////////////////////////////////////////////////////////////////

    boost::filesystem::path OutofcoreOctreeNodeMetadata::getMetadataFilename () const
    {
      return (metadata_filename_);
    }

////////////////////////////////////////////////////////////////////////////////

    void OutofcoreOctreeNodeMetadata::setMetadataFilename (const boost::filesystem::path path_to_metadata)
    {
      directory_ = path_to_metadata.parent_path ();
      metadata_filename_ = path_to_metadata;
    }

////////////////////////////////////////////////////////////////////////////////

    Eigen::Vector3d OutofcoreOctreeNodeMetadata::getVoxelCenter () const
    {
      return (midpoint_xyz_);
    }

////////////////////////////////////////////////////////////////////////////////

    void OutofcoreOctreeNodeMetadata::serializeMetadataToDisk ()
    {
      boost::shared_ptr<cJSON> idx (cJSON_CreateObject (), cJSON_Delete);

      cJSON* cjson_outofcore_version = cJSON_CreateNumber (outofcore_version_);

      double min_array[3];
      double max_array[3];

      for(int i=0; i<3; i++)
      {
        min_array[i] = min_bb_[i];
        max_array[i] = max_bb_[i];
      }

      cJSON* cjson_bb_min = cJSON_CreateDoubleArray (min_array, 3);
      cJSON* cjson_bb_max = cJSON_CreateDoubleArray (max_array, 3);

      std::string binary_point_filename_string = binary_point_filename_.filename ().generic_string ();
      cJSON* cjson_bin_point_filename = cJSON_CreateString (binary_point_filename_string.c_str ());

      cJSON_AddItemToObject (idx.get (), "version", cjson_outofcore_version);
      cJSON_AddItemToObject (idx.get (), "bb_min", cjson_bb_min);
      cJSON_AddItemToObject (idx.get (), "bb_max", cjson_bb_max);
      cJSON_AddItemToObject (idx.get (), "bin", cjson_bin_point_filename);

      char* idx_txt = cJSON_Print (idx.get ());

      std::ofstream f (metadata_filename_.c_str (), std::ios::out | std::ios::trunc);
      f << idx_txt;
      f.close ();

      free (idx_txt);
    }

////////////////////////////////////////////////////////////////////////////////

    int OutofcoreOctreeNodeMetadata::loadMetadataFromDisk ()
    {
      if(directory_ != metadata_filename_.parent_path ())
      {
        PCL_ERROR ("directory_ is not set correctly\n");
      }

      //if the file to load doesn't exist, return failure
      if (!boost::filesystem::exists (metadata_filename_))
      {
        PCL_ERROR ("[pcl::outofcore::OutofcoreOctreeNodeMetadata] Can not find index metadata at %s.\n", metadata_filename_.c_str ());
        return (0);
      }
      else if(boost::filesystem::is_directory (metadata_filename_))
      {
        PCL_ERROR ("[pcl::outofcore::OutofcoreOctreeNodeMetadata] Got a directory, but no oct_idx metadata?\n");
        return (0);
      }

      //load CJSON
      std::vector<char> idx_input;
      boost::uintmax_t len = boost::filesystem::file_size (metadata_filename_);
      idx_input.resize (len + 1);

      std::ifstream f (metadata_filename_.c_str (), std::ios::in);
      f.read (&(idx_input.front ()), len);
      idx_input.back () = '\0';

      //Parse
      boost::shared_ptr<cJSON> idx (cJSON_Parse (&(idx_input.front ())), cJSON_Delete);

      cJSON* cjson_outofcore_version = cJSON_GetObjectItem (idx.get (), "version");
      cJSON* cjson_bb_min = cJSON_GetObjectItem (idx.get (), "bb_min");
      cJSON* cjson_bb_max = cJSON_GetObjectItem (idx.get (), "bb_max");
      cJSON* cjson_bin_point_filename = cJSON_GetObjectItem (idx.get (), "bin");

      for (int i = 0; i < 3; i++)
      {
        min_bb_[i] = cJSON_GetArrayItem (cjson_bb_min, i)->valuedouble;
        max_bb_[i] = cJSON_GetArrayItem (cjson_bb_max, i)->valuedouble;
      }
      outofcore_version_ = cjson_outofcore_version->valueint;

      binary_point_filename_= directory_ / cjson_bin_point_filename->valuestring;
      midpoint_xyz_ = (max_bb_+min_bb_)/static_cast<double>(2.0);

      //return success
      return (1);
    }

////////////////////////////////////////////////////////////////////////////////

    int OutofcoreOctreeNodeMetadata::loadMetadataFromDisk (const boost::filesystem::path path_to_metadata)
    {
      this->setMetadataFilename (path_to_metadata);
      this->setDirectoryPathname (path_to_metadata.parent_path ());
      return (this->loadMetadataFromDisk ());
    }

////////////////////////////////////////////////////////////////////////////////

    void OutofcoreOctreeNodeMetadata::updateVoxelCenter ()
    {
      midpoint_xyz_ = (this->max_bb_ + this->min_bb_)/static_cast<double>(2.0);
    }

////////////////////////////////////////////////////////////////////////////////
  }//namespace outofcore
}//namespace pcl

<|endoftext|>


<commit_before>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 of the License,
or (at your option) any later version.

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

You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.

*/

#include "server/zone/managers/director/ScreenPlayObserver.h"
#include "DirectorManager.h"

int ScreenPlayObserverImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) {
	Lua* lua = DirectorManager::instance()->getLuaInstance();

	LuaFunction startScreenPlay(lua->getLuaState(), play, key, 1);
	startScreenPlay << observable;
	startScreenPlay << arg1;
	startScreenPlay << arg2;

	startScreenPlay.callFunction();

	if (lua_gettop(lua->getLuaState()) == 0) {
		Logger::console.error("ScreenPlayObserverImplementation::notifyObserverEvent didnt return a value from " + play + ":" + key);

		assert(0 && "no return value in  ScreenPlayObserverImplementation::notifyObserverEvent");

		return 1;
	}

	int ret = lua->getIntParameter(lua->getLuaState());

	//1 remove observer, 0 keep observer

	return ret;
}
<commit_msg>[fixed] stability issue<commit_after>/*
Copyright (C) 2007 <SWGEmu>
This File is part of Core3.
This program is free software; you can redistribute
it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation; either version 2 of the License,
or (at your option) any later version.

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

You should have received a copy of the GNU Lesser General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

Linking Engine3 statically or dynamically with other modules
is making a combined work based on Engine3.
Thus, the terms and conditions of the GNU Lesser General Public License
cover the whole combination.

In addition, as a special exception, the copyright holders of Engine3
give you permission to combine Engine3 program with free software
programs or libraries that are released under the GNU LGPL and with
code included in the standard release of Core3 under the GNU LGPL
license (or modified versions of such code, with unchanged license).
You may copy and distribute such a system following the terms of the
GNU LGPL for Engine3 and the licenses of the other code concerned,
provided that you include the source code of that other code when
and as the GNU LGPL requires distribution of source code.

Note that people who make modified versions of Engine3 are not obligated
to grant this special exception for their modified versions;
it is their choice whether to do so. The GNU Lesser General Public License
gives permission to release a modified version without this exception;
this exception also makes it possible to release a modified version
which carries forward this exception.

*/

#include "server/zone/managers/director/ScreenPlayObserver.h"
#include "DirectorManager.h"
#include "engine/lua/LuaPanicException.h"

int ScreenPlayObserverImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) {
	int ret = 1;

	try {
		Lua* lua = DirectorManager::instance()->getLuaInstance();

		LuaFunction startScreenPlay(lua->getLuaState(), play, key, 1);
		startScreenPlay << observable;
		startScreenPlay << arg1;
		startScreenPlay << arg2;

		startScreenPlay.callFunction();

		if (lua_gettop(lua->getLuaState()) == 0) {
			Logger::console.error("ScreenPlayObserverImplementation::notifyObserverEvent didnt return a value from " + play + ":" + key);

			assert(0 && "no return value in  ScreenPlayObserverImplementation::notifyObserverEvent");

			return 1;
		}

		ret = lua->getIntParameter(lua->getLuaState());

	} catch (LuaPanicException& panic) {
		Logger::console.error("Panic exception: " + panic.getMessage() + " while trying to run SceenPlayObserver: " + play + ":" + key);
	}

	//1 remove observer, 0 keep observer

	return ret;
}
<|endoftext|>


<commit_before>//******************************************************************************
// FILE : variable_scalar.cpp
//
// LAST MODIFIED : 26 November 2003
//
// DESCRIPTION :
//???DB.  Should be template?
//==============================================================================

#include <new>
#include <sstream>
#include <string>
#include <stdio.h>

//???DB.  Put in include?
const bool Assert_on=true;

template<class Assertion,class Exception>inline void Assert(
	Assertion assertion,Exception exception)
{
	if (Assert_on&&!(assertion)) throw exception;
}

#include "computed_variable/variable_scalar.hpp"

// module classes
// ==============

// class Variable_input_scalar_value
// ---------------------------------

class Variable_input_scalar_value : public Variable_input
//******************************************************************************
// LAST MODIFIED : 26 November 2003
//
// DESCRIPTION :
//==============================================================================
{
	friend class Variable_scalar;
	public:
		Variable_input_scalar_value(const Variable_scalar_handle& variable_scalar):
			variable_scalar(variable_scalar){};
		~Variable_input_scalar_value(){};
		Variable_size_type size()
		{
			return (1);
		};
		virtual bool operator==(const Variable_input& input)
		try
		{
			{
				const Variable_input_scalar_value& input_scalar_value=
					dynamic_cast<const Variable_input_scalar_value&>(input);

				return (variable_scalar==input_scalar_value.variable_scalar);
			}
			catch (std::bad_cast)
			{
				return (false);
			};
		};
	private:
		Variable_scalar_handle variable_scalar;
};

#if defined (USE_INTRUSIVE_SMART_POINTER)
typedef boost::intrusive_ptr<Variable_input_scalar_value>
	Variable_input_scalar_value_handle;
#elif defined (USE_SMART_POINTER)
typedef boost::shared_ptr<Variable_input_scalar_value>
	Variable_input_scalar_value_handle;
#else
typedef Variable_input_scalar_value * Variable_input_scalar_value_handle;
#endif

// global classes
// ==============

// class Variable_scalar
// ---------------------

Variable_scalar::Variable_scalar(const Scalar value):
	Variable(),value(value)
//******************************************************************************
// LAST MODIFIED : 7 October 2003
//
// DESCRIPTION :
// Constructor.
//==============================================================================
{
}

Variable_scalar::Variable_scalar(const Variable_scalar& variable_scalar):
	Variable(),value(variable_scalar.value)
//******************************************************************************
// LAST MODIFIED : 11 October 2003
//
// DESCRIPTION :
// Copy constructor.
//==============================================================================
{
}

Variable_scalar& Variable_scalar::operator=(
	const Variable_scalar& variable_scalar)
//******************************************************************************
// LAST MODIFIED : 2 October 2003
//
// DESCRIPTION :
// Assignment operator.
//==============================================================================
{
	this->value=variable_scalar.value;

	return (*this);
}

Variable_size_type Variable_scalar::size()
//******************************************************************************
// LAST MODIFIED : 24 October 2003
//
// DESCRIPTION :
// Destructor.
//==============================================================================
{
	return (1);
}

Vector *Variable_scalar::scalars()
//******************************************************************************
// LAST MODIFIED : 24 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	Vector *values_vector;

	if (values_vector=new Vector(1))
	{
		(*values_vector)[0]=value;
	}

	return (values_vector);
}

Variable_scalar::~Variable_scalar()
//******************************************************************************
// LAST MODIFIED : 7 September 2003
//
// DESCRIPTION :
// Destructor.
//==============================================================================
{
	// do nothing
}

Variable_input_handle Variable_scalar::input_value()
//******************************************************************************
// LAST MODIFIED : 11 October 2003
//
// DESCRIPTION :
// Returns the value input for a scalar.
//==============================================================================
{
	return (Variable_input_handle(new Variable_input_scalar_value(
		Variable_scalar_handle(this))));
}

Variable_handle Variable_scalar::evaluate_local()
//******************************************************************************
// LAST MODIFIED : 12 October 2003
//
// DESCRIPTION :
// Duplicate <this> so that <this> isn't changed by operations on the result.
//==============================================================================
{
	return (Variable_handle(new Variable_scalar(*this)));
}

void Variable_scalar::evaluate_derivative_local(Matrix& matrix,
	std::list<Variable_input_handle>& independent_variables)
//******************************************************************************
// LAST MODIFIED : 17 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	Variable_input_scalar_value_handle input_value_handle;

	// matrix is zero'd on entry
	if ((1==independent_variables.size())&&(input_value_handle=
#if defined (USE_SMART_POINTER)
		boost::dynamic_pointer_cast<Variable_input_scalar_value,Variable_input>(
		independent_variables.front())
#else /* defined (USE_SMART_POINTER) */
		dynamic_cast<Variable_input_scalar_value *>(independent_variables.front())
#endif /* defined (USE_SMART_POINTER) */
		)&&(input_value_handle->variable_scalar==Variable_handle(this)))
	{
		Assert((1==matrix.size1())&&(1==matrix.size2()),std::logic_error(
			"Variable_scalar::evaluate_derivative_local.  "
			"Incorrect matrix size"));
		matrix(0,0)=1;
	}
}

Variable_handle Variable_scalar::get_input_value_local(
	const Variable_input_handle& input)
//******************************************************************************
// LAST MODIFIED : 15 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	Variable_scalar_handle value_scalar;
	Variable_input_scalar_value_handle input_value_handle;

	if ((input_value_handle=
#if defined (USE_SMART_POINTER)
		boost::dynamic_pointer_cast<Variable_input_scalar_value,Variable_input>(
		input)
#else /* defined (USE_SMART_POINTER) */
		dynamic_cast<Variable_input_scalar_value *>(input)
#endif /* defined (USE_SMART_POINTER) */
		)&&(input_value_handle->variable_scalar==Variable_scalar_handle(this)))
	{
		value_scalar=Variable_scalar_handle(new Variable_scalar(*this));
	}
	else
	{
		value_scalar=Variable_scalar_handle((Variable_scalar *)0);
	}

	return (value_scalar);
}

int Variable_scalar::set_input_value_local(const Variable_input_handle& input,
	const Variable_handle& value)
//******************************************************************************
// LAST MODIFIED : 24 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	int return_code;
	Variable_input_scalar_value_handle input_value_handle;
	Vector *values_vector;

	return_code=0;
	if ((input_value_handle=
#if defined (USE_SMART_POINTER)
		boost::dynamic_pointer_cast<Variable_input_scalar_value,Variable_input>(
		input)
#else /* defined (USE_SMART_POINTER) */
		dynamic_cast<Variable_input_scalar_value *>(input)
#endif /* defined (USE_SMART_POINTER) */
		)&&(input_value_handle->variable_scalar==Variable_scalar_handle(this))&&
		(1==value->size())&&(values_vector=value->scalars()))
	{
		this->value=(*values_vector)[0];
		return_code=1;
		delete values_vector;
	}

	return (return_code);
}

string_handle Variable_scalar::get_string_representation_local()
//******************************************************************************
// LAST MODIFIED : 12 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	string_handle return_string;
	std::ostringstream out;

	if (return_string=new std::string)
	{
		out << value;
		*return_string=out.str();
	}

	return (return_string);
}
<commit_msg>typo<commit_after>//******************************************************************************
// FILE : variable_scalar.cpp
//
// LAST MODIFIED : 26 November 2003
//
// DESCRIPTION :
//???DB.  Should be template?
//==============================================================================

#include <new>
#include <sstream>
#include <string>
#include <stdio.h>

//???DB.  Put in include?
const bool Assert_on=true;

template<class Assertion,class Exception>inline void Assert(
	Assertion assertion,Exception exception)
{
	if (Assert_on&&!(assertion)) throw exception;
}

#include "computed_variable/variable_scalar.hpp"

// module classes
// ==============

// class Variable_input_scalar_value
// ---------------------------------

class Variable_input_scalar_value : public Variable_input
//******************************************************************************
// LAST MODIFIED : 26 November 2003
//
// DESCRIPTION :
//==============================================================================
{
	friend class Variable_scalar;
	public:
		Variable_input_scalar_value(const Variable_scalar_handle& variable_scalar):
			variable_scalar(variable_scalar){};
		~Variable_input_scalar_value(){};
		Variable_size_type size()
		{
			return (1);
		};
		virtual bool operator==(const Variable_input& input)
		{
			try
			{
				{
					const Variable_input_scalar_value& input_scalar_value=
						dynamic_cast<const Variable_input_scalar_value&>(input);

					return (variable_scalar==input_scalar_value.variable_scalar);
				}
			}
			catch (std::bad_cast)
			{
				return (false);
			}
		};
	private:
		Variable_scalar_handle variable_scalar;
};

#if defined (USE_INTRUSIVE_SMART_POINTER)
typedef boost::intrusive_ptr<Variable_input_scalar_value>
	Variable_input_scalar_value_handle;
#elif defined (USE_SMART_POINTER)
typedef boost::shared_ptr<Variable_input_scalar_value>
	Variable_input_scalar_value_handle;
#else
typedef Variable_input_scalar_value * Variable_input_scalar_value_handle;
#endif

// global classes
// ==============

// class Variable_scalar
// ---------------------

Variable_scalar::Variable_scalar(const Scalar value):
	Variable(),value(value)
//******************************************************************************
// LAST MODIFIED : 7 October 2003
//
// DESCRIPTION :
// Constructor.
//==============================================================================
{
}

Variable_scalar::Variable_scalar(const Variable_scalar& variable_scalar):
	Variable(),value(variable_scalar.value)
//******************************************************************************
// LAST MODIFIED : 11 October 2003
//
// DESCRIPTION :
// Copy constructor.
//==============================================================================
{
}

Variable_scalar& Variable_scalar::operator=(
	const Variable_scalar& variable_scalar)
//******************************************************************************
// LAST MODIFIED : 2 October 2003
//
// DESCRIPTION :
// Assignment operator.
//==============================================================================
{
	this->value=variable_scalar.value;

	return (*this);
}

Variable_size_type Variable_scalar::size()
//******************************************************************************
// LAST MODIFIED : 24 October 2003
//
// DESCRIPTION :
// Destructor.
//==============================================================================
{
	return (1);
}

Vector *Variable_scalar::scalars()
//******************************************************************************
// LAST MODIFIED : 24 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	Vector *values_vector;

	if (values_vector=new Vector(1))
	{
		(*values_vector)[0]=value;
	}

	return (values_vector);
}

Variable_scalar::~Variable_scalar()
//******************************************************************************
// LAST MODIFIED : 7 September 2003
//
// DESCRIPTION :
// Destructor.
//==============================================================================
{
	// do nothing
}

Variable_input_handle Variable_scalar::input_value()
//******************************************************************************
// LAST MODIFIED : 11 October 2003
//
// DESCRIPTION :
// Returns the value input for a scalar.
//==============================================================================
{
	return (Variable_input_handle(new Variable_input_scalar_value(
		Variable_scalar_handle(this))));
}

Variable_handle Variable_scalar::evaluate_local()
//******************************************************************************
// LAST MODIFIED : 12 October 2003
//
// DESCRIPTION :
// Duplicate <this> so that <this> isn't changed by operations on the result.
//==============================================================================
{
	return (Variable_handle(new Variable_scalar(*this)));
}

void Variable_scalar::evaluate_derivative_local(Matrix& matrix,
	std::list<Variable_input_handle>& independent_variables)
//******************************************************************************
// LAST MODIFIED : 17 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	Variable_input_scalar_value_handle input_value_handle;

	// matrix is zero'd on entry
	if ((1==independent_variables.size())&&(input_value_handle=
#if defined (USE_SMART_POINTER)
		boost::dynamic_pointer_cast<Variable_input_scalar_value,Variable_input>(
		independent_variables.front())
#else /* defined (USE_SMART_POINTER) */
		dynamic_cast<Variable_input_scalar_value *>(independent_variables.front())
#endif /* defined (USE_SMART_POINTER) */
		)&&(input_value_handle->variable_scalar==Variable_handle(this)))
	{
		Assert((1==matrix.size1())&&(1==matrix.size2()),std::logic_error(
			"Variable_scalar::evaluate_derivative_local.  "
			"Incorrect matrix size"));
		matrix(0,0)=1;
	}
}

Variable_handle Variable_scalar::get_input_value_local(
	const Variable_input_handle& input)
//******************************************************************************
// LAST MODIFIED : 15 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	Variable_scalar_handle value_scalar;
	Variable_input_scalar_value_handle input_value_handle;

	if ((input_value_handle=
#if defined (USE_SMART_POINTER)
		boost::dynamic_pointer_cast<Variable_input_scalar_value,Variable_input>(
		input)
#else /* defined (USE_SMART_POINTER) */
		dynamic_cast<Variable_input_scalar_value *>(input)
#endif /* defined (USE_SMART_POINTER) */
		)&&(input_value_handle->variable_scalar==Variable_scalar_handle(this)))
	{
		value_scalar=Variable_scalar_handle(new Variable_scalar(*this));
	}
	else
	{
		value_scalar=Variable_scalar_handle((Variable_scalar *)0);
	}

	return (value_scalar);
}

int Variable_scalar::set_input_value_local(const Variable_input_handle& input,
	const Variable_handle& value)
//******************************************************************************
// LAST MODIFIED : 24 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	int return_code;
	Variable_input_scalar_value_handle input_value_handle;
	Vector *values_vector;

	return_code=0;
	if ((input_value_handle=
#if defined (USE_SMART_POINTER)
		boost::dynamic_pointer_cast<Variable_input_scalar_value,Variable_input>(
		input)
#else /* defined (USE_SMART_POINTER) */
		dynamic_cast<Variable_input_scalar_value *>(input)
#endif /* defined (USE_SMART_POINTER) */
		)&&(input_value_handle->variable_scalar==Variable_scalar_handle(this))&&
		(1==value->size())&&(values_vector=value->scalars()))
	{
		this->value=(*values_vector)[0];
		return_code=1;
		delete values_vector;
	}

	return (return_code);
}

string_handle Variable_scalar::get_string_representation_local()
//******************************************************************************
// LAST MODIFIED : 12 October 2003
//
// DESCRIPTION :
//==============================================================================
{
	string_handle return_string;
	std::ostringstream out;

	if (return_string=new std::string)
	{
		out << value;
		*return_string=out.str();
	}

	return (return_string);
}
<|endoftext|>


<commit_before>//=====================================================================//
/*!	@file
	@brief	R8C I2C メイン @n
			for DS1302 RTC
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "main.hpp"
#include <cstring>
#include "system.hpp"
#include "clock.hpp"
#include "common/command.hpp"
#include "common/format.hpp"

// 対象の RTC を有効にする
// #define DS1371
#define DS3231

static void wait_(uint16_t n)
{
	while(n > 0) {
		asm("nop");
		--n;
	}
}

static timer_b timer_b_;
static uart0 uart0_;
static utils::command<64> command_;
static i2c_io i2c_io_;
#ifdef DS1371
static ds1371 rtc_(i2c_io_);
#endif
#ifdef DS3231
static ds3231 rtc_(i2c_io_);
#endif

extern "C" {
	void sci_putch(char ch) {
		uart0_.putch(ch);
	}

	char sci_getch(void) {
		return uart0_.getch();
	}

	uint16_t sci_length() {
		return uart0_.length();
	}

	void sci_puts(const char* str) {
		uart0_.puts(str);
	}
}

extern "C" {
	const void* variable_vectors_[] __attribute__ ((section (".vvec"))) = {
		reinterpret_cast<void*>(brk_inst_),		nullptr,	// (0)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (1) flash_ready
		reinterpret_cast<void*>(null_task_),	nullptr,	// (2)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (3)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (4) コンパレーターB1
		reinterpret_cast<void*>(null_task_),	nullptr,	// (5) コンパレーターB3
		reinterpret_cast<void*>(null_task_),	nullptr,	// (6)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (7) タイマＲＣ

		reinterpret_cast<void*>(null_task_),	nullptr,	// (8)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (9)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (10)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (11)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (12)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (13) キー入力
		reinterpret_cast<void*>(null_task_),	nullptr,	// (14) A/D 変換
		reinterpret_cast<void*>(null_task_),	nullptr,	// (15)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (16)
		reinterpret_cast<void*>(uart0_.isend),	nullptr,	// (17) UART0 送信
		reinterpret_cast<void*>(uart0_.irecv),	nullptr,	// (18) UART0 受信
		reinterpret_cast<void*>(null_task_),	nullptr,	// (19)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (20)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (21) /INT2
		reinterpret_cast<void*>(null_task_),	nullptr,	// (22) タイマＲＪ２
		reinterpret_cast<void*>(null_task_),	nullptr,	// (23) 周期タイマ

		reinterpret_cast<void*>(timer_b_.itask),nullptr,	// (24) タイマＲＢ２
		reinterpret_cast<void*>(null_task_),	nullptr,	// (25) /INT1
		reinterpret_cast<void*>(null_task_),	nullptr,	// (26) /INT3
		reinterpret_cast<void*>(null_task_),	nullptr,	// (27)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (28)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (29) /INT0
		reinterpret_cast<void*>(null_task_),	nullptr,	// (30)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (31)
	};
}

static time_t get_time_() {
	time_t t = 0;
	if(!rtc_.get_time(t)) {
		sci_puts("Stall RTC read...\n");
	}
	return t;
}

static const char* wday_[] = {
	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};

static const char* mon_[] = {
	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

static void disp_time_(time_t t) {
	struct tm *m = gmtime(&t);

	utils::format("%s %s %d %02d:%02d:%02d  %4d\n")
		% wday_[m->tm_wday]
		% mon_[m->tm_mon]
		% static_cast<uint32_t>(m->tm_mday)
		% static_cast<uint32_t>(m->tm_hour)
		% static_cast<uint32_t>(m->tm_min)
		% static_cast<uint32_t>(m->tm_sec)
		% static_cast<uint32_t>(m->tm_year + 1900);
}

static bool check_key_word_(uint8_t idx, const char* key)
{
	char buff[12];
	if(command_.get_word(idx, sizeof(buff), buff)) {
		if(strcmp(buff, key) == 0) {
			return true;
		}
	}
	return false;
}

static const char* get_dec_(const char* p, char tmch, int& value) {
	int v = 0;
	char ch;
	while((ch = *p) != 0) {
		++p;
		if(ch == tmch) {
			break;
		} else if(ch >= '0' && ch <= '9') {
			v *= 10;
			v += ch - '0';
		} else {
			return nullptr;
		}
	}
	value = v;
	return p;
}

 __attribute__ ((section (".exttext")))
static void set_time_date_()
{
	time_t t = get_time_();
	if(t == 0) return;

	struct tm *m = gmtime(&t);
	bool err = false;
	if(command_.get_words() == 3) {
		char buff[12];
		if(command_.get_word(1, sizeof(buff), buff)) {
			const char* p = buff;
			int vs[3];
			uint8_t i;
			for(i = 0; i < 3; ++i) {
				p = get_dec_(p, '/', vs[i]);
				if(p == nullptr) {
					break;
				}
			}
			if(p != nullptr && p[0] == 0 && i == 3) {
				if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900;
				if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1;
				if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2];
			} else {
				err = true;
			}
		}

		if(command_.get_word(2, sizeof(buff), buff)) {
			const char* p = buff;
			int vs[3];
			uint8_t i;
			for(i = 0; i < 3; ++i) {
				p = get_dec_(p, ':', vs[i]);
				if(p == nullptr) {
					break;
				}
			}
			if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) {
				if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0];
				if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1];
				if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2];
				else m->tm_sec = 0;
			} else {
				err = true;
			}
		}
	}

	if(err) {
		sci_puts("Can't analize Time/Date input.\n");
		return;
	}

	time_t tt = mktime(m);
	if(!rtc_.set_time(tt)) {
		sci_puts("Stall RTC write...\n");
	}
}

 __attribute__ ((section (".exttext")))
int main(int argc, char *argv[])
{
	using namespace device;

// クロック関係レジスタ・プロテクト解除
	PRCR.PRC0 = 1;

// 高速オンチップオシレーターへ切り替え(20MHz)
// ※ F_CLK を設定する事（Makefile内）
	OCOCR.HOCOE = 1;
	wait_(1000);
	SCKCR.HSCKSEL = 1;
	CKSTPR.SCKSEL = 1;

	// タイマーＢ初期化
	{
		uint8_t ir_level = 2;
		timer_b_.start_timer(60, ir_level);
	}

	// UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in])
	// ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意！
	{
		utils::PORT_MAP(utils::port_map::P14::TXD0);
		utils::PORT_MAP(utils::port_map::P15::RXD0);
		uint8_t ir_level = 1;
		uart0_.start(19200, ir_level);
	}

	// I2C クラスの初期化
	{
		i2c_io_.init();
	}

	// DS1371 RTC を開始
	{
		rtc_.start();
	}

	sci_puts("Start R8C RTC monitor\n");
	command_.set_prompt("# ");

	// LED シグナル用ポートを出力
	PD1.B0 = 1;

	uint8_t cnt = 0;
	while(1) {
		timer_b_.sync();

		if(cnt >= 20) {
			cnt = 0;
		}
		if(cnt < 10) P1.B0 = 1;
		else P1.B0 = 0;
		++cnt;

		// コマンド入力と、コマンド解析
		if(command_.service()) {
			uint8_t cmdn = command_.get_words();
			if(cmdn >= 1) {
				if(check_key_word_(0, "date")) {
					if(cmdn == 1) {
						time_t t = get_time_();
						if(t != 0) {
							disp_time_(t);
						}
					} else {
						set_time_date_();
					}
				} else if(check_key_word_(0, "help")) {
					sci_puts("date\n");
					sci_puts("date yyyy/mm/dd hh:mm[:ss]\n");
				} else {
					char buff[12];
					if(command_.get_word(0, sizeof(buff), buff)) {
						sci_puts("Command error: ");
						sci_puts(buff);
						sci_putch('\n');
					}
				}
			}
		}
	}
}
<commit_msg>update<commit_after>//=====================================================================//
/*!	@file
	@brief	R8C I2C メイン @n
			for DS1302 RTC
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "main.hpp"
#include <cstring>
#include "system.hpp"
#include "clock.hpp"
#include "common/command.hpp"
#include "common/format.hpp"

// 対象の RTC を有効にする
// #define DS1371
#define DS3231

static void wait_(uint16_t n)
{
	while(n > 0) {
		asm("nop");
		--n;
	}
}

static timer_b timer_b_;
static uart0 uart0_;
static utils::command<64> command_;
static i2c_io i2c_io_;
#ifdef DS1371
static ds1371 rtc_(i2c_io_);
#endif
#ifdef DS3231
static ds3231 rtc_(i2c_io_);
#endif

extern "C" {
	void sci_putch(char ch) {
		uart0_.putch(ch);
	}

	char sci_getch(void) {
		return uart0_.getch();
	}

	uint16_t sci_length() {
		return uart0_.length();
	}

	void sci_puts(const char* str) {
		uart0_.puts(str);
	}
}

extern "C" {
	const void* variable_vectors_[] __attribute__ ((section (".vvec"))) = {
		reinterpret_cast<void*>(brk_inst_),		nullptr,	// (0)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (1) flash_ready
		reinterpret_cast<void*>(null_task_),	nullptr,	// (2)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (3)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (4) コンパレーターB1
		reinterpret_cast<void*>(null_task_),	nullptr,	// (5) コンパレーターB3
		reinterpret_cast<void*>(null_task_),	nullptr,	// (6)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (7) タイマＲＣ

		reinterpret_cast<void*>(null_task_),	nullptr,	// (8)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (9)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (10)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (11)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (12)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (13) キー入力
		reinterpret_cast<void*>(null_task_),	nullptr,	// (14) A/D 変換
		reinterpret_cast<void*>(null_task_),	nullptr,	// (15)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (16)
		reinterpret_cast<void*>(uart0_.isend),	nullptr,	// (17) UART0 送信
		reinterpret_cast<void*>(uart0_.irecv),	nullptr,	// (18) UART0 受信
		reinterpret_cast<void*>(null_task_),	nullptr,	// (19)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (20)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (21) /INT2
		reinterpret_cast<void*>(null_task_),	nullptr,	// (22) タイマＲＪ２
		reinterpret_cast<void*>(null_task_),	nullptr,	// (23) 周期タイマ

		reinterpret_cast<void*>(timer_b_.itask),nullptr,	// (24) タイマＲＢ２
		reinterpret_cast<void*>(null_task_),	nullptr,	// (25) /INT1
		reinterpret_cast<void*>(null_task_),	nullptr,	// (26) /INT3
		reinterpret_cast<void*>(null_task_),	nullptr,	// (27)

		reinterpret_cast<void*>(null_task_),	nullptr,	// (28)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (29) /INT0
		reinterpret_cast<void*>(null_task_),	nullptr,	// (30)
		reinterpret_cast<void*>(null_task_),	nullptr,	// (31)
	};
}

static time_t get_time_() {
	time_t t = 0;
	if(!rtc_.get_time(t)) {
		sci_puts("Stall RTC read...\n");
	}
	return t;
}

static const char* wday_[] = {
	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};

static const char* mon_[] = {
	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

static void disp_time_(time_t t) {
	struct tm *m = gmtime(&t);
	utils::format("%s %s %d %02d:%02d:%02d  %4d\n")
		% wday_[m->tm_wday]
		% mon_[m->tm_mon]
		% static_cast<uint32_t>(m->tm_mday)
		% static_cast<uint32_t>(m->tm_hour)
		% static_cast<uint32_t>(m->tm_min)
		% static_cast<uint32_t>(m->tm_sec)
		% static_cast<uint32_t>(m->tm_year + 1900);
}

static bool check_key_word_(uint8_t idx, const char* key)
{
	char buff[12];
	if(command_.get_word(idx, sizeof(buff), buff)) {
		if(strcmp(buff, key) == 0) {
			return true;
		}
	}
	return false;
}

static const char* get_dec_(const char* p, char tmch, int& value) {
	int v = 0;
	char ch;
	while((ch = *p) != 0) {
		++p;
		if(ch == tmch) {
			break;
		} else if(ch >= '0' && ch <= '9') {
			v *= 10;
			v += ch - '0';
		} else {
			return nullptr;
		}
	}
	value = v;
	return p;
}

 __attribute__ ((section (".exttext")))
static void set_time_date_()
{
	time_t t = get_time_();
	if(t == 0) return;

	struct tm *m = gmtime(&t);
	bool err = false;
	if(command_.get_words() == 3) {
		char buff[12];
		if(command_.get_word(1, sizeof(buff), buff)) {
			const char* p = buff;
			int vs[3];
			uint8_t i;
			for(i = 0; i < 3; ++i) {
				p = get_dec_(p, '/', vs[i]);
				if(p == nullptr) {
					break;
				}
			}
			if(p != nullptr && p[0] == 0 && i == 3) {
				if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900;
				if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1;
				if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2];
			} else {
				err = true;
			}
		}

		if(command_.get_word(2, sizeof(buff), buff)) {
			const char* p = buff;
			int vs[3];
			uint8_t i;
			for(i = 0; i < 3; ++i) {
				p = get_dec_(p, ':', vs[i]);
				if(p == nullptr) {
					break;
				}
			}
			if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) {
				if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0];
				if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1];
				if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2];
				else m->tm_sec = 0;
			} else {
				err = true;
			}
		}
	}

	if(err) {
		sci_puts("Can't analize Time/Date input.\n");
		return;
	}

	time_t tt = mktime(m);
	if(!rtc_.set_time(tt)) {
		sci_puts("Stall RTC write...\n");
	}
}

 __attribute__ ((section (".exttext")))
int main(int argc, char *argv[])
{
	using namespace device;

// クロック関係レジスタ・プロテクト解除
	PRCR.PRC0 = 1;

// 高速オンチップオシレーターへ切り替え(20MHz)
// ※ F_CLK を設定する事（Makefile内）
	OCOCR.HOCOE = 1;
	wait_(1000);
	SCKCR.HSCKSEL = 1;
	CKSTPR.SCKSEL = 1;

	// タイマーＢ初期化
	{
		uint8_t ir_level = 2;
		timer_b_.start_timer(60, ir_level);
	}

	// UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in])
	// ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意！
	{
		utils::PORT_MAP(utils::port_map::P14::TXD0);
		utils::PORT_MAP(utils::port_map::P15::RXD0);
		uint8_t ir_level = 1;
		uart0_.start(19200, ir_level);
	}

	// I2C クラスの初期化
	{
		i2c_io_.init();
	}

	// RTC を開始
	{
		rtc_.start();
	}

	sci_puts("Start R8C RTC monitor\n");
	command_.set_prompt("# ");

	// LED シグナル用ポートを出力
	PD1.B0 = 1;

	uint8_t cnt = 0;
	while(1) {
		timer_b_.sync();

		if(cnt >= 20) {
			cnt = 0;
		}
		if(cnt < 10) P1.B0 = 1;
		else P1.B0 = 0;
		++cnt;

		// コマンド入力と、コマンド解析
		if(command_.service()) {
			uint8_t cmdn = command_.get_words();
			if(cmdn >= 1) {
				if(check_key_word_(0, "date")) {
					if(cmdn == 1) {
						time_t t = get_time_();
						if(t != 0) {
							disp_time_(t);
						}
					} else {
						set_time_date_();
					}
				} else if(check_key_word_(0, "help")) {
					sci_puts("date\n");
					sci_puts("date yyyy/mm/dd hh:mm[:ss]\n");
				} else {
					char buff[12];
					if(command_.get_word(0, sizeof(buff), buff)) {
						sci_puts("Command error: ");
						sci_puts(buff);
						sci_putch('\n');
					}
				}
			}
		}
	}
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

class HammingEncoder
{
public:
	string EncodeHamming(string message)
	{
		return CalculateHamming(message, true);
	}

	string DecodeHamming(string message)
	{
		return CalculateHamming(message, false);
	}

private:
	string CalculateHamming(string message, bool encode)
	{
		int numPBits;
		int numOnes = 0;
		string encodedMessage;
		int counter = 0;
		string testStr = "";

		int numSuccessful = 0;
		int numUnsuccessful = 0;
		int error = 0;

		numPBits = floor(log2(message.length())) + 1;

		if (encode)
		{
			for (int i = 0; i < numPBits; i++)
				message.insert(pow(2, i) - 1, "_");
		}

		encodedMessage = message;

		while (counter < numPBits)
		{
			testStr = determineTestString(counter, encodedMessage);

			if (encode)
				encodedMessage[pow(2, counter) - 1] = determineParity(testStr);
			else
			{
				if (encodedMessage[pow(2, counter) - 1] == determineParity(testStr.substr(1)))
				{
					//	cout << "check at " << pow(2, counter) - 1 << " successful" << endl;
					numSuccessful++;
				}
				else
				{
					cout << "parity check failure at position: " << pow(2, counter) - 1 << endl;
					numUnsuccessful++;
					error += pow(2, counter);
					//		cout << "error is: " << error - 1 << endl;
				}
			}

			testStr.clear();
			counter++;
		}

		if (!encode && numUnsuccessful != 0)
		{
			cout << "error detected at position: " << error - 1 << endl;
			return "_" + to_string(error);
		}

		if (!encode && numUnsuccessful == 0)
		{
			for (int i = numPBits - 1; i >= 0; i--)
				encodedMessage.erase(pow(2, i) - 1, 1);
		}

		return encodedMessage;
	}

	string determineTestString(int counter, string encodedMessage)
	{
		string testStr = "";
		//		cout << "counter is: " << counter << endl;
		for (int i = pow(2, counter) - 1; i < encodedMessage.length(); i += pow(2, counter) * 2)
		{
			//	cout << "i is: " << i << endl;

			if (i + pow(2, counter) > encodedMessage.length())
			{
				//cout << "checking: " << encodedMessage.substr(i) << endl;
				testStr += encodedMessage.substr(i);
			}
			else
			{
				//	cout << "checking: " << encodedMessage.substr(i, pow(2, counter)) << endl;
				testStr += encodedMessage.substr(i, pow(2, counter));
			}
		}

		return testStr;

	}

	char determineParity(string testStr)
	{
		int num = 0;

		for (int i = 0; i < testStr.length(); i++)
		{
			if (testStr[i] == '1')
				num++;
		}

		if (isOdd(num))
			return '0';

		return '1';
	}

	bool isOdd(int num)
	{
		if (num % 2 == 1)
			return true;
		return false;
	}
};<commit_msg>removed unused include<commit_after>#include <iostream>
#include <string>

using namespace std;

class HammingEncoder
{
public:
	string EncodeHamming(string message)
	{
		return CalculateHamming(message, true);
	}

	string DecodeHamming(string message)
	{
		return CalculateHamming(message, false);
	}

private:
	string CalculateHamming(string message, bool encode)
	{
		int numPBits;
		int numOnes = 0;
		string encodedMessage;
		int counter = 0;
		string testStr = "";

		int numSuccessful = 0;
		int numUnsuccessful = 0;
		int error = 0;

		numPBits = floor(log2(message.length())) + 1;

		if (encode)
		{
			for (int i = 0; i < numPBits; i++)
				message.insert(pow(2, i) - 1, "_");
		}

		encodedMessage = message;

		while (counter < numPBits)
		{
			testStr = determineTestString(counter, encodedMessage);

			if (encode)
				encodedMessage[pow(2, counter) - 1] = determineParity(testStr);
			else
			{
				if (encodedMessage[pow(2, counter) - 1] == determineParity(testStr.substr(1)))
				{
					//	cout << "check at " << pow(2, counter) - 1 << " successful" << endl;
					numSuccessful++;
				}
				else
				{
					cout << "parity check failure at position: " << pow(2, counter) - 1 << endl;
					numUnsuccessful++;
					error += pow(2, counter);
					//		cout << "error is: " << error - 1 << endl;
				}
			}

			testStr.clear();
			counter++;
		}

		if (!encode && numUnsuccessful != 0)
		{
			cout << "error detected at position: " << error - 1 << endl;
			return "_" + to_string(error);
		}

		if (!encode && numUnsuccessful == 0)
		{
			for (int i = numPBits - 1; i >= 0; i--)
				encodedMessage.erase(pow(2, i) - 1, 1);
		}

		return encodedMessage;
	}

	string determineTestString(int counter, string encodedMessage)
	{
		string testStr = "";
		//		cout << "counter is: " << counter << endl;
		for (int i = pow(2, counter) - 1; i < encodedMessage.length(); i += pow(2, counter) * 2)
		{
			//	cout << "i is: " << i << endl;

			if (i + pow(2, counter) > encodedMessage.length())
			{
				//cout << "checking: " << encodedMessage.substr(i) << endl;
				testStr += encodedMessage.substr(i);
			}
			else
			{
				//	cout << "checking: " << encodedMessage.substr(i, pow(2, counter)) << endl;
				testStr += encodedMessage.substr(i, pow(2, counter));
			}
		}

		return testStr;

	}

	char determineParity(string testStr)
	{
		int num = 0;

		for (int i = 0; i < testStr.length(); i++)
		{
			if (testStr[i] == '1')
				num++;
		}

		if (isOdd(num))
			return '0';

		return '1';
	}

	bool isOdd(int num)
	{
		if (num % 2 == 1)
			return true;
		return false;
	}
};<|endoftext|>


<commit_before>#ifndef AIKIDO_STATESPACE_COMPOUNDSTATESPACE_H
#define AIKIDO_STATESPACE_COMPOUNDSTATESPACE_H
#include <vector>
#include "StateSpace.hpp"
#include "ScopedState.hpp"

namespace aikido {
namespace statespace {

// Defined in detail/CompoundStateSpace.hpp
template <class> class CompoundStateHandle;

/// Represents the Cartesian product of other StateSpaces.
class CompoundStateSpace
  : std::enable_shared_from_this<CompoundStateSpace>
  , public virtual StateSpace
{
public:
  /// A tuple of states where the i-th state is from the i-th subspace.
  class State : public StateSpace::State
  {
  protected:
    State() = default;
    ~State() = default;

    friend class CompoundStateSpace;
  };

  using StateHandle = CompoundStateHandle<State>;
  using StateHandleConst = CompoundStateHandle<const State>;

  using ScopedState = statespace::ScopedState<StateHandle>;
  using ScopedStateConst = statespace::ScopedState<StateHandleConst>;

  /// Construct the Cartesian product of a vector of subspaces.
  explicit CompoundStateSpace(const std::vector<StateSpacePtr>& _subspaces);

  /// Helper function to create a ScopedState.
  ScopedState createState() const;

  /// Gets number of subspaces.
  size_t getNumStates() const;

  /// Gets subspace by index.
  template <class Space = StateSpace>
  const Space* getSubSpace(size_t _index) const;

  /// Gets state of type by subspace index.
  template <class Space = StateSpace>
  typename Space::State* getSubState(
    StateSpace::State* _state, size_t _index) const;

  /// Gets state of type by subspace index.
  template <class Space = StateSpace>
  const typename Space::State* getSubState(
    const StateSpace::State* _state, size_t _index) const;

  /// Gets state handle of type by subspace index.
  template <class Space = StateSpace>
  typename Space::StateHandle getSubStateHandle(
    StateSpace::State* _state, size_t _index) const;

  /// Gets state handle of type by subspace index.
  template <class Space = StateSpace>
  typename Space::StateHandleConst getSubStateHandle(
    const StateSpace::State* _state, size_t _index) const;

  // Documentation inherited.
  size_t getStateSizeInBytes() const override;

  // Documentation inherited.
  StateSpace::State* allocateStateInBuffer(void* _buffer) const override;

  // Documentation inherited.
  void freeStateInBuffer(StateSpace::State* _state) const override;

  // Documentation inherited.
  SampleableConstraintPtr createSampleableConstraint(
    std::unique_ptr<util::RNG> _rng) const override;

  // Documentation inherited.
  void compose(
    const StateSpace::State* _state1, const StateSpace::State* _state2,
    StateSpace::State* _out) const override;

  // Documentation inherited
  unsigned int getDimension() const override;

  // Documentation inherited
  double getMaximumExtent() const override;

  // Documentation inherited
  double getMeasure() const override;

  // Documentation inherited
  void enforceBounds(StateSpace::State* _state) const override;

  // Documentation inherited
  bool satisfiesBounds(const StateSpace::State* _state) const override;

  // Documentation inherited
  void copyState(StateSpace::State* _destination,
                 const StateSpace::State* _source) const override;

  // Documentation inherited
  double distance(const StateSpace::State* _state1,
                  const StateSpace::State* _state2) const override;

  // Documentation inherited
  bool equalStates(const StateSpace::State* _state1,
                   const StateSpace::State* _state2) const override;

  // Documentation inherited
  void interpolate(const StateSpace::State* _from,
                   const StateSpace::State* _to,
                   const double _t,
                   StateSpace::State* _State) const;

  // Documentation inherited. _tangent should be 3d twist.
  void expMap(
    const Eigen::VectorXd& _tangent, StateSpace::State* _out) const override;

private:
  std::vector<StateSpacePtr> mSubspaces;
  std::vector<std::size_t> mOffsets;
  size_t mSizeInBytes;
};

} // namespace statespace
} // namespace aikido

#include "detail/CompoundStateSpace.hpp"

#endif
<commit_msg>fixed shared_from on CompoundStateSpace<commit_after>#ifndef AIKIDO_STATESPACE_COMPOUNDSTATESPACE_H
#define AIKIDO_STATESPACE_COMPOUNDSTATESPACE_H
#include <vector>
#include "StateSpace.hpp"
#include "ScopedState.hpp"

namespace aikido {
namespace statespace {

// Defined in detail/CompoundStateSpace.hpp
template <class> class CompoundStateHandle;

/// Represents the Cartesian product of other StateSpaces.
class CompoundStateSpace
  : public std::enable_shared_from_this<CompoundStateSpace>
  , public virtual StateSpace
{
public:
  /// A tuple of states where the i-th state is from the i-th subspace.
  class State : public StateSpace::State
  {
  protected:
    State() = default;
    ~State() = default;

    friend class CompoundStateSpace;
  };

  using StateHandle = CompoundStateHandle<State>;
  using StateHandleConst = CompoundStateHandle<const State>;

  using ScopedState = statespace::ScopedState<StateHandle>;
  using ScopedStateConst = statespace::ScopedState<StateHandleConst>;

  /// Construct the Cartesian product of a vector of subspaces.
  explicit CompoundStateSpace(const std::vector<StateSpacePtr>& _subspaces);

  /// Helper function to create a ScopedState.
  ScopedState createState() const;

  /// Gets number of subspaces.
  size_t getNumStates() const;

  /// Gets subspace by index.
  template <class Space = StateSpace>
  const Space* getSubSpace(size_t _index) const;

  /// Gets state of type by subspace index.
  template <class Space = StateSpace>
  typename Space::State* getSubState(
    StateSpace::State* _state, size_t _index) const;

  /// Gets state of type by subspace index.
  template <class Space = StateSpace>
  const typename Space::State* getSubState(
    const StateSpace::State* _state, size_t _index) const;

  /// Gets state handle of type by subspace index.
  template <class Space = StateSpace>
  typename Space::StateHandle getSubStateHandle(
    StateSpace::State* _state, size_t _index) const;

  /// Gets state handle of type by subspace index.
  template <class Space = StateSpace>
  typename Space::StateHandleConst getSubStateHandle(
    const StateSpace::State* _state, size_t _index) const;

  // Documentation inherited.
  size_t getStateSizeInBytes() const override;

  // Documentation inherited.
  StateSpace::State* allocateStateInBuffer(void* _buffer) const override;

  // Documentation inherited.
  void freeStateInBuffer(StateSpace::State* _state) const override;

  // Documentation inherited.
  SampleableConstraintPtr createSampleableConstraint(
    std::unique_ptr<util::RNG> _rng) const override;

  // Documentation inherited.
  void compose(
    const StateSpace::State* _state1, const StateSpace::State* _state2,
    StateSpace::State* _out) const override;

  // Documentation inherited
  unsigned int getDimension() const override;

  // Documentation inherited
  double getMaximumExtent() const override;

  // Documentation inherited
  double getMeasure() const override;

  // Documentation inherited
  void enforceBounds(StateSpace::State* _state) const override;

  // Documentation inherited
  bool satisfiesBounds(const StateSpace::State* _state) const override;

  // Documentation inherited
  void copyState(StateSpace::State* _destination,
                 const StateSpace::State* _source) const override;

  // Documentation inherited
  double distance(const StateSpace::State* _state1,
                  const StateSpace::State* _state2) const override;

  // Documentation inherited
  bool equalStates(const StateSpace::State* _state1,
                   const StateSpace::State* _state2) const override;

  // Documentation inherited
  void interpolate(const StateSpace::State* _from,
                   const StateSpace::State* _to,
                   const double _t,
                   StateSpace::State* _State) const;

  // Documentation inherited. _tangent should be 3d twist.
  void expMap(
    const Eigen::VectorXd& _tangent, StateSpace::State* _out) const override;

private:
  std::vector<StateSpacePtr> mSubspaces;
  std::vector<std::size_t> mOffsets;
  size_t mSizeInBytes;
};

} // namespace statespace
} // namespace aikido

#include "detail/CompoundStateSpace.hpp"

#endif
<|endoftext|>