<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Electron");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "8c5e74e"
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>date-time<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Electron");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-beta"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "8c5e74e"
#    define GIT_COMMIT_DATE "2015-08-12 20:12:09 +0100"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Library
  Module:    vlUGridR.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "vlUGridR.hh"

vlUnstructuredGridReader::vlUnstructuredGridReader()
{
}

vlUnstructuredGridReader::~vlUnstructuredGridReader()
{
}

unsigned long int vlUnstructuredGridReader::GetMTime()
{
  unsigned long dtime = this->vlUnstructuredGridSource::GetMTime();
  unsigned long rtime = this->Reader.GetMTime();
  return (dtime > rtime ? dtime : rtime);
}

// Description:
// Specify file name of vl polygonal data file to read.
void vlUnstructuredGridReader::SetFilename(char *name)
{
  this->Reader.SetFilename(name);
}
char *vlUnstructuredGridReader::GetFilename()
{
  return this->Reader.GetFilename();
}

// Description:
// Get the type of file (ASCII or BINARY)
int vlUnstructuredGridReader::GetFileType()
{
  return this->Reader.GetFileType();
}

// Description:
// Set the name of the scalar data to extract. If not specified, first
// scalar data encountered is extracted.
void vlUnstructuredGridReader::SetScalarsName(char *name)
{
  this->Reader.SetScalarsName(name);
}
char *vlUnstructuredGridReader::GetScalarsName()
{
  return this->Reader.GetScalarsName();
}

// Description:
// Set the name of the vector data to extract. If not specified, first
// vector data encountered is extracted.
void vlUnstructuredGridReader::SetVectorsName(char *name)
{
  this->Reader.SetVectorsName(name);
}
char *vlUnstructuredGridReader::GetVectorsName()
{
  return this->Reader.GetVectorsName();
}

// Description:
// Set the name of the tensor data to extract. If not specified, first
// tensor data encountered is extracted.
void vlUnstructuredGridReader::SetTensorsName(char *name)
{
  this->Reader.SetTensorsName(name);
}
char *vlUnstructuredGridReader::GetTensorsName()
{
  return this->Reader.GetTensorsName();
}

// Description:
// Set the name of the normal data to extract. If not specified, first
// normal data encountered is extracted.
void vlUnstructuredGridReader::SetNormalsName(char *name)
{
  this->Reader.SetNormalsName(name);
}
char *vlUnstructuredGridReader::GetNormalsName()
{
  return this->Reader.GetNormalsName();
}

// Description:
// Set the name of the texture coordinate data to extract. If not specified,
// first texture coordinate data encountered is extracted.
void vlUnstructuredGridReader::SetTCoordsName(char *name)
{
  this->Reader.SetTCoordsName(name);
}
char *vlUnstructuredGridReader::GetTCoordsName()
{
  return this->Reader.GetTCoordsName();
}

// Description:
// Set the name of the lookup table data to extract. If not specified, uses
// lookup table named by scalar. Otherwise, this specification supersedes.
void vlUnstructuredGridReader::SetLookupTableName(char *name)
{
  this->Reader.SetLookupTableName(name);
}
char *vlUnstructuredGridReader::GetLookupTableName()
{
  return this->Reader.GetLookupTableName();
}

void vlUnstructuredGridReader::Execute()
{
  FILE *fp;
  int numPts=0;
  int retStat;
  char line[257];
  int npts, size, ncells;
  vlCellArray *cells=NULL;
  int *types=NULL;

  vlDebugMacro(<<"Reading vl unstructured grid...");
  this->Initialize();

  if ( !(fp=this->Reader.OpenVLFile(this->Debug)) ||
  ! this->Reader.ReadHeader(fp,this->Debug) )
      return;
//
// Read unstructured grid specific stuff
//
  if ( (retStat=fscanf(fp,"%256s",line)) == EOF || retStat < 1 )
    {
    vlErrorMacro(<<"Data file ends prematurely!");
    return;
    }

  if ( !strncmp(this->Reader.LowerCase(line),"dataset",(unsigned long)7) )
    {
//
// Make sure we're reading right type of geometry
//
    if ( (retStat=fscanf(fp,"%256s",line)) == EOF || retStat < 1 )
      {
      vlErrorMacro(<<"Data file ends prematurely!");
      return;
      }

    if ( strncmp(this->Reader.LowerCase(line),"unstructured_grid",17) )
      {
      vlErrorMacro(<< "Cannot read dataset type: " << line);
      return;
      }
//
// Might find points, cells, and cell types
//
    while (1)
      {
      if ( (retStat=fscanf(fp,"%256s",line)) == EOF || retStat < 1 ) break;

      if ( ! strncmp(this->Reader.LowerCase(line),"points",6) )
        {
        if ( (retStat=fscanf(fp,"%d", &numPts)) == EOF || retStat < 1 )
          {
          vlErrorMacro(<<"Cannot read number of points!");
          return;
          }

        if ( ! this->Reader.ReadPoints(fp, (vlPointSet *)this, numPts) ) return;
        }

      else if ( ! strncmp(line,"cells",5) )
        {
        if ((retStat=fscanf(fp,"%d %d", &ncells, &size)) == EOF || retStat < 2)
          {
          vlErrorMacro(<<"Cannot read cells!");
          return;
          }

        cells = new vlCellArray;
        if ( !this->Reader.ReadCells(fp, size, cells->WritePtr(ncells,size)) ) return;
        cells->WrotePtr();
        if ( cells && types ) this->SetCells(types, cells);
        }

      else if ( ! strncmp(line,"cell_types",5) )
        {
        if ( (retStat=fscanf(fp,"%d", &ncells)) == EOF || retStat < 1 )
          {
          vlErrorMacro(<<"Cannot read cell types!");
          return;
          }

        types = new int[ncells];
        if ( this->Reader.GetFileType() == BINARY )
          {
          if ( (fgets(line,256,fp) == NULL) ||
          (fread(types,sizeof(int),ncells,fp) != ncells) )
            {
            vlErrorMacro(<<"Error reading binary cell types!");
            return;
            }
          }
        else //ascii
          {
          for (int i=0; i<size; i++)
            {
            if ((retStat=fscanf(fp,"%d",types[i])) == EOF || retStat < 1)
              {
              vlErrorMacro(<<"Error reading cell types!");
              return;
              }
            }
          }
        if ( cells && types ) this->SetCells(types, cells);
        }

      else if ( ! strncmp(line, "point_data", 10) )
        {
        if ( (retStat=fscanf(fp,"%d", &npts)) == EOF || retStat < 1 )
          {
          vlErrorMacro(<<"Cannot read point data!");
          return;
          }

        if ( npts != numPts )
          {
          vlErrorMacro(<<"Number of points don't match!");
          return;
          }

        this->Reader.ReadPointData(fp, (vlDataSet *)this, npts, this->Debug);
        break; //out of this loop
        }

      else
        {
        vlErrorMacro(<< "Unrecognized keyord: " << line);
        return;
        }
      }
      if ( ! this->GetPoints() ) vlWarningMacro(<<"No points read!");
      if ( ! (cells && types) )  vlWarningMacro(<<"No topology read!");
    }

  else if ( !strncmp(line, "point_data", 10) )
    {
    vlWarningMacro(<<"No geometry defined in data file!");
    if ( (retStat=fscanf(fp,"%d", &numPts)) == EOF || retStat < 1 )
      {
      vlErrorMacro(<<"Cannot read point data!");
      return;
      }

    this->Reader.ReadPointData(fp, (vlDataSet *)this, numPts, this->Debug);
    }

  else
    {
    vlErrorMacro(<< "Unrecognized keyord: " << line);
    }
//
// Now read the point data
//
  if ( types ) delete [] types;
  return;
}

void vlUnstructuredGridReader::PrintSelf(ostream& os, vlIndent indent)
{
  vlUnstructuredGridSource::PrintSelf(os,indent);
  this->Reader.PrintSelf(os,indent.GetNextIndent());
}
<commit_msg>*** empty log message ***<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    vlUGridR.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "vlUGridR.hh"

vlUnstructuredGridReader::vlUnstructuredGridReader()
{
}

vlUnstructuredGridReader::~vlUnstructuredGridReader()
{
}

unsigned long int vlUnstructuredGridReader::GetMTime()
{
  unsigned long dtime = this->vlUnstructuredGridSource::GetMTime();
  unsigned long rtime = this->Reader.GetMTime();
  return (dtime > rtime ? dtime : rtime);
}

// Description:
// Specify file name of vl polygonal data file to read.
void vlUnstructuredGridReader::SetFilename(char *name)
{
  this->Reader.SetFilename(name);
}
char *vlUnstructuredGridReader::GetFilename()
{
  return this->Reader.GetFilename();
}

// Description:
// Get the type of file (ASCII or BINARY)
int vlUnstructuredGridReader::GetFileType()
{
  return this->Reader.GetFileType();
}

// Description:
// Set the name of the scalar data to extract. If not specified, first
// scalar data encountered is extracted.
void vlUnstructuredGridReader::SetScalarsName(char *name)
{
  this->Reader.SetScalarsName(name);
}
char *vlUnstructuredGridReader::GetScalarsName()
{
  return this->Reader.GetScalarsName();
}

// Description:
// Set the name of the vector data to extract. If not specified, first
// vector data encountered is extracted.
void vlUnstructuredGridReader::SetVectorsName(char *name)
{
  this->Reader.SetVectorsName(name);
}
char *vlUnstructuredGridReader::GetVectorsName()
{
  return this->Reader.GetVectorsName();
}

// Description:
// Set the name of the tensor data to extract. If not specified, first
// tensor data encountered is extracted.
void vlUnstructuredGridReader::SetTensorsName(char *name)
{
  this->Reader.SetTensorsName(name);
}
char *vlUnstructuredGridReader::GetTensorsName()
{
  return this->Reader.GetTensorsName();
}

// Description:
// Set the name of the normal data to extract. If not specified, first
// normal data encountered is extracted.
void vlUnstructuredGridReader::SetNormalsName(char *name)
{
  this->Reader.SetNormalsName(name);
}
char *vlUnstructuredGridReader::GetNormalsName()
{
  return this->Reader.GetNormalsName();
}

// Description:
// Set the name of the texture coordinate data to extract. If not specified,
// first texture coordinate data encountered is extracted.
void vlUnstructuredGridReader::SetTCoordsName(char *name)
{
  this->Reader.SetTCoordsName(name);
}
char *vlUnstructuredGridReader::GetTCoordsName()
{
  return this->Reader.GetTCoordsName();
}

// Description:
// Set the name of the lookup table data to extract. If not specified, uses
// lookup table named by scalar. Otherwise, this specification supersedes.
void vlUnstructuredGridReader::SetLookupTableName(char *name)
{
  this->Reader.SetLookupTableName(name);
}
char *vlUnstructuredGridReader::GetLookupTableName()
{
  return this->Reader.GetLookupTableName();
}

