<commit_before>// @(#)root/test:$name:  $:$id: filter.cxx,v 1.0 exp $
// Author: O.Couet

//
//    filters doc files.
//

#include <stdlib.h>
#include <Riostream.h>
#include <time.h>
#include <TString.h>
#include <TROOT.h>
#include <TError.h>
#include <TRandom.h>
#include <TBenchmark.h>
#include <TSystem.h>
#include <TApplication.h>
#include <TDatime.h>
#include <TFile.h>
#include <TF1.h>
#include "TF2.h"
#include <TF3.h>
#include <TH2.h>
#include <TNtuple.h>
#include <TProfile.h>
#include "TString.h"

#include <TStyle.h>
#include <TCanvas.h>
#include <TColor.h>
#include <TFrame.h>
#include <TPostScript.h>
#include <TPDF.h>
#include <TLine.h>
#include <TMarker.h>
#include <TPolyLine.h>
#include <TLatex.h>
#include <TMathText.h>
#include <TLegend.h>
#include <TEllipse.h>
#include <TCurlyArc.h>
#include <TArc.h>
#include <TPaveText.h>
#include <TPaveStats.h>
#include <TPaveLabel.h>
#include <TGaxis.h>
#include <TGraph.h>
#include <TGraphErrors.h>
#include <TGraphAsymmErrors.h>
#include <TGraphBentErrors.h>
#include <TMultiGraph.h>
#include <TGraph2D.h>
#include <TParallelCoord.h>
#include <TImage.h>
#include <TMath.h>
#include <TSystem.h>

// Auxiliary functions
void    GetClassName();
void    StandardizeKeywords();
void    ExecuteMacro();
void    ExecuteCommand(TString);

// Global variables.
char    gLine[255];
TString gFileName;
TString gLineString;
TString gClassName;
TString gImageName;
Bool_t  gHeader;
Bool_t  gSource;
Bool_t  gInClassDef;
Bool_t  gClass;
Int_t   gInMacro;
Int_t   gImageID;

//______________________________________________________________________________
int main(int argc, char *argv[])
{
   // Filter ROOT files for Doxygen.

   // Initialisation

   gFileName   = argv[1];
   gHeader     = kFALSE;
   gSource     = kFALSE;
   gInClassDef = kFALSE;
   gClass      = kFALSE;
   gInMacro    = 0;
   gImageID    = 0;
   if (gFileName.EndsWith(".cxx")) gSource = kTRUE;
   if (gFileName.EndsWith(".h"))   gHeader = kTRUE;
   GetClassName();

   // Loop on file.
   FILE *f = fopen(gFileName.Data(),"r");

   // File header.
   if (gHeader) {
      while (fgets(gLine,255,f)) {
         gLineString = gLine;

         if (gLineString.BeginsWith("class"))    gInClassDef = kTRUE;
         if (gLineString.Index("ClassDef") >= 0) gInClassDef = kFALSE;

         if (gInClassDef && gLineString.Index("//") >= 0) {
            gLineString.ReplaceAll("//","///<");
         }

         printf("%s",gLineString.Data());
      }
   }

   // Source file.
   if (gSource) {
      while (fgets(gLine,255,f)) {
         gLineString = gLine;
         StandardizeKeywords();

         if (gLineString.Index("begin_html") >= 0) {
            if (!gClass) {
               gLineString = TString::Format("/*! \\class %s\n",gClassName.Data());
               gClass = kTRUE;
            } else {
               gLineString.ReplaceAll("begin_html","");
            }
         }

         if (gLineString.Index("end_html") >= 0) {
            gLineString.ReplaceAll("end_html","");
         }

         if (gInMacro) {
            if (gInMacro == 1) {
               if (gLineString.EndsWith(".C\n")) ExecuteMacro();
            }
            gInMacro++;
         }

         if (gLineString.Index("Begin_Macro") >= 0) {
            gLineString = "
\n";
            gInMacro++;
         }

         if (gLineString.Index("End_Macro") >= 0) {
            gLineString.ReplaceAll("End_Macro","
\n");
            gInMacro = 0;
         }

         printf("%s",gLineString.Data());
      }
   }

   return 1;
}

//______________________________________________________________________________
void GetClassName()
{
   // Retrieve the class name.

   Int_t i1 = 0;
   Int_t i2 = 0;

   FILE *f = fopen(gFileName.Data(),"r");

   // File header.
   if (gHeader) {
      while (fgets(gLine,255,f)) {
         gLineString = gLine;
         if (gLineString.Index("ClassDef") >= 0) {
            i1 = gLineString.Index("(")+1;
            i2 = gLineString.Index(",")-1;
            gClassName = gLineString(i1,i2-i1+1);
            fclose(f);
            return;
         }
      }
   }

   // Source file.
   if (gSource) {
      while (fgets(gLine,255,f)) {
         gLineString = gLine;
         if (gLineString.Index("ClassImp") >= 0) {
            i1 = gLineString.Index("(")+1;
            i2 = gLineString.Index(")")-1;
            gClassName = gLineString(i1,i2-i1+1);
            fclose(f);
            return;
         }
      }
   }

   fclose(f);
   return;
}

//______________________________________________________________________________
void StandardizeKeywords()
{
   // Standardize the THTML keywords to ease the parsing.

   gLineString.ReplaceAll("End_Html","end_html");
   gLineString.ReplaceAll("End_html","end_html");
   gLineString.ReplaceAll("end_html ","end_html");
   gLineString.ReplaceAll("Begin_Html","begin_html");
   gLineString.ReplaceAll("Begin_html","begin_html");
   gLineString.ReplaceAll("<big>","");
   gLineString.ReplaceAll("</big>","");
}

//______________________________________________________________________________
void ExecuteMacro()
{
   // Execute the macro in gLineString and produce the corresponding picture

   // Name of the next Image to be generated
   gImageName = TString::Format("%s_%3.3d.png", gClassName.Data()
                                              , gImageID++);

   // Build the ROOT command to be executed.
   gLineString.ReplaceAll("../../..","root -l -b -q \"makeimage.C(\\\"../..");
   Int_t l = gLineString.Length();
   gLineString.Replace(l-2,1,TString::Format("C\\\",\\\"%s/html/%s\\\")\"", gSystem->Getenv("OUTPUT_DIRECTORY")
                                                                          , gImageName.Data()));

   ExecuteCommand(gLineString);

   gLineString = TString::Format("\\image html %s\n",gImageName.Data());
}

//______________________________________________________________________________
void ExecuteCommand(TString command)
{
   // Execute a command making sure stdout will not go in the doxygen file.

   int o = dup(fileno(stdout));
   freopen("stdout.dat","a",stdout);
   gSystem->Exec(command.Data());
   dup2(o,fileno(stdout));
   close(o);
}<commit_msg>Generate pictures for macros in ../doc/macros<commit_after>// @(#)root/test:$name:  $:$id: filter.cxx,v 1.0 exp $
// Author: O.Couet

//
//    filters doc files.
//

#include <stdlib.h>
#include <Riostream.h>
#include <time.h>
#include <TString.h>
#include <TROOT.h>
#include <TError.h>
#include <TRandom.h>
#include <TBenchmark.h>
#include <TSystem.h>
#include <TApplication.h>
#include <TDatime.h>
#include <TFile.h>
#include <TF1.h>
#include "TF2.h"
#include <TF3.h>
#include <TH2.h>
#include <TNtuple.h>
#include <TProfile.h>
#include "TString.h"

#include <TStyle.h>
#include <TCanvas.h>
#include <TColor.h>
#include <TFrame.h>
#include <TPostScript.h>
#include <TPDF.h>
#include <TLine.h>
#include <TMarker.h>
#include <TPolyLine.h>
#include <TLatex.h>
#include <TMathText.h>
#include <TLegend.h>
#include <TEllipse.h>
#include <TCurlyArc.h>
#include <TArc.h>
#include <TPaveText.h>
#include <TPaveStats.h>
#include <TPaveLabel.h>
#include <TGaxis.h>
#include <TGraph.h>
#include <TGraphErrors.h>
#include <TGraphAsymmErrors.h>
#include <TGraphBentErrors.h>
#include <TMultiGraph.h>
#include <TGraph2D.h>
#include <TParallelCoord.h>
#include <TImage.h>
#include <TMath.h>
#include <TSystem.h>

// Auxiliary functions
void    GetClassName();
void    StandardizeKeywords();
void    ExecuteMacro();
void    ExecuteCommand(TString);

// Global variables.
char    gLine[255];
TString gFileName;
TString gLineString;
TString gClassName;
TString gImageName;
TString gCwd;
Bool_t  gHeader;
Bool_t  gSource;
Bool_t  gInClassDef;
Bool_t  gClass;
Int_t   gInMacro;
Int_t   gImageID;

//______________________________________________________________________________
int main(int argc, char *argv[])
{
   // Filter ROOT files for Doxygen.

   // Initialisation

   gFileName   = argv[1];
   gHeader     = kFALSE;
   gSource     = kFALSE;
   gInClassDef = kFALSE;
   gClass      = kFALSE;
   gInMacro    = 0;
   gImageID    = 0;
   if (gFileName.EndsWith(".cxx")) gSource = kTRUE;
   if (gFileName.EndsWith(".h"))   gHeader = kTRUE;
   GetClassName();
   gCwd = gFileName(0, gFileName.Last('/'));

   // Loop on file.
   FILE *f = fopen(gFileName.Data(),"r");

   // File header.
   if (gHeader) {
      while (fgets(gLine,255,f)) {
         gLineString = gLine;

         if (gLineString.BeginsWith("class"))    gInClassDef = kTRUE;
         if (gLineString.Index("ClassDef") >= 0) gInClassDef = kFALSE;

         if (gInClassDef && gLineString.Index("//") >= 0) {
            gLineString.ReplaceAll("//","///<");
         }

         printf("%s",gLineString.Data());
      }
   }

   // Source file.
   if (gSource) {
      while (fgets(gLine,255,f)) {
         gLineString = gLine;
         StandardizeKeywords();

         if (gLineString.Index("begin_html") >= 0) {
            if (!gClass) {
               gLineString = TString::Format("/*! \\class %s\n",gClassName.Data());
               gClass = kTRUE;
            } else {
               gLineString.ReplaceAll("begin_html","");
            }
         }

         if (gLineString.Index("end_html") >= 0) {
            gLineString.ReplaceAll("end_html","");
         }

         if (gInMacro) {
            if (gInMacro == 1) {
               if (gLineString.EndsWith(".C\n")) {
                  ExecuteMacro();
                  gInMacro++;
               } else {
               }
            } else {
            }
         }

         if (gLineString.Index("Begin_Macro") >= 0) {
            gLineString = "
\n";
            gInMacro++;
         }

         if (gLineString.Index("End_Macro") >= 0) {
            gLineString.ReplaceAll("End_Macro","
\n");
            gInMacro = 0;
         }

         printf("%s",gLineString.Data());
      }
   }

   return 1;
}

//______________________________________________________________________________
void GetClassName()
{
   // Retrieve the class name.

   Int_t i1 = 0;
   Int_t i2 = 0;

   FILE *f = fopen(gFileName.Data(),"r");

   // File header.
   if (gHeader) {
      while (fgets(gLine,255,f)) {
         gLineString = gLine;
         if (gLineString.Index("ClassDef") >= 0) {
            i1 = gLineString.Index("(")+1;
            i2 = gLineString.Index(",")-1;
            gClassName = gLineString(i1,i2-i1+1);
            fclose(f);
            return;
         }
      }
   }

   // Source file.
   if (gSource) {
      while (fgets(gLine,255,f)) {
         gLineString = gLine;
         if (gLineString.Index("ClassImp") >= 0) {
            i1 = gLineString.Index("(")+1;
            i2 = gLineString.Index(")")-1;
            gClassName = gLineString(i1,i2-i1+1);
            fclose(f);
            return;
         }
      }
   }

   fclose(f);

   return;
}

//______________________________________________________________________________
void StandardizeKeywords()
{
   // Standardize the THTML keywords to ease the parsing.

   gLineString.ReplaceAll("End_Html","end_html");
   gLineString.ReplaceAll("End_html","end_html");
   gLineString.ReplaceAll("end_html ","end_html");
   gLineString.ReplaceAll("Begin_Html","begin_html");
   gLineString.ReplaceAll("Begin_html","begin_html");
   gLineString.ReplaceAll("<big>","");
   gLineString.ReplaceAll("</big>","");
}

//______________________________________________________________________________
void ExecuteMacro()
{
   // Execute the macro in gLineString and produce the corresponding picture

   // Name of the next Image to be generated
   gImageName = TString::Format("%s_%3.3d.png", gClassName.Data()
                                              , gImageID++);

   // Build the ROOT command to be executed.
   if (gLineString.Index("../../..") >= 0) {
      gLineString.ReplaceAll("../../..","root -l -b -q \"makeimage.C(\\\"../..");
   } else {
      gLineString.Prepend(TString::Format("root -l -b -q \"makeimage.C(\\\"%s/../doc/macros/",gCwd.Data()));
   }
   Int_t l = gLineString.Length();
   TString OutDir = gSystem->Getenv("OUTPUT_DIRECTORY");
   OutDir.ReplaceAll("\"","");
   gLineString.Replace(l-2,1,TString::Format("C\\\",\\\"%s/html/%s\\\")\"",
                                             OutDir.Data(),
                                             gImageName.Data()));

   ExecuteCommand(gLineString);

   gLineString = TString::Format("\\image html %s\n",gImageName.Data());
}

//______________________________________________________________________________
void ExecuteCommand(TString command)
{
   // Execute a command making sure stdout will not go in the doxygen file.

   int o = dup(fileno(stdout));
   freopen("stdout.dat","a",stdout);
   gSystem->Exec(command.Data());
   dup2(o,fileno(stdout));
   close(o);
}<|endoftext|>


<commit_before>#include "drape_frontend/visual_params.hpp"

#include "base/macros.hpp"
#include "base/math.hpp"
#include "base/assert.hpp"

#include "indexer/mercator.hpp"

#include "std/limits.hpp"
#include "std/algorithm.hpp"

namespace df
{

uint32_t const YotaDevice = 0x1;

namespace
{

static VisualParams g_VizParams;

typedef pair<string, double> visual_scale_t;

struct VisualScaleFinder
{
  VisualScaleFinder(double vs)
    : m_vs(vs)
  {
  }

  bool operator()(visual_scale_t const & node)
  {
    return my::AlmostEqualULPs(node.second, m_vs);
  }

  double m_vs;
};

} // namespace

#ifdef DEBUG
static bool g_isInited = false;
#define RISE_INITED g_isInited = true
#define ASSERT_INITED ASSERT(g_isInited, ())
#else
#define RISE_INITED
#define ASSERT_INITED
#endif

void VisualParams::Init(double vs, uint32_t tileSize, vector<uint32_t> const & additionalOptions)
{
  g_VizParams.m_tileSize = tileSize;
  g_VizParams.m_visualScale = vs;
  if (find(additionalOptions.begin(), additionalOptions.end(), YotaDevice) != additionalOptions.end())
    g_VizParams.m_isYotaDevice = true;
  RISE_INITED;
}

VisualParams & VisualParams::Instance()
{
  ASSERT_INITED;
  return g_VizParams;
}

string const & VisualParams::GetResourcePostfix(double visualScale, bool isYotaDevice)
{
  static visual_scale_t postfixes[] =
  {
    make_pair("ldpi", 0.75),
    make_pair("mdpi", 1.0),
    make_pair("hdpi", 1.5),
    make_pair("xhdpi", 2.0),
    make_pair("xxhdpi", 3.0),
    make_pair("6plus", 2.4),
  };

  static string specifixPostfixes[] =
  {
    "yota"
  };

  if (isYotaDevice)
    return specifixPostfixes[0];

  visual_scale_t * finded = find_if(postfixes, postfixes + ARRAY_SIZE(postfixes), VisualScaleFinder(visualScale));
  ASSERT(finded < postfixes + ARRAY_SIZE(postfixes), ());
  return finded->first;
}

string const & VisualParams::GetResourcePostfix() const
{
  return VisualParams::GetResourcePostfix(m_visualScale, m_isYotaDevice);
}

double VisualParams::GetVisualScale() const
{
  return m_visualScale;
}

uint32_t VisualParams::GetTileSize() const
{
  return m_tileSize;
}

uint32_t VisualParams::GetTouchRectRadius() const
{
  return 20 * GetVisualScale();
}

double VisualParams::GetDragThreshold() const
{
  return 10.0 * GetVisualScale();
}

VisualParams::VisualParams()
  : m_tileSize(0)
  , m_visualScale(0.0)
{
}

m2::RectD const & GetWorldRect()
{
  static m2::RectD const worldRect = MercatorBounds::FullRect();
  return worldRect;
}

int GetTileScaleBase(ScreenBase const & s, uint32_t tileSize)
{
  ScreenBase tmpS = s;
  tmpS.Rotate(-tmpS.GetAngle());

  // slightly smaller than original to produce "antialiasing" effect using bilinear filtration.
  int const halfSize = static_cast<int>(tileSize / 1.05 / 2.0);

  m2::RectD glbRect;
  m2::PointD const pxCenter = tmpS.PixelRect().Center();
  tmpS.PtoG(m2::RectD(pxCenter - m2::PointD(halfSize, halfSize),
                      pxCenter + m2::PointD(halfSize, halfSize)),
            glbRect);

  return GetTileScaleBase(glbRect);
}

int GetTileScaleBase(ScreenBase const & s)
{
  return GetTileScaleBase(s, VisualParams::Instance().GetTileSize());
}

int GetTileScaleBase(m2::RectD const & r)
{
  double const sz = max(r.SizeX(), r.SizeY());
  return max(1, my::rounds(log((MercatorBounds::maxX - MercatorBounds::minX) / sz) / log(2.0)));
}

int GetTileScaleIncrement(uint32_t tileSize, double visualScale)
{
  return log(tileSize / 256.0 / visualScale) / log(2.0);
}

int GetTileScaleIncrement()
{
  VisualParams const & p = VisualParams::Instance();
  return GetTileScaleIncrement(p.GetTileSize(), p.GetVisualScale());
}

m2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)
{
  // +1 - we will calculate half length for each side
  double const factor = 1 << (max(1, drawScale - GetTileScaleIncrement(tileSize, visualScale)) + 1);

  double const len = (MercatorBounds::maxX - MercatorBounds::minX) / factor;

  return m2::RectD(MercatorBounds::ClampX(center.x - len),
                   MercatorBounds::ClampY(center.y - len),
                   MercatorBounds::ClampX(center.x + len),
                   MercatorBounds::ClampY(center.y + len));
}

m2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center)
{
  VisualParams const & p = VisualParams::Instance();
  return GetRectForDrawScale(drawScale, center, p.GetTileSize(), p.GetVisualScale());
}

m2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)
{
  return GetRectForDrawScale(my::rounds(drawScale), center, tileSize, visualScale);
}

