text:
#include "ff_wordalign.h"

#include <algorithm>
#include <iterator>
#include <set>
#include <sstream>
#include <string>
#include <cmath>
#include <bitset>
#ifndef HAVE_OLD_CPP
# include <unordered_map>
#else
# include <tr1/unordered_map>
namespace std { using std::tr1::unordered_map; }
#endif

#include <boost/tuple/tuple.hpp>
#include "boost/tuple/tuple_comparison.hpp"
#include <boost/functional/hash.hpp>

#include "factored_lexicon_helper.h"
#include "verbose.h"
#include "stringlib.h"
#include "sentence_metadata.h"
#include "hg.h"
#include "fdict.h"
#include "aligner.h"
#include "tdict.h"   // Blunsom hack
#include "filelib.h" // Blunsom hack

static const int MAX_SENTENCE_SIZE = 100;

static const int kNULL_i = 255;  // -1 as an unsigned char

using namespace std;

// TODO new feature: if a word is translated as itself and there is a transition back to the same word, fire a feature

RelativeSentencePosition::RelativeSentencePosition(const string& param) :
    fid_(FD::Convert("RelativeSentencePosition")) {
  if (!param.empty()) {
    cerr << "  Loading word classes from " << param << endl;
    condition_on_fclass_ = true;
    ReadFile rf(param);
    istream& in = *rf.stream();
    set<WordID> classes;
    while(in) {
      string line;
      getline(in, line);
      if (line.empty()) continue;
      vector<WordID> v;
      TD::ConvertSentence(line, &v);
      pos_.push_back(v);
      for (int i = 0; i < v.size(); ++i)
        classes.insert(v[i]);
    }
    for (set<WordID>::iterator i = classes.begin(); i != classes.end(); ++i) {
      ostringstream os;
      os << "RelPos_FC:" << TD::Convert(*i);
      fids_[*i] = FD::Convert(os.str());
    }
  } else {
    condition_on_fclass_ = false;
  }
}

void RelativeSentencePosition::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                                     const Hypergraph::Edge& edge,
                                                     const vector<const void*>& // ant_states
                                                     ,
                                                     SparseVector<double>* features,
                                                     SparseVector<double>* // estimated_features
                                                     ,
                                                     void* // state
  ) const {
  // if the source word is either null or the generated word
  // has no position in the reference
  if (edge.i_ == -1 || edge.prev_i_ == -1)
    return;

  assert(smeta.GetTargetLength() > 0);
  const double val = fabs(static_cast<double>(edge.i_) / smeta.GetSourceLength() -
                          static_cast<double>(edge.prev_i_) / smeta.GetTargetLength());
  features->set_value(fid_, val);
  if (condition_on_fclass_) {
    assert(smeta.GetSentenceID() < pos_.size());
    const WordID cur_fclass = pos_[smeta.GetSentenceID()][edge.i_];
    std::map<WordID, int>::const_iterator fidit = fids_.find(cur_fclass);
    assert(fidit != fids_.end());
    const int fid = fidit->second;
    features->set_value(fid, val);
  }
//  cerr << f_len_ << " " << e_len_ << " [" << edge.i_ << "," << edge.j_ << "|" << edge.prev_i_ << "," << edge.prev_j_ << "]\t" << edge.rule_->AsString() << "\tVAL=" << val << endl;
}

LexNullJump::LexNullJump(const string& param) :
    FeatureFunction(1),
    fid_lex_null_(FD::Convert("JumpLexNull")),
    fid_null_lex_(FD::Convert("JumpNullLex")),
    fid_null_null_(FD::Convert("JumpNullNull")),
    fid_lex_lex_(FD::Convert("JumpLexLex")) {}

void LexNullJump::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                        const Hypergraph::Edge& edge,
                                        const vector<const void*>& ant_states,
                                        SparseVector<double>* features,
                                        SparseVector<double>* /* estimated_features */,
                                        void* state) const {
  char& dpstate = *((char*)state);
  if (edge.Arity() == 0) {
    // dpstate is 'N' = null or 'L' = lex
    if (edge.i_ < 0) { dpstate = 'N'; } else { dpstate = 'L'; }
  } else if (edge.Arity() == 1) {
    dpstate = *((unsigned char*)ant_states[0]);
  } else if (edge.Arity() == 2) {
    char left = *((char*)ant_states[0]);
    char right = *((char*)ant_states[1]);
    dpstate = right;
    if (left == 'N') {
      if (right == 'N')
        features->set_value(fid_null_null_, 1.0);
      else
        features->set_value(fid_null_lex_, 1.0);
    } else { // left == 'L'
      if (right == 'N')
        features->set_value(fid_lex_null_, 1.0);
      else
        features->set_value(fid_lex_lex_, 1.0);
    }
  } else {
    assert(!"something really unexpected is happening");
  }
}

NewJump::NewJump(const string& param) :
    FeatureFunction(1),
    kBOS_(TD::Convert("BOS")),
    kEOS_(TD::Convert("EOS")) {
  cerr << "    NewJump";
  vector<string> argv;
  set<string> permitted;
  permitted.insert("use_binned_log_lengths");
  permitted.insert("flen");
  permitted.insert("elen");
  permitted.insert("fprev");
  permitted.insert("f0");
  permitted.insert("f-1");
  permitted.insert("f+1");
  // also permitted f:FILENAME
  int argc = SplitOnWhitespace(param, &argv);
  set<string> config;
  string f_file;
  for (int i = 0; i < argc; ++i) {
    if (argv[i].size() > 2 && argv[i].find("f:") == 0) {
      assert(f_file.empty());  // only one f file!
      f_file = argv[i].substr(2);
      cerr << " source_file=" << f_file;
    } else {
      if (permitted.count(argv[i])) {
        assert(config.count(argv[i]) == 0);
        config.insert(argv[i]);
        cerr << " " << argv[i];
      } else {
        cerr << "\nNewJump: don't understand param '" << argv[i] << "'\n";
        abort();
      }
    }
  }
  cerr << endl;
  use_binned_log_lengths_ = config.count("use_binned_log_lengths") > 0;
  f0_ = config.count("f0") > 0;
  fm1_ = config.count("f-1") > 0;
  fp1_ = config.count("f+1") > 0;
  fprev_ = config.count("fprev") > 0;
  elen_ = config.count("elen") > 0;
  flen_ = config.count("flen") > 0;
  if (f0_ || fm1_ || fp1_ || fprev_) {
    if (f_file.empty()) {
      cerr << "NewJump: conditioning on src but f:FILE not specified!\n";
      abort();
    }
    ReadFile rf(f_file);
    istream& in = *rf.stream();
    string line;
    while(in) {
      getline(in, line);
      if (!in) continue;
      vector<WordID> v;
      TD::ConvertSentence(line, &v);
      src_.push_back(v);
    }
  }
  fid_str_ = "J";
  if (flen_) fid_str_ += "F";
  if (elen_) fid_str_ += "E";
  if (f0_) fid_str_ += "C";
  if (fm1_) fid_str_ += "L";
  if (fp1_) fid_str_ += "R";
  if (fprev_) fid_str_ += "P";
}

// do a log transform on the length (of a sentence, a jump, etc)
// this basically means that large distances that are close to each other
// are put into the same bin
int BinnedLogLength(int len) {
  int res = static_cast<int>(log(len+1) / log(1.3));
  if (res > 16) res = 16;
  return res;
}

// <0>=jump size <1>=jump_dir <2>=flen, <3>=elen, <4>=f0, <5>=f-1, <6>=f+1, <7>=fprev
typedef boost::tuple<short, char, short, short, WordID, WordID, WordID, WordID> NewJumpFeatureKey;

struct KeyHash : unary_function<NewJumpFeatureKey, size_t> {
  size_t operator()(const NewJumpFeatureKey& k) const {
    size_t h = 0x37473DEF321;
    boost::hash_combine(h, k.get<0>());
    boost::hash_combine(h, k.get<1>());
    boost::hash_combine(h, k.get<2>());
    boost::hash_combine(h, k.get<3>());
    boost::hash_combine(h, k.get<4>());
    boost::hash_combine(h, k.get<5>());
    boost::hash_combine(h, k.get<6>());
    boost::hash_combine(h, k.get<7>());
    return h;
  }
};

void NewJump::FireFeature(const SentenceMetadata& smeta,
                          const int prev_src_index,
                          const int cur_src_index,
                          SparseVector<double>* features) const {
  const int id = smeta.GetSentenceID();
  const int src_len = smeta.GetSourceLength();
  const int raw_jump = cur_src_index - prev_src_index;
  short jump_magnitude = raw_jump;
  char jtype = 0;
  if (raw_jump > 0) { jtype = 'R'; } // Right
  else if (raw_jump == 0) { jtype = 'S'; } // Stay
  else { jtype = 'L'; jump_magnitude = raw_jump * -1; } // Left
  int effective_src_len = src_len;
  int effective_trg_len = smeta.GetTargetLength();
  if (use_binned_log_lengths_) {
    jump_magnitude = BinnedLogLength(jump_magnitude);
    effective_src_len = BinnedLogLength(src_len);
    effective_trg_len = BinnedLogLength(effective_trg_len);
  }
  NewJumpFeatureKey key(jump_magnitude,jtype,0,0,0,0,0);
  using boost::get;
  if (flen_)  get<2>(key) = effective_src_len;
  if (elen_)  get<3>(key) = effective_trg_len;
  if (f0_)    get<4>(key) = GetSourceWord(id, cur_src_index);
  if (fm1_)   get<5>(key) = GetSourceWord(id, cur_src_index - 1);
  if (fp1_)   get<6>(key) = GetSourceWord(id, cur_src_index + 1);
  if (fprev_) get<7>(key) = GetSourceWord(id, prev_src_index);

  static std::unordered_map<NewJumpFeatureKey, int, KeyHash> fids;
  int& fid = fids[key];
  if (!fid) {
    ostringstream os;
    os << fid_str_ << ':' << jtype << jump_magnitude;
    if (flen_)  os << ':' << get<2>(key);
    if (elen_)  os << ':' << get<3>(key);
    if (f0_)    os << ':' << TD::Convert(get<4>(key));
    if (fm1_)   os << ':' << TD::Convert(get<5>(key));
    if (fp1_)   os << ':' << TD::Convert(get<6>(key));
    if (fprev_) os << ':' << TD::Convert(get<7>(key));
    fid = FD::Convert(os.str());
  }
  features->set_value(fid, 1.0);
}

void NewJump::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                       const Hypergraph::Edge& edge,
                                       const vector<const void*>& ant_states,
                                       SparseVector<double>* features,
                                       SparseVector<double>* /* estimated_features */,
                                       void* state) const {
  unsigned char& dpstate = *((unsigned char*)state);
  // IMPORTANT: this only fires on non-Null transitions!
  const int flen = smeta.GetSourceLength();
  if (edge.Arity() == 0) {
    dpstate = static_cast<unsigned int>(edge.i_);
    if (edge.prev_i_ == 0) {     // first target word in sentence
      if (edge.i_ >= 0) {   // generated from non-Null token?
        FireFeature(smeta,
                    -1,  // previous src = beginning of sentence index
                    edge.i_, // current src
                    features);
      }
    } else if (edge.prev_i_ == smeta.GetTargetLength() - 1) {  // last word
      if (edge.i_ >= 0) {  // generated from non-Null token?
        FireFeature(smeta,
                    edge.i_,  // previous src = last word position
                    flen,     // current src
                    features);
      }
    }
  } else if (edge.Arity() == 1) {
    dpstate = *((unsigned char*)ant_states[0]);
  } else if (edge.Arity() == 2) {
    int left_index = *((unsigned char*)ant_states[0]);
    int right_index = *((unsigned char*)ant_states[1]);
    if (right_index == -1)
      dpstate = static_cast<unsigned int>(left_index);
    else
      dpstate = static_cast<unsigned int>(right_index);
    if (left_index != kNULL_i && right_index != kNULL_i) {
      FireFeature(smeta,
                  left_index,          // previous src index
                  right_index,         // current src index
                  features);
    }
  } else {
    assert(!"something really unexpected is happening");
  }
}

SourceBigram::SourceBigram(const std::string& param) :
    FeatureFunction(sizeof(WordID) + sizeof(int)) {
  fid_str_ = "SB:";
  if (param.size() > 0) {
    vector<string> argv;
    int argc = SplitOnWhitespace(param, &argv);
    if (argc != 2) {
      cerr << "SourceBigram [FEATURE_NAME_PREFIX PATH]\n";
      abort();
    }
    fid_str_ = argv[0] + ":";
    lexmap_.reset(new FactoredLexiconHelper(argv[1], "*"));
  } else {
    lexmap_.reset(new FactoredLexiconHelper);
  }
}

