text:
/* -*- c++ -*- */
/*
 * Copyright 2006,2013,2015 Free Software Foundation, Inc.
 *
 * This file is part of GNU Radio
 *
 * GNU Radio is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * GNU Radio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <gnuradio/prefs.h>
#include <gnuradio/sys_paths.h>
#include <gnuradio/constants.h>

#include <algorithm>
#include <fstream>
#include <iostream>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/program_options.hpp>
#include <boost/foreach.hpp>
namespace fs = boost::filesystem;
namespace po = boost::program_options;
typedef std::ifstream::char_type char_t;

namespace gr {

  prefs *
  prefs::singleton()
  {
    static prefs instance; // Guaranteed to be destroyed.
                            // Instantiated on first use.
    return &instance;
  }

  prefs::prefs()
  {
    _read_files(_sys_prefs_filenames());
  }

  prefs::~prefs()
  {
    // nop
  }

  std::vector<std::string>
  prefs::_sys_prefs_filenames()
  {
    std::vector<std::string> fnames;

    fs::path dir = prefsdir();
    if(!fs::is_directory(dir))
      return fnames;

    fs::directory_iterator diritr(dir);
    while(diritr != fs::directory_iterator()) {
      fs::path p = *diritr++;
      if(p.extension() == ".conf")
        fnames.push_back(p.string());
    }
    std::sort(fnames.begin(), fnames.end());

    // Find if there is a ~/.gnuradio/config.conf file and add this to
    // the end of the file list to override any preferences in the
    // installed path config files.
    fs::path userconf = fs::path(gr::userconf_path()) / "config.conf";
    if(fs::exists(userconf)) {
      fnames.push_back(userconf.string());
    }

    return fnames;
  }

  void
  prefs::_read_files(const std::vector<std::string> &filenames)
  {
    BOOST_FOREACH( std::string fname, filenames) {
      std::ifstream infile(fname.c_str());
      if(infile.good()) {
        try {
          po::basic_parsed_options<char_t> parsed = po::parse_config_file(infile, po::options_description(), true);
          BOOST_FOREACH(po::basic_option<char_t> o, (parsed.options) ){
            std::string okey = o.string_key;
            size_t pos = okey.find(".");
            std::string section, key;
            if(pos != std::string::npos) {
              section = okey.substr(0,pos);
              key = okey.substr(pos+1);
            } else {
              section = "default";
              key = okey;
            }
            std::transform(section.begin(), section.end(), section.begin(), ::tolower);
            std::transform(key.begin(), key.end(), key.begin(), ::tolower);
            // value of a basic_option is always a std::vector<string>; we only allow single values, so:
            std::string value = o.value[0];
            d_config_map[section][key] = value;
          }
        } catch(std::exception e) {
          std::cerr << "WARNING: Config file '" << fname << "' failed to parse:" << std::endl;
          std::cerr << e.what() << std::endl;
          std::cerr << "Skipping it" << std::endl;
        }
      } else { // infile.good();
        std::cerr << "WARNING: Config file '" << fname << "' could not be opened for reading." << std::endl;
      }
    }
  }

  void
  prefs::add_config_file(const std::string &configfile)
  {
    std::vector<std::string> filenames;
    filenames.push_back(configfile);

    _read_files(filenames);
  }

  std::string
  prefs::to_string()
  {
    config_map_itr sections;
    config_map_elem_itr options;
    std::stringstream s;

    for(sections = d_config_map.begin(); sections != d_config_map.end(); sections++) {
      s << "[" << sections->first << "]" << std::endl;
      for(options = sections->second.begin(); options != sections->second.end(); options++) {
        s << options->first << " = " << options->second << std::endl;
      }
      s << std::endl;
    }

    return s.str();
  }

  void
  prefs::save()
  {
    std::string conf = to_string();
    fs::path userconf = fs::path(gr::userconf_path()) / "config.conf";
    fs::ofstream fout(userconf);
    fout << conf;
    fout.close();
  }

  char *
  prefs::option_to_env(std::string section, std::string option)
  {
    std::stringstream envname;
    std::string secname=section, optname=option;

    std::transform(section.begin(), section.end(), secname.begin(), ::toupper);
    std::transform(option.begin(), option.end(), optname.begin(), ::toupper);
    envname << "GR_CONF_" << secname << "_" << optname;

    return getenv(envname.str().c_str());
  }

  bool
  prefs::has_section(const std::string &section)
  {
    std::string s = section;
    std::transform(section.begin(), section.end(), s.begin(), ::tolower);
    return d_config_map.count(s) > 0;
  }

  bool
  prefs::has_option(const std::string &section, const std::string &option)
  {
    if(option_to_env(section, option))
      return true;

    if(has_section(section)) {
      std::string s = section;
      std::transform(section.begin(), section.end(), s.begin(), ::tolower);

      std::string o = option;
      std::transform(option.begin(), option.end(), o.begin(), ::tolower);

      config_map_itr sec = d_config_map.find(s);
      return sec->second.count(o) > 0;
    }
    else {
      return false;
    }
  }

  const std::string
  prefs::get_string(const std::string &section, const std::string &option,
                    const std::string &default_val)
  {
    char *env = option_to_env(section, option);
    if(env)
      return std::string(env);

    if(has_option(section, option)) {
      std::string s = section;
      std::transform(section.begin(), section.end(), s.begin(), ::tolower);

      std::string o = option;
      std::transform(option.begin(), option.end(), o.begin(), ::tolower);

      config_map_itr sec = d_config_map.find(s);
      config_map_elem_itr opt = sec->second.find(o);
      return opt->second;
    }
    else {
      return default_val;
    }
  }

  void
  prefs::set_string(const std::string &section, const std::string &option,
                    const std::string &val)
  {
    std::string s = section;
    std::transform(section.begin(), section.end(), s.begin(), ::tolower);

    std::string o = option;
    std::transform(option.begin(), option.end(), o.begin(), ::tolower);

    std::map<std::string, std::string> opt_map = d_config_map[s];

    opt_map[o] = val;

    d_config_map[s] = opt_map;
  }

  bool
  prefs::get_bool(const std::string &section, const std::string &option,
                  bool default_val)
  {
    if(has_option(section, option)) {
      std::string str = get_string(section, option, "");
      if(str == "") {
        return default_val;
      }
      std::transform(str.begin(), str.end(), str.begin(), ::tolower);
      if((str == "true") || (str == "on") || (str == "1"))
        return true;
      else if((str == "false") || (str == "off") || (str == "0"))
        return false;
      else
        return default_val;
    }
    else {
      return default_val;
    }
  }

  void
  prefs::set_bool(const std::string &section, const std::string &option,
                  bool val)
  {
    std::string s = section;
    std::transform(section.begin(), section.end(), s.begin(), ::tolower);

    std::string o = option;
    std::transform(option.begin(), option.end(), o.begin(), ::tolower);

    std::map<std::string, std::string> opt_map = d_config_map[s];

    std::stringstream sstr;
    sstr << (val == true);
    opt_map[o] = sstr.str();

    d_config_map[s] = opt_map;
  }

  long
  prefs::get_long(const std::string &section, const std::string &option,
                  long default_val)
  {
    if(has_option(section, option)) {
      std::string str = get_string(section, option, "");
      if(str == "") {
        return default_val;
      }
      std::stringstream sstr(str);
      long n;
      sstr >> n;
      return n;
    }
    else {
      return default_val;
    }
  }

  void
  prefs::set_long(const std::string &section, const std::string &option,
                  long val)
  {
    std::string s = section;
    std::transform(section.begin(), section.end(), s.begin(), ::tolower);

    std::string o = option;
    std::transform(option.begin(), option.end(), o.begin(), ::tolower);

    std::map<std::string, std::string> opt_map = d_config_map[s];

    std::stringstream sstr;
    sstr << val;
    opt_map[o] = sstr.str();

    d_config_map[s] = opt_map;
  }

  double
  prefs::get_double(const std::string &section, const std::string &option,
                    double default_val)
  {
    if(has_option(section, option)) {
      std::string str = get_string(section, option, "");
      if(str == "") {
        return default_val;
      }
      std::stringstream sstr(str);
      double n;
      sstr >> n;
      return n;
    }
    else {
      return default_val;
    }
  }

  void
  prefs::set_double(const std::string &section, const std::string &option,
                    double val)
  {
    std::string s = section;
    std::transform(section.begin(), section.end(), s.begin(), ::tolower);

    std::string o = option;
    std::transform(option.begin(), option.end(), o.begin(), ::tolower);

    std::map<std::string, std::string> opt_map = d_config_map[s];

    std::stringstream sstr;
    sstr << val;
    opt_map[o] = sstr.str();

    d_config_map[s] = opt_map;
  }

} /* namespace gr */


text:
/*
 * Copyright 2014-2017 Jouni Roivas
 */

#include "blieng/character.h"

#include <boost/foreach.hpp>

using blieng::Character;

Character::Character()
    : blieng::BliObject()
{
    setValue("dead", false);
}

bool Character::kill()
{
    setValue("dead", true);
    return true;
}

bool Character::isAlive() const
{
    if (!isValue("dead")) {
        throw std::string("Object does not have value 'dead'");
    }

    return !getBoolValue("dead");
}

unsigned int Character::addItem(
    std::unique_ptr<blieng::Item> item)
{
    items.push_back(std::move(item));
    return items.size();
}

bool Character::removeItem(
    unsigned int index)
{
    if (index >= size())
        throw std::string("Index out of bounds");
        //return false;

    items.erase(index);
    return true;
}

unsigned int Character::size() const
{
    return items.size();
}

void Character::assignObject(
    const BliObject *another)
{
    blieng::BliObject::assignObject(another);
}

void Character::assignObject(
    Character *another)
{
    if (another == nullptr)
        return;

    blieng::BliObject::assignObject(static_cast<BliObject*>(another));

    for (blieng::Item *item : another->items) {
        items.push_back(item->copy());
    }
}

ext: cpp

max_stars_repo_name: jroivas/blieng

max_issues_repo_name: jroivas/blieng

max_forks_repo_name: jroivas/blieng


text:
/*=============================================================================
    Copyright (c) 2006-2007 Tobias Schwinger

    Use modification and distribution are subject to 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).
==============================================================================*/

#if !defined(BOOST_FUSION_FUNCTIONAL_ADAPTER_LIMITS_HPP_INCLUDED)
#define BOOST_FUSION_FUNCTIONAL_ADAPTER_LIMITS_HPP_INCLUDED

#include <boost/fusion/container/vector/detail/config.hpp>
#if !defined(BOOST_FUSION_HAS_VARIADIC_VECTOR)
#include <boost/fusion/container/vector/detail/cpp03/limits.hpp>
#endif

