text:
#include "PerfTools/Callgrind/interface/ProfilerService.h"

#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/ActivityRegistry.h"

#include <boost/ref.hpp>

#include <limits>
#include <vector>
#include <string>
#include <cmath>

#include <cppunit/extensions/HelperMacros.h>

namespace {
  std::string gS;
  double gD;
  void doSomething(std::string const& name) {
    static std::string const local("p1");
    if (name == local)
      gS = name;
    if (!name.empty())
      gD += std::sqrt(double(name[0]));
  }
  void doSomethingElse(std::string const& name) {
    static std::string const local("p1");
    if (name == local)
      gS = name;
    if (!name.empty())
      gD += std::sqrt(double(name[0]));
  }
}  // namespace

namespace test {
  class TestProfilerService : public CppUnit::TestFixture {
    CPPUNIT_TEST_SUITE(TestProfilerService);
    CPPUNIT_TEST(check_constr);
    CPPUNIT_TEST(check_config);
    CPPUNIT_TEST(check_Instrumentation);
    CPPUNIT_TEST(check_FullEvent);
    CPPUNIT_TEST(check_Event);
    CPPUNIT_TEST(check_Path);
    CPPUNIT_TEST(check_ExcludedPath);
    // CPPUNIT_TEST(check_AllPaths);
    CPPUNIT_TEST(check_Nesting);
    CPPUNIT_TEST_SUITE_END();

  public:
    TestProfilerService();
    void setUp();
    void tearDown();
    void check_constr();
    void check_config();
    void check_Instrumentation();
    void check_FullEvent();
    void check_Event();
    void check_Path();
    void check_ExcludedPath();
    void check_AllPaths();
    void check_Nesting();
  };

  CPPUNIT_TEST_SUITE_REGISTRATION(TestProfilerService);

  TestProfilerService::TestProfilerService() {}

  void TestProfilerService::setUp() {}

  void TestProfilerService::tearDown() {}

  void TestProfilerService::check_constr() {
    edm::ParameterSet pset;
    edm::ActivityRegistry activity;
    ProfilerService ps(pset, activity);
    CPPUNIT_ASSERT(ps.m_firstEvent == 0);
    CPPUNIT_ASSERT(ps.m_lastEvent == std::numeric_limits<int>::max());
    CPPUNIT_ASSERT(ps.m_dumpInterval == 100);
    CPPUNIT_ASSERT(ps.m_excludedPaths.empty());
    CPPUNIT_ASSERT(ps.m_paths.empty());
  }

  void TestProfilerService::check_config() {
    int fe = 2;
    int le = 10;
    int di = 5;
    std::vector<std::string> paths = {"p1", "p2", "p3"};
    std::vector<std::string> ep = {"e1", "e2", "e3"};
    edm::ParameterSet pset;
    pset.addUntrackedParameter<int>("firstEvent", fe);
    pset.addUntrackedParameter<int>("lastEvent", le);
    pset.addUntrackedParameter<int>("dumpInterval", di);
    pset.addUntrackedParameter<std::vector<std::string> >("paths", paths);
    pset.addUntrackedParameter<std::vector<std::string> >("excludePaths", ep);
    edm::ActivityRegistry activity;
    {
      ProfilerService ps(pset, activity);
      CPPUNIT_ASSERT(ps.m_firstEvent == fe);
      CPPUNIT_ASSERT(ps.m_lastEvent == le);
      CPPUNIT_ASSERT(ps.m_dumpInterval == di);
      CPPUNIT_ASSERT(ps.m_excludedPaths == ep);
      CPPUNIT_ASSERT(ps.m_paths == paths);
      CPPUNIT_ASSERT(!ps.m_allPaths);
    }
    paths.push_back("ALL");
    pset.addUntrackedParameter<std::vector<std::string> >("paths", paths);
    {
      ProfilerService ps(pset, activity);
      CPPUNIT_ASSERT(ps.m_allPaths);
    }
  }

  void TestProfilerService::check_Instrumentation() {
    int fe = 2;
    int le = 10;
    int di = 5;
    edm::ParameterSet pset;
    pset.addUntrackedParameter<int>("firstEvent", fe);
    pset.addUntrackedParameter<int>("lastEvent", le);
    pset.addUntrackedParameter<int>("dumpInterval", di);
    edm::ActivityRegistry activity;
    ProfilerService ps(pset, activity);
    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(!ps.doEvent());
    CPPUNIT_ASSERT(ps.m_counts == 0);
    CPPUNIT_ASSERT(!ps.startInstrumentation());
    doSomethingElse("bha");
    CPPUNIT_ASSERT(!ps.stopInstrumentation());
    CPPUNIT_ASSERT(!ps.forceStopInstrumentation());

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(ps.m_counts == 0);
    CPPUNIT_ASSERT(ps.doEvent());
    CPPUNIT_ASSERT(ps.startInstrumentation());
    CPPUNIT_ASSERT(ps.m_counts == 1);
    doSomething("bha");
    CPPUNIT_ASSERT(ps.stopInstrumentation());
    CPPUNIT_ASSERT(!ps.forceStopInstrumentation());

    CPPUNIT_ASSERT(ps.startInstrumentation());
    CPPUNIT_ASSERT(!ps.startInstrumentation());
    doSomething("bha");
    CPPUNIT_ASSERT(!ps.stopInstrumentation());
    CPPUNIT_ASSERT(ps.stopInstrumentation());
    CPPUNIT_ASSERT(!ps.stopInstrumentation());

    for (int i = 2; i < 10; i++) {
      ps.beginEvent();
      doSomething("bha");
    }
    CPPUNIT_ASSERT(ps.m_evtCount == 10);
    CPPUNIT_ASSERT(ps.doEvent());
    CPPUNIT_ASSERT(ps.startInstrumentation());
    CPPUNIT_ASSERT(ps.m_counts == 3);
    doSomething("bha");
    CPPUNIT_ASSERT(ps.stopInstrumentation());
    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_evtCount == 11);
    CPPUNIT_ASSERT(!ps.doEvent());
    CPPUNIT_ASSERT(!ps.startInstrumentation());
    doSomethingElse("bha");
    CPPUNIT_ASSERT(!ps.stopInstrumentation());
    CPPUNIT_ASSERT(ps.m_counts == 3);
  }

  void TestProfilerService::check_FullEvent() {
    int fe = 2;
    int le = 10;
    std::vector<std::string> paths = {"FullEvent"};
    edm::ParameterSet pset;
    pset.addUntrackedParameter<int>("firstEvent", fe);
    pset.addUntrackedParameter<int>("lastEvent", le);
    pset.addUntrackedParameter<std::vector<std::string> >("paths", paths);
    edm::ActivityRegistry activity;
    ProfilerService ps(pset, activity);

    ps.fullEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(!ps.doEvent());
    doSomethingElse("bha");

    ps.fullEvent();
    CPPUNIT_ASSERT(ps.m_active == 1);
    CPPUNIT_ASSERT(ps.doEvent());
    doSomething("bha");
    for (int i = 2; i < 10; i++) {
      ps.fullEvent();
      doSomething("bha");
    }
    CPPUNIT_ASSERT(ps.m_evtCount == 10);
    CPPUNIT_ASSERT(ps.doEvent());  // who cares?

    ps.fullEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(!ps.doEvent());
    doSomethingElse("bha");
    ps.fullEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
  }

  // now used ALL paths....
  void TestProfilerService::check_Event() {
    int fe = 2;
    int le = 10;
    std::vector<std::string> paths = {"ALL"};
    edm::ParameterSet pset;
    pset.addUntrackedParameter<int>("firstEvent", fe);
    pset.addUntrackedParameter<int>("lastEvent", le);
    pset.addUntrackedParameter<std::vector<std::string> >("paths", paths);
    edm::ActivityRegistry activity;
    ProfilerService ps(pset, activity);

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(!ps.doEvent());
    doSomethingElse("bha");
    ps.endEvent();

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 1);
    CPPUNIT_ASSERT(ps.doEvent());
    doSomething("bha");
    ps.endEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    for (int i = 2; i < 10; i++) {
      ps.beginEvent();
      doSomething("bha");
      ps.endEvent();
    }
    CPPUNIT_ASSERT(ps.m_evtCount == 10);
    CPPUNIT_ASSERT(ps.doEvent());  // who cares?

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(!ps.doEvent());
    doSomethingElse("bha");
    ps.endEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
  }

  struct CheckPaths {
    CheckPaths(ProfilerService& ips, std::vector<std::string> const& iselpaths, int ibase = 0, bool iexc = false)
        : ps(ips), selpaths(iselpaths), base(ibase), exc(iexc), done(0) {}
    ProfilerService& ps;
    std::vector<std::string> const& selpaths;
    int base;
    bool exc;

    mutable int done;

    void operator()(std::string const& path) const {
      bool found = std::find(selpaths.begin(), selpaths.end(), path) != selpaths.end();
      bool ok = ps.doEvent() && (exc ? !found : found);
      noselPath(true);
      ps.beginPath(path);
      if (ok)
        selPath(path);
      else
        noselPath(!ps.doEvent());
      ps.endPath(path);
      noselPath(true);
    }

    void selPath(const std::string& path) const {
      CPPUNIT_ASSERT(ps.m_active == (base + (exc ? 0 : 1)));
      CPPUNIT_ASSERT(exc || ps.m_activePath == path);
      CPPUNIT_ASSERT(!ps.m_paused);
      ++done;
      doSomething(path);
    }

    void noselPath(bool f = false) const {
      CPPUNIT_ASSERT(ps.m_active == base);
      CPPUNIT_ASSERT(ps.m_activePath.empty());
      CPPUNIT_ASSERT(f || (!exc) || ps.m_paused);
      CPPUNIT_ASSERT(!(f && ps.m_paused));
      doSomethingElse("else");
    }
  };

  void TestProfilerService::check_Path() {
    int fe = 2;
    int le = 10;
    std::vector<std::string> paths = {"p1", "p2", "p3"};
    edm::ParameterSet pset;
    pset.addUntrackedParameter<int>("firstEvent", fe);
    pset.addUntrackedParameter<int>("lastEvent", le);
    pset.addUntrackedParameter<std::vector<std::string> >("paths", paths);
    edm::ActivityRegistry activity;
    ProfilerService ps(pset, activity);

    std::vector<std::string> allPaths = {"p1", "p21", "p22", "p3"};
    CheckPaths cp(ps, paths);
    CPPUNIT_ASSERT(std::find(paths.begin(), paths.end(), allPaths[0]) != paths.end());
    CPPUNIT_ASSERT(std::find(paths.begin(), paths.end(), allPaths[1]) == paths.end());
    CPPUNIT_ASSERT(std::find(paths.begin(), paths.end(), allPaths[2]) == paths.end());
    CPPUNIT_ASSERT(std::find(paths.begin(), paths.end(), allPaths[3]) != paths.end());

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(!ps.doEvent());
    CPPUNIT_ASSERT(std::for_each(allPaths.begin(), allPaths.end(), cp).done == 0);
    ps.endEvent();

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(ps.doEvent());
    CPPUNIT_ASSERT(std::for_each(allPaths.begin(), allPaths.end(), cp).done == 2);
    ps.endEvent();
  }
  void TestProfilerService::check_ExcludedPath() {
    int fe = 2;
    int le = 10;
    std::vector<std::string> paths = {"ALL"};
    std::vector<std::string> expaths = {"p21"};
    edm::ParameterSet pset;
    pset.addUntrackedParameter<int>("firstEvent", fe);
    pset.addUntrackedParameter<int>("lastEvent", le);
    pset.addUntrackedParameter<std::vector<std::string> >("paths", paths);
    pset.addUntrackedParameter<std::vector<std::string> >("excludePaths", expaths);
    edm::ActivityRegistry activity;
    ProfilerService ps(pset, activity);

    std::vector<std::string> allPaths = {"p1", "p21", "p22", "p3"};
    CheckPaths cp0(ps, expaths, 0, true);
    CheckPaths cp1(ps, expaths, 1, true);
    CPPUNIT_ASSERT(std::find(expaths.begin(), expaths.end(), allPaths[0]) == expaths.end());
    CPPUNIT_ASSERT(std::find(expaths.begin(), expaths.end(), allPaths[1]) != expaths.end());
    CPPUNIT_ASSERT(std::find(expaths.begin(), expaths.end(), allPaths[2]) == expaths.end());
    CPPUNIT_ASSERT(std::find(expaths.begin(), expaths.end(), allPaths[3]) == expaths.end());

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(!ps.doEvent());
    CPPUNIT_ASSERT(std::for_each(allPaths.begin(), allPaths.end(), cp0).done == 0);
    ps.endEvent();

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active != 0);
    CPPUNIT_ASSERT(ps.doEvent());
    CPPUNIT_ASSERT(std::for_each(allPaths.begin(), allPaths.end(), cp1).done == 3);
    ps.endEvent();
  }

  // same as nesting, removed....
  void TestProfilerService::check_AllPaths() {
    int fe = 2;
    int le = 10;
    std::vector<std::string> paths = {"ALL", "p2", "p3"};
    edm::ParameterSet pset;
    pset.addUntrackedParameter<int>("firstEvent", fe);
    pset.addUntrackedParameter<int>("lastEvent", le);
    pset.addUntrackedParameter<std::vector<std::string> >("paths", paths);
    edm::ActivityRegistry activity;
    ProfilerService ps(pset, activity);

    std::vector<std::string> allPaths = {"p1", "p21", "p22", "p3"};
    CheckPaths cp(ps, paths);

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(!ps.doEvent());
    CPPUNIT_ASSERT(std::for_each(allPaths.begin(), allPaths.end(), cp).done == 0);
    ps.endEvent();

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 1);
    CPPUNIT_ASSERT(ps.doEvent());
    //  CPPUNIT_ASSERT(std::for_each(allPaths.begin(),allPaths.end(),cp).done==4);
    CPPUNIT_ASSERT(std::for_each(allPaths.begin(), allPaths.end(), cp).done == 1);
    ps.endEvent();
  }

  void TestProfilerService::check_Nesting() {
    int fe = 2;
    int le = 10;
    std::vector<std::string> paths = {"ALL", "p1", "p2", "p3"};
    edm::ParameterSet pset;
    pset.addUntrackedParameter<int>("firstEvent", fe);
    pset.addUntrackedParameter<int>("lastEvent", le);
    pset.addUntrackedParameter<std::vector<std::string> >("paths", paths);
    edm::ActivityRegistry activity;
    ProfilerService ps(pset, activity);

    std::vector<std::string> allPaths = {"p1", "p21", "p22", "p3"};

    CheckPaths cp0(ps, paths, 0);
    CheckPaths cp1(ps, paths, 1);

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
    CPPUNIT_ASSERT(!ps.doEvent());
    CPPUNIT_ASSERT(std::for_each(allPaths.begin(), allPaths.end(), cp0).done == 0);
    ps.endEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);

    ps.beginEvent();
    CPPUNIT_ASSERT(ps.m_active == 1);
    CPPUNIT_ASSERT(ps.doEvent());
    CPPUNIT_ASSERT(std::for_each(allPaths.begin(), allPaths.end(), cp1).done == 2);
    ps.endEvent();
    CPPUNIT_ASSERT(ps.m_active == 0);
  }
}  // namespace test