m2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center)
{
  return GetRectForDrawScale(my::rounds(drawScale), center);
}

int CalculateTileSize(int screenWidth, int screenHeight)
{
  int const maxSz = max(screenWidth, screenHeight);

  // we're calculating the tileSize based on (maxSz > 1024 ? rounded : ceiled)
  // to the nearest power of two value of the maxSz

  int const ceiledSz = 1 << static_cast<int>(ceil(log(double(maxSz + 1)) / log(2.0)));
  int res = 0;

  if (maxSz < 1024)
    res = ceiledSz;
  else
  {
    int const flooredSz = ceiledSz / 2;
    // rounding to the nearest power of two.
    if (ceiledSz - maxSz < maxSz - flooredSz)
      res = ceiledSz;
    else
      res = flooredSz;
  }

#ifndef OMIM_OS_DESKTOP
  return my::clamp(res / 2, 256, 1024);
#else
  return my::clamp(res / 2, 512, 1024);
#endif
}

int GetDrawTileScale(int baseScale, uint32_t tileSize, double visualScale)
{
  return max(1, baseScale + GetTileScaleIncrement(tileSize, visualScale));
}

int GetDrawTileScale(ScreenBase const & s, uint32_t tileSize, double visualScale)
{
  return GetDrawTileScale(GetTileScaleBase(s, tileSize), tileSize, visualScale);
}

int GetDrawTileScale(m2::RectD const & r, uint32_t tileSize, double visualScale)
{
  return GetDrawTileScale(GetTileScaleBase(r), tileSize, visualScale);
}

int GetDrawTileScale(int baseScale)
{
  VisualParams const & p = VisualParams::Instance();
  return GetDrawTileScale(baseScale, p.GetTileSize(), p.GetVisualScale());
}

int GetDrawTileScale(ScreenBase const & s)
{
  VisualParams const & p = VisualParams::Instance();
  return GetDrawTileScale(s, p.GetTileSize(), p.GetVisualScale());
}

int GetDrawTileScale(m2::RectD const & r)
{
  VisualParams const & p = VisualParams::Instance();
  return GetDrawTileScale(r, p.GetTileSize(), p.GetVisualScale());
}

} // namespace df
<commit_msg>Fixed algorithm to choose resource postfix to more stable<commit_after>#include "drape_frontend/visual_params.hpp"

#include "base/macros.hpp"
#include "base/math.hpp"
#include "base/assert.hpp"

#include "indexer/mercator.hpp"

#include "std/limits.hpp"
#include "std/algorithm.hpp"

namespace df
{

uint32_t const YotaDevice = 0x1;

namespace
{

static VisualParams g_VizParams;

typedef pair<string, double> visual_scale_t;

} // namespace

#ifdef DEBUG
static bool g_isInited = false;
#define RISE_INITED g_isInited = true
#define ASSERT_INITED ASSERT(g_isInited, ())
#else
#define RISE_INITED
#define ASSERT_INITED
#endif

void VisualParams::Init(double vs, uint32_t tileSize, vector<uint32_t> const & additionalOptions)
{
  g_VizParams.m_tileSize = tileSize;
  g_VizParams.m_visualScale = vs;
  if (find(additionalOptions.begin(), additionalOptions.end(), YotaDevice) != additionalOptions.end())
    g_VizParams.m_isYotaDevice = true;
  RISE_INITED;
}

VisualParams & VisualParams::Instance()
{
  ASSERT_INITED;
  return g_VizParams;
}

string const & VisualParams::GetResourcePostfix(double visualScale, bool isYotaDevice)
{
  static visual_scale_t postfixes[] =
  {
    make_pair("ldpi", 0.75),
    make_pair("mdpi", 1.0),
    make_pair("hdpi", 1.5),
    make_pair("xhdpi", 2.0),
    make_pair("xxhdpi", 3.0),
    make_pair("6plus", 2.4),
  };

  static string specifixPostfixes[] =
  {
    "yota"
  };

  if (isYotaDevice)
    return specifixPostfixes[0];

  // Looking for the nearest available scale.
  int postfixIndex = -1;
  double minValue = numeric_limits<float>::max();
  for (int i = 0; i < ARRAY_SIZE(postfixes); i++)
  {
    double val = fabs(postfixes[i].second - visualScale);
    if (val < minValue)
    {
      minValue = val;
      postfixIndex = i;
    }
  }

  ASSERT_GREATER_OR_EQUAL(postfixIndex, 0, ());
  return postfixes[postfixIndex].first;
}

string const & VisualParams::GetResourcePostfix() const
{
  return VisualParams::GetResourcePostfix(m_visualScale, m_isYotaDevice);
}

double VisualParams::GetVisualScale() const
{
  return m_visualScale;
}

uint32_t VisualParams::GetTileSize() const
{
  return m_tileSize;
}

uint32_t VisualParams::GetTouchRectRadius() const
{
  return 20 * GetVisualScale();
}

double VisualParams::GetDragThreshold() const
{
  return 10.0 * GetVisualScale();
}

VisualParams::VisualParams()
  : m_tileSize(0)
  , m_visualScale(0.0)
{
}

m2::RectD const & GetWorldRect()
{
  static m2::RectD const worldRect = MercatorBounds::FullRect();
  return worldRect;
}

int GetTileScaleBase(ScreenBase const & s, uint32_t tileSize)
{
  ScreenBase tmpS = s;
  tmpS.Rotate(-tmpS.GetAngle());

  // slightly smaller than original to produce "antialiasing" effect using bilinear filtration.
  int const halfSize = static_cast<int>(tileSize / 1.05 / 2.0);

  m2::RectD glbRect;
  m2::PointD const pxCenter = tmpS.PixelRect().Center();
  tmpS.PtoG(m2::RectD(pxCenter - m2::PointD(halfSize, halfSize),
                      pxCenter + m2::PointD(halfSize, halfSize)),
            glbRect);

  return GetTileScaleBase(glbRect);
}

int GetTileScaleBase(ScreenBase const & s)
{
  return GetTileScaleBase(s, VisualParams::Instance().GetTileSize());
}

int GetTileScaleBase(m2::RectD const & r)
{
  double const sz = max(r.SizeX(), r.SizeY());
  return max(1, my::rounds(log((MercatorBounds::maxX - MercatorBounds::minX) / sz) / log(2.0)));
}

int GetTileScaleIncrement(uint32_t tileSize, double visualScale)
{
  return log(tileSize / 256.0 / visualScale) / log(2.0);
}

int GetTileScaleIncrement()
{
  VisualParams const & p = VisualParams::Instance();
  return GetTileScaleIncrement(p.GetTileSize(), p.GetVisualScale());
}

m2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)
{
  // +1 - we will calculate half length for each side
  double const factor = 1 << (max(1, drawScale - GetTileScaleIncrement(tileSize, visualScale)) + 1);

  double const len = (MercatorBounds::maxX - MercatorBounds::minX) / factor;

  return m2::RectD(MercatorBounds::ClampX(center.x - len),
                   MercatorBounds::ClampY(center.y - len),
                   MercatorBounds::ClampX(center.x + len),
                   MercatorBounds::ClampY(center.y + len));
}