void vlUnstructuredGridReader::Execute()
{
  FILE *fp;
  int numPts=0;
  int retStat;
  char line[257];
  int npts, size, ncells;
  vlCellArray *cells=NULL;
  int *types=NULL;

  vlDebugMacro(<<"Reading vl unstructured grid...");
  this->Initialize();

  if ( !(fp=this->Reader.OpenVLFile(this->Debug)) ||
  ! this->Reader.ReadHeader(fp,this->Debug) )
      return;
//
// Read unstructured grid specific stuff
//
  if ( (retStat=fscanf(fp,"%256s",line)) == EOF || retStat < 1 )
    {
    vlErrorMacro(<<"Data file ends prematurely!");
    return;
    }

  if ( !strncmp(this->Reader.LowerCase(line),"dataset",(unsigned long)7) )
    {
//
// Make sure we're reading right type of geometry
//
    if ( (retStat=fscanf(fp,"%256s",line)) == EOF || retStat < 1 )
      {
      vlErrorMacro(<<"Data file ends prematurely!");
      return;
      }

    if ( strncmp(this->Reader.LowerCase(line),"unstructured_grid",17) )
      {
      vlErrorMacro(<< "Cannot read dataset type: " << line);
      return;
      }
//
// Might find points, cells, and cell types
//
    while (1)
      {
      if ( (retStat=fscanf(fp,"%256s",line)) == EOF || retStat < 1 ) break;

      if ( ! strncmp(this->Reader.LowerCase(line),"points",6) )
        {
        if ( (retStat=fscanf(fp,"%d", &numPts)) == EOF || retStat < 1 )
          {
          vlErrorMacro(<<"Cannot read number of points!");
          return;
          }

        if ( ! this->Reader.ReadPoints(fp, (vlPointSet *)this, numPts) ) return;
        }

      else if ( ! strncmp(line,"cells",5) )
        {
        if ((retStat=fscanf(fp,"%d %d", &ncells, &size)) == EOF || retStat < 2)
          {
          vlErrorMacro(<<"Cannot read cells!");
          return;
          }

        cells = new vlCellArray;
        if ( !this->Reader.ReadCells(fp, size, cells->WritePtr(ncells,size)) ) return;
        cells->WrotePtr();
        if ( cells && types ) this->SetCells(types, cells);
        }

      else if ( ! strncmp(line,"cell_types",5) )
        {
        if ( (retStat=fscanf(fp,"%d", &ncells)) == EOF || retStat < 1 )
          {
          vlErrorMacro(<<"Cannot read cell types!");
          return;
          }

        types = new int[ncells];
        if ( this->Reader.GetFileType() == BINARY )
          {
          if ( (fgets(line,256,fp) == NULL) ||
          (fread(types,sizeof(int),ncells,fp) != ncells) )
            {
            vlErrorMacro(<<"Error reading binary cell types!");
            return;
            }
          }
        else //ascii
          {
          for (int i=0; i<size; i++)
            {
            if ((retStat=fscanf(fp,"%d",types+i)) == EOF || retStat < 1)
              {
              vlErrorMacro(<<"Error reading cell types!");
              return;
              }
            }
          }
        if ( cells && types ) this->SetCells(types, cells);
        }

      else if ( ! strncmp(line, "point_data", 10) )
        {
        if ( (retStat=fscanf(fp,"%d", &npts)) == EOF || retStat < 1 )
          {
          vlErrorMacro(<<"Cannot read point data!");
          return;
          }

        if ( npts != numPts )
          {
          vlErrorMacro(<<"Number of points don't match!");
          return;
          }

        this->Reader.ReadPointData(fp, (vlDataSet *)this, npts, this->Debug);
        break; //out of this loop
        }

      else
        {
        vlErrorMacro(<< "Unrecognized keyord: " << line);
        return;
        }
      }
      if ( ! this->GetPoints() ) vlWarningMacro(<<"No points read!");
      if ( ! (cells && types) )  vlWarningMacro(<<"No topology read!");
    }

  else if ( !strncmp(line, "point_data", 10) )
    {
    vlWarningMacro(<<"No geometry defined in data file!");
    if ( (retStat=fscanf(fp,"%d", &numPts)) == EOF || retStat < 1 )
      {
      vlErrorMacro(<<"Cannot read point data!");
      return;
      }

    this->Reader.ReadPointData(fp, (vlDataSet *)this, numPts, this->Debug);
    }

  else
    {
    vlErrorMacro(<< "Unrecognized keyord: " << line);
    }
//
// Now read the point data
//
  if ( types ) delete [] types;
  return;
}

void vlUnstructuredGridReader::PrintSelf(ostream& os, vlIndent indent)
{
  vlUnstructuredGridSource::PrintSelf(os,indent);
  this->Reader.PrintSelf(os,indent.GetNextIndent());
}
<|endoftext|>


<commit_before>#ifndef OpenFAST_h
#define OpenFAST_h
#include "FAST_Library.h"
#include "sys/stat.h"
#include "math.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <stdexcept>
#include <vector>
#include <set>
#include <map>
#include "dlfcn.h"
#define OMPI_SKIP_MPICXX
#define MPICH_SKIP_MPICXX
#include "mpi.h"
#include "SC.h"

namespace fast {

struct globTurbineDataType {
  int TurbID;
  std::string FASTInputFileName;
  std::string FASTRestartFileName;
  std::vector<double> TurbineBasePos;
  std::vector<double> TurbineHubPos;
  int numForcePtsBlade;
  int numForcePtsTwr;
};

enum ActuatorNodeType {
  HUB = 0,
  BLADE = 1,
  TOWER = 2,
  ActuatorNodeType_END
};

class fastInputs {

 public:

  MPI_Comm comm;
  int nTurbinesGlob;
  bool dryRun;
  bool debug;
  double tStart;
  int nEveryCheckPoint;
  double tMax;
  double dtFAST;

  bool scStatus;
  std::string scLibFile;
  int numScInputs, numScOutputs;

  std::vector<globTurbineDataType>  globTurbineData;

  // Constructor
  fastInputs() ;

  // Destructor
  ~fastInputs() {} ;

};

class OpenFAST {

 private:

  MPI_Comm mpiComm;
  bool dryRun;        // If this is true, class will simply go through allocation and deallocation of turbine data
  bool debug;   // Write out extra information if this flags is turned on
  std::vector<globTurbineDataType> globTurbineData;
  int nTurbinesProc;
  int nTurbinesGlob;
  bool restart;
  bool timeZero;
  double dtFAST;
  double tMax;
  std::vector<std::vector<float>> TurbineBasePos;
  std::vector<std::vector<float>> TurbineHubPos;
  std::vector<int> TurbID;
  std::vector<std::string > FASTInputFileName;
  std::vector<std::string > CheckpointFileRoot;
  double tStart;
  int nt_global;
  int ntStart;      // The time step to start the FAST simulation
  int nEveryCheckPoint;    // Check point files will be written every 'nEveryCheckPoint' time steps
  std::vector<int> numBlades;           // Number of blades
  std::vector<int> numForcePtsBlade;
  std::vector<int> numForcePtsTwr;
  std::vector<int> numVelPtsBlade;
  std::vector<int> numVelPtsTwr;
  int numScOutputs;  // # outputs from the supercontroller == # inputs to the controller == NumSC2Ctrl
  int numScInputs;   // # inputs to the supercontroller == # outputs from the controller == NumCtrl2SC
  std::vector<double> scOutputsGlob;  // # outputs from the supercontroller for all turbines
  std::vector<double> scInputsGlob;   // # inputs to the supercontroller for all turbines

  std::vector<std::vector<std::vector<double>>> forceNodeVel; // Velocity at force nodes - Store temporarily to interpolate to the velocity nodes
  std::vector<OpFM_InputType_t> cDriver_Input_from_FAST;
  std::vector<OpFM_OutputType_t> cDriver_Output_to_FAST;

  std::vector<SC_InputType_t> cDriverSC_Input_from_FAST;
  std::vector<SC_OutputType_t> cDriverSC_Output_to_FAST;

  // Turbine Number is DIFFERENT from TurbID. Turbine Number simply runs from 0:n-1 locally and globally.
  std::map<int, int> turbineMapGlobToProc; // Mapping global turbine number to processor number
  std::map<int, int> turbineMapProcToGlob; // Mapping local to global turbine number
  std::map<int, int> reverseTurbineMapProcToGlob; // Reverse Mapping global turbine number to local turbine number
  std::set<int> turbineSetProcs; // Set of processors containing atleast one turbine
  std::vector<int> turbineProcs; // Same as the turbineSetProcs, but as an integer array

  //Supercontroller stuff
  bool scStatus;
  std::string scLibFile;
  // Dynamic load stuff copied from 'C++ dlopen mini HOWTO' on tldp.org
  void *scLibHandle ;
  typedef SuperController* create_sc_t();
  create_sc_t * create_SuperController;
  typedef void destroy_sc_t(SuperController *);
  destroy_sc_t * destroy_SuperController;
  SuperController * sc;

  int fastMPIGroupSize;
  MPI_Group fastMPIGroup;
  MPI_Comm  fastMPIComm;
  int fastMPIRank;

  MPI_Group worldMPIGroup;
  int worldMPIRank;

  int ErrStat;
  char ErrMsg[INTERFACE_STRING_LENGTH];  // make sure this is the same size as IntfStrLen in FAST_Library.f90

 public:

  // Constructor
  OpenFAST() ;

  // Destructor
  ~OpenFAST() {} ;

  void setInputs(const fastInputs &);

  void init();
  void solution0();
  void step();
  void end();

  void setTurbineProcNo(int iTurbGlob, int procNo) { turbineMapGlobToProc[iTurbGlob] = procNo; }
  void allocateTurbinesToProcsSimple();
  void getApproxHubPos(std::vector<double> & currentCoords, int iTurbGlob);
  void getHubPos(std::vector<double> & currentCoords, int iTurbGlob);
  void getHubShftDir(std::vector<double> & hubShftVec, int iTurbGlob);

  ActuatorNodeType getVelNodeType(int iTurbGlob, int iNode);
  void getVelNodeCoordinates(std::vector<double> & currentCoords, int iNode, int iTurbGlob);
  void setVelocity(std::vector<double> & velocity, int iNode, int iTurbGlob);
  void setVelocityForceNode(std::vector<double> & velocity, int iNode, int iTurbGlob);
  void interpolateVel_ForceToVelNodes();
  ActuatorNodeType getForceNodeType(int iTurbGlob, int iNode);
  void getForceNodeCoordinates(std::vector<double> & currentCoords, int iNode, int iTurbGlob);
  void getForceNodeOrientation(std::vector<double> & currentOrientation, int iNode, int iTurbGlob);
  void getForce(std::vector<double> & force, int iNode, int iTurbGlob);
  double getChord(int iNode, int iTurbGlob);

  int get_ntStart() { return ntStart; }
  bool isDryRun() { return dryRun; }
  bool isDebug() { return debug; }
  bool isRestart() { return restart; }
  bool isTimeZero() { return timeZero; }
  int get_procNo(int iTurbGlob) { return turbineMapGlobToProc[iTurbGlob] ; } // Get processor number of a turbine with global id 'iTurbGlob'
  int get_localTurbNo(int iTurbGlob) { return reverseTurbineMapProcToGlob[iTurbGlob]; }
  int get_nTurbinesGlob() { return nTurbinesGlob; }

  int get_numBlades(int iTurbGlob) { return get_numBladesLoc(get_localTurbNo(iTurbGlob)); }
  int get_numVelPtsBlade(int iTurbGlob) { return get_numVelPtsBladeLoc(get_localTurbNo(iTurbGlob)); }
  int get_numVelPtsTwr(int iTurbGlob) { return get_numVelPtsTwrLoc(get_localTurbNo(iTurbGlob)); }
  int get_numVelPts(int iTurbGlob) { return get_numVelPtsLoc(get_localTurbNo(iTurbGlob)); }
  int get_numForcePtsBlade(int iTurbGlob) { return get_numForcePtsBladeLoc(get_localTurbNo(iTurbGlob)); }
  int get_numForcePtsTwr(int iTurbGlob) { return get_numForcePtsTwrLoc(get_localTurbNo(iTurbGlob)); }
  int get_numForcePts(int iTurbGlob) { return get_numForcePtsLoc(get_localTurbNo(iTurbGlob)); }