void SourceBigram::PrepareForInput(const SentenceMetadata& smeta) {
  lexmap_->PrepareForInput(smeta);
}

void SourceBigram::FinalTraversalFeatures(const void* context,
                                      SparseVector<double>* features) const {
  WordID left = *static_cast<const WordID*>(context);
  int left_wc = *(static_cast<const int*>(context) + 1);
  if (left_wc == 1)
    FireFeature(-1, left, features);
  FireFeature(left, -1, features);
}

void SourceBigram::FireFeature(WordID left,
                   WordID right,
                   SparseVector<double>* features) const {
  int& fid = fmap_[left][right];
  // TODO important important !!! escape strings !!!
  if (!fid) {
    ostringstream os;
    os << fid_str_;
    if (left < 0) { os << "BOS"; } else { os << TD::Convert(left); }
    os << '_';
    if (right < 0) { os << "EOS"; } else { os << TD::Convert(right); }
    fid = FD::Convert(os.str());
    if (fid == 0) fid = -1;
  }
  if (fid > 0) features->set_value(fid, 1.0);
}

void SourceBigram::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                     const Hypergraph::Edge& edge,
                                     const std::vector<const void*>& ant_contexts,
                                     SparseVector<double>* features,
                                            SparseVector<double>* /* estimated_features */,
                                     void* context) const {
  WordID& out_context = *static_cast<WordID*>(context);
  int& out_word_count = *(static_cast<int*>(context) + 1);
  const int arity = edge.Arity();
  if (arity == 0) {
    out_context = lexmap_->SourceWordAtPosition(edge.i_);
    out_word_count = edge.rule_->EWords();
    assert(out_word_count == 1); // this is only defined for lex translation!
    // revisit this if you want to translate into null words
  } else if (arity == 1) {
    WordID left = *static_cast<const WordID*>(ant_contexts[0]);
    int left_wc = *(static_cast<const int*>(ant_contexts[0]) + 1);
    out_context = left;
    out_word_count = left_wc;
  } else if (arity == 2) {
    WordID left = *static_cast<const WordID*>(ant_contexts[0]);
    WordID right = *static_cast<const WordID*>(ant_contexts[1]);
    int left_wc = *(static_cast<const int*>(ant_contexts[0]) + 1);
    int right_wc = *(static_cast<const int*>(ant_contexts[0]) + 1);
    if (left_wc == 1 && right_wc == 1)
      FireFeature(-1, left, features);
    FireFeature(left, right, features);
    out_word_count = left_wc + right_wc;
    out_context = right;
  }
}

LexicalTranslationTrigger::LexicalTranslationTrigger(const std::string& param) :
    FeatureFunction(0) {
  if (param.empty()) {
    cerr << "LexicalTranslationTrigger requires a parameter (file containing triggers)!\n";
  } else {
    ReadFile rf(param);
    istream& in = *rf.stream();
    string line;
    while(in) {
      getline(in, line);
      if (!in) continue;
      vector<WordID> v;
      TD::ConvertSentence(line, &v);
      triggers_.push_back(v);
    }
  }
}

void LexicalTranslationTrigger::FireFeature(WordID trigger,
                                     WordID src,
                                     WordID trg,
                                     SparseVector<double>* features) const {
  int& fid = fmap_[trigger][src][trg];
  if (!fid) {
    ostringstream os;
    os << "T:" << TD::Convert(trigger) << ':' << TD::Convert(src) << '_' << TD::Convert(trg);
    fid = FD::Convert(os.str());
  }
  features->set_value(fid, 1.0);

  int &tfid = target_fmap_[trigger][trg];
  if (!tfid) {
    ostringstream os;
    os << "TT:" << TD::Convert(trigger) << ':' << TD::Convert(trg);
    tfid = FD::Convert(os.str());
  }
  features->set_value(tfid, 1.0);
}

void LexicalTranslationTrigger::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                     const Hypergraph::Edge& edge,
                                     const std::vector<const void*>& ant_contexts,
                                     SparseVector<double>* features,
                                            SparseVector<double>* /* estimated_features */,
                                     void* context) const {
  if (edge.Arity() == 0) {
    assert(edge.rule_->EWords() == 1);
    assert(edge.rule_->FWords() == 1);
    WordID trg = edge.rule_->e()[0];
    WordID src = edge.rule_->f()[0];
    assert(triggers_.size() > smeta.GetSentenceID());
    const vector<WordID>& triggers = triggers_[smeta.GetSentenceID()];
    for (int i = 0; i < triggers.size(); ++i) {
      FireFeature(triggers[i], src, trg, features);
    }
  }
}

BlunsomSynchronousParseHack::BlunsomSynchronousParseHack(const string& param) :
  FeatureFunction((100 / 8) + 1), fid_(FD::Convert("NotRef")), cur_sent_(-1) {
  ReadFile rf(param);
  istream& in = *rf.stream(); int lc = 0;
  while(in) {
    string line;
    getline(in, line);
    if (!in) break;
    ++lc;
    refs_.push_back(vector<WordID>());
    TD::ConvertSentence(line, &refs_.back());
  }
  cerr << "  Loaded " << lc << " refs\n";
}

void BlunsomSynchronousParseHack::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                           const Hypergraph::Edge& edge,
                                           const vector<const void*>& ant_states,
                                           SparseVector<double>* features,
                                           SparseVector<double>* /* estimated_features */,
                                           void* state) const {
  if (cur_sent_ != smeta.GetSentenceID()) {
    // assert(smeta.HasReference());
    cur_sent_ = smeta.GetSentenceID();
    assert(cur_sent_ < refs_.size());
    cur_ref_ = &refs_[cur_sent_];
    cur_map_.clear();
    for (int i = 0; i < cur_ref_->size(); ++i) {
      vector<WordID> phrase;
      for (int j = i; j < cur_ref_->size(); ++j) {
        phrase.push_back((*cur_ref_)[j]);
        cur_map_[phrase] = i;
      }
    }
  }
  //cerr << edge.rule_->AsString() << endl;
  for (int i = 0; i < ant_states.size(); ++i) {
    if (DoesNotBelong(ant_states[i])) {
      //cerr << "  ant " << i << " does not belong\n";
      return;
    }
  }
  vector<vector<WordID> > ants(ant_states.size());
  vector<const vector<WordID>* > pants(ant_states.size());
  for (int i = 0; i < ant_states.size(); ++i) {
    AppendAntecedentString(ant_states[i], &ants[i]);
    //cerr << "  ant[" << i << "]: " << ((int)*(static_cast<const unsigned char*>(ant_states[i]))) << " " << TD::GetString(ants[i]) << endl;
    pants[i] = &ants[i];
  }
  vector<WordID> yield;
  edge.rule_->ESubstitute(pants, &yield);
  //cerr << "YIELD: " << TD::GetString(yield) << endl;
  Vec2Int::iterator it = cur_map_.find(yield);
  if (it == cur_map_.end()) {
    features->set_value(fid_, 1);
    //cerr << "  BAD!\n";
    return;
  }
  SetStateMask(it->second, it->second + yield.size(), state);
}

IdentityCycleDetector::IdentityCycleDetector(const std::string& param) : FeatureFunction(2) {
  length_min_ = 3;
  if (!param.empty())
    length_min_ = atoi(param.c_str());
  assert(length_min_ >= 0);
  ostringstream os;
  os << "IdentityCycle_LenGT" << length_min_;
  fid_ = FD::Convert(os.str());
}

inline bool IsIdentityTranslation(const void* state) {
  return static_cast<const unsigned char*>(state)[0];
}

inline int SourceIndex(const void* state) {
  unsigned char i = static_cast<const unsigned char*>(state)[1];
  if (i == 255) return -1;
  return i;
}

void IdentityCycleDetector::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                     const Hypergraph::Edge& edge,
                                     const std::vector<const void*>& ant_contexts,
                                     SparseVector<double>* features,
                                     SparseVector<double>* estimated_features,
                                     void* context) const {
  unsigned char* out_state = static_cast<unsigned char*>(context);
  unsigned char& out_is_identity = out_state[0];
  unsigned char& out_src_index = out_state[1];

  if (edge.Arity() == 0) {
    assert(edge.rule_->EWords() == 1);
    assert(edge.rule_->FWords() == 1);
    out_src_index = edge.i_;
    out_is_identity = false;
    if (edge.rule_->e_[0] == edge.rule_->f_[0]) {
      const WordID word = edge.rule_->e_[0];
      static map<WordID, bool> big_enough;
      map<WordID,bool>::iterator it = big_enough_.find(word);
      if (it == big_enough_.end()) {
        out_is_identity = big_enough_[word] = TD::Convert(word).size() >= length_min_;
      } else {
        out_is_identity = it->second;
      }
    }
  } else if (edge.Arity() == 1) {
    memcpy(context, ant_contexts[0], 2);
  } else if (edge.Arity() == 2) {
    bool left_identity = IsIdentityTranslation(ant_contexts[0]);
    int left_index = SourceIndex(ant_contexts[0]);
    bool right_identity = IsIdentityTranslation(ant_contexts[1]);
    int right_index = SourceIndex(ant_contexts[1]);
    if ((left_identity && left_index == right_index && !right_identity) ||
        (right_identity && left_index == right_index && !left_identity)) {
      features->set_value(fid_, 1.0);
    }
    out_is_identity = right_identity;
    out_src_index = right_index;
  } else { assert("really really bad"); }
}

InputIndicator::InputIndicator(const std::string& param) {}

void InputIndicator::FireFeature(WordID src,
                                 SparseVector<double>* features) const {
  int& fid = fmap_[src];
  if (!fid) {
    static map<WordID, WordID> escape;
    if (escape.empty()) {
      escape[TD::Convert("=")] = TD::Convert("__EQ");
      escape[TD::Convert(";")] = TD::Convert("__SC");
      escape[TD::Convert(",")] = TD::Convert("__CO");
    }
    if (escape.count(src)) src = escape[src];
    ostringstream os;
    os << "S:" << TD::Convert(src);
    fid = FD::Convert(os.str());
  }
  features->set_value(fid, 1.0);
}

void InputIndicator::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                     const Hypergraph::Edge& edge,
                                     const std::vector<const void*>& ant_contexts,
                                     SparseVector<double>* features,
                                     SparseVector<double>* estimated_features,
                                     void* context) const {
  const vector<WordID>& fw = edge.rule_->f_;
  for (int i = 0; i < fw.size(); ++i) {
    const WordID& f = fw[i];
    if (f > 0) FireFeature(f, features);
  }
}