#if !defined(BOOST_FUSION_UNFUSED_MAX_ARITY)
#define BOOST_FUSION_UNFUSED_MAX_ARITY 6
#elif !defined(BOOST_FUSION_HAS_VARIADIC_VECTOR) &&                            \
    (BOOST_FUSION_UNFUSED_GENERIC_MAX_ARITY > FUSION_MAX_VECTOR_SIZE)
#error "BOOST_FUSION_UNFUSED_GENERIC_MAX_ARITY > FUSION_MAX_VECTOR_SIZE"
#endif
#if !defined(BOOST_FUSION_UNFUSED_TYPED_MAX_ARITY)
#define BOOST_FUSION_UNFUSED_TYPED_MAX_ARITY 6
#elif !defined(BOOST_FUSION_HAS_VARIADIC_VECTOR) &&                            \
    (BOOST_FUSION_UNFUSED_TYPED_MAX_ARITY > FUSION_MAX_VECTOR_SIZE)
#error "BOOST_FUSION_UNFUSED_TYPED_MAX_ARITY > FUSION_MAX_VECTOR_SIZE"
#endif

#endif

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
// Andrew Naplavkov

#ifndef BARK_DB_POSTGRES_BIND_PARAM_HPP
#define BARK_DB_POSTGRES_BIND_PARAM_HPP

#include <bark/db/postgres/detail/utility.hpp>
#include <bark/db/variant.hpp>
#include <boost/predef/other/endian.h>

namespace bark::db::postgres {

struct param {
    virtual ~param() = default;
    virtual Oid type() = 0;
    virtual const char* value() = 0;
    virtual int length() = 0;
    virtual int format() = 0;
};

using param_holder = std::unique_ptr<param>;

struct param_null : param {
    Oid type() override { return PGRES_TYPE_TEXT; }
    const char* value() override { return nullptr; }
    int length() override { return 0; }
    int format() override { return PGRES_FORMAT_TEXT; }
};

template <class T>
class param_val : public param {
    T val_;

public:
    explicit param_val(T val)
    {
#if defined BOOST_ENDIAN_LITTLE_BYTE
        val_ = reversed(val);
#elif defined BOOST_ENDIAN_BIG_BYTE
        val_ = val;
#else
#error byte order error
#endif
    }

    Oid type() override { return code_of<T>(); }
    const char* value() override { return (const char*)&val_; }
    int length() override { return sizeof(T); }
    int format() override { return PGRES_FORMAT_BINARY; }
};

template <class T, int Format>
class param_arr : public param {
    T data_;

public:
    explicit param_arr(T data) : data_(data) {}
    Oid type() override { return code_of<T>(); }
    const char* value() override { return (const char*)data_.data(); }
    int length() override { return int(data_.size()); }
    int format() override { return Format; }
};

inline param_holder bind_param(const variant_t& v)
{
    return std::visit(
        overloaded{[](std::monostate) -> param_holder {
                       return std::make_unique<param_null>();
                   },
                   [](auto v) -> param_holder {
                       return std::make_unique<param_val<decltype(v)>>(v);
                   },
                   [](std::string_view v) -> param_holder {
                       return std::make_unique<
                           param_arr<std::string_view, PGRES_FORMAT_TEXT>>(v);
                   },
                   [](blob_view v) -> param_holder {
                       return std::make_unique<
                           param_arr<blob_view, PGRES_FORMAT_BINARY>>(v);
                   }},
        v);
}

}  // namespace bark::db::postgres

#endif  // BARK_DB_POSTGRES_BIND_PARAM_HPP

max_stars_repo_name: storm-ptr/bark

max_issues_repo_name: storm-ptr/bark

max_forks_repo_name: storm-ptr/bark


text:
/**
 * Swagger Petstore
 * This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters.
 *
 * The version of the OpenAPI document: 1.0.0
 * Contact: apiteam@swagger.io
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#include <corvusoft/restbed/byte.hpp>
#include <corvusoft/restbed/string.hpp>
#include <corvusoft/restbed/settings.hpp>
#include <corvusoft/restbed/request.hpp>
#include <corvusoft/restbed/uri.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

#include "PetApi.h"

namespace org {
namespace openapitools {
namespace server {
namespace api {

using namespace org::openapitools::server::model;

PetApiException::PetApiException(int status_code, std::string what)
  : m_status(status_code),
    m_what(what)
{

}
int PetApiException::getStatus() const
{
    return m_status;
}
const char* PetApiException::what() const noexcept
{
    return m_what.c_str();
}

template<class MODEL_T>
std::shared_ptr<MODEL_T> extractJsonModelBodyParam(const std::string& bodyContent)
{
    std::stringstream sstream(bodyContent);
    boost::property_tree::ptree pt;
    boost::property_tree::json_parser::read_json(sstream, pt);

    auto model = std::make_shared<MODEL_T>(pt);
    return model;
}

template<class MODEL_T>
std::vector<std::shared_ptr<MODEL_T>> extractJsonArrayBodyParam(const std::string& bodyContent)
{
    std::stringstream sstream(bodyContent);
    boost::property_tree::ptree pt;
    boost::property_tree::json_parser::read_json(sstream, pt);

    auto arrayRet = std::vector<std::shared_ptr<MODEL_T>>();
    for (const auto& child: pt) {
        arrayRet.emplace_back(std::make_shared<MODEL_T>(child.second));
    }
    return arrayRet;
}

template <class KEY_T, class VAL_T>
std::string convertMapResponse(const std::map<KEY_T, VAL_T>& map)
{
    boost::property_tree::ptree pt;
    for(const auto &kv: map) {
    pt.push_back(boost::property_tree::ptree::value_type(
        boost::lexical_cast<std::string>(kv.first),
        boost::property_tree::ptree(
        boost::lexical_cast<std::string>(kv.second))));
    }
    std::stringstream sstream;
    write_json(sstream, pt);
    std::string result = sstream.str();
    return result;
}

PetApiPetResource::PetApiPetResource(const std::string& context /* = "/v2" */)
{
	this->set_path(context + "/pet/");
	this->set_method_handler("POST",
		std::bind(&PetApiPetResource::handler_POST_internal, this,
			std::placeholders::_1));
	this->set_method_handler("PUT",
		std::bind(&PetApiPetResource::handler_PUT_internal, this,
			std::placeholders::_1));
}

PetApiPetResource::~PetApiPetResource()
{
}

std::pair<int, std::string> PetApiPetResource::handlePetApiException(const PetApiException& e)
{
    return std::make_pair<int, std::string>(e.getStatus(), e.what());
}

std::pair<int, std::string> PetApiPetResource::handleStdException(const std::exception& e)
{
    return std::make_pair<int, std::string>(500, e.what());
}

std::pair<int, std::string> PetApiPetResource::handleUnspecifiedException()
{
    return std::make_pair<int, std::string>(500, "Unknown exception occurred");
}

void PetApiPetResource::setResponseHeader(const std::shared_ptr<restbed::Session>& session, const std::string& header)
{
    session->set_header(header, "");
}

void PetApiPetResource::returnResponse(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result, const std::string& contentType)
{
    session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} });
}

void PetApiPetResource::defaultSessionClose(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result)
{
    session->close(status, result, { {"Connection", "close"} });
}

void PetApiPetResource::handler_POST_internal(const std::shared_ptr<restbed::Session> session)
{
    const auto request = session->get_request();
    std::string bodyContent = extractBodyContent(session);

    // Get body params or form params here from the body content string
    auto body = extractJsonModelBodyParam<Pet>(bodyContent);

    int status_code = 500;
    std::string result = "";

    try {
         status_code =
             handler_POST(body);
    }
    catch(const PetApiException& e) {
        std::tie(status_code, result) = handlePetApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 405) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 405, result.empty() ? "Invalid input" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}

// x-extension
void PetApiPetResource::handler_PUT_internal(const std::shared_ptr<restbed::Session> session) {

    const auto request = session->get_request();
    std::string bodyContent = extractBodyContent(session);

    // body params or form params here from the body content string
    auto body = extractJsonModelBodyParam<Pet>(bodyContent);

    int status_code = 500;
    std::string result = "";

    try {
        status_code =
            handler_PUT(body);
    }
    catch(const PetApiException& e) {
        std::tie(status_code, result) = handlePetApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 400) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType);
        return;
    }
    if (status_code == 404) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 404, result.empty() ? "Pet not found" : result, contentType);
        return;
    }
    if (status_code == 405) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 405, result.empty() ? "Validation exception" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}

int PetApiPetResource::handler_POST(
        std::shared_ptr<Pet> const & body)
{
    throw PetApiException(501, "Not implemented");
}

int PetApiPetResource::handler_PUT(
    std::shared_ptr<Pet> const & body)
{
    throw PetApiException(501, "Not implemented");
}

std::string PetApiPetResource::extractBodyContent(const std::shared_ptr<restbed::Session>& session) {
  const auto request = session->get_request();
  int content_length = request->get_header("Content-Length", 0);
  std::string bodyContent;
  session->fetch(content_length,
                 [&bodyContent](const std::shared_ptr<restbed::Session> session,
                                const restbed::Bytes &body) {
                   bodyContent = restbed::String::format(
                       "%.*s\n", (int)body.size(), body.data());
                 });
  return bodyContent;
}
PetApiPetPetIdResource::PetApiPetPetIdResource(const std::string& context /* = "/v2" */)
{
	this->set_path(context + "/pet/{petId: .*}/");
	this->set_method_handler("DELETE",
		std::bind(&PetApiPetPetIdResource::handler_DELETE_internal, this,
			std::placeholders::_1));
	this->set_method_handler("GET",
		std::bind(&PetApiPetPetIdResource::handler_GET_internal, this,
			std::placeholders::_1));
	this->set_method_handler("POST",
		std::bind(&PetApiPetPetIdResource::handler_POST_internal, this,
			std::placeholders::_1));
}

PetApiPetPetIdResource::~PetApiPetPetIdResource()
{
}

std::pair<int, std::string> PetApiPetPetIdResource::handlePetApiException(const PetApiException& e)
{
    return std::make_pair<int, std::string>(e.getStatus(), e.what());
}

std::pair<int, std::string> PetApiPetPetIdResource::handleStdException(const std::exception& e)
{
    return std::make_pair<int, std::string>(500, e.what());
}

std::pair<int, std::string> PetApiPetPetIdResource::handleUnspecifiedException()
{
    return std::make_pair<int, std::string>(500, "Unknown exception occurred");
}

void PetApiPetPetIdResource::setResponseHeader(const std::shared_ptr<restbed::Session>& session, const std::string& header)
{
    session->set_header(header, "");
}

void PetApiPetPetIdResource::returnResponse(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result, const std::string& contentType)
{
    session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} });
}

void PetApiPetPetIdResource::defaultSessionClose(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result)
{
    session->close(status, result, { {"Connection", "close"} });
}