  void computeTorqueThrust(int iTurGlob, std::vector<double> &  torque, std::vector<double> &  thrust);

 private:

  void checkError(const int ErrStat, const char * ErrMsg);
  inline bool checkFileExists(const std::string& name);

  void allocateMemory();

  int get_numBladesLoc(int iTurbLoc) { return numBlades[iTurbLoc]; }
  int get_numVelPtsBladeLoc(int iTurbLoc) { return numVelPtsBlade[iTurbLoc]; }
  int get_numVelPtsTwrLoc(int iTurbLoc) { return numVelPtsTwr[iTurbLoc]; }
  int get_numVelPtsLoc(int iTurbLoc) { return 1 + numBlades[iTurbLoc]*numVelPtsBlade[iTurbLoc] + numVelPtsTwr[iTurbLoc]; }
  int get_numForcePtsBladeLoc(int iTurbLoc) { return numForcePtsBlade[iTurbLoc]; }
  int get_numForcePtsTwrLoc(int iTurbLoc) { return numForcePtsTwr[iTurbLoc]; }
  int get_numForcePtsLoc(int iTurbLoc) { return 1 + numBlades[iTurbLoc]*numForcePtsBlade[iTurbLoc] + numForcePtsTwr[iTurbLoc]; }

  void loadSuperController(const fastInputs & fi);
  void fillScInputsGlob() ;
  void fillScOutputsLoc() ;

  void setOutputsToFAST(OpFM_InputType_t cDriver_Input_from_FAST, OpFM_OutputType_t cDriver_Output_to_FAST) ; // An example to set velocities at the Aerodyn nodes

};

}

#endif
<commit_msg>Reverting to old style std vector declaration and adding some ifndefs to allow for compilation with older compilers<commit_after>#ifndef OpenFAST_h
#define OpenFAST_h
#include "FAST_Library.h"
#include "sys/stat.h"
#include "math.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <stdexcept>
#include <vector>
#include <set>
#include <map>
#include "dlfcn.h"
#ifndef OMPI_SKIP_MPICXX
 #define OMPI_SKIP_MPICXX
#endif
#ifndef MPICH_SKIP_MPICXX
 #define MPICH_SKIP_MPICXX
#endif
#include "mpi.h"
#include "SC.h"

namespace fast {

struct globTurbineDataType {
  int TurbID;
  std::string FASTInputFileName;
  std::string FASTRestartFileName;
  std::vector<double> TurbineBasePos;
  std::vector<double> TurbineHubPos;
  int numForcePtsBlade;
  int numForcePtsTwr;
};

enum ActuatorNodeType {
  HUB = 0,
  BLADE = 1,
  TOWER = 2,
  ActuatorNodeType_END
};

class fastInputs {

 public:

  MPI_Comm comm;
  int nTurbinesGlob;
  bool dryRun;
  bool debug;
  double tStart;
  int nEveryCheckPoint;
  double tMax;
  double dtFAST;

  bool scStatus;
  std::string scLibFile;
  int numScInputs, numScOutputs;

  std::vector<globTurbineDataType>  globTurbineData;

  // Constructor
  fastInputs() ;

  // Destructor
  ~fastInputs() {} ;

};

class OpenFAST {

 private:

  MPI_Comm mpiComm;
  bool dryRun;        // If this is true, class will simply go through allocation and deallocation of turbine data
  bool debug;   // Write out extra information if this flags is turned on
  std::vector<globTurbineDataType> globTurbineData;
  int nTurbinesProc;
  int nTurbinesGlob;
  bool restart;
  bool timeZero;
  double dtFAST;
  double tMax;
  std::vector<std::vector<float> > TurbineBasePos;
  std::vector<std::vector<float> > TurbineHubPos;
  std::vector<int> TurbID;
  std::vector<std::string > FASTInputFileName;
  std::vector<std::string > CheckpointFileRoot;
  double tStart;
  int nt_global;
  int ntStart;      // The time step to start the FAST simulation
  int nEveryCheckPoint;    // Check point files will be written every 'nEveryCheckPoint' time steps
  std::vector<int> numBlades;           // Number of blades
  std::vector<int> numForcePtsBlade;
  std::vector<int> numForcePtsTwr;
  std::vector<int> numVelPtsBlade;
  std::vector<int> numVelPtsTwr;
  int numScOutputs;  // # outputs from the supercontroller == # inputs to the controller == NumSC2Ctrl
  int numScInputs;   // # inputs to the supercontroller == # outputs from the controller == NumCtrl2SC
  std::vector<double> scOutputsGlob;  // # outputs from the supercontroller for all turbines
  std::vector<double> scInputsGlob;   // # inputs to the supercontroller for all turbines

  std::vector<std::vector<std::vector<double> > > forceNodeVel; // Velocity at force nodes - Store temporarily to interpolate to the velocity nodes
  std::vector<OpFM_InputType_t> cDriver_Input_from_FAST;
  std::vector<OpFM_OutputType_t> cDriver_Output_to_FAST;

  std::vector<SC_InputType_t> cDriverSC_Input_from_FAST;
  std::vector<SC_OutputType_t> cDriverSC_Output_to_FAST;

  // Turbine Number is DIFFERENT from TurbID. Turbine Number simply runs from 0:n-1 locally and globally.
  std::map<int, int> turbineMapGlobToProc; // Mapping global turbine number to processor number
  std::map<int, int> turbineMapProcToGlob; // Mapping local to global turbine number
  std::map<int, int> reverseTurbineMapProcToGlob; // Reverse Mapping global turbine number to local turbine number
  std::set<int> turbineSetProcs; // Set of processors containing atleast one turbine
  std::vector<int> turbineProcs; // Same as the turbineSetProcs, but as an integer array

  //Supercontroller stuff
  bool scStatus;
  std::string scLibFile;
  // Dynamic load stuff copied from 'C++ dlopen mini HOWTO' on tldp.org
  void *scLibHandle ;
  typedef SuperController* create_sc_t();
  create_sc_t * create_SuperController;
  typedef void destroy_sc_t(SuperController *);
  destroy_sc_t * destroy_SuperController;
  SuperController * sc;

  int fastMPIGroupSize;
  MPI_Group fastMPIGroup;
  MPI_Comm  fastMPIComm;
  int fastMPIRank;

  MPI_Group worldMPIGroup;
  int worldMPIRank;

  int ErrStat;
  char ErrMsg[INTERFACE_STRING_LENGTH];  // make sure this is the same size as IntfStrLen in FAST_Library.f90

 public:

  // Constructor
  OpenFAST() ;

  // Destructor
  ~OpenFAST() {} ;

  void setInputs(const fastInputs &);

  void init();
  void solution0();
  void step();
  void end();

  void setTurbineProcNo(int iTurbGlob, int procNo) { turbineMapGlobToProc[iTurbGlob] = procNo; }
  void allocateTurbinesToProcsSimple();
  void getApproxHubPos(std::vector<double> & currentCoords, int iTurbGlob);
  void getHubPos(std::vector<double> & currentCoords, int iTurbGlob);
  void getHubShftDir(std::vector<double> & hubShftVec, int iTurbGlob);

  ActuatorNodeType getVelNodeType(int iTurbGlob, int iNode);
  void getVelNodeCoordinates(std::vector<double> & currentCoords, int iNode, int iTurbGlob);
  void setVelocity(std::vector<double> & velocity, int iNode, int iTurbGlob);
  void setVelocityForceNode(std::vector<double> & velocity, int iNode, int iTurbGlob);
  void interpolateVel_ForceToVelNodes();
  ActuatorNodeType getForceNodeType(int iTurbGlob, int iNode);
  void getForceNodeCoordinates(std::vector<double> & currentCoords, int iNode, int iTurbGlob);
  void getForceNodeOrientation(std::vector<double> & currentOrientation, int iNode, int iTurbGlob);
  void getForce(std::vector<double> & force, int iNode, int iTurbGlob);
  double getChord(int iNode, int iTurbGlob);

  int get_ntStart() { return ntStart; }
  bool isDryRun() { return dryRun; }
  bool isDebug() { return debug; }
  bool isRestart() { return restart; }
  bool isTimeZero() { return timeZero; }
  int get_procNo(int iTurbGlob) { return turbineMapGlobToProc[iTurbGlob] ; } // Get processor number of a turbine with global id 'iTurbGlob'
  int get_localTurbNo(int iTurbGlob) { return reverseTurbineMapProcToGlob[iTurbGlob]; }
  int get_nTurbinesGlob() { return nTurbinesGlob; }

  int get_numBlades(int iTurbGlob) { return get_numBladesLoc(get_localTurbNo(iTurbGlob)); }
  int get_numVelPtsBlade(int iTurbGlob) { return get_numVelPtsBladeLoc(get_localTurbNo(iTurbGlob)); }
  int get_numVelPtsTwr(int iTurbGlob) { return get_numVelPtsTwrLoc(get_localTurbNo(iTurbGlob)); }
  int get_numVelPts(int iTurbGlob) { return get_numVelPtsLoc(get_localTurbNo(iTurbGlob)); }
  int get_numForcePtsBlade(int iTurbGlob) { return get_numForcePtsBladeLoc(get_localTurbNo(iTurbGlob)); }
  int get_numForcePtsTwr(int iTurbGlob) { return get_numForcePtsTwrLoc(get_localTurbNo(iTurbGlob)); }
  int get_numForcePts(int iTurbGlob) { return get_numForcePtsLoc(get_localTurbNo(iTurbGlob)); }

  void computeTorqueThrust(int iTurGlob, std::vector<double> &  torque, std::vector<double> &  thrust);

 private:

  void checkError(const int ErrStat, const char * ErrMsg);
  inline bool checkFileExists(const std::string& name);

  void allocateMemory();

  int get_numBladesLoc(int iTurbLoc) { return numBlades[iTurbLoc]; }
  int get_numVelPtsBladeLoc(int iTurbLoc) { return numVelPtsBlade[iTurbLoc]; }
  int get_numVelPtsTwrLoc(int iTurbLoc) { return numVelPtsTwr[iTurbLoc]; }
  int get_numVelPtsLoc(int iTurbLoc) { return 1 + numBlades[iTurbLoc]*numVelPtsBlade[iTurbLoc] + numVelPtsTwr[iTurbLoc]; }
  int get_numForcePtsBladeLoc(int iTurbLoc) { return numForcePtsBlade[iTurbLoc]; }
  int get_numForcePtsTwrLoc(int iTurbLoc) { return numForcePtsTwr[iTurbLoc]; }
  int get_numForcePtsLoc(int iTurbLoc) { return 1 + numBlades[iTurbLoc]*numForcePtsBlade[iTurbLoc] + numForcePtsTwr[iTurbLoc]; }

  void loadSuperController(const fastInputs & fi);
  void fillScInputsGlob() ;
  void fillScOutputsLoc() ;

  void setOutputsToFAST(OpFM_InputType_t cDriver_Input_from_FAST, OpFM_OutputType_t cDriver_Output_to_FAST) ; // An example to set velocities at the Aerodyn nodes

};

}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Mar 10, 2014
 */

#ifndef DefaultValue_h__
#define DefaultValue_h__
#include <type_traits>
#include <typeinfo>