ext: cc

max_stars_repo_name: Purva-Chaudhari/cmssw

max_issues_repo_name: Purva-Chaudhari/cmssw

max_forks_repo_name: Purva-Chaudhari/cmssw


text:
// NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION

// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// $Source: /physbam_repository/External_Libraries/Archives/boost/boost/type_traits/detail/size_t_trait_def.hpp,v $
// $Date: 2007/02/12 18:26:08 $
// $Revision: 1.1 $

#include <boost/type_traits/detail/template_arity_spec.hpp>
#include <boost/type_traits/integral_constant.hpp>
#include <boost/mpl/aux_/lambda_support.hpp>
#include <boost/mpl/size_t.hpp>

#include <cstddef>

#if !defined(BOOST_MSVC) || BOOST_MSVC > 1200
#   define BOOST_TT_AUX_SIZE_T_BASE(C) ::boost::integral_constant<std::size_t,C>
#   define BOOST_TT_AUX_SIZE_T_TRAIT_VALUE_DECL(C) /**/
#else
#   define BOOST_TT_AUX_SIZE_T_BASE(C) ::boost::mpl::size_t<C>
#   define BOOST_TT_AUX_SIZE_T_TRAIT_VALUE_DECL(C) \
    typedef ::boost::mpl::size_t<C> base_; \
    using base_::value; \
    /**/
#endif

#define BOOST_TT_AUX_SIZE_T_TRAIT_DEF1(trait,T,C) \
template< typename T > struct trait \
    : BOOST_TT_AUX_SIZE_T_BASE(C) \
{ \
    BOOST_TT_AUX_SIZE_T_TRAIT_VALUE_DECL(C) \
    BOOST_MPL_AUX_LAMBDA_SUPPORT(1,trait,(T)) \
}; \
\
BOOST_TT_AUX_TEMPLATE_ARITY_SPEC(1,trait) \
/**/

#define BOOST_TT_AUX_SIZE_T_TRAIT_SPEC1(trait,spec,C) \
template<> struct trait<spec> \
    : BOOST_TT_AUX_SIZE_T_BASE(C) \
{ \
    BOOST_TT_AUX_SIZE_T_TRAIT_VALUE_DECL(C) \
    BOOST_MPL_AUX_LAMBDA_SUPPORT_SPEC(1,trait,(spec)) \
}; \
/**/

#define BOOST_TT_AUX_SIZE_T_TRAIT_PARTIAL_SPEC1_1(param,trait,spec,C) \
template< param > struct trait<spec> \
    : BOOST_TT_AUX_SIZE_T_BASE(C) \
{ \
}; \
/**/

ext: hpp

max_stars_repo_name: schinmayee/nimbus

max_issues_repo_name: schinmayee/nimbus

max_forks_repo_name: schinmayee/nimbus


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file    testJunctionTree.cpp
 * @brief   Unit tests for Junction Tree
 * @author  Kai Ni
 * @author  Frank Dellaert
 */

#include <boost/assign/std/list.hpp> // for operator +=
#include <boost/assign/std/vector.hpp> // for operator +=
#include <boost/assign/std/set.hpp> // for operator +=
using namespace boost::assign;

#include <CppUnitLite/TestHarness.h>
#include <gtsam/base/TestableAssertions.h>

#include <gtsam/inference/SymbolicFactorGraph.h>
#include <gtsam/inference/JunctionTree.h>
#include <gtsam/inference/ClusterTree.h>
#include <gtsam/inference/JunctionTree.h>
#include <gtsam/inference/IndexFactor.h>
#include <gtsam/inference/SymbolicSequentialSolver.h>

using namespace gtsam;
using namespace std;

typedef JunctionTree<SymbolicFactorGraph> SymbolicJunctionTree;

/* ************************************************************************* *
 * x1 - x2 - x3 - x4
 * x3 x4
 *    x2 x1 : x3
 ****************************************************************************/
TEST( JunctionTree, constructor )
{
  const Index x2=0, x1=1, x3=2, x4=3;
  SymbolicFactorGraph fg;
  fg.push_factor(x2,x1);
  fg.push_factor(x2,x3);
  fg.push_factor(x3,x4);

  SymbolicJunctionTree actual(fg);

  vector<Index> frontal1; frontal1 += x3, x4;
  vector<Index> frontal2; frontal2 += x2, x1;
  vector<Index> sep1;
  vector<Index> sep2; sep2 += x3;
  CHECK(assert_equal(frontal1, actual.root()->frontal));
  CHECK(assert_equal(sep1,     actual.root()->separator));
  LONGS_EQUAL(1,               actual.root()->size());
  CHECK(assert_equal(frontal2, actual.root()->children().front()->frontal));
  CHECK(assert_equal(sep2,     actual.root()->children().front()->separator));
  LONGS_EQUAL(2,               actual.root()->children().front()->size());
  CHECK(assert_equal(*fg[2], *(*actual.root())[0]));
  CHECK(assert_equal(*fg[0], *(*actual.root()->children().front())[0]));
  CHECK(assert_equal(*fg[1], *(*actual.root()->children().front())[1]));
}

/* ************************************************************************* *
 * x1 - x2 - x3 - x4
 * x3 x4
 *    x2 x1 : x3
 ****************************************************************************/
TEST( JunctionTree, eliminate)
{
  const Index x2=0, x1=1, x3=2, x4=3;
  SymbolicFactorGraph fg;
  fg.push_factor(x2,x1);
  fg.push_factor(x2,x3);
  fg.push_factor(x3,x4);

  SymbolicJunctionTree jt(fg);
  SymbolicBayesTree::sharedClique actual = jt.eliminate(&EliminateSymbolic);

  BayesNet<IndexConditional> bn(*SymbolicSequentialSolver(fg).eliminate());
  SymbolicBayesTree expected(bn);

//  cout << "BT from JT:\n";
//  actual->printTree("");

  CHECK(assert_equal(*expected.root(), *actual));
}