WordPairFeatures::WordPairFeatures(const string& param) {
  vector<string> argv;
  int argc = SplitOnWhitespace(param, &argv);
  if (argc != 1) {
    cerr << "WordPairFeature /path/to/feature_values.table\n";
    abort();
  }
  set<WordID> all_srcs;
  {
    ReadFile rf(argv[0]);
    istream& in = *rf.stream();
    string buf;
    while (in) {
      getline(in, buf);
      if (buf.empty()) continue;
      int start = 0;
      while(start < buf.size() && buf[start] == ' ') ++start;
      int end = start;
      while(end < buf.size() && buf[end] != ' ') ++end;
      const WordID src = TD::Convert(buf.substr(start, end - start));
      all_srcs.insert(src);
    }
  }
  if (all_srcs.empty()) {
    cerr << "WordPairFeature " << param << " loaded empty file!\n";
    return;
  }
  fkeys_.reserve(all_srcs.size());
  copy(all_srcs.begin(), all_srcs.end(), back_inserter(fkeys_));
  values_.resize(all_srcs.size());
  if (!SILENT) { cerr << "WordPairFeature: " << all_srcs.size() << " sources\n"; }
  ReadFile rf(argv[0]);
  istream& in = *rf.stream();
  string buf;
  double val = 0;
  WordID cur_src = 0;
  map<WordID, SparseVector<float> > *pv = NULL;
  const WordID kBARRIER = TD::Convert("|||");
  while (in) {
    getline(in, buf);
    if (buf.size() == 0) continue;
    int start = 0;
    while(start < buf.size() && buf[start] == ' ') ++start;
    int end = start;
    while(end < buf.size() && buf[end] != ' ') ++end;
    const WordID src = TD::Convert(buf.substr(start, end - start));
    if (cur_src != src) {
      cur_src = src;
      size_t ind = distance(fkeys_.begin(), lower_bound(fkeys_.begin(), fkeys_.end(), cur_src));
      pv = &values_[ind];
    }
    end += 1;
    start = end;
    while(end < buf.size() && buf[end] != ' ') ++end;
    WordID x = TD::Convert(buf.substr(start, end - start));
    if (x != kBARRIER) {
      cerr << "1 Format error: " << buf << endl;
      abort();
    }
    start = end + 1;
    end = start + 1;
    while(end < buf.size() && buf[end] != ' ') ++end;
    WordID trg = TD::Convert(buf.substr(start, end - start));
    if (trg == kBARRIER) {
      cerr << "2 Format error: " << buf << endl;
      abort();
    }
    start = end + 1;
    end = start + 1;
    while(end < buf.size() && buf[end] != ' ') ++end;
    WordID x2 = TD::Convert(buf.substr(start, end - start));
    if (x2 != kBARRIER) {
      cerr << "3 Format error: " << buf << endl;
      abort();
    }
    start = end + 1;

    SparseVector<float>& v = (*pv)[trg];
    while(start < buf.size()) {
      end = start + 1;
      while(end < buf.size() && buf[end] != '=' && buf[end] != ' ') ++end;
      if (end == buf.size() || buf[end] != '=') { cerr << "4 Format error: " << buf << endl; abort(); }
      const int fid = FD::Convert(buf.substr(start, end - start));
      start = end + 1;
      while(start < buf.size() && buf[start] == ' ') ++start;
      end = start + 1;
      while(end < buf.size() && buf[end] != ' ') ++end;
      assert(end > start);
      if (end < buf.size()) buf[end] = 0;
      val = strtod(&buf.c_str()[start], NULL);
      v.set_value(fid, val);
      start = end + 1;
    }
  }
}

void WordPairFeatures::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                     const Hypergraph::Edge& edge,
                                     const std::vector<const void*>& ant_contexts,
                                     SparseVector<double>* features,
                                     SparseVector<double>* estimated_features,
                                     void* context) const {
  if (edge.Arity() == 0) {
    assert(edge.rule_->EWords() == 1);
    assert(edge.rule_->FWords() == 1);
    const WordID trg = edge.rule_->e()[0];
    const WordID src = edge.rule_->f()[0];
    size_t ind = distance(fkeys_.begin(), lower_bound(fkeys_.begin(), fkeys_.end(), src));
    if (ind == fkeys_.size() || fkeys_[ind] != src) {
      cerr << "WordPairFeatures no source entries for " << TD::Convert(src) << endl;
      abort();
    }
    const map<WordID, SparseVector<float> >::const_iterator it = values_[ind].find(trg);
    // TODO optional strict flag to make sure there are features for all pairs?
    if (it != values_[ind].end())
      (*features) += it->second;
  }
}

struct PathFertility {
  unsigned char null_fertility;
  unsigned char index_fertility[255];
  PathFertility& operator+=(const PathFertility& rhs) {
    null_fertility += rhs.null_fertility;
    for (int i = 0; i < 255; ++i)
      index_fertility[i] += rhs.index_fertility[i];
    return *this;
  }
};

Fertility::Fertility(const string& config) :
    FeatureFunction(sizeof(PathFertility)) {}

void Fertility::TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                      const Hypergraph::Edge& edge,
                                      const std::vector<const void*>& ant_contexts,
                                      SparseVector<double>* features,
                                      SparseVector<double>* estimated_features,
                                      void* context) const {
  PathFertility& out_fert = *static_cast<PathFertility*>(context);
  if (edge.Arity() == 0) {
    if (edge.i_ < 0) {
      out_fert.null_fertility = 1;
    } else {
      out_fert.index_fertility[edge.i_] = 1;
    }
  } else if (edge.Arity() == 2) {
    const PathFertility left = *static_cast<const PathFertility*>(ant_contexts[0]);
    const PathFertility right = *static_cast<const PathFertility*>(ant_contexts[1]);
    out_fert += left;
    out_fert += right;
  } else if (edge.Arity() == 1) {
    out_fert += *static_cast<const PathFertility*>(ant_contexts[0]);
  }
}

ext: cc

max_stars_repo_name: kho/cdec

max_issues_repo_name: kho/cdec

max_forks_repo_name: kho/cdec


text:
#include <fc/io/raw.hpp>
#include <fc/io/json.hpp>
#include <fc/crypto/hex.hpp>
#include <fc/optional.hpp>
#include <fc/reflect/reflect.hpp>
#include <fc/filesystem.hpp>

#include <ultrainio/chain/worldstate.hpp>
#include <ultrainio/chain/chain_worldstate.hpp>
#include <ultrainio/chain/block_header_state.hpp>
#include <ultrainio/chain/block_state.hpp>
#include <ultrainio/chain/authority.hpp>
#include <chainbase/chainbase.hpp>

#include <boost/program_options.hpp>
#include <fstream>

// TODO: find a better way to instantiate chainbase objects
#undef OBJECT_CTOR
#define OBJECT_CTOR(...) public:
#define shared_string vector<char>
#define shared_authority authority
#define shared_vector vector
#define shared_set  set
namespace ultrainio { namespace chain { namespace config {
           template<>
                             constexpr uint64_t billable_size_v<authority> = 1;
}}}
#include <ultrainio/chain/abi_serializer.hpp>
#include <ultrainio/chain/account_object.hpp>
#include <ultrainio/chain/global_property_object.hpp>
#include <ultrainio/chain/block_summary_object.hpp>
#include <ultrainio/chain/transaction_object.hpp>
#include <ultrainio/chain/generated_transaction_object.hpp>
#include <ultrainio/chain/contract_table_objects.hpp>
#include <ultrainio/chain/authorization_manager.hpp>
#include <ultrainio/chain/permission_link_object.hpp>
#include <ultrainio/chain/resource_limits.hpp>
#include <ultrainio/chain/resource_limits_private.hpp>
#include <ultrainio/chain/whiteblacklist_object.hpp>
using namespace fc;
using namespace std;
using namespace ultrainio::chain;
using namespace chainbase;
using namespace ultrainio::chain::resource_limits;

// If using custom worldstate object, need re-define the template here
namespace ultrainio { namespace chain {
    namespace detail {
        template<>
        struct worldstate_row_traits<permission_object> {
            using value_type = permission_object;
            using worldstate_type = worldstate_permission_object;
        };
    }
}}

#define LAMBDA_PARAME (auto& row,auto& mvo,auto& section,auto& more)
#define READ_SECTION(objtype) read_section<objtype>(out,[]LAMBDA_PARAME{});
#define READ_SECTION_LAMBDA(objtype,lbd) read_section<objtype>(out,lbd);

namespace po = boost::program_options;

typedef decltype(std::make_shared<istream_worldstate_reader>(std::ifstream{}) ) WS;
const fc::microseconds max_serialization_time{100000};
map<account_name, abi_def> contract_abi;
WS worldstate;
boost::filesystem::path temp = boost::filesystem::unique_path();
chainbase::database db(temp, database::read_write, 1024);
std::ofstream table_info_out;
std::ofstream  account_info_out;

struct contract_table_info {
    table_name     table;
    uint64_t        len = 0;
    uint64_t        cnt = 0;
};

struct account_info {
    account_name name;
    uint64_t     recv_sequence = 0;
    uint64_t     auth_sequence = 0;
    uint64_t     code_sequence = 0;
    uint64_t     abi_sequence  = 0;
    uint64_t     ram_usage = 0;
    int64_t     ram_quota = 0;
    std::map<table_name, contract_table_info>  contract_info_map;
    uint64_t cnt_of_contact_table = 0;
    uint64_t cnt_of_contact_record = 0;
    uint64_t len_of_contact_in_ws = 0;
};

struct table_info {
    std::string table_name_text;
    uint64_t size_of_ws_file = 0;
    uint64_t cnt_of_record = 0;
};

FC_REFLECT(account_info, (name)(recv_sequence)(auth_sequence)(code_sequence)(abi_sequence)(ram_usage)(ram_quota)\
            (cnt_of_contact_table)(cnt_of_contact_record)(len_of_contact_in_ws))
FC_REFLECT(table_info, (table_name_text)(size_of_ws_file)(cnt_of_record))

std::map<account_name, account_info> account_info_map;
std::vector<table_info> table_info_vector;
bool is_enable_json = false;
bool is_detail = false;

//process section with lambda , contract table etc.
template<typename ObjectType,typename ProcessTable>
void read_section(std::ostream& out,ProcessTable&& pt) {
    auto it = [&](auto &section){
            string type_name= boost::core::demangle(typeid(ObjectType).name());
            string name = type_name.substr(type_name.find_last_of(":",type_name.size()-1)+1,type_name.size()-1);
            out << name << "\n";
            auto start_pos = worldstate->current_pos();
            int total_record = 0;
            bool more = !section.empty();
            while(more) {
              total_record++;
              auto row = typename ultrainio::chain::detail::worldstate_row_traits<ObjectType>::worldstate_type();
              more = section.read_row(row, db);

              fc::variant v;
              fc::to_variant(row, v);
              fc::mutable_variant_object mvo(v);

              pt(row,mvo,section,more);

                if (!std::is_same<ObjectType, table_id_object>::value) {
                    out << fc::json::to_string(mvo)<<"\n";
                }
            }

            table_info t_info;
            t_info.table_name_text = name;
            t_info.size_of_ws_file = worldstate->current_pos() - start_pos;
            t_info.cnt_of_record = total_record;
            if (table_info_out.is_open() && !std::is_same<ObjectType, block_state>::value && !std::is_same<ObjectType, chain_worldstate_header>::value) {
                table_info_vector.push_back(t_info);
            }
        };
        if (std::is_same<ObjectType, table_id_object>::value)
            worldstate->read_section("contract_tables",it);
        else if (std::is_same<ObjectType, block_header_state>::value)
            worldstate->read_section<block_state>(it);
        else
            worldstate->read_section<ObjectType>(it);
}

void output_info()
{
    if (!table_info_out.is_open())
        return;

    //print account info
    if (!is_enable_json){
        account_info_out << std::left << std::setw(13) << "name";
        account_info_out << std::setw(15) << "ram_usage"<< " ";
        account_info_out << std::setw(15) << "ram_limit"<< " ";
        account_info_out << std::setw(15) << "recv_sequence"<< " ";
        account_info_out << std::setw(15) << "abi_sequence"<< " ";
        account_info_out << std::setw(15) << "auth_sequence"<< " ";
        account_info_out << std::setw(15) << "code_sequence"<< " ";
        account_info_out << std::setw(15) << "cnt_of_contact_table"<< " ";
        account_info_out << std::setw(15) << "cnt_of_contact_record"<< " ";
        account_info_out << std::setw(15) << "len_of_contact_in_ws"<< " ";
        account_info_out << "\n";
    }

    std::vector<account_info> acc_v;
    for(auto& it : account_info_map){
        if (!is_detail && it.second.ram_quota == 0)//ram is 0 and simple mode
            continue;

        int len = 0;
        int cnt = 0;
        for (auto& t : it.second.contract_info_map){
            len += t.second.len;
            cnt += t.second.cnt;
        }
        it.second.cnt_of_contact_table = it.second.contract_info_map.size();
        it.second.cnt_of_contact_record = cnt;
        it.second.len_of_contact_in_ws = len;

        if (!is_enable_json) {
            account_info_out << std::left << std::setw(13) << it.second.name << " ";
            account_info_out << std::setw(15) << it.second.ram_usage << " ";
            if(it.second.ram_quota == -1)
                account_info_out << std::setw(15) << "unlimited" << " ";
            else
                account_info_out << std::setw(15) << it.second.ram_quota << " ";
            account_info_out << std::setw(15) << it.second.recv_sequence << " ";
            account_info_out << std::setw(15) << it.second.abi_sequence << " ";
            account_info_out << std::setw(15) << it.second.auth_sequence << " ";
            account_info_out << std::setw(15) << it.second.code_sequence << " ";
            account_info_out << std::setw(15) << it.second.cnt_of_contact_table << " ";
            account_info_out << std::setw(15) << it.second.cnt_of_contact_record << " ";
            account_info_out << std::setw(15) << it.second.len_of_contact_in_ws << " ";
            account_info_out << "\n";
        } else {
            acc_v.push_back(it.second);
        }
    }

    if (is_enable_json) {
        account_info_out << fc::json::to_string(acc_v);
    }

    //print  table_info
    if (!is_enable_json) {
        table_info_out << std::left << std::setw(50) << "Native_table_name ";
        table_info_out <<std::setw(20)<< "size_of_ws_file" << " " << std::setw(20) << "cnt_of_record" << "\n";
        for(auto& it : table_info_vector) {
            table_info_out << std::left << std::setw(50) << it.table_name_text << " ";
            table_info_out <<std::setw(20)<< it.size_of_ws_file << std::setw(20) << it.cnt_of_record << "\n";
        }
    } else {
        table_info_out << fc::json::to_string(table_info_vector);
    }
}