m2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center)
{
  VisualParams const & p = VisualParams::Instance();
  return GetRectForDrawScale(drawScale, center, p.GetTileSize(), p.GetVisualScale());
}

m2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)
{
  return GetRectForDrawScale(my::rounds(drawScale), center, tileSize, visualScale);
}

m2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center)
{
  return GetRectForDrawScale(my::rounds(drawScale), center);
}

int CalculateTileSize(int screenWidth, int screenHeight)
{
  int const maxSz = max(screenWidth, screenHeight);

  // we're calculating the tileSize based on (maxSz > 1024 ? rounded : ceiled)
  // to the nearest power of two value of the maxSz

  int const ceiledSz = 1 << static_cast<int>(ceil(log(double(maxSz + 1)) / log(2.0)));
  int res = 0;

  if (maxSz < 1024)
    res = ceiledSz;
  else
  {
    int const flooredSz = ceiledSz / 2;
    // rounding to the nearest power of two.
    if (ceiledSz - maxSz < maxSz - flooredSz)
      res = ceiledSz;
    else
      res = flooredSz;
  }

#ifndef OMIM_OS_DESKTOP
  return my::clamp(res / 2, 256, 1024);
#else
  return my::clamp(res / 2, 512, 1024);
#endif
}

int GetDrawTileScale(int baseScale, uint32_t tileSize, double visualScale)
{
  return max(1, baseScale + GetTileScaleIncrement(tileSize, visualScale));
}

int GetDrawTileScale(ScreenBase const & s, uint32_t tileSize, double visualScale)
{
  return GetDrawTileScale(GetTileScaleBase(s, tileSize), tileSize, visualScale);
}

int GetDrawTileScale(m2::RectD const & r, uint32_t tileSize, double visualScale)
{
  return GetDrawTileScale(GetTileScaleBase(r), tileSize, visualScale);
}

int GetDrawTileScale(int baseScale)
{
  VisualParams const & p = VisualParams::Instance();
  return GetDrawTileScale(baseScale, p.GetTileSize(), p.GetVisualScale());
}

int GetDrawTileScale(ScreenBase const & s)
{
  VisualParams const & p = VisualParams::Instance();
  return GetDrawTileScale(s, p.GetTileSize(), p.GetVisualScale());
}

int GetDrawTileScale(m2::RectD const & r)
{
  VisualParams const & p = VisualParams::Instance();
  return GetDrawTileScale(r, p.GetTileSize(), p.GetVisualScale());
}

} // namespace df
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_GMSH_HH
#define DUNE_STUFF_GRID_PROVIDER_GMSH_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#else
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#if HAVE_DUNE_GRID
#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID

#include <memory>
#include <sstream>
#include <type_traits>

#include <boost/assign/list_of.hpp>

#include <dune/common/parametertree.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>

#include <dune/grid/utility/structuredgridfactory.hh>
#include <dune/grid/sgrid.hh>
#include <dune/grid/io/file/gmshreader.hh>

#include <dune/stuff/common/parameter/tree.hh>

#include "interface.hh"

namespace Dune {
namespace Stuff {

/**
 * \brief   Gmsh grid provider
 */
#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridImp = Dune::GridSelector::GridType >
#else
template< class GridImp = Dune::SGrid< 2, 2 > >
#endif
class GridProviderGmsh
  : public GridProviderInterface< GridImp >
{
public:
  //! Type of the provided grid.
  typedef GridImp GridType;

  typedef GridProviderInterface< GridType > BaseType;

  typedef GridProviderGmsh< GridType > ThisType;

  //! Dimension of the provided grid.
  static const unsigned int dim = BaseType::dim;

  //! Type of the grids coordinates.
  typedef typename BaseType::CoordinateType CoordinateType;

  //! Unique identifier: \c stuff.grid.provider.gmsh
  static const std::string id()
  {
    return BaseType::id() + ".gmsh";
  }

  GridProviderGmsh(const std::string filename)
  {
    dune_static_assert(!(Dune::is_same< GridType, Dune::YaspGrid< dim > >::value), "GmshReader does not work with YaspGrid!");
    dune_static_assert(!(Dune::is_same< GridType, Dune::SGrid< 2, 2 > >::value), "GmshReader does not work with SGrid!");
    grid_ = std::shared_ptr< GridType >(GmshReader< GridType >::read(filename));
  }

  GridProviderGmsh(ThisType& other)
    : grid_(other.grid_)
  {}

  GridProviderGmsh(const ThisType& other)
    : grid_(other.grid_)
  {}

  static Dune::ParameterTree defaultSettings(const std::string subName = "")
  {
    Dune::ParameterTree description;
    description["filename"] = "path_to_g.msh";
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  } // ... createDefaultSettings(...)

  static ThisType* create(const Dune::ParameterTree& _settings, const std::string subName = id())
  {
    // get correct _settings
    Dune::Stuff::Common::ExtendedParameterTree settings;
    if (_settings.hasSub(subName))
      settings = _settings.sub(subName);
    else
      settings = _settings;
    // create and return
    if (!settings.hasKey("filename"))
      DUNE_THROW(Dune::RangeError,
                 "\nMissing key 'filename' in the following Dune::ParameterTree:\n" << settings.reportString("  "));
    const std::string filename = settings.get("filename", "meaningless_default_value");
    return new ThisType(filename);
  }

  ThisType& operator=(ThisType& other)
  {
    if (this != &other) {
      grid_ = other.grid();
    }
    return this;
  }

  //! access to shared ptr
  virtual std::shared_ptr<GridType> grid()
  {
    return grid_;
  }

  //! const access to shared ptr
  virtual const std::shared_ptr< const GridType > grid() const
  {
    return grid_;
  }

private:
  std::shared_ptr< GridType > grid_;
}; // class GridProviderGmsh

} // namespace Stuff
} // namespace Dune

#endif // HAVE_DUNE_GRID
#endif // defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID
#endif // HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG

#endif // DUNE_STUFF_GRID_PROVIDER_GMSH_HH
<commit_msg>[grid.provider.gmsh] removed SGrid default and some #ifdefs<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_GMSH_HH
#define DUNE_STUFF_GRID_PROVIDER_GMSH_HH

#if HAVE_DUNE_GRID

#include <memory>
#include <sstream>
#include <type_traits>

#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>

#include <dune/grid/utility/structuredgridfactory.hh>
#include <dune/grid/sgrid.hh>
#include <dune/grid/io/file/gmshreader.hh>

#include <dune/stuff/common/parameter/tree.hh>

#include "interface.hh"

namespace Dune {
namespace Stuff {

/**
 * \brief   Gmsh grid provider
 */
#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridImp = Dune::GridSelector::GridType >
#else
template< class GridImp >
#endif
class GridProviderGmsh
  : public GridProviderInterface< GridImp >
{
public:
  //! Type of the provided grid.
  typedef GridImp GridType;

  typedef GridProviderInterface< GridType > BaseType;

  typedef GridProviderGmsh< GridType > ThisType;

  //! Dimension of the provided grid.
  static const unsigned int dim = BaseType::dim;

  //! Type of the grids coordinates.
  typedef typename BaseType::CoordinateType CoordinateType;

  //! Unique identifier: \c stuff.grid.provider.gmsh
  static const std::string id()
  {
    return BaseType::id() + ".gmsh";
  }

  GridProviderGmsh(const std::string filename)
  {
    dune_static_assert(!(Dune::is_same< GridType, Dune::YaspGrid< dim > >::value),
                       "GmshReader does not work with YaspGrid!");
    dune_static_assert(!(Dune::is_same< GridType, Dune::SGrid< 2, 2 > >::value),
                       "GmshReader does not work with SGrid!");
    grid_ = std::shared_ptr< GridType >(GmshReader< GridType >::read(filename));
  }

  GridProviderGmsh(ThisType& other)
    : grid_(other.grid_)
  {}

  GridProviderGmsh(const ThisType& other)
    : grid_(other.grid_)
  {}

  static Dune::ParameterTree defaultSettings(const std::string subName = "")
  {
    Dune::ParameterTree description;
    description["filename"] = "path_to_g.msh";
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  } // ... createDefaultSettings(...)

  static ThisType* create(const Dune::ParameterTree& _settings, const std::string subName = id())
  {
    // get correct _settings
    Dune::Stuff::Common::ExtendedParameterTree settings;
    if (_settings.hasSub(subName))
      settings = _settings.sub(subName);
    else
      settings = _settings;
    // create and return
    if (!settings.hasKey("filename"))
      DUNE_THROW(Dune::RangeError,
                 "\nMissing key 'filename' in the following Dune::ParameterTree:\n" << settings.reportString("  "));
    const std::string filename = settings.get("filename", "meaningless_default_value");
    return new ThisType(filename);
  }

  ThisType& operator=(ThisType& other)
  {
    if (this != &other) {
      grid_ = other.grid();
    }
    return this;
  }

  //! access to shared ptr
  virtual std::shared_ptr<GridType> grid()
  {
    return grid_;
  }

  //! const access to shared ptr
  virtual const std::shared_ptr< const GridType > grid() const
  {
    return grid_;
  }

private:
  std::shared_ptr< GridType > grid_;
}; // class GridProviderGmsh

} // namespace Stuff
} // namespace Dune

#endif // HAVE_DUNE_GRID

#endif // DUNE_STUFF_GRID_PROVIDER_GMSH_HH
<|endoftext|>


<commit_before>#include <map>
#include <iostream>
#include <stdlib.h>
using namespace std;