/* ************************************************************************* */
int main() {
  TestResult tr;
  return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */

ext: cpp

max_stars_repo_name: malcolmreynolds/GTSAM

max_issues_repo_name: malcolmreynolds/GTSAM

max_forks_repo_name: malcolmreynolds/GTSAM


text:
#include <boost/test/minimal.hpp>

#include <RCF/RCF.hpp>
#include <RCF/util/CommandLine.hpp>
#include <RCF/util/PortNumbers.hpp>

int test_main(int argc, char **argv)
{
    util::CommandLineOption<int> port("port", util::Ports::getNext(), "endpoint server port number");
    util::CommandLine::getSingleton().parse(argc, argv);

    RCF::RcfServer server(port);
    server.start();

    return 0;
}

max_stars_repo_name: importlib/klib

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
#define GRAPHVIZ_DIRECTED 0

/*  A Bison parser, made from graphviz_parser.yy
    by GNU Bison version 1.28  */

#define YYBISON 1  /* Identify Bison output.  */

#define yyparse bgl_undir_parse
#define yylex bgl_undir_lex
#define yyerror bgl_undir_error
#define yylval bgl_undir_lval
#define yychar bgl_undir_char
#define yydebug bgl_undir_debug
#define yynerrs bgl_undir_nerrs
#define GRAPH_T 257
#define NODE_T  258
#define EDGE_T  259
#define DIGRAPH_T       260
#define EDGEOP_T        261
#define SUBGRAPH_T      262
#define ID_T    263

//=======================================================================
// Copyright 2001 University of Notre Dame.
// Author: Lie-Quan Lee
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>

#include <boost/config.hpp>
#include <boost/graph/graphviz.hpp>

#if defined BOOST_NO_STRINGSTREAM
  //#include <strstream> //We cannot use it since there is a bug in strstream
#include <stdlib.h>
#else
#include <sstream>
#endif

using std::free;
using std::malloc;

#ifndef GRAPHVIZ_DIRECTED
#error Need to define the GRAPHVIZ_DIRECTED macro to either 0 or 1
#endif

#if GRAPHVIZ_DIRECTED == 0
#define GRAPHVIZ_GRAPH boost::GraphvizGraph
#define yyrestart bgl_undir_restart
#else
#define GRAPHVIZ_GRAPH boost::GraphvizDigraph
#define yyrestart bgl_dir_restart
#endif

#define YYPARSE_PARAM g

#include "yystype.h"

  extern void yyerror(char* str);
  extern void yyrestart(FILE* str);
  extern int yylex(YYSTYPE* lvalp);

  enum AttrState {GRAPH_GRAPH_A, GRAPH_NODE_A, GRAPH_EDGE_A, NODE_A, EDGE_A};

  using boost::GraphvizAttrList;

  namespace graphviz {

    typedef boost::graph_traits<GRAPHVIZ_GRAPH>::vertex_descriptor Vertex;
    typedef boost::graph_traits<GRAPHVIZ_GRAPH>::edge_descriptor   Edge;
    typedef GRAPHVIZ_GRAPH Subgraph;

    static Vertex current_vertex;
    static Edge   current_edge;
    static Subgraph* current_graph = NULL;
    static Subgraph* previous_graph = NULL;

    static std::vector< std::pair<void*, bool>* > vlist;//store a list of rhs

    static std::map<std::string,std::string> attributes;//store attributes temporarily
    static AttrState attribute_state;

    static std::map<std::string, Subgraph*> subgraphs;  //store the names of subgraphs
    static std::map<std::string, Vertex> nodes;         //store the names of nodes

    typedef std::map<std::string, Subgraph*>::iterator It;
    typedef std::map<std::string, Vertex>::iterator Iter;

    static const std::string& get_graph_name(const Subgraph& g) {
      const boost::graph_property<Subgraph, boost::graph_name_t>::type&
        name = boost::get_property(g, boost::graph_name);
      return name;
    }

    static std::pair<Iter, bool> lookup(const std::string& name) {
      //lookup in the top level
      Iter it = nodes.find(name);
      bool found = (it != nodes.end() );
      return std::make_pair(it, found);
    }

    static Vertex add_name(const std::string& name, GRAPHVIZ_GRAPH& g) {
      Vertex v = boost::add_vertex(*current_graph);
      v = current_graph->local_to_global(v);

      //set the label of vertex, it could be overwritten later.
      boost::property_map<GRAPHVIZ_GRAPH, boost::vertex_attribute_t>::type
        va = boost::get(boost::vertex_attribute, g);
      va[v]["label"] = name;

      //add v into the map so next time we will find it.
      nodes[name] = v;
      return v;
    }

    static std::pair<It, bool> lookup_subgraph(const std::string& name) {
      It it = subgraphs.find(name);
      bool found = (it != subgraphs.end() );
      return std::make_pair(it, found);
    }

    static Subgraph* create_subgraph(const std::string& name) {

      Subgraph* new_subgraph = &(current_graph->create_subgraph());

      subgraphs[name]        = new_subgraph;
      return new_subgraph;
    }

    static void set_attribute(GraphvizAttrList& p,
                              const GraphvizAttrList& attr) {
      GraphvizAttrList::const_iterator i, end;
      for ( i=attr.begin(), end=attr.end(); i!=end; ++i)
        p[i->first]=i->second;
    }

    static void set_attribute(Subgraph& g,
                              AttrState s, bool clear_attribute = true) {
      typedef Subgraph Graph;
      switch ( s ) {
      case GRAPH_GRAPH_A:
        {
          boost::graph_property<Graph, boost::graph_graph_attribute_t>::type&
            gga = boost::get_property(g, boost::graph_graph_attribute);
          set_attribute(gga, attributes);
        }
        break;
      case GRAPH_NODE_A:
        {
          boost::graph_property<Graph, boost::graph_vertex_attribute_t>::type&
            gna = boost::get_property(g, boost::graph_vertex_attribute);
          set_attribute(gna, attributes);
        }
        break;
      case GRAPH_EDGE_A:
        {
          boost::graph_property<Graph, boost::graph_edge_attribute_t>::type&
            gea = boost::get_property(g, boost::graph_edge_attribute);
          set_attribute(gea, attributes);
        }
        break;
      case NODE_A:
        {
          boost::property_map<Graph, boost::vertex_attribute_t>::type
            va = boost::get(boost::vertex_attribute, g);    //va[v]
          set_attribute(va[current_vertex], attributes);
        }
        break;
      case EDGE_A:
        {
          boost::property_map<Graph, boost::edge_attribute_t>::type
            ea = boost::get(boost::edge_attribute, g);      //ea[e]
          set_attribute(ea[current_edge], attributes);
        }
        break;
      }
      if ( clear_attribute )
        attributes.clear();
    }

    static void add_edges(const Vertex& u,
                          const Vertex& v, GRAPHVIZ_GRAPH& g) {
      graphviz::current_edge = boost::add_edge(u, v, g).first;
      graphviz::set_attribute(g, EDGE_A, false);
    }

    static void add_edges(Subgraph* G1, Subgraph* G2,
                          GRAPHVIZ_GRAPH& g) {
      boost::graph_traits<Subgraph>::vertex_iterator i, j, m, n;
      for ( boost::tie(i, j) = boost::vertices(*G1); i != j; ++i) {
        for ( boost::tie(m, n) = boost::vertices(*G2); m != n; ++m) {
          graphviz::add_edges(G1->local_to_global(*i),
                              G2->local_to_global(*m), g);
        }
      }
    }

    static void add_edges(Subgraph* G, const Vertex& v, GRAPHVIZ_GRAPH& g) {
      boost::graph_traits<Subgraph>::vertex_iterator i, j;
      for ( boost::tie(i, j) = boost::vertices(*G); i != j; ++i) {
        graphviz::add_edges(G->local_to_global(*i), v, g);
      }
    }

    static void add_edges(const Vertex& u, Subgraph* G, GRAPHVIZ_GRAPH& g) {
      boost::graph_traits<Subgraph>::vertex_iterator i, j;
      for ( boost::tie(i, j) = boost::vertices(*G); i != j; ++i) {
        graphviz::add_edges(u, G->local_to_global(*i), g);
      }
    }

    static std::string random_string() {
      static int i=0;
#if defined BOOST_NO_STRINGSTREAM
      //std::strstream out;
      char buf[256];
      sprintf(buf, "default%i\0", i);
      ++i;
      return std::string(buf);
#else
      std::stringstream out;
      out << "default" << i;
      ++i;
      return out.str();
#endif
    }

    static void set_graph_name(const std::string& name) {
      boost::graph_property<Subgraph, boost::graph_name_t>::type&
        gea = boost::get_property(*current_graph, boost::graph_name);
      gea = name;
    }

  } //namespace detail {

#include <stdio.h>

#ifndef __cplusplus
#ifndef __STDC__
#define const
#endif
#endif

#define YYFINAL         67
#define YYFLAG          -32768
#define YYNTBASE        18

#define YYTRANSLATE(x) ((unsigned)(x) <= 263 ? yytranslate[x] : 46)

static const char yytranslate[] = {     0,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,    16,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,    17,    12,     2,
    15,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
    13,     2,    14,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,    10,     2,    11,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
     2,     2,     2,     2,     2,     1,     3,     4,     5,     6,
     7,     8,     9
};

#if YYDEBUG != 0
static const short yyprhs[] = {     0,
     0,     3,     7,    10,    12,    14,    16,    17,    20,    22,
    24,    25,    28,    31,    36,    38,    40,    42,    44,    45,
    47,    51,    55,    57,    59,    60,    62,    64,    66,    68,
    70,    73,    77,    78,    80,    82,    86,    90,    93,    95,
    98,   100,   102,   105,   106,   109,   112,   114
};

static const short yyrhs[] = {    20,
    19,     0,    10,    23,    11,     0,    21,    22,     0,     3,
     0,     6,     0,     9,     0,     0,    23,    25,     0,    25,
     0,    12,     0,     0,    26,    24,     0,    32,    24,     0,
    27,    13,    28,    14,     0,     3,     0,     4,     0,     5,
     0,    29,     0,     0,    30,     0,    29,    31,    30,     0,
     9,    15,     9,     0,    12,     0,    16,     0,     0,    34,
     0,    38,     0,    33,     0,    42,     0,    30,     0,    36,
    35,     0,    13,    28,    14,     0,     0,     9,     0,    37,
     0,     9,    17,     9,     0,    41,    40,    35,     0,     7,
    41,     0,    39,     0,    40,    39,     0,    36,     0,    42,
     0,    44,    45,     0,     0,    43,    19,     0,     8,     9,
     0,    19,     0,     0
};

#endif

#if YYDEBUG != 0
static const short yyrline[] = { 0,
   239,   242,   245,   259,   259,   262,   262,   265,   265,   268,
   268,   271,   271,   275,   282,   283,   284,   287,   287,   290,
   290,   293,   303,   303,   303,   306,   306,   306,   306,   309,
   317,   328,   328,   331,   346,   349,   368,   413,   417,   417,
   420,   429,   440,   447,   457,   462,   483,   483
};
#endif

#if YYDEBUG != 0 || defined (YYERROR_VERBOSE)

static const char * const yytname[] = {   "$","error","$undefined.","GRAPH_T",
"NODE_T","EDGE_T","DIGRAPH_T","EDGEOP_T","SUBGRAPH_T","ID_T","'{'","'}'","';'",
"'['","']'","'='","','","':'","graph","graph_body","graph_header","graph_type",
"graph_name","stmt_list","semicolon","stmt","attr_stmt","attr_header","attr_list",
"nonempty_attr_list","attr","attr_separator","compound_stmt","graph_attr","node_stmt",
"opt_attr","node_id","node_port","edge_stmt","edge_rhs_one","edge_rhs","edge_endpoint",
"subgraph","@1","subgraph_header","opt_graph_body", NULL
};
#endif

static const short yyr1[] = {     0,
    18,    19,    20,    21,    21,    22,    22,    23,    23,    24,
    24,    25,    25,    26,    27,    27,    27,    28,    28,    29,
    29,    30,    31,    31,    31,    32,    32,    32,    32,    33,
    34,    35,    35,    36,    36,    37,    38,    39,    40,    40,
    41,    41,    42,    43,    42,    44,    45,    45
};

static const short yyr2[] = {     0,
     2,     3,     2,     1,     1,     1,     0,     2,     1,     1,
     0,     2,     2,     4,     1,     1,     1,     1,     0,     1,
     3,     3,     1,     1,     0,     1,     1,     1,     1,     1,
     2,     3,     0,     1,     1,     3,     3,     2,     1,     2,
     1,     1,     2,     0,     2,     2,     1,     0
};

static const short yydefact[] = {     0,
     4,     5,     0,     7,    44,     1,     6,     3,    15,    16,
    17,     0,    34,    44,     9,    11,     0,    30,    11,    28,
    26,    33,    35,    27,     0,    29,     0,    48,    46,     0,
     0,     2,     8,    10,    12,    19,    13,    19,    31,    44,
    39,    33,    45,    47,    43,    22,    36,     0,     0,    18,
    20,     0,    34,    41,    38,    42,    37,    40,    14,    23,
    24,     0,    32,    21,     0,     0,     0
};

static const short yydefgoto[] = {    65,
     6,     3,     4,     8,    14,    35,    15,    16,    17,    49,
    50,    18,    62,    19,    20,    21,    39,    22,    23,    24,
    41,    42,    25,    26,    27,    28,    45
};

static const short yypact[] = {    19,
-32768,-32768,    -9,     9,    12,-32768,-32768,-32768,-32768,-32768,
-32768,    18,    13,     0,-32768,    17,    20,-32768,    17,-32768,
-32768,    -1,-32768,-32768,    27,    28,    -9,    -9,-32768,    29,
    30,-32768,-32768,-32768,-32768,    31,-32768,    31,-32768,    15,
-32768,     6,-32768,-32768,-32768,-32768,-32768,    21,    23,    -2,
-32768,    32,    24,-32768,-32768,-32768,-32768,-32768,-32768,-32768,
-32768,    31,-32768,-32768,    42,    43,-32768
};

static const short yypgoto[] = {-32768,
     4,-32768,-32768,-32768,-32768,    25,    33,-32768,-32768,     7,
-32768,   -36,-32768,-32768,-32768,-32768,     8,    11,-32768,-32768,
    10,-32768,    14,    16,-32768,-32768,-32768
};

#define YYLAST          56

static const short yytable[] = {    51,
     5,    51,     9,    10,    11,   -41,   -25,    12,    13,    60,
    32,    38,    40,    61,     9,    10,    11,     7,    38,    12,
    13,     1,    12,    53,     2,    64,    29,    30,    34,    31,
    43,    44,    36,    40,   -42,    30,    59,    46,    47,    48,
    31,    66,    67,    37,    52,    63,    33,     0,     0,    57,
    54,    58,     0,    55,     0,    56
};

static const short yycheck[] = {    36,
    10,    38,     3,     4,     5,     7,     9,     8,     9,    12,
    11,    13,     7,    16,     3,     4,     5,     9,    13,     8,
     9,     3,     8,     9,     6,    62,     9,    15,    12,    17,
    27,    28,    13,     7,     7,    15,    14,     9,     9,     9,
    17,     0,     0,    19,    38,    14,    14,    -1,    -1,    42,
    40,    42,    -1,    40,    -1,    40
};
#define YYPURE 1

/* -*-C-*-  Note some compilers choke on comments on `#line' lines.  */

/* This file comes from bison-1.28.  */

/* Skeleton output parser for bison,
   Copyright (C) 1984, 1989, 1990 Free Software Foundation, Inc.

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

/* As a special exception, when this file is copied by Bison into a
   Bison output file, you may use that output file without restriction.
   This special exception was added by the Free Software Foundation
   in version 1.24 of Bison.  */

/* This is the parser code that is written into each bison parser
  when the %semantic_parser declaration is not specified in the grammar.
  It was written by Richard Stallman by simplifying the hairy parser
  used when %semantic_parser is specified.  */

#ifndef YYSTACK_USE_ALLOCA
#ifdef alloca
#define YYSTACK_USE_ALLOCA
#else /* alloca not defined */
#ifdef __GNUC__
#define YYSTACK_USE_ALLOCA
#define alloca __builtin_alloca
#else /* not GNU C.  */
#if (!defined (__STDC__) && defined (sparc)) || defined (__sparc__) || defined (__sparc) || defined (__sgi) || (defined (__sun) && defined (__i386))
#define YYSTACK_USE_ALLOCA
#include <alloca.h>
#else /* not sparc */
/* We think this test detects Watcom and Microsoft C.  */
/* This used to test MSDOS, but that is a bad idea
   since that symbol is in the user namespace.  */
#if (defined (_MSDOS) || defined (_MSDOS_)) && !defined (__TURBOC__)
#if 0 /* No need for malloc.h, which pollutes the namespace;
         instead, just don't use alloca.  */
#include <malloc.h>
#endif
#else /* not MSDOS, or __TURBOC__ */
#if defined(_AIX)
/* I don't know what this was needed for, but it pollutes the namespace.
   So I turned it off.   rms, 2 May 1997.  */
/* #include <malloc.h>  */
 #pragma alloca
#define YYSTACK_USE_ALLOCA
#else /* not MSDOS, or __TURBOC__, or _AIX */
#if 0
#ifdef __hpux /* haible@ilog.fr says this works for HPUX 9.05 and up,
                 and on HPUX 10.  Eventually we can turn this on.  */
#define YYSTACK_USE_ALLOCA
#define alloca __builtin_alloca
#endif /* __hpux */
#endif
#endif /* not _AIX */
#endif /* not MSDOS, or __TURBOC__ */
#endif /* not sparc */
#endif /* not GNU C */
#endif /* alloca not defined */
#endif /* YYSTACK_USE_ALLOCA not defined */

#ifdef YYSTACK_USE_ALLOCA
#define YYSTACK_ALLOC alloca
#else
#define YYSTACK_ALLOC malloc
#endif

/* Note: there must be only one dollar sign in this file.
   It is replaced by the list of actions, each action
   as one case of the switch.  */

#define yyerrok         (yyerrstatus = 0)
#define yyclearin       (yychar = YYEMPTY)
#define YYEMPTY         -2
#define YYEOF           0
#define YYACCEPT        goto yyacceptlab
#define YYABORT         goto yyabortlab
#define YYERROR         goto yyerrlab1
/* Like YYERROR except do call yyerror.
   This remains here temporarily to ease the
   transition to the new meaning of YYERROR, for GCC.
   Once GCC version 2 has supplanted version 1, this can go.  */
#define YYFAIL          goto yyerrlab
#define YYRECOVERING()  (!!yyerrstatus)
#define YYBACKUP(token, value) \
do                                                              \
  if (yychar == YYEMPTY && yylen == 1)                          \
    { yychar = (token), yylval = (value);                       \
      yychar1 = YYTRANSLATE (yychar);                           \
      YYPOPSTACK;                                               \
      goto yybackup;                                            \
    }                                                           \
  else                                                          \
    { yyerror ("syntax error: cannot back up"); YYERROR; }      \
while (0)

#define YYTERROR        1
#define YYERRCODE       256

#ifndef YYPURE
#define YYLEX           yylex()
#endif

#ifdef YYPURE
#ifdef YYLSP_NEEDED
#ifdef YYLEX_PARAM
#define YYLEX           yylex(&yylval, &yylloc, YYLEX_PARAM)
#else
#define YYLEX           yylex(&yylval, &yylloc)
#endif
#else /* not YYLSP_NEEDED */
#ifdef YYLEX_PARAM
#define YYLEX           yylex(&yylval, YYLEX_PARAM)
#else
#define YYLEX           yylex(&yylval)
#endif
#endif /* not YYLSP_NEEDED */
#endif

/* If nonreentrant, generate the variables here */

#ifndef YYPURE

int     yychar;                 /*  the lookahead symbol                */
YYSTYPE yylval;                 /*  the semantic value of the           */
                                /*  lookahead symbol                    */

#ifdef YYLSP_NEEDED
YYLTYPE yylloc;                 /*  location data for the lookahead     */
                                /*  symbol                              */
#endif

int yynerrs;                    /*  number of parse errors so far       */
#endif  /* not YYPURE */

#if YYDEBUG != 0
int yydebug;                    /*  nonzero means print parse trace     */
/* Since this is uninitialized, it does not stop multiple parsers
   from coexisting.  */
#endif

/*  YYINITDEPTH indicates the initial size of the parser's stacks       */

#ifndef YYINITDEPTH
#define YYINITDEPTH 200
#endif

/*  YYMAXDEPTH is the maximum size the stacks can grow to
    (effective only if the built-in stack extension method is used).  */

#if YYMAXDEPTH == 0
#undef YYMAXDEPTH
#endif

#ifndef YYMAXDEPTH
#define YYMAXDEPTH 10000
#endif

/* Define __yy_memcpy.  Note that the size argument
   should be passed with type unsigned int, because that is what the non-GCC
   definitions require.  With GCC, __builtin_memcpy takes an arg
   of type size_t, but it can handle unsigned int.  */

#if __GNUC__ > 1                /* GNU C and GNU C++ define this.  */
#define __yy_memcpy(TO,FROM,COUNT)      __builtin_memcpy(TO,FROM,COUNT)
#else                           /* not GNU C or C++ */
#ifndef __cplusplus

/* This is the most reliable way to avoid incompatibilities
   in available built-in functions on various systems.  */
static void
__yy_memcpy (to, from, count)
     char *to;
     char *from;
     unsigned int count;
{
  register char *f = from;
  register char *t = to;
  register int i = count;

  while (i-- > 0)
    *t++ = *f++;
}

#else /* __cplusplus */

/* This is the most reliable way to avoid incompatibilities
   in available built-in functions on various systems.  */
static void
__yy_memcpy (char *to, char *from, unsigned int count)
{
  register char *t = to;
  register char *f = from;
  register int i = count;

  while (i-- > 0)
    *t++ = *f++;
}

#endif
#endif

/* The user can define YYPARSE_PARAM as the name of an argument to be passed
   into yyparse.  The argument should have type void *.
   It should actually point to an object.
   Grammar actions can access the variable by casting it
   to the proper pointer type.  */

#ifdef YYPARSE_PARAM
#ifdef __cplusplus
#define YYPARSE_PARAM_ARG void *YYPARSE_PARAM
#define YYPARSE_PARAM_DECL
#else /* not __cplusplus */
#define YYPARSE_PARAM_ARG YYPARSE_PARAM
#define YYPARSE_PARAM_DECL void *YYPARSE_PARAM;
#endif /* not __cplusplus */
#else /* not YYPARSE_PARAM */
#define YYPARSE_PARAM_ARG
#define YYPARSE_PARAM_DECL
#endif /* not YYPARSE_PARAM */

/* Prevent warning if -Wstrict-prototypes.  */
#ifdef __GNUC__
#ifdef YYPARSE_PARAM
int yyparse (void *);
#else
int yyparse (void);
#endif
#endif

int
yyparse(YYPARSE_PARAM_ARG)
     YYPARSE_PARAM_DECL
{
  register int yystate;
  register int yyn;
  register short *yyssp;
  register YYSTYPE *yyvsp;
  int yyerrstatus;      /*  number of tokens to shift before error messages enabled */
  int yychar1 = 0;              /*  lookahead token as an internal (translated) token number */

  short yyssa[YYINITDEPTH];     /*  the state stack                     */
  YYSTYPE yyvsa[YYINITDEPTH];   /*  the semantic value stack            */

  short *yyss = yyssa;          /*  refer to the stacks thru separate pointers */
  YYSTYPE *yyvs = yyvsa;        /*  to allow yyoverflow to reallocate them elsewhere */

#ifdef YYLSP_NEEDED
  YYLTYPE yylsa[YYINITDEPTH];   /*  the location stack                  */
  YYLTYPE *yyls = yylsa;
  YYLTYPE *yylsp;

#define YYPOPSTACK   (yyvsp--, yyssp--, yylsp--)
#else
#define YYPOPSTACK   (yyvsp--, yyssp--)
#endif

  int yystacksize = YYINITDEPTH;
  int yyfree_stacks = 0;

#ifdef YYPURE
  int yychar;
  YYSTYPE yylval;
  int yynerrs;
#ifdef YYLSP_NEEDED
  YYLTYPE yylloc;
#endif
#endif

  YYSTYPE yyval;                /*  the variable used to return         */
                                /*  semantic values from the action     */
                                /*  routines                            */

  int yylen;

#if YYDEBUG != 0
  if (yydebug)
    fprintf(stderr, "Starting parse\n");
#endif

  yystate = 0;
  yyerrstatus = 0;
  yynerrs = 0;
  yychar = YYEMPTY;             /* Cause a token to be read.  */

  /* Initialize stack pointers.
     Waste one element of value and location stack
     so that they stay on the same level as the state stack.
     The wasted elements are never initialized.  */

  yyssp = yyss - 1;
  yyvsp = yyvs;
#ifdef YYLSP_NEEDED
  yylsp = yyls;
#endif

/* Push a new state, which is found in  yystate  .  */
/* In all cases, when you get here, the value and location stacks
   have just been pushed. so pushing a state here evens the stacks.  */
yynewstate:

  *++yyssp = yystate;

  if (yyssp >= yyss + yystacksize - 1)
    {
      /* Give user a chance to reallocate the stack */
      /* Use copies of these so that the &'s don't force the real ones into memory. */
      YYSTYPE *yyvs1 = yyvs;
      short *yyss1 = yyss;
#ifdef YYLSP_NEEDED
      YYLTYPE *yyls1 = yyls;
#endif

      /* Get the current used size of the three stacks, in elements.  */
      int size = yyssp - yyss + 1;

#ifdef yyoverflow
      /* Each stack pointer address is followed by the size of
         the data in use in that stack, in bytes.  */
#ifdef YYLSP_NEEDED
      /* This used to be a conditional around just the two extra args,
         but that might be undefined if yyoverflow is a macro.  */
      yyoverflow("parser stack overflow",
                 &yyss1, size * sizeof (*yyssp),
                 &yyvs1, size * sizeof (*yyvsp),
                 &yyls1, size * sizeof (*yylsp),
                 &yystacksize);
#else
      yyoverflow("parser stack overflow",
                 &yyss1, size * sizeof (*yyssp),
                 &yyvs1, size * sizeof (*yyvsp),
                 &yystacksize);
#endif

      yyss = yyss1; yyvs = yyvs1;
#ifdef YYLSP_NEEDED
      yyls = yyls1;
#endif
#else /* no yyoverflow */
      /* Extend the stack our own way.  */
      if (yystacksize >= YYMAXDEPTH)
        {
          yyerror("parser stack overflow");
          if (yyfree_stacks)
            {
              free (yyss);
              free (yyvs);
#ifdef YYLSP_NEEDED
              free (yyls);
#endif
            }
          return 2;
        }
      yystacksize *= 2;
      if (yystacksize > YYMAXDEPTH)
        yystacksize = YYMAXDEPTH;
#ifndef YYSTACK_USE_ALLOCA
      yyfree_stacks = 1;
#endif
      yyss = (short *) YYSTACK_ALLOC (yystacksize * sizeof (*yyssp));
      __yy_memcpy ((char *)yyss, (char *)yyss1,
                   size * (unsigned int) sizeof (*yyssp));
      yyvs = (YYSTYPE *) YYSTACK_ALLOC (yystacksize * sizeof (*yyvsp));
      __yy_memcpy ((char *)yyvs, (char *)yyvs1,
                   size * (unsigned int) sizeof (*yyvsp));
#ifdef YYLSP_NEEDED
      yyls = (YYLTYPE *) YYSTACK_ALLOC (yystacksize * sizeof (*yylsp));
      __yy_memcpy ((char *)yyls, (char *)yyls1,
                   size * (unsigned int) sizeof (*yylsp));
#endif
#endif /* no yyoverflow */

      yyssp = yyss + size - 1;
      yyvsp = yyvs + size - 1;
#ifdef YYLSP_NEEDED
      yylsp = yyls + size - 1;
#endif

#if YYDEBUG != 0
      if (yydebug)
        fprintf(stderr, "Stack size increased to %d\n", yystacksize);
#endif

      if (yyssp >= yyss + yystacksize - 1)
        YYABORT;
    }

#if YYDEBUG != 0
  if (yydebug)
    fprintf(stderr, "Entering state %d\n", yystate);
#endif

  goto yybackup;
 yybackup:

/* Do appropriate processing given the current state.  */
/* Read a lookahead token if we need one and don't already have one.  */
/* yyresume: */

  /* First try to decide what to do without reference to lookahead token.  */

  yyn = yypact[yystate];
  if (yyn == YYFLAG)
    goto yydefault;

  /* Not known => get a lookahead token if don't already have one.  */

  /* yychar is either YYEMPTY or YYEOF
     or a valid token in external form.  */

  if (yychar == YYEMPTY)
    {
#if YYDEBUG != 0
      if (yydebug)
        fprintf(stderr, "Reading a token: ");
#endif
      yychar = YYLEX;
    }

  /* Convert token to internal form (in yychar1) for indexing tables with */

  if (yychar <= 0)              /* This means end of input. */
    {
      yychar1 = 0;
      yychar = YYEOF;           /* Don't call YYLEX any more */

#if YYDEBUG != 0
      if (yydebug)
        fprintf(stderr, "Now at end of input.\n");
#endif
    }
  else
    {
      yychar1 = YYTRANSLATE(yychar);

#if YYDEBUG != 0
      if (yydebug)
        {
          fprintf (stderr, "Next token is %d (%s", yychar, yytname[yychar1]);
          /* Give the individual parser a way to print the precise meaning
             of a token, for further debugging info.  */
#ifdef YYPRINT
          YYPRINT (stderr, yychar, yylval);
#endif
          fprintf (stderr, ")\n");
        }
#endif
    }

  yyn += yychar1;
  if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1)
    goto yydefault;

  yyn = yytable[yyn];

  /* yyn is what to do for this token type in this state.
     Negative => reduce, -yyn is rule number.
     Positive => shift, yyn is new state.
       New state is final state => don't bother to shift,
       just return success.
     0, or most negative number => error.  */

  if (yyn < 0)
    {
      if (yyn == YYFLAG)
        goto yyerrlab;
      yyn = -yyn;
      goto yyreduce;
    }
  else if (yyn == 0)
    goto yyerrlab;

  if (yyn == YYFINAL)
    YYACCEPT;

  /* Shift the lookahead token.  */

#if YYDEBUG != 0
  if (yydebug)
    fprintf(stderr, "Shifting token %d (%s), ", yychar, yytname[yychar1]);
#endif

  /* Discard the token being shifted unless it is eof.  */
  if (yychar != YYEOF)
    yychar = YYEMPTY;

  *++yyvsp = yylval;
#ifdef YYLSP_NEEDED
  *++yylsp = yylloc;
#endif

  /* count tokens shifted since error; after three, turn off error status.  */
  if (yyerrstatus) yyerrstatus--;

  yystate = yyn;
  goto yynewstate;

/* Do the default action for the current state.  */
yydefault:

  yyn = yydefact[yystate];
  if (yyn == 0)
    goto yyerrlab;

/* Do a reduction.  yyn is the number of a rule to reduce with.  */
yyreduce:
  yylen = yyr2[yyn];
  if (yylen > 0)
    yyval = yyvsp[1-yylen]; /* implement default value of the action */

#if YYDEBUG != 0
  if (yydebug)
    {
      int i;

      fprintf (stderr, "Reducing via rule %d (line %d), ",
               yyn, yyrline[yyn]);

      /* Print the symbols being reduced, and their result.  */
      for (i = yyprhs[yyn]; yyrhs[i] > 0; i++)
        fprintf (stderr, "%s ", yytname[yyrhs[i]]);
      fprintf (stderr, " -> %s\n", yytname[yyr1[yyn]]);
    }
#endif

  switch (yyn) {

case 2:
{yyval.i=0;;
    break;}
case 3:
{
    graphviz::vlist.clear();
    graphviz::attributes.clear();
    graphviz::subgraphs.clear();
    graphviz::nodes.clear();
    std::string* name = static_cast<std::string*>(yyvsp[0].ptr);
    graphviz::previous_graph = static_cast<graphviz::Subgraph*>(g);
    graphviz::current_graph = static_cast<graphviz::Subgraph*>(g);
    graphviz::set_graph_name(*name);
    delete name;
  ;
    break;}
case 6:
{yyval.ptr = yyvsp[0].ptr; ;
    break;}
case 7:
{yyval.ptr=(void*)(new std::string("G")); ;
    break;}
case 14:
{
    graphviz::set_attribute(*graphviz::current_graph,
                          graphviz::attribute_state);
  ;
    break;}
case 15:
{ graphviz::attribute_state = GRAPH_GRAPH_A; ;
    break;}
case 16:
{ graphviz::attribute_state = GRAPH_NODE_A; ;
    break;}
case 17:
{ graphviz::attribute_state = GRAPH_EDGE_A; ;
    break;}
case 19:
{;
    break;}
case 22:
{
    std::string* name  = static_cast<std::string*>(yyvsp[-2].ptr);
    std::string* value = static_cast<std::string*>(yyvsp[0].ptr);
    graphviz::attributes[*name] = *value;
    delete name;
    delete value;
  ;
    break;}
case 29:
{ yyval.i = 0; ;
    break;}
case 30:
{
    graphviz::set_attribute(
         *static_cast<graphviz::Subgraph*>(graphviz::current_graph),
                            GRAPH_GRAPH_A);
  ;
    break;}
case 31:
{
    graphviz::Vertex* temp   = static_cast<graphviz::Vertex*>(yyvsp[-1].ptr);
    graphviz::current_vertex = *temp;
    graphviz::set_attribute(*static_cast<GRAPHVIZ_GRAPH*>(YYPARSE_PARAM),
                            NODE_A);
    delete temp;
    yyval.i = 0;
  ;
    break;}
case 32:
{ yyval.i=0; ;
    break;}
case 33:
{ yyval.i=0; ;
    break;}
case 34:
{
    std::string* name  = static_cast<std::string*>(yyvsp[0].ptr);
    std::pair<graphviz::Iter, bool> result = graphviz::lookup(*name);
    if (result.second) {
      graphviz::current_vertex = result.first->second;
      if (! graphviz::current_graph->is_root())
        boost::add_vertex(graphviz::current_vertex, *graphviz::current_graph);
    } else
      graphviz::current_vertex = graphviz::add_name(*name, *static_cast<GRAPHVIZ_GRAPH*>(YYPARSE_PARAM)) ;
    graphviz::Vertex* temp = new graphviz::Vertex(graphviz::current_vertex);
    yyval.ptr = (void *)temp;
    graphviz::attribute_state = NODE_A;
    delete name;
  ;
    break;}
case 35:
{ yyval.ptr=yyvsp[0].ptr; ;
    break;}
case 36:
{
    //consider port as a special properties ?? --need work here
    std::string* name = static_cast<std::string*>(yyvsp[-2].ptr);
    std::string* port = static_cast<std::string*>(yyvsp[0].ptr);

    std::pair<graphviz::Iter, bool> result = graphviz::lookup(*name);
    if (result.second)
      graphviz::current_vertex = result.first->second;
    else
      graphviz::current_vertex = graphviz::add_name(*name, *static_cast<GRAPHVIZ_GRAPH*>(YYPARSE_PARAM)) ;
    graphviz::Vertex* temp = new graphviz::Vertex(graphviz::current_vertex);
    yyval.ptr = (void *)temp;
    graphviz::attribute_state = NODE_A;
    delete name;
    delete port;
  ;
    break;}
case 37:
{

    typedef std::pair<void*, bool>* Ptr;
    Ptr source = static_cast<Ptr>(yyvsp[-2].ptr);

    for (std::vector<Ptr>::iterator it=graphviz::vlist.begin();
         it !=graphviz::vlist.end(); ++it) {
      if ( source->second ) {
        if ( (*it)->second )
          graphviz::add_edges(static_cast<graphviz::Subgraph*>(source->first),
                            static_cast<graphviz::Subgraph*>((*it)->first),
                            *static_cast<GRAPHVIZ_GRAPH*>(YYPARSE_PARAM));
        else
          graphviz::add_edges(static_cast<graphviz::Subgraph*>(source->first),
                            *static_cast<graphviz::Vertex*>((*it)->first),
                            *static_cast<GRAPHVIZ_GRAPH*>(YYPARSE_PARAM));
      } else {
        graphviz::Vertex* temp = static_cast<graphviz::Vertex*>(source->first);
        if ( (*it)->second )
          graphviz::add_edges(*temp,
                            static_cast<graphviz::Subgraph*>((*it)->first),
                            *static_cast<GRAPHVIZ_GRAPH*>(YYPARSE_PARAM));
        else
          graphviz::add_edges(*temp,
                            *static_cast<graphviz::Vertex*>((*it)->first),
                            *static_cast<GRAPHVIZ_GRAPH*>(YYPARSE_PARAM));
        delete temp;
      }

      delete source;
      source = *it;
    }

    if ( ! source->second ) {
      graphviz::Vertex* temp = static_cast<graphviz::Vertex*>(source->first);
      delete temp;
    }
    delete source;

    graphviz::attributes.clear();
    graphviz::vlist.clear();
  ;
    break;}
case 38:
{ graphviz::vlist.push_back(static_cast<std::pair<void*, bool>*>(yyvsp[0].ptr)); ;
    break;}
case 41:
{
    std::pair<void*, bool>* temp = new std::pair<void*, bool>;
    temp->first = yyvsp[0].ptr;
    temp->second = false;
    yyval.ptr = (void*)temp;

    graphviz::attribute_state = EDGE_A;
  ;
    break;}
case 42:
{
    std::pair<void*, bool>* temp = new std::pair<void*, bool>;
    temp->first = yyvsp[0].ptr;
    temp->second = true;
    yyval.ptr = (void*)temp;

    graphviz::attribute_state = EDGE_A;
  ;
    break;}
case 43:
{
    if ( yyvsp[0].i )
      graphviz::current_graph = &graphviz::current_graph->parent();
    else
      graphviz::current_graph = graphviz::previous_graph;
  ;
    break;}
case 44:
{
    graphviz::previous_graph = graphviz::current_graph;
    std::string name = graphviz::random_string();
    graphviz::Subgraph* temp = graphviz::create_subgraph(name);
    graphviz::current_graph = temp;
    graphviz::set_graph_name(name);

    yyval.ptr = (void *) graphviz::current_graph;
  ;
    break;}
case 45:
{
    graphviz::current_graph = &graphviz::current_graph->parent();
  ;
    break;}
case 46:
{
    //lookup ID_T if it is already in the subgraph,
    //if it is not, add a new subgraph
    std::string* name  = static_cast<std::string*>(yyvsp[0].ptr);

    std::pair<graphviz::It, bool> temp = graphviz::lookup_subgraph(*name);

    graphviz::previous_graph = graphviz::current_graph;
    if ( temp.second )  {//found
      graphviz::current_graph = (temp.first)->second;
    } else {
      graphviz::current_graph = graphviz::create_subgraph(*name);
      graphviz::set_graph_name(*name);
    }

    yyval.ptr = (void *) graphviz::current_graph;
    delete name;
  ;
    break;}
case 47:
{yyval.i = 1; ;
    break;}
case 48:
{ yyval.i = 0; ;
    break;}
}
   /* the action file gets copied in in place of this dollarsign */

  yyvsp -= yylen;
  yyssp -= yylen;
#ifdef YYLSP_NEEDED
  yylsp -= yylen;
#endif

#if YYDEBUG != 0
  if (yydebug)
    {
      short *ssp1 = yyss - 1;
      fprintf (stderr, "state stack now");
      while (ssp1 != yyssp)
        fprintf (stderr, " %d", *++ssp1);
      fprintf (stderr, "\n");
    }
#endif

  *++yyvsp = yyval;

#ifdef YYLSP_NEEDED
  yylsp++;
  if (yylen == 0)
    {
      yylsp->first_line = yylloc.first_line;
      yylsp->first_column = yylloc.first_column;
      yylsp->last_line = (yylsp-1)->last_line;
      yylsp->last_column = (yylsp-1)->last_column;
      yylsp->text = 0;
    }
  else
    {
      yylsp->last_line = (yylsp+yylen-1)->last_line;
      yylsp->last_column = (yylsp+yylen-1)->last_column;
    }
#endif

  /* Now "shift" the result of the reduction.
     Determine what state that goes to,
     based on the state we popped back to
     and the rule number reduced by.  */

  yyn = yyr1[yyn];

  yystate = yypgoto[yyn - YYNTBASE] + *yyssp;
  if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp)
    yystate = yytable[yystate];
  else
    yystate = yydefgoto[yyn - YYNTBASE];

  goto yynewstate;