void decode_ws(std::ostream& out){
    READ_SECTION(chain_worldstate_header)

    READ_SECTION(block_header_state)

    auto acc_obj=[&]LAMBDA_PARAME{
        abi_def abi;
        if( abi_serializer::to_abi(row.abi, abi) ) {
            contract_abi[row.name] = abi;
            fc::variant vabi;
            fc::to_variant(abi, vabi);
            mvo["abi"] = vabi;
        }
        ULTRAIN_ASSERT(account_info_map.find(row.name) == account_info_map.end(), worldstate_exception, "Account already exist: ${a}", ("a", row.name));

        account_info info;
        info.name = row.name;
        account_info_map[row.name] = info;
    };
    READ_SECTION_LAMBDA(account_object, acc_obj)

    auto tb = [&]LAMBDA_PARAME{
        table_id_object::id_type t_id = row.id;
        const auto& abi = contract_abi[row.code];
        abi_serializer abis(abi,max_serialization_time);
        string table_type = abis.get_table_type(row.table);
        vector<char> data;
        out<<"\ntid:"<<fc::json::to_string(row)<<"\n";
        out<<"rows:\n";

        ULTRAIN_ASSERT(account_info_map.find(row.code) != account_info_map.end(), worldstate_exception, "Account don't exist: ${a}", ("a", row.code));
        auto& info = account_info_map[row.code];
        auto start_pos = worldstate->current_pos();
        int total_record = 0;

        unsigned_int size;
        more = section.read_row(size, db);
        for (size_t idx = 0; idx < size.value; idx++) {
            key_value_object row;
            row.t_id = t_id;
            more = section.read_row(row, db);

            total_record++;

            out<< row.primary_key << ":";
            if(!table_type.size()) {
                out << "{\"hex_data\":\"" << fc::to_hex(row.value.data(), row.value.size()) << "\n";
            } else {
                data.resize( row.value.size() );
                memcpy(data.data(), row.value.data(), row.value.size());
                out << "{\"data\":"
                    << fc::json::to_string( abis.binary_to_variant(table_type, data, max_serialization_time))
                    <<"\n";
            }
        }

        more = section.read_row(size, db);
        for (size_t idx = 0; idx < size.value; idx++) {
            index64_object row;
            row.t_id = t_id;
            more = section.read_row(row, db);
            out<< row.primary_key << ":";
            fc::variant v;
            fc::to_variant(row, v);
            fc::mutable_variant_object mvo(v);
            out << "index64 "<<fc::json::to_string(mvo)<<"\n";
        }

        more = section.read_row(size, db);
        for (size_t idx = 0; idx < size.value; idx++) {
            index128_object row;
            row.t_id = t_id;
            more = section.read_row(row, db);
        }

        more = section.read_row(size, db);
        for (size_t idx = 0; idx < size.value; idx++) {
            index_double_object row;
            row.t_id = t_id;
            more = section.read_row(row, db);
            fc::variant v;
            fc::to_variant(row, v);
            fc::mutable_variant_object mvo(v);
            out << fc::json::to_string(mvo)<<"\n";
        }

        more = section.read_row(size, db);
        for (size_t idx = 0; idx < size.value; idx++) {
            index_long_double_object row;
            row.t_id = t_id;
            more = section.read_row(row, db);
        }

        more = section.read_row(size, db);
        for (size_t idx = 0; idx < size.value; idx++) {
            index256_object row;
            row.t_id = t_id;
            more = section.read_row(row, db);
            fc::variant v;
            fc::to_variant(row, v);
            fc::mutable_variant_object mvo(v);
            out << "index256 "<<fc::json::to_string(mvo)<<"\n";
        }

        auto data_len = worldstate->current_pos() - start_pos;
        if (info.contract_info_map.find(row.table) != info.contract_info_map.end()){
            auto& table_info = info.contract_info_map.find(row.table)->second;
            table_info.len += data_len;
            table_info.cnt += total_record;
        } else {
            contract_table_info table_info;
            table_info.table = row.table;
            table_info.len = data_len;
            table_info.cnt = total_record;
            info.contract_info_map[row.table] = table_info;
        }
    };
    READ_SECTION_LAMBDA(table_id_object,tb)
    READ_SECTION_LAMBDA(account_sequence_object, [&]LAMBDA_PARAME{
        ULTRAIN_ASSERT(account_info_map.find(row.name) != account_info_map.end(), worldstate_exception, "Account don't exist: ${a}", ("a", row.name));
        auto& info = account_info_map[row.name];
        info.recv_sequence = row.recv_sequence;
        info.auth_sequence = row.auth_sequence;
        info.code_sequence = row.code_sequence;
        info.abi_sequence = row.abi_sequence;
    });
    READ_SECTION(global_property_object)
    READ_SECTION(dynamic_global_property_object)
    READ_SECTION(block_summary_object)
    READ_SECTION(transaction_object)
    READ_SECTION(generated_transaction_object)
    READ_SECTION(auth_sequence_object)
    READ_SECTION(permission_object)
    READ_SECTION(permission_link_object)
    READ_SECTION_LAMBDA(resource_limits_object, [&]LAMBDA_PARAME{
        ULTRAIN_ASSERT(account_info_map.find(row.owner) != account_info_map.end(), worldstate_exception, "Account don't exist: ${a}", ("a", row.owner));
        auto& info = account_info_map[row.owner];
        if (info.ram_quota <= 0 || row.pending == true)
            info.ram_quota = row.ram_bytes;
    });
    READ_SECTION_LAMBDA(resource_usage_object, [&]LAMBDA_PARAME{
        ULTRAIN_ASSERT(account_info_map.find(row.owner) != account_info_map.end(), worldstate_exception, "Account don't exist: ${a}", ("a", row.owner));
        auto& info = account_info_map[row.owner];
        info.ram_usage = row.ram_usage;
    });
    READ_SECTION(resource_limits_state_object)
    READ_SECTION(resource_limits_config_object)
    READ_SECTION(whiteblacklist_object)

    output_info();
}

int main(int argc, const char **argv) {
    try {
        po::options_description desc("Convert ws 2 json");
        desc.add_options()
            ("help,h", "Print this help message and exit")
            ("in,i", po::value<string>(), "Pathname of the input binary snapshot")
            ("out,o", po::value<string>(), "Pathname of the output JSON file")
            ("table,t","output contact table and account info")
            ("json,j","output contact table and account info as json format")
            ("detail,d","output all account info,include acount which ram is 0")
            ;
        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);

        string in_file;
        if(vm.count("in")) {
            in_file = vm.at("in").as<string>();
        }

        if( vm.count("detail") ) {
            is_detail = true;
        }

        if( vm.count("help") || !in_file.size() ) {
            std::cout << desc << std::endl;
            return 1;
        }

        if(!fc::exists(in_file)) {
            cout << "Input file does not exists: " << in_file << endl;
            return 1;
        }

        std::ifstream ifs(in_file, (std::ios::in | std::ios::binary));
        worldstate = std::make_shared<istream_worldstate_reader>(ifs);

        std::streambuf *buf;
        std::ofstream ofs;
        string out_path;
        if(vm.count("out")) {
            out_path=vm.at("out").as<string>();
            if(!fc::is_directory(out_path))
                fc::create_directories(out_path);
            ofs.open(out_path+"/ws.json");
            buf = ofs.rdbuf();
        } else {
            buf = std::cout.rdbuf();
        }

        std::ostream out(buf);

        if(vm.count("table")) {
            account_info_out = std::ofstream(out_path+"/account_info.txt", ios::out);
            table_info_out = std::ofstream(out_path+"/table_info.txt", ios::out);
            if(vm.count("json"))
                is_enable_json = true;
        }

        cout << temp.native() << " \n";

        decode_ws(out);
        ifs.close();
        ofs.close();
        table_info_out.close();
        account_info_out.close();
        boost::filesystem::remove_all( temp );
        return 0;
    }
    FC_CAPTURE_AND_LOG(());
    return 1;
}

ext: cpp

max_stars_repo_name: ultrain-os/ultrain-core-production

max_issues_repo_name: sighttviewliu/ultrain-core-production

max_forks_repo_name: sighttviewliu/ultrain-core-production


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS
  @copyright 2016 J.T. Lapreste

  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_SIMD_ARCH_COMMON_SIMD_FUNCTION_IS_NLEZ_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_IS_NLEZ_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>

#include <boost/simd/meta/hierarchy/simd.hpp>
#include <boost/simd/meta/as_logical.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/simd/is_gtz.hpp>
#include <boost/simd/function/simd/is_not_less_equal.hpp>

namespace boost { namespace simd { namespace ext
{
   namespace bd = boost::dispatch;
   namespace bs = boost::simd;
   BOOST_DISPATCH_OVERLOAD(is_nlez_
                          , (typename A0, typename X)
                          , bd::cpu_
                          , bs::pack_<bd::floating_<A0>, X>
                          )
   {
      BOOST_FORCEINLINE bs::as_logical_t<A0>  operator()( const A0& a0) const BOOST_NOEXCEPT
      {
        return is_not_less_equal(a0, Zero<A0>());
      }
   };

   BOOST_DISPATCH_OVERLOAD(is_nlez_
                          , (typename A0, typename X)
                          , bd::cpu_
                          , bs::pack_<bd::arithmetic_<A0>, X>
                          )
   {
      BOOST_FORCEINLINE bs::as_logical_t<A0>  operator()( const A0& a0) const BOOST_NOEXCEPT
      {
        return is_gtz(a0);
      }
   };

} } }
#endif

ext: hpp


text:
//
// Created by terrywei on 2017/9/3.
//

#include <cstdint>
#include <iostream>
#include <vector>
#include <boost/optional.hpp>
#include <string>
#include "snow.hpp"

static auto logger = spdlog::basic_logger_mt("test2", "./test2.txt", true);

class AddCodec : public snow::Codec<uint32_t, uint32_t> {
public:
    virtual int check(const char *data, std::size_t size) const override {
        logger->trace("check size {}", size);
        if (size < sizeof(uint32_t)) {
            return 0;
        } else {
            return sizeof(uint32_t);
        }
    }

    virtual bool encode(snow::FixedSizeBuffer<4096> &buffer) const override {
        buffer.append((char *) &m_request, sizeof(m_request));
        return true;
    }

    virtual bool decode(snow::FixedSizeBuffer<4096> &buffer) override {
        m_response = *(uint32_t *) (buffer.read_index());
        buffer.increase_read_index(4);
        return true;
    }

    virtual std::string get_dest_addr() const override {
        return "127.0.0.1:10000";
    }
};

int main(int argc, char *argv[]) {
    logger->set_level(spdlog::level::trace);
    logger->trace("test2 begin");
    for (int i = 0; i < 1; ++i) {
        boost::asio::io_service ios;
        boost::asio::spawn(ios, [&ios](boost::asio::yield_context yield) mutable {
            std::vector<std::unique_ptr<AddCodec>> adds;
            for (uint32_t i = 0; i < 1; ++i) {
                adds.emplace_back(new AddCodec);
                adds.back()->get_request() = i;
            }
            snow::Client client(ios, yield);
            client.request(adds, std::chrono::milliseconds(100));
            for (auto &add : adds) {
                logger->trace("request success, req {}, resp = {}", add->get_request(), add->get_response());
            }
        });
        ios.run();
    }
    logger->trace("test2 end");

    return 0;
}

max_stars_repo_name: weijingtao/snow

max_issues_repo_name: weijingtao/snow

max_forks_repo_name: weijingtao/snow


text:
/*
 * SvgPath.hpp
 *
 *  Created on: 11 Jul, 2014
 *      Author: liuwlz
 */

#ifndef SVGPATH_HPP_
#define SVGPATH_HPP_

#include <iostream>
#include <stdio.h>
#include <sstream>
#include <stdexcept>

#include <math.h>
#include <float.h>