void PetApiPetPetIdResource::handler_DELETE_internal(const std::shared_ptr<restbed::Session> session)
{
    const auto request = session->get_request();

    // Getting the path params
    const int64_t petId = getPathParam_petId(request);

    // Getting the headers
    const std::string apiKey = getHeader_api_key(request);

    int status_code = 500;
    std::string result = "";

    try {
         status_code =
             handler_DELETE(petId, apiKey);
    }
    catch(const PetApiException& e) {
        std::tie(status_code, result) = handlePetApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 400) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType);
        return;
    }
    if (status_code == 404) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 404, result.empty() ? "Pet not found" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}

// x-extension
void PetApiPetPetIdResource::handler_GET_internal(const std::shared_ptr<restbed::Session> session) {

    const auto request = session->get_request();

    // Getting the path params
    const int64_t petId = getPathParam_petId_x_extension(request);

    int status_code = 500;
    std::shared_ptr<Pet> resultObject = std::make_shared<Pet>();
    std::string result = "";

    try {
        std::tie(status_code, resultObject) =
            handler_GET(petId);
    }
    catch(const PetApiException& e) {
        std::tie(status_code, result) = handlePetApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 200) {
        result = resultObject->toJsonString();

        const constexpr auto contentType = "application/json";
        returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType);
        return;
    }
    if (status_code == 400) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType);
        return;
    }
    if (status_code == 404) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 404, result.empty() ? "Pet not found" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}
// x-extension
void PetApiPetPetIdResource::handler_POST_internal(const std::shared_ptr<restbed::Session> session) {

    const auto request = session->get_request();

    // Getting the path params
    const int64_t petId = getPathParam_petId_x_extension(request);

    int status_code = 500;
    std::string result = "";

    try {
        status_code =
            handler_POST(petId, name, status);
    }
    catch(const PetApiException& e) {
        std::tie(status_code, result) = handlePetApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 405) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 405, result.empty() ? "Invalid input" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}

int PetApiPetPetIdResource::handler_DELETE(
        int64_t const & petId, std::string const & apiKey)
{
    throw PetApiException(501, "Not implemented");
}

std::pair<int, std::shared_ptr<Pet>> PetApiPetPetIdResource::handler_GET(
    int64_t const & petId)
{
    throw PetApiException(501, "Not implemented");
}
int PetApiPetPetIdResource::handler_POST(
    int64_t const & petId, std::string const & name, std::string const & status)
{
    throw PetApiException(501, "Not implemented");
}

std::string PetApiPetPetIdResource::extractBodyContent(const std::shared_ptr<restbed::Session>& session) {
  const auto request = session->get_request();
  int content_length = request->get_header("Content-Length", 0);
  std::string bodyContent;
  session->fetch(content_length,
                 [&bodyContent](const std::shared_ptr<restbed::Session> session,
                                const restbed::Bytes &body) {
                   bodyContent = restbed::String::format(
                       "%.*s\n", (int)body.size(), body.data());
                 });
  return bodyContent;
}
PetApiPetFindByStatusResource::PetApiPetFindByStatusResource(const std::string& context /* = "/v2" */)
{
	this->set_path(context + "/pet/findByStatus/");
	this->set_method_handler("GET",
		std::bind(&PetApiPetFindByStatusResource::handler_GET_internal, this,
			std::placeholders::_1));
}

PetApiPetFindByStatusResource::~PetApiPetFindByStatusResource()
{
}

std::pair<int, std::string> PetApiPetFindByStatusResource::handlePetApiException(const PetApiException& e)
{
    return std::make_pair<int, std::string>(e.getStatus(), e.what());
}

std::pair<int, std::string> PetApiPetFindByStatusResource::handleStdException(const std::exception& e)
{
    return std::make_pair<int, std::string>(500, e.what());
}

std::pair<int, std::string> PetApiPetFindByStatusResource::handleUnspecifiedException()
{
    return std::make_pair<int, std::string>(500, "Unknown exception occurred");
}

void PetApiPetFindByStatusResource::setResponseHeader(const std::shared_ptr<restbed::Session>& session, const std::string& header)
{
    session->set_header(header, "");
}

void PetApiPetFindByStatusResource::returnResponse(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result, const std::string& contentType)
{
    session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} });
}

void PetApiPetFindByStatusResource::defaultSessionClose(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result)
{
    session->close(status, result, { {"Connection", "close"} });
}

void PetApiPetFindByStatusResource::handler_GET_internal(const std::shared_ptr<restbed::Session> session)
{
    const auto request = session->get_request();

    // Getting the query params

    int status_code = 500;
    std::vector<std::shared_ptr<Pet>> resultObject = std::vector<std::shared_ptr<Pet>>();
    std::string result = "";

    try {
        std::tie(status_code, resultObject) =
             handler_GET(status);
    }
    catch(const PetApiException& e) {
        std::tie(status_code, result) = handlePetApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 200) {

        const constexpr auto contentType = "application/json";
        returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType);
        return;
    }
    if (status_code == 400) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 400, result.empty() ? "Invalid status value" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}

std::pair<int, std::vector<std::shared_ptr<Pet>>> PetApiPetFindByStatusResource::handler_GET(
        std::vector<std::string> const & status)
{
    throw PetApiException(501, "Not implemented");
}

std::string PetApiPetFindByStatusResource::extractBodyContent(const std::shared_ptr<restbed::Session>& session) {
  const auto request = session->get_request();
  int content_length = request->get_header("Content-Length", 0);
  std::string bodyContent;
  session->fetch(content_length,
                 [&bodyContent](const std::shared_ptr<restbed::Session> session,
                                const restbed::Bytes &body) {
                   bodyContent = restbed::String::format(
                       "%.*s\n", (int)body.size(), body.data());
                 });
  return bodyContent;
}
PetApiPetFindByTagsResource::PetApiPetFindByTagsResource(const std::string& context /* = "/v2" */)
{
	this->set_path(context + "/pet/findByTags/");
	this->set_method_handler("GET",
		std::bind(&PetApiPetFindByTagsResource::handler_GET_internal, this,
			std::placeholders::_1));
}

PetApiPetFindByTagsResource::~PetApiPetFindByTagsResource()
{
}

std::pair<int, std::string> PetApiPetFindByTagsResource::handlePetApiException(const PetApiException& e)
{
    return std::make_pair<int, std::string>(e.getStatus(), e.what());
}

std::pair<int, std::string> PetApiPetFindByTagsResource::handleStdException(const std::exception& e)
{
    return std::make_pair<int, std::string>(500, e.what());
}

std::pair<int, std::string> PetApiPetFindByTagsResource::handleUnspecifiedException()
{
    return std::make_pair<int, std::string>(500, "Unknown exception occurred");
}

void PetApiPetFindByTagsResource::setResponseHeader(const std::shared_ptr<restbed::Session>& session, const std::string& header)
{
    session->set_header(header, "");
}

void PetApiPetFindByTagsResource::returnResponse(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result, const std::string& contentType)
{
    session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} });
}

void PetApiPetFindByTagsResource::defaultSessionClose(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result)
{
    session->close(status, result, { {"Connection", "close"} });
}

void PetApiPetFindByTagsResource::handler_GET_internal(const std::shared_ptr<restbed::Session> session)
{
    const auto request = session->get_request();

    // Getting the query params

    int status_code = 500;
    std::vector<std::shared_ptr<Pet>> resultObject = std::vector<std::shared_ptr<Pet>>();
    std::string result = "";

    try {
        std::tie(status_code, resultObject) =
             handler_GET(tags);
    }
    catch(const PetApiException& e) {
        std::tie(status_code, result) = handlePetApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 200) {

        const constexpr auto contentType = "application/json";
        returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType);
        return;
    }
    if (status_code == 400) {

        const constexpr auto contentType = "text/plain";
        returnResponse(session, 400, result.empty() ? "Invalid tag value" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}

std::pair<int, std::vector<std::shared_ptr<Pet>>> PetApiPetFindByTagsResource::handler_GET(
        std::vector<std::string> const & tags)
{
    throw PetApiException(501, "Not implemented");
}

std::string PetApiPetFindByTagsResource::extractBodyContent(const std::shared_ptr<restbed::Session>& session) {
  const auto request = session->get_request();
  int content_length = request->get_header("Content-Length", 0);
  std::string bodyContent;
  session->fetch(content_length,
                 [&bodyContent](const std::shared_ptr<restbed::Session> session,
                                const restbed::Bytes &body) {
                   bodyContent = restbed::String::format(
                       "%.*s\n", (int)body.size(), body.data());
                 });
  return bodyContent;
}
PetApiPetPetIdUploadImageResource::PetApiPetPetIdUploadImageResource(const std::string& context /* = "/v2" */)
{
	this->set_path(context + "/pet/{petId: .*}/uploadImage/");
	this->set_method_handler("POST",
		std::bind(&PetApiPetPetIdUploadImageResource::handler_POST_internal, this,
			std::placeholders::_1));
}

PetApiPetPetIdUploadImageResource::~PetApiPetPetIdUploadImageResource()
{
}

std::pair<int, std::string> PetApiPetPetIdUploadImageResource::handlePetApiException(const PetApiException& e)
{
    return std::make_pair<int, std::string>(e.getStatus(), e.what());
}

std::pair<int, std::string> PetApiPetPetIdUploadImageResource::handleStdException(const std::exception& e)
{
    return std::make_pair<int, std::string>(500, e.what());
}

std::pair<int, std::string> PetApiPetPetIdUploadImageResource::handleUnspecifiedException()
{
    return std::make_pair<int, std::string>(500, "Unknown exception occurred");
}

void PetApiPetPetIdUploadImageResource::setResponseHeader(const std::shared_ptr<restbed::Session>& session, const std::string& header)
{
    session->set_header(header, "");
}

void PetApiPetPetIdUploadImageResource::returnResponse(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result, const std::string& contentType)
{
    session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} });
}

void PetApiPetPetIdUploadImageResource::defaultSessionClose(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result)
{
    session->close(status, result, { {"Connection", "close"} });
}

