<commit_before>#ifndef HUMPConfig_HPP
#define HUMPConfig_HPP

#include <string>
#include <cstring>
#include <cstdlib>
#include <stdexcept>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <list>
#include <vector>
#include <cmath>
#include <boost/smart_ptr.hpp>
#include <boost/numeric/ublas/storage.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/format.hpp>
#include <fstream>
#include <eigen3/Eigen/Dense>

#include "../config/config.hpp"
#include "object.hpp"

/** version of the library */
#define HUMP_VERSION_MAJOR 2
#define HUMP_VERSION_MINOR 0

//definition of the macro ASSERT
#ifndef DEBUG
    #define ASSERT(x)
#else
    #define ASSERT(x) \
             if (! (x)) \
            { \
               cout << "ERROR!! Assert " << #x << " failed\n"; \
               cout << " on line " << __LINE__  << "\n"; \
               cout << " in file " << __FILE__ << "\n";  \
            }
#endif

using namespace std;
using namespace Eigen;

/** This is the main namespace of the library */
namespace HUMotion{

typedef boost::shared_ptr<Object> objectPtr;/**< shared pointer to an object in the scenario */

const double PHI = (-log(2.0)/log(TB));/**< parameter to control when the bounce posture is reached */
const double AP = 15.0*static_cast<double>(M_PI)/180; /**< aperture of the fingers when approaching to pick [rad] */

const double BLANK_PERCENTAGE = 0.10; /**< percentage of steps to eliminate when either reaching to grasp an object OR move at the beginning of a move movement [0,1]*/

const int N_STEP_MIN = 5; /**< minimum number of steps */
const int N_STEP_MAX = 50; /**< maximum number of steps */

const double W_RED_MIN = 1; /**< minimum value of angular velocity reduction when approaching */
const double W_RED_MAX = 15; /**< maximum value of angular velocity reduction when approaching */

/** this struct defines the Denavit-Hartenberg kinematic parameters */
typedef struct{
    vector<double> d; /**< distances between consecutive frames along the y axes in [mm] */
    vector<double> a; /**< distances between concecutive frames along the z axes in [mm] */
    vector<double> alpha; /**< angle around the x axes between consecutive z axes in [rad] */
    vector<double> theta; /**< angle around the z axes between consecutive x axes in [rad] */
} DHparameters;

/** this struct defines the barrett hand */
typedef struct{
    double maxAperture; /**< [mm] max aperture of the hand in [mm] */
    double Aw; /**< smallest distance between F1 and F2 in [mm] */
    double A1; /**< length of the 1st part of the finger in [mm] */
    double A2; /**< length of the first phalax in [mm] */
    double A3; /**< length of the second phalax in [mm] */
    double D3; /**< depth of the fingertip in [mm] */
    double phi2; /**< angular displacement between the 1st part of the finger and the 1st phalax in [rad] */
    double phi3; /**< angular displacement between the 1st and the 2nd phalax in [rad] */
    vector<int> rk; /**< r parameters of the barrett hand */
    vector<int> jk; /**< j parameters of the barrett hand */
} BarrettHand;

/** this struct defines a human finger */
typedef struct{
    double ux; /**<  position of the finger with respect to the center of the palm along the x axis in [mm] */
    double uy; /**<  position of the finger with respect to the center of the palm along the y axis in [mm] */
    double uz; /**<  position of the finger with respect to the center of the palm along the z axis in [mm] */
    DHparameters finger_specs; /**< the Denavit-Hartenberg parameters of the finger */
} HumanFinger;

/** this struct defines a human thumb */
typedef struct{
    double uTx; /**<  position of the thumb with respect to the center of the palm along the x axis in [mm] */
    double uTy; /**<  position of the thumb with respect to the center of the palm along the y axis in [mm] */
    double uTz; /**<  position of the thumb with respect to the center of the palm along the z axis in [mm] */
    DHparameters thumb_specs; /**< the Denavit-Hartenberg parameters of the thumb */
} HumanThumb;

/** this struct defines a human hand */
typedef struct{
  vector<HumanFinger> fingers; /**< fingers of the hand */
  HumanThumb thumb; /**<  thumb of the hand */
  double maxAperture; /**< max aperture of the hand in [mm] */
} HumanHand;

/** this struct defines the parameters of the movement */
typedef struct{
    int arm_code; /**< the code of the arm: 0 = both arms, 1 = right arm, 2 = left arm */
    int hand_code;/**< the code of the hand: 0 = human hand, 1 = barrett hand */
    int griptype; /**< the type of the grip */
    string mov_infoline; /**< description of the movement */
    double dHO;/**< distanche hand-target*/
    std::vector<double> finalHand;/**< final posture of the hand */
    std::vector<double> target;/**< target / location to reach: target(0)=x, target(1)=y, target(2)=z, target(3)=roll, target(4)=pitch, target(6)=yaw,*/
    objectPtr obj; /**< object involved in the movement. The info of the object have to be updated according to the selected movement */
    bool approach;/**< true to use the approach options, false otherwise  */
    bool retreat;/**< true to use the retreat options, false otherwise */
    std::vector<double> pre_grasp_approach; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/
    std::vector<double> post_grasp_retreat; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/
    std::vector<double> pre_place_approach; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/
    std::vector<double> post_place_retreat; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/
    bool rand_init; /**< true to select randon initialization in "plan" stages */
    bool coll; /**< true to enable collisions with the environment (body of the robot included) */
    bool use_move_plane; /**< true to constrain the end-effector to move on a plane in move movements, false otherwise*/
    std::vector<double> plane_params; /**< plane cartesian parameters in move movements: a*x+b*y+c*z+d=0. a=plane_params(0), b=plane_params(1), c=plane_params(2), d=plane_params(3) */
}mov_params;
/** this struct defines the boundary conditions of the movement*/
typedef struct{
    vector<double> vel_0; /**< initial velocity of the joints in [rad/s] */
    vector<double> vel_f; /**< final velocity of the joints in [rad/s] */
    vector<double> acc_0; /**< initial acceleration of the joints in [rad/s²] */
    vector<double> acc_f; /**< final acceleration of the joints in [rad/s²] */
} boundaryConditions;

/** this struct defines the tolerances that have to be set before planning the trajectory*/
typedef struct{
    mov_params mov_specs; /**< specifications of the movement */
    vector<double> tolsArm; /**< radius of the spheres along the arm in [mm] */
    MatrixXd tolsHand; /**< radius of the spheres along the fingers in [mm] */
    MatrixXd final_tolsObstacles; /**< tolerances of the final posture against the obstacles in [mm] */
    vector< MatrixXd > singleArm_tolsTarget; /**< tolerances of the trajectory against the target in [mm] */
    vector< MatrixXd > singleArm_tolsObstacles; /**< tolerances of the trajectory against the obstacles in [mm] */
    double tolTarPos; /**< tolerance of the final position of the hand against the target in [mm] */
    double tolTarOr; /**< tolerance of the final orientation of the hand against the target in [mm] */
    boundaryConditions bounds; /**< boundary condistions of the bounce problem */
    vector<double> vel_approach; /**< velocity of the joints in [rad/s] at the beginning of the approach stage */
    vector<double> acc_approach; /**< acceleration of the joints in [rad/s²] at the beginning of the approach stage */
    vector<double> lambda_final; /**< weights for the final posture optimization */
    vector<double> lambda_bounce; /**< weights for the bounce posture optimization */
    vector<double> w_max; /**< maximum angular velocity for each joint [rad/s] */
    bool obstacle_avoidance; /**< true to avoid obstacle */
    bool target_avoidance; /**< true to avoid the target during the motion */
} hump_params;

/** This struct defines the result of the planned trajectory */
typedef struct{
    int mov_type;/**< type of the planned movement */
    int status;/**< status code of the planning */
    string status_msg;/**< status message of the planning */
    string object_id;/**< identity of the object involved in the movement */
    vector<MatrixXd> trajectory_stages;/**< sequence of the trajectories */
    vector<MatrixXd> velocity_stages;/**< sequence of the velocities */
    vector<MatrixXd> acceleration_stages;/**< sequence of the accelerations */
    vector<double> time_steps; /**< sequence of each time steps for each trajectory */
    vector<string> trajectory_descriptions;/**< description of the trajectories */
}planning_result;

} // namespace HUMotion

#endif // HUMPConfig_HPP
<commit_msg>bug fixes<commit_after>#ifndef HUMPConfig_HPP
#define HUMPConfig_HPP