namespace fakeit {

struct DefaultValueInstatiationException {
	virtual ~DefaultValueInstatiationException() = default;
	DefaultValueInstatiationException() = default;
	virtual std::string what() const = 0;
};

template<class C, class Enable = void>
struct DefaultValue;

template<class C>
struct DefaultValue <C,
	typename std::enable_if<
	!(std::is_default_constructible<typename std::remove_reference<C>::type>::value
	&& !std::is_abstract<typename std::remove_reference<C>::type>::value)
	>::type> {
	static C& value() {
		if (std::is_reference<C>::value){
			typename std::remove_reference<C>::type * ptr = nullptr;
			return *ptr;
		}

		class Exception : public DefaultValueInstatiationException {
			virtual std::string what() const override {
				return (std::string("Type ") + std::string(typeid(C).name())
				+ std::string(" is not default constructible. Could not instantiate a default return value")).c_str();
			}
		};

		throw Exception();
	}
};

template<class C>
struct DefaultValue <C,
	typename std::enable_if<
	std::is_default_constructible<typename std::remove_reference<C>::type>::value
	&& !std::is_abstract<typename std::remove_reference<C>::type>::value
	>::type> {
	// this was a reference to abstract type
	static C& value() {
		static typename std::remove_reference<C>::type val { };
		return val;
	}
};

template<> struct DefaultValue<void> {
	static void value() {
		return;
	}
};

template<> struct DefaultValue<bool> {
	static bool& value() {
		static bool value { false };
		return value;
	}
};

template<> struct DefaultValue<char> {
	static char& value() {
		static char value { 0 };
		return value;
	}
};

template<> struct DefaultValue<char16_t> {
	static char16_t& value() {
		static char16_t value { 0 };
		return value;
	}
};
template<> struct DefaultValue<char32_t> {
	static char32_t& value() {
		static char32_t value { 0 };
		return value;
	}
};
template<> struct DefaultValue<wchar_t> {
	static wchar_t& value() {
		static wchar_t value { 0 };
		return value;
	}
};
template<> struct DefaultValue<short> {
	static short& value() {
		static short value { 0 };
		return value;
	}
};
template<> struct DefaultValue<int> {
	static int& value() {
		static int value { 0 };
		return value;
	}
};
template<> struct DefaultValue<long> {
	static long& value() {
		static long value { 0 };
		return value;
	}
};
template<> struct DefaultValue<long long> {
	static long long& value() {
		static long long value { 0 };
		return value;
	}
};

}
#endif // DefaultValue_h__
<commit_msg>Refactor DefualtValue.hpp Try to improve compile time.<commit_after>/*
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Mar 10, 2014
 */

#ifndef DefaultValue_h__
#define DefaultValue_h__
#include <type_traits>
#include <typeinfo>

namespace fakeit {

struct DefaultValueInstatiationException {
	virtual ~DefaultValueInstatiationException() = default;
	virtual std::string what() const = 0;
};

template<class C>
struct is_constructible_type{
	static const bool value = std::is_default_constructible<typename std::remove_reference<C>::type>::value
	&& !std::is_abstract<typename std::remove_reference<C>::type>::value;
};

template<class C, class Enable = void>
struct DefaultValue;

template<class C>
struct DefaultValue <C, typename std::enable_if<!is_constructible_type<C>::value>::type> {
	static C& value() {
		if (std::is_reference<C>::value){
			typename std::remove_reference<C>::type * ptr = nullptr;
			return *ptr;
		}

		class Exception : public DefaultValueInstatiationException {
			virtual std::string what() const override {
				return (std::string("Type ") + std::string(typeid(C).name())
				+ std::string(" is not default constructible. Could not instantiate a default return value")).c_str();
			}
		};

		throw Exception();
	}
};

template<class C>
struct DefaultValue <C, typename std::enable_if<is_constructible_type<C>::value>::type> {
	static C& value() {
		static typename std::remove_reference<C>::type val { };
		return val;
	}
};

template<> struct DefaultValue<void> {
	static void value() {
		return;
	}
};

template<> struct DefaultValue<bool> {
	static bool& value() {
		static bool value { false };
		return value;
	}
};

template<> struct DefaultValue<char> {
	static char& value() {
		static char value { 0 };
		return value;
	}
};

template<> struct DefaultValue<char16_t> {
	static char16_t& value() {
		static char16_t value { 0 };
		return value;
	}
};
template<> struct DefaultValue<char32_t> {
	static char32_t& value() {
		static char32_t value { 0 };
		return value;
	}
};
template<> struct DefaultValue<wchar_t> {
	static wchar_t& value() {
		static wchar_t value { 0 };
		return value;
	}
};
template<> struct DefaultValue<short> {
	static short& value() {
		static short value { 0 };
		return value;
	}
};
template<> struct DefaultValue<int> {
	static int& value() {
		static int value { 0 };
		return value;
	}
};
template<> struct DefaultValue<long> {
	static long& value() {
		static long value { 0 };
		return value;
	}
};
template<> struct DefaultValue<long long> {
	static long long& value() {
		static long long value { 0 };
		return value;
	}
};

}
#endif // DefaultValue_h__
<|endoftext|>


<commit_before>#ifndef COFFEE_MILL_CYLINDRICAL_COORDINATE
#define COFFEE_MILL_CYLINDRICAL_COORDINATE
#include "mathematics/LinearAlgebra.hpp"
#include "mathematics/VectorRotation.hpp"
#include <cassert>

namespace coffeemill
{
    class CylindricalCoordinate
    {
        public:
            CylindricalCoordinate(const Realvec& c,
                                   const Realvec& r,
                                   const Realvec& z)
                : center(c), r_axis(r/length(r)), z_axis(z/length(z))
            {
                if(fabs(dot_prod(r_axis, z_axis)) > 1e-12)
                {
                    std::cout << "Warning: dotp(r, z) = "
                              << dot_prod(r_axis, z_axis)
                              <<  " is not zero. over tolerance" << std::endl;
                    double z_axis_r = dot_prod(r_axis, z_axis);
                    z_axis -= z_axis_r * r_axis;
                    z_axis /= length(z_axis);
                    assert(fabs(dot_prod(r_axis, z_axis)) < 1e-12);
                    assert(fabs(length(z_axis) - 1e0) < 1e-12);
                    std::cout << "new z axis = " << z_axis << std::endl;
                    std::cout << "length(z axis) = " << length(z_axis)
                              << std::endl;
                    std::cout << "dotp(z axis, r_axis) = "
                              << dot_prod(z_axis, r_axis) << std::endl;
                }
                assert(fabs(length(r_axis) - 1e0) < 1e-12);
                assert(fabs(length(z_axis) - 1e0) < 1e-12);
            }
            ~CylindricalCoordinate(){};

            std::array<double, 3> translate(const Realvec& position);
            Realvec translate(const std::array<double, 3>& position);

            Realvec get_center() const {return center;}
            Realvec get_r_axis() const {return r_axis;}
            Realvec get_z_axis() const {return z_axis;}

        private:
            const Realvec center;
            const Realvec r_axis;
            Realvec z_axis;
    };

    std::array<double, 3> CylindricalCoordinate::translate(
                                                    const Realvec& position)
    {
        Realvec relative_position = position - center;
        double z = dot_prod(relative_position, z_axis);
        Realvec planner = relative_position - (z*z_axis);
        double r = length(planner);
        double theta = acos(dot_prod(planner, r_axis)/r);

        if(dot_prod(cross_prod(planner, r_axis), z_axis) > 0e0)
            theta *= -1e0;

        return std::array<double, 3>({{r, theta * 180 / M_PI, z}});
    }

    Realvec CylindricalCoordinate::translate(const std::array<double, 3>&
                                                                 position)
    {
        return center
             + rotation(position[1], z_axis, position[0] * r_axis)
             + position[2] * z_axis;
    }

}

#endif//COFFEE_MILL_CYLINDRICAL_COORDINATE
<commit_msg>add: cylindor const<commit_after>#ifndef COFFEE_MILL_CYLINDRICAL_COORDINATE
#define COFFEE_MILL_CYLINDRICAL_COORDINATE
#include "mathematics/LinearAlgebra.hpp"
#include "mathematics/VectorRotation.hpp"
#include <cassert>

namespace coffeemill
{
    class CylindricalCoordinate
    {
        public:
            CylindricalCoordinate(const Realvec& c,
                                   const Realvec& r,
                                   const Realvec& z)
                : center(c), r_axis(r/length(r)), z_axis(z/length(z))
            {
                if(fabs(dot_prod(r_axis, z_axis)) > 1e-12)
                {
                    std::cout << "Warning: dotp(r, z) = "
                              << dot_prod(r_axis, z_axis)
                              <<  " is not zero. over tolerance" << std::endl;
                    double z_axis_r = dot_prod(r_axis, z_axis);
                    z_axis -= z_axis_r * r_axis;
                    z_axis /= length(z_axis);
                    assert(fabs(dot_prod(r_axis, z_axis)) < 1e-12);
                    assert(fabs(length(z_axis) - 1e0) < 1e-12);
                    std::cout << "new z axis = " << z_axis << std::endl;
                    std::cout << "length(z axis) = " << length(z_axis)
                              << std::endl;
                    std::cout << "dotp(z axis, r_axis) = "
                              << dot_prod(z_axis, r_axis) << std::endl;
                }
                assert(fabs(length(r_axis) - 1e0) < 1e-12);
                assert(fabs(length(z_axis) - 1e0) < 1e-12);
            }
            ~CylindricalCoordinate(){};

            std::array<double, 3> translate(const Realvec& position) const;
            Realvec translate(const std::array<double, 3>& position) const;

            Realvec get_center() const {return center;}
            Realvec get_r_axis() const {return r_axis;}
            Realvec get_z_axis() const {return z_axis;}

        private:
            const Realvec center;
            const Realvec r_axis;
            Realvec z_axis;
    };

    std::array<double, 3> CylindricalCoordinate::translate(
                                                    const Realvec& position) const
    {
        Realvec relative_position = position - center;
        double z = dot_prod(relative_position, z_axis);
        Realvec planner = relative_position - (z*z_axis);
        double r = length(planner);
        double theta = acos(dot_prod(planner, r_axis)/r);

        if(dot_prod(cross_prod(planner, r_axis), z_axis) > 0e0)
            theta *= -1e0;

        return std::array<double, 3>({{r, theta, z}});
    }

    Realvec CylindricalCoordinate::translate(const std::array<double, 3>&
                                                                 position) const
    {
        return center
             + rotation(position[1], z_axis, position[0] * r_axis)
             + position[2] * z_axis;
    }

}

#endif//COFFEE_MILL_CYLINDRICAL_COORDINATE
<|endoftext|>


<commit_before><commit_msg>FIRE-6485; check mesh repo thread before actively using it.<commit_after><|endoftext|>


<commit_before>#include "BaseItem.h"
#include "../resources/Constants.h"

namespace NSDocxRenderer
{
        CBaseItem& CBaseItem::operator=(const CBaseItem& oSrc)
        {
            if (this == &oSrc)
            {
                return *this;
            }

            m_eType                 = oSrc.m_eType;
            m_bIsNotNecessaryToUse	= oSrc.m_bIsNotNecessaryToUse;

            m_dLeft = oSrc.m_dLeft;
            m_dTop = oSrc.m_dTop;
            m_dWidth = oSrc.m_dWidth;
            m_dHeight = oSrc.m_dHeight;
            m_dBaselinePos = oSrc.m_dBaselinePos;
            m_dRight = oSrc.m_dRight;

            return *this;
        }

        bool CBaseItem::IsBigger(const CBaseItem* oSrc)
        {
            return (m_dLeft > oSrc->m_dLeft) ? true : false;
        }

        bool CBaseItem::IsBiggerOrEqual(const CBaseItem* oSrc)
        {
            return (m_dLeft >= oSrc->m_dLeft) ? true : false;
        }