void PetApiPetPetIdUploadImageResource::handler_POST_internal(const std::shared_ptr<restbed::Session> session)
{
    const auto request = session->get_request();

    // Getting the path params
    const int64_t petId = getPathParam_petId(request);

    int status_code = 500;
    std::shared_ptr<ApiResponse> resultObject = std::make_shared<ApiResponse>();
    std::string result = "";

    try {
        std::tie(status_code, resultObject) =
             handler_POST(petId, additionalMetadata, file);
    }
    catch(const PetApiException& e) {
        std::tie(status_code, result) = handlePetApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 200) {
        result = resultObject->toJsonString();

        const constexpr auto contentType = "application/json";
        returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}

std::pair<int, std::shared_ptr<ApiResponse>> PetApiPetPetIdUploadImageResource::handler_POST(
        int64_t const & petId, std::string const & additionalMetadata, std::string const & file)
{
    throw PetApiException(501, "Not implemented");
}

std::string PetApiPetPetIdUploadImageResource::extractBodyContent(const std::shared_ptr<restbed::Session>& session) {
  const auto request = session->get_request();
  int content_length = request->get_header("Content-Length", 0);
  std::string bodyContent;
  session->fetch(content_length,
                 [&bodyContent](const std::shared_ptr<restbed::Session> session,
                                const restbed::Bytes &body) {
                   bodyContent = restbed::String::format(
                       "%.*s\n", (int)body.size(), body.data());
                 });
  return bodyContent;
}

PetApi::PetApi(std::shared_ptr<restbed::Service> const& restbedService)
: m_service(restbedService)
{
}

PetApi::~PetApi() {}

void PetApi::setPetApiPetResource(std::shared_ptr<PetApiPetResource> spPetApiPetResource) {
    m_spPetApiPetResource = spPetApiPetResource;
    m_service->publish(m_spPetApiPetResource);
}
void PetApi::setPetApiPetPetIdResource(std::shared_ptr<PetApiPetPetIdResource> spPetApiPetPetIdResource) {
    m_spPetApiPetPetIdResource = spPetApiPetPetIdResource;
    m_service->publish(m_spPetApiPetPetIdResource);
}
void PetApi::setPetApiPetFindByStatusResource(std::shared_ptr<PetApiPetFindByStatusResource> spPetApiPetFindByStatusResource) {
    m_spPetApiPetFindByStatusResource = spPetApiPetFindByStatusResource;
    m_service->publish(m_spPetApiPetFindByStatusResource);
}
void PetApi::setPetApiPetFindByTagsResource(std::shared_ptr<PetApiPetFindByTagsResource> spPetApiPetFindByTagsResource) {
    m_spPetApiPetFindByTagsResource = spPetApiPetFindByTagsResource;
    m_service->publish(m_spPetApiPetFindByTagsResource);
}
void PetApi::setPetApiPetPetIdUploadImageResource(std::shared_ptr<PetApiPetPetIdUploadImageResource> spPetApiPetPetIdUploadImageResource) {
    m_spPetApiPetPetIdUploadImageResource = spPetApiPetPetIdUploadImageResource;
    m_service->publish(m_spPetApiPetPetIdUploadImageResource);
}

void PetApi::publishDefaultResources() {
    if (!m_spPetApiPetResource) {
        setPetApiPetResource(std::make_shared<PetApiPetResource>());
    }
    if (!m_spPetApiPetPetIdResource) {
        setPetApiPetPetIdResource(std::make_shared<PetApiPetPetIdResource>());
    }
    if (!m_spPetApiPetFindByStatusResource) {
        setPetApiPetFindByStatusResource(std::make_shared<PetApiPetFindByStatusResource>());
    }
    if (!m_spPetApiPetFindByTagsResource) {
        setPetApiPetFindByTagsResource(std::make_shared<PetApiPetFindByTagsResource>());
    }
    if (!m_spPetApiPetPetIdUploadImageResource) {
        setPetApiPetPetIdUploadImageResource(std::make_shared<PetApiPetPetIdUploadImageResource>());
    }
}

std::shared_ptr<restbed::Service> PetApi::service() {
    return m_service;
}

}
}
}
}

max_stars_repo_name: RyanJeong/cpprest

max_issues_repo_name: RyanJeong/cpprest

max_forks_repo_name: RyanJeong/cpprest


text:
#include <Access/GrantedRoles.h>
#include <Access/RolesOrUsersSet.h>
#include <boost/range/algorithm/set_algorithm.hpp>
#include <boost/range/algorithm_ext/erase.hpp>
#include <boost/range/algorithm/copy.hpp>

namespace DB
{
void GrantedRoles::grant(const UUID & role_)
{
    roles.insert(role_);
}

void GrantedRoles::grant(const std::vector<UUID> & roles_)
{
    roles.insert(roles_.begin(), roles_.end());
}

void GrantedRoles::grantWithAdminOption(const UUID & role_)
{
    roles.insert(role_);
    roles_with_admin_option.insert(role_);
}

void GrantedRoles::grantWithAdminOption(const std::vector<UUID> & roles_)
{
    roles.insert(roles_.begin(), roles_.end());
    roles_with_admin_option.insert(roles_.begin(), roles_.end());
}

void GrantedRoles::revoke(const UUID & role_)
{
    roles.erase(role_);
    roles_with_admin_option.erase(role_);
}

void GrantedRoles::revoke(const std::vector<UUID> & roles_)
{
    for (const UUID & role : roles_)
        revoke(role);
}

void GrantedRoles::revokeAdminOption(const UUID & role_)
{
    roles_with_admin_option.erase(role_);
}

void GrantedRoles::revokeAdminOption(const std::vector<UUID> & roles_)
{
    for (const UUID & role : roles_)
        revokeAdminOption(role);
}

bool GrantedRoles::isGranted(const UUID & role_) const
{
    return roles.count(role_);
}

bool GrantedRoles::isGrantedWithAdminOption(const UUID & role_) const
{
    return roles_with_admin_option.count(role_);
}

std::vector<UUID> GrantedRoles::findGranted(const std::vector<UUID> & ids) const
{
    std::vector<UUID> res;
    res.reserve(ids.size());
    for (const UUID & id : ids)
    {
        if (isGranted(id))
            res.push_back(id);
    }
    return res;
}

std::vector<UUID> GrantedRoles::findGranted(const boost::container::flat_set<UUID> & ids) const
{
    std::vector<UUID> res;
    res.reserve(ids.size());
    boost::range::set_intersection(ids, roles, std::back_inserter(res));
    return res;
}

std::vector<UUID> GrantedRoles::findGranted(const RolesOrUsersSet & ids) const
{
    std::vector<UUID> res;
    for (const UUID & id : roles)
    {
        if (ids.match(id))
            res.emplace_back(id);
    }
    return res;
}

std::vector<UUID> GrantedRoles::findGrantedWithAdminOption(const std::vector<UUID> & ids) const
{
    std::vector<UUID> res;
    res.reserve(ids.size());
    for (const UUID & id : ids)
    {
        if (isGrantedWithAdminOption(id))
            res.push_back(id);
    }
    return res;
}

std::vector<UUID> GrantedRoles::findGrantedWithAdminOption(const boost::container::flat_set<UUID> & ids) const
{
    std::vector<UUID> res;
    res.reserve(ids.size());
    boost::range::set_intersection(ids, roles_with_admin_option, std::back_inserter(res));
    return res;
}

std::vector<UUID> GrantedRoles::findGrantedWithAdminOption(const RolesOrUsersSet & ids) const
{
    std::vector<UUID> res;
    for (const UUID & id : roles_with_admin_option)
    {
        if (ids.match(id))
            res.emplace_back(id);
    }
    return res;
}

GrantedRoles::Elements GrantedRoles::getElements() const
{
    Elements elements;

    Element element;
    element.ids.reserve(roles.size());
    boost::range::set_difference(roles, roles_with_admin_option, std::back_inserter(element.ids));
    if (!element.empty())
    {
        element.admin_option = false; //-V1048
        elements.emplace_back(std::move(element));
    }

    if (!roles_with_admin_option.empty())
    {
        element = {};
        element.ids.insert(element.ids.end(), roles_with_admin_option.begin(), roles_with_admin_option.end());
        element.admin_option = true;
        elements.emplace_back(std::move(element));
    }

    return elements;
}

void GrantedRoles::makeUnion(const GrantedRoles & other)
{
    roles.insert(other.roles.begin(), other.roles.end());
    roles_with_admin_option.insert(other.roles_with_admin_option.begin(), other.roles_with_admin_option.end());
}

void GrantedRoles::makeIntersection(const GrantedRoles & other)
{
    boost::range::remove_erase_if(roles, [&other](const UUID & id) { return other.roles.find(id) == other.roles.end(); });

    boost::range::remove_erase_if(roles_with_admin_option, [&other](const UUID & id)
    {
        return other.roles_with_admin_option.find(id) == other.roles_with_admin_option.end();
    });
}

std::vector<UUID> GrantedRoles::findDependencies() const
{
    std::vector<UUID> res;
    boost::range::copy(roles, std::back_inserter(res));
    return res;
}

void GrantedRoles::replaceDependencies(const std::unordered_map<UUID, UUID> & old_to_new_ids)
{
    std::vector<UUID> new_ids;

    for (auto it = roles.begin(); it != roles.end();)
    {
        auto id = *it;
        auto it_new_id = old_to_new_ids.find(id);
        if (it_new_id != old_to_new_ids.end())
        {
            auto new_id = it_new_id->second;
            new_ids.push_back(new_id);
            it = roles.erase(it);
        }
        else
        {
            ++it;
        }
    }

    if (!new_ids.empty())
    {
        boost::range::copy(new_ids, std::inserter(roles, roles.end()));
        new_ids.clear();

        for (auto it = roles_with_admin_option.begin(); it != roles_with_admin_option.end();)
        {
            auto id = *it;
            auto it_new_id = old_to_new_ids.find(id);
            if (it_new_id != old_to_new_ids.end())
            {
                auto new_id = it_new_id->second;
                new_ids.push_back(new_id);
                it = roles_with_admin_option.erase(it);
            }
            else
            {
                ++it;
            }
        }

        boost::range::copy(new_ids, std::inserter(roles_with_admin_option, roles_with_admin_option.end()));
    }
}

}


text:
#include <gtest/gtest.h>

#include "zcash/Address.hpp"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#include "util.h"

#include <boost/filesystem.hpp>

/**
 * This test covers Sapling methods on CWallet
 * GenerateNewSaplingZKey()
 * AddSaplingZKey()
 * AddSaplingIncomingViewingKey()
 * LoadSaplingZKey()
 * LoadSaplingIncomingViewingKey()
 * LoadSaplingZKeyMetadata()
 */