#include <wordexp.h>
#include <vector>
#include <boost/shared_ptr.hpp>

#include <nav_msgs/Path.h>

#define DEBUG 1

using namespace std;
using namespace boost;

namespace MissionPlan{

	struct PathPoint{
		PathPoint(){};
		PathPoint(double x, double y):x_(x),y_(y){};
		double x_, y_, yaw_;
	};

	class StationPath{
	public:
		StationPath();
		~StationPath(){point_set_.clear();};

		StationPath& operator=(const StationPath &stationPathIn);
		StationPath& operator+(const StationPath &stationPathIn);

		bool exist_;
		vector<PathPoint> point_set_;
		double distance_;
		double speed_limit_;
		double congestion_;
	};

	typedef pair<string, PathPoint> StationPair;

	class SvgPath{
	public:
		SvgPath();
		SvgPath(const char* fileNameIn,double resolution);
		virtual ~SvgPath();

		virtual void loadFile(const char* fileNameIn,double resolution);
		virtual vector<string> getStationList(vector<StationPair> &stationListOut);
		virtual StationPath getStationPath(string pathNameIn);
                virtual nav_msgs::Path getStart_End(string pathNameIn);
		virtual bool checkStationPath(string pathNameIn);
		virtual double getSpeedLimit(string pathNameIn){return 0.0;};

	private:

		double resolution_;

		string tildeExpand(const char *path);
	};
}

#endif /* SVGPATH_HPP_ */


text:
/*
 * ConcreteMySqlFactory.cpp
 *
 *  Created on: May 8, 2016
 *      Author: samuele
 */
#include "ConcreteMySqlFactory.h"
#include "ConcreteMySqlConnection.h"        // for ConcreteMySqlConnection, MySQL::PreparedStatementSP, etc definition
#include "src/macisamuele/cache/LruCache.h"              // for LruCache definition
#include "src/macisamuele/logger/StderrLogger.h"         // for StderrLogger definition
#include <boost/assert.hpp>                 // for assert definition

namespace macisamuele {

ConcreteMySqlFactory::ConcreteMySqlFactory(const MySQL::MySqlConfig& iConfiguration) :
        configuration(iConfiguration), statementCache(new Cache::LruCache<std::string, MySQL::PreparedStatementSP>(10)), logger(Logger::Logger::GetLogger<Logger::StderrLogger>()) {
    CONSTRUCTOR(this);
}

ConcreteMySqlFactory::ConcreteMySqlFactory(const MySQL::MySqlCacheSP& iMySqlCache, const MySQL::MySqlConfig& iConfiguration) :
        configuration(iConfiguration), statementCache(iMySqlCache), logger(Logger::Logger::GetLogger<Logger::StderrLogger>()) {
    CONSTRUCTOR(this);
}
ConcreteMySqlFactory::ConcreteMySqlFactory(const Logger::LoggerSP& iLogger, const MySQL::MySqlCacheSP& iMySqlCache, const MySQL::MySqlConfig& iConfiguration) :
        configuration(iConfiguration), statementCache(iMySqlCache), logger(iLogger) {
    CONSTRUCTOR(this);
}

ConcreteMySqlFactory::~ConcreteMySqlFactory() {
    DESTRUCTOR(this);
}
Resource::ResourceSP ConcreteMySqlFactory::create() {
    return boost::static_pointer_cast<MySQL::MySqlConnection>(
            boost::shared_ptr<MySQL::MySqlConnection>(
                    new ConcreteMySqlConnection(logger, statementCache, configuration)
            ));
}

} /* namespace macisamuele */

max_stars_repo_name: macisamuele/mysql-connection-pool-cpp

max_issues_repo_name: macisamuele/mysql-connection-pool-cpp

max_forks_repo_name: macisamuele/mysql-connection-pool-cpp


text:
// Copyright (c) 2006-2010 Emil Dotchevski and Reverge Studios, Inc.

// 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)

#ifndef UUID_CE6983AC753411DDA764247956D89593
#define UUID_CE6983AC753411DDA764247956D89593

#include <boost/config.hpp>
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
#include <boost/type_traits/is_nothrow_move_constructible.hpp>
#endif
#include <string>
#include <utility>

#if (__GNUC__ * 100 + __GNUC_MINOR__ > 301) &&                                 \
    !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma GCC system_header
#endif
#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma warning(push, 1)
#endif

namespace boost
{
namespace exception_detail
{
class error_info_base
{
  public:
    virtual std::string name_value_string() const = 0;
    virtual error_info_base* clone() const = 0;

    virtual ~error_info_base() throw()
    {
    }
};
} // namespace exception_detail

template <class Tag, class T>
class error_info : public exception_detail::error_info_base
{
    error_info_base* clone() const
    {
        return new error_info<Tag, T>(*this);
    }

  public:
    typedef T value_type;
    error_info(value_type const& v) : v_(v)
    {
    }
#if (__GNUC__ * 100 + __GNUC_MINOR__ != 406) // workaround for g++ bug
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
    error_info(error_info const& x) : v_(x.v_)
    {
    }
    error_info(T&& v)
        BOOST_NOEXCEPT_IF(boost::is_nothrow_move_constructible<T>::value) :
        v_(std::move(v))
    {
    }
    error_info(error_info&& x)
        BOOST_NOEXCEPT_IF(boost::is_nothrow_move_constructible<T>::value) :
        v_(std::move(x.v_))
    {
    }
#endif
#endif
    ~error_info() throw()
    {
    }
    value_type const& value() const
    {
        return v_;
    }
    value_type& value()
    {
        return v_;
    }

  private:
    error_info& operator=(error_info const&);
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
    error_info& operator=(error_info&& x);
#endif
    std::string name_value_string() const;
    value_type v_;
};
} // namespace boost

#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma warning(pop)
#endif
#endif

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
//
// Copyright 2005-2007 Adobe Systems Incorporated
//
// 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
//
#ifndef BOOST_GIL_EXTENSION_DYNAMIC_IMAGE_APPLY_OPERATION_HPP
#define BOOST_GIL_EXTENSION_DYNAMIC_IMAGE_APPLY_OPERATION_HPP

#include <boost/gil/extension/dynamic_image/apply_operation_base.hpp>
#include <boost/gil/extension/dynamic_image/variant.hpp>

#ifdef BOOST_GIL_DOXYGEN_ONLY
#undef BOOST_GIL_REDUCE_CODE_BLOAT
#endif

// Implements apply_operation for variants.
// Optionally performs type reduction.
#ifdef BOOST_GIL_REDUCE_CODE_BLOAT

#include <boost/gil/extension/dynamic_image/reduce.hpp>

#else

namespace boost { namespace gil {

/// \ingroup Variant
/// \brief Invokes a generic mutable operation (represented as a unary function object) on a variant
template <typename Types, typename UnaryOp> BOOST_FORCEINLINE
typename UnaryOp::result_type apply_operation(variant<Types>& arg, UnaryOp op) {
    return apply_operation_base<Types>(arg._bits, arg._index ,op);
}

/// \ingroup Variant
/// \brief Invokes a generic constant operation (represented as a unary function object) on a variant
template <typename Types, typename UnaryOp> BOOST_FORCEINLINE
typename UnaryOp::result_type apply_operation(const variant<Types>& arg, UnaryOp op) {
    return apply_operation_basec<Types>(arg._bits, arg._index ,op);
}

/// \ingroup Variant
/// \brief Invokes a generic constant operation (represented as a binary function object) on two variants
template <typename Types1, typename Types2, typename BinaryOp> BOOST_FORCEINLINE
typename BinaryOp::result_type apply_operation(const variant<Types1>& arg1, const variant<Types2>& arg2, BinaryOp op) {
    return apply_operation_base<Types1,Types2>(arg1._bits, arg1._index, arg2._bits, arg2._index, op);
}

}}  // namespace boost::gil

#endif // defined(BOOST_GIL_REDUCE_CODE_BLOAT)

#endif


text:
// alphacommands.hpp
//
// Copyright (c) 2007, 2008 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// 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.
//
#ifndef ALPHA_COMMANDS_HPP
#define ALPHA_COMMANDS_HPP

#include <list>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/utility.hpp>

#include "utility/queue.hpp"
#include "utility/streampointer.hpp"
#include "utility/istream.hpp"
#include "utility/ostream.hpp"

#include "frame/ipc/ipcconnectionuid.hpp"
#include "frame/file/filestream.hpp"

#include "core/common.hpp"
#include "alphacommand.hpp"

namespace fs = boost::filesystem;
using boost::filesystem::path;
using boost::next;
using boost::prior;

using solid::uint32;
using solid::int32;
using solid::uint16;
using solid::int16;
using solid::uint64;
using solid::int64;

namespace solid{
namespace protocol{
namespace text{
struct Parameter;
}
}
}

namespace concept{
namespace alpha{

class Connection;
class Reader;
class Writer;
//! Basic alpha commands - with no parameters.
class Basic: public Command{
public:
	enum Types{
		Noop, Logout, Capability
	};
	Basic(Types _tp);
	~Basic();
	void initReader(Reader &);
	void execute(Connection &_rc);
private:
	void execNoop(Connection &_rc);
	void execLogout(Connection &_rc);
	void execCapability(Connection &_rc);
private:
	Types tp;
};

//! Alpha Login command
/*!
	Syntax:

	tag SP LOGIN SP astring = nume SP astring = password CRLF

*/
class Login: public Command{
public:
	Login();
	~Login();
	void initReader(Reader &);
	void execute(Connection &);
private:
	solid::String user,pass;
};
//! Alpha (remote) file fetch commad
/*!
	Syntax:

	tag SP FETCH SP astring = path [SP astring = peer_address [SP number = peer_ipc_base_port]] CRLF

	Example:

	aa fetch "/tmp/00001.txt"

	aa fetch "/tmp/00001.txt" homehost 1222

*/
class Fetch: public Command{
public:
	Fetch(Connection &);
	~Fetch();
	void initReader(Reader &);
	void execute(Connection &);
	//! Writer plugin
	/*!
		Implements the logic for requesting a file from FileManager,
		eventually wait for it, write the file on socket.

		For remote fetch the things are more complicated as we will
		use a local temp file as buffer and:

		- request a temp stream
		- when we've got the temp stream, reques the size and the first 1MB of file
		- when we've received the size and the firs 1MB, request for the next 1MB
			and write the first 1MB on socket
		- and so forth
	*/
	int reinitWriter(Writer &, solid::protocol::text::Parameter &);
	int receiveFilePointer(
		FilePointerMessage &_rmsg
	);
	/*virtual*/ int receiveMessage(solid::DynamicPointer<FetchSlaveMessage> &_rmsgptr);
private:
	enum State{
		InitLocal,
		SendLocal,
		InitRemote,
		SendFirstData,
		SendNextData,
		WaitLocalStream,
		WaitTempStream,
		WaitFirstRemoteStream,
		WaitRemoteStream,
		SendRemoteError,
		SendTempError,
		SendError,
		ReturnBad,
		ReturnOk,
		ReturnCrlf,
	};
	void doSendMaster(const solid::frame::UidT &_ruid);
	int doInitLocal();
	int doSendLiteral(Writer &_rw, bool _local);
	int doGetTempStream(uint32 _sz);
	int doSendFirstData(Writer &_rw);
	int doSendNextData(Writer &_rw);
private:
	typedef solid::frame::file::FileIOStream<256>		FileIOStreamT;
	solid::String								strpth;
	solid::String								straddr;
	solid::String								port;
	Connection									&rc;
	int16 										state;
	uint64										litsz;
	solid::protocol::text::Parameter			*pp;

	FileIOStreamT								ios;

	solid::frame::UidT							mastermsguid;
	uint32										tmpstreamcp;//temp stream capacity
	uint64										streamsz;
	uint32										streamcp;
	solid::DynamicPointer<FetchSlaveMessage>	cachedmsg;
};
//! Store a file locally
/*!
	Syntax:

	tag SP STORE SP astring = path SP '{' number = literalsize '}' CRLF literal_data CRLF

*/
class Store: public Command{
public:
	enum {Init, SendWait, PrepareReceive};
	Store(Connection &);
	~Store();
	void initReader(Reader &);
	int reinitReader(Reader &, solid::protocol::text::Parameter &);
	void execute(Connection &);
	int receiveFilePointer(FilePointerMessage &_rmsg);
	int reinitWriter(Writer &, solid::protocol::text::Parameter &);
private:
	typedef solid::frame::file::FileOStream<1024>		FileOStreamT;
	solid::String								strpth;//the file path
	FileOStreamT								os;
	Connection									&rc;
	int 										st;
	uint32										litsz;
	uint64										litsz64;
};

//! Lists one level of the requested path
/*!
	Syntax:

	tag SP LIST SP astring = path [SP astring = peer_ipc_address] [SP number=peer_ipc_port]

	If the path is a directory, the direct cildren are displayed.
	If the path is a file, the file information is displayed.
*/
class List: public Command{
public:
	enum {Step, Stop};
	List();
	~List();
	void initReader(Reader &);
	void execute(Connection &);