        eVerticalCrossingType CBaseItem::GetVerticalCrossingType(const CBaseItem* oSrc)
        {
            if (m_dTop > oSrc->m_dTop && m_dBaselinePos < oSrc->m_dBaselinePos)
            {
                return eVerticalCrossingType::vctCurrentInsideNext;
            }
            else if (m_dTop < oSrc->m_dTop && m_dBaselinePos > oSrc->m_dBaselinePos)
            {
                return  eVerticalCrossingType::vctCurrentOutsideNext;
            }
            else if (m_dTop < oSrc->m_dTop && m_dBaselinePos < oSrc->m_dBaselinePos && m_dBaselinePos > oSrc->m_dTop)
            {
                return  eVerticalCrossingType::vctCurrentAboveNext;
            }
            else if (m_dTop > oSrc->m_dTop && m_dBaselinePos > oSrc->m_dBaselinePos && m_dTop < oSrc->m_dBaselinePos)
            {
                return  eVerticalCrossingType::vctCurrentBelowNext;
            }
            else if (m_dTop == oSrc->m_dTop && m_dBaselinePos == oSrc->m_dBaselinePos &&
                     m_dLeft == oSrc->m_dLeft && m_dRight == oSrc->m_dRight)
            {
                return  eVerticalCrossingType::vctDublicate;
            }
            else if (fabs(m_dTop - oSrc->m_dTop) < c_dTHE_SAME_STRING_Y_PRECISION_MM)
            {
                return  eVerticalCrossingType::vctTopBordersMatch;
            }
            else if (fabs(m_dBaselinePos - oSrc->m_dBaselinePos) < c_dTHE_SAME_STRING_Y_PRECISION_MM)
            {
                return  eVerticalCrossingType::vctBottomBordersMatch;
            }
            else if (m_dBaselinePos < oSrc->m_dTop)
            {
                return  eVerticalCrossingType::vctNoCrossingCurrentAboveNext;
            }
            else if (m_dTop > oSrc->m_dBaselinePos)
            {
                return  eVerticalCrossingType::vctNoCrossingCurrentBelowNext;
            }
            else
            {
                return  eVerticalCrossingType::vctUnknown;
            }
        }

        eHorizontalCrossingType CBaseItem::GetHorizontalCrossingType(const CBaseItem* oSrc)
        {
            if (m_dLeft > oSrc->m_dLeft && m_dRight < oSrc->m_dRight)
            {
                return eHorizontalCrossingType::hctCurrentInsideNext;
            }
            else if (m_dLeft < oSrc->m_dLeft && m_dRight > oSrc->m_dRight)
            {
                return  eHorizontalCrossingType::hctCurrentOutsideNext;
            }
            else if (m_dLeft < oSrc->m_dLeft && m_dRight < oSrc->m_dRight && m_dRight > oSrc->m_dLeft)
            {
                return  eHorizontalCrossingType::hctCurrentLeftOfNext;
            }
            else if (m_dLeft > oSrc->m_dLeft && m_dRight > oSrc->m_dRight && m_dLeft < oSrc->m_dRight)
            {
                return  eHorizontalCrossingType::hctCurrentRightOfNext;
            }
            else if (m_dLeft == oSrc->m_dLeft && m_dRight == oSrc->m_dRight &&
                     m_dTop == oSrc->m_dTop && m_dBaselinePos == oSrc->m_dBaselinePos)
            {
                return  eHorizontalCrossingType::hctDublicate;
            }
            else if (fabs(m_dLeft - oSrc->m_dLeft) < c_dTHE_SAME_STRING_Y_PRECISION_MM)
            {
                return  eHorizontalCrossingType::hctLeftBordersMatch;
            }
            else if (fabs(m_dRight - oSrc->m_dRight) < c_dTHE_SAME_STRING_Y_PRECISION_MM)
            {
                return  eHorizontalCrossingType::hctRightBordersMatch;
            }
            else if (m_dRight < oSrc->m_dLeft)
            {
                return  eHorizontalCrossingType::hctNoCrossingCurrentLeftOfNext;
            }
            else if (m_dLeft > oSrc->m_dRight)
            {
                return  eHorizontalCrossingType::hctNoCrossingCurrentRightOfNext;
            }
            else
            {
                return  eHorizontalCrossingType::hctUnknown;
            }
        }
}
<commit_msg>Fix mac build<commit_after>#include "BaseItem.h"
#include "../resources/Constants.h"
#include <math.h>

namespace NSDocxRenderer
{
        CBaseItem& CBaseItem::operator=(const CBaseItem& oSrc)
        {
            if (this == &oSrc)
            {
                return *this;
            }

            m_eType                 = oSrc.m_eType;
            m_bIsNotNecessaryToUse	= oSrc.m_bIsNotNecessaryToUse;

            m_dLeft = oSrc.m_dLeft;
            m_dTop = oSrc.m_dTop;
            m_dWidth = oSrc.m_dWidth;
            m_dHeight = oSrc.m_dHeight;
            m_dBaselinePos = oSrc.m_dBaselinePos;
            m_dRight = oSrc.m_dRight;

            return *this;
        }

        bool CBaseItem::IsBigger(const CBaseItem* oSrc)
        {
            return (m_dLeft > oSrc->m_dLeft) ? true : false;
        }

        bool CBaseItem::IsBiggerOrEqual(const CBaseItem* oSrc)
        {
            return (m_dLeft >= oSrc->m_dLeft) ? true : false;
        }

        eVerticalCrossingType CBaseItem::GetVerticalCrossingType(const CBaseItem* oSrc)
        {
            if (m_dTop > oSrc->m_dTop && m_dBaselinePos < oSrc->m_dBaselinePos)
            {
                return eVerticalCrossingType::vctCurrentInsideNext;
            }
            else if (m_dTop < oSrc->m_dTop && m_dBaselinePos > oSrc->m_dBaselinePos)
            {
                return  eVerticalCrossingType::vctCurrentOutsideNext;
            }
            else if (m_dTop < oSrc->m_dTop && m_dBaselinePos < oSrc->m_dBaselinePos && m_dBaselinePos > oSrc->m_dTop)
            {
                return  eVerticalCrossingType::vctCurrentAboveNext;
            }
            else if (m_dTop > oSrc->m_dTop && m_dBaselinePos > oSrc->m_dBaselinePos && m_dTop < oSrc->m_dBaselinePos)
            {
                return  eVerticalCrossingType::vctCurrentBelowNext;
            }
            else if (m_dTop == oSrc->m_dTop && m_dBaselinePos == oSrc->m_dBaselinePos &&
                     m_dLeft == oSrc->m_dLeft && m_dRight == oSrc->m_dRight)
            {
                return  eVerticalCrossingType::vctDublicate;
            }
            else if (fabs(m_dTop - oSrc->m_dTop) < c_dTHE_SAME_STRING_Y_PRECISION_MM)
            {
                return  eVerticalCrossingType::vctTopBordersMatch;
            }
            else if (fabs(m_dBaselinePos - oSrc->m_dBaselinePos) < c_dTHE_SAME_STRING_Y_PRECISION_MM)
            {
                return  eVerticalCrossingType::vctBottomBordersMatch;
            }
            else if (m_dBaselinePos < oSrc->m_dTop)
            {
                return  eVerticalCrossingType::vctNoCrossingCurrentAboveNext;
            }
            else if (m_dTop > oSrc->m_dBaselinePos)
            {
                return  eVerticalCrossingType::vctNoCrossingCurrentBelowNext;
            }
            else
            {
                return  eVerticalCrossingType::vctUnknown;
            }
        }

        eHorizontalCrossingType CBaseItem::GetHorizontalCrossingType(const CBaseItem* oSrc)
        {
            if (m_dLeft > oSrc->m_dLeft && m_dRight < oSrc->m_dRight)
            {
                return eHorizontalCrossingType::hctCurrentInsideNext;
            }
            else if (m_dLeft < oSrc->m_dLeft && m_dRight > oSrc->m_dRight)
            {
                return  eHorizontalCrossingType::hctCurrentOutsideNext;
            }
            else if (m_dLeft < oSrc->m_dLeft && m_dRight < oSrc->m_dRight && m_dRight > oSrc->m_dLeft)
            {
                return  eHorizontalCrossingType::hctCurrentLeftOfNext;
            }
            else if (m_dLeft > oSrc->m_dLeft && m_dRight > oSrc->m_dRight && m_dLeft < oSrc->m_dRight)
            {
                return  eHorizontalCrossingType::hctCurrentRightOfNext;
            }
            else if (m_dLeft == oSrc->m_dLeft && m_dRight == oSrc->m_dRight &&
                     m_dTop == oSrc->m_dTop && m_dBaselinePos == oSrc->m_dBaselinePos)
            {
                return  eHorizontalCrossingType::hctDublicate;
            }
            else if (fabs(m_dLeft - oSrc->m_dLeft) < c_dTHE_SAME_STRING_Y_PRECISION_MM)
            {
                return  eHorizontalCrossingType::hctLeftBordersMatch;
            }
            else if (fabs(m_dRight - oSrc->m_dRight) < c_dTHE_SAME_STRING_Y_PRECISION_MM)
            {
                return  eHorizontalCrossingType::hctRightBordersMatch;
            }
            else if (m_dRight < oSrc->m_dLeft)
            {
                return  eHorizontalCrossingType::hctNoCrossingCurrentLeftOfNext;
            }
            else if (m_dLeft > oSrc->m_dRight)
            {
                return  eHorizontalCrossingType::hctNoCrossingCurrentRightOfNext;
            }
            else
            {
                return  eHorizontalCrossingType::hctUnknown;
            }
        }
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/base/mock_ffmpeg.h"
#include "media/base/mock_filters.h"
#include "media/ffmpeg/ffmpeg_common.h"
#include "media/filters/ffmpeg_glue.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::_;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::Return;
using ::testing::SetArgumentPointee;
using ::testing::StrictMock;

namespace media {

class MockProtocol : public FFmpegURLProtocol {
 public:
  MockProtocol() {
  }

  MOCK_METHOD2(Read, int(int size, uint8* data));
  MOCK_METHOD1(GetPosition, bool(int64* position_out));
  MOCK_METHOD1(SetPosition, bool(int64 position));
  MOCK_METHOD1(GetSize, bool(int64* size_out));
  MOCK_METHOD0(IsStreaming, bool());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockProtocol);
};

class FFmpegGlueTest : public ::testing::Test {
 public:
  FFmpegGlueTest() {
    MockFFmpeg::set(&mock_ffmpeg_);
  }

  virtual ~FFmpegGlueTest() {
    MockFFmpeg::set(NULL);
  }

  // Helper to open a URLContext pointing to the given mocked protocol.
  // Callers are expected to close the context at the end of their test.
  virtual void OpenContext(MockProtocol* protocol, URLContext* context) {
    // IsStreaming() is called when opening.
    EXPECT_CALL(*protocol, IsStreaming()).WillOnce(Return(true));

    // Add the protocol to the glue layer and open a context.
    std::string key = FFmpegGlue::get()->AddProtocol(protocol);
    memset(context, 0, sizeof(*context));
    EXPECT_EQ(0, protocol_->url_open(context, key.c_str(), 0));
    FFmpegGlue::get()->RemoveProtocol(protocol);
  }

 protected:
  // Fixture members.
  MockFFmpeg mock_ffmpeg_;
  static URLProtocol* protocol_;