TEST(wallet_zkeys_tests, StoreAndLoadSaplingZkeys) {
    SelectParams(CBaseChainParams::MAIN);

    CWallet wallet;

    // wallet should be empty
    std::set<libzcash::SaplingPaymentAddress> addrs;
    wallet.GetSaplingPaymentAddresses(addrs);
    ASSERT_EQ(0, addrs.size());

    // No HD seed in the wallet
    EXPECT_ANY_THROW(wallet.GenerateNewSaplingZKey());

    // Load the all-zeroes seed
    CKeyingMaterial rawSeed(32, 0);
    HDSeed seed(rawSeed);
    wallet.LoadHDSeed(seed);

    // Now this call succeeds
    auto address = wallet.GenerateNewSaplingZKey();

    // wallet should have one key
    wallet.GetSaplingPaymentAddresses(addrs);
    ASSERT_EQ(1, addrs.size());

    // verify wallet has incoming viewing key for the address
    ASSERT_TRUE(wallet.HaveSaplingIncomingViewingKey(address));

    // manually add new spending key to wallet
    auto m = libzcash::SaplingExtendedSpendingKey::Master(seed);
    auto sk = m.Derive(0);
    ASSERT_TRUE(wallet.AddSaplingZKey(sk, sk.DefaultAddress()));

    // verify wallet did add it
    auto extfvk = sk.ToXFVK();
    ASSERT_TRUE(wallet.HaveSaplingSpendingKey(extfvk));

    // verify spending key stored correctly
    libzcash::SaplingExtendedSpendingKey keyOut;
    wallet.GetSaplingSpendingKey(extfvk, keyOut);
    ASSERT_EQ(sk, keyOut);

    // verify there are two keys
    wallet.GetSaplingPaymentAddresses(addrs);
    EXPECT_EQ(2, addrs.size());
    EXPECT_EQ(1, addrs.count(address));
    EXPECT_EQ(1, addrs.count(sk.DefaultAddress()));

    // Generate a diversified address different to the default
    // If we can't get an early diversified address, we are very unlucky
    blob88 diversifier;
    diversifier.begin()[0] = 10;
    auto dpa = sk.ToXFVK().Address(diversifier).get().second;

    // verify wallet only has the default address
    EXPECT_TRUE(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress()));
    EXPECT_FALSE(wallet.HaveSaplingIncomingViewingKey(dpa));

    // manually add a diversified address
    auto ivk = fvk.in_viewing_key();
    EXPECT_TRUE(wallet.AddSaplingIncomingViewingKey(ivk, dpa));

    // verify wallet did add it
    EXPECT_TRUE(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress()));
    EXPECT_TRUE(wallet.HaveSaplingIncomingViewingKey(dpa));

    // Load a third key into the wallet
    auto sk2 = m.Derive(1);
    ASSERT_TRUE(wallet.LoadSaplingZKey(sk2));

    // attach metadata to this third key
    auto ivk2 = sk2.expsk.full_viewing_key().in_viewing_key();
    int64_t now = GetTime();
    CKeyMetadata meta(now);
    ASSERT_TRUE(wallet.LoadSaplingZKeyMetadata(ivk2, meta));

    // check metadata is the same
    ASSERT_EQ(wallet.mapSaplingZKeyMetadata[ivk2].nCreateTime, now);

    // Load a diversified address for the third key into the wallet
    auto dpa2 = sk2.ToXFVK().Address(diversifier).get().second;
    EXPECT_TRUE(wallet.HaveSaplingIncomingViewingKey(sk2.DefaultAddress()));
    EXPECT_FALSE(wallet.HaveSaplingIncomingViewingKey(dpa2));
    EXPECT_TRUE(wallet.LoadSaplingPaymentAddress(dpa2, ivk2));
    EXPECT_TRUE(wallet.HaveSaplingIncomingViewingKey(dpa2));
}

/**
 * This test covers methods on CWallet
 * GenerateNewSproutZKey()
 * AddSproutZKey()
 * LoadZKey()
 * LoadZKeyMetadata()
 */
TEST(wallet_zkeys_tests, store_and_load_zkeys) {
    SelectParams(CBaseChainParams::MAIN);

    CWallet wallet;

    // wallet should be empty
    std::set<libzcash::SproutPaymentAddress> addrs;
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(0, addrs.size());

    // wallet should have one key
    auto addr = wallet.GenerateNewSproutZKey();
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(1, addrs.size());

    // verify wallet has spending key for the address
    ASSERT_TRUE(wallet.HaveSproutSpendingKey(addr));

    // manually add new spending key to wallet
    auto sk = libzcash::SproutSpendingKey::random();
    ASSERT_TRUE(wallet.AddSproutZKey(sk));

    // verify wallet did add it
    addr = sk.address();
    ASSERT_TRUE(wallet.HaveSproutSpendingKey(addr));

    // verify spending key stored correctly
    libzcash::SproutSpendingKey keyOut;
    wallet.GetSproutSpendingKey(addr, keyOut);
    ASSERT_EQ(sk, keyOut);

    // verify there are two keys
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(2, addrs.size());
    ASSERT_EQ(1, addrs.count(addr));

    // Load a third key into the wallet
    sk = libzcash::SproutSpendingKey::random();
    ASSERT_TRUE(wallet.LoadZKey(sk));

    // attach metadata to this third key
    addr = sk.address();
    int64_t now = GetTime();
    CKeyMetadata meta(now);
    ASSERT_TRUE(wallet.LoadZKeyMetadata(addr, meta));

    // check metadata is the same
    CKeyMetadata m= wallet.mapSproutZKeyMetadata[addr];
    ASSERT_EQ(m.nCreateTime, now);
}

/**
 * This test covers methods on CWallet
 * AddSproutViewingKey()
 * RemoveSproutViewingKey()
 * LoadSproutViewingKey()
 */
TEST(wallet_zkeys_tests, StoreAndLoadViewingKeys) {
    SelectParams(CBaseChainParams::MAIN);

    CWallet wallet;

    // wallet should be empty
    std::set<libzcash::SproutPaymentAddress> addrs;
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(0, addrs.size());

    // manually add new viewing key to wallet
    auto sk = libzcash::SproutSpendingKey::random();
    auto vk = sk.viewing_key();
    ASSERT_TRUE(wallet.AddSproutViewingKey(vk));

    // verify wallet did add it
    auto addr = sk.address();
    ASSERT_TRUE(wallet.HaveSproutViewingKey(addr));
    // and that we don't have the corresponding spending key
    ASSERT_FALSE(wallet.HaveSproutSpendingKey(addr));

    // verify viewing key stored correctly
    libzcash::SproutViewingKey vkOut;
    wallet.GetSproutViewingKey(addr, vkOut);
    ASSERT_EQ(vk, vkOut);

    // Load a second viewing key into the wallet
    auto sk2 = libzcash::SproutSpendingKey::random();
    ASSERT_TRUE(wallet.LoadSproutViewingKey(sk2.viewing_key()));

    // verify wallet did add it
    auto addr2 = sk2.address();
    ASSERT_TRUE(wallet.HaveSproutViewingKey(addr2));
    ASSERT_FALSE(wallet.HaveSproutSpendingKey(addr2));

    // Remove the first viewing key
    ASSERT_TRUE(wallet.RemoveSproutViewingKey(vk));
    ASSERT_FALSE(wallet.HaveSproutViewingKey(addr));
    ASSERT_TRUE(wallet.HaveSproutViewingKey(addr2));
}

/**
 * This test covers methods on CWalletDB
 * WriteZKey()
 */
TEST(wallet_zkeys_tests, write_zkey_direct_to_db) {
    SelectParams(CBaseChainParams::TESTNET);

    // Get temporary and unique path for file.
    // Note: / operator to append paths
    boost::filesystem::path pathTemp = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
    boost::filesystem::create_directories(pathTemp);
    mapArgs["-datadir"] = pathTemp.string();

    bool fFirstRun;
    CWallet wallet("wallet.dat");
    ASSERT_EQ(DB_LOAD_OK, wallet.LoadWallet(fFirstRun));

    // No default CPubKey set
    ASSERT_TRUE(fFirstRun);

    // wallet should be empty
    std::set<libzcash::SproutPaymentAddress> addrs;
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(0, addrs.size());

    // Add random key to the wallet
    auto paymentAddress = wallet.GenerateNewSproutZKey();

    // wallet should have one key
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(1, addrs.size());

    // create random key and add it to database directly, bypassing wallet
    auto sk = libzcash::SproutSpendingKey::random();
    auto addr = sk.address();
    int64_t now = GetTime();
    CKeyMetadata meta(now);
    CWalletDB db("wallet.dat");
    db.WriteZKey(addr, sk, meta);

    // wallet should not be aware of key
    ASSERT_FALSE(wallet.HaveSproutSpendingKey(addr));

    // wallet sees one key
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(1, addrs.size());

    // wallet should have default metadata for addr with null createtime
    CKeyMetadata m = wallet.mapSproutZKeyMetadata[addr];
    ASSERT_EQ(m.nCreateTime, 0);
    ASSERT_NE(m.nCreateTime, now);

    // load the wallet again
    ASSERT_EQ(DB_LOAD_OK, wallet.LoadWallet(fFirstRun));

    // wallet can now see the spending key
    ASSERT_TRUE(wallet.HaveSproutSpendingKey(addr));

    // check key is the same
    libzcash::SproutSpendingKey keyOut;
    wallet.GetSproutSpendingKey(addr, keyOut);
    ASSERT_EQ(sk, keyOut);

    // wallet should have two keys
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(2, addrs.size());

    // check metadata is now the same
    m = wallet.mapSproutZKeyMetadata[addr];
    ASSERT_EQ(m.nCreateTime, now);
}

/**
 * This test covers methods on CWalletDB
 * WriteSproutViewingKey()
 */
TEST(wallet_zkeys_tests, WriteViewingKeyDirectToDB) {
    SelectParams(CBaseChainParams::TESTNET);

    // Get temporary and unique path for file.
    // Note: / operator to append paths
    boost::filesystem::path pathTemp = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
    boost::filesystem::create_directories(pathTemp);
    mapArgs["-datadir"] = pathTemp.string();

    bool fFirstRun;
    CWallet wallet("wallet-vkey.dat");
    ASSERT_EQ(DB_LOAD_OK, wallet.LoadWallet(fFirstRun));

    // No default CPubKey set
    ASSERT_TRUE(fFirstRun);

    // create random viewing key and add it to database directly, bypassing wallet
    auto sk = libzcash::SproutSpendingKey::random();
    auto vk = sk.viewing_key();
    auto addr = sk.address();
    int64_t now = GetTime();
    CKeyMetadata meta(now);
    CWalletDB db("wallet-vkey.dat");
    db.WriteSproutViewingKey(vk);

    // wallet should not be aware of viewing key
    ASSERT_FALSE(wallet.HaveSproutViewingKey(addr));

    // load the wallet again
    ASSERT_EQ(DB_LOAD_OK, wallet.LoadWallet(fFirstRun));

    // wallet can now see the viewing key
    ASSERT_TRUE(wallet.HaveSproutViewingKey(addr));

    // check key is the same
    libzcash::SproutViewingKey vkOut;
    wallet.GetSproutViewingKey(addr, vkOut);
    ASSERT_EQ(vk, vkOut);
}

/**
 * This test covers methods on CWalletDB to load/save crypted z keys.
 */