	int reinitWriter(Writer &, solid::protocol::text::Parameter &);
private:
	solid::String			strpth;
	fs::directory_iterator 	it,end;
};

//! Lists one level of the requested remote path
/*!
	Syntax:

	tag SP REMOTELIST SP astring = path SP astring = peer_ipc_address SP number=peer_ipc_port

	If the path is a directory, the direct cildren are displayed.
	If the path is a file, the file information is displayed.
*/
class RemoteList: public Command{
public:
	enum {Wait, SendList, SendError, SendListContinue};
	//typedef std::list<std::pair<String,int64> > PathListT;
	struct PathListT: std::list<std::pair<solid::String,int64> >{
		PathListT();
		~PathListT();
	};
	RemoteList();
	~RemoteList();
	void initReader(Reader &);
	void execute(Connection &);

	int reinitWriter(Writer &, solid::protocol::text::Parameter &);
	template <int U>
	int reinitReader(Reader &, solid::protocol::text::Parameter &);

private:
	/*virtual*/ int receiveMessage(solid::DynamicPointer<RemoteListMessage> &_rmsgptr);
private:
	struct HostAddr{
		solid::String	addr;
		solid::String	port;
		uint32			netid;
	};
	typedef std::vector<HostAddr>				HostAddrVectorT;
	typedef solid::protocol::text::Parameter	ParameterT;
	solid::String				strpth;
	HostAddrVectorT				hostvec;
	uint32						pausems;
	PathListT					*ppthlst;
	PathListT::const_iterator	it;
	int							state;
	ParameterT					*pp;
};

//! Wait for internal server events
/*!
	Use in combination with sendstream and sendstring.

	Syntax:

	tag SP IDLE CRLF

	...events are displayed ...

	done CRLF

	So the command will both wait for "done" from client and for
	events.
*/
class Idle: public Command{
public:
	Idle(Connection &_rc):rc(_rc){}
	~Idle();
	void initReader(Reader &);
	void execute(Connection &);
	int reinitWriter(Writer &, solid::protocol::text::Parameter &);
	/*virtual*/ int receiveFilePointer(
		FilePointerMessage &_rmsg
	);
	int receiveString(
		const solid::String &_str,
		int			_which,
		const ObjectUidT&_from,
		const solid::frame::ipc::ConnectionUid *_conid
	);
private:
	typedef solid::frame::file::FileIStream<1024>		FileIStreamT;
	typedef solid::frame::file::FilePointerT			FilePointerT;
	enum Type{LocalStringType, PeerStringType, LocalStreamType, PeerStreamType};
	solid::Queue<Type>										typeq;
	solid::Queue<solid::String>								stringq;
	solid::Queue<ObjectUidT>								fromq;
	solid::Queue<solid::frame::ipc::ConnectionUid>			conidq;
	solid::Queue<FilePointerT>								fileptrq;
	Connection												&rc;
	FileIStreamT											is;
	uint64													litsz64;
};

}//namespace alpha
}//namespace concept

#endif

max_stars_repo_name: joydit/solidframe

max_issues_repo_name: joydit/solidframe

max_forks_repo_name: joydit/solidframe


text:
//
// Created by huangqinjin on 7/18/17.
//
#include <glw/Widget.hpp>
#include <GL/glew.h>
#include <Eigen/Geometry>
#include <iostream>

using namespace glw;
using namespace Eigen;

class MainWindow : public Widget
{
    const bool orth;
    Affine3f T = Affine3f::Identity();

public:
    explicit MainWindow(bool orth) : orth(orth) {}

private:
    void initialize() override
    {
        glClearColor(0, 0, 0, 0);
        glShadeModel(GL_SMOOTH);
        glEnable(GL_DEPTH_TEST);

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        if(orth) glOrtho(-1, 1, -1, 1, 1, 3 /* -1 */);
        else glFrustum(-1.0, 1.0, -1.0, 1.0, 1, 100);
        glMatrixMode(GL_MODELVIEW);

        T = Translation3f(0, 0, -2.f);

        std::cout << "initialize" << std::endl;
    }

    void paintEvent(PaintEvent* e) override
    {
        // Clear the screen.
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glLoadMatrixf(T.data());
        glTranslatef(-0.5f, -0.5f, -0.5f);

        GLfloat data[8][3] = {
                {0, 0, 0},
                {1, 0, 0},
                {1, 1, 0},
                {0, 1, 0},
                {0, 1, 1},
                {0, 0, 1},
                {1, 0, 1},
                {1, 1, 1},
        };

        glBegin(GL_QUADS);
        glColor3fv(data[0]); glVertex3fv(data[0]);
        glColor3fv(data[1]); glVertex3fv(data[1]);
        glColor3fv(data[2]); glVertex3fv(data[2]);
        glColor3fv(data[3]); glVertex3fv(data[3]);

        glColor3fv(data[2]); glVertex3fv(data[2]);
        glColor3fv(data[3]); glVertex3fv(data[3]);
        glColor3fv(data[4]); glVertex3fv(data[4]);
        glColor3fv(data[7]); glVertex3fv(data[7]);

        glColor3fv(data[4]); glVertex3fv(data[4]);
        glColor3fv(data[7]); glVertex3fv(data[7]);
        glColor3fv(data[6]); glVertex3fv(data[6]);
        glColor3fv(data[5]); glVertex3fv(data[5]);

        glColor3fv(data[6]); glVertex3fv(data[6]);
        glColor3fv(data[5]); glVertex3fv(data[5]);
        glColor3fv(data[0]); glVertex3fv(data[0]);
        glColor3fv(data[1]); glVertex3fv(data[1]);

        glColor3fv(data[0]); glVertex3fv(data[0]);
        glColor3fv(data[3]); glVertex3fv(data[3]);
        glColor3fv(data[4]); glVertex3fv(data[4]);
        glColor3fv(data[5]); glVertex3fv(data[5]);

        glColor3fv(data[1]); glVertex3fv(data[1]);
        glColor3fv(data[2]); glVertex3fv(data[2]);
        glColor3fv(data[7]); glVertex3fv(data[7]);
        glColor3fv(data[6]); glVertex3fv(data[6]);
        glEnd();

        // Draw the scene:
//        glBegin(GL_TRIANGLES);
//        glColor3f(1.0f, 0.0f, 0.0f);
//        glVertex3f(-1, -1, 0.0);
//
//        glColor3f(0.0f, 1.0f, 0.0f);
//        glVertex3f(1, 0.0, 0.0);
//
//        glColor3f(0.0f, 0.0f, 1.0f);
//        glVertex3f(0.0, 1, 0.0);
//        glEnd();
//
//        repaint(1);
        std::cout << "paint " << e->dt << std::endl;
    }

    void keyEvent(KeyEvent* e) override
    {
        std::cout << "key " << (char)e->key << ' ' << (int)e->action << std::endl;
    }

    void mouseEvent(MouseEvent* e) override
    {
        std::cout << "mouse " << (int)e->button << ' ' << (int)e->action << std::endl;
        if(e->button == MouseButton::MIDDLE && e->action == KeyAction::RELEASE)
        {
            initialize();
            repaint();
        }
    }

    void wheelEvent(WheelEvent* e) override
    {
        std::cout << "wheel " << e->dx << std::endl;

        if(orth) T.linear() *= (1 + e->dx * 0.1f);
        else T.translation() += Vector3f(0, 0, -e->dx * 0.1f);
        repaint();
    }

    void cursorEvent(CursorEvent* e) override
    {
        if(KeyAction::PRESS == status(MouseButton::LEFT))
        {
            Vector3f axis(e->dp.y, e->dp.x, 0);
            T.linear() = AngleAxisf(axis.norm() * 0.01f, axis.normalized()) * T.linear();
        }
        else if(KeyAction::PRESS == status(MouseButton::RIGHT))
        {
            Vector3f dir(e->dp.x, -e->dp.y, 0);
            T.translation() += dir * 0.01f;
        }
        else
        {
            return;
        }
        repaint();
        std::cout << "cursor " << ' ' << (int)e->action << ' ' << e->dp.x << ' ' << e->dp.y << std::endl;
    }

    void moveEvent(MoveEvent* e) override
    {
        std::cout << "move " << e->dp.x << ' ' << e->dp.y << std::endl;
    }

    void resizeEvent(SizeEvent* e) override
    {
        auto sz = size();
        auto s = static_cast<GLsizei>((std::min)(sz.w, sz.h));
        glViewport(0, 0, s, s);

        std::cout << "resize " << e->dz.w << ' ' << e->dz.h << std::endl;
    }

    void closeEvent() override
    {
        close();
        std::cout << "close" << std::endl;
    }
};

int main(int argc, char* argv[])
{
    std::cout << "STDCPP_DEFAULT_NEW_ALIGNMENT = "
              #ifdef __STDCPP_DEFAULT_NEW_ALIGNMENT__
              << __STDCPP_DEFAULT_NEW_ALIGNMENT__
              #else
              << "NULL"
              #endif
              << "    EIGEN_MAX_STATIC_ALIGN_BYTES = "
              << EIGEN_MAX_STATIC_ALIGN_BYTES
              << std::endl;

    Application app(argc, argv);
    MainWindow w(argc <= 1);
    w.rename("MainWindow");
    w.resize({200, 200});
    w.show();
    return app.exec();
}

max_stars_repo_name: huangqinjin/glw

max_issues_repo_name: huangqinjin/glw

max_forks_repo_name: huangqinjin/glw


text:
#pragma once

#include <boost/multiprecision/cpp_int.hpp>

#include <crypto/cryptopp/osrng.h>