 private:
  DISALLOW_COPY_AND_ASSIGN(FFmpegGlueTest);
};

URLProtocol* FFmpegGlueTest::protocol_ = NULL;

TEST_F(FFmpegGlueTest, InitializeFFmpeg) {
  // Singleton should initialize FFmpeg.
  FFmpegGlue* glue = FFmpegGlue::get();
  EXPECT_TRUE(glue);

  // Assign our static copy of URLProtocol for the rest of the tests.
  protocol_ = MockFFmpeg::protocol();

  // Make sure URLProtocol was filled out correctly.
  EXPECT_STREQ("http", protocol_->name);
  EXPECT_TRUE(protocol_->url_close);
  EXPECT_TRUE(protocol_->url_open);
  EXPECT_TRUE(protocol_->url_read);
  EXPECT_TRUE(protocol_->url_seek);
  EXPECT_TRUE(protocol_->url_write);
}

TEST_F(FFmpegGlueTest, AddRemoveGetProtocol) {
  // Prepare testing data.
  FFmpegGlue* glue = FFmpegGlue::get();

  // Create our protocols and add them to the glue layer.
  scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol_a(
      new StrictMock<Destroyable<MockProtocol> >());
  scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol_b(
      new StrictMock<Destroyable<MockProtocol> >());

  // Make sure the keys are unique.
  std::string key_a = glue->AddProtocol(protocol_a.get());
  std::string key_b = glue->AddProtocol(protocol_b.get());
  EXPECT_EQ(0u, key_a.find("http://"));
  EXPECT_EQ(0u, key_b.find("http://"));
  EXPECT_NE(key_a, key_b);

  // Our keys should return our protocols.
  FFmpegURLProtocol* protocol_c;
  FFmpegURLProtocol* protocol_d;
  glue->GetProtocol(key_a, &protocol_c);
  glue->GetProtocol(key_b, &protocol_d);
  EXPECT_EQ(protocol_a.get(), protocol_c);
  EXPECT_EQ(protocol_b.get(), protocol_d);

  // Adding the same Protocol should create the same key and not add an extra
  // reference.
  std::string key_a2 = glue->AddProtocol(protocol_a.get());
  EXPECT_EQ(key_a, key_a2);
  glue->GetProtocol(key_a2, &protocol_c);
  EXPECT_EQ(protocol_a.get(), protocol_c);

  // Removes the protocols then releases our references.  They should be
  // destroyed.
  InSequence s;
  EXPECT_CALL(*protocol_a, OnDestroy());
  EXPECT_CALL(*protocol_b, OnDestroy());
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(0));

  glue->RemoveProtocol(protocol_a.get());
  glue->GetProtocol(key_a, &protocol_c);
  EXPECT_FALSE(protocol_c);
  glue->GetProtocol(key_b, &protocol_d);
  EXPECT_EQ(protocol_b.get(), protocol_d);
  glue->RemoveProtocol(protocol_b.get());
  glue->GetProtocol(key_b, &protocol_d);
  EXPECT_FALSE(protocol_d);
  protocol_a.reset();
  protocol_b.reset();

  // Data sources should be deleted by this point.
  mock_ffmpeg_.CheckPoint(0);
}

TEST_F(FFmpegGlueTest, OpenClose) {
  // Prepare testing data.
  FFmpegGlue* glue = FFmpegGlue::get();

  // Create our protocol and add them to the glue layer.
  scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol(
      new StrictMock<Destroyable<MockProtocol> >());
  EXPECT_CALL(*protocol, IsStreaming()).WillOnce(Return(true));
  std::string key = glue->AddProtocol(protocol.get());

  // Prepare FFmpeg URLContext structure.
  URLContext context;
  memset(&context, 0, sizeof(context));

  // Test opening a URLContext with a protocol that doesn't exist.
  EXPECT_EQ(AVERROR_IO, protocol_->url_open(&context, "foobar", 0));

  // Test opening a URLContext with our protocol.
  EXPECT_EQ(0, protocol_->url_open(&context, key.c_str(), 0));
  EXPECT_EQ(URL_RDONLY, context.flags);
  EXPECT_EQ(protocol.get(), context.priv_data);
  EXPECT_TRUE(context.is_streamed);

  // We're going to remove references one by one until the last reference is
  // held by FFmpeg.  Once we close the URLContext, the protocol should be
  // destroyed.
  InSequence s;
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(0));
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(1));
  EXPECT_CALL(*protocol, OnDestroy());
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(2));

  // Remove the protocol from the glue layer, releasing a reference.
  glue->RemoveProtocol(protocol.get());
  mock_ffmpeg_.CheckPoint(0);

  // Remove our own reference -- URLContext should maintain a reference.
  mock_ffmpeg_.CheckPoint(1);
  protocol.reset();

  // Close the URLContext, which should release the final reference.
  EXPECT_EQ(0, protocol_->url_close(&context));
  mock_ffmpeg_.CheckPoint(2);
}

TEST_F(FFmpegGlueTest, Write) {
  scoped_ptr<StrictMock<MockProtocol> > protocol(
      new StrictMock<MockProtocol>());
  URLContext context;
  OpenContext(protocol.get(), &context);

  const int kBufferSize = 16;
  uint8 buffer[kBufferSize];

  // Writing should always fail and never call the protocol.
  EXPECT_EQ(AVERROR_IO, protocol_->url_write(&context, NULL, 0));
  EXPECT_EQ(AVERROR_IO, protocol_->url_write(&context, buffer, 0));
  EXPECT_EQ(AVERROR_IO, protocol_->url_write(&context, buffer, kBufferSize));

  // Destroy the protocol.
  protocol_->url_close(&context);
}

TEST_F(FFmpegGlueTest, Read) {
  scoped_ptr<StrictMock<MockProtocol> > protocol(
      new StrictMock<MockProtocol>());
  URLContext context;
  OpenContext(protocol.get(), &context);

  const int kBufferSize = 16;
  uint8 buffer[kBufferSize];

  // Reads are for the most part straight-through calls to Read().
  InSequence s;
  EXPECT_CALL(*protocol, Read(0, buffer))
      .WillOnce(Return(0));
  EXPECT_CALL(*protocol, Read(kBufferSize, buffer))
      .WillOnce(Return(kBufferSize));
  EXPECT_CALL(*protocol, Read(kBufferSize, buffer))
      .WillOnce(Return(DataSource::kReadError));

  EXPECT_EQ(0, protocol_->url_read(&context, buffer, 0));
  EXPECT_EQ(kBufferSize, protocol_->url_read(&context, buffer, kBufferSize));
  EXPECT_EQ(AVERROR_IO, protocol_->url_read(&context, buffer, kBufferSize));

  // Destroy the protocol.
  protocol_->url_close(&context);
}

TEST_F(FFmpegGlueTest, Seek) {
  scoped_ptr<StrictMock<MockProtocol> > protocol(
      new StrictMock<MockProtocol>());
  URLContext context;
  OpenContext(protocol.get(), &context);

  // SEEK_SET should be a straight-through call to SetPosition(), which when
  // successful will return the result from GetPosition().
  InSequence s;
  EXPECT_CALL(*protocol, SetPosition(-16))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, SetPosition(16))
      .WillOnce(Return(true));
  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true)));

  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, -16, SEEK_SET));
  EXPECT_EQ(8, protocol_->url_seek(&context, 16, SEEK_SET));

  // SEEK_CUR should call GetPosition() first, and if it succeeds add the offset
  // to the result then call SetPosition()+GetPosition().
  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true)));
  EXPECT_CALL(*protocol, SetPosition(16))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true)));
  EXPECT_CALL(*protocol, SetPosition(16))
      .WillOnce(Return(true));
  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true)));

  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, 8, SEEK_CUR));
  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, 8, SEEK_CUR));
  EXPECT_EQ(16, protocol_->url_seek(&context, 8, SEEK_CUR));

  // SEEK_END should call GetSize() first, and if it succeeds add the offset
  // to the result then call SetPosition()+GetPosition().
  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true)));
  EXPECT_CALL(*protocol, SetPosition(8))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true)));
  EXPECT_CALL(*protocol, SetPosition(8))
      .WillOnce(Return(true));
  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true)));

  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, -8, SEEK_END));
  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, -8, SEEK_END));
  EXPECT_EQ(8, protocol_->url_seek(&context, -8, SEEK_END));

  // AVSEEK_SIZE should be a straight-through call to GetSize().
  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true)));

  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, 0, AVSEEK_SIZE));
  EXPECT_EQ(16, protocol_->url_seek(&context, 0, AVSEEK_SIZE));

  // Destroy the protocol.
  protocol_->url_close(&context);
}

TEST_F(FFmpegGlueTest, Destroy) {
  // Create our protocol and add them to the glue layer.
  scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol(
      new StrictMock<Destroyable<MockProtocol> >());
  std::string key = FFmpegGlue::get()->AddProtocol(protocol.get());

  // We should expect the protocol to get destroyed when the unit test
  // exits.
  InSequence s;
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(0));
  EXPECT_CALL(*protocol, OnDestroy());

  // Remove our own reference, we shouldn't be destroyed yet.
  mock_ffmpeg_.CheckPoint(0);
  protocol.reset();

  // ~FFmpegGlue() will be called when this unit test finishes execution.  By
  // leaving something inside FFmpegGlue's map we get to test our cleanup code.
}

}  // namespace media
<commit_msg>Disable FFmpegGlueTest.Write and friends<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/base/mock_ffmpeg.h"
#include "media/base/mock_filters.h"
#include "media/ffmpeg/ffmpeg_common.h"
#include "media/filters/ffmpeg_glue.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::_;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::Return;
using ::testing::SetArgumentPointee;
using ::testing::StrictMock;

namespace media {

class MockProtocol : public FFmpegURLProtocol {
 public:
  MockProtocol() {
  }

  MOCK_METHOD2(Read, int(int size, uint8* data));
  MOCK_METHOD1(GetPosition, bool(int64* position_out));
  MOCK_METHOD1(SetPosition, bool(int64 position));
  MOCK_METHOD1(GetSize, bool(int64* size_out));
  MOCK_METHOD0(IsStreaming, bool());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockProtocol);
};

class FFmpegGlueTest : public ::testing::Test {
 public:
  FFmpegGlueTest() {
    MockFFmpeg::set(&mock_ffmpeg_);
  }

  virtual ~FFmpegGlueTest() {
    MockFFmpeg::set(NULL);
  }

  // Helper to open a URLContext pointing to the given mocked protocol.
  // Callers are expected to close the context at the end of their test.
  virtual void OpenContext(MockProtocol* protocol, URLContext* context) {
    // IsStreaming() is called when opening.
    EXPECT_CALL(*protocol, IsStreaming()).WillOnce(Return(true));

    // Add the protocol to the glue layer and open a context.
    std::string key = FFmpegGlue::get()->AddProtocol(protocol);
    memset(context, 0, sizeof(*context));
    EXPECT_EQ(0, protocol_->url_open(context, key.c_str(), 0));
    FFmpegGlue::get()->RemoveProtocol(protocol);
  }

 protected:
  // Fixture members.
  MockFFmpeg mock_ffmpeg_;
  static URLProtocol* protocol_;

 private:
  DISALLOW_COPY_AND_ASSIGN(FFmpegGlueTest);
};

URLProtocol* FFmpegGlueTest::protocol_ = NULL;

TEST_F(FFmpegGlueTest, InitializeFFmpeg) {
  // Singleton should initialize FFmpeg.
  FFmpegGlue* glue = FFmpegGlue::get();
  EXPECT_TRUE(glue);

  // Assign our static copy of URLProtocol for the rest of the tests.
  protocol_ = MockFFmpeg::protocol();

  // Make sure URLProtocol was filled out correctly.
  EXPECT_STREQ("http", protocol_->name);
  EXPECT_TRUE(protocol_->url_close);
  EXPECT_TRUE(protocol_->url_open);
  EXPECT_TRUE(protocol_->url_read);
  EXPECT_TRUE(protocol_->url_seek);
  EXPECT_TRUE(protocol_->url_write);
}