TEST(wallet_zkeys_tests, write_cryptedzkey_direct_to_db) {
    SelectParams(CBaseChainParams::TESTNET);

    // Get temporary and unique path for file.
    // Note: / operator to append paths
    boost::filesystem::path pathTemp = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
    boost::filesystem::create_directories(pathTemp);
    mapArgs["-datadir"] = pathTemp.string();

    bool fFirstRun;
    CWallet wallet("wallet_crypted.dat");
    ASSERT_EQ(DB_LOAD_OK, wallet.LoadWallet(fFirstRun));

    // No default CPubKey set
    ASSERT_TRUE(fFirstRun);

    // wallet should be empty
    std::set<libzcash::SproutPaymentAddress> addrs;
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(0, addrs.size());

    // Add random key to the wallet
    auto paymentAddress = wallet.GenerateNewSproutZKey();

    // wallet should have one key
    wallet.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(1, addrs.size());

    // encrypt wallet
    SecureString strWalletPass;
    strWalletPass.reserve(100);
    strWalletPass = "hello";
    ASSERT_TRUE(wallet.EncryptWallet(strWalletPass));

    // adding a new key will fail as the wallet is locked
    EXPECT_ANY_THROW(wallet.GenerateNewSproutZKey());

    // unlock wallet and then add
    wallet.Unlock(strWalletPass);
    auto paymentAddress2 = wallet.GenerateNewSproutZKey();

    // Create a new wallet from the existing wallet path
    CWallet wallet2("wallet_crypted.dat");
    ASSERT_EQ(DB_LOAD_OK, wallet2.LoadWallet(fFirstRun));

    // Confirm it's not the same as the other wallet
    ASSERT_TRUE(&wallet != &wallet2);

    // wallet should have two keys
    wallet2.GetSproutPaymentAddresses(addrs);
    ASSERT_EQ(2, addrs.size());

    // check we have entries for our payment addresses
    ASSERT_TRUE(addrs.count(paymentAddress));
    ASSERT_TRUE(addrs.count(paymentAddress2));

    // spending key is crypted, so we can't extract valid payment address
    libzcash::SproutSpendingKey keyOut;
    wallet2.GetSproutSpendingKey(paymentAddress, keyOut);
    ASSERT_FALSE(paymentAddress == keyOut.address());

    // unlock wallet to get spending keys and verify payment addresses
    wallet2.Unlock(strWalletPass);

    wallet2.GetSproutSpendingKey(paymentAddress, keyOut);
    ASSERT_EQ(paymentAddress, keyOut.address());

    wallet2.GetSproutSpendingKey(paymentAddress2, keyOut);
    ASSERT_EQ(paymentAddress2, keyOut.address());
}

/**
 * This test covers methods on CWalletDB to load/save crypted sapling z keys.
 */
TEST(wallet_zkeys_tests, WriteCryptedSaplingZkeyDirectToDb) {
    SelectParams(CBaseChainParams::TESTNET);

    // Get temporary and unique path for file.
    // Note: / operator to append paths
    boost::filesystem::path pathTemp = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
    boost::filesystem::create_directories(pathTemp);
    mapArgs["-datadir"] = pathTemp.string();

    bool fFirstRun;
    CWallet wallet("wallet_crypted_sapling.dat");
    ASSERT_EQ(DB_LOAD_OK, wallet.LoadWallet(fFirstRun));

     // No default CPubKey set
    ASSERT_TRUE(fFirstRun);

    ASSERT_FALSE(wallet.HaveHDSeed());
    wallet.GenerateNewSeed();

    // wallet should be empty
    std::set<libzcash::SaplingPaymentAddress> addrs;
    wallet.GetSaplingPaymentAddresses(addrs);
    ASSERT_EQ(0, addrs.size());

    // Add random key to the wallet
    auto address = wallet.GenerateNewSaplingZKey();

    // wallet should have one key
    wallet.GetSaplingPaymentAddresses(addrs);
    ASSERT_EQ(1, addrs.size());

    // Generate a diversified address different to the default
    // If we can't get an early diversified address, we are very unlucky
    libzcash::SaplingExtendedSpendingKey extsk;
    EXPECT_TRUE(wallet.GetSaplingExtendedSpendingKey(address, extsk));
    blob88 diversifier;
    diversifier.begin()[0] = 10;
    auto dpa = extsk.ToXFVK().Address(diversifier).get().second;

    // Add diversified address to the wallet
    auto ivk = extsk.expsk.full_viewing_key().in_viewing_key();
    EXPECT_TRUE(wallet.AddSaplingIncomingViewingKey(ivk, dpa));

    // encrypt wallet
    SecureString strWalletPass;
    strWalletPass.reserve(100);
    strWalletPass = "hello";
    ASSERT_TRUE(wallet.EncryptWallet(strWalletPass));

    // adding a new key will fail as the wallet is locked
    EXPECT_ANY_THROW(wallet.GenerateNewSaplingZKey());

    // unlock wallet and then add
    wallet.Unlock(strWalletPass);
    auto address2 = wallet.GenerateNewSaplingZKey();

    // Create a new wallet from the existing wallet path
    CWallet wallet2("wallet_crypted_sapling.dat");
    ASSERT_EQ(DB_LOAD_OK, wallet2.LoadWallet(fFirstRun));

    // Confirm it's not the same as the other wallet
    ASSERT_TRUE(&wallet != &wallet2);
    ASSERT_TRUE(wallet2.HaveHDSeed());

    // wallet should have three addresses
    wallet2.GetSaplingPaymentAddresses(addrs);
    ASSERT_EQ(3, addrs.size());

    //check we have entries for our payment addresses
    ASSERT_TRUE(addrs.count(address));
    ASSERT_TRUE(addrs.count(address2));
    ASSERT_TRUE(addrs.count(dpa));

    // spending key is crypted, so we can't extract valid payment address
    libzcash::SaplingExtendedSpendingKey keyOut;
    EXPECT_FALSE(wallet2.GetSaplingExtendedSpendingKey(address, keyOut));
    ASSERT_FALSE(address == keyOut.DefaultAddress());

    // address -> ivk mapping is not crypted
    libzcash::SaplingIncomingViewingKey ivkOut;
    EXPECT_TRUE(wallet2.GetSaplingIncomingViewingKey(dpa, ivkOut));
    EXPECT_EQ(ivk, ivkOut);

    // unlock wallet to get spending keys and verify payment addresses
    wallet2.Unlock(strWalletPass);

    EXPECT_TRUE(wallet2.GetSaplingExtendedSpendingKey(address, keyOut));
    ASSERT_EQ(address, keyOut.DefaultAddress());

    EXPECT_TRUE(wallet2.GetSaplingExtendedSpendingKey(address2, keyOut));
    ASSERT_EQ(address2, keyOut.DefaultAddress());
}

max_stars_repo_name: barrystyle/VerusCoin

max_issues_repo_name: barrystyle/VerusCoin

max_forks_repo_name: barrystyle/VerusCoin


text:
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include <tvgutil/containers/PriorityQueue.h>
using namespace tvgutil;

typedef PriorityQueue<std::string, double, int, std::greater<double> > PQ;

BOOST_AUTO_TEST_SUITE(test_PriorityQueue)

BOOST_AUTO_TEST_CASE(clear_test)
{
  PQ pq;
  pq.insert("S", 1.0, 23);
    BOOST_CHECK_EQUAL(pq.empty(), false);
  pq.clear();
    BOOST_CHECK_EQUAL(pq.empty(), true);
}

BOOST_AUTO_TEST_CASE(contains_test)
{
  PQ pq;
    BOOST_CHECK_EQUAL(pq.contains("S"), false);
    BOOST_CHECK_EQUAL(pq.contains("K"), false);
  pq.insert("S", 1.0, 23);
    BOOST_CHECK_EQUAL(pq.contains("S"), true);
    BOOST_CHECK_EQUAL(pq.contains("K"), false);
  pq.insert("K", 0.9, 13);
    BOOST_CHECK_EQUAL(pq.contains("S"), true);
    BOOST_CHECK_EQUAL(pq.contains("K"), true);
}

BOOST_AUTO_TEST_CASE(element_test)
{
  PQ pq;
  pq.insert("S", 1.0, 23);
  PQ::Element& e = pq.element("S");
    BOOST_CHECK_EQUAL(e.id(), "S");
    BOOST_CHECK_CLOSE(e.key(), 1.0, 0.001);	// they differ by no more than 0.001% of their value
    BOOST_CHECK_EQUAL(e.data(), 23);
}

// Note: empty() has been tested in other test cases

BOOST_AUTO_TEST_CASE(erase_test)
{
  PQ pq;
    BOOST_CHECK_EQUAL(pq.size(), 0);
  pq.insert("S", 1.0, 23);
    BOOST_CHECK_EQUAL(pq.size(), 1);
    BOOST_CHECK_EQUAL(pq.contains("S"), true);
  pq.erase("S");
    BOOST_CHECK_EQUAL(pq.size(), 0);
    BOOST_CHECK_EQUAL(pq.contains("S"), false);
}

// Note: insert() has been tested in other test cases

BOOST_AUTO_TEST_CASE(pop_test)
{
  PQ pq;
  pq.insert("S", 1.0, 23);
  pq.insert("K", 0.9, 13);
    BOOST_CHECK_EQUAL(pq.contains("S"), true);
    BOOST_CHECK_EQUAL(pq.contains("K"), true);
  pq.pop();
    BOOST_CHECK_EQUAL(pq.contains("S"), false);
    BOOST_CHECK_EQUAL(pq.contains("K"), true);
}

BOOST_AUTO_TEST_CASE(size_test)
{
  PQ pq;
    BOOST_CHECK_EQUAL(pq.size(), 0);
  pq.insert("S", 1.0, 23);
    BOOST_CHECK_EQUAL(pq.size(), 1);
  pq.insert("K", 0.9, 13);
    BOOST_CHECK_EQUAL(pq.size(), 2);
  pq.insert("M", 1.1, 7);
    BOOST_CHECK_EQUAL(pq.size(), 3);
  pq.insert("D", 1.1, 7);
    BOOST_CHECK_EQUAL(pq.size(), 4);
  pq.insert("G", 1.1, 24);
    BOOST_CHECK_EQUAL(pq.size(), 5);
  pq.erase("S");
    BOOST_CHECK_EQUAL(pq.size(), 4);
  pq.insert("S", 1.0, 23);
    BOOST_CHECK_EQUAL(pq.size(), 5);

  for(int i=0; i<5; ++i)
  {
    pq.pop();
    BOOST_CHECK_EQUAL(pq.size(), 4 - i);
  }
}

BOOST_AUTO_TEST_CASE(top_test)
{
  PQ pq;
  pq.insert("S", 1.0, 23);
  pq.insert("K", 1.1, 13);
    BOOST_CHECK_EQUAL(pq.top().id(), "K");
  pq.pop();
    BOOST_CHECK_EQUAL(pq.top().id(), "S");
}