namespace nano
{
using uint128_t = boost::multiprecision::uint128_t;
using uint256_t = boost::multiprecision::uint256_t;
using uint512_t = boost::multiprecision::uint512_t;
// SI dividers
nano::uint128_t const Gxrb_ratio = nano::uint128_t ("1000000000000000000000000000000000"); // 10^33
nano::uint128_t const Mxrb_ratio = nano::uint128_t ("1000000000000000000000000000000"); // 10^30
nano::uint128_t const kxrb_ratio = nano::uint128_t ("1000000000000000000000000000"); // 10^27
nano::uint128_t const xrb_ratio = nano::uint128_t ("1000000000000000000000000"); // 10^24
nano::uint128_t const raw_ratio = nano::uint128_t ("1"); // 10^0

union uint128_union final
{
public:
	uint128_union () = default;
	/**
	 * Decode from hex string
	 * @warning Aborts at runtime if the input is invalid
	 */
	uint128_union (std::string const &);
	uint128_union (uint64_t);
	uint128_union (nano::uint128_t const &);
	bool operator== (nano::uint128_union const &) const;
	bool operator!= (nano::uint128_union const &) const;
	bool operator< (nano::uint128_union const &) const;
	bool operator> (nano::uint128_union const &) const;
	void encode_hex (std::string &) const;
	bool decode_hex (std::string const &);
	void encode_dec (std::string &) const;
	bool decode_dec (std::string const &, bool = false);
	bool decode_dec (std::string const &, nano::uint128_t);
	std::string format_balance (nano::uint128_t scale, int precision, bool group_digits);
	std::string format_balance (nano::uint128_t scale, int precision, bool group_digits, const std::locale & locale);
	nano::uint128_t number () const;
	void clear ();
	bool is_zero () const;
	std::string to_string () const;
	std::string to_string_dec () const;
	std::array<uint8_t, 16> bytes;
	std::array<char, 16> chars;
	std::array<uint32_t, 4> dwords;
	std::array<uint64_t, 2> qwords;
};
// Balances are 128 bit.
using amount = uint128_union;
class raw_key;
union uint256_union final
{
	uint256_union () = default;
	/**
	 * Decode from hex string
	 * @warning Aborts at runtime if the input is invalid
	 */
	uint256_union (std::string const &);
	uint256_union (uint64_t);
	uint256_union (nano::uint256_t const &);
	void encrypt (nano::raw_key const &, nano::raw_key const &, uint128_union const &);
	uint256_union & operator^= (nano::uint256_union const &);
	uint256_union operator^ (nano::uint256_union const &) const;
	bool operator== (nano::uint256_union const &) const;
	bool operator!= (nano::uint256_union const &) const;
	bool operator< (nano::uint256_union const &) const;
	void encode_hex (std::string &) const;
	bool decode_hex (std::string const &);
	void encode_dec (std::string &) const;
	bool decode_dec (std::string const &);
	void encode_account (std::string &) const;
	std::string to_account () const;
	bool decode_account (std::string const &);
	std::array<uint8_t, 32> bytes;
	std::array<char, 32> chars;
	std::array<uint32_t, 8> dwords;
	std::array<uint64_t, 4> qwords;
	std::array<uint128_union, 2> owords;
	void clear ();
	bool is_zero () const;
	std::string to_string () const;
	nano::uint256_t number () const;
};
// All keys and hashes are 256 bit.
using block_hash = uint256_union;
using account = uint256_union;
using public_key = uint256_union;
using private_key = uint256_union;
using secret_key = uint256_union;
class raw_key final
{
public:
	~raw_key ();
	void decrypt (nano::uint256_union const &, nano::raw_key const &, uint128_union const &);
	bool operator== (nano::raw_key const &) const;
	bool operator!= (nano::raw_key const &) const;
	nano::uint256_union data;
};
union uint512_union final
{
	uint512_union () = default;
	uint512_union (nano::uint256_union const &, nano::uint256_union const &);
	uint512_union (nano::uint512_t const &);
	bool operator== (nano::uint512_union const &) const;
	bool operator!= (nano::uint512_union const &) const;
	nano::uint512_union & operator^= (nano::uint512_union const &);
	void encode_hex (std::string &) const;
	bool decode_hex (std::string const &);
	std::array<uint8_t, 64> bytes;
	std::array<uint32_t, 16> dwords;
	std::array<uint64_t, 8> qwords;
	std::array<uint256_union, 2> uint256s;
	void clear ();
	bool is_zero () const;
	nano::uint512_t number () const;
	std::string to_string () const;
};
using signature = uint512_union;
using qualified_root = uint512_union;

nano::uint512_union sign_message (nano::raw_key const &, nano::public_key const &, nano::uint256_union const &);
bool validate_message (nano::public_key const &, nano::uint256_union const &, nano::uint512_union const &);
bool validate_message_batch (const unsigned char **, size_t *, const unsigned char **, const unsigned char **, size_t, int *);
void deterministic_key (nano::uint256_union const &, uint32_t, nano::uint256_union &);
nano::public_key pub_key (nano::private_key const &);

/* Conversion methods */
std::string to_string_hex (uint64_t const);
bool from_string_hex (std::string const &, uint64_t &);

/**
 * Convert a double to string in fixed format
 * @param precision_a (optional) use a specific precision (default is the maximum)
 */
std::string to_string (double const, int const precision_a = std::numeric_limits<double>::digits10);

namespace difficulty
{
	uint64_t from_multiplier (double const, uint64_t const);
	double to_multiplier (uint64_t const, uint64_t const);
}
}

namespace std
{
template <>
struct hash<::nano::uint256_union>
{
	size_t operator() (::nano::uint256_union const & data_a) const
	{
		return *reinterpret_cast<size_t const *> (data_a.bytes.data ());
	}
};
template <>
struct hash<::nano::uint256_t>
{
	size_t operator() (::nano::uint256_t const & number_a) const
	{
		return number_a.convert_to<size_t> ();
	}
};
template <>
struct hash<::nano::uint512_union>
{
	size_t operator() (::nano::uint512_union const & data_a) const
	{
		return *reinterpret_cast<size_t const *> (data_a.bytes.data ());
	}
};
}

max_stars_repo_name: orhanhenrik/nano-node

max_issues_repo_name: orhanhenrik/nano-node

max_forks_repo_name: orhanhenrik/nano-node


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

// Author: David Alexander

#include <ConsensusCore/Quiver/detail/RecursorBase.hpp>

#include <ConsensusCore/Align/PairwiseAlignment.hpp>
#include <ConsensusCore/LValue.hpp>
#include <ConsensusCore/Logging.hpp>
#include <ConsensusCore/Matrix/DenseMatrix.hpp>
#include <ConsensusCore/Matrix/SparseMatrix.hpp>
#include <ConsensusCore/Quiver/detail/Combiner.hpp>
#include <ConsensusCore/Edna/EdnaEvaluator.hpp>
#include <ConsensusCore/Quiver/QuiverConfig.hpp>
#include <ConsensusCore/Quiver/QvEvaluator.hpp>
#include <ConsensusCore/Types.hpp>
#include <ConsensusCore/Utils.hpp>

#include <algorithm>
#include <boost/type_traits.hpp>
#include <string>
#include <vector>

// TODO(dalexander): put these into a RecursorConfig struct
#define MAX_FLIP_FLOPS                  5
#define ALPHA_BETA_MISMATCH_TOLERANCE   0.2
#define REBANDING_THRESHOLD             0.04

using std::max;
using std::min;

namespace ConsensusCore {
namespace detail {

    template<typename M, typename E, typename C>
    int
    RecursorBase<M, E, C>::FillAlphaBeta(const E& e, M& a, M& b) const
        throw(AlphaBetaMismatchException)
    {
        FillAlpha(e, M::Null(), a);
        FillBeta(e, a, b);

        int I = e.ReadLength();
        int J = e.TemplateLength();
        int flipflops = 0;
        int maxSize = static_cast<int>(0.5 + REBANDING_THRESHOLD * (I + 1) * (J + 1));

        // if we use too much space, do at least one more round
        // to take advantage of rebanding
        if (a.UsedEntries() >= maxSize ||
            b.UsedEntries() >= maxSize)
        {
            FillAlpha(e, b, a);
            FillBeta(e, a, b);
            FillAlpha(e, b, a);
            flipflops += 3;
        }

        while (fabs(a(I, J) - b(0, 0)) > ALPHA_BETA_MISMATCH_TOLERANCE
               && flipflops <= MAX_FLIP_FLOPS)
        {
            if (flipflops % 2 == 0)
            {
                FillAlpha(e, b, a);
            }
            else
            {
                FillBeta(e, a, b);
            }
            flipflops++;
        }

        if (fabs(a(I, J) - b(0, 0)) > ALPHA_BETA_MISMATCH_TOLERANCE)
        {
            LDEBUG << "Could not mate alpha, beta.  Read: "
                   << e.ReadName() << " Tpl: " << e.Template();
            throw AlphaBetaMismatchException();
        }

        return flipflops;
    }

    struct MoveSpec {
        Move MoveType;
        int ReadDelta;
        int ReferenceDelta;
    };

    template<typename M, typename E, typename C>
    const PairwiseAlignment*
    RecursorBase<M, E, C>::Alignment(const E& e, const M& a) const
    {
        if (!boost::is_same<C, ViterbiCombiner>::value)
        {
            ShouldNotReachHere();
        }

        int I, J;
        I = e.ReadLength();
        J = e.TemplateLength();

        // Matrix must be filled in before requesting traceback
        assert(a(I, J) != lfloat());

        int i = I;
        int j = J;
        float pathScore = 0;

        MoveSpec incMove   = { INCORPORATE, 1, 1 };
        MoveSpec delMove   = { DELETE,      0, 1 };
        MoveSpec extraMove = { EXTRA,       1, 0 };
        MoveSpec mergeMove = { MERGE,       1, 2 };
        std::vector<MoveSpec> moves;

        while (i > 0 || j > 0)
        {
            MoveSpec bestMove = { INVALID_MOVE, 0, 0 };
            float prevScore, moveScore, totalScore;
            float bestScore = lfloat();
            float bestMoveScore = lfloat();

            if (i > 0 && j > 0)
            {
                prevScore = a(i - 1, j - 1);
                moveScore = e.Inc(i - 1, j - 1);
                totalScore = prevScore + moveScore;
                if (totalScore > bestScore)
                {
                    // Incorporate (match or mismatch)
                    bestMove = incMove;
                    bestScore = totalScore;
                    bestMoveScore = moveScore;
                }
            }

            if (j > 0)
            {
                // Delete
                prevScore = a(i, j - 1);
                bool freeDelete = (!e.PinEnd() && i == I) || (!e.PinStart() && i == 0);
                moveScore = freeDelete ? 0 : e.Del(i, j - 1);
                totalScore = prevScore + moveScore;
                if (totalScore > bestScore)
                {
                    bestMove = delMove;
                    bestScore = totalScore;
                    bestMoveScore = moveScore;
                }
            }

            if (i > 0)
            {
                // Extra
                prevScore = a(i - 1, j);
                moveScore = e.Extra(i - 1, j);
                totalScore = prevScore + moveScore;
                if (totalScore > bestScore)
                {
                    bestMove = extraMove;
                    bestScore = totalScore;
                    bestMoveScore = moveScore;
                }
            }

            if ((movesAvailable_ & MERGE) && i > 0 && j > 1)
            {
                // Merge
                prevScore = a(i - 1, j - 2);
                moveScore = e.Merge(i - 1, j - 2);
                totalScore = prevScore + moveScore;
                if (totalScore > bestScore)
                {
                    bestMove = mergeMove;
                    bestScore = totalScore;
                    bestMoveScore = moveScore;
                }
            }
            assert(AlmostEqual(a(i, j), bestScore));
            assert(bestMove.MoveType != INVALID_MOVE);
            assert(bestMoveScore != lfloat());

            moves.push_back(bestMove);
            i -= bestMove.ReadDelta;
            j -= bestMove.ReferenceDelta;
            pathScore += bestMoveScore;
        }
        assert(i == 0 && j == 0);

        // Reverse moves
        std::reverse(moves.begin(), moves.end());

        // Replay moves and stringify.
        std::string target;
        std::string query;
        i = 0;
        j = 0;
        foreach (const MoveSpec& move, moves)
        {
            switch (move.MoveType) {
            case INCORPORATE:
                target     += e.Template()[j];
                query      += e.Basecalls()[i];
                break;
            case EXTRA:
                target     += '-';
                query      += e.Basecalls()[i];
                break;
            case DELETE:
                target     += e.Template()[j];
                query      += '-';
                break;
            case MERGE:
                target     += e.Template()[j];
                target     += e.Template()[j+1];
                query      += '-';
                query      += e.Basecalls()[i];
                break;
            case INVALID_MOVE:
                ShouldNotReachHere();
                break;
            default:
                ShouldNotReachHere();
            }
            i += move.ReadDelta;
            j += move.ReferenceDelta;
            assert(target.length() == query.length());
        }

        return new PairwiseAlignment(target, query);
    }

    template<typename M, typename E, typename C>
    RecursorBase<M, E, C>::RecursorBase(int movesAvailable, const BandingOptions& bandingOptions)
        : movesAvailable_(movesAvailable),
          bandingOptions_(bandingOptions)
    {}

    template<typename M, typename E, typename C>
    RecursorBase<M, E, C>::~RecursorBase()
    {}

    // template instantiation
    template class RecursorBase<DenseMatrixF, QvEvaluator, ViterbiCombiner>;
    template class RecursorBase<SparseMatrixF, QvEvaluator, ViterbiCombiner>;
    template class RecursorBase<SparseMatrixF, QvEvaluator, SumProductCombiner>;
    template class RecursorBase<SparseMatrixF, EdnaEvaluator, SumProductCombiner>;
}}

max_stars_repo_name: pb-cdunn/pbccs

max_issues_repo_name: pb-cdunn/pbccs

max_forks_repo_name: pb-cdunn/pbccs


text:
// Copyright Aleksey Gurtovoy 2001-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)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Source: /CVSROOT/boost/libs/mpl/test/insert_range.cpp,v $
// $Date: 2007/10/29 07:32:56 $
// $Revision: 1.1.1.1 $

#include <boost/mpl/insert_range.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/list.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/equal.hpp>

#include <boost/mpl/aux_/test.hpp>

MPL_TEST_CASE()
{
    typedef vector_c<int,0,1,7,8,9> numbers;
    typedef find< numbers,integral_c<int,7> >::type pos;
    typedef insert_range< numbers,pos,range_c<int,2,7> >::type range;

    MPL_ASSERT_RELATION( size<range>::value, ==, 10 );
    MPL_ASSERT(( equal< range,range_c<int,0,10> > ));

    typedef insert_range< list0<>,end< list0<> >::type,list1<int> >::type result2;
    MPL_ASSERT_RELATION( size<result2>::value, ==, 1 );
}