float* def_variables(int ecozone, int forestmodel_data, int ifl, int climate, int plant_data, int lossyr)
{

	int model_years;    // How many loss years are in the model
    model_years = 15;

	int tropical;       // The ecozone code for the tropics
    tropical = 1;
    int temperate;      // The ecozone code for the temperate zone
    temperate = 3;
    int boreal;         // The ecozone code for the boreal zone
    boreal = 2;

	// returns Cf, CO2, CH4, N2O, peatburn, peat_drain_total
	float Cf;
	float CO2;
	float CH4;
	float N2O;
	float peatburn;
	float peat_drain_annual;
	float peat_drain_total;

	if ((forestmodel_data == 1) || (forestmodel_data == 2) || (forestmodel_data == 5)) // Commodities, shifting ag., or urbanization
	{
		if (ecozone == boreal) // Commodities/shifting ag/urbanization, boreal
		{
			Cf = 0.59;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 36;
		}
		else if (ecozone == temperate)// Commodities/shifting ag/urbanization, temperate
		{
			Cf = 0.51;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 31;
		}
		else if (ecozone == tropical) // Commodities/shifting ag/urbanization, tropics
		{
			CO2 = 1580;
			CH4 = 6.8;
			N2O = 0.2;
			peatburn = 163;

            if (plant_data == 1)  // Commodities/shifting ag/urbanization, tropics, oil palm
            {
                peat_drain_annual = 47;
            }
            else if (plant_data == 2) // Commodities/shifting ag/urbanization, tropics, wood fiber
            {
                peat_drain_annual = 80;
            }
            else // Commodities/shifting ag/urbanization, tropics, other plantation or no plantation
            {
                peat_drain_annual = 62;
            }
            peat_drain_total = (model_years - lossyr) * peat_drain_annual;

			if (ifl > 0)    // Commodities/shifting ag/urbanization, tropics, in IFL
			{
				Cf = 0.36;
			}
			else            // Commodities/shifting ag/urbanization, tropics, outside IFL
			{
				Cf = 0.55;
			}
		}
//        cout << "ecozone: " << ecozone << endl;
//        cout << "forestmodel_data: " << forestmodel_data << endl;
//        cout << "ifl: " << ifl << endl;
//        cout << "climate: " << climate << endl;
//        cout << "plant_data: " << plant_data << endl;
//        cout << "model_years: " << model_years << endl;
//        cout << "loss_yr: " << lossyr << endl;
//        cout << "peat_drain_annual: " << peat_drain_annual << endl;
//        cout << "peat_drain_total: " << peat_drain_total << endl;
	}

	else if (forestmodel_data == 3) // Forestry
	{

		if (ecozone == boreal) // Forestry, boreal
		{
			Cf = 0.33;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 3;
		}
		else if (ecozone == temperate)// Forestry, temperate
		{
			Cf = 0.62;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 12;
		}
		else if (ecozone == tropical) // Forestry, tropics
		{
			CO2 = 1580;
			CH4 = 6.8;
			N2O = 0.2;
			peatburn = 163;

			if (plant_data == 1) // Forestry, tropics, oil palm
            {
                peat_drain_annual = 45;
            }
            else if (plant_data == 2) // Forestry, tropics, wood fiber
            {
                peat_drain_annual = 79;
            }
            else // Forestry, tropics, other plantation or no plantation
            {
                peat_drain_annual = 60;
            }
            peat_drain_total = (model_years - lossyr) * peat_drain_annual;

			if (ifl > 0)
			{
				Cf = 0.36;      // Forestry, tropics, in IFL
			}
			else
			{
				Cf = 0.55;      // Forestry, tropics, outside IFL
			}
		}
//        cout << "ecozone: " << ecozone << endl;
//        cout << "forestmodel_data: " << forestmodel_data << endl;
//        cout << "ifl: " << ifl << endl;
//        cout << "climate: " << climate << endl;
//        cout << "plant_data: " << plant_data << endl;
//        cout << "model_years: " << model_years << endl;
//        cout << "loss_yr: " << lossyr << endl;
//        cout << "peat_drain_annual: " << peat_drain_annual << endl;
//        cout << "peat_drain_total: " << peat_drain_total << endl;
	}

	else if (forestmodel_data == 4) // Wildfire
	{

		if (ecozone == boreal) // Wildfire, boreal
		{
			Cf = 0.59;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 3;
		}
		else if (ecozone == temperate)// Wildfire, temperate
		{
			Cf = 0.51;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 12;
		}
		else if (ecozone == tropical) // Wildfire, tropics
		{
			CO2 = 1580;
			CH4 = 6.8;
			N2O = 0.2;
			peatburn = 371;

		    if (plant_data == 1) // Wildfire, tropics, oil palm
            {
                peat_drain_annual = 45;
            }
            else if (plant_data == 2) // Wildfire, tropics, wood fiber
            {
                peat_drain_annual = 79;
            }
            else // Wildfire, tropics, other plantation or no plantation
            {
                peat_drain_annual = 60;
            }
            peat_drain_total = (model_years - lossyr) * peat_drain_annual;

			if (ifl > 0)        // Wildfire, tropics, in IFL
			{
				Cf = 0.36;
			}
			else                // Wildfire, tropics, outside IFL
			{
				Cf = 0.55;
			}
		}
//        cout << "ecozone: " << ecozone << endl;
//        cout << "forestmodel_data: " << forestmodel_data << endl;
//        cout << "ifl: " << ifl << endl;
//        cout << "climate: " << climate << endl;
//        cout << "plant_data: " << plant_data << endl;
//        cout << "model_years: " << model_years << endl;
//        cout << "loss_yr: " << lossyr << endl;
//        cout << "peat_drain_annual: " << peat_drain_annual << endl;
//        cout << "peat_drain_total: " << peat_drain_total << endl;
	}

	else  // No driver-- same as forestry
	{
		if (ecozone == boreal) // No driver, boreal
		{
			Cf = 0.33;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 3;
		}
		else if (ecozone == temperate)// No driver, temperate
		{
			Cf = 0.62;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 12;
		}
		else if (ecozone == tropical) // No driver, tropics
		{
			CO2 = 1580;
			CH4 = 6.8;
			N2O = 0.2;
			peatburn = 163;

			if (plant_data == 1) // No driver, tropics, oil palm
            {
                peat_drain_annual = 45;
            }
            else if (plant_data == 2) // No driver, tropics, wood fiber
            {
                peat_drain_annual = 79;
            }
            else // No driver, tropics, other plantation or no plantation
            {
                peat_drain_annual = 60;
            }
            peat_drain_total = (model_years - lossyr) * peat_drain_annual;

			if (ifl > 0)
			{
				Cf = 0.36;      // No driver, tropics, in IFL
			}
			else
			{
				Cf = 0.55;      // No driver, tropics, outside IFL
			}
		}
//        cout << "ecozone: " << ecozone << endl;
//        cout << "forestmodel_data: " << forestmodel_data << endl;
//        cout << "ifl: " << ifl << endl;
//        cout << "climate: " << climate << endl;
//        cout << "plant_data: " << plant_data << endl;
//        cout << "model_years: " << model_years << endl;
//        cout << "loss_yr: " << lossyr << endl;
//        cout << "peat_drain_annual: " << peat_drain_annual << endl;
//        cout << "peat_drain_total: " << peat_drain_total << endl;
	}

//    cout << "ecozone end of fx: " << ecozone << endl;
//    cout << "forestmodel_data end of fx: " << forestmodel_data << endl;
//    cout << "ifl end of fx: " << ifl << endl;
//    cout << "climate end of fx: " << climate << endl;
//    cout << "plant_data end of fx: " << plant_data << endl;
//    cout << "model_years end of fx: " << model_years << endl;
//    cout << "loss_yr end of fx: " << lossyr << endl;

    float test;
    test = srand(time(0));

    cout << "cf end of fx: " << Cf << endl;
    cout << "gef_co2 end of fx: " << CO2 << endl;
    cout << "gef_Ch4 end of fx: " << CH4 << endl;
    cout << "gef_n2o end of fx: " << N2O << endl;
    cout << "peatburn end of fx: " << peatburn << endl;
    cout << "peat_drain_annual end of fx: " << peat_drain_annual << endl;
    cout << "peat_drain_total end of fx: " << peat_drain_total << endl;
    cout << "random_number end of fx: " << test << endl;
    cout << endl;

	static float def_variables[6] = {Cf, CO2, CH4, N2O, peatburn, test};

	return def_variables;

}<commit_msg>Peat drain values aren't being added to emissions. Trying to figure out why.<commit_after>#include <map>
#include <iostream>
#include <stdlib.h>
using namespace std;