#include <string>
#include <cstring>
#include <cstdlib>
#include <stdexcept>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <list>
#include <vector>
#include <cmath>
#include <boost/smart_ptr.hpp>
#include <boost/numeric/ublas/storage.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/format.hpp>
#include <fstream>
#include <eigen3/Eigen/Dense>

#include "../config/config.hpp"
#include "object.hpp"

/** version of the library */
#define HUMP_VERSION_MAJOR 2
#define HUMP_VERSION_MINOR 0

//definition of the macro ASSERT
#ifndef DEBUG
    #define ASSERT(x)
#else
    #define ASSERT(x) \
             if (! (x)) \
            { \
               cout << "ERROR!! Assert " << #x << " failed\n"; \
               cout << " on line " << __LINE__  << "\n"; \
               cout << " in file " << __FILE__ << "\n";  \
            }
#endif

using namespace std;
using namespace Eigen;

/** This is the main namespace of the library */
namespace HUMotion{

typedef boost::shared_ptr<Object> objectPtr;/**< shared pointer to an object in the scenario */

const double PHI = (-log(2.0)/log(TB));/**< parameter to control when the bounce posture is reached */
const double AP = 15.0*static_cast<double>(M_PI)/180; /**< aperture of the fingers when approaching to pick [rad] */

const double BLANK_PERCENTAGE = 0.10; /**< percentage of steps to eliminate when either reaching to grasp an object OR move at the beginning of a move movement [0,1]*/

const int N_STEP_MIN = 5; /**< minimum number of steps */
const int N_STEP_MAX = 50; /**< maximum number of steps */

const double W_RED_MIN = 1; /**< minimum value of angular velocity reduction when approaching */
const double W_RED_MAX = 20; /**< maximum value of angular velocity reduction when approaching */

/** this struct defines the Denavit-Hartenberg kinematic parameters */
typedef struct{
    vector<double> d; /**< distances between consecutive frames along the y axes in [mm] */
    vector<double> a; /**< distances between concecutive frames along the z axes in [mm] */
    vector<double> alpha; /**< angle around the x axes between consecutive z axes in [rad] */
    vector<double> theta; /**< angle around the z axes between consecutive x axes in [rad] */
} DHparameters;

/** this struct defines the barrett hand */
typedef struct{
    double maxAperture; /**< [mm] max aperture of the hand in [mm] */
    double Aw; /**< smallest distance between F1 and F2 in [mm] */
    double A1; /**< length of the 1st part of the finger in [mm] */
    double A2; /**< length of the first phalax in [mm] */
    double A3; /**< length of the second phalax in [mm] */
    double D3; /**< depth of the fingertip in [mm] */
    double phi2; /**< angular displacement between the 1st part of the finger and the 1st phalax in [rad] */
    double phi3; /**< angular displacement between the 1st and the 2nd phalax in [rad] */
    vector<int> rk; /**< r parameters of the barrett hand */
    vector<int> jk; /**< j parameters of the barrett hand */
} BarrettHand;

/** this struct defines a human finger */
typedef struct{
    double ux; /**<  position of the finger with respect to the center of the palm along the x axis in [mm] */
    double uy; /**<  position of the finger with respect to the center of the palm along the y axis in [mm] */
    double uz; /**<  position of the finger with respect to the center of the palm along the z axis in [mm] */
    DHparameters finger_specs; /**< the Denavit-Hartenberg parameters of the finger */
} HumanFinger;

/** this struct defines a human thumb */
typedef struct{
    double uTx; /**<  position of the thumb with respect to the center of the palm along the x axis in [mm] */
    double uTy; /**<  position of the thumb with respect to the center of the palm along the y axis in [mm] */
    double uTz; /**<  position of the thumb with respect to the center of the palm along the z axis in [mm] */
    DHparameters thumb_specs; /**< the Denavit-Hartenberg parameters of the thumb */
} HumanThumb;

/** this struct defines a human hand */
typedef struct{
  vector<HumanFinger> fingers; /**< fingers of the hand */
  HumanThumb thumb; /**<  thumb of the hand */
  double maxAperture; /**< max aperture of the hand in [mm] */
} HumanHand;

/** this struct defines the parameters of the movement */
typedef struct{
    int arm_code; /**< the code of the arm: 0 = both arms, 1 = right arm, 2 = left arm */
    int hand_code;/**< the code of the hand: 0 = human hand, 1 = barrett hand */
    int griptype; /**< the type of the grip */
    string mov_infoline; /**< description of the movement */
    double dHO;/**< distanche hand-target*/
    std::vector<double> finalHand;/**< final posture of the hand */
    std::vector<double> target;/**< target / location to reach: target(0)=x, target(1)=y, target(2)=z, target(3)=roll, target(4)=pitch, target(6)=yaw,*/
    objectPtr obj; /**< object involved in the movement. The info of the object have to be updated according to the selected movement */
    bool approach;/**< true to use the approach options, false otherwise  */
    bool retreat;/**< true to use the retreat options, false otherwise */
    std::vector<double> pre_grasp_approach; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/
    std::vector<double> post_grasp_retreat; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/
    std::vector<double> pre_place_approach; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/
    std::vector<double> post_place_retreat; /**< (0)= x component, (1)= y component, (2)= z component, (3)= distance from the target*/
    bool rand_init; /**< true to select randon initialization in "plan" stages */
    bool coll; /**< true to enable collisions with the environment (body of the robot included) */
    bool use_move_plane; /**< true to constrain the end-effector to move on a plane in move movements, false otherwise*/
    std::vector<double> plane_params; /**< plane cartesian parameters in move movements: a*x+b*y+c*z+d=0. a=plane_params(0), b=plane_params(1), c=plane_params(2), d=plane_params(3) */
}mov_params;
/** this struct defines the boundary conditions of the movement*/
typedef struct{
    vector<double> vel_0; /**< initial velocity of the joints in [rad/s] */
    vector<double> vel_f; /**< final velocity of the joints in [rad/s] */
    vector<double> acc_0; /**< initial acceleration of the joints in [rad/s²] */
    vector<double> acc_f; /**< final acceleration of the joints in [rad/s²] */
} boundaryConditions;

/** this struct defines the tolerances that have to be set before planning the trajectory*/
typedef struct{
    mov_params mov_specs; /**< specifications of the movement */
    vector<double> tolsArm; /**< radius of the spheres along the arm in [mm] */
    MatrixXd tolsHand; /**< radius of the spheres along the fingers in [mm] */
    MatrixXd final_tolsObstacles; /**< tolerances of the final posture against the obstacles in [mm] */
    vector< MatrixXd > singleArm_tolsTarget; /**< tolerances of the trajectory against the target in [mm] */
    vector< MatrixXd > singleArm_tolsObstacles; /**< tolerances of the trajectory against the obstacles in [mm] */
    double tolTarPos; /**< tolerance of the final position of the hand against the target in [mm] */
    double tolTarOr; /**< tolerance of the final orientation of the hand against the target in [mm] */
    boundaryConditions bounds; /**< boundary condistions of the bounce problem */
    vector<double> vel_approach; /**< velocity of the joints in [rad/s] at the beginning of the approach stage */
    vector<double> acc_approach; /**< acceleration of the joints in [rad/s²] at the beginning of the approach stage */
    vector<double> lambda_final; /**< weights for the final posture optimization */
    vector<double> lambda_bounce; /**< weights for the bounce posture optimization */
    vector<double> w_max; /**< maximum angular velocity for each joint [rad/s] */
    bool obstacle_avoidance; /**< true to avoid obstacle */
    bool target_avoidance; /**< true to avoid the target during the motion */
} hump_params;

/** This struct defines the result of the planned trajectory */
typedef struct{
    int mov_type;/**< type of the planned movement */
    int status;/**< status code of the planning */
    string status_msg;/**< status message of the planning */
    string object_id;/**< identity of the object involved in the movement */
    vector<MatrixXd> trajectory_stages;/**< sequence of the trajectories */
    vector<MatrixXd> velocity_stages;/**< sequence of the velocities */
    vector<MatrixXd> acceleration_stages;/**< sequence of the accelerations */
    vector<double> time_steps; /**< sequence of each time steps for each trajectory */
    vector<string> trajectory_descriptions;/**< description of the trajectories */
}planning_result;

} // namespace HUMotion

#endif // HUMPConfig_HPP
<|endoftext|>


<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGTable.cpp
 Author:       Jon S. Berndt
 Date started: 1/9/2001
 Purpose:      Models a lookup table

 ------------- Copyright (C) 2001  Jon S. Berndt (jsb@hal-pc.org) -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

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

 You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