yyerrlab:   /* here on detecting error */

  if (! yyerrstatus)
    /* If not already recovering from an error, report this error.  */
    {
      ++yynerrs;

#ifdef YYERROR_VERBOSE
      yyn = yypact[yystate];

      if (yyn > YYFLAG && yyn < YYLAST)
        {
          int size = 0;
          char *msg;
          int x, count;

          count = 0;
          /* Start X at -yyn if nec to avoid negative indexes in yycheck.  */
          for (x = (yyn < 0 ? -yyn : 0);
               x < (sizeof(yytname) / sizeof(char *)); x++)
            if (yycheck[x + yyn] == x)
              size += strlen(yytname[x]) + 15, count++;
          msg = (char *) malloc(size + 15);
          if (msg != 0)
            {
              strcpy(msg, "parse error");

              if (count < 5)
                {
                  count = 0;
                  for (x = (yyn < 0 ? -yyn : 0);
                       x < (sizeof(yytname) / sizeof(char *)); x++)
                    if (yycheck[x + yyn] == x)
                      {
                        strcat(msg, count == 0 ? ", expecting `" : " or `");
                        strcat(msg, yytname[x]);
                        strcat(msg, "'");
                        count++;
                      }
                }
              yyerror(msg);
              free(msg);
            }
          else
            yyerror ("parse error; also virtual memory exceeded");
        }
      else
#endif /* YYERROR_VERBOSE */
        yyerror("parse error");
    }

  goto yyerrlab1;