TEST_F(FFmpegGlueTest, AddRemoveGetProtocol) {
  // Prepare testing data.
  FFmpegGlue* glue = FFmpegGlue::get();

  // Create our protocols and add them to the glue layer.
  scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol_a(
      new StrictMock<Destroyable<MockProtocol> >());
  scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol_b(
      new StrictMock<Destroyable<MockProtocol> >());

  // Make sure the keys are unique.
  std::string key_a = glue->AddProtocol(protocol_a.get());
  std::string key_b = glue->AddProtocol(protocol_b.get());
  EXPECT_EQ(0u, key_a.find("http://"));
  EXPECT_EQ(0u, key_b.find("http://"));
  EXPECT_NE(key_a, key_b);

  // Our keys should return our protocols.
  FFmpegURLProtocol* protocol_c;
  FFmpegURLProtocol* protocol_d;
  glue->GetProtocol(key_a, &protocol_c);
  glue->GetProtocol(key_b, &protocol_d);
  EXPECT_EQ(protocol_a.get(), protocol_c);
  EXPECT_EQ(protocol_b.get(), protocol_d);

  // Adding the same Protocol should create the same key and not add an extra
  // reference.
  std::string key_a2 = glue->AddProtocol(protocol_a.get());
  EXPECT_EQ(key_a, key_a2);
  glue->GetProtocol(key_a2, &protocol_c);
  EXPECT_EQ(protocol_a.get(), protocol_c);

  // Removes the protocols then releases our references.  They should be
  // destroyed.
  InSequence s;
  EXPECT_CALL(*protocol_a, OnDestroy());
  EXPECT_CALL(*protocol_b, OnDestroy());
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(0));

  glue->RemoveProtocol(protocol_a.get());
  glue->GetProtocol(key_a, &protocol_c);
  EXPECT_FALSE(protocol_c);
  glue->GetProtocol(key_b, &protocol_d);
  EXPECT_EQ(protocol_b.get(), protocol_d);
  glue->RemoveProtocol(protocol_b.get());
  glue->GetProtocol(key_b, &protocol_d);
  EXPECT_FALSE(protocol_d);
  protocol_a.reset();
  protocol_b.reset();

  // Data sources should be deleted by this point.
  mock_ffmpeg_.CheckPoint(0);
}

TEST_F(FFmpegGlueTest, OpenClose) {
  // Prepare testing data.
  FFmpegGlue* glue = FFmpegGlue::get();

  // Create our protocol and add them to the glue layer.
  scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol(
      new StrictMock<Destroyable<MockProtocol> >());
  EXPECT_CALL(*protocol, IsStreaming()).WillOnce(Return(true));
  std::string key = glue->AddProtocol(protocol.get());

  // Prepare FFmpeg URLContext structure.
  URLContext context;
  memset(&context, 0, sizeof(context));

  // Test opening a URLContext with a protocol that doesn't exist.
  EXPECT_EQ(AVERROR_IO, protocol_->url_open(&context, "foobar", 0));

  // Test opening a URLContext with our protocol.
  EXPECT_EQ(0, protocol_->url_open(&context, key.c_str(), 0));
  EXPECT_EQ(URL_RDONLY, context.flags);
  EXPECT_EQ(protocol.get(), context.priv_data);
  EXPECT_TRUE(context.is_streamed);

  // We're going to remove references one by one until the last reference is
  // held by FFmpeg.  Once we close the URLContext, the protocol should be
  // destroyed.
  InSequence s;
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(0));
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(1));
  EXPECT_CALL(*protocol, OnDestroy());
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(2));

  // Remove the protocol from the glue layer, releasing a reference.
  glue->RemoveProtocol(protocol.get());
  mock_ffmpeg_.CheckPoint(0);

  // Remove our own reference -- URLContext should maintain a reference.
  mock_ffmpeg_.CheckPoint(1);
  protocol.reset();

  // Close the URLContext, which should release the final reference.
  EXPECT_EQ(0, protocol_->url_close(&context));
  mock_ffmpeg_.CheckPoint(2);
}

TEST_F(FFmpegGlueTest, DISABLED_Write) {
  scoped_ptr<StrictMock<MockProtocol> > protocol(
      new StrictMock<MockProtocol>());
  URLContext context;
  OpenContext(protocol.get(), &context);

  const int kBufferSize = 16;
  uint8 buffer[kBufferSize];

  // Writing should always fail and never call the protocol.
  EXPECT_EQ(AVERROR_IO, protocol_->url_write(&context, NULL, 0));
  EXPECT_EQ(AVERROR_IO, protocol_->url_write(&context, buffer, 0));
  EXPECT_EQ(AVERROR_IO, protocol_->url_write(&context, buffer, kBufferSize));

  // Destroy the protocol.
  protocol_->url_close(&context);
}

TEST_F(FFmpegGlueTest, DISABLED_Read) {
  scoped_ptr<StrictMock<MockProtocol> > protocol(
      new StrictMock<MockProtocol>());
  URLContext context;
  OpenContext(protocol.get(), &context);

  const int kBufferSize = 16;
  uint8 buffer[kBufferSize];

  // Reads are for the most part straight-through calls to Read().
  InSequence s;
  EXPECT_CALL(*protocol, Read(0, buffer))
      .WillOnce(Return(0));
  EXPECT_CALL(*protocol, Read(kBufferSize, buffer))
      .WillOnce(Return(kBufferSize));
  EXPECT_CALL(*protocol, Read(kBufferSize, buffer))
      .WillOnce(Return(DataSource::kReadError));

  EXPECT_EQ(0, protocol_->url_read(&context, buffer, 0));
  EXPECT_EQ(kBufferSize, protocol_->url_read(&context, buffer, kBufferSize));
  EXPECT_EQ(AVERROR_IO, protocol_->url_read(&context, buffer, kBufferSize));

  // Destroy the protocol.
  protocol_->url_close(&context);
}

TEST_F(FFmpegGlueTest, DISABLED_Seek) {
  scoped_ptr<StrictMock<MockProtocol> > protocol(
      new StrictMock<MockProtocol>());
  URLContext context;
  OpenContext(protocol.get(), &context);

  // SEEK_SET should be a straight-through call to SetPosition(), which when
  // successful will return the result from GetPosition().
  InSequence s;
  EXPECT_CALL(*protocol, SetPosition(-16))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, SetPosition(16))
      .WillOnce(Return(true));
  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true)));

  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, -16, SEEK_SET));
  EXPECT_EQ(8, protocol_->url_seek(&context, 16, SEEK_SET));

  // SEEK_CUR should call GetPosition() first, and if it succeeds add the offset
  // to the result then call SetPosition()+GetPosition().
  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true)));
  EXPECT_CALL(*protocol, SetPosition(16))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true)));
  EXPECT_CALL(*protocol, SetPosition(16))
      .WillOnce(Return(true));
  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true)));

  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, 8, SEEK_CUR));
  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, 8, SEEK_CUR));
  EXPECT_EQ(16, protocol_->url_seek(&context, 8, SEEK_CUR));

  // SEEK_END should call GetSize() first, and if it succeeds add the offset
  // to the result then call SetPosition()+GetPosition().
  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true)));
  EXPECT_CALL(*protocol, SetPosition(8))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true)));
  EXPECT_CALL(*protocol, SetPosition(8))
      .WillOnce(Return(true));
  EXPECT_CALL(*protocol, GetPosition(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true)));

  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, -8, SEEK_END));
  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, -8, SEEK_END));
  EXPECT_EQ(8, protocol_->url_seek(&context, -8, SEEK_END));

  // AVSEEK_SIZE should be a straight-through call to GetSize().
  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(Return(false));

  EXPECT_CALL(*protocol, GetSize(_))
      .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true)));

  EXPECT_EQ(AVERROR_IO, protocol_->url_seek(&context, 0, AVSEEK_SIZE));
  EXPECT_EQ(16, protocol_->url_seek(&context, 0, AVSEEK_SIZE));

  // Destroy the protocol.
  protocol_->url_close(&context);
}

TEST_F(FFmpegGlueTest, DISABLED_Destroy) {
  // Create our protocol and add them to the glue layer.
  scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol(
      new StrictMock<Destroyable<MockProtocol> >());
  std::string key = FFmpegGlue::get()->AddProtocol(protocol.get());

  // We should expect the protocol to get destroyed when the unit test
  // exits.
  InSequence s;
  EXPECT_CALL(mock_ffmpeg_, CheckPoint(0));
  EXPECT_CALL(*protocol, OnDestroy());

  // Remove our own reference, we shouldn't be destroyed yet.
  mock_ffmpeg_.CheckPoint(0);
  protocol.reset();

  // ~FFmpegGlue() will be called when this unit test finishes execution.  By
  // leaving something inside FFmpegGlue's map we get to test our cleanup code.
}

}  // namespace media
<|endoftext|>


<commit_before><commit_msg>Only print GS multi-stream log info when GS is present<commit_after><|endoftext|>


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

#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
#include <iostream>  // cpplint: Streams are highly discouraged.
#include <fstream>   // cpplint: Streams are highly discouraged.

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

#include "utils/log_message_loop_thread.h"
#include "utils/logger.h"

#include "./life_cycle.h"
#include "signal_handlers.h"

#include "utils/signals.h"
#include "utils/system.h"
#include "config_profile/profile.h"
#include "utils/appenders_loader.h"

#if defined(EXTENDED_MEDIA_MODE)
#include <gst/gst.h>
#endif

#include "media_manager/media_manager_impl.h"
// ----------------------------------------------------------------------------
// Third-Party includes
#include "networking.h"  // cpplint: Include the directory when naming .h files

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

CREATE_LOGGERPTR_GLOBAL(logger_, "appMain")

namespace {

const std::string kBrowser = "/usr/bin/chromium-browser";
const std::string kBrowserName = "chromium-browser";
const std::string kBrowserParams = "--auth-schemes=basic,digest,ntlm";
const std::string kLocalHostAddress = "127.0.0.1";

#ifdef WEB_HMI
/**
 * Initialize HTML based HMI.
 * @return true if success otherwise false.
 */
bool InitHmi() {
  std::string hmi_link = profile::Profile::instance()->link_to_web_hmi();
  struct stat sb;
  if (stat(hmi_link.c_str(), &sb) == -1) {
    LOG4CXX_FATAL(logger_, "HMI index file " << hmi_link << " doesn't exist!");
    return false;
  }
  return utils::System(kBrowser, kBrowserName).Add(kBrowserParams).Add(hmi_link)
      .Execute();
}
#endif  // WEB_HMI

#ifdef QT_HMI
/**
 * Initialize HTML based HMI.
 * @return true if success otherwise false.
 */
bool InitHmi() {
  std::string kStartHmi = "./start_hmi.sh";
  struct stat sb;
  if (stat(kStartHmi.c_str(), &sb) == -1) {
    LOG4CXX_FATAL(logger_, "HMI start script doesn't exist!");
    return false;
  }

  return utils::System(kStartHmi).Execute();
}
#endif  // QT_HMI

}

/**
 * \brief Entry point of the program.
 * \param argc number of argument
 * \param argv array of arguments
 * \return EXIT_SUCCESS or EXIT_FAILURE
 */