BOOST_AUTO_TEST_CASE(update_key_test)
{
  PQ pq;
  pq.insert("S", 1.0, 23);
  pq.insert("M", 0.9, 7);
  pq.update_key("M", 1.1);
    BOOST_CHECK_EQUAL(pq.top().id(), "M");
    BOOST_CHECK_CLOSE(pq.top().key(), 1.1, 0.001);
    BOOST_CHECK_EQUAL(pq.top().data(), 7);
  pq.pop();
    BOOST_CHECK_EQUAL(pq.top().id(), "S");
    BOOST_CHECK_CLOSE(pq.top().key(), 1.0, 0.001);
    BOOST_CHECK_EQUAL(pq.top().data(), 23);
  pq.pop();
    BOOST_CHECK_EQUAL(pq.empty(), true);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: torrvision/spaint

max_issues_repo_name: GucciPrada/spaint

max_forks_repo_name: GucciPrada/spaint


text:
#define BOOST_TEST_MODULE "Utreexo unit tests"
#include <boost/test/included/unit_test.hpp>

max_stars_repo_name: HalosGhost/libutreexo

max_issues_repo_name: HalosGhost/libutreexo

max_forks_repo_name: HalosGhost/libutreexo


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

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

#include <fc/interprocess/signals.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/network/http/server.hpp>
#include <fc/network/http/websocket.hpp>
#include <fc/rpc/cli.hpp>
#include <fc/rpc/http_api.hpp>
#include <fc/rpc/websocket_api.hpp>

#include <graphene/app/api.hpp>
#include <graphene/utilities/dirhelper.hpp>
#include <graphene/utilities/key_conversion.hpp>
#include <graphene/utilities/keys_generator.hpp>
#include <graphene/wallet/wallet.hpp>

#include <decent/about.hpp>
#include <decent/package/package_config.hpp>

#ifdef WIN32
# include <signal.h>
#else
# include <csignal>
#endif

namespace bpo = boost::program_options;

int main( int argc, char** argv )
{
   try {
      auto &pf = graphene::utilities::decent_path_finder::instance();
      bpo::options_description opts("CLI Wallet");
      opts.add_options()
         ("help,h", "Print this help message and exit")
         ("version,v", "Print version information and exit")
         ("generate-keys,g", "Generate brain, wif private and public keys")
         ("wallet-file,w", bpo::value<boost::filesystem::path>()->implicit_value("wallet.json"), "Wallet to load")
         ("log-level,l", bpo::value<char>()->default_value('I'), "Set minimum log level: (D)ebug, (I)nfo, (W)arning, (E)rror, (O)ff")
         ("daemon", "Run the wallet in daemon mode")
         ("chain-id", bpo::value<std::string>(), "Chain ID to connect to")
         ("packages-path", bpo::value<boost::filesystem::path>()->default_value(pf.get_decent_packages()), "Directory to store submitted packages")
         ("ipfs-api", bpo::value<std::string>()->default_value("127.0.0.1:5001"), "IPFS daemon API")
         ("server-rpc-endpoint,s", bpo::value<std::string>()->implicit_value("ws://127.0.0.1:8090"), "Server websocket RPC endpoint")
         ("server-rpc-user,u", bpo::value<std::string>(), "Server Username")
         ("server-rpc-password,p", bpo::value<std::string>(), "Server Password")
         ("rpc-endpoint,r", bpo::value<std::string>()->implicit_value("127.0.0.1:8091"), "Endpoint for wallet websocket RPC to listen on")
         ("rpc-tls-endpoint,t", bpo::value<std::string>()->implicit_value("127.0.0.1:8092"), "Endpoint for wallet websocket TLS RPC to listen on")
         ("rpc-tls-certificate,c", bpo::value<std::string>()->default_value("server.pem"), "PEM certificate for wallet websocket TLS RPC")
         ("rpc-http-endpoint,H", bpo::value<std::string>()->implicit_value("127.0.0.1:8093"), "Endpoint for wallet HTTP RPC to listen on")
         ("from-command-file,f", bpo::value<std::string>(), "Load commands from a command file")
      ;

      bpo::variables_map options;
      bpo::parsed_options optparsed = bpo::command_line_parser(argc, argv).options(opts).allow_unregistered().run();
      bpo::store( optparsed, options );

      if( decent::check_unrecognized(optparsed) )
      {
         return EXIT_FAILURE;
      }

      if( options.count("help") )
      {
         std::cout << opts << "\n";
         return EXIT_SUCCESS;
      }
      else if( options.count("version") )
      {
         decent::dump_version_info("CLI Wallet");
         return EXIT_SUCCESS;
      }
      else if( options.count("generate-keys") )
      {
         std::string brain_key = graphene::utilities::generate_brain_key();
         fc::ecc::private_key priv_key = graphene::utilities::derive_private_key(brain_key);
         graphene::chain::public_key_type pub_key(priv_key.get_public_key());

         std::cout << "Brain key:    " << brain_key << std::endl;
         std::cout << "Private key:  " << graphene::utilities::key_to_wif(priv_key) << std::endl;
         std::cout << "Public key:   " << std::string(pub_key) << std::endl;
         return EXIT_SUCCESS;
      }

      pf.set_packages_path(options["packages-path"].as<boost::filesystem::path>());

      fc::log_level level = fc::log_level::off;
      switch(options["log-level"].as<char>())
      {
         case 'D':
            level = fc::log_level::debug;
            break;
         case 'I':
            level = fc::log_level::info;
            break;
         case 'W':
            level = fc::log_level::warn;
            break;
         case 'E':
            level = fc::log_level::error;
            break;
         case 'O':
            level = fc::log_level::off;
            break;
         default:
            std::cerr << "Unknown log level: " << options["log-level"].as<char>() << std::endl;
            return EXIT_FAILURE;
      }

      const boost::filesystem::path log_dir = pf.get_decent_logs();

      fc::file_appender::config ac_default;
      ac_default.filename             = log_dir / "cli_wallet.log";
      ac_default.flush                = true;
      ac_default.rotate               = true;
      ac_default.rotation_interval    = fc::hours( 1 );
      ac_default.rotation_limit       = fc::days( 1 );

      fc::logger_config lc_default("default");
      lc_default.level          = level;
      lc_default.appenders      = {"default"};

      fc::logging_config cfg;
      cfg.appenders.push_back(fc::appender_config( "default", "file", fc::variant(ac_default)));
      cfg.loggers.push_back(lc_default);
      std::clog << "Logging to file: " << ac_default.filename.string() << std::endl;

      fc::configure_logging( cfg );

      //
      // TODO:  We read wallet_data twice, once in main() to grab the
      //    socket info, again in wallet_api when we do
      //    load_wallet_file().  Seems like this could be better
      //    designed.
      //
      graphene::wallet::wallet_data wdata;
      boost::filesystem::path wallet_file( options.count("wallet-file") ?
         options.at("wallet-file").as<boost::filesystem::path>() : pf.get_decent_home() / "wallet.json");
      bool has_wallet_file = exists( wallet_file );
      if( has_wallet_file )
      {
         wdata = fc::json::from_file( wallet_file ).as<graphene::wallet::wallet_data>();
      }

      // but allow CLI to override
      if( options.count("server-rpc-endpoint") )
         wdata.ws_server = options.at("server-rpc-endpoint").as<std::string>();
      if( options.count("server-rpc-user") )
         wdata.ws_user = options.at("server-rpc-user").as<std::string>();
      if( options.count("server-rpc-password") )
         wdata.ws_password = options.at("server-rpc-password").as<std::string>();

      fc::http::websocket_client client;
      ilog( "Connecting to server at ${s}", ("s", wdata.ws_server) );
      auto con  = client.connect( wdata.ws_server );
      auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);

      auto remote_api = apic->get_remote_api<graphene::app::login_api>(1);
      // TODO:  Error message here
      FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) );

      if( !has_wallet_file )
      {
         if( options.count("chain-id") )
         {
            wdata.chain_id = graphene::chain::chain_id_type(options.at("chain-id").as<std::string>());
            // the --chain-id on the CLI must match the chain ID of database we connect to
            if( remote_api->database()->get_chain_id() != wdata.chain_id )
            {
               std::cerr << "Chain ID from CLI does not match database chain ID\n";
               return 1;
            }

            std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (from CLI)\n";
         }
         else
         {
            wdata.chain_id = remote_api->database()->get_chain_id();
            std::cout << "Starting a new wallet with chain ID " << wdata.chain_id.str() << " (empty one)\n";
         }
      }
      else if( options.count("chain-id") )
      {
         // the --chain-id on the CLI must match the chain ID embedded in the wallet file
         if( graphene::chain::chain_id_type(options.at("chain-id").as<std::string>()) != wdata.chain_id )
         {
            std::cerr << "Chain ID in wallet file " << wallet_file.generic_string() << " does not match specified chain ID\n";
            return 1;
         }
      }
      else if( remote_api->database()->get_chain_id() != wdata.chain_id )
      {
         std::cerr << "Chain ID in wallet file " << wallet_file.generic_string() << " does not match database chain ID\n";
         return 1;
      }

      try
      {
         fc::ip::endpoint api = fc::ip::endpoint::resolve_string(options.at("ipfs-api").as<std::string>()).back();
         auto& pmc = decent::package::PackageManagerConfigurator::instance();
         pmc.set_ipfs_endpoint(api.get_address(), api.port());
      }
      catch( const fc::exception& e )
      {
         std::cerr << "Failed to resolve IPFS daemon API address " << options.at("ipfs-api").as<std::string>() << ", " << e.what() << std::endl;
         return 1;
      }

      graphene::wallet::server_data ws{ wdata.ws_server, wdata.ws_user, wdata.ws_password };
      auto wapiptr = std::make_shared<graphene::wallet::wallet_api>( remote_api, wdata.chain_id, ws );
      if( has_wallet_file && !wapiptr->load_wallet_file(wallet_file.generic_string()) )
      {
         std::cerr << "Failed to load wallet file " << wallet_file.generic_string() << std::endl;
         return 1;
      }
      wapiptr->set_wallet_filename( wallet_file.generic_string() );
      std::clog << "Connected to " << wdata.ws_server << std::endl;

      fc::api<graphene::wallet::wallet_api> wapi(wapiptr);

      auto wallet_cli = std::make_shared<fc::rpc::cli>();
      for( auto& name_formatter : wapiptr->get_result_formatters() )
         wallet_cli->format_result( name_formatter.first, name_formatter.second );

      boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{
         std::cerr << "Server has disconnected us.\n";
         wallet_cli->stop();
      }));
      (void)(closed_connection);

      if( wapiptr->is_new() )
      {
         std::cout << "Please use the set_password method to initialize a new wallet before continuing\n";
         wallet_cli->set_prompt( "new >>> " );
      } else
         wallet_cli->set_prompt( "locked >>> " );

      boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) {
         wallet_cli->set_prompt(  locked ? "locked >>> " : "unlocked >>> " );
      }));

      auto _websocket_server = options.count("rpc-endpoint") ?
               std::make_shared<fc::http::websocket_server>() :
               std::shared_ptr<fc::http::websocket_server>();

      if( _websocket_server )
      {
         _websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c, bool& is_tls ){
            is_tls = false;
            wlog("." );
            auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
            wsc->register_api(wapi);
            c->set_session_data( wsc );
         });
         ilog( "Listening for incoming RPC requests on ${p}", ("p", options.at("rpc-endpoint").as<std::string>() ));
         _websocket_server->listen( fc::ip::endpoint::resolve_string(options.at("rpc-endpoint").as<std::string>()).back() );
         _websocket_server->start_accept();
      }

      auto _websocket_tls_server = options.count("rpc-tls-endpoint") ?
               std::make_shared<fc::http::websocket_tls_server>(options.at("rpc-tls-certificate").as<std::string>()) :
               std::shared_ptr<fc::http::websocket_tls_server>();

      if( _websocket_tls_server )
      {
         _websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c, bool& is_tls ){
            is_tls = true;
            auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);
            wsc->register_api(wapi);
            c->set_session_data( wsc );
         });
         ilog( "Listening for incoming TLS RPC requests on ${p}, certificate file ${c}",
               ("p", options.at("rpc-tls-endpoint").as<std::string>() )("c", options.at("rpc-tls-certificate").as<std::string>() ));
         _websocket_tls_server->listen( fc::ip::endpoint::resolve_string(options.at("rpc-tls-endpoint").as<std::string>()).back() );
         _websocket_tls_server->start_accept();
      }

      auto _http_server = options.count("rpc-http-endpoint" ) ?
               std::make_shared<fc::http::server>() :
               std::shared_ptr<fc::http::server>();

      if( _http_server )
      {
         ilog( "Listening for incoming HTTP RPC requests on ${p}", ("p", options.at("rpc-http-endpoint").as<std::string>() ) );
         _http_server->listen( fc::ip::endpoint::resolve_string(options.at("rpc-http-endpoint").as<std::string>()).back() );
         //
         // due to implementation, on_request() must come AFTER listen()
         //
         _http_server->on_request(
            [&]( const fc::http::request& req, const fc::http::server::response& resp )
            {
               std::shared_ptr< fc::rpc::http_api_connection > conn =
                  std::make_shared< fc::rpc::http_api_connection>();
               conn->register_api( wapi );
               conn->on_request( req, resp );
            } );
      }

      if( !options.count( "daemon" ) )
      {
         wallet_cli->register_api( wapi );
         if( options.count("from-command-file") )
         {
             wallet_cli->set_command_file(options.at( "from-command-file" ).as<std::string>());
         }
         wallet_cli->start();
         wallet_cli->wait();
      }
      else
      {
        fc::promise<int>::ptr exit_promise = new fc::promise<int>("UNIX Signal Handler");
        fc::set_signal_handler([&exit_promise](int signal) {
           exit_promise->set_value(signal);
        }, SIGINT);

        ilog( "Entering Daemon Mode, ^C to exit" );
        exit_promise->wait();
      }

      if( !wapi->is_locked() )
         wapi->save_wallet_file(wallet_file.generic_string());
      locked_connection.disconnect();
      closed_connection.disconnect();
   }
   catch ( const fc::exception& e )
   {
      std::cerr << e.to_detail_string() << std::endl;
      return EXIT_FAILURE;
   }
   catch ( const std::exception& e )
   {
      std::cerr << e.what() << std::endl;
      return EXIT_FAILURE;
   }

   return EXIT_SUCCESS;
}