yyerrlab1:   /* here on error raised explicitly by an action */

  if (yyerrstatus == 3)
    {
      /* if just tried and failed to reuse lookahead token after an error, discard it.  */

      /* return failure if at end of input */
      if (yychar == YYEOF)
        YYABORT;

#if YYDEBUG != 0
      if (yydebug)
        fprintf(stderr, "Discarding token %d (%s).\n", yychar, yytname[yychar1]);
#endif

      yychar = YYEMPTY;
    }

  /* Else will try to reuse lookahead token
     after shifting the error token.  */

  yyerrstatus = 3;              /* Each real token shifted decrements this */

  goto yyerrhandle;

yyerrdefault:  /* current state does not do anything special for the error token. */

#if 0
  /* This is wrong; only states that explicitly want error tokens
     should shift them.  */
  yyn = yydefact[yystate];  /* If its default is to accept any token, ok.  Otherwise pop it.*/
  if (yyn) goto yydefault;
#endif

yyerrpop:   /* pop the current state because it cannot handle the error token */

  if (yyssp == yyss) YYABORT;
  yyvsp--;
  yystate = *--yyssp;
#ifdef YYLSP_NEEDED
  yylsp--;
#endif

#if YYDEBUG != 0
  if (yydebug)
    {
      short *ssp1 = yyss - 1;
      fprintf (stderr, "Error: state stack now");
      while (ssp1 != yyssp)
        fprintf (stderr, " %d", *++ssp1);
      fprintf (stderr, "\n");
    }