float* def_variables(int ecozone, int forestmodel_data, int ifl, int climate, int plant_data, int lossyr)
{

	int model_years;    // How many loss years are in the model
    model_years = 15;

	int tropical;       // The ecozone code for the tropics
    tropical = 1;
    int temperate;      // The ecozone code for the temperate zone
    temperate = 3;
    int boreal;         // The ecozone code for the boreal zone
    boreal = 2;

	// returns Cf, CO2, CH4, N2O, peatburn, peat_drain_total
	float Cf;
	float CO2;
	float CH4;
	float N2O;
	float peatburn;
	float peat_drain_annual;
	float peat_drain_total;

	if ((forestmodel_data == 1) || (forestmodel_data == 2) || (forestmodel_data == 5)) // Commodities, shifting ag., or urbanization
	{
		if (ecozone == boreal) // Commodities/shifting ag/urbanization, boreal
		{
			Cf = 0.59;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 36;
		}
		else if (ecozone == temperate)// Commodities/shifting ag/urbanization, temperate
		{
			Cf = 0.51;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 31;
		}
		else if (ecozone == tropical) // Commodities/shifting ag/urbanization, tropics
		{
			CO2 = 1580;
			CH4 = 6.8;
			N2O = 0.2;
			peatburn = 163;

            if (plant_data == 1)  // Commodities/shifting ag/urbanization, tropics, oil palm
            {
                peat_drain_annual = 47;
            }
            else if (plant_data == 2) // Commodities/shifting ag/urbanization, tropics, wood fiber
            {
                peat_drain_annual = 80;
            }
            else // Commodities/shifting ag/urbanization, tropics, other plantation or no plantation
            {
                peat_drain_annual = 62;
            }
            peat_drain_total = (model_years - lossyr) * peat_drain_annual;

			if (ifl > 0)    // Commodities/shifting ag/urbanization, tropics, in IFL
			{
				Cf = 0.36;
			}
			else            // Commodities/shifting ag/urbanization, tropics, outside IFL
			{
				Cf = 0.55;
			}
		}
//        cout << "ecozone: " << ecozone << endl;
//        cout << "forestmodel_data: " << forestmodel_data << endl;
//        cout << "ifl: " << ifl << endl;
//        cout << "climate: " << climate << endl;
//        cout << "plant_data: " << plant_data << endl;
//        cout << "model_years: " << model_years << endl;
//        cout << "loss_yr: " << lossyr << endl;
//        cout << "peat_drain_annual: " << peat_drain_annual << endl;
//        cout << "peat_drain_total: " << peat_drain_total << endl;
	}

	else if (forestmodel_data == 3) // Forestry
	{

		if (ecozone == boreal) // Forestry, boreal
		{
			Cf = 0.33;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 3;
		}
		else if (ecozone == temperate)// Forestry, temperate
		{
			Cf = 0.62;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 12;
		}
		else if (ecozone == tropical) // Forestry, tropics
		{
			CO2 = 1580;
			CH4 = 6.8;
			N2O = 0.2;
			peatburn = 163;

			if (plant_data == 1) // Forestry, tropics, oil palm
            {
                peat_drain_annual = 45;
            }
            else if (plant_data == 2) // Forestry, tropics, wood fiber
            {
                peat_drain_annual = 79;
            }
            else // Forestry, tropics, other plantation or no plantation
            {
                peat_drain_annual = 60;
            }
            peat_drain_total = (model_years - lossyr) * peat_drain_annual;

			if (ifl > 0)
			{
				Cf = 0.36;      // Forestry, tropics, in IFL
			}
			else
			{
				Cf = 0.55;      // Forestry, tropics, outside IFL
			}
		}
//        cout << "ecozone: " << ecozone << endl;
//        cout << "forestmodel_data: " << forestmodel_data << endl;
//        cout << "ifl: " << ifl << endl;
//        cout << "climate: " << climate << endl;
//        cout << "plant_data: " << plant_data << endl;
//        cout << "model_years: " << model_years << endl;
//        cout << "loss_yr: " << lossyr << endl;
//        cout << "peat_drain_annual: " << peat_drain_annual << endl;
//        cout << "peat_drain_total: " << peat_drain_total << endl;
	}

	else if (forestmodel_data == 4) // Wildfire
	{

		if (ecozone == boreal) // Wildfire, boreal
		{
			Cf = 0.59;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 3;
		}
		else if (ecozone == temperate)// Wildfire, temperate
		{
			Cf = 0.51;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 12;
		}
		else if (ecozone == tropical) // Wildfire, tropics
		{
			CO2 = 1580;
			CH4 = 6.8;
			N2O = 0.2;
			peatburn = 371;

		    if (plant_data == 1) // Wildfire, tropics, oil palm
            {
                peat_drain_annual = 45;
            }
            else if (plant_data == 2) // Wildfire, tropics, wood fiber
            {
                peat_drain_annual = 79;
            }
            else // Wildfire, tropics, other plantation or no plantation
            {
                peat_drain_annual = 60;
            }
            peat_drain_total = (model_years - lossyr) * peat_drain_annual;

			if (ifl > 0)        // Wildfire, tropics, in IFL
			{
				Cf = 0.36;
			}
			else                // Wildfire, tropics, outside IFL
			{
				Cf = 0.55;
			}
		}
//        cout << "ecozone: " << ecozone << endl;
//        cout << "forestmodel_data: " << forestmodel_data << endl;
//        cout << "ifl: " << ifl << endl;
//        cout << "climate: " << climate << endl;
//        cout << "plant_data: " << plant_data << endl;
//        cout << "model_years: " << model_years << endl;
//        cout << "loss_yr: " << lossyr << endl;
//        cout << "peat_drain_annual: " << peat_drain_annual << endl;
//        cout << "peat_drain_total: " << peat_drain_total << endl;
	}

	else  // No driver-- same as forestry
	{
		if (ecozone == boreal) // No driver, boreal
		{
			Cf = 0.33;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 3;
		}
		else if (ecozone == temperate)// No driver, temperate
		{
			Cf = 0.62;
			CO2 = 1569;
			CH4 = 4.7;
			N2O = 0.26;
			peatburn = 41;
			peat_drain_total = (model_years - lossyr) * 12;
		}
		else if (ecozone == tropical) // No driver, tropics
		{
			CO2 = 1580;
			CH4 = 6.8;
			N2O = 0.2;
			peatburn = 163;

			if (plant_data == 1) // No driver, tropics, oil palm
            {
                peat_drain_annual = 45;
            }
            else if (plant_data == 2) // No driver, tropics, wood fiber
            {
                peat_drain_annual = 79;
            }
            else // No driver, tropics, other plantation or no plantation
            {
                peat_drain_annual = 60;
            }
            peat_drain_total = (model_years - lossyr) * peat_drain_annual;

			if (ifl > 0)
			{
				Cf = 0.36;      // No driver, tropics, in IFL
			}
			else
			{
				Cf = 0.55;      // No driver, tropics, outside IFL
			}
		}
//        cout << "ecozone: " << ecozone << endl;
//        cout << "forestmodel_data: " << forestmodel_data << endl;
//        cout << "ifl: " << ifl << endl;
//        cout << "climate: " << climate << endl;
//        cout << "plant_data: " << plant_data << endl;
//        cout << "model_years: " << model_years << endl;
//        cout << "loss_yr: " << lossyr << endl;
//        cout << "peat_drain_annual: " << peat_drain_annual << endl;
//        cout << "peat_drain_total: " << peat_drain_total << endl;
	}

//    cout << "ecozone end of fx: " << ecozone << endl;
//    cout << "forestmodel_data end of fx: " << forestmodel_data << endl;
//    cout << "ifl end of fx: " << ifl << endl;
//    cout << "climate end of fx: " << climate << endl;
//    cout << "plant_data end of fx: " << plant_data << endl;
//    cout << "model_years end of fx: " << model_years << endl;
//    cout << "loss_yr end of fx: " << lossyr << endl;

    float test;
    srand(time(0));
    test = rand();

    cout << "cf end of fx: " << Cf << endl;
    cout << "gef_co2 end of fx: " << CO2 << endl;
    cout << "gef_Ch4 end of fx: " << CH4 << endl;
    cout << "gef_n2o end of fx: " << N2O << endl;
    cout << "peatburn end of fx: " << peatburn << endl;
    cout << "peat_drain_annual end of fx: " << peat_drain_annual << endl;
    cout << "peat_drain_total end of fx: " << peat_drain_total << endl;
    cout << "random_number end of fx: " << test << endl;
    cout << endl;

	static float def_variables[6] = {Cf, CO2, CH4, N2O, peatburn, test};

	return def_variables;

}<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2005-2008 by the FIFE team                              *
 *   http://www.fifengine.de                                               *
 *   This file is part of FIFE.                                            *
 *                                                                         *
 *   FIFE 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.1 of the License, or (at your option) any later version.    *
 *                                                                         *
 *   This library 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 library; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
 ***************************************************************************/

// Standard C++ library includes
#include <fstream>

// 3rd party library includes
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/version.hpp>

// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "vfs/raw/rawdata.h"
#include "vfs/raw/rawdatafile.h"
#include "util/log/logger.h"
#include "util/base/exception.h"
#include "vfsdirectory.h"

namespace
{
    // grab the major and minor version of boost, taken from boost/version.hpp
#define BOOST_MAJOR_VERSION BOOST_VERSION / 100000
#define BOOST_MINOR_VERSION BOOST_VERSION / 100 % 1000

#if (BOOST_MAJOR_VERSION >= 1 && BOOST_MINOR_VERSION >= 36)
    #define USE_NEW_BOOST_FILESYSTEM
#endif
}

namespace bfs = boost::filesystem;
namespace FIFE {
	static Logger _log(LM_VFS);

	VFSDirectory::VFSDirectory(VFS* vfs, const std::string& root) : VFSSource(vfs), m_root(root) {
		FL_DBG(_log, LMsg("VFSDirectory created with root path ") << m_root);
		if(!m_root.empty() && *(m_root.end() - 1) != '/')
			m_root.append(1,'/');
	}

	VFSDirectory::~VFSDirectory() {
	}

	bool VFSDirectory::fileExists(const std::string& name) const {
		std::string fullpath = m_root + name;
		std::ifstream file(fullpath.c_str());
		if (file)
			return true;

		return false;
	}

	RawData* VFSDirectory::open(const std::string& file) const {
		return new RawData(new RawDataFile(m_root + file));
	}

	std::set<std::string> VFSDirectory::listFiles(const std::string& path) const {
		return list(path, false);
	}

	std::set<std::string> VFSDirectory::listDirectories(const std::string& path) const {
		return list(path, true);
	}

	std::set<std::string> VFSDirectory::list(const std::string& path, bool directorys) const {
		std::set<std::string> list;
		std::string dir = m_root;

		// Avoid double slashes
		if(path[0] == '/' && m_root[m_root.size()-1] == '/') {
			dir.append(path.substr(1));
		}
		else {
			dir.append(path);
		}

		try {
			bfs::path boost_path(dir);
			if (!bfs::exists(boost_path) || !bfs::is_directory(boost_path))
				return list;

			bfs::directory_iterator end;
			for	(bfs::directory_iterator i(boost_path); i != end; ++i) {
				if (bfs::is_directory(*i) != directorys)
					continue;

#if defined(USE_NEW_BOOST_FILESYSTEM)
                // the new way to get a filename using 1.36 and above
                list.insert(i->path().filename());
#else
                // the old way to get a filename in version 1.35 and below
                list.insert(i->leaf());
#endif
			}
		}
		catch (const bfs::filesystem_error& ex) {
			throw Exception(ex.what());
		}

		return list;
	}
}
<commit_msg>Fixed the VFSDirectory so that it is compatible with the different versions of boost::filesystem. It chooses the correct functions based on the boost version being used. This is the same fix that was applied to the trunk. closes[t:529]<commit_after>/***************************************************************************
 *   Copyright (C) 2005-2008 by the FIFE team                              *
 *   http://www.fifengine.de                                               *
 *   This file is part of FIFE.                                            *
 *                                                                         *
 *   FIFE 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.1 of the License, or (at your option) any later version.    *
 *                                                                         *
 *   This library 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 library; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
 ***************************************************************************/

// Standard C++ library includes
#include <fstream>

// 3rd party library includes
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/version.hpp>

// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "vfs/raw/rawdata.h"
#include "vfs/raw/rawdatafile.h"
#include "util/log/logger.h"
#include "util/base/exception.h"
#include "vfsdirectory.h"

namespace bfs = boost::filesystem;

namespace
{
    // grab the major and minor version of boost,
    // calculations taken from boost/version.hpp
    #define BOOST_MAJOR_VERSION BOOST_VERSION / 100000
    #define BOOST_MINOR_VERSION BOOST_VERSION / 100 % 1000

#if (BOOST_MAJOR_VERSION >= 1 && BOOST_MINOR_VERSION >= 46)
    // this define will tell us to use boost filesystem
    // version 3 since this is the default version of the library
    // starting in boost version 1.46 and above
    #define USE_BOOST_FILESYSTEM_V3
#elif (BOOST_MAJOR_VERSION >= 1 && BOOST_MINOR_VERSION >= 36)
    // this define will tell us not to use the deprecated functions
    // in boost filesystem version 2 library which were introduced
    // in boost version 1.36 and above
    #define USE_NON_DEPRECATED_BOOST_FILESYSTEM_V2
#endif
}

namespace FIFE {
	static Logger _log(LM_VFS);

	VFSDirectory::VFSDirectory(VFS* vfs, const std::string& root) : VFSSource(vfs), m_root(root) {
		FL_DBG(_log, LMsg("VFSDirectory created with root path ") << m_root);
		if(!m_root.empty() && *(m_root.end() - 1) != '/')
			m_root.append(1,'/');
	}

	VFSDirectory::~VFSDirectory() {
	}

	bool VFSDirectory::fileExists(const std::string& name) const {
		std::string fullpath = m_root + name;
		std::ifstream file(fullpath.c_str());
		if (file)
			return true;

		return false;
	}

	RawData* VFSDirectory::open(const std::string& file) const {
		return new RawData(new RawDataFile(m_root + file));
	}

	std::set<std::string> VFSDirectory::listFiles(const std::string& path) const {
		return list(path, false);
	}

	std::set<std::string> VFSDirectory::listDirectories(const std::string& path) const {
		return list(path, true);
	}

	std::set<std::string> VFSDirectory::list(const std::string& path, bool directorys) const {
		std::set<std::string> list;
		std::string dir = m_root;

		// Avoid double slashes
		if(path[0] == '/' && m_root[m_root.size()-1] == '/') {
			dir.append(path.substr(1));
		}
		else {
			dir.append(path);
		}

		try {
			bfs::path boost_path(dir);
			if (!bfs::exists(boost_path) || !bfs::is_directory(boost_path))
				return list;

			bfs::directory_iterator end;
			for	(bfs::directory_iterator i(boost_path); i != end; ++i) {
				if (bfs::is_directory(*i) != directorys)
					continue;

#if defined(USE_BOOST_FILESYSTEM_V3)
                // boost version 1.46 and above uses
                // boost filesystem version 3 as the default
                // which has yet a different way of getting
                // a filename string
                bfs::path filenamePath = i->path().filename();
                list.insert(filenamePath.string());
#elif defined(USE_NON_DEPRECATED_BOOST_FILESYSTEM_V2)
                // the new way in boost filesystem version 2
                // to get a filename string
                //(this is for boost version 1.36 and above)
                list.insert(i->path().filename());
#else
                // the old way in boost filesystem version 2
                // to get a filename string
                //(this is for boost version 1.35 and below)
                list.insert(i->leaf());
#endif
			}
		}
		catch (const bfs::filesystem_error& ex) {
			throw Exception(ex.what());
		}

		return list;
	}
}
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include <memory>
#include <string>
#include <cstdint>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "tests/utils/MockObjects.h"
#include "joynr/tests/testProvider.h"
#include "joynr/tests/testProxy.h"
#include "joynr/vehicle/GpsProxy.h"
#include "joynr/types/ProviderQos.h"
#include "joynr/Future.h"
#include "joynr/OnChangeWithKeepAliveSubscriptionQos.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/PrivateCopyAssign.h"
#include "tests/JoynrTest.h"