text:
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <time.h>
#include <yaml-cpp/yaml.h>

#include <boost/filesystem.hpp>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

#include "nexus/backend/model_ins_simple.h"
#include "nexus/common/block_queue.h"
#include "nexus/common/device.h"
#include "nexus/common/model_db.h"
#include "nexus/common/typedef.h"
#include "nexus/proto/nnquery.pb.h"

DEFINE_int32(gpu, 0, "GPU device id");
DEFINE_string(framework, "tensorflow", "Framework");
DEFINE_string(model, "", "Model name");
DEFINE_int32(model_version, 1, "Version");
DEFINE_int32(min_batch, 1, "Minimum batch size");
DEFINE_int32(max_batch, 64, "Maximum batch size");
DEFINE_string(output, "", "Output file");
DEFINE_int32(height, 0, "Image height");
DEFINE_int32(width, 0, "Image width");

namespace nexus {
namespace backend {

using duration = std::chrono::microseconds;

class LoadTest {
 public:
  LoadTest(int gpu, const std::string& framework, const std::string& model_name,
           int model_version, int height = 0, int width = 0)
      : gpu_(gpu) {
    model_info_ = ModelDatabase::Singleton().GetModelInfo(framework, model_name,
                                                          model_version);
    CHECK(model_info_ != nullptr) << "Cannot find model info for " << framework
                                  << ":" << model_name << ":" << model_version;
    // Init model session
    model_sess_.set_framework(framework);
    model_sess_.set_model_name(model_name);
    model_sess_.set_version(model_version);
    model_sess_.set_latency_sla(50000);
    if (height > 0) {
      CHECK_GT(width, 0) << "Height and width must be set together";
      model_sess_.set_image_height(height);
      model_sess_.set_image_width(width);
    } else {
      if ((*model_info_)["resizable"] &&
          (*model_info_)["resizable"].as<bool>()) {
        // Set default image size for resizable CNN
        model_sess_.set_image_height(
            (*model_info_)["image_height"].as<uint32_t>());
        model_sess_.set_image_width(
            (*model_info_)["image_width"].as<uint32_t>());
      }
    }
    LOG(INFO) << model_sess_.DebugString();
    model_sessions_.push_back(ModelSessionToString(model_sess_));
    LOG(INFO) << "Profile model " << ModelSessionToProfileID(model_sess_);
    // Get test dataset
    cpu_device_ = DeviceManager::Singleton().GetCPUDevice();
#ifdef USE_GPU
    // Init GPU device
    NEXUS_CUDA_CHECK(cudaSetDevice(gpu_));
    gpu_device_ = DeviceManager::Singleton().GetGPUDevice(gpu_);
#else
    if (gpu_ != -1) {
      LOG(FATAL) << "The code is compiled without USE_GPU. Please set "
                    "`-gpu=-1` to profile on CPU.";
    }
#endif
  }

  void TestTime(int min_batch, int max_batch, const std::string output = "",
                int repeat = 10) {
    std::ostream* fout;
    if (output.length() == 0) {
      fout = &std::cout;
    } else {
      fout = new std::ofstream(output, std::ofstream::out);
    }
#ifdef USE_GPU
    *fout << gpu_device_->device_name() << "\n";
    *fout << gpu_device_->uuid() << "\n";
#endif

    ModelInstanceConfig config;
    config.add_model_session()->CopyFrom(model_sess_);
    size_t batch_size = 64;
    config.set_batch(batch_size);
    config.set_max_batch(batch_size);

    std::unique_ptr<ModelInstanceSimple> models[300];
    for (int i = 0; i < 10; i++) {
      auto beg = std::chrono::high_resolution_clock::now();
      CreateModelInstanceSimple(gpu_, config, ModelIndex(0), &models[i]);
      auto end = std::chrono::high_resolution_clock::now();
      auto forward = std::chrono::duration_cast<duration>(end - beg).count();
      std::cout << i + 1 << "," << forward << "\n";
    }
  }

  void TestLimit(int min_batch, int max_batch, const std::string output = "",
                 int repeat = 10) {
    std::ostream* fout;
    if (output.length() == 0) {
      fout = &std::cout;
    } else {
      fout = new std::ofstream(output, std::ofstream::out);
    }
#ifdef USE_GPU
    *fout << gpu_device_->device_name() << "\n";
    *fout << gpu_device_->uuid() << "\n";
#endif

    ModelInstanceConfig config;
    config.add_model_session()->CopyFrom(model_sess_);
    size_t batch_size = 64;
    config.set_batch(batch_size);
    config.set_max_batch(batch_size);

    std::unique_ptr<ModelInstanceSimple> models[10086];
    for (int i = 0;; i++) {
      CreateModelInstanceSimple(gpu_, config, ModelIndex(0), &models[i]);
      for (int j = 0; j < 2; ++j) {
        auto input_array = models[i]->CreateInputGpuArray();
      }
      models[i]->ForwardSimple(batch_size);
      auto bytes = models[i]->GetBytesInUse();
      auto peak_bytes = models[i]->GetPeakBytesInUse();
      std::cout << i + 1 << "," << bytes << "," << peak_bytes << "\n";
      std::cout << std::flush;
    }
  }

 private:
  template <class T>
  std::pair<float, float> GetStats(const std::vector<T>& lats) {
    float mean = 0.;
    float std = 0.;
    for (uint i = 0; i < lats.size(); ++i) {
      mean += lats[i];
    }
    mean /= lats.size();
    for (uint i = 0; i < lats.size(); ++i) {
      std += (lats[i] - mean) * (lats[i] - mean);
    }
    std = sqrt(std / (lats.size() - 1));
    return {mean, std};
  }

 private:
  int gpu_;
  ModelSession model_sess_;
  const YAML::Node* model_info_;
  std::string framework_;
  std::string model_name_;
  int version_;
  int height_;
  int width_;
  std::vector<std::string> model_sessions_;
  CPUDevice* cpu_device_;
#ifdef USE_GPU
  GPUDevice* gpu_device_;
#endif
};

}  // namespace backend
}  // namespace nexus

int main(int argc, char** argv) {
  using namespace nexus;
  using namespace nexus::backend;

  // log to stderr
  FLAGS_logtostderr = 1;
  // Init glog
  google::InitGoogleLogging(argv[0]);
  // Parse command line flags
  google::ParseCommandLineFlags(&argc, &argv, true);
  // Setup backtrace on segfault
  google::InstallFailureSignalHandler();
  // Check flags
  CHECK_GT(FLAGS_framework.length(), 0) << "Missing framework";
  CHECK_GT(FLAGS_model.length(), 0) << "Missing model";
  srand(time(NULL));

  LoadTest load(FLAGS_gpu, FLAGS_framework, FLAGS_model, FLAGS_model_version,
                FLAGS_height, FLAGS_width);
  // load.TestTime(FLAGS_min_batch, FLAGS_max_batch, FLAGS_output);
  load.TestLimit(FLAGS_min_batch, FLAGS_max_batch, FLAGS_output);
}

max_stars_repo_name: dengwxn/nexuslb

max_issues_repo_name: dengwxn/nexuslb

max_forks_repo_name: dengwxn/nexuslb