#endif

yyerrhandle:

  yyn = yypact[yystate];
  if (yyn == YYFLAG)
    goto yyerrdefault;

  yyn += YYTERROR;
  if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR)
    goto yyerrdefault;

  yyn = yytable[yyn];
  if (yyn < 0)
    {
      if (yyn == YYFLAG)
        goto yyerrpop;
      yyn = -yyn;
      goto yyreduce;
    }
  else if (yyn == 0)
    goto yyerrpop;

  if (yyn == YYFINAL)
    YYACCEPT;

#if YYDEBUG != 0
  if (yydebug)
    fprintf(stderr, "Shifting error token, ");
#endif

  *++yyvsp = yylval;
#ifdef YYLSP_NEEDED
  *++yylsp = yylloc;
#endif

  yystate = yyn;
  goto yynewstate;

 yyacceptlab:
  /* YYACCEPT comes here.  */
  if (yyfree_stacks)
    {
      free (yyss);
      free (yyvs);
#ifdef YYLSP_NEEDED
      free (yyls);
#endif
    }
  return 0;

 yyabortlab:
  /* YYABORT comes here.  */
  if (yyfree_stacks)
    {
      free (yyss);
      free (yyvs);
#ifdef YYLSP_NEEDED
      free (yyls);
#endif
    }
  return 1;
}

namespace boost {

  void read_graphviz(const std::string& filename, GRAPHVIZ_GRAPH& g) {
    FILE* file = fopen(filename.c_str(), "r");
    yyrestart(file);
    void* in = static_cast<void*>(file);
    yyparse(static_cast<void*>(&g));
  }

  void read_graphviz(FILE* file, GRAPHVIZ_GRAPH& g) {
    void* in = static_cast<void*>(file);
    yyrestart(file);
    yyparse(static_cast<void*>(&g));
  }

}

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM


text:
#ifndef VIENNAUTILS_EXCEPTION_HPP
#define VIENNAUTILS_EXCEPTION_HPP

#include <stdexcept>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/utility/enable_if.hpp>

namespace viennautils
{

struct exception : virtual std::exception
{
public:
  virtual ~exception() throw() {}

  virtual char const* what() const throw()
  {
      return what_.c_str();
  }

  void set_what(std::string const & str)
  {
    what_ = str;
  }

private:
  std::string what_;
};

template <typename T>
typename boost::enable_if<boost::is_base_of<exception, T>, T>::type make_exception(std::string const & str)
{
  T e;
  e.set_what(str);
  return e;
}

} //end of namespace viennautils

#endif

max_stars_repo_name: viennautils/viennautils-dev

max_issues_repo_name: viennautils/viennautils-dev

max_forks_repo_name: viennautils/viennautils-dev