using namespace ::testing;

using namespace joynr;

class End2EndRPCTest : public TestWithParam< std::string >{
public:
    std::string domain;
    std::shared_ptr<JoynrClusterControllerRuntime> runtime;
    std::shared_ptr<vehicle::GpsProvider> gpsProvider;

    End2EndRPCTest() :
        domain(),
        runtime()
    {
        runtime = std::make_shared<JoynrClusterControllerRuntime>(
                    std::make_unique<Settings>(GetParam())
        );
        runtime->init();
        domain = "cppEnd2EndRPCTest_Domain_" + util::createUuid();

        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
        discoveryQos.setDiscoveryTimeoutMs(3000);
    }
    // Sets up the test fixture.
    void SetUp(){
       runtime->start();
    }

    // Tears down the test fixture.
    void TearDown(){
        bool deleteChannel = true;
        runtime->stop(deleteChannel);

        // Delete persisted files
        std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());

        std::this_thread::sleep_for(std::chrono::milliseconds(550));
    }

    ~End2EndRPCTest() = default;
protected:

    joynr::DiscoveryQos discoveryQos;

private:
    DISALLOW_COPY_AND_ASSIGN(End2EndRPCTest);
};

// leadsm to assert failure in GpsInProcessConnector line 185: not yet implemented in connector
TEST_P(End2EndRPCTest, call_rpc_method_and_get_expected_result)
{

    auto mockProvider = std::make_shared<MockGpsProvider>();

    types::ProviderQos providerQos;
    std::chrono::milliseconds millisSinceEpoch =
        std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::system_clock::now().time_since_epoch());
    providerQos.setPriority(millisSinceEpoch.count());
    providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
    providerQos.setSupportsOnChangeSubscriptions(true);
    std::string participantId = runtime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);
    std::this_thread::sleep_for(std::chrono::milliseconds(550));

    std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =
            runtime->createProxyBuilder<vehicle::GpsProxy>(domain);

    std::int64_t qosRoundTripTTL = 40000;
    std::shared_ptr<vehicle::GpsProxy> gpsProxy = gpsProxyBuilder
            ->setMessagingQos(MessagingQos(qosRoundTripTTL))
            ->setDiscoveryQos(discoveryQos)
            ->build();
    std::shared_ptr<Future<int> >gpsFuture (gpsProxy->calculateAvailableSatellitesAsync());
    gpsFuture->wait();
    int expectedValue = 42; //as defined in MockGpsProvider
    int actualValue;
    gpsFuture->get(actualValue);
    EXPECT_EQ(expectedValue, actualValue);
    // This is not yet implemented in CapabilitiesClient
    // runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
    runtime->unregisterProvider(participantId);
}

TEST_P(End2EndRPCTest, call_void_operation)
{
    auto mockProvider = std::make_shared<MockTestProvider>();

    types::ProviderQos providerQos;
    std::chrono::milliseconds millisSinceEpoch =
        std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::system_clock::now().time_since_epoch());
    providerQos.setPriority(millisSinceEpoch.count());
    providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
    providerQos.setSupportsOnChangeSubscriptions(true);
    std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);
    std::this_thread::sleep_for(std::chrono::milliseconds(550));

    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>(domain);

    std::int64_t qosRoundTripTTL = 40000;
    std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder
            ->setMessagingQos(MessagingQos(qosRoundTripTTL))
            ->setDiscoveryQos(discoveryQos)
            ->build();
    testProxy->voidOperation();
//    EXPECT_EQ(expectedValue, gpsFuture->getValue());
    // This is not yet implemented in CapabilitiesClient
    // runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
    runtime->unregisterProvider(participantId);
}

// tests in process subscription
TEST_P(End2EndRPCTest, _call_subscribeTo_and_get_expected_result)
{
    auto mockProvider = std::make_shared<MockTestProvider>();
    types::ProviderQos providerQos;
    std::chrono::milliseconds millisSinceEpoch =
        std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::system_clock::now().time_since_epoch());
    providerQos.setPriority(millisSinceEpoch.count());
    providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
    providerQos.setSupportsOnChangeSubscriptions(true);
    std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);

    std::this_thread::sleep_for(std::chrono::milliseconds(550));

    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>(domain);

    std::int64_t qosRoundTripTTL = 40000;
    std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder
            ->setMessagingQos(MessagingQos(qosRoundTripTTL))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    MockGpsSubscriptionListener* mockListener = new MockGpsSubscriptionListener();
    std::shared_ptr<ISubscriptionListener<types::Localisation::GpsLocation> > subscriptionListener(
                mockListener);

    EXPECT_CALL(*mockListener, onReceive(A<const types::Localisation::GpsLocation&>()))
            .Times(AtLeast(2));

    auto subscriptionQos = std::make_shared<OnChangeWithKeepAliveSubscriptionQos>(
                800, // validity_ms
                1000, // publication ttl
                100, // minInterval_ms
                200, // maxInterval_ms
                1000 // alertInterval_ms
    );
    std::shared_ptr<Future<std::string>> subscriptionIdFuture = testProxy->subscribeToLocation(subscriptionListener, subscriptionQos);
    std::this_thread::sleep_for(std::chrono::milliseconds(1500));
    // This is not yet implemented in CapabilitiesClient
    // runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
    std::string subscriptionId;
    JOYNR_ASSERT_NO_THROW(subscriptionIdFuture->get(5000, subscriptionId));
    JOYNR_ASSERT_NO_THROW(testProxy->unsubscribeFromLocation(subscriptionId));
    runtime->unregisterProvider(participantId);
}

INSTANTIATE_TEST_CASE_P(Http,
        End2EndRPCTest,
        testing::Values(
            "test-resources/HttpSystemIntegrationTest1.settings"
        )
);

INSTANTIATE_TEST_CASE_P(Mqtt,
        End2EndRPCTest,
        testing::Values(
            "test-resources/MqttSystemIntegrationTest1.settings"
        )
);
<commit_msg>[C++] Fixed End2EndRPCTest<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include <memory>
#include <string>
#include <cstdint>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "tests/utils/MockObjects.h"
#include "joynr/tests/testProvider.h"
#include "joynr/tests/testProxy.h"
#include "joynr/vehicle/GpsProxy.h"
#include "joynr/types/ProviderQos.h"
#include "joynr/Future.h"
#include "joynr/OnChangeWithKeepAliveSubscriptionQos.h"
#include "joynr/LibjoynrSettings.h"
#include "joynr/PrivateCopyAssign.h"
#include "tests/JoynrTest.h"

using namespace ::testing;

using namespace joynr;

class End2EndRPCTest : public TestWithParam< std::string >{
public:
    std::string domain;
    std::shared_ptr<JoynrClusterControllerRuntime> runtime;
    std::shared_ptr<vehicle::GpsProvider> gpsProvider;

    End2EndRPCTest() :
        domain(),
        runtime()
    {
        runtime = std::make_shared<JoynrClusterControllerRuntime>(
                    std::make_unique<Settings>(GetParam())
        );
        runtime->init();
        domain = "cppEnd2EndRPCTest_Domain_" + util::createUuid();

        discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);
        discoveryQos.setDiscoveryTimeoutMs(3000);
    }
    // Sets up the test fixture.
    void SetUp(){
       runtime->start();
    }

    // Tears down the test fixture.
    void TearDown(){
        bool deleteChannel = true;
        runtime->stop(deleteChannel);
        runtime.reset();

        // Delete persisted files
        std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());
        std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());

        std::this_thread::sleep_for(std::chrono::milliseconds(550));
    }

    ~End2EndRPCTest() = default;
protected:

    joynr::DiscoveryQos discoveryQos;

private:
    DISALLOW_COPY_AND_ASSIGN(End2EndRPCTest);
};

// leadsm to assert failure in GpsInProcessConnector line 185: not yet implemented in connector
TEST_P(End2EndRPCTest, call_rpc_method_and_get_expected_result)
{

    auto mockProvider = std::make_shared<MockGpsProvider>();

    types::ProviderQos providerQos;
    std::chrono::milliseconds millisSinceEpoch =
        std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::system_clock::now().time_since_epoch());
    providerQos.setPriority(millisSinceEpoch.count());
    providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
    providerQos.setSupportsOnChangeSubscriptions(true);
    std::string participantId = runtime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);
    std::this_thread::sleep_for(std::chrono::milliseconds(550));

    std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =
            runtime->createProxyBuilder<vehicle::GpsProxy>(domain);

    std::int64_t qosRoundTripTTL = 40000;
    std::shared_ptr<vehicle::GpsProxy> gpsProxy = gpsProxyBuilder
            ->setMessagingQos(MessagingQos(qosRoundTripTTL))
            ->setDiscoveryQos(discoveryQos)
            ->build();
    std::shared_ptr<Future<int> >gpsFuture (gpsProxy->calculateAvailableSatellitesAsync());
    gpsFuture->wait();
    int expectedValue = 42; //as defined in MockGpsProvider
    int actualValue;
    gpsFuture->get(actualValue);
    EXPECT_EQ(expectedValue, actualValue);
    // This is not yet implemented in CapabilitiesClient
    // runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
    runtime->unregisterProvider(participantId);
}

TEST_P(End2EndRPCTest, call_void_operation)
{
    auto mockProvider = std::make_shared<MockTestProvider>();

    types::ProviderQos providerQos;
    std::chrono::milliseconds millisSinceEpoch =
        std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::system_clock::now().time_since_epoch());
    providerQos.setPriority(millisSinceEpoch.count());
    providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
    providerQos.setSupportsOnChangeSubscriptions(true);
    std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);
    std::this_thread::sleep_for(std::chrono::milliseconds(550));

    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>(domain);

    std::int64_t qosRoundTripTTL = 40000;
    std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder
            ->setMessagingQos(MessagingQos(qosRoundTripTTL))
            ->setDiscoveryQos(discoveryQos)
            ->build();
    testProxy->voidOperation();
//    EXPECT_EQ(expectedValue, gpsFuture->getValue());
    // This is not yet implemented in CapabilitiesClient
    // runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
    runtime->unregisterProvider(participantId);
}

// tests in process subscription
TEST_P(End2EndRPCTest, _call_subscribeTo_and_get_expected_result)
{
    auto mockProvider = std::make_shared<MockTestProvider>();
    types::ProviderQos providerQos;
    std::chrono::milliseconds millisSinceEpoch =
        std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::system_clock::now().time_since_epoch());
    providerQos.setPriority(millisSinceEpoch.count());
    providerQos.setScope(joynr::types::ProviderScope::GLOBAL);
    providerQos.setSupportsOnChangeSubscriptions(true);
    std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);

    std::this_thread::sleep_for(std::chrono::milliseconds(550));

    std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =
            runtime->createProxyBuilder<tests::testProxy>(domain);

    std::int64_t qosRoundTripTTL = 40000;
    std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder
            ->setMessagingQos(MessagingQos(qosRoundTripTTL))
            ->setDiscoveryQos(discoveryQos)
            ->build();

    MockGpsSubscriptionListener* mockListener = new MockGpsSubscriptionListener();
    std::shared_ptr<ISubscriptionListener<types::Localisation::GpsLocation> > subscriptionListener(
                mockListener);

    EXPECT_CALL(*mockListener, onReceive(A<const types::Localisation::GpsLocation&>()))
            .Times(AtLeast(2));

    auto subscriptionQos = std::make_shared<OnChangeWithKeepAliveSubscriptionQos>(
                800, // validity_ms
                1000, // publication ttl
                100, // minInterval_ms
                200, // maxInterval_ms
                1000 // alertInterval_ms
    );
    std::shared_ptr<Future<std::string>> subscriptionIdFuture = testProxy->subscribeToLocation(subscriptionListener, subscriptionQos);
    std::this_thread::sleep_for(std::chrono::milliseconds(1500));
    // This is not yet implemented in CapabilitiesClient
    // runtime->unregisterProvider("Fake_ParticipantId_vehicle/gpsDummyProvider");
    std::string subscriptionId;
    JOYNR_ASSERT_NO_THROW(subscriptionIdFuture->get(5000, subscriptionId));
    JOYNR_ASSERT_NO_THROW(testProxy->unsubscribeFromLocation(subscriptionId));
    runtime->unregisterProvider(participantId);
}