max_stars_repo_name: hackerlank/SourceCode

max_issues_repo_name: shacojx/SourceCodeGameTLBB

max_forks_repo_name: shacojx/SourceCodeGameTLBB


text:
/**
    Copyright 2007-2020 Red Anchor Trading Co. Ltd.

    Distributed under the Boost Software License, Version 1.0.
    See <http://www.boost.org/LICENSE_1_0.txt>
 */

#ifndef FOST_PARSE_JSON_HPP
#define FOST_PARSE_JSON_HPP
#pragma once

#include <fost/json.hpp>
#include <fost/unicode.hpp>
#include <fost/parse/parse.hpp>

#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi_eps.hpp>
#include <boost/fusion/include/std_pair.hpp>

namespace fostlib {

    template<typename Iterator>
    struct json_string_parser :
    public boost::spirit::qi::grammar<Iterator, string()> {
        static_assert(
                sizeof(decltype(*Iterator())) == 2,
                "The JSON parsing iterator must produce UTF-16");

        boost::spirit::qi::rule<Iterator, string()> top;
        boost::spirit::qi::rule<Iterator, std::vector<char16_t>()> str;
        boost::spirit::qi::rule<Iterator, char16_t> escaped;

        json_string_parser() : json_string_parser::base_type(top) {
            using boost::spirit::qi::_1;
            using boost::spirit::qi::_val;
            using boost::spirit::qi::lit;

            top = str[boost::phoenix::bind(
                    [](auto &v, auto &s) {
                        auto pos = f5::cord::make_u16u32_iterator<
                                exceptions::unicode_encoding>(
                                s.begin(), s.end());
                        for (; pos.first != pos.second; ++pos.first) {
                            v += *pos.first;
                        }
                    },
                    _val, _1)];

            str = lit('"')
                    >> *((lit('\\') > escaped)
                         | (boost::spirit::qi::standard_wide::char_ - '"'))
                    >> lit('"');

            escaped = boost::spirit::qi::char_('"')[_val = '"']
                    | boost::spirit::qi::char_('\\')[_val = '\\']
                    | boost::spirit::qi::char_('/')[_val = '/']
                    | boost::spirit::qi::char_('b')[_val = 0x08]
                    | boost::spirit::qi::char_('f')[_val = 0x0c]
                    | boost::spirit::qi::char_('n')[_val = '\n']
                    | boost::spirit::qi::char_('r')[_val = '\r']
                    | boost::spirit::qi::char_('t')[_val = '\t']
                    | (lit('u') >> boost::spirit::qi::uint_parser<
                               char16_t, 16, 4, 4>())[_val = _1];
        }
    };

    /// Support a limited JSON string that is not allowed to have \uXXXX escapes
    /// in it
    template<typename Iterator>
    struct json_string_parser_no_unicode_escapes :
    public boost::spirit::qi::grammar<Iterator, string()> {
        static_assert(
                sizeof(decltype(*Iterator())) == 1,
                "The JSON parsing iterator must produce UTF-8");

        boost::spirit::qi::rule<Iterator, string()> top;
        boost::spirit::qi::rule<Iterator, std::string()> str;
        boost::spirit::qi::rule<Iterator, char()> escaped;

        json_string_parser_no_unicode_escapes()
        : json_string_parser_no_unicode_escapes::base_type(top) {
            using boost::spirit::qi::_1;
            using boost::spirit::qi::_val;
            using boost::spirit::qi::lit;

            top = str[boost::phoenix::bind(
                    [](auto &v, auto &s) { v = f5::u8string{std::move(s)}; },
                    _val, _1)];

            str = lit('"')
                    >> *((lit('\\') > escaped)
                         | (boost::spirit::qi::standard_wide::char_ - '"'))
                    >> lit('"');

            escaped = boost::spirit::qi::char_('"')[_val = '"']
                    | boost::spirit::qi::char_('\\')[_val = '\\']
                    | boost::spirit::qi::char_('/')[_val = '/']
                    | boost::spirit::qi::char_('b')[_val = 0x08]
                    | boost::spirit::qi::char_('f')[_val = 0x0c]
                    | boost::spirit::qi::char_('n')[_val = '\n']
                    | boost::spirit::qi::char_('r')[_val = '\r']
                    | boost::spirit::qi::char_('t')[_val = '\t'];
        }
    };

    template<typename Iterator, template<typename> typename Sp = json_string_parser>
    struct json_embedded_parser :
    public boost::spirit::qi::grammar<Iterator, json()> {
        using object_pair_t = std::pair<string, json>;

        boost::spirit::qi::rule<Iterator, json()> top, atom, null, boolean,
                number;
        boost::spirit::qi::rule<Iterator, object_pair_t()> object_pair;
        boost::spirit::qi::rule<Iterator, json::object_t()> object,
                object_array;
        boost::spirit::qi::rule<Iterator, json::array_t()> array, array_list;
        boost::spirit::qi::real_parser<
                double,
                boost::spirit::qi::strict_real_policies<double>>
                real_p;
        Sp<Iterator> json_string_p;
        boost::spirit::qi::rule<Iterator, void()> whitespace;

        json_embedded_parser() : json_embedded_parser::base_type(top) {
            using boost::spirit::qi::_1;
            using boost::spirit::qi::_val;

            /// A non-capture whitespace parser
            whitespace = *(boost::spirit::qi::lit(' ') | '\n' | '\t' | '\r');

            top = object | array | atom;

            object =
                    (boost::spirit::qi::lit('{') >> whitespace >> -object_array
                     >> whitespace >> boost::spirit::qi::lit('}'));
            object_pair =
                    (json_string_p >> whitespace >> boost::spirit::qi::lit(':')
                     >> whitespace >> top);
            object_array = object_pair
                    % (whitespace >> boost::spirit::qi::lit(',') >> whitespace);

            array =
                    (boost::spirit::qi::lit('[') >> whitespace >> -array_list
                     >> whitespace >> boost::spirit::qi::lit(']'));
            array_list = top
                    % (whitespace >> boost::spirit::qi::lit(',') >> whitespace);

            null = boost::spirit::qi::string("null")[_val = json()];
            boolean = boost::spirit::qi::string("false")[_val = json(false)]
                    | boost::spirit::qi::string("true")[_val = json(true)];
            number = real_p[_val = _1]
                    | boost::spirit::qi::int_parser<int64_t>()[_val = _1];

            atom = null | boolean | number | json_string_p;
        }
    };

    template<typename Iterator, template<typename> typename Sp = json_string_parser>
    struct sloppy_json_embedded_parser :
    public boost::spirit::qi::grammar<Iterator, json()> {
        using object_pair_t = std::pair<string, json>;

        boost::spirit::qi::rule<Iterator, void()> comment;
        boost::spirit::qi::rule<Iterator, void()> oneline_comment;
        boost::spirit::qi::rule<Iterator, void()> multiline_comment;

        boost::spirit::qi::rule<Iterator, json()> top, atom, null, boolean,
                number;
        boost::spirit::qi::rule<Iterator, object_pair_t()> object_pair;
        boost::spirit::qi::rule<Iterator, json::object_t()> object,
                object_array;
        boost::spirit::qi::rule<Iterator, json::array_t()> array, array_list;
        boost::spirit::qi::real_parser<
                double,
                boost::spirit::qi::strict_real_policies<double>>
                real_p;
        Sp<Iterator> json_string_p;
        boost::spirit::qi::rule<Iterator, string()> json_string;

        boost::spirit::qi::rule<Iterator, void()> whitespace;

        sloppy_json_embedded_parser()
        : sloppy_json_embedded_parser::base_type(top) {
            using boost::spirit::qi::_1;
            using boost::spirit::qi::_val;

            /// A non-capture whitespace parser
            whitespace =
                    *(boost::spirit::qi::lit(' ') | '\n' | '\t' | '\r' | ','
                      | comment);

            top = object | array | atom;

            oneline_comment = boost::spirit::qi::lit("//")
                    >> *(boost::spirit::qi::standard_wide::char_ - '\n')
                    >> -boost::spirit::qi::lit('\n');

            multiline_comment = boost::spirit::qi::lit("/*")
                    >> *(boost::spirit::qi::standard_wide::char_
                         - boost::spirit::qi::lit("*/"))
                    >> boost::spirit::qi::lit("*/");

            comment = oneline_comment | multiline_comment;

            object = whitespace >> boost::spirit::qi::lit('{') >> whitespace
                    >> -object_array >> whitespace
                    >> boost::spirit::qi::lit('}') >> whitespace;
            object_pair =
                    (json_string_p >> whitespace >> boost::spirit::qi::lit(':')
                     >> whitespace >> top);
            object_array = object_pair % whitespace;

            array = whitespace >> boost::spirit::qi::lit('[') >> whitespace
                    >> -array_list >> whitespace >> boost::spirit::qi::lit(']')
                    >> whitespace;
            array_list = top % whitespace;

            null = whitespace
                    >> boost::spirit::qi::string("null")[_val = json()]
                    >> whitespace;
            boolean = whitespace >> boost::spirit::qi::string(
                              "false")[_val = json(false)]
                            >> whitespace
                    | whitespace >> boost::spirit::qi::string(
                              "true")[_val = json(true)]
                            >> whitespace;
            number = whitespace >> real_p[_val = _1] >> whitespace
                    | whitespace
                            >> boost::spirit::qi::int_parser<int64_t>()[_val = _1]
                            >> whitespace;

            json_string = whitespace >> json_string_p >> whitespace;

            atom = null | boolean | number | json_string;
        }
    };

    template<typename Iterator, template<typename> typename Sp = json_string_parser>
    struct json_parser : boost::spirit::qi::grammar<Iterator, json()> {
        boost::spirit::qi::rule<Iterator, json()> top;
        json_embedded_parser<Iterator, Sp> embedded;

        json_parser() : json_parser::base_type(top) {
            using boost::spirit::qi::_2;
            using boost::spirit::qi::_val;

            top = (*boost::spirit::qi::space >> embedded
                   >> *boost::spirit::qi::space)[_val = _2];
        }
    };

    template<typename Iterator, template<typename> typename Sp = json_string_parser>
    struct sloppy_json_parser : boost::spirit::qi::grammar<Iterator, json()> {
        boost::spirit::qi::rule<Iterator, json()> top;
        sloppy_json_embedded_parser<Iterator, Sp> sloppy;

        sloppy_json_parser() : sloppy_json_parser::base_type(top) {
            using boost::spirit::qi::_2;
            using boost::spirit::qi::_val;
            top = (*boost::spirit::qi::space >> sloppy
                   >> *boost::spirit::qi::space)[_val = _2];
        }
    };

}

#endif // FOST_PARSE_JSON_HPP

max_stars_repo_name: KayEss/fost-base

max_issues_repo_name: KayEss/fost-base

max_forks_repo_name: KayEss/fost-base


text:
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// 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)

#ifndef BOOST_PROCESS_WINDOWS_SHELL_PATH_HPP
#define BOOST_PROCESS_WINDOWS_SHELL_PATH_HPP

#include <process/detail/config.hpp>
#include <system_error>
#include <boost/filesystem/path.hpp>
#include <boost/detail/winapi/basic_types.hpp>
#include <boost/detail/winapi/get_system_directory.hpp>

namespace ets { namespace process { namespace detail { namespace windows {

inline boost::filesystem::path shell_path()
{
    ::boost::detail::winapi::WCHAR_ sysdir[260];
    unsigned int size = ::boost::detail::winapi::get_system_directory(sysdir, sizeof(sysdir));
    if (!size)
        throw_last_error("GetSystemDirectory() failed");

    boost::filesystem::path p = sysdir;
    return p / "cmd.exe";
}

inline boost::filesystem::path shell_path(std::error_code &ec) BOOST_NOEXCEPT
{

    ::boost::detail::winapi::WCHAR_ sysdir[260];
    unsigned int size = ::boost::detail::winapi::get_system_directory(sysdir, sizeof(sysdir));
    boost::filesystem::path p;
    if (!size)
        ec = std::error_code(
                ::boost::detail::winapi::GetLastError(),
                std::system_category());
    else
    {
        ec.clear();
        p = sysdir;
        p /= "cmd.exe";
    }
    return p;
}

}}}}

#endif

max_stars_repo_name: ets-ddui/ets

max_issues_repo_name: ets-ddui/ets

max_forks_repo_name: ets-ddui/ets