text:
/*!
@file
Defines an equivalent to `std::is_floating_point`.

@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_DETAIL_STD_IS_FLOATING_POINT_HPP
#define BOOST_HANA_DETAIL_STD_IS_FLOATING_POINT_HPP

#include <boost/hana/detail/std/integral_constant.hpp>

namespace boost { namespace hana { namespace detail { namespace std {
    template <typename T> struct is_floating_point : false_type { };
    template <typename T> struct is_floating_point<T const> : is_floating_point<T> { };
    template <typename T> struct is_floating_point<T volatile> : is_floating_point<T> { };
    template <typename T> struct is_floating_point<T const volatile> : is_floating_point<T> { };
    template <> struct is_floating_point<float> : true_type { };
    template <> struct is_floating_point<double> : true_type { };
    template <> struct is_floating_point<long double> : true_type { };
}}}} // end namespace boost::hana::detail::std

#endif // !BOOST_HANA_DETAIL_STD_IS_FLOATING_POINT_HPP

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
#include "w_python_pch.h"
#include "w_python.h"

#ifndef BOOST_PYTHON_SOURCE
#define BOOST_PYTHON_STATIC_LIB
#endif
#include <boost/python.hpp>

using namespace std;
using namespace wolf::system;
using namespace boost::python;

void w_python::initialize()
{
	Py_Initialize();
}

HRESULT w_python::run(std::string pScriptText)
{
	//create main python module
	object main_module(handle<>(borrowed(PyImport_AddModule("__main__"))));
	//create main namespace as dictionary
	boost::python::object _main_namespace = main_module.attr("__dict__");

	auto _hr = S_OK;
	handle<>* _handle_script = nullptr;

	try
	{
		_handle_script = new handle<>((PyRun_String(
			pScriptText.c_str(),
			Py_file_input,
			_main_namespace.ptr(),
			_main_namespace.ptr())));
	}
	catch (error_already_set&)
	{
		_hr = S_FALSE;
		V(_hr, _fetch_error(), this->name, 3);
	}
	if (_handle_script)
	{
		_handle_script->release();
		_handle_script = nullptr;
	}

	return _hr;
}

const std::wstring w_python::_fetch_error()
{
	PyObject* _type;
	PyObject* _value;
	PyObject* _traceback;

	PyErr_Fetch(&_type, &_value, &_traceback);

	handle<> _handle_type(_type);
	object extype(_handle_type);

	if (!_traceback)
	{
		auto _error_msg = L"Unknown";
		this->_log += _error_msg;
		return _error_msg;
	}
	handle<> _handle_traceback(_traceback);
	object traceback(_handle_traceback);

	//Extract error message
	wstring _str_error_message = extract<wstring>(_value);

	//	Extract line number (top entry of call stack)
	//	if you want to extract another levels of call stack
	//	also process traceback.attr("tb_next") recurently
	long _line_number = extract<long>(traceback.attr("tb_lineno"));
	wstring _func_name = extract<wstring>(traceback.attr("tb_frame").attr("f_code").attr("co_name"));
	wstring _file_name = extract<wstring>(traceback.attr("tb_frame").attr("f_code").attr("co_filename"));

	auto _error_msg = L"\r\nTraceback(most recent call last) :\r\n"
		"File \"" + _file_name + L"\", line " + std::to_wstring(_line_number) + L", in " + _func_name + L"\r\nNameError : " + _str_error_message;
	this->_log += _error_msg;

	logger.error(_error_msg);

	Py_DECREF(_type);
	Py_DECREF(_value);
	Py_DECREF(_traceback);

	return _error_msg;
}

ULONG w_python::release()
{
	if (_super::get_is_released()) return 0;

	_log.clear();
	Py_Finalize();

	return w_object::release();
}


text:
// Copyright (c) 2001 Ronald Garcia, Indiana University (garcia@osl.iu.edu)
// Andrew Lumsdaine, Indiana University (lums@osl.iu.edu).
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_UTF8_CODECVT_FACET_HPP
#define BOOST_UTF8_CODECVT_FACET_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// utf8_codecvt_facet.hpp

// This header defines class utf8_codecvt_facet, derived fro
// std::codecvt<wchar_t, char>, which can be used to convert utf8 data in
// files into wchar_t strings in the application.
//
// The header is NOT STANDALONE, and is not to be included by the USER.
// There are at least two libraries which want to use this functionality, and
// we want to avoid code duplication. It would be possible to create utf8
// library, but:
// - this requires review process first
// - in the case, when linking the a library which uses utf8
//   (say 'program_options'), user should also link to the utf8 library.
//   This seems inconvenient, and asking a user to link to an unrevieved
//   library is strange.
// Until the above points are fixed, a library which wants to use utf8 must:
// - include this header from one of it's headers or sources
// - include the corresponding .cpp file from one of the sources
// - before including either file, the library must define
//   - BOOST_UTF8_BEGIN_NAMESPACE to the namespace declaration that must be used
//   - BOOST_UTF8_END_NAMESPACE to the code to close the previous namespace
//   - declaration.
//   - BOOST_UTF8_DECL -- to the code which must be used for all 'exportable'
//     symbols.
//
// For example, program_options library might contain:
//    #define BOOST_UTF8_BEGIN_NAMESPACE <backslash character>
//             namespace boost { namespace program_options {
//    #define BOOST_UTF8_END_NAMESPACE }}
//    #define BOOST_UTF8_DECL BOOST_PROGRAM_OPTIONS_DECL
//    #include "../../detail/utf8/utf8_codecvt.cpp"
//
// Essentially, each library will have its own copy of utf8 code, in
// different namespaces.

// Note:(Robert Ramey).  I have made the following alterations in the original
// code.
// a) Rendered utf8_codecvt<wchar_t, char>  with using templates
// b) Move longer functions outside class definition to prevent inlining
// and make code smaller
// c) added on a derived class to permit translation to/from current
// locale to utf8

//  See http://www.boost.org for updates, documentation, and revision history.

// archives stored as text - note these ar templated on the basic
// stream templates to accommodate wide (and other?) kind of characters
//
// note the fact that on libraries without wide characters, ostream is
// is not a specialization of basic_ostream which in fact is not defined
// in such cases.   So we can't use basic_ostream<OStream::char_type> but rather
// use two template parameters
//
// utf8_codecvt_facet
//   This is an implementation of a std::codecvt facet for translating
//   from UTF-8 externally to UCS-4.  Note that this is not tied to
//   any specific types in order to allow customization on platforms
//   where wchar_t is not big enough.
//
// NOTES:  The current implementation jumps through some unpleasant hoops in
// order to deal with signed character types.  As a std::codecvt_base::result,
// it is necessary  for the ExternType to be convertible to unsigned  char.
// I chose not to tie the extern_type explicitly to char. But if any combination
// of types other than <wchar_t,char_t> is used, then std::codecvt must be
// specialized on those types for this to work.

#include <locale>
// for mbstate_t
#include <wchar.h>
// for std::size_t
#include <cstddef>

#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>

namespace std {
#if defined(__LIBCOMO__)
	using ::mbstate_t;
#elif defined(BOOST_DINKUMWARE_STDLIB) && !defined(__BORLANDC__)
	using ::mbstate_t;
#elif defined(__SGI_STL_PORT)
#elif defined(BOOST_NO_STDC_NAMESPACE)
	using ::mbstate_t;
	using ::codecvt;
#endif
} // namespace std

#if !defined(__MSL_CPP__) && !defined(__LIBCOMO__)
#define BOOST_CODECVT_DO_LENGTH_CONST const
#else
#define BOOST_CODECVT_DO_LENGTH_CONST
#endif

// maximum lenght of a multibyte string
#define MB_LENGTH_MAX 8

namespace {
	template<std::size_t s>
	int get_cont_octet_out_count_impl(wchar_t word){
		if (word < 0x80) {
			return 0;
		}
		if (word < 0x800) {
			return 1;
		}
		return 2;
	}

	// note the following code will generate on some platforms where
	// wchar_t is defined as UCS2.  The warnings are superfluous as
	// the specialization is never instantitiated with such compilers.
	template<>
	int get_cont_octet_out_count_impl<4>(wchar_t word){
		if (word < 0x80) {
			return 0;
		}
		if (word < 0x800) {
			return 1;
		}
		if (word < 0x10000) {
			return 2;
		}
		if (word < 0x200000) {
			return 3;
		}
		if (word < 0x4000000) {
			return 4;
		}
		return 5;
	}

} // namespace anonymous

BOOST_UTF8_BEGIN_NAMESPACE

struct BOOST_UTF8_DECL utf8_codecvt_facet :
	public std::codecvt<wchar_t, char, std::mbstate_t>
{
public:
	explicit utf8_codecvt_facet(std::size_t no_locale_manage=0)
		: std::codecvt<wchar_t, char, std::mbstate_t>(no_locale_manage)
	{}
protected:
	// Translate incoming UTF-8 into UCS-4
	virtual std::codecvt_base::result do_in(
		std::mbstate_t& /*state*/,
		const char * from,
		const char * from_end,
		const char * & from_next,
		wchar_t * to,
		wchar_t * to_end,
		wchar_t*& to_next
		) const {
			// Basic algorithm:  The first octet determines how many
			// octets total make up the UCS-4 character.  The remaining
			// "continuing octets" all begin with "10". To convert, subtract
			// the amount that specifies the number of octets from the first
			// octet.  Subtract 0x80 (1000 0000) from each continuing octet,
			// then mash the whole lot together.  Note that each continuing
			// octet only uses 6 bits as unique values, so only shift by
			// multiples of 6 to combine.
			while (from != from_end && to != to_end) {

				// Error checking   on the first octet
				if (invalid_leading_octet(*from)){
					from_next = from;
					to_next = to;
					return std::codecvt_base::error;
				}

				// The first octet is   adjusted by a value dependent upon
				// the number   of "continuing octets" encoding the character
				const   int cont_octet_count = get_cont_octet_count(*from);
				const   wchar_t octet1_modifier_table[] =   {
					0x00, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc
				};

				// The unsigned char conversion is necessary in case char is
				// signed   (I learned this the hard way)
				wchar_t ucs_result =
					(unsigned char)(*from++) - octet1_modifier_table[cont_octet_count];

				// Invariants   :
				//   1) At the start of the loop,   'i' continuing characters have been
				//    processed
				//   2) *from   points to the next continuing character to be processed.
				int i   = 0;
				while(i != cont_octet_count && from != from_end) {

					// Error checking on continuing characters
					if (invalid_continuing_octet(*from)) {
						from_next   = from;
						to_next =   to;
						return std::codecvt_base::error;
					}

					ucs_result *= (1 << 6);

					// each continuing character has an extra (10xxxxxx)b attached to
					// it that must be removed.
					ucs_result += (unsigned char)(*from++) - 0x80;
					++i;
				}

				// If   the buffer ends with an incomplete unicode character...
				if (from == from_end && i   != cont_octet_count) {
					// rewind "from" to before the current character translation
					from_next = from - (i+1);
					to_next = to;
					return std::codecvt_base::partial;
				}
				*to++   = ucs_result;
			}
			from_next = from;
			to_next = to;

			// Were we done converting or did we run out of destination space?
			if(from == from_end) return std::codecvt_base::ok;
			else return std::codecvt_base::partial;
	}

	virtual std::codecvt_base::result do_out(
		std::mbstate_t & /*state*/, const wchar_t * from,
		const wchar_t * from_end, const wchar_t*  & from_next,
		char * to, char * to_end, char * & to_next
		) const
	{
		// RG - consider merging this table with the other one
		const wchar_t octet1_modifier_table[] = {
			0x00, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc
		};

		wchar_t max_wchar = (std::numeric_limits<wchar_t>::max)();
		while (from != from_end && to != to_end) {

			// Check for invalid UCS-4 character
			if (*from  > max_wchar) {
				from_next = from;
				to_next = to;
				return std::codecvt_base::error;
			}

			int cont_octet_count = get_cont_octet_out_count(*from);

			// RG  - comment this formula better
			int shift_exponent = (cont_octet_count) *   6;

			// Process the first character
			*to++ = static_cast<char>(octet1_modifier_table[cont_octet_count] +
				(unsigned char)(*from / (1 << shift_exponent)));

			// Process the continuation characters
			// Invariants: At   the start of the loop:
			//   1) 'i' continuing octets   have been generated
			//   2) '*to'   points to the next location to place an octet
			//   3) shift_exponent is   6 more than needed for the next octet
			int i   = 0;
			while   (i != cont_octet_count && to != to_end) {
				shift_exponent -= 6;
				*to++ = static_cast<char>(0x80 + ((*from / (1 << shift_exponent)) % (1 << 6)));
				++i;
			}
			// If   we filled up the out buffer before encoding the character
			if(to   == to_end && i != cont_octet_count) {
				from_next = from;
				to_next = to - (i+1);
				return std::codecvt_base::partial;
			}
			*from++;
		}
		from_next = from;
		to_next = to;
		// Were we done or did we run out of destination space
		if(from == from_end) return std::codecvt_base::ok;
		else return std::codecvt_base::partial;
	}

	bool invalid_continuing_octet(unsigned char octet_1) const {
		return (octet_1 < 0x80|| 0xbf< octet_1);
	}

	bool invalid_leading_octet(unsigned char octet_1)   const {
		return (0x7f < octet_1 && octet_1 < 0xc0) ||
			(octet_1 > 0xfd);
	}

	// continuing octets = octets except for the leading octet
	static unsigned int get_cont_octet_count(unsigned   char lead_octet) {
		return get_octet_count(lead_octet) - 1;
	}

	static unsigned int get_octet_count(unsigned char   lead_octet)
	{
		// if the 0-bit (MSB) is 0, then 1 character
		if (lead_octet <= 0x7f) return 1;

		// Otherwise the count number of consecutive 1 bits starting at MSB
		//    assert(0xc0 <= lead_octet && lead_octet <= 0xfd);

		if (0xc0 <= lead_octet && lead_octet <= 0xdf) return 2;
		else if (0xe0 <= lead_octet && lead_octet <= 0xef) return 3;
		else if (0xf0 <= lead_octet && lead_octet <= 0xf7) return 4;
		else if (0xf8 <= lead_octet && lead_octet <= 0xfb) return 5;
		else return 6;
	}

	// How many "continuing octets" will be needed for this word
	// ==   total octets - 1.
	int get_cont_octet_out_count(wchar_t word) const
	{
		return get_cont_octet_out_count_impl<sizeof(wchar_t)>(word);
	}

	virtual bool do_always_noconv() const throw() { return false; }

	// UTF-8 isn't really stateful since we rewind on partial conversions
	virtual std::codecvt_base::result do_unshift(
		std::mbstate_t&,
		char * from,
		char * /*to*/,
		char * & next
		) const
	{
		next = from;
		return ok;
	}

	virtual int do_encoding() const throw() {
		const int variable_byte_external_encoding=0;
		return variable_byte_external_encoding;
	}

	// How many char objects can I process to get <= max_limit
	// wchar_t objects?
	virtual int do_length(
		BOOST_CODECVT_DO_LENGTH_CONST std::mbstate_t &,
		const char * from,
		const char * from_end,
		std::size_t max_limit
#if BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600))
		) const throw()
#else
		) const
#endif
	{
		// RG - this code is confusing!  I need a better way to express it.
		// and test cases.

		// Invariants:
		// 1) last_octet_count has the size of the last measured character
		// 2) char_count holds the number of characters shown to fit
		// within the bounds so far (no greater than max_limit)
		// 3) from_next points to the octet 'last_octet_count' before the
		// last measured character.
		int last_octet_count=0;
		std::size_t char_count = 0;
		const char* from_next = from;
		// Use "<" because the buffer may represent incomplete characters
		while (from_next+last_octet_count <= from_end && char_count <= max_limit) {
			from_next += last_octet_count;
			last_octet_count = (get_octet_count(*from_next));
			++char_count;
		}
		return static_cast<int>(from_next-from_end);
	}
	// Largest possible value do_length(state,from,from_end,1) could return.
	virtual int do_max_length() const throw () {
		return 6; // largest UTF-8 encoding of a UCS-4 character
	}
};

BOOST_UTF8_END_NAMESPACE

// BOOST_UTF8_CODECVT_FACET_HPP
#endif

max_stars_repo_name: dancefire/openclas