Models a lookup table

HISTORY
--------------------------------------------------------------------------------
JSB  1/9/00          Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGTable.h"

#if defined ( sgi ) && !defined( __GNUC__ )
#include <iomanip.h>
#else
#include <iomanip>
#endif

static const char *IdSrc = "$Id: FGTable.cpp,v 1.21 2002/01/10 11:51:30 dmegginson Exp $";
static const char *IdHdr = ID_TABLE;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

using namespace std;

FGTable::FGTable(int NRows, int NCols) : nRows(NRows), nCols(NCols)
{
  if (NCols > 1) {
    Type = tt2D;
    colCounter = 1;
    rowCounter = 0;
  } else if (NCols == 1) {
    Type = tt1D;
    colCounter = 0;
    rowCounter = 1;
  } else {
    cerr << "FGTable cannot accept 'Rows=0'" << endl;
  }

  Data = Allocate();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGTable::FGTable(int NRows) : nRows(NRows), nCols(1)
{
  Type = tt1D;
  colCounter = 0;
  rowCounter = 1;

  Data = Allocate();
  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

double** FGTable::Allocate(void)
{
  Data = new double*[nRows+1];
  for (int r=0; r<=nRows; r++) {
    Data[r] = new double[nCols+1];
    for (int c=0; c<=nCols; c++) {
      Data[r][c] = 0.0;
    }
  }
  return Data;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGTable::~FGTable()
{
  for (int r=0; r<=nRows; r++) if (Data[r]) delete[] Data[r];
  if (Data) delete[] Data;
  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

double FGTable::GetValue(double key)
{
  double Factor, Value, Span;
  int r;

  for (r=1; r<=nRows; r++) if (Data[r][0] >= key) break;
  r = r < 2 ? 2 : (r > nRows ? nRows : r);

  // make sure denominator below does not go to zero.

  Span = Data[r][0] - Data[r-1][0];
  if (Span != 0.0) {
    Factor = (key - Data[r-1][0]) / Span;
    if (Factor > 1.0) Factor = 1.0;
  } else {
    Factor = 1.0;
  }

  Value = Factor*(Data[r][1] - Data[r-1][1]) + Data[r-1][1];

  return Value;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

double FGTable::GetValue(double rowKey, double colKey)
{
  double rFactor, cFactor, col1temp, col2temp, Value;
  int r, c;

  for (r=1;r<=nRows;r++) if (Data[r][0] >= rowKey) break;
  for (c=1;c<=nCols;c++) if (Data[0][c] >= colKey) break;

  c = c < 2 ? 2 : (c > nCols ? nCols : c);
  r = r < 2 ? 2 : (r > nRows ? nRows : r);

  rFactor = (rowKey - Data[r-1][0]) / (Data[r][0] - Data[r-1][0]);
  cFactor = (colKey - Data[0][c-1]) / (Data[0][c] - Data[0][c-1]);

  if (rFactor > 1.0) rFactor = 1.0;
  else if (rFactor < 0.0) rFactor = 0.0;

  if (cFactor > 1.0) cFactor = 1.0;
  else if (cFactor < 0.0) cFactor = 0.0;

  col1temp = rFactor*(Data[r][c-1] - Data[r-1][c-1]) + Data[r-1][c-1];
  col2temp = rFactor*(Data[r][c] - Data[r-1][c]) + Data[r-1][c];

  Value = col1temp + cFactor*(col2temp - col1temp);

  return Value;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGTable::operator<<(FGConfigFile& infile)
{
  int startRow;

  if (Type == tt1D) startRow = 1;
  else startRow = 0;

  for (int r=startRow; r<=nRows; r++) {
    for (int c=0; c<=nCols; c++) {
      if (r != 0 || c != 0) {
        infile >> Data[r][c];
      }
    }
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGTable& FGTable::operator<<(const double n)
{
  Data[rowCounter][colCounter] = n;
  if (colCounter == nCols) {
    colCounter = 0;
    rowCounter++;
  } else {
    colCounter++;
  }
  return *this;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGTable& FGTable::operator<<(const int n)
{
  *this << (double)n;
  return *this;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGTable::Print(void)
{
  int startRow;

  if (Type == tt1D) startRow = 1;
  else startRow = 0;

  cout.setf(ios::fixed); // set up output stream
  cout.precision(4);

  for (int r=startRow; r<=nRows; r++) {
    cout << "	";
    for (int c=0; c<=nCols; c++) {
      if (r == 0 && c == 0) {
      cout << "	";
      } else {
      cout << Data[r][c] << "	";
      }
    }
    cout << endl;
  }
  cout.setf((ios_base::fmtflags)0, ios::floatfield); // reset
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGTable::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor

    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGTable" << endl;
    if (from == 1) cout << "Destroyed:    FGTable" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}

<commit_msg>Change from Norman Vine to avoid breaking G++ 2.95.<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGTable.cpp
 Author:       Jon S. Berndt
 Date started: 1/9/2001
 Purpose:      Models a lookup table

 ------------- Copyright (C) 2001  Jon S. Berndt (jsb@hal-pc.org) -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

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

 You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
Models a lookup table

HISTORY
--------------------------------------------------------------------------------
JSB  1/9/00          Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGTable.h"

#if defined ( sgi ) && !defined( __GNUC__ )
#include <iomanip.h>
#else
#include <iomanip>
#endif

static const char *IdSrc = "$Id: FGTable.cpp,v 1.22 2002/01/11 16:55:14 dmegginson Exp $";
static const char *IdHdr = ID_TABLE;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

using namespace std;

FGTable::FGTable(int NRows, int NCols) : nRows(NRows), nCols(NCols)
{
  if (NCols > 1) {
    Type = tt2D;
    colCounter = 1;
    rowCounter = 0;
  } else if (NCols == 1) {
    Type = tt1D;
    colCounter = 0;
    rowCounter = 1;
  } else {
    cerr << "FGTable cannot accept 'Rows=0'" << endl;
  }

  Data = Allocate();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGTable::FGTable(int NRows) : nRows(NRows), nCols(1)
{
  Type = tt1D;
  colCounter = 0;
  rowCounter = 1;

  Data = Allocate();
  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

double** FGTable::Allocate(void)
{
  Data = new double*[nRows+1];
  for (int r=0; r<=nRows; r++) {
    Data[r] = new double[nCols+1];
    for (int c=0; c<=nCols; c++) {
      Data[r][c] = 0.0;
    }
  }
  return Data;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGTable::~FGTable()
{
  for (int r=0; r<=nRows; r++) if (Data[r]) delete[] Data[r];
  if (Data) delete[] Data;
  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

double FGTable::GetValue(double key)
{
  double Factor, Value, Span;
  int r;

  for (r=1; r<=nRows; r++) if (Data[r][0] >= key) break;
  r = r < 2 ? 2 : (r > nRows ? nRows : r);

  // make sure denominator below does not go to zero.

  Span = Data[r][0] - Data[r-1][0];
  if (Span != 0.0) {
    Factor = (key - Data[r-1][0]) / Span;
    if (Factor > 1.0) Factor = 1.0;
  } else {
    Factor = 1.0;
  }

  Value = Factor*(Data[r][1] - Data[r-1][1]) + Data[r-1][1];

  return Value;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

double FGTable::GetValue(double rowKey, double colKey)
{
  double rFactor, cFactor, col1temp, col2temp, Value;
  int r, c;

  for (r=1;r<=nRows;r++) if (Data[r][0] >= rowKey) break;
  for (c=1;c<=nCols;c++) if (Data[0][c] >= colKey) break;

  c = c < 2 ? 2 : (c > nCols ? nCols : c);
  r = r < 2 ? 2 : (r > nRows ? nRows : r);

  rFactor = (rowKey - Data[r-1][0]) / (Data[r][0] - Data[r-1][0]);
  cFactor = (colKey - Data[0][c-1]) / (Data[0][c] - Data[0][c-1]);

  if (rFactor > 1.0) rFactor = 1.0;
  else if (rFactor < 0.0) rFactor = 0.0;

  if (cFactor > 1.0) cFactor = 1.0;
  else if (cFactor < 0.0) cFactor = 0.0;

  col1temp = rFactor*(Data[r][c-1] - Data[r-1][c-1]) + Data[r-1][c-1];
  col2temp = rFactor*(Data[r][c] - Data[r-1][c]) + Data[r-1][c];

  Value = col1temp + cFactor*(col2temp - col1temp);

  return Value;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGTable::operator<<(FGConfigFile& infile)
{
  int startRow;

  if (Type == tt1D) startRow = 1;
  else startRow = 0;

  for (int r=startRow; r<=nRows; r++) {
    for (int c=0; c<=nCols; c++) {
      if (r != 0 || c != 0) {
        infile >> Data[r][c];
      }
    }
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGTable& FGTable::operator<<(const double n)
{
  Data[rowCounter][colCounter] = n;
  if (colCounter == nCols) {
    colCounter = 0;
    rowCounter++;
  } else {
    colCounter++;
  }
  return *this;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGTable& FGTable::operator<<(const int n)
{
  *this << (double)n;
  return *this;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGTable::Print(void)
{
  int startRow;

  if (Type == tt1D) startRow = 1;
  else startRow = 0;

  ios::fmtflags flags = cout.setf(ios::fixed); // set up output stream
  cout.precision(4);

  for (int r=startRow; r<=nRows; r++) {
    cout << "	";
    for (int c=0; c<=nCols; c++) {
      if (r == 0 && c == 0) {
      cout << "	";
      } else {
      cout << Data[r][c] << "	";
      }
    }
    cout << endl;
  }
  cout.setf(flags); // reset
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGTable::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor

    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGTable" << endl;
    if (from == 1) cout << "Destroyed:    FGTable" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}

<|endoftext|>


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

namespace cmoh {
namespace util {

/**
 * Count the number of arguments in a template parameter pack
 *
 * Instantiations of this struct will contain a static member `value`, which
 * will hold the number of arguments supplied to the template.
 */
template <
    typename ...Args
>
struct count;

// Specialization for lists of at least one argument
template <
    typename Arg0,
    typename ...Args
>
struct count<Arg0, Args...> {
    static constexpr unsigned long int value = count<Args...>::value + 1;
};

// Recursion terminator/specialization for zero arguments
template <>
struct count<> {
    static constexpr unsigned long int value = 0;
};

/**
 * Logical conjunction of type traits `Items`
 *
 * Providing that each of the `Items` types provides a member `value` of type
 * bool, this type provides a member `value` of type bool with the value of the
 * logical conjunction of each of the values taken from the parameters.
 *
 * This template mirrors a utility which is expected to ship with C++17
 * compliant STL implementations.
 */
template <
    typename ...Items
>
struct conjunction : std::true_type {};

template <
    typename Item0,
    typename ...Items
>
struct conjunction<Item0, Items...> {
    static constexpr bool value = Item0::value && conjunction<Items...>::value;
};

/**
 * Logical disjunction of type traits `Items`
 *
 * Providing that each of the `Items` types provides a member `value` of type
 * bool, this type provides a member `value` of type bool with the value of the
 * logical disjunction of each of the values taken from the parameters.
 *
 * This template mirrors a utility which is expected to ship with C++17
 * compliant STL implementations.
 */
template <
    typename ...Items
>
struct disjunction : std::false_type {};

template <
    typename Item0,
    typename ...Items
>
struct disjunction<Item0, Items...> {
    static constexpr bool value = Item0::value || disjunction<Items...>::value;
};

/**
 * Test whether a type occurs in a template parameter pack
 *
 * Instantiations of this struct contain a static member `value`, which will
 * be `true` if `Compare` occurs in `Types` and false otherwise.
 */
template <
    typename Compare, ///< Type to compare against items in `Types`
    typename ...Types ///< Types against which to compare `Compare` against
>
using contains = disjunction<std::is_same<Compare, Types>...>;

/**
 * Predeclaration of the C++17 std::void_t
 *
 * Used for SFINAE.
 */
template <
    typename...
>
using void_t = void;

/**
 * Meta type extracting the common type of a parameter pack
 *
 * If all `Types` are identical, the type will be exported as the member `type`.
 * If not all parameters are identical, a compile time error will be issued.
 */
template <
    typename ...Types ///< types to unify
>
struct common_type {
    static_assert(count<Types...>::value > 0, "Parameter pack is empty");
};

// Specialization for more than one parameter
template <
    typename Type0,
    typename ...Types
>
struct common_type<Type0, Types...> {
    typedef Type0 type;
    static_assert(
        std::is_same<type, typename common_type<Types...>::type>::value,
        "Types are not identical"
    );
};

// Specialization for exactly one parameter
template <
    typename Type
>
struct common_type<Type> {
    typedef Type type;
};

/**
 * Container holding various items, which can be retrieved via criteria
 *
 * Use this container if you have a bunch of items of which you want to select
 * one using some criteria.  The container is constructible from values of
 * arbitrary types.
 *
 * At compile time, those items can be accessed through overloads of the variadic
 * method template `get()`, which takes as template parameters types featuring a
 * member `value` which is either `true` or `false`. The use case this template
 * was designed for is when you want to select one of the items based on some
 * meta function. Example:
 *
 *     template <typename ...Types> struct foo {
 *         selectable_items<Types...> bar;
 *         // ...
 *         void meth() {
 *             bar.get<has_some_feature<Types>...>();
 *         }
 *     };
 *
 * Currently, only the retrieval of const references is supported.
 */
template <
    typename ...Types ///< types of the items held by the container
>
struct selectable_items {
    template <typename...> void get() {}
};

// Specialization for at least one parameter
template <
    typename Type0,
    typename ...Types
>
struct selectable_items<Type0, Types...> {
    typedef Type0 value;
    typedef selectable_items<Types...> next;

private:
    // members have to be declares before get() because of decltype usage
    value _value;
    next _next;

public:
    selectable_items(value&& current, Types... values) :
            _value(std::forward<value>(current)),
            _next(std::forward<Types>(values)...) {};
    selectable_items(selectable_items const&) = default;
    selectable_items(selectable_items&&) = default;
    selectable_items() = delete;

    template <
        typename BoolType0,
        typename ...BoolTypes
    >
    typename std::enable_if<
        BoolType0::value,
        const value&
    >::type
    get() const {
        return _value;
    }

    template <
        typename BoolType0,
        typename ...BoolTypes
    >
    typename std::enable_if<
        !BoolType0::value,
        decltype(_next.template get<BoolTypes...>())
    >::type
    get() const {
        return _next.template get<BoolTypes...>();
    }
};

}
}

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

namespace cmoh {
namespace util {

/**
 * Count the number of arguments in a template parameter pack
 *
 * Instantiations of this struct will contain a static member `value`, which
 * will hold the number of arguments supplied to the template.
 */
template <
    typename ...Args
>
struct count;

// Specialization for lists of at least one argument
template <
    typename Arg0,
    typename ...Args
>
struct count<Arg0, Args...> {
    static constexpr unsigned long int value = count<Args...>::value + 1;
};

// Recursion terminator/specialization for zero arguments
template <>
struct count<> {
    static constexpr unsigned long int value = 0;
};

/**
 * Logical conjunction of type traits `Items`
 *
 * Providing that each of the `Items` types provides a member `value` of type
 * bool, this type provides a member `value` of type bool with the value of the
 * logical conjunction of each of the values taken from the parameters.
 *
 * This template mirrors a utility which is expected to ship with C++17
 * compliant STL implementations.
 */
template <
    typename ...Items
>
struct conjunction : std::true_type {};

template <
    typename Item0,
    typename ...Items
>
struct conjunction<Item0, Items...> {
    static constexpr bool value = Item0::value && conjunction<Items...>::value;
};

/**
 * Logical disjunction of type traits `Items`
 *
 * Providing that each of the `Items` types provides a member `value` of type
 * bool, this type provides a member `value` of type bool with the value of the
 * logical disjunction of each of the values taken from the parameters.
 *
 * This template mirrors a utility which is expected to ship with C++17
 * compliant STL implementations.
 */
template <
    typename ...Items
>
struct disjunction : std::false_type {};

template <
    typename Item0,
    typename ...Items
>
struct disjunction<Item0, Items...> {
    static constexpr bool value = Item0::value || disjunction<Items...>::value;
};

/**
 * Test whether a type occurs in a template parameter pack
 *
 * Instantiations of this struct contain a static member `value`, which will
 * be `true` if `Compare` occurs in `Types` and false otherwise.
 */
template <
    typename Compare, ///< Type to compare against items in `Types`
    typename ...Types ///< Types against which to compare `Compare` against
>
using contains = disjunction<std::is_same<Compare, Types>...>;

/**
 * Predeclaration of the C++17 std::void_t
 *
 * Used for SFINAE.
 */
template <
    typename...
>
using void_t = void;

/**
 * Meta type extracting the common type of a parameter pack
 *
 * If all `Types` are identical, the type will be exported as the member `type`.
 * If not all parameters are identical, a compile time error will be issued.
 */
template <
    typename ...Types ///< types to unify
>
struct common_type {
    static_assert(count<Types...>::value > 0, "Parameter pack is empty");
};

// Specialization for more than one parameter
template <
    typename Type0,
    typename ...Types
>
struct common_type<Type0, Types...> {
    typedef Type0 type;
    static_assert(
        std::is_same<type, typename common_type<Types...>::type>::value,
        "Types are not identical"
    );
};

// Specialization for exactly one parameter
template <
    typename Type
>
struct common_type<Type> {
    typedef Type type;
};

/**
 * Container holding various items, which can be retrieved via criteria
 *
 * Use this container if you have a bunch of items of which you want to select
 * one using some criteria.  The container is constructible from values of
 * arbitrary types.
 *
 * At compile time, those items can be accessed through overloads of the variadic
 * method template `get()`, which takes as template parameters types featuring a
 * member `value` which is either `true` or `false`. The use case this template
 * was designed for is when you want to select one of the items based on some
 * meta function. Example:
 *
 *     template <typename ...Types> struct foo {
 *         selectable_items<Types...> bar;
 *         // ...
 *         void meth() {
 *             bar.get<has_some_feature<Types>...>();
 *         }
 *     };
 *
 * Currently, only the retrieval of const references is supported.
 */
template <
    typename ...Types ///< types of the items held by the container
>
struct selectable_items {
    template <typename...> void get() {}
};

// Specialization for at least one parameter
template <
    typename Type0,
    typename ...Types
>
struct selectable_items<Type0, Types...> {
    typedef Type0 value;
    typedef selectable_items<Types...> next;

private:
    // members have to be declares before get() because of decltype usage
    value _value;
    next _next;

public:
    selectable_items(value&& current, Types... values) :
            _value(std::forward<value>(current)),
            _next(std::forward<Types>(values)...) {};
    selectable_items(selectable_items const&) = default;
    selectable_items(selectable_items&&) = default;
    selectable_items() = delete;

    template <
        typename BoolType0,
        typename ...BoolTypes
    >
    typename std::enable_if<
        BoolType0::value,
        value const&
    >::type
    get() const {
        return _value;
    }

    template <
        typename BoolType0,
        typename ...BoolTypes
    >
    typename std::enable_if<
        !BoolType0::value,
        decltype(_next.template get<BoolTypes...>())
    >::type
    get() const {
        return _next.template get<BoolTypes...>();
    }
};

}
}

#endif
<|endoftext|>


<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Author: kenton@google.com (Kenton Varda)

#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/python/python_generator.h>
#include <google/protobuf/compiler/java/java_generator.h>

int main(int argc, char* argv[]) {

  google::protobuf::compiler::CommandLineInterface cli;

  // Proto2 C++
  google::protobuf::compiler::cpp::CppGenerator cpp_generator;
  cli.RegisterGenerator("--cpp_out", &cpp_generator,
                        "Generate C++ header and source.");

  // Proto2 Java
  google::protobuf::compiler::java::JavaGenerator java_generator;
  cli.RegisterGenerator("--java_out", &java_generator,
                        "Generate Java source file.");

  // Proto2 Python
  google::protobuf::compiler::python::Generator py_generator;
  cli.RegisterGenerator("--python_out", &py_generator,
                        "Generate Python source file.");

  return cli.Run(argc, argv);
}
<commit_msg>porting code over<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Author: kenton@google.com (Kenton Varda)

#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/python/python_generator.h>
#include <google/protobuf/compiler/java/java_generator.h>
#include <google/protobuf/compiler/objectivec/objectivec_generator.h>

int main(int argc, char* argv[]) {

  google::protobuf::compiler::CommandLineInterface cli;

  // Proto2 C++
  google::protobuf::compiler::cpp::CppGenerator cpp_generator;
  cli.RegisterGenerator("--cpp_out", &cpp_generator,
                        "Generate C++ header and source.");

  // Proto2 Java
  google::protobuf::compiler::java::JavaGenerator java_generator;
  cli.RegisterGenerator("--java_out", &java_generator,
                        "Generate Java source file.");

  // Proto2 Python
  google::protobuf::compiler::python::Generator py_generator;
  cli.RegisterGenerator("--python_out", &py_generator,
                        "Generate Python source file.");

  // Proto2 Objective-C
  google::protobuf::compiler::objectivec::ObjectiveCGenerator objc_generator;
  cli.RegisterGenerator("--objc_out", &objc_generator,
                        "Generate Objective-C source file.");

  return cli.Run(argc, argv);
}
<|endoftext|>


<commit_before><commit_msg>make sure dialog api object is reset when window is closed ( but not vetoed )<commit_after><|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

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

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WhisperDB.cpp
* @author Vladislav Gluhovsky <vlad@ethdev.com>
* @date July 2015
 */

#include "WhisperDB.h"
#include <boost/filesystem.hpp>
#include <libdevcore/FileSystem.h>
#include "WhisperHost.h"

using namespace std;
using namespace dev;
using namespace dev::shh;
namespace fs = boost::filesystem;

WhisperDB::WhisperDB(string const& _type)
{
	m_readOptions.verify_checksums = true;
	string path = dev::getDataDir("shh");
	fs::create_directories(path);
	fs::permissions(path, fs::owner_all);
	path.append("\\").append(_type);
	leveldb::Options op;
	op.create_if_missing = true;
	op.max_open_files = 256;
	leveldb::DB* p = nullptr;
	leveldb::Status status = leveldb::DB::Open(op, path, &p);
	m_db.reset(p);
	if (!status.ok())
		BOOST_THROW_EXCEPTION(FailedToOpenLevelDB(status.ToString()));
}

string WhisperDB::lookup(dev::h256 const& _key) const
{
	string ret;
	leveldb::Slice slice((char const*)_key.data(), _key.size);
	leveldb::Status status = m_db->Get(m_readOptions, slice, &ret);
	if (!status.ok() && !status.IsNotFound())
		BOOST_THROW_EXCEPTION(FailedLookupInLevelDB(status.ToString()));

	return ret;
}

void WhisperDB::insert(dev::h256 const& _key, string const& _value)
{
	leveldb::Slice slice((char const*)_key.data(), _key.size);
	leveldb::Status status = m_db->Put(m_writeOptions, slice, _value);
	if (!status.ok())
		BOOST_THROW_EXCEPTION(FailedInsertInLevelDB(status.ToString()));
}

void WhisperDB::insert(dev::h256 const& _key, bytes const& _value)
{
	leveldb::Slice k((char const*)_key.data(), _key.size);
	leveldb::Slice v((char const*)_value.data(), _value.size());
	leveldb::Status status = m_db->Put(m_writeOptions, k, v);
	if (!status.ok())
		BOOST_THROW_EXCEPTION(FailedInsertInLevelDB(status.ToString()));
}

void WhisperDB::kill(dev::h256 const& _key)
{
	leveldb::Slice slice((char const*)_key.data(), _key.size);
	leveldb::Status status = m_db->Delete(m_writeOptions, slice);
	if (!status.ok())
		BOOST_THROW_EXCEPTION(FailedDeleteInLevelDB(status.ToString()));
}

void WhisperMessagesDB::loadAllMessages(std::map<h256, Envelope>& o_dst)
{
	leveldb::ReadOptions op;
	op.fill_cache = false;
	op.verify_checksums = true;
	vector<string> wasted;
	unique_ptr<leveldb::Iterator> it(m_db->NewIterator(op));
	unsigned const now = (unsigned)time(0);

	for (it->SeekToFirst(); it->Valid(); it->Next())
	{
		leveldb::Slice const k = it->key();
		leveldb::Slice const v = it->value();
		bool useless = true;

		try
		{
			RLP rlp((byte const*)v.data(), v.size());
			Envelope e(rlp);
			h256 h2 = e.sha3();
			h256 h1;

			if (k.size() == h256::size)
				h1 = h256((byte const*)k.data(), h256::ConstructFromPointer);

			if (h1 != h2)
				cwarn << "Corrupted data in Level DB:" << h1.hex() << "versus" << h2.hex();
			else if (e.expiry() > now)
			{
				o_dst[h1] = e;
				useless = false;
			}
		}
		catch(RLPException const& ex)
		{
			cwarn << "RLPException in WhisperDB::loadAll():" << ex.what();
		}
		catch(Exception const& ex)
		{
			cwarn << "Exception in WhisperDB::loadAll():" << ex.what();
		}

		if (useless)
			wasted.push_back(k.ToString());
	}

	cdebug << "WhisperDB::loadAll(): loaded " << o_dst.size() << ", deleted " << wasted.size() << "messages";

	for (auto const& k: wasted)
	{
		leveldb::Status status = m_db->Delete(m_writeOptions, k);
		if (!status.ok())
			cwarn << "Failed to delete an entry from Level DB:" << k;
	}
}

void WhisperMessagesDB::saveSingleMessage(h256 const& _key, Envelope const& _e)
{
	try
	{
		RLPStream rlp;
		_e.streamRLP(rlp);
		bytes b;
		rlp.swapOut(b);
		insert(_key, b);
	}
	catch(RLPException const& ex)
	{
		cwarn << boost::diagnostic_information(ex);
	}
	catch(FailedInsertInLevelDB const& ex)
	{
		cwarn << boost::diagnostic_information(ex);
	}
}

vector<unsigned> WhisperFiltersDB::restoreTopicsFromDB(WhisperHost* _host, h256 const& _id)
{
	vector<unsigned> ret;
	string raw = lookup(_id);
	if (!raw.empty())
	{
		RLP rlp(raw);
		auto sz = rlp.itemCountStrict();

		for (unsigned i = 0; i < sz; ++i)
		{
			RLP r = rlp[i];
			bytesConstRef ref(r.toBytesConstRef());
			Topics topics;
			unsigned num = ref.size() / h256::size;
			for (unsigned j = 0; j < num; ++j)
			{
				h256 topic(ref.data() + j * h256::size, h256::ConstructFromPointerType());
				topics.push_back(topic);
			}

			unsigned w = _host->installWatch(topics);
			ret.push_back(w);
		}
	}

	return ret;
}

void WhisperFiltersDB::saveTopicsToDB(WhisperHost const& _host, h256 const& _id)
{
	bytes b;
	RLPStream rlp;
	_host.exportFilters(rlp);
	rlp.swapOut(b);
	insert(_id, b);
}
<commit_msg>Fix silly paths for whisper.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

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

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WhisperDB.cpp
* @author Vladislav Gluhovsky <vlad@ethdev.com>
* @date July 2015
 */

#include "WhisperDB.h"
#include <boost/filesystem.hpp>
#include <libdevcore/FileSystem.h>
#include "WhisperHost.h"

using namespace std;
using namespace dev;
using namespace dev::shh;
namespace fs = boost::filesystem;

WhisperDB::WhisperDB(string const& _type)
{
	m_readOptions.verify_checksums = true;
	string path = dev::getDataDir("shh");
	fs::create_directories(path);
	fs::permissions(path, fs::owner_all);
	path += "/" + _type;
	leveldb::Options op;
	op.create_if_missing = true;
	op.max_open_files = 256;
	leveldb::DB* p = nullptr;
	leveldb::Status status = leveldb::DB::Open(op, path, &p);
	m_db.reset(p);
	if (!status.ok())
		BOOST_THROW_EXCEPTION(FailedToOpenLevelDB(status.ToString()));
}

string WhisperDB::lookup(dev::h256 const& _key) const
{
	string ret;
	leveldb::Slice slice((char const*)_key.data(), _key.size);
	leveldb::Status status = m_db->Get(m_readOptions, slice, &ret);
	if (!status.ok() && !status.IsNotFound())
		BOOST_THROW_EXCEPTION(FailedLookupInLevelDB(status.ToString()));

	return ret;
}

void WhisperDB::insert(dev::h256 const& _key, string const& _value)
{
	leveldb::Slice slice((char const*)_key.data(), _key.size);
	leveldb::Status status = m_db->Put(m_writeOptions, slice, _value);
	if (!status.ok())
		BOOST_THROW_EXCEPTION(FailedInsertInLevelDB(status.ToString()));
}

void WhisperDB::insert(dev::h256 const& _key, bytes const& _value)
{
	leveldb::Slice k((char const*)_key.data(), _key.size);
	leveldb::Slice v((char const*)_value.data(), _value.size());
	leveldb::Status status = m_db->Put(m_writeOptions, k, v);
	if (!status.ok())
		BOOST_THROW_EXCEPTION(FailedInsertInLevelDB(status.ToString()));
}

void WhisperDB::kill(dev::h256 const& _key)
{
	leveldb::Slice slice((char const*)_key.data(), _key.size);
	leveldb::Status status = m_db->Delete(m_writeOptions, slice);
	if (!status.ok())
		BOOST_THROW_EXCEPTION(FailedDeleteInLevelDB(status.ToString()));
}

void WhisperMessagesDB::loadAllMessages(std::map<h256, Envelope>& o_dst)
{
	leveldb::ReadOptions op;
	op.fill_cache = false;
	op.verify_checksums = true;
	vector<string> wasted;
	unique_ptr<leveldb::Iterator> it(m_db->NewIterator(op));
	unsigned const now = (unsigned)time(0);

	for (it->SeekToFirst(); it->Valid(); it->Next())
	{
		leveldb::Slice const k = it->key();
		leveldb::Slice const v = it->value();
		bool useless = true;

		try
		{
			RLP rlp((byte const*)v.data(), v.size());
			Envelope e(rlp);
			h256 h2 = e.sha3();
			h256 h1;

			if (k.size() == h256::size)
				h1 = h256((byte const*)k.data(), h256::ConstructFromPointer);

			if (h1 != h2)
				cwarn << "Corrupted data in Level DB:" << h1.hex() << "versus" << h2.hex();
			else if (e.expiry() > now)
			{
				o_dst[h1] = e;
				useless = false;
			}
		}
		catch(RLPException const& ex)
		{
			cwarn << "RLPException in WhisperDB::loadAll():" << ex.what();
		}
		catch(Exception const& ex)
		{
			cwarn << "Exception in WhisperDB::loadAll():" << ex.what();
		}

		if (useless)
			wasted.push_back(k.ToString());
	}

	cdebug << "WhisperDB::loadAll(): loaded " << o_dst.size() << ", deleted " << wasted.size() << "messages";

	for (auto const& k: wasted)
	{
		leveldb::Status status = m_db->Delete(m_writeOptions, k);
		if (!status.ok())
			cwarn << "Failed to delete an entry from Level DB:" << k;
	}
}

void WhisperMessagesDB::saveSingleMessage(h256 const& _key, Envelope const& _e)
{
	try
	{
		RLPStream rlp;
		_e.streamRLP(rlp);
		bytes b;
		rlp.swapOut(b);
		insert(_key, b);
	}
	catch(RLPException const& ex)
	{
		cwarn << boost::diagnostic_information(ex);
	}
	catch(FailedInsertInLevelDB const& ex)
	{
		cwarn << boost::diagnostic_information(ex);
	}
}

vector<unsigned> WhisperFiltersDB::restoreTopicsFromDB(WhisperHost* _host, h256 const& _id)
{
	vector<unsigned> ret;
	string raw = lookup(_id);
	if (!raw.empty())
	{
		RLP rlp(raw);
		auto sz = rlp.itemCountStrict();

		for (unsigned i = 0; i < sz; ++i)
		{
			RLP r = rlp[i];
			bytesConstRef ref(r.toBytesConstRef());
			Topics topics;
			unsigned num = ref.size() / h256::size;
			for (unsigned j = 0; j < num; ++j)
			{
				h256 topic(ref.data() + j * h256::size, h256::ConstructFromPointerType());
				topics.push_back(topic);
			}

			unsigned w = _host->installWatch(topics);
			ret.push_back(w);
		}
	}

	return ret;
}

void WhisperFiltersDB::saveTopicsToDB(WhisperHost const& _host, h256 const& _id)
{
	bytes b;
	RLPStream rlp;
	_host.exportFilters(rlp);
	rlp.swapOut(b);
	insert(_id, b);
}
<|endoftext|>


<commit_before><commit_msg>Fix code comment about IMPALA-2031 (query end time < start time)<commit_after><|endoftext|>


<commit_before>#pragma once

#include <vector>
#include <utility>

namespace helene
{
template <class T, class Allocator = std::allocator<T>>
class handle_map
{
public:
    typedef typename std::vector<T>::size_type size_type;
    typedef typename std::vector<size_type>::size_type handle_type;

public:
    typedef typename std::vector<T>::iterator iterator;
    typedef typename std::vector<T>::const_iterator const_iterator;

public:
    handle_type
    insert(const T& value)
    {
        // always insert at end of dense storage
        dense_.push_back(value);

        handle_type new_handle;
        // find new handle
        if(free_.empty())
        {
            // no free handle slots, push back new slot
            sparse_.push_back(dense_.size() - 1);

            new_handle = sparse_.size() - 1;
        }
        else
        {
            // slot is available for new handle
            new_handle = free_.back();
            sparse_[new_handle] = dense_.size() - 1;
            free_.pop_back();
        }

        reverse_.push_back(new_handle);

        return new_handle;
    }

    void
    erase(handle_type n)
    {
        // find handle of dense's back
        const auto index_of_dense_back = dense_.size() - 1;
        const auto back_handle = reverse_[index_of_dense_back];

        // swap element to erase with back element
        std::swap(dense_[sparse_[n]], dense_.back());
        std::swap(reverse_[n], reverse_[index_of_dense_back]);

        // update handle reference to new dense location
        sparse_[back_handle] = sparse_[n];

        // pop back
        dense_.pop_back();
        reverse_.pop_back();

        // add handle to free list
        free_.push_back(n);
    }

    size_type
    size() const
    {
        return dense_.size();
    }

    bool
    empty() const
    {
        return dense_.empty();
    }

    T& operator[](handle_type n)
    {
        return dense_[sparse_[n]];
    }

    const T& operator[](handle_type n) const
    {
        return dense_[sparse_[n]];
    }

    iterator
    begin()
    {
        return dense_.begin();
    }

    iterator
    end()
    {
        return dense_.end();
    }

    const_iterator
    cbegin() const
    {
        return dense_.cbegin();
    }

    const_iterator
    cend() const
    {
        return dense_.cend();
    }

private:
    std::vector<T> dense_;
    std::vector<size_type> sparse_;
    std::vector<handle_type> reverse_;
    std::vector<handle_type> free_;
};
} // namespace helene
<commit_msg>Remove unused defaulted template parameter. 	modified:   include/handle_map.hpp<commit_after>#pragma once

#include <vector>
#include <utility>

namespace helene
{

template <class T>
class handle_map
{
public:
    typedef typename std::vector<T>::size_type size_type;
    typedef typename std::vector<size_type>::size_type handle_type;

public:
    typedef typename std::vector<T>::iterator iterator;
    typedef typename std::vector<T>::const_iterator const_iterator;

public:
    handle_type
    insert(const T& value)
    {
        // always insert at end of dense storage
        dense_.push_back(value);

        handle_type new_handle;
        // find new handle
        if(free_.empty())
        {
            // no free handle slots, push back new slot
            sparse_.push_back(dense_.size() - 1);

            new_handle = sparse_.size() - 1;
        }
        else
        {
            // slot is available for new handle
            new_handle = free_.back();
            sparse_[new_handle] = dense_.size() - 1;
            free_.pop_back();
        }

        reverse_.push_back(new_handle);

        return new_handle;
    }

    void
    erase(handle_type n)
    {
        // find handle of dense's back
        const auto index_of_dense_back = dense_.size() - 1;
        const auto back_handle = reverse_[index_of_dense_back];

        // swap element to erase with back element
        std::swap(dense_[sparse_[n]], dense_.back());
        std::swap(reverse_[n], reverse_[index_of_dense_back]);

        // update handle reference to new dense location
        sparse_[back_handle] = sparse_[n];

        // pop back
        dense_.pop_back();
        reverse_.pop_back();

        // add handle to free list
        free_.push_back(n);
    }

    size_type
    size() const
    {
        return dense_.size();
    }

    bool
    empty() const
    {
        return dense_.empty();
    }

    T& operator[](handle_type n)
    {
        return dense_[sparse_[n]];
    }

    const T& operator[](handle_type n) const
    {
        return dense_[sparse_[n]];
    }

    iterator
    begin()
    {
        return dense_.begin();
    }

    iterator
    end()
    {
        return dense_.end();
    }

    const_iterator
    cbegin() const
    {
        return dense_.cbegin();
    }

    const_iterator
    cend() const
    {
        return dense_.cend();
    }

private:
    std::vector<T> dense_;
    std::vector<size_type> sparse_;
    std::vector<handle_type> reverse_;
    std::vector<handle_type> free_;
};
} // namespace helene
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/voltage/gen_mss_voltage_traits.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
<commit_msg>Move MSS volt attr setters to generic folder<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/voltage/gen_mss_voltage_traits.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file gen_mss_voltage_traits.H
/// @brief Contains voltage traits information
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP FW Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: CI

#ifndef _GEN_MSS_VOLTAGE_TRAITS_H_
#define _GEN_MSS_VOLTAGE_TRAITS_H_

#include <fapi2.H>
#include <generic/memory/lib/utils/shared/mss_generic_consts.H>

namespace mss
{

///
/// @class Traits and policy class for voltage code
/// @tparam M mss::mc_type memory controller type
/// @tparam D mss::spd::device_type DRAM device type (generation)
///
template< mss::mc_type M, mss::spd::device_type D >
class voltage_traits;

///
/// @class Traits and policy class for voltage code - specialization for the NIMBUS memory controller type
///
template<>
class voltage_traits<mss::mc_type::NIMBUS, mss::spd::device_type::DDR4>
{
    public:
        //////////////////////////////////////////////////////////////
        // Target types
        //////////////////////////////////////////////////////////////
        static constexpr fapi2::TargetType VOLTAGE_TARGET_TYPE = fapi2::TARGET_TYPE_MCBIST;
        static constexpr fapi2::TargetType SPD_TARGET_TYPE = fapi2::TARGET_TYPE_MCS;

        //////////////////////////////////////////////////////////////
        // Traits values
        //////////////////////////////////////////////////////////////
        // List of attribute setter functions for setting voltage rail values
        // This vector is defined in the p9 space: lib/eff_config/nimbus_mss_voltage.C
        static const std::vector<fapi2::ReturnCode (*)(const fapi2::Target<VOLTAGE_TARGET_TYPE>&, uint32_t)> voltage_setters;
};

} // ns mss
#endif
<|endoftext|>


<commit_before>// vimshell.cpp : Defines the entry point for the application.
//

#include "vimshell.h"
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <shellapi.h>

bool cvtLPW2stdstring(std::string& s, const LPWSTR pw,
                      UINT codepage = CP_ACP)
{
    bool res = false;
    char* p = 0;
    int bsz;

    bsz = WideCharToMultiByte(codepage,
        0,
        pw,-1,
        0,0,
        0,0);
    if (bsz > 0) {
        p = new char[bsz];
        int rc = WideCharToMultiByte(codepage,
            0,
            pw,-1,
            p,bsz,
            0,0);
        if (rc != 0) {
            p[bsz-1] = 0;
            s = p;
            res = true;
        }
    }
    delete [] p;
    return res;
}

std::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace )
{
	size_t uPos = 0;
	size_t uFindLen = tFind.length();
	size_t uReplaceLen = tReplace.length();

	if( uFindLen == 0 )
	{
		return tInput;
	}

	for( ;(uPos = tInput.find( tFind, uPos )) != std::string::npos; )
	{
		tInput.replace( uPos, uFindLen, tReplace );
		uPos += uReplaceLen;
	}

	return tInput;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	int count;
	//MessageBox(0, lpCmdLine, 0, 0);
	LPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count);
	std::string currentDir;

	cvtLPW2stdstring(currentDir, strings[0]);

	// Cut off the filename
	while((currentDir.length() > 0) &&
		(currentDir[currentDir.length()-1] != '/') &&
		(currentDir[currentDir.length()-1] != '\\'))
	{
		currentDir = currentDir.substr(0, currentDir.length()-1);
	}
	if(currentDir.length() > 0 && currentDir[0] == '"')
		currentDir = currentDir.substr(1);

	std::string filename = currentDir + std::string("shell.txt");

	std::ifstream fileIn(filename.c_str());
	if(!fileIn)
	{
		MessageBox(0, "Please create a file called shell.txt in the same folder you put this new vimrun.exe", 0,0);
		return 1;
	}

	std::string argumentshellcommand;
	std::string silentshellcommand;
	std::string interactiveshellcommand;

	std::getline(fileIn, argumentshellcommand);
	std::getline(fileIn, silentshellcommand);
	std::getline(fileIn, interactiveshellcommand);

	std::string args = lpCmdLine;

	while(args.length() > 0 && args[0] == ' ')
		args = args.substr(1);

	bool execSilently = false;

	if(args.length() > 3 &&
			args[0] == '-' &&
			args[1] == 's' &&
			args[2] == ' ')
	{
		args = args.substr(3);
		execSilently = true;
	}

	size_t spacepos = args.find_first_of(" ");
	args = args.substr(spacepos+1);
	spacepos = args.find_first_of(" ");
	args = args.substr(spacepos+1);

	std::string cmd;

	if(spacepos == std::string::npos)
		args = "";

	std::string argcmd = execSilently ? silentshellcommand : argumentshellcommand;

	if(args.length() == 0)
	{
		cmd = interactiveshellcommand;
	}
	else
	{
		std::string quotedPH = "#QQQQ#";
		if(argcmd.find(quotedPH) != std::string::npos)
		{
			args = FindAndReplace(args,"\"", "\\\"");
			args = FindAndReplace(args, "\\", "\\\\");
			cmd = FindAndReplace(argcmd, quotedPH, args);
		}
		else
		{
			cmd = argcmd + " " + args;
		}
	}
	//MessageBox(0,cmd.c_str(), 0,0);
	// I know, I know, baaaaad win16 function, unfortunately I could not get
	// CreateProcess working as I wanted it (actually showing me the window)
	// and also if I used CreateProcess, I would have to parse the program name
	// out of the shell.txt file to know where the parameters begint etc,
	// which is kinda difficult and not pleasant at all.
	WinExec(cmd.c_str(), SW_SHOW);
	return 0;
}
<commit_msg>Fixed vague for loop that was actually a while loop<commit_after>// vimshell.cpp : Defines the entry point for the application.
//

#include "vimshell.h"
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <shellapi.h>

bool cvtLPW2stdstring(std::string& s, const LPWSTR pw,
                      UINT codepage = CP_ACP)
{
    bool res = false;
    char* p = 0;
    int bsz;

    bsz = WideCharToMultiByte(codepage,
        0,
        pw,-1,
        0,0,
        0,0);
    if (bsz > 0) {
        p = new char[bsz];
        int rc = WideCharToMultiByte(codepage,
            0,
            pw,-1,
            p,bsz,
            0,0);
        if (rc != 0) {
            p[bsz-1] = 0;
            s = p;
            res = true;
        }
    }
    delete [] p;
    return res;
}

std::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace )
{
	size_t uPos = 0;
	size_t uFindLen = tFind.length();
	size_t uReplaceLen = tReplace.length();

	if( uFindLen == 0 )
	{
		return tInput;
	}

	while((uPos = tInput.find( tFind, uPos )) != std::string::npos)
	{
		tInput.replace( uPos, uFindLen, tReplace );
		uPos += uReplaceLen;
	}

	return tInput;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	int count;
	//MessageBox(0, lpCmdLine, 0, 0);
	LPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count);
	std::string currentDir;

	cvtLPW2stdstring(currentDir, strings[0]);

	// Cut off the filename
	while((currentDir.length() > 0) &&
		(currentDir[currentDir.length()-1] != '/') &&
		(currentDir[currentDir.length()-1] != '\\'))
	{
		currentDir = currentDir.substr(0, currentDir.length()-1);
	}
	if(currentDir.length() > 0 && currentDir[0] == '"')
		currentDir = currentDir.substr(1);

	std::string filename = currentDir + std::string("shell.txt");

	std::ifstream fileIn(filename.c_str());
	if(!fileIn)
	{
		MessageBox(0, "Please create a file called shell.txt in the same folder you put this new vimrun.exe", 0,0);
		return 1;
	}

	std::string argumentshellcommand;
	std::string silentshellcommand;
	std::string interactiveshellcommand;

	std::getline(fileIn, argumentshellcommand);
	std::getline(fileIn, silentshellcommand);
	std::getline(fileIn, interactiveshellcommand);

	std::string args = lpCmdLine;

	while(args.length() > 0 && args[0] == ' ')
		args = args.substr(1);

	bool execSilently = false;

	if(args.length() > 3 &&
			args[0] == '-' &&
			args[1] == 's' &&
			args[2] == ' ')
	{
		args = args.substr(3);
		execSilently = true;
	}

	size_t spacepos = args.find_first_of(" ");
	args = args.substr(spacepos+1);
	spacepos = args.find_first_of(" ");
	args = args.substr(spacepos+1);

	std::string cmd;

	if(spacepos == std::string::npos)
		args = "";

	std::string argcmd = execSilently ? silentshellcommand : argumentshellcommand;

	if(args.length() == 0)
	{
		cmd = interactiveshellcommand;
	}
	else
	{
		std::string quotedPH = "#QQQQ#";
		if(argcmd.find(quotedPH) != std::string::npos)
		{
			args = FindAndReplace(args,"\"", "\\\"");
			args = FindAndReplace(args, "\\", "\\\\");
			cmd = FindAndReplace(argcmd, quotedPH, args);
		}
		else
		{
			cmd = argcmd + " " + args;
		}
	}
	//MessageBox(0,cmd.c_str(), 0,0);
	// I know, I know, baaaaad win16 function, unfortunately I could not get
	// CreateProcess working as I wanted it (actually showing me the window)
	// and also if I used CreateProcess, I would have to parse the program name
	// out of the shell.txt file to know where the parameters begint etc,
	// which is kinda difficult and not pleasant at all.
	WinExec(cmd.c_str(), SW_SHOW);
	return 0;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_resclk_defines.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
<commit_msg>PM: Resonant Clocking Enablement - Infrastructure<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/lib/p9_resclk_defines.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file   p9_resclk_defines.H
/// @brief  Defines Resonant Clocking default values (provided by clock team).
///
// *HWP HWP Owner:
// *HWP FW Owner:
// *HWP Team:           PM
// *HWP Level:
// *HWP Consumed by:

#ifndef __P9_RESCLK_DEFINES_H__
#define __P9_RESCLK_DEFINES_H__

#include <vector>

namespace p9_resclk_defines
{
typedef struct
{
    uint16_t freq;
    uint8_t  idx;
} rsclk_freq_idx_t;
//###############################################################################
// Table 1: Resonant Clocking Control Index
// consists of 8 entries consisting of a comma-delimited pair.
// Freq(in Mhz), Index(decimal number between 0 & 63, index into the next table)
// The first entry is always 0 Mhz. Entries are in ascending order of frequency.
// Algorithm will search starting at the bottom of the index until it
// finds the first entry at or below target frequency, then walk to that index.
//###############################################################################
std::vector<rsclk_freq_idx_t> const RESCLK_INDEX_VEC =
{
    //  { Freq, Idx}
    {    0,  3 },
    { 1500,  3 },
    { 2000, 24 },
    { 3000, 24 },
    { 3400, 24 },
    { 3700, 24 },
    { 3900, 24 },
    { 4100, 24 }
};
//###############################################################################
// Table 2: Resonant (Core & L2) Grids Control Data
// 64 entries,each entry a 16-bit hex value.
// First row corresponds to Index 0 from Table 1.  Last row is Index 63.
// Left aligned hex value corresponding to the first 13-bits of the QACCR register
// 0:3 SB_STRENGTH; 4 SB_SPARE; 6:7 SB_PULSE_MODE; 8:11 SW_RESCLK; 12 SW_SPARE
//###############################################################################
std::vector<uint16_t> const RESCLK_TABLE_VEC =
{
    0x2000,
    0x3000,
    0x1000,
    0x0000,
    0x0010,
    0x0030,
    0x0020,
    0x0060,
    0x0070,
    0x0050,
    0x0040,
    0x00C0,
    0x00D0,
    0x00F0,
    0x00E0,
    0x00A0,
    0x00B0,
    0x0090,
    0x0080,
    0x8080,
    0x9080,
    0xB080,
    0xA080,
    0xE080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080,
    0xF080
};
//###############################################################################
// Table 3: L3 Grid Control Data
// 4 entries, each a 8-bit hex value to transition between two modes
// Entry 0 is the "Full Power" setting
// Entry 3 is the "Low  Power" setting, for use above voltages defined by
// L3_VOLTAGE_THRESHOLD_MV (ATTR_SYSTEM_RESCLK_L3_VOLTAGE_THRESHOLD_MV)
// Hex value corresponding to L3 control bits in the QACCR(16:23)
// 0:3 SB_STRENGTH;       (Not supported: 4 SB_SPARE; 5:7 SB_PULSE_MODE)
//###############################################################################
std::vector<uint8_t> const L3CLK_TABLE_VEC
{
    0,
    1,
    3,
    2
};
//###############################################################################
// L3 Voltage Threshold (millivolts)
//###############################################################################
uint16_t const L3_VOLTAGE_THRESHOLD_MV = 600;
}

#endif //__P9_RESCLK_DEFINES_H__
<|endoftext|>