int32_t main(int32_t argc, char** argv) {

  // --------------------------------------------------------------------------
  // Logger initialization
  INIT_LOGGER("log4cxx.properties");
#if defined(__QNXNTO__) and defined(GCOV_ENABLED)
  LOG4CXX_WARN(logger_,
                "Attention! This application was built with unsupported "
                "configuration (gcov + QNX). Use it at your own risk.");
#endif

  threads::Thread::SetNameForId(threads::Thread::CurrentId(), "MainThread");

  if (!utils::appenders_loader.Loaded()) {
    LOG4CXX_ERROR(logger_, "Appenders plugin not loaded, file logging disabled");
  }

  LOG4CXX_INFO(logger_, "Application started!");
  LOG4CXX_INFO(logger_, "SDL version: "
                         << profile::Profile::instance()->sdl_version());

  // Initialize gstreamer. Needed to activate debug from the command line.
#if defined(EXTENDED_MEDIA_MODE)
  gst_init(&argc, &argv);
#endif

  // --------------------------------------------------------------------------
  // Components initialization
  if ((argc > 1)&&(0 != argv)) {
      profile::Profile::instance()->config_file_name(argv[1]);
  } else {
      profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
  }

#ifdef __QNX__
  if (profile::Profile::instance()->enable_policy()) {
    if (!utils::System("./init_policy.sh").Execute(true)) {
      LOG4CXX_FATAL(logger_, "Failed to init policy database");
      DEINIT_LOGGER();
      exit(EXIT_FAILURE);
    }
  }
#endif  // __QNX__

  if (!main_namespace::LifeCycle::instance()->StartComponents()) {
    LOG4CXX_FATAL(logger_, "Failed to start components");
    main_namespace::LifeCycle::instance()->StopComponents();
    DEINIT_LOGGER();
    exit(EXIT_FAILURE);
  }

  // --------------------------------------------------------------------------
  // Third-Party components initialization.

  if (!main_namespace::LifeCycle::instance()->InitMessageSystem()) {
    LOG4CXX_FATAL(logger_, "Failed to init message system");
    DEINIT_LOGGER();
    exit(EXIT_FAILURE);
  }
  LOG4CXX_INFO(logger_, "InitMessageBroker successful");

  if (profile::Profile::instance()->launch_hmi()) {
    if (profile::Profile::instance()->server_address() == kLocalHostAddress) {
      LOG4CXX_INFO(logger_, "Start HMI on localhost");

#ifndef NO_HMI
      if (!InitHmi()) {
        LOG4CXX_INFO(logger_, "InitHmi successful");
      } else {
        LOG4CXX_WARN(logger_, "Failed to init HMI");
      }
#endif  // #ifndef NO_HMI
    }
  }
  // --------------------------------------------------------------------------

  main_namespace::LifeCycle::instance()->Run();
  LOG4CXX_INFO(logger_, "Stopping application due to signal caught");

  main_namespace::LifeCycle::instance()->StopComponents();

  LOG4CXX_INFO(logger_, "Application successfully stopped");
  DEINIT_LOGGER();

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

#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
#include <iostream>  // cpplint: Streams are highly discouraged.
#include <fstream>   // cpplint: Streams are highly discouraged.

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

#include "utils/log_message_loop_thread.h"
#include "utils/logger.h"

#include "./life_cycle.h"
#include "signal_handlers.h"

#include "utils/signals.h"
#include "utils/system.h"
#include "config_profile/profile.h"
#include "utils/appenders_loader.h"

#if defined(EXTENDED_MEDIA_MODE)
#include <gst/gst.h>
#endif

#include "media_manager/media_manager_impl.h"
// ----------------------------------------------------------------------------
// Third-Party includes
#include "networking.h"  // cpplint: Include the directory when naming .h files

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

CREATE_LOGGERPTR_GLOBAL(logger_, "appMain")

namespace {

const std::string kBrowser = "/usr/bin/chromium-browser";
const std::string kBrowserName = "chromium-browser";
const std::string kBrowserParams = "--auth-schemes=basic,digest,ntlm";
const std::string kLocalHostAddress = "127.0.0.1";

#ifdef WEB_HMI
/**
 * Initialize HTML based HMI.
 * @return true if success otherwise false.
 */
bool InitHmi() {
  std::string hmi_link = profile::Profile::instance()->link_to_web_hmi();
  struct stat sb;
  if (stat(hmi_link.c_str(), &sb) == -1) {
    LOG4CXX_FATAL(logger_, "HMI index file " << hmi_link << " doesn't exist!");
    return false;
  }
  return utils::System(kBrowser, kBrowserName).Add(kBrowserParams).Add(hmi_link)
      .Execute();
}
#endif  // WEB_HMI

#ifdef QT_HMI
/**
 * Initialize HTML based HMI.
 * @return true if success otherwise false.
 */
bool InitHmi() {
  std::string kStartHmi = "./start_hmi.sh";
  struct stat sb;
  if (stat(kStartHmi.c_str(), &sb) == -1) {
    LOG4CXX_FATAL(logger_, "HMI start script doesn't exist!");
    return false;
  }

  return utils::System(kStartHmi).Execute();
}
#endif  // QT_HMI

}

/**
 * \brief Entry point of the program.
 * \param argc number of argument
 * \param argv array of arguments
 * \return EXIT_SUCCESS or EXIT_FAILURE
 */
int32_t main(int32_t argc, char** argv) {

  // --------------------------------------------------------------------------
  if ((argc > 1)&&(0 != argv)) {
    profile::Profile::instance()->config_file_name(argv[1]);
  } else {
    profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
  }

  // Logger initialization
  INIT_LOGGER("log4cxx.properties");

  threads::Thread::SetNameForId(threads::Thread::CurrentId(), "MainThread");

  if (!utils::appenders_loader.Loaded()) {
    LOG4CXX_ERROR(logger_, "Appenders plugin not loaded, file logging disabled");
  }

  LOG4CXX_INFO(logger_, "Application started!");
  LOG4CXX_INFO(logger_, "SDL version: "
                         << profile::Profile::instance()->sdl_version());

  // --------------------------------------------------------------------------
  // Components initialization
  if (!main_namespace::LifeCycle::instance()->StartComponents()) {
    LOG4CXX_FATAL(logger_, "Failed to start components");
    main_namespace::LifeCycle::instance()->StopComponents();
    DEINIT_LOGGER();
    exit(EXIT_FAILURE);
  }

  // --------------------------------------------------------------------------
  // Third-Party components initialization.

  if (!main_namespace::LifeCycle::instance()->InitMessageSystem()) {
    LOG4CXX_FATAL(logger_, "Failed to init message system");
    DEINIT_LOGGER();
    exit(EXIT_FAILURE);
  }
  LOG4CXX_INFO(logger_, "InitMessageBroker successful");

  if (profile::Profile::instance()->launch_hmi()) {
    if (profile::Profile::instance()->server_address() == kLocalHostAddress) {
      LOG4CXX_INFO(logger_, "Start HMI on localhost");

#ifndef NO_HMI
      if (!InitHmi()) {
        LOG4CXX_INFO(logger_, "InitHmi successful");
      } else {
        LOG4CXX_WARN(logger_, "Failed to init HMI");
      }
#endif  // #ifndef NO_HMI
    }
  }
  // --------------------------------------------------------------------------

  main_namespace::LifeCycle::instance()->Run();
  LOG4CXX_INFO(logger_, "Stopping application due to signal caught");

  main_namespace::LifeCycle::instance()->StopComponents();

  LOG4CXX_INFO(logger_, "Application successfully stopped");
  DEINIT_LOGGER();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Open the two solution files named on standard input, find all
// variables they have in common, and output the Hilbert norms of the
// differences between them.

#include "libmesh.h"

#include "mesh.h"
#include "equation_systems.h"
#include "exact_solution.h"

unsigned int dim = 2; // This gets overridden by most mesh formats

int main(int argc, char** argv)
{
  libMesh::init (argc, argv);
  {
    Mesh mesh1(dim), mesh2(dim);
    EquationSystems es1(mesh1), es2(mesh2);

    std::cout << "Usage: " << argv[0]
              << " coarsemesh coarsesolution finemesh finesolution" << std::endl;

    mesh1.read(argv[1]);
    std::cout << "Loaded coarse mesh " << argv[1] << std::endl;
    es1.read(argv[2], libMeshEnums::READ);
    std::cout << "Loaded coarse solution " << argv[2] << std::endl;
    mesh2.read(argv[3]);
    std::cout << "Loaded fine mesh " << argv[3] << std::endl;
    es2.read(argv[4], libMeshEnums::READ);
    std::cout << "Loaded fine solution " << argv[4] << std::endl;

    ExactSolution exact_sol(es1);
    exact_sol.attach_reference_solution(&es2);

    std::vector<std::string> sysnames;
    sysnames.reserve(es1.n_systems());

    for (unsigned int i = 0; i != es1.n_systems(); ++i)
      if (es2.has_system(es1.get_system(i).name()))
        sysnames.push_back(es1.get_system(i).name());

    for (unsigned int i = 0; i != sysnames.size(); ++i)
      {
        std::string sysname = sysnames[i];
        System &sys1 = es1.get_system(sysname);
        System &sys2 = es2.get_system(sysname);

        for (unsigned int j = 0; j != sys1.n_vars(); ++j)
          {
            std::string varname = sys1.variable_name(j);

            if (!sys2.has_variable(varname))
              continue;

            exact_sol.compute_error(sysname, varname);

            std::cout << "Errors in system " << sysname << ", variable " << varname << ":" << std::endl;
            std::cout << "L2 error: " << exact_sol.l2_error(sysname, varname) << std::endl;
            std::cout << "H1 error: " << exact_sol.h1_error(sysname, varname) << std::endl;
            std::cout << "H2 error: " << exact_sol.h2_error(sysname, varname) << std::endl;
          }
      }
  }
  return libMesh::close();
}
<commit_msg>Use LibMeshInit<commit_after>// Open the two solution files named on standard input, find all
// variables they have in common, and output the Hilbert norms of the
// differences between them.

#include "libmesh.h"

#include "mesh.h"
#include "equation_systems.h"
#include "exact_solution.h"

unsigned int dim = 2; // This gets overridden by most mesh formats

int main(int argc, char** argv)
{
  LibMeshInit init(argc, argv);

  Mesh mesh1(dim), mesh2(dim);
  EquationSystems es1(mesh1), es2(mesh2);

  std::cout << "Usage: " << argv[0]
            << " coarsemesh coarsesolution finemesh finesolution" << std::endl;

  mesh1.read(argv[1]);
  std::cout << "Loaded coarse mesh " << argv[1] << std::endl;
  es1.read(argv[2], libMeshEnums::READ);
  std::cout << "Loaded coarse solution " << argv[2] << std::endl;
  mesh2.read(argv[3]);
  std::cout << "Loaded fine mesh " << argv[3] << std::endl;
  es2.read(argv[4], libMeshEnums::READ);
  std::cout << "Loaded fine solution " << argv[4] << std::endl;

  ExactSolution exact_sol(es1);
  exact_sol.attach_reference_solution(&es2);

  std::vector<std::string> sysnames;
  sysnames.reserve(es1.n_systems());

  for (unsigned int i = 0; i != es1.n_systems(); ++i)
    if (es2.has_system(es1.get_system(i).name()))
      sysnames.push_back(es1.get_system(i).name());

  for (unsigned int i = 0; i != sysnames.size(); ++i)
    {
      std::string sysname = sysnames[i];
      System &sys1 = es1.get_system(sysname);
      System &sys2 = es2.get_system(sysname);

      for (unsigned int j = 0; j != sys1.n_vars(); ++j)
        {
          std::string varname = sys1.variable_name(j);

          if (!sys2.has_variable(varname))
            continue;

          exact_sol.compute_error(sysname, varname);

          std::cout << "Errors in system " << sysname << ", variable " << varname << ":" << std::endl;
          std::cout << "L2 error: " << exact_sol.l2_error(sysname, varname) << std::endl;
          std::cout << "H1 error: " << exact_sol.h1_error(sysname, varname) << std::endl;
          std::cout << "H2 error: " << exact_sol.h2_error(sysname, varname) << std::endl;
        }
    }

  return 0.;
}
<|endoftext|>