INSTANTIATE_TEST_CASE_P(Http,
        End2EndRPCTest,
        testing::Values(
            "test-resources/HttpSystemIntegrationTest1.settings"
        )
);

INSTANTIATE_TEST_CASE_P(Mqtt,
        End2EndRPCTest,
        testing::Values(
            "test-resources/MqttSystemIntegrationTest1.settings"
        )
);
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE test_function

#include <stdexcept>
#include <boost/test/included/unit_test.hpp>

#include "variable.hxx"
#include "coreutils.hxx"

double sum(std::vector<double> & args)
{
  double res(0.);
  for (unsigned i = 0; i < args.size(); ++i) {
    res += double(args[i]);
  }
  return res;
}

struct fnsetup {
  fnsetup() : myfunc(NULL)
  {
    double array[3] = {1, 2, 3};
    myfunc = &make_function(sum, 3, array);
  }
  ~fnsetup() {}
  function * myfunc;
};

BOOST_AUTO_TEST_SUITE(test)

BOOST_FIXTURE_TEST_CASE(automatic_conversion, fnsetup)
{
  BOOST_CHECK_EQUAL(6.0, *myfunc); // 1+2+3
}

BOOST_FIXTURE_TEST_CASE(direct_access, fnsetup)
{
  auto& vars = myfunc->components();
  vars[1] = fnbase_ptr(new variable(3));
  vars[2] = fnbase_ptr(new variable(5));
  BOOST_CHECK_EQUAL(9, *myfunc); // 1+3+5
}

BOOST_FIXTURE_TEST_CASE(setter_access, fnsetup)
{
  for (unsigned i = 0; i < 3; ++i) {
    myfunc->replace(i, new variable((i+1) * 2));
  }
  BOOST_CHECK_EQUAL(12, *myfunc); // 2+4+6
}

BOOST_AUTO_TEST_CASE(functional)
{
  double array[3] = {1, 2, 3};
  function myfunc1 = make_function(sum, 3, array); // 1+2+3
  function myfunc2 = make_function(sum, 3, array); // 1+2+3
  fnbase_vec vars {fnbase_ptr(&myfunc1), fnbase_ptr(&myfunc2)};
  function * grandsum = new function(sum, vars); // 6+6
  BOOST_CHECK_EQUAL(12, *grandsum);
}

BOOST_FIXTURE_TEST_CASE(assignment_operator, fnsetup)
{
  function newfn = *myfunc;
  BOOST_CHECK_EQUAL(*myfunc, newfn);
}