max_issues_repo_name: dancefire/openclas

max_forks_repo_name: dancefire/openclas


text:
//------------------------------------------------------------------------------
/*
    This file is part of validator-keys-tool:
        https://github.com/ripple/validator-keys-tool
    Copyright (c) 2016 Ripple Labs Inc.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include <ValidatorKeys.h>
#include <ripple/basics/base64.h>
#include <ripple/basics/StringUtilities.h>
#include <ripple/json/json_reader.h>
#include <ripple/json/to_string.h>
#include <ripple/protocol/HashPrefix.h>
#include <ripple/protocol/Sign.h>
#include <boost/algorithm/clamp.hpp>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <fstream>

namespace ripple {

std::string
ValidatorToken::toString () const
{
    Json::Value jv;
    jv["validation_secret_key"] = strHex(secretKey);
    jv["manifest"] = manifest;

    return ripple::base64_encode(to_string(jv));
}

ValidatorKeys::ValidatorKeys (KeyType const& keyType)
    : keyType_ (keyType)
    , tokenSequence_ (0)
    , revoked_ (false)
{
    std::tie (publicKey_, secretKey_) = generateKeyPair (
        keyType_, randomSeed ());
}

ValidatorKeys::ValidatorKeys (
    KeyType const& keyType,
    SecretKey const& secretKey,
    std::uint32_t tokenSequence,
    bool revoked)
    : keyType_ (keyType)
    , secretKey_ (secretKey)
    , tokenSequence_ (tokenSequence)
    , revoked_ (revoked)
{
    publicKey_ = derivePublicKey(keyType_, secretKey_);
}

ValidatorKeys
ValidatorKeys::make_ValidatorKeys (
    boost::filesystem::path const& keyFile)
{
    std::ifstream ifsKeys (keyFile.c_str (), std::ios::in);

    if (! ifsKeys)
        throw std::runtime_error (
            "Failed to open key file: " + keyFile.string());

    Json::Reader reader;
    Json::Value jKeys;
    if (! reader.parse (ifsKeys, jKeys))
    {
        throw std::runtime_error (
            "Unable to parse json key file: " + keyFile.string());
    }

    static std::array<std::string, 4> const requiredFields {{
        "key_type",
        "secret_key",
        "token_sequence",
        "revoked"
    }};

    for (auto field : requiredFields)
    {
        if (! jKeys.isMember(field))
        {
            throw std::runtime_error (
                "Key file '" + keyFile.string() +
                "' is missing \"" + field + "\" field");
        }
    }

    auto const keyType = keyTypeFromString (jKeys["key_type"].asString());
    if (!keyType)
    {
        throw std::runtime_error (
            "Key file '" + keyFile.string() +
            "' contains invalid \"key_type\" field: " +
            jKeys["key_type"].toStyledString());
    }

    auto const secret = parseBase58<SecretKey> (
        TokenType::NodePrivate, jKeys["secret_key"].asString());

    if (! secret)
    {
        throw std::runtime_error (
            "Key file '" + keyFile.string() +
            "' contains invalid \"secret_key\" field: " +
            jKeys["secret_key"].toStyledString());
    }

    std::uint32_t tokenSequence;
    try {
        if (! jKeys["token_sequence"].isIntegral())
            throw std::runtime_error ("");

        tokenSequence = jKeys["token_sequence"].asUInt();
    }
    catch (std::runtime_error&)
    {
        throw std::runtime_error (
            "Key file '" + keyFile.string() +
            "' contains invalid \"token_sequence\" field: " +
            jKeys["token_sequence"].toStyledString());
    }

    if (! jKeys["revoked"].isBool())
        throw std::runtime_error (
            "Key file '" + keyFile.string() +
            "' contains invalid \"revoked\" field: " +
            jKeys["revoked"].toStyledString());

    ValidatorKeys vk(
        *keyType, *secret, tokenSequence, jKeys["revoked"].asBool());

    if (jKeys.isMember("domain"))
    {
        if (! jKeys["domain"].isString())
            throw std::runtime_error (
                "Key file '" + keyFile.string() +
                "' contains invalid \"domain\" field: " +
                jKeys["domain"].toStyledString());

        vk.domain(jKeys["domain"].asString());
    }

    if (jKeys.isMember("manifest"))
    {
        if (! jKeys["manifest"].isString())
            throw std::runtime_error (
                "Key file '" + keyFile.string() +
                "' contains invalid \"manifest\" field: " +
                jKeys["manifest"].toStyledString());

        auto ret = strUnHex (jKeys["manifest"].asString());

        if (!ret || ret->size() == 0)
            throw std::runtime_error (
                "Key file '" + keyFile.string() +
                "' contains invalid \"manifest\" field: " +
                jKeys["manifest"].toStyledString());

        vk.manifest_.clear();
        vk.manifest_.reserve(ret->size());
        std::copy(ret->begin(), ret->end(),
            std::back_inserter(vk.manifest_));
    }

    return vk;
}

void
ValidatorKeys::writeToFile (
    boost::filesystem::path const& keyFile) const
{
    using namespace boost::filesystem;

    Json::Value jv;
    jv["key_type"] = to_string(keyType_);
    jv["public_key"] = toBase58(TokenType::NodePublic, publicKey_);
    jv["secret_key"] = toBase58(TokenType::NodePrivate, secretKey_);
    jv["secret_key_hex"] = strHex(secretKey_);
    jv["token_sequence"] = Json::UInt (tokenSequence_);
    jv["revoked"] = revoked_;
    if (!domain_.empty())
        jv["domain"] = domain_;
    if (!manifest_.empty())
        jv["manifest"] = strHex(makeSlice(manifest_));

    if (! keyFile.parent_path().empty())
    {
        boost::system::error_code ec;
        if (! exists (keyFile.parent_path()))
            boost::filesystem::create_directories(keyFile.parent_path(), ec);

        if (ec || ! is_directory (keyFile.parent_path()))
            throw std::runtime_error ("Cannot create directory: " +
                    keyFile.parent_path().string());
    }

    std::ofstream o (keyFile.string (), std::ios_base::trunc);
    if (o.fail())
        throw std::runtime_error ("Cannot open key file: " +
            keyFile.string());

    o << jv.toStyledString();
}

boost::optional<ValidatorToken>
ValidatorKeys::createValidatorToken (
    KeyType const& keyType)
{
    if (revoked () ||
            std::numeric_limits<std::uint32_t>::max () - 1 <= tokenSequence_)
        return boost::none;

    ++tokenSequence_;

    auto const tokenSecret = generateSecretKey (keyType, randomSeed ());
    auto const tokenPublic = derivePublicKey(keyType, tokenSecret);

    STObject st(sfGeneric);
    st[sfSequence] = tokenSequence_;
    st[sfPublicKey] = publicKey_;
    st[sfSigningPubKey] = tokenPublic;

    if (!domain_.empty())
        st[sfDomain] = makeSlice(domain_);

    ripple::sign(st, HashPrefix::manifest, keyType, tokenSecret);
    ripple::sign(st, HashPrefix::manifest, keyType_, secretKey_, sfMasterSignature);

    Serializer s;
    st.add(s);

    manifest_.clear();
    manifest_.reserve(s.size());
    std::copy(s.begin(), s.end(), std::back_inserter(manifest_));

    return ValidatorToken {
        ripple::base64_encode(manifest_.data(), manifest_.size()), tokenSecret };
}

boost::optional<std::string>
ValidatorKeys::createUNL (std::string const& dataPath)
{
    // Try to load UNL source data
    boost::filesystem::path unlSource = dataPath;
    if (!exists (unlSource))
        throw std::runtime_error (
            "Specified UNL source file doesn't exist: " +
                unlSource.string ());
    std::ifstream ifsData (unlSource.c_str (), std::ios::in);
    if (! ifsData)
        throw std::runtime_error (
            "Failed to open UNL source file: " + unlSource.string());

    // Parse data
    Json::Reader reader;
    Json::Value jValidators;
    if (! reader.parse (ifsData, jValidators))
    {
        throw std::runtime_error (
            "Unable to parse json file: " + unlSource.string());
    }
    if (!jValidators.isArray())
    {
        throw std::runtime_error (
            "The json file must contain an array");
    }

    // Check that neither master key is revoked nor we
    //   have exceeded an allowed sequence range.
    if (revoked () ||
            std::numeric_limits<std::uint32_t>::max () - 1 <= tokenSequence_)
        return boost::none;

    // Generate one-time signing keys and create manifest
    ++tokenSequence_;

    auto const tokenSecret = generateSecretKey (randomSeed ());
    auto const tokenPublic = derivePublicKey(tokenSecret);

    STObject st(sfGeneric);
    st[sfSequence] = tokenSequence_;
    st[sfPublicKey] = publicKey_;
    st[sfSigningPubKey] = tokenPublic;

    ripple::sign(st, HashPrefix::manifest, tokenSecret);
    ripple::sign(st, HashPrefix::manifest, secretKey_,
        sfMasterSignature);

    Serializer s;
    st.add(s);

    std::string manifest (static_cast<char const*> (s.data()), s.size());

    std::string vlBlob, vlStr;

    // Create blob to sign
    Json::Value jvToSign;
    int currTime = std::time(nullptr) - 1614556800;
    jvToSign["sequence"] = tokenSequence_;
    jvToSign["expiration"] = currTime  + 7889238;
    jvToSign["validators"] = jValidators;

    vlBlob = to_string(jvToSign);
    auto signature = ripple::sign (tokenPublic, tokenSecret, makeSlice (vlBlo
b));

    // Pack the final list and serialize it
    Json::Value jvl;
    jvl["public_key"] = strHex(publicKey_);
    jvl["manifest"] = ripple::base64_encode(manifest);
    jvl["blob"] = ripple::base64_encode(vlBlob);
    jvl["signature"] = strHex(signature);
    jvl["version"] = 1;

    return to_string(jvl);
}

std::string
ValidatorKeys::revoke ()
{
    revoked_ = true;

    STObject st(sfGeneric);
    st[sfSequence] = std::numeric_limits<std::uint32_t>::max ();
    st[sfPublicKey] = publicKey_;

    ripple::sign(st, HashPrefix::manifest, keyType_, secretKey_, sfMasterSignature);

    Serializer s;
    st.add(s);

    manifest_.clear();
    manifest_.reserve(s.size());
    std::copy(s.begin(), s.end(), std::back_inserter(manifest_));

    return ripple::base64_encode(manifest_.data(), manifest_.size());
}

std::string
ValidatorKeys::sign (std::string const& data) const
{
    return strHex(ripple::sign (publicKey_, secretKey_, makeSlice (data)));
}

void
ValidatorKeys::domain(std::string d)
{
    if (!d.empty())
    {
        // A valid domain for a validator must be at least 4 characters
        // long, should contain at least one . and should not be longer
        // that 128 characters.
        if (d.size() < 4 || d.size() > 128)
            throw std::runtime_error (
                "The domain must be between 4 and 128 characters long.");

        // This regular expression should do a decent job of weeding out
        // obviously wrong domain names but it isn't perfect. It does not
        // really support IDNs. If this turns out to be an issue, a more
        // thorough regex can be used or this check can just be removed.
        static boost::regex const re(
                "^"                     // Beginning of line
                "("                     // Hostname or domain name
                "(?!-)"                 //  - must not begin with '-'
                "[a-zA-Z0-9-]{1,63}"    //  - only alphanumeric and '-'
                "(?<!-)"                //  - must not end with '-'
                "\\."                   // segment separator
                ")+"                    // 1 or more segments
                "[A-Za-z]{2,63}"        // TLD
                "$"                     // End of line
            , boost::regex_constants::optimize);

        if (!boost::regex_match(d, re))
            throw std::runtime_error (
                "The domain field must use the '[host.][subdomain.]domain.tld' format");
    }

    domain_ = std::move(d);
}

} // ripple

max_stars_repo_name: BRTNetwork/validator-keys-tool

max_issues_repo_name: BRTNetwork/validator-keys-tool

max_forks_repo_name: BRTNetwork/validator-keys-tool