BOOST_FIXTURE_TEST_CASE(index_out_of_range_exception, fnsetup)
{
  BOOST_REQUIRE_THROW(myfunc->replace(3, new variable(2)),
		      std::out_of_range);
  // BOOST_REQUIRE_EXCEPTION(myfunc->replace(3, new variable(2)),
  // 			  std::out_of_range, predicate);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add test for memory problem in case of funcitonals<commit_after>#define BOOST_TEST_MODULE test_function

#include <stdexcept>
#include <boost/test/included/unit_test.hpp>

#include "variable.hxx"
#include "coreutils.hxx"

double sum(std::vector<double> & args)
{
  double res(0.);
  for (unsigned i = 0; i < args.size(); ++i) {
    res += double(args[i]);
  }
  return res;
}

struct fnsetup {
  fnsetup() : myfunc(NULL)
  {
    double array[3] = {1, 2, 3};
    myfunc = &make_function(sum, 3, array);
  }
  ~fnsetup() {}
  function * myfunc;
};

BOOST_AUTO_TEST_SUITE(test)

BOOST_AUTO_TEST_CASE(base_class)
{
  double array[3] = {1, 2, 3};
  function myfunc1 = make_function(sum, 3, array); // 1+2+3
  function myfunc2 = make_function(sum, 3, array); // 1+2+3
  fnbase_vec vars {fnbase_ptr(&myfunc1), fnbase_ptr(&myfunc2)};
  function grandsum(sum, vars); // 6+6
  BOOST_CHECK_EQUAL(12, grandsum);
  // function * grandsum = new function(sum, vars); // 6+6
  // BOOST_CHECK_EQUAL(12, *grandsum);
}

BOOST_FIXTURE_TEST_CASE(automatic_conversion, fnsetup)
{
  BOOST_CHECK_EQUAL(6.0, *myfunc); // 1+2+3
}

BOOST_FIXTURE_TEST_CASE(direct_access, fnsetup)
{
  auto& vars = myfunc->components();
  vars[1] = fnbase_ptr(new variable(3));
  vars[2] = fnbase_ptr(new variable(5));
  BOOST_CHECK_EQUAL(9, *myfunc); // 1+3+5
}

BOOST_FIXTURE_TEST_CASE(setter_access, fnsetup)
{
  for (unsigned i = 0; i < 3; ++i) {
    myfunc->replace(i, new variable((i+1) * 2));
  }
  BOOST_CHECK_EQUAL(12, *myfunc); // 2+4+6
}

BOOST_AUTO_TEST_CASE(functional)
{
  double array[3] = {1, 2, 3};
  function myfunc1 = make_function(sum, 3, array); // 1+2+3
  function myfunc2 = make_function(sum, 3, array); // 1+2+3
  fnbase_vec vars {fnbase_ptr(&myfunc1), fnbase_ptr(&myfunc2)};
  function * grandsum = new function(sum, vars); // 6+6
  BOOST_CHECK_EQUAL(12, *grandsum);
}

BOOST_FIXTURE_TEST_CASE(assignment_operator, fnsetup)
{
  function newfn = *myfunc;
  BOOST_CHECK_EQUAL(*myfunc, newfn);
}

BOOST_FIXTURE_TEST_CASE(index_out_of_range_exception, fnsetup)
{
  BOOST_REQUIRE_THROW(myfunc->replace(3, new variable(2)),
		      std::out_of_range);
  // BOOST_REQUIRE_EXCEPTION(myfunc->replace(3, new variable(2)),
  // 			  std::out_of_range, predicate);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*
 * MIT License
 *
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <map>
#include <signal.h>
#include <iostream>
#include "Common/config.h"

#ifdef ENABLE_OPENSSL
#include "Util/SSLBox.h"
#include "Http/HttpsSession.h"
#endif//ENABLE_OPENSSL

#include "Util/File.h"
#include "Util/logger.h"
#include "Util/onceToken.h"
#include "Network/TcpServer.h"
#include "Poller/EventPoller.h"
#include "Thread/WorkThreadPool.h"
#include "Util/NoticeCenter.h"

using namespace std;
using namespace ZL::Util;
using namespace ZL::Http;
using namespace ZL::Thread;
using namespace ZL::Network;

static onceToken s_token([](){
    NoticeCenter::Instance().addListener(nullptr,Config::Broadcast::kBroadcastHttpRequest,[](BroadcastHttpRequestArgs){
        //const Parser &parser,HttpSession::HttpResponseInvoker &invoker,bool &consumed
        if(strstr(parser.Url().data(),"/api/") != parser.Url().data()){
            return;
        }
        //url以"/api/起始，说明是http api"
        consumed = true;//该http请求已被消费

        _StrPrinter printer;
        ////////////////method////////////////////
        printer << "\r\nmethod:\r\n\t" << parser.Method();
        ////////////////url/////////////////
        printer << "\r\nurl:\r\n\t" << parser.Url();
        ////////////////protocol/////////////////
        printer << "\r\nprotocol:\r\n\t" << parser.Tail();
        ///////////////args//////////////////
        printer << "\r\nargs:\r\n";
        for(auto &pr : parser.getUrlArgs()){
            printer <<  "\t" << pr.first << " : " << pr.second << "\r\n";
        }
        ///////////////header//////////////////
        printer << "\r\nheader:\r\n";
        for(auto &pr : parser.getValues()){
            printer <<  "\t" << pr.first << " : " << pr.second << "\r\n";
        }
        ////////////////content/////////////////
        printer << "\r\ncontent:\r\n" << parser.Content();
        auto contentOut = printer << endl;

        ////////////////我们测算异步回复，当然你也可以同步回复/////////////////
        EventPoller::Instance().sync([invoker,contentOut](){
            HttpSession::KeyValue headerOut;
			//你可以自定义header,如果跟默认header重名，则会覆盖之
			//默认header有:Server,Connection,Date,Content-Type,Content-Length
			//请勿覆盖Connection、Content-Length键
			//键名覆盖时不区分大小写
            headerOut["TestHeader"] = "HeaderValue";
            invoker("200 OK",headerOut,contentOut);
        });
    });
}, nullptr);

int main(int argc,char *argv[]){
	//设置退出信号处理函数
	signal(SIGINT, [](int){EventPoller::Instance().shutdown();});
	//设置日志
	Logger::Instance().add(std::make_shared<ConsoleChannel>("stdout", LTrace));
    Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
	//加载配置文件，如果配置文件不存在就创建一个
	Config::loadIniConfig();

#ifdef ENABLE_OPENSSL
	//请把证书"test_httpApi.pem"放置在本程序可执行程序同目录下
	try{
		//加载证书，证书包含公钥和私钥
		SSL_Initor::Instance().loadServerPem((exePath() + ".pem").data());
	}catch(...){
		FatalL << "请把证书:" << (exeName() + ".pem") << "放置在本程序可执行程序同目录下:" << exeDir() << endl;
		return 0;
	}
#endif //ENABLE_OPENSSL

	//开启http服务器
	TcpServer<HttpSession>::Ptr httpSrv(new TcpServer<HttpSession>());
	httpSrv->start(mINI::Instance()[Config::Http::kPort]);//默认80

#ifdef ENABLE_OPENSSL
    //如果支持ssl，还可以开启https服务器
	TcpServer<HttpsSession>::Ptr httpsSrv(new TcpServer<HttpsSession>());
	httpsSrv->start(mINI::Instance()[Config::Http::kSSLPort]);//默认443
#endif //ENABLE_OPENSSL

	InfoL << "你可以在浏览器输入:http://127.0.0.1/api/my_api?key0=val0&key1=参数1" << endl;

	EventPoller::Instance().runLoop();

	static onceToken s_token(nullptr,[]() {
		//TcpServer用到了WorkThreadPool
		WorkThreadPool::Destory();
		EventPoller::Destory();
		Logger::Destory();
	});
	return 0;
}

<commit_msg>修复编译不过的bug<commit_after>/*
 * MIT License
 *
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <map>
#include <signal.h>
#include <iostream>
#include "Common/config.h"
#include "Http/HttpSession.h"
#ifdef ENABLE_OPENSSL
#include "Util/SSLBox.h"
#include "Http/HttpsSession.h"
#endif//ENABLE_OPENSSL

#include "Util/File.h"
#include "Util/logger.h"
#include "Util/onceToken.h"
#include "Network/TcpServer.h"
#include "Poller/EventPoller.h"
#include "Thread/WorkThreadPool.h"
#include "Util/NoticeCenter.h"

using namespace std;
using namespace ZL::Util;
using namespace ZL::Http;
using namespace ZL::Thread;
using namespace ZL::Network;

static onceToken s_token([](){
    NoticeCenter::Instance().addListener(nullptr,Config::Broadcast::kBroadcastHttpRequest,[](BroadcastHttpRequestArgs){
        //const Parser &parser,HttpSession::HttpResponseInvoker &invoker,bool &consumed
        if(strstr(parser.Url().data(),"/api/") != parser.Url().data()){
            return;
        }
        //url以"/api/起始，说明是http api"
        consumed = true;//该http请求已被消费

        _StrPrinter printer;
        ////////////////method////////////////////
        printer << "\r\nmethod:\r\n\t" << parser.Method();
        ////////////////url/////////////////
        printer << "\r\nurl:\r\n\t" << parser.Url();
        ////////////////protocol/////////////////
        printer << "\r\nprotocol:\r\n\t" << parser.Tail();
        ///////////////args//////////////////
        printer << "\r\nargs:\r\n";
        for(auto &pr : parser.getUrlArgs()){
            printer <<  "\t" << pr.first << " : " << pr.second << "\r\n";
        }
        ///////////////header//////////////////
        printer << "\r\nheader:\r\n";
        for(auto &pr : parser.getValues()){
            printer <<  "\t" << pr.first << " : " << pr.second << "\r\n";
        }
        ////////////////content/////////////////
        printer << "\r\ncontent:\r\n" << parser.Content();
        auto contentOut = printer << endl;

        ////////////////我们测算异步回复，当然你也可以同步回复/////////////////
        EventPoller::Instance().sync([invoker,contentOut](){
            HttpSession::KeyValue headerOut;
			//你可以自定义header,如果跟默认header重名，则会覆盖之
			//默认header有:Server,Connection,Date,Content-Type,Content-Length
			//请勿覆盖Connection、Content-Length键
			//键名覆盖时不区分大小写
            headerOut["TestHeader"] = "HeaderValue";
            invoker("200 OK",headerOut,contentOut);
        });
    });
}, nullptr);

int main(int argc,char *argv[]){
	//设置退出信号处理函数
	signal(SIGINT, [](int){EventPoller::Instance().shutdown();});
	//设置日志
	Logger::Instance().add(std::make_shared<ConsoleChannel>("stdout", LTrace));
    Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());
	//加载配置文件，如果配置文件不存在就创建一个
	Config::loadIniConfig();

#ifdef ENABLE_OPENSSL
	//请把证书"test_httpApi.pem"放置在本程序可执行程序同目录下
	try{
		//加载证书，证书包含公钥和私钥
		SSL_Initor::Instance().loadServerPem((exePath() + ".pem").data());
	}catch(...){
		FatalL << "请把证书:" << (exeName() + ".pem") << "放置在本程序可执行程序同目录下:" << exeDir() << endl;
		return 0;
	}
#endif //ENABLE_OPENSSL

	//开启http服务器
	TcpServer<HttpSession>::Ptr httpSrv(new TcpServer<HttpSession>());
	httpSrv->start(mINI::Instance()[Config::Http::kPort]);//默认80

#ifdef ENABLE_OPENSSL
    //如果支持ssl，还可以开启https服务器
	TcpServer<HttpsSession>::Ptr httpsSrv(new TcpServer<HttpsSession>());
	httpsSrv->start(mINI::Instance()[Config::Http::kSSLPort]);//默认443
#endif //ENABLE_OPENSSL

	InfoL << "你可以在浏览器输入:http://127.0.0.1/api/my_api?key0=val0&key1=参数1" << endl;

	EventPoller::Instance().runLoop();

	static onceToken s_token(nullptr,[]() {
		//TcpServer用到了WorkThreadPool
		WorkThreadPool::Destory();
		EventPoller::Destory();
		Logger::Destory();
	});
	return 0;
}

<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE "test_acceptor"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/utility.hpp>
#include <vector>
#include <array>

BOOST_AUTO_TEST_CASE(test_resize)
{
    {
        typedef std::vector<int>  resizable_type;
        typedef std::array<int,1> non_resizable_type;
        BOOST_CHECK(toml::detail::has_resize_method<resizable_type>::value);
        BOOST_CHECK(!toml::detail::has_resize_method<non_resizable_type>::value);
    }

    {
        bool thrown = false;
        std::vector<int> v;
        try
        {
            toml::resize(v, 10);
        }
        catch(std::exception& ex)
        {
            thrown = true;
        }
        BOOST_CHECK(!thrown);
        BOOST_CHECK_EQUAL(v.size(), 10);
    }

    {
        bool thrown = false;
        std::array<int, 15> a;
        try
        {
            toml::resize(a, 10);
        }
        catch(std::exception& ex)
        {
            thrown = true;
        }
        BOOST_CHECK(!thrown);
        BOOST_CHECK_EQUAL(a.size(), 15);
    }

    {
        bool thrown = false;
        std::array<int, 15> a;
        try
        {
            toml::resize(a, 20);
        }
        catch(std::exception& ex)
        {
            thrown = true;
        }
        BOOST_CHECK(thrown);
    }
}
<commit_msg>add test for concat_string<commit_after>#define BOOST_TEST_MODULE "test_acceptor"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/utility.hpp>
#include <vector>
#include <array>

BOOST_AUTO_TEST_CASE(test_resize)
{
    {
        typedef std::vector<int>  resizable_type;
        typedef std::array<int,1> non_resizable_type;
        BOOST_CHECK(toml::detail::has_resize_method<resizable_type>::value);
        BOOST_CHECK(!toml::detail::has_resize_method<non_resizable_type>::value);
    }

    {
        bool thrown = false;
        std::vector<int> v;
        try
        {
            toml::resize(v, 10);
        }
        catch(std::exception& ex)
        {
            thrown = true;
        }
        BOOST_CHECK(!thrown);
        BOOST_CHECK_EQUAL(v.size(), 10u);
    }

    {
        bool thrown = false;
        std::array<int, 15> a;
        try
        {
            toml::resize(a, 10);
        }
        catch(std::exception& ex)
        {
            thrown = true;
        }
        BOOST_CHECK(!thrown);
        BOOST_CHECK_EQUAL(a.size(), 15u);
    }

    {
        bool thrown = false;
        std::array<int, 15> a;
        try
        {
            toml::resize(a, 20);
        }
        catch(std::exception& ex)
        {
            thrown = true;
        }
        BOOST_CHECK(thrown);
    }
}

BOOST_AUTO_TEST_CASE(test_concat_to_string)
{
    const std::string cat = toml::concat_to_string("foo", "bar", 42);
    BOOST_CHECK(cat == "foobar42");
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include <putl/state_ptr.hpp>

#include <vector>
#include <iostream>

namespace {

using namespace putl;

struct Foo{
	int a;
};

TEST(ConstexprLog2, Zero) {
	EXPECT_EQ(detail::log2(0), 0);
}

TEST(ConstexprLog2, One) {
	EXPECT_EQ(detail::log2(1), 0);
}

TEST(ConstexprLog2, PowersOfTwo) {
	EXPECT_EQ(detail::log2(   2),  1);
	EXPECT_EQ(detail::log2(   4),  2);
	EXPECT_EQ(detail::log2(   8),  3);
	EXPECT_EQ(detail::log2(  16),  4);
	EXPECT_EQ(detail::log2(  32),  5);
	EXPECT_EQ(detail::log2(  64),  6);
	EXPECT_EQ(detail::log2( 128),  7);
	EXPECT_EQ(detail::log2( 256),  8);
	EXPECT_EQ(detail::log2( 512),  9);
	EXPECT_EQ(detail::log2(1024), 10);
}

TEST(ConstexprLog2, Odd) {
	EXPECT_EQ(detail::log2(13), 3);
	EXPECT_EQ(detail::log2(17), 4);
	EXPECT_EQ(detail::log2(35), 5);
}

TEST(StatePointer, InitializedAsNull) {
	state_ptr<Foo> foo{nullptr, 0};
	state_ptr<Foo> bar{nullptr, 0};
	ASSERT_EQ(foo, bar);
	ASSERT_EQ(foo, nullptr);
}

TEST(StatePointer, GetStateNull) {
	Foo* foo = new Foo;
	state_ptr<Foo> p{foo, 0};
	ASSERT_EQ(p.get_ptr(), foo);
	ASSERT_EQ(p.get_state(), 0ul);
	free(foo);
}

TEST(StatePointer, SetState) {
	Foo foo;
	state_ptr<Foo> p{&foo, 1};
	ASSERT_EQ(p.get_ptr(), &foo);
	ASSERT_EQ(p.get_state(), 1ul);
	p.set_state(2);
	ASSERT_EQ(p.get_ptr(), &foo);
	ASSERT_EQ(p.get_state(), 2ul);
}

} // namspace
<commit_msg>added a new test for custom state type<commit_after>#include <gtest/gtest.h>

#include <putl/state_ptr.hpp>

#include <vector>
#include <iostream>

namespace {

using namespace putl;

struct Foo{
	int a;
};

enum Bar {
	A = 0,
	B = 1,
	C = 2,
	D = 1337 // probably too large !
};

TEST(ConstexprLog2, Zero) {
	EXPECT_EQ(detail::log2(0), 0);
}

TEST(ConstexprLog2, One) {
	EXPECT_EQ(detail::log2(1), 0);
}

TEST(ConstexprLog2, PowersOfTwo) {
	EXPECT_EQ(detail::log2(   2),  1);
	EXPECT_EQ(detail::log2(   4),  2);
	EXPECT_EQ(detail::log2(   8),  3);
	EXPECT_EQ(detail::log2(  16),  4);
	EXPECT_EQ(detail::log2(  32),  5);
	EXPECT_EQ(detail::log2(  64),  6);
	EXPECT_EQ(detail::log2( 128),  7);
	EXPECT_EQ(detail::log2( 256),  8);
	EXPECT_EQ(detail::log2( 512),  9);
	EXPECT_EQ(detail::log2(1024), 10);
}

TEST(ConstexprLog2, Odd) {
	EXPECT_EQ(detail::log2(13), 3);
	EXPECT_EQ(detail::log2(17), 4);
	EXPECT_EQ(detail::log2(35), 5);
}

TEST(StatePointer, InitializedAsNull) {
	state_ptr<Foo> foo{nullptr, 0};
	state_ptr<Foo> bar{nullptr, 0};
	ASSERT_EQ(foo, bar);
	ASSERT_EQ(foo, nullptr);
}

TEST(StatePointer, GetStateNull) {
	Foo foo;
	state_ptr<Foo> p{&foo, 0};
	ASSERT_EQ(p.get_ptr(), &foo);
	ASSERT_EQ(p.get_state(), 0ul);
}

TEST(StatePointer, SetState) {
	Foo foo;
	state_ptr<Foo> p{&foo, 1};
	ASSERT_EQ(p.get_ptr(), &foo);
	ASSERT_EQ(p.get_state(), 1ul);
	p.set_state(2);
	ASSERT_EQ(p.get_ptr(), &foo);
	ASSERT_EQ(p.get_state(), 2ul);
}

TEST(StatePointer, EnumState) {
	Foo foo;
	state_ptr<Foo, Bar> p{&foo, Bar::A};
	ASSERT_EQ(p.get_ptr(), &foo);
	ASSERT_EQ(p.get_state(), Bar::A);
	p.set_state(Bar::B);
	ASSERT_EQ(p.get_ptr(), &foo);
	ASSERT_EQ(p.get_state(), Bar::B);
}

} // namspace
<|endoftext|>


<commit_before>//
//	Time.hpp
//	A class around std::chrono that can be used for high precision timers for gameloops
//

#pragma once

#include <chrono>
#include <cstdint> //std::uint64_t

using namespace std;
using namespace chrono;

class Time
{
public:
	inline uint64_t nanoTime()
	{
		return duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch()).count();
	}

	inline uint64_t sysTime()
	{
		return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
	}
};<commit_msg>Final Commit<commit_after>//
//	Time.hpp
//	A wrapper around std::chrono that can be used for high precision timers for gameloops
//

#pragma once

#include <chrono>
#include <cstdint> //std::uint64_t

using namespace std;
using namespace chrono;

struct Time
{
	inline uint64_t nanoTime()
	{
		return duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch()).count();
	}

	inline uint64_t sysTime()
	{
		return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
	}
} Time;<|endoftext|>