text:
#include "StoredQuery.h"
#include "FeatureID.h"
#include "WfsConst.h"
#include "WfsException.h"
#include "XmlUtils.h"
#include <boost/algorithm/string.hpp>
#include <macgyver/StringConversion.h>
#include <macgyver/TypeName.h>
#include <macgyver/Exception.h>
#include <set>
#include <sstream>

namespace ba = boost::algorithm;
namespace bw = SmartMet::Plugin::WFS;
namespace bwx = SmartMet::Plugin::WFS::Xml;

static void check_param_max_occurs(int actual_count,
                                   int max_occurs,
                                   const std::string& location,
                                   const std::string& param_name);

static void check_param_min_occurs(int actual_count,
                                   int min_occurs,
                                   const std::string& location,
                                   const std::string& param_name);

bwx::ParameterExtractor bw::StoredQuery::param_extractor;

bw::StoredQuery::StoredQuery() : handler(), debug_format(false) {}

bw::StoredQuery::~StoredQuery() {}

bw::QueryBase::QueryType bw::StoredQuery::get_type() const
{
  return STORED_QUERY;
}

std::string bw::StoredQuery::get_cache_key() const
{
  return cache_key;
}

boost::shared_ptr<bw::StoredQuery> bw::StoredQuery::create_from_kvp(
    const std::string& language,
    const StandardPresentationParameters& spp,
    const SmartMet::Spine::HTTP::Request& http_request,
    const bw::StoredQueryMap& stored_query_map)
{
  try
  {
    bool redirect = false;
    std::string query_id;
    std::string redirected_query_id;
    std::set<std::string> redirect_id_set;

    if (not get_kvp_stored_query_id(http_request, &query_id))
    {
      Fmi::Exception exception(BCP, "Failed to extract 'storedquery_id'!");
      exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
      throw exception;
    }

    redirect_id_set.insert(query_id);

    boost::shared_ptr<bw::StoredQuery> query(new bw::StoredQuery);

    do
    {
      query->language = language;

      // Get stored query handler object by storedquery_id parameter value
      query->handler = stored_query_map.get_handler_by_name(query_id);

      // Extract KVP query parameters convert them to appropriate types
      auto config = query->handler->get_config();
      bw::StoredQuery::extract_kvp_parameters(http_request, *config, *query);
      query->params = query->handler->process_params(query_id, query->orig_params);

      redirected_query_id = "";
      redirect = query->handler->redirect(*query, redirected_query_id);
      if (redirect)
      {
        if (redirect_id_set.insert(redirected_query_id).second and (redirected_query_id != ""))
        {
          query_id = redirected_query_id;
        }
        else
        {
          throw Fmi::Exception(
              BCP,
              "SmartMet::Plugin::WFS::StoredQuery::create_from_xml: invalid"
              " stored query redirect");
        }
      }
    } while (redirect);

    query->id = query_id;
    query->debug_format = spp.get_output_format() == "debug";
    // We do not need query sequence number here

    bw::FeatureID feature_id(query_id, query->params->get_map(), 0);
    feature_id.add_param("source", query->handler->get_data_source());
    feature_id.add_param("language", language);
    if (query->debug_format)
      feature_id.add_param("debugFormat", 1);
    query->cache_key = feature_id.get_id();
    query->set_stale_seconds(query->handler->get_config()->get_expires_seconds());

    return query;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

boost::shared_ptr<bw::StoredQuery> bw::StoredQuery::create_from_xml(
    const std::string& language,
    const StandardPresentationParameters& spp,
    const xercesc::DOMElement& element,
    const bw::StoredQueryMap& stored_query_map)
{
  try
  {
    bool redirect = false;
    std::string query_id;
    std::string redirected_query_id;
    std::set<std::string> redirect_id_set;

    if (not get_xml_stored_query_id(element, &query_id))
    {
      Fmi::Exception exception(BCP, "Failed to extract stored query ID!");
      exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
      throw exception;
    }

    redirect_id_set.insert(query_id);

    boost::shared_ptr<bw::StoredQuery> query(new bw::StoredQuery);

    do
    {
      query->language = language;

      // Get stored query handler object by storedquery_id parameter value
      query->handler = stored_query_map.get_handler_by_name(query_id);

      // Extract KVP query parameters convert them to appropriate types
      auto config = query->handler->get_config();
      bw::StoredQuery::extract_xml_parameters(element, *config, *query);
      query->params = query->handler->process_params(query_id, query->orig_params);

      redirected_query_id = "";
      redirect = query->handler->redirect(*query, redirected_query_id);
      if (redirect)
      {
        if (redirect_id_set.insert(redirected_query_id).second and (redirected_query_id != ""))
        {
          query_id = redirected_query_id;
        }
        else
        {
          throw Fmi::Exception(
              BCP,
              "SmartMet::Plugin::WFS::StoredQuery::create_from_xml: invalid"
              " stored query redirect");
        }
      }
    } while (redirect);

    query->id = query_id;
    query->debug_format = spp.get_output_format() == "debug";

    bw::FeatureID feature_id(query_id, query->params->get_map(), 0);
    feature_id.add_param("source", query->handler->get_data_source());
    feature_id.add_param("language", language);
    if (query->debug_format)
      feature_id.add_param("debugFormat", 1);
    query->cache_key = feature_id.get_id();
    query->set_stale_seconds(query->handler->get_config()->get_expires_seconds());

    return query;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

boost::shared_ptr<bw::StoredQuery> bw::StoredQuery::create_from_feature_id(
    const std::string& feature_id_str,
    const StoredQueryMap& sq_map,
    const bw::StoredQuery& orig_query)
{
  try
  {
    boost::shared_ptr<bw::FeatureID> feature_id = bw::FeatureID::create_from_id(feature_id_str);
    const std::string& query_id = feature_id->get_stored_query_id();

    boost::shared_ptr<bw::StoredQuery> query(new bw::StoredQuery);
    query->id = query_id;
    boost::shared_ptr<bw::RequestParameterMap> param_map(
        new RequestParameterMap(feature_id->get_params()));
    query->params = param_map;
    query->orig_params = param_map;
    query->handler = sq_map.get_handler_by_name(query_id);

    query->language = orig_query.language;
    query->debug_format = orig_query.debug_format;

    bw::FeatureID cache_feature_id(query_id, query->params->get_map(), 0);
    cache_feature_id.add_param("source", query->handler->get_data_source());
    cache_feature_id.add_param("language", query->language);
    if (query->debug_format)
      cache_feature_id.add_param("debugFormat", 1);
    query->cache_key = cache_feature_id.get_id();
    query->set_stale_seconds(query->handler->get_config()->get_expires_seconds());

    return query;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

void bw::StoredQuery::execute(std::ostream& output, const std::string& language, const boost::optional<std::string>& hostname) const
{
  try
  {
    assert(handler != nullptr);

    handler->query(*this, language, hostname, output);
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

const SmartMet::Spine::Value& bw::StoredQuery::get_param(const std::string& name) const
{
  try
  {
    auto range = params->get_map().equal_range(name);
    if (range.first == range.second)
    {
      Fmi::Exception exception(BCP, "Mandatory parameter '" + name + "' missing!");
      exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
      throw exception;
    }

    const SmartMet::Spine::Value& v = (range.first++)->second;

    if (range.first != range.second)
    {
      Fmi::Exception exception(BCP, "'" + name + "' specified more than once!");
      exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
      throw exception;
    }

    return v;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

std::vector<SmartMet::Spine::Value> bw::StoredQuery::get_param_values(const std::string& name) const
{
  try
  {
    std::vector<SmartMet::Spine::Value> result = params->get_values(name);
    return result;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

bool bw::StoredQuery::get_kvp_stored_query_id(const SmartMet::Spine::HTTP::Request& http_request,
                                              std::string* stored_query_id)
{
  try
  {
    // Verify whether we have request=getFeature in HTTP request
    auto request = http_request.getParameter("request");

    if (not request)
      return false;

    if (not ba::iequals(*request, "getFeature") and not ba::iequals(*request, "getPropertyValue"))
      return false;

    // Verify whether we have storedquery_id in HTTP request parameters and return it
    // if found.
    auto sqi = http_request.getParameter("storedquery_id");
    if (sqi)
    {
      *stored_query_id = *sqi;
      return true;
    }
    else
    {
      return false;
    }
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

bool bw::StoredQuery::get_xml_stored_query_id(const xercesc::DOMElement& query_root,
                                              std::string* stored_query_id)
{
  try
  {
    try
    {
      const std::string ns = bwx::to_string(query_root.getNamespaceURI());
      const std::string name = bwx::to_string(query_root.getLocalName());
      if ((ns == WFS_NAMESPACE_URI) and (name == "StoredQuery"))
      {
        const std::string id = bwx::get_mandatory_attr(query_root, WFS_NAMESPACE_URI, "id");
        *stored_query_id = id;
        return true;
      }
      return false;
    }
    catch (...)
    {
      Fmi::Exception exception(BCP, "Operation failed!", nullptr);
      if (exception.getExceptionByParameterName(WFS_EXCEPTION_CODE) == nullptr)
        exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
      throw exception;
    }
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

void bw::StoredQuery::extract_kvp_parameters(const SmartMet::Spine::HTTP::Request& request,
                                             const StoredQueryConfig& config,
                                             bw::StoredQuery& query)
{
  try
  {
    const char* method = "SmartMet::Plugin::WFS::StoredQuery::extract_kvp_parameters";

    query.params.reset(new bw::RequestParameterMap);
    query.orig_params = query.params;
    query.skipped_params.clear();

    auto param_desc_map = config.get_param_descriptions();

    const auto& params = request.getParameterMap();

    std::multiset<std::string> param_name_set;
    std::set<std::string> forbidden;

    BOOST_FOREACH (const auto& item, params)
    {
      const std::string& param_name = Fmi::ascii_tolower_copy(item.first);
      const std::string& value_str = item.second;

      auto desc_it = param_desc_map.find(param_name);
      const auto& param_desc = desc_it->second;

      if (forbidden.count(param_name))
      {
        std::string sep = " ";
        std::ostringstream msg;
        msg << method << ": stored query parameter '" << item.first << "' conflicts with";
        for (auto it = param_desc.conflicts_with.begin(); it != param_desc.conflicts_with.end();
             ++it)
        {
          msg << sep << "'" << *it << "'";
          sep = ", ";
        }
        Fmi::Exception exception(BCP, msg.str());
        exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
        throw exception;
      }

      const bw::StoredQueryParamDef& param_def = param_desc.param_def;
      if (desc_it == param_desc_map.end())
      {
        /* Skip unknown parameters (required to support GetFeatureById) */
        /* Save skipped parameters information however for logging purposes */
        std::ostringstream msg;
        msg << param_name << "="
            << "'" << value_str << "'";
        query.skipped_params.push_back(msg.str());
      }
      else
      {
        // Parameter is not yet processed, therefore compare with count + 1
        check_param_max_occurs(param_name_set.count(param_name) + 1,
                               param_desc.max_occurs,
                               "SmartMet::Plugin::WFS::StoredQuery::extract_kvp_parameters",
                               param_name);

        try
        {
          if (param_def.isArray())
          {
            std::vector<std::string> parts;
            ba::split(parts, value_str, ba::is_any_of(","));
            // FIXME: unescape parts if needed (for example escaped ','
            std::vector<SmartMet::Spine::Value> new_values = param_def.readValues(parts);
            BOOST_FOREACH (const auto& value, new_values)
            {
              value.check_limits(param_desc.lower_limit, param_desc.upper_limit);
              query.params->insert_value(param_name, value);
            }
          }
          else
          {
            std::vector<SmartMet::Spine::Value> vect;
            SmartMet::Spine::Value value = param_def.readValue(value_str);
            value.check_limits(param_desc.lower_limit, param_desc.upper_limit);
            query.params->insert_value(param_name, value);
          }

          for (auto it = param_desc.conflicts_with.begin(); it != param_desc.conflicts_with.end();
               ++it)
          {
            forbidden.insert(Fmi::ascii_tolower_copy(*it));
          }

          param_name_set.insert(param_name);
        }
        catch (...)
        {
          std::ostringstream msg;
          msg << "While parsing value '" << value_str << "' of request parameter '" << param_name
              << "'";
          Fmi::Exception exception(BCP, "Operation failed!", nullptr);
          exception.addDetail(msg.str());
          throw exception;
        }
      }
    }

    // Now verify that all mandatory parameters are specified enough times
    BOOST_FOREACH (const auto& param_desc, param_desc_map)
    {
      check_param_min_occurs(param_name_set.count(param_desc.second.name),
                             param_desc.second.min_occurs,
                             "SmartMet::Plugin::WFS::StoredQuery::extract_xml_parameters",
                             param_desc.second.name);
    }
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

void bw::StoredQuery::extract_xml_parameters(const xercesc::DOMElement& query_root,
                                             const StoredQueryConfig& config,
                                             bw::StoredQuery& query)
{
  try
  {
    const char* method = "SmartMet::Plugin::WFS::StoredQuery::extract_xml_parameters";

    query.params.reset(new bw::RequestParameterMap);
    query.orig_params = query.params;
    query.skipped_params.clear();

    std::multiset<std::string> param_name_set;
    std::set<std::string> forbidden;

    std::vector<xercesc::DOMElement*> param_elements =
        bwx::get_child_elements(query_root, WFS_NAMESPACE_URI, "Parameter");

    const auto& param_desc_map = config.get_param_descriptions();

    BOOST_FOREACH (const xercesc::DOMElement* element, param_elements)
    {
      const std::string& param_name = bwx::get_mandatory_attr(*element, WFS_NAMESPACE_URI, "name");

      auto desc_it = param_desc_map.find(Fmi::ascii_tolower_copy(param_name));
      if (desc_it == param_desc_map.end())
      {
        /* Skip unknown parameters (required to support GetFeatureById) */
        /* Save skipped parameters information however for logging purposes */
        query.skipped_params.push_back(bwx::xml2string(element));
      }
      else
      {
        const auto& param_desc = desc_it->second;

        if (forbidden.count(param_name))
        {
          std::string sep = " ";
          std::ostringstream msg;
          msg << method << ": stored query parameter '" << param_name << "' conflicts with";
          for (auto it = param_desc.conflicts_with.begin(); it != param_desc.conflicts_with.end();
               ++it)
          {
            msg << sep << "'" << *it << "'";
            sep = ", ";
          }
          Fmi::Exception exception(BCP, msg.str());
          throw exception;
        }

        for (auto it = param_desc.conflicts_with.begin(); it != param_desc.conflicts_with.end();
             ++it)
        {
          forbidden.insert(Fmi::ascii_tolower_copy(*it));
        }

        check_param_max_occurs(param_name_set.count(param_name) + 1,
                               param_desc.max_occurs,
                               "SmartMet::Plugin::WFS::StoredQuery::extract_xml_parameters",
                               param_name);

	try {
	  const auto values = param_extractor.extract_param(*element, param_desc.xml_type);

	  BOOST_FOREACH (const auto& value, values)
	    {
	      value.check_limits(param_desc.lower_limit, param_desc.upper_limit);
	      query.params->insert_value(param_name, value);
	    }

	  param_name_set.insert(param_name);
	} catch (Fmi::Exception& e) {
	  e.addDetail("Query parameter name '" + param_name + "'");
	  throw;
	}
      }
    }

    // Now verify that all mandatory parameters are specified enough times
    BOOST_FOREACH (const auto& param_desc, param_desc_map)
    {
      check_param_min_occurs(param_name_set.count(param_desc.second.name),
                             param_desc.second.min_occurs,
                             "SmartMet::Plugin::WFS::StoredQuery::extract_xml_parameters",
                             param_desc.second.name);
    }
  }
  catch (...)
  {
    Fmi::Exception exception(BCP, "Operation parsing failed!", nullptr);
    if (exception.getExceptionByParameterName(WFS_EXCEPTION_CODE) == nullptr)
      exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
    throw exception;
  }
}

void bw::StoredQuery::dump_query_info(std::ostream& output) const
{
  try
  {
    std::ostringstream msg;
    std::string sep = "";
    msg << "STORED QUERY: name='" << handler->get_query_name() << "', ";
    msg << "params={";

    // Collect parameter names for message
    const auto names = params->get_keys();

    BOOST_FOREACH (const auto& name, names)
    {
      msg << sep << name << "=(";
      auto range = params->get_map().equal_range(name);
      for (auto it = range.first; it != range.second; ++it)
      {
        msg << '(' << it->second << ')';
      }
      msg << ')';
      sep = "; ";
    }

    msg << "}, ";
    if (not skipped_params.empty())
    {
      sep = "";
      msg << "skipped_params=(";
      BOOST_FOREACH (const auto& param, skipped_params)
      {
        msg << sep << '"' << param << '"';
        sep = ", ";
      }
      msg << ')';
    }
    msg << "\n";

    output << msg.str() << std::flush;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

void check_param_max_occurs(int actual_count,
                            int max_occurs,
                            const std::string& location,
                            const std::string& param_name)
{
  try
  {
    if (actual_count > max_occurs)
    {
      std::ostringstream msg;
      msg << location << ": parameter '" << param_name << "' specified more than ";
      if (max_occurs == 1)
      {
        msg << "once";
      }
      else
      {
        msg << max_occurs << " times";
      }
      msg << " (found " << actual_count << " occurances)";

      Fmi::Exception exception(BCP, msg.str());
      exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
      throw exception;
    }
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

void check_param_min_occurs(int actual_count,
                            int min_occurs,
                            const std::string& location,
                            const std::string& param_name)
{
  try
  {
    if (actual_count < min_occurs)
    {
      std::ostringstream msg;
      msg << location << ": parameter '" << param_name << "' must be specified at least "
          << min_occurs << " times (found " << actual_count << " occurrences).";
      Fmi::Exception exception(BCP, msg.str());
      exception.addParameter(WFS_EXCEPTION_CODE, WFS_OPERATION_PARSING_FAILED);
      throw exception;
    }
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

std::ostream& bw::operator<<(
    std::ostream& ost, const std::map<std::string, std::vector<SmartMet::Spine::Value> >& params)
{
  try
  {
    ost << '{';
    BOOST_FOREACH (const auto& item, params)
    {
      ost << "('" << item.first << "' ==> (";
      std::copy(item.second.begin(),
                item.second.end(),
                std::ostream_iterator<SmartMet::Spine::Value>(ost));
      ost << ')';
    }
    ost << '}';
    return ost;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

max_stars_repo_name: nakkim/smartmet-plugin-wfs

max_issues_repo_name: nakkim/smartmet-plugin-wfs

max_forks_repo_name: nakkim/smartmet-plugin-wfs


text:
#include <memory>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <boost/thread/latch.hpp>
#include "CurrentThread.h"
#include "Thread.h"
#include "Exception.h"
#include "Logging.h"

namespace UBERS
{
  namespace CurrentThread
  {
    //* 缓存加速
    thread_local int t_cachedTid = 0;
    thread_local std::string t_tidString;
  } // namespace CurrentThread

  namespace detail
  {
    //* std::function<void()>
    using ThreadFunc = UBERS::Thread::ThreadFunc;

    void RunInThread(const ThreadFunc& func, pid_t* tid, boost::latch* latch)
    {
      *tid = UBERS::CurrentThread::tid();
      latch->count_down();

      try
      {
        func();
      }
      catch(const Exception& ex)
      {
        fprintf(stderr, "exception caught in Thread %d \n", CurrentThread::tid());
        fprintf(stderr, "reason: %s \n", ex.what());
        fprintf(stderr, "stack trace: %s\n", ex.stackTrace());
        abort();
      }
      catch(const std::exception& ex)
      {
        fprintf(stderr, "exception caught in Thread %d \n", CurrentThread::tid());
        fprintf(stderr, "reason: %s\n", ex.what());
        abort();
      }
      catch(...)
      {
        fprintf(stderr, "unkonwn exception caught in Thread %d\n", CurrentThread::tid());
        throw;
      }
    }
  }
}
using namespace UBERS;

bool CurrentThread::isMainThread()
{
  return tid() == getpid();
}

Thread::Thread(ThreadFunc func)
  : func_(std::move(func)),
    latch_(1),
    started_(false),
    tid_(0)
{
}

Thread::~Thread()
{
  if(started_ && !thread_->joinable())
    thread_->join();
}

void Thread::start()
{
  assert(!started_);
  started_ = true;
  thread_ = std::make_unique<std::jthread>(std::jthread(detail::RunInThread, func_, &tid_, &latch_));
  if(thread_ == nullptr)
  {
    started_ = false;
    LOG_OFF << "ThreadCreating is wrong!";
  }
  else
  {
    latch_.wait();
    assert(tid_ > 0);
  }
}

ext: cpp

max_stars_repo_name: fansehep/UBERS

max_issues_repo_name: fansehep/UBERS

max_forks_repo_name: fansehep/UBERS


text:
#include "my_project/project_library_version.h"
#include "my_project/dummy.h"

#include <boost/program_options.hpp>

#include <iostream>

using my_project::Dummy;
using boost::program_options::options_description;
using boost::program_options::parse_command_line;

int main(int argc, const char** argv) {
    options_description option_description{"Allowed options"};
    option_description.add_options()
            ("help,h", "produce help message")
            ("version", "show version");

    boost::program_options::variables_map variable_map;
    boost::program_options::store(parse_command_line(argc, argv, option_description),
                                  variable_map);
    boost::program_options::notify(variable_map);

    if (variable_map.count("help") > 0) {
        std::cout << option_description << std::endl;
        return 1;
    }

    if (variable_map.count("version") > 0) {
        std::cout << "version: "
                  << my_project::version_major
                  << "."
                  << my_project::version_minor
                  << "."
                  << my_project::version_patch
                  << std::endl;
        return 1;
    }

    Dummy english_dummy{"Hello", "World"};

    std::cout << "A english dummy says: " << english_dummy.say_hello() << std::endl;
    return 0;
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2013-2018 Regents of the University of California.
 *
 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
 *
 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * ndn-cxx library 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 Lesser General Public License for more details.
 *
 * You should have received copies of the GNU General Public License and GNU Lesser
 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 */

#ifndef NDN_SECURITY_V2_TRUST_ANCHOR_CONTAINER_HPP
#define NDN_SECURITY_V2_TRUST_ANCHOR_CONTAINER_HPP

#include "trust-anchor-group.hpp"
#include "certificate.hpp"
#include "../../interest.hpp"

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/mem_fun.hpp>

namespace ndn {
namespace security {
namespace v2 {

/**
 * @brief represents a container for trust anchors.
 *
 * There are two kinds of anchors:
 * - static anchors that are permanent for the lifetime of the container
 * - dynamic anchors that are periodically updated.
 *
 * Trust anchors are organized in groups. Each group has a unique group id.  The same anchor
 * certificate (same name without considering the implicit digest) can be inserted into
 * multiple groups, but no more than once into each.
 *
 * Dynamic groups are created using the appropriate TrustAnchorContainer::insert method. Once
 * created, the dynamic anchor group cannot be updated.
 *
 * The returned pointer to Certificate from `find` methods is only guaranteed to be valid until
 * the next invocation of `find` and may be invalidated afterwards.
 */
class TrustAnchorContainer : noncopyable
{
public:
  class Error : public std::runtime_error
  {
  public:
    using std::runtime_error::runtime_error;
  };

  /**
   * @brief Insert a static trust anchor.
   *
   * @param groupId  Certificate group id.
   * @param cert     Certificate to insert.
   *
   * If @p cert (same name without considering implicit digest) already exists in the group @p
   * groupId, this method has no effect.
   *
   * @throw Error @p groupId is a dynamic anchor group .
   */
  void
  insert(const std::string& groupId, Certificate&& cert);

  /**
   * @brief Insert dynamic trust anchors from path.
   *
   * @param groupId        Certificate group id, must not be empty.
   * @param path           Specifies the path to load the trust anchors.
   * @param refreshPeriod  Refresh period for the trust anchors, must be positive.
   *                       Relevant trust anchors will only be updated when find is called
   * @param isDir          Tells whether the path is a directory or a single file.
   *
   * @throw std::invalid_argument @p refreshPeriod is not positive
   * @throw Error a group with @p groupId already exists
   */
  void
  insert(const std::string& groupId, const boost::filesystem::path& path,
         time::nanoseconds refreshPeriod, bool isDir = false);

  /**
   * @brief Remove all static or dynamic anchors
   */
  void
  clear();

  /**
   * @brief Search for certificate across all groups (longest prefix match)
   * @param keyName  Key name prefix for searching the certificate.
   * @return The found certificate, nullptr if not found.
   *
   * @note The returned value may be invalidated after next call to one of `find` methods.
   */
  const Certificate*
  find(const Name& keyName) const;

  /**
   * @brief Find certificate given interest
   * @param interest  The input interest packet.
   * @return The found certificate, nullptr if not found.
   *
   * @note The returned value may be invalidated after next call to one of `find` methods.
   *
   * @note Interest with implicit digest is not supported.
   *
   * @note ChildSelector is not supported.
   */
  const Certificate*
  find(const Interest& interest) const;

  /**
   * @brief Get trusted anchor group
   * @throw Error @p groupId does not exist
   */
  TrustAnchorGroup&
  getGroup(const std::string& groupId) const;

  /**
   * @brief Get number of trust anchors across all groups
   */
  size_t
  size() const;

private:
  void
  refresh();

private:
  using AnchorContainerBase = boost::multi_index::multi_index_container<
    Certificate,
    boost::multi_index::indexed_by<
      boost::multi_index::ordered_unique<
        boost::multi_index::const_mem_fun<Data, const Name&, &Data::getName>
      >
    >
  >;

  class AnchorContainer : public CertContainerInterface,
                          public AnchorContainerBase
  {
  public:
    void
    add(Certificate&& cert) final;

    void
    remove(const Name& certName) final;

    void
    clear();
  };

  using GroupContainer = boost::multi_index::multi_index_container<
    shared_ptr<TrustAnchorGroup>,
    boost::multi_index::indexed_by<
      boost::multi_index::hashed_unique<
        boost::multi_index::const_mem_fun<TrustAnchorGroup, const std::string&, &TrustAnchorGroup::getId>
      >
    >
  >;

  GroupContainer m_groups;
  AnchorContainer m_anchors;
};

} // namespace v2
} // namespace security
} // namespace ndn

#endif // NDN_SECURITY_V2_TRUST_ANCHOR_CONTAINER_HPP

ext: hpp


text:
// test-SchemaItem-class.cc
//
// Copyright 2018 Jeffrey Kintscher <websurfer@surf2c.net>
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

#include <boost/test/unit_test.hpp>
#include "ParsedItemData.hh"
#include "SchemaItem.hh"

#define VARS_FILE       "SchemaItem-vars.hh"
#define TEST_OBJECT     sitem1
#define TEST_NAMESPACE  jsonschemaenforcer

BOOST_AUTO_TEST_SUITE( SchemaItem_class_test_suite )

BOOST_AUTO_TEST_CASE( test_SchemaItem_class )
{
    jsonschemaenforcer::ParsedItemData idata_integer,
                                 idata_number,
                                 idata_intnum1,
                                 idata_intnum2,
                                 idata_intnum3,
                                 idata_intnum4,
                                 idata_intnum5,
                                 idata_string;
    jsonschemaenforcer::SchemaItem sitem_integer,
                             sitem_number,
                             sitem_string,
                             sitem1;

    //
    // initialize ParsedItemData vars
    //

    idata_integer.set_item_type(jsonschemaenforcer::ItemType::type_Integer);
    idata_integer.set_item_exclusive_maximum(1);
    idata_integer.set_item_exclusive_minimum(2);
    idata_integer.set_item_maximum(3);
    idata_integer.set_item_minimum(4);
    idata_integer.set_item_multiple_of(5);

    idata_number.set_item_type(jsonschemaenforcer::ItemType::type_Number);
    idata_number.set_item_exclusive_maximum(1.1);
    idata_number.set_item_exclusive_minimum(2.1);
    idata_number.set_item_maximum(3.1);
    idata_number.set_item_minimum(4.1);
    idata_number.set_item_multiple_of(5.1);

    idata_intnum1.set_item_type(jsonschemaenforcer::ItemType::type_Integer);
    idata_intnum1.set_item_exclusive_maximum(1);
    idata_intnum1.set_item_exclusive_minimum(2.1);
    idata_intnum1.set_item_maximum(3.1);
    idata_intnum1.set_item_minimum(4.1);
    idata_intnum1.set_item_multiple_of(5.1);

    idata_intnum2.set_item_type(jsonschemaenforcer::ItemType::type_Integer);
    idata_intnum2.set_item_exclusive_maximum(1.1);
    idata_intnum2.set_item_exclusive_minimum(2);
    idata_intnum2.set_item_maximum(3.1);
    idata_intnum2.set_item_minimum(4.1);
    idata_intnum2.set_item_multiple_of(5.1);

    idata_intnum3.set_item_type(jsonschemaenforcer::ItemType::type_Integer);
    idata_intnum3.set_item_exclusive_maximum(1.1);
    idata_intnum3.set_item_exclusive_minimum(2.1);
    idata_intnum3.set_item_maximum(3);
    idata_intnum3.set_item_minimum(4.1);
    idata_intnum3.set_item_multiple_of(5.1);

    idata_intnum4.set_item_type(jsonschemaenforcer::ItemType::type_Integer);
    idata_intnum4.set_item_exclusive_maximum(1.1);
    idata_intnum4.set_item_exclusive_minimum(2.1);
    idata_intnum4.set_item_maximum(3.1);
    idata_intnum4.set_item_minimum(4);
    idata_intnum4.set_item_multiple_of(5.1);

    idata_intnum5.set_item_type(jsonschemaenforcer::ItemType::type_Integer);
    idata_intnum5.set_item_exclusive_maximum(1.1);
    idata_intnum5.set_item_exclusive_minimum(2.1);
    idata_intnum5.set_item_maximum(3.1);
    idata_intnum5.set_item_minimum(4.1);
    idata_intnum5.set_item_multiple_of(5);

    idata_string.set_item_type(jsonschemaenforcer::ItemType::type_String);
    idata_string.set_item_max_length(256);
    idata_string.set_item_min_length(128);
    idata_string.set_item_pattern("foo[123]+");

    //
    // test object defaults
    //

    BOOST_CHECK(sitem1.empty());
#   include "var-obj-macros.hh"
    BOOST_CHECK(sitem1.empty());
    // BOOST_CHECK_EQUAL(sitem1.array_n_max_items, 0);
    // BOOST_CHECK_EQUAL(sitem1.array_n_min_items, 0);
    // BOOST_CHECK(sitem1.array_properties.empty());
    // BOOST_CHECK(!sitem1.array_b_unique);
    // BOOST_CHECK(!sitem1.b_has_array_max_items);
    // BOOST_CHECK(!sitem1.b_has_array_min_items);
    // BOOST_CHECK(!sitem1.b_has_array_properties);
    // BOOST_CHECK(!sitem1.b_has_array_unique);
    // BOOST_CHECK(!sitem1.b_has_int_exclusive_maximum);
    // BOOST_CHECK(!sitem1.b_has_int_exclusive_minimum);
    // BOOST_CHECK(!sitem1.b_has_int_maximum);
    // BOOST_CHECK(!sitem1.b_has_int_minimum);
    // BOOST_CHECK(!sitem1.b_has_int_multiple_of);
    // BOOST_CHECK(!sitem1.b_has_num_exclusive_maximum);
    // BOOST_CHECK(!sitem1.b_has_num_exclusive_minimum);
    // BOOST_CHECK(!sitem1.b_has_num_exclusive_minimum);
    // BOOST_CHECK(!sitem1.b_has_num_minimum);
    // BOOST_CHECK(!sitem1.b_has_num_multiple_of);
    // BOOST_CHECK(!sitem1.b_has_str_n_max_length);
    // BOOST_CHECK(!sitem1.b_has_str_n_min_length);
    // BOOST_CHECK(!sitem1.b_has_str_pattern);
    // BOOST_CHECK_EQUAL(sitem1.int_exclusive_maximum, 0);
    // BOOST_CHECK_EQUAL(sitem1.int_exclusive_minimum, 0);
    // BOOST_CHECK_EQUAL(sitem1.int_maximum, 0);
    // BOOST_CHECK_EQUAL(sitem1.int_minimum, 0);
    // BOOST_CHECK_EQUAL(sitem1.int_multiple_of, 0);
    // BOOST_CHECK_EQUAL(sitem1.item_type, jsonschemaenforcer::ItemType::type_Unknown);
    // BOOST_CHECK_EQUAL(sitem1.key, "");
    // BOOST_CHECK_EQUAL(sitem1.num_exclusive_maximum, 0);
    // BOOST_CHECK_EQUAL(sitem1.num_exclusive_minimum, 0);
    // BOOST_CHECK_EQUAL(sitem1.num_maximum, 0);
    // BOOST_CHECK_EQUAL(sitem1.num_minimum, 0);
    // BOOST_CHECK_EQUAL(sitem1.num_multiple_of, 0);
    // BOOST_CHECK_EQUAL(sitem1.str_n_max_length, 0);
    // BOOST_CHECK_EQUAL(sitem1.str_n_min_length, 0);
    // BOOST_CHECK_EQUAL(sitem1.str_pattern, "");
    // BOOST_CHECK(sitem1.get_type_name().empty());

    //
    // check setting values
    //

#   define TEST_ALL_VALUES
    sitem1.clear();
    BOOST_CHECK(sitem1.empty());
#   include "var-obj-macros.hh"
#   undef TEST_ALL_VALUES
    BOOST_CHECK(!sitem1.empty());
    sitem1.clear();

    //
    // test itegers/numbers
    //

    BOOST_CHECK(sitem_integer.define_item("key_int", idata_integer));
    BOOST_CHECK(sitem_integer.has_Integer_type());
    BOOST_CHECK_EQUAL(sitem_integer.key, "key_int");
    BOOST_CHECK_EQUAL(sitem_integer.int_exclusive_maximum, 1);
    BOOST_CHECK_EQUAL(sitem_integer.int_exclusive_minimum, 2);
    BOOST_CHECK_EQUAL(sitem_integer.int_maximum, 3);
    BOOST_CHECK_EQUAL(sitem_integer.int_minimum, 4);
    BOOST_CHECK_EQUAL(sitem_integer.int_multiple_of, 5);
    BOOST_CHECK_EQUAL(sitem_integer.num_exclusive_maximum, 0);
    BOOST_CHECK_EQUAL(sitem_integer.num_exclusive_minimum, 0);
    BOOST_CHECK_EQUAL(sitem_integer.num_maximum, 0);
    BOOST_CHECK_EQUAL(sitem_integer.num_minimum, 0);
    BOOST_CHECK_EQUAL(sitem_integer.num_multiple_of, 0);
    BOOST_CHECK(!sitem_integer.array_b_unique);
    BOOST_CHECK(!sitem_integer.b_has_array_max_items);
    BOOST_CHECK(!sitem_integer.b_has_array_min_items);
    BOOST_CHECK(!sitem_integer.b_has_array_properties);
    BOOST_CHECK(!sitem_integer.b_has_array_unique);
    BOOST_CHECK(sitem_integer.b_has_int_exclusive_maximum);
    BOOST_CHECK(sitem_integer.b_has_int_exclusive_minimum);
    BOOST_CHECK(sitem_integer.b_has_int_maximum);
    BOOST_CHECK(sitem_integer.b_has_int_minimum);
    BOOST_CHECK(sitem_integer.b_has_int_multiple_of);
    BOOST_CHECK(!sitem_integer.b_has_num_exclusive_maximum);
    BOOST_CHECK(!sitem_integer.b_has_num_exclusive_minimum);
    BOOST_CHECK(!sitem_integer.b_has_num_exclusive_minimum);
    BOOST_CHECK(!sitem_integer.b_has_num_minimum);
    BOOST_CHECK(!sitem_integer.b_has_num_multiple_of);
    BOOST_CHECK(!sitem_integer.b_has_str_n_max_length);
    BOOST_CHECK(!sitem_integer.b_has_str_n_min_length);
    BOOST_CHECK(!sitem_integer.b_has_str_pattern);

    BOOST_CHECK(sitem_number.define_item("key_num", idata_number));
    BOOST_CHECK(sitem_number.has_Number_type());
    BOOST_CHECK_EQUAL(sitem_number.key, "key_num");
    BOOST_CHECK_EQUAL(sitem_number.int_exclusive_maximum, 0);
    BOOST_CHECK_EQUAL(sitem_number.int_exclusive_minimum, 0);
    BOOST_CHECK_EQUAL(sitem_number.int_maximum, 0);
    BOOST_CHECK_EQUAL(sitem_number.int_minimum, 0);
    BOOST_CHECK_EQUAL(sitem_number.int_multiple_of, 0);
    BOOST_CHECK_EQUAL(sitem_number.num_exclusive_maximum, 1.1);
    BOOST_CHECK_EQUAL(sitem_number.num_exclusive_minimum, 2.1);
    BOOST_CHECK_EQUAL(sitem_number.num_maximum, 3.1);
    BOOST_CHECK_EQUAL(sitem_number.num_minimum, 4.1);
    BOOST_CHECK_EQUAL(sitem_number.num_multiple_of, 5.1);
    BOOST_CHECK(!sitem_number.array_b_unique);
    BOOST_CHECK(!sitem_number.b_has_array_max_items);
    BOOST_CHECK(!sitem_number.b_has_array_min_items);
    BOOST_CHECK(!sitem_number.b_has_array_properties);
    BOOST_CHECK(!sitem_number.b_has_array_unique);
    BOOST_CHECK(!sitem_number.b_has_int_exclusive_maximum);
    BOOST_CHECK(!sitem_number.b_has_int_exclusive_minimum);
    BOOST_CHECK(!sitem_number.b_has_int_maximum);
    BOOST_CHECK(!sitem_number.b_has_int_minimum);
    BOOST_CHECK(!sitem_number.b_has_int_multiple_of);
    BOOST_CHECK(sitem_number.b_has_num_exclusive_maximum);
    BOOST_CHECK(sitem_number.b_has_num_exclusive_minimum);
    BOOST_CHECK(sitem_number.b_has_num_exclusive_minimum);
    BOOST_CHECK(sitem_number.b_has_num_minimum);
    BOOST_CHECK(sitem_number.b_has_num_multiple_of);
    BOOST_CHECK(!sitem_number.b_has_str_n_max_length);
    BOOST_CHECK(!sitem_number.b_has_str_n_min_length);
    BOOST_CHECK(!sitem_number.b_has_str_pattern);

    BOOST_CHECK(!sitem1.define_item("key_intnum1", idata_intnum1));
    sitem1.clear();
    BOOST_CHECK(!sitem1.define_item("key_intnum2", idata_intnum2));
    sitem1.clear();
    BOOST_CHECK(!sitem1.define_item("key_intnum3", idata_intnum3));
    sitem1.clear();
    BOOST_CHECK(!sitem1.define_item("key_intnum4", idata_intnum4));
    sitem1.clear();
    BOOST_CHECK(!sitem1.define_item("key_intnum5", idata_intnum5));

    //
    // test strings
    //

    BOOST_CHECK(sitem_string.define_item("key_string", idata_string));
    BOOST_CHECK_EQUAL(sitem_number.int_exclusive_maximum, 0);
    BOOST_CHECK_EQUAL(sitem_number.int_exclusive_minimum, 0);
    BOOST_CHECK_EQUAL(sitem_number.int_maximum, 0);
    BOOST_CHECK_EQUAL(sitem_number.int_minimum, 0);
    BOOST_CHECK_EQUAL(sitem_number.int_multiple_of, 0);
    BOOST_CHECK_EQUAL(sitem_integer.num_exclusive_maximum, 0);
    BOOST_CHECK_EQUAL(sitem_integer.num_exclusive_minimum, 0);
    BOOST_CHECK_EQUAL(sitem_integer.num_maximum, 0);
    BOOST_CHECK_EQUAL(sitem_integer.num_minimum, 0);
    BOOST_CHECK_EQUAL(sitem_integer.num_multiple_of, 0);
    BOOST_CHECK(sitem_string.has_String_type());
    BOOST_CHECK_EQUAL(sitem_string.key, "key_string");
    BOOST_CHECK_EQUAL(sitem_string.str_n_max_length, 256);
    BOOST_CHECK_EQUAL(sitem_string.str_n_min_length, 128);
    BOOST_CHECK_EQUAL(sitem_string.str_pattern, "foo[123]+");
    BOOST_CHECK(!sitem_string.array_b_unique);
    BOOST_CHECK(!sitem_string.b_has_array_max_items);
    BOOST_CHECK(!sitem_string.b_has_array_min_items);
    BOOST_CHECK(!sitem_string.b_has_array_properties);
    BOOST_CHECK(!sitem_string.b_has_array_unique);
    BOOST_CHECK(!sitem_string.b_has_int_exclusive_maximum);
    BOOST_CHECK(!sitem_string.b_has_int_exclusive_minimum);
    BOOST_CHECK(!sitem_string.b_has_int_maximum);
    BOOST_CHECK(!sitem_string.b_has_int_minimum);
    BOOST_CHECK(!sitem_string.b_has_int_multiple_of);
    BOOST_CHECK(!sitem_string.b_has_num_exclusive_maximum);
    BOOST_CHECK(!sitem_string.b_has_num_exclusive_minimum);
    BOOST_CHECK(!sitem_string.b_has_num_exclusive_minimum);
    BOOST_CHECK(!sitem_string.b_has_num_minimum);
    BOOST_CHECK(!sitem_string.b_has_num_multiple_of);
    BOOST_CHECK(sitem_string.b_has_str_n_max_length);
    BOOST_CHECK(sitem_string.b_has_str_n_min_length);
    BOOST_CHECK(sitem_string.b_has_str_pattern);

    //
    // test equality
    //

    sitem1.clear();
    BOOST_CHECK(sitem1 != sitem_integer);
    BOOST_CHECK(sitem1 != sitem_number);
    BOOST_CHECK(sitem1 != sitem_string);
    BOOST_CHECK(sitem_string != sitem1);
    BOOST_CHECK(sitem_string != sitem_integer);
    BOOST_CHECK(sitem_string != sitem_number);
    BOOST_CHECK(sitem_integer != sitem1);
    BOOST_CHECK(sitem_integer != sitem_number);
    BOOST_CHECK(sitem_integer != sitem_string);
    BOOST_CHECK(sitem_number != sitem1);
    BOOST_CHECK(sitem_number != sitem_integer);
    BOOST_CHECK(sitem_number != sitem_string);

    sitem1 = sitem_integer;
    BOOST_CHECK(sitem1 == sitem_integer);
    BOOST_CHECK(sitem1 != sitem_number);
    BOOST_CHECK(sitem1 != sitem_string);
    BOOST_CHECK(sitem_integer == sitem1);
    BOOST_CHECK(sitem_integer != sitem_number);
    BOOST_CHECK(sitem_integer != sitem_string);
    BOOST_CHECK(sitem_number != sitem1);
    BOOST_CHECK(sitem_number != sitem_integer);
    BOOST_CHECK(sitem_number != sitem_string);
    BOOST_CHECK(sitem_string != sitem1);
    BOOST_CHECK(sitem_string != sitem_integer);
    BOOST_CHECK(sitem_string != sitem_number);

    sitem1 = sitem_number;
    BOOST_CHECK(sitem1 != sitem_integer);
    BOOST_CHECK(sitem1 == sitem_number);
    BOOST_CHECK(sitem1 != sitem_string);
    BOOST_CHECK(sitem_integer != sitem1);
    BOOST_CHECK(sitem_integer != sitem_number);
    BOOST_CHECK(sitem_integer != sitem_string);
    BOOST_CHECK(sitem_number == sitem1);
    BOOST_CHECK(sitem_number != sitem_integer);
    BOOST_CHECK(sitem_number != sitem_string);
    BOOST_CHECK(sitem_string != sitem1);
    BOOST_CHECK(sitem_string != sitem_integer);
    BOOST_CHECK(sitem_string != sitem_number);

    sitem1 = sitem_string;
    BOOST_CHECK(sitem1 != sitem_integer);
    BOOST_CHECK(sitem1 != sitem_number);
    BOOST_CHECK(sitem1 == sitem_string);
    BOOST_CHECK(sitem_string == sitem1);
    BOOST_CHECK(sitem_string != sitem_integer);
    BOOST_CHECK(sitem_string != sitem_number);
    BOOST_CHECK(sitem_integer != sitem1);
    BOOST_CHECK(sitem_integer != sitem_number);
    BOOST_CHECK(sitem_integer != sitem_string);
    BOOST_CHECK(sitem_number != sitem1);
    BOOST_CHECK(sitem_number != sitem_integer);
    BOOST_CHECK(sitem_number != sitem_string);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc


text:
// ----------------------------------------------------------------------------
// Copyright (C) 2002-2006 Marcin Kalicinski
//
// 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)
//
// For more information, see www.boost.org
// ----------------------------------------------------------------------------
#ifndef BOOST_PROPERTY_TREE_DETAIL_XML_PARSER_READ_PUGXML_HPP_INCLUDED
#define BOOST_PROPERTY_TREE_DETAIL_XML_PARSER_READ_PUGXML_HPP_INCLUDED

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/detail/xml_parser_error.hpp>
#include <boost/property_tree/detail/xml_parser_flags.hpp>
#include <boost/property_tree/detail/xml_parser_utils.hpp>
#include <boost/property_tree/detail/pugxml.hpp>

namespace boost { namespace property_tree { namespace xml_parser
{

    template<class Ptree>
    void read_xml_node(pug::xml_node node, Ptree &pt, int flags)
    {
        typedef typename Ptree::key_type::value_type Ch;
        if (node.type() == pug::node_element ||
            node.type() == pug::node_document)
        {
            Ptree &tmp = pt.push_back(std::make_pair(node.name(), empty_ptree<Ptree>()))->second;
            for (pug::xml_node::attribute_iterator it = node.attributes_begin(); it != node.attributes_end(); ++it)
                tmp.put(xmlattr<Ch>() + Ch('.') + it->name(), it->value());
            for (pug::xml_node::child_iterator it = node.children_begin(); it != node.children_end(); ++it)
                read_xml_node(*it, tmp, flags);
        }
        else if (node.type() == pug::node_pcdata)
        {
            if (flags & no_concat_text)
                pt.push_back(std::make_pair(xmltext<Ch>(), Ptree(node.value())));
            else
                pt.data() += node.value();
        }
        else if (node.type() == pug::node_comment)
        {
            if (!(flags & no_comments))
                pt.push_back(std::make_pair(xmlcomment<Ch>(), Ptree(node.value())));
        }
    }

    template<class Ptree>
    void read_xml_internal(std::basic_istream<typename Ptree::key_type::value_type> &stream,
                           Ptree &pt,
                           int flags,
                           const std::string &filename)
    {

        typedef typename Ptree::key_type::value_type Ch;

        // Load data into vector
        std::vector<Ch> data(std::istreambuf_iterator<Ch>(stream.rdbuf()),
                             std::istreambuf_iterator<Ch>());
        if (!stream.good())
            BOOST_PROPERTY_TREE_THROW(xml_parser_error("read error", filename, 0));
        data.push_back(Ch('\0'));

        // Parse
        pug::xml_parser parser;
        if (parser.parse(&data.front()))
        {
            Ptree local;
            pug::xml_node doc = parser.document();
            for (pug::xml_node::child_iterator it = doc.children_begin(); it != doc.children_end(); ++it)
                read_xml_node(*it, local, flags);
            local.swap(pt);
        }
        else
            BOOST_PROPERTY_TREE_THROW(xml_parser_error("parse error", filename, 0));

    }

} } }

#endif

max_stars_repo_name: gbucknell/fsc-sdk

max_issues_repo_name: gbucknell/fsc-sdk

max_forks_repo_name: gbucknell/fsc-sdk


text:
#ifndef __wrapper_MSSMNoFV_onshell_physical_decl_gm2calc_1_3_0_hpp__
#define __wrapper_MSSMNoFV_onshell_physical_decl_gm2calc_1_3_0_hpp__

#include <cstddef>
#include <ostream>
#include <Eigen/Core>
#include "forward_decls_wrapper_classes.hpp"
#include "gambit/Backends/wrapperbase.hpp"
#include "abstract_MSSMNoFV_onshell_physical.hpp"

#include "identification.hpp"

namespace CAT_3(BACKENDNAME,_,SAFE_VERSION)
{

   namespace gm2calc
   {

      class MSSMNoFV_onshell_physical : public WrapperBase
      {
            // Member variables:
         public:
            // -- Static factory pointers:
            static Abstract_MSSMNoFV_onshell_physical* (*__factory0)();

            // -- Other member variables:
         public:
            double& MVG;
            double& MGlu;
            double& MVP;
            double& MVZ;
            double& MFd;
            double& MFs;
            double& MFb;
            double& MFu;
            double& MFc;
            double& MFt;
            double& MFve;
            double& MFvm;
            double& MFvt;
            double& MFe;
            double& MFm;
            double& MFtau;
            double& MSveL;
            double& MSvmL;
            double& MSvtL;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSd;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSu;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSe;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSm;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MStau;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSs;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSc;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSb;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MSt;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& Mhh;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MAh;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MHpm;
            ::Eigen::Array<double, 4, 1, 0, 4, 1>& MChi;
            ::Eigen::Array<double, 2, 1, 0, 2, 1>& MCha;
            double& MVWm;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZD;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZU;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZE;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZM;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZTau;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZS;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZC;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZB;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZT;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZH;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZA;
            ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& ZP;
            ::Eigen::Matrix<std::complex<double>, 4, 4, 0, 4, 4>& ZN;
            ::Eigen::Matrix<std::complex<double>, 2, 2, 0, 2, 2>& UM;
            ::Eigen::Matrix<std::complex<double>, 2, 2, 0, 2, 2>& UP;

            // Member functions:
         public:
            void clear();

            void convert_to_hk();

            void convert_to_slha();

            void print(::std::basic_ostream<char, std::char_traits<char> >& arg_1) const;

            // Wrappers for original constructors:
         public:
            MSSMNoFV_onshell_physical();

            // Special pointer-based constructor:
            MSSMNoFV_onshell_physical(Abstract_MSSMNoFV_onshell_physical* in);

            // Copy constructor:
            MSSMNoFV_onshell_physical(const MSSMNoFV_onshell_physical& in);

            // Assignment operator:
            MSSMNoFV_onshell_physical& operator=(const MSSMNoFV_onshell_physical& in);

            // Destructor:
            ~MSSMNoFV_onshell_physical();

            // Returns correctly casted pointer to Abstract class:
            Abstract_MSSMNoFV_onshell_physical* get_BEptr() const;

      };
   }

}

#include "gambit/Backends/backend_undefs.hpp"

#endif /* __wrapper_MSSMNoFV_onshell_physical_decl_gm2calc_1_3_0_hpp__ */


text:
//  Copyright (c) 2005 Carl Barron. 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 ACTIONS_H
#define ACTIONS_H
#include <boost/spirit/include/phoenix1.hpp>
#include <boost/variant.hpp>
#include "tag.hpp"

struct push_child_impl
{
    template <class T,class A>
    struct result {typedef void type;};

    template <class T,class A>
    void operator () (T &list, const A &value) const
    {
        typename tag::variant_type p(value);
        list.push_back(p);
    }
};

struct store_in_map_impl
{
    template <class T,class A>
    struct result{typedef void type;};

    template <class T,class A>
    void operator () (T &map,const A &value)const
    {
        typedef typename T::value_type value_type;
        map.insert(value_type(value));
    }
};

struct push_back_impl
{
    template <class T,class A>
    struct result {typedef void type;};

    template <class T,class A>
    void operator () (T &list,const A &value)const
    {
        list.push_back(value);
    }
};

struct store_tag_impl
{
    template <class T,class A,class B,class C>
    struct result {typedef void type;};

    template <class T,class A,class B,class C>
    void operator ()(T &t,const A &a,const B &b,const C &c)const
    {
        t.id = a;
        t.attributes = b;
        t.children = c;
    }
};

typedef phoenix::function<push_back_impl>   push_back_f;
typedef phoenix::function<store_in_map_impl>store_in_map_f;
typedef phoenix::function<push_child_impl>  push_child_f;
typedef phoenix::function<store_tag_impl>   store_tag_f;
#endif

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
 All rights reserved.

 This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
 under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
 MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/

#include "sensors/sensor_log.h"
#include <boost/range/iterator_range.hpp>
#include <fstream>
#include <iostream>
#include <string>

using namespace vulcan;

void save_encoders(const sensors::SensorLog& log, const std::string& filename);
void save_odometry(const sensors::SensorLog& log, const std::string& filename);
void save_imu(const sensors::SensorLog& log, const std::string& filename);
void save_joystick(const sensors::SensorLog& log, const std::string& filename);

int main(int argc, char** argv)
{
    const std::string kEncoderName("encoders_");
    const std::string kOdometryName("odometry_");
    const std::string kIMUName("imu_");
    const std::string kJoystickName("joystick_");

    if (argc < 2) {
        std::cout << "Expected input: motion_sensor_to_text 'log_filename'\n";
        return -1;
    }

    std::string logFilename(argv[1]);

    sensors::SensorLog log(logFilename);

    save_encoders(log, kEncoderName + logFilename);
    save_odometry(log, kOdometryName + logFilename);
    save_imu(log, kIMUName + logFilename);
    save_joystick(log, kJoystickName + logFilename);

    return 0;
}

void save_encoders(const sensors::SensorLog& log, const std::string& filename)
{
    std::ofstream out(filename);

    for (auto& encoders : boost::make_iterator_range(log.beginEncoders(), log.endEncoders())) {
        out << encoders.timestamp << ' ' << encoders.deltaLeftWheel << ' ' << encoders.deltaRightWheel << '\n';
    }
}

void save_odometry(const sensors::SensorLog& log, const std::string& filename)
{
    std::ofstream out(filename);

    for (auto& odom : boost::make_iterator_range(log.beginOdometry(), log.endOdometry())) {
        out << odom.timestamp << ' ' << odom.x << ' ' << odom.y << ' ' << odom.theta << ' ' << odom.translation << ' '
            << odom.rotation << '\n';
    }
}

void save_imu(const sensors::SensorLog& log, const std::string& filename)
{
    std::ofstream out(filename);

    for (auto& imu : boost::make_iterator_range(log.beginImu(), log.endImu())) {
        out << imu.timestamp << ' ' << imu.rotationalVelocity[IMU_YAW_INDEX] << '\n';
    }
}

void save_joystick(const sensors::SensorLog& log, const std::string& filename)
{
    std::ofstream out(filename);

    for (auto& joystick : boost::make_iterator_range(log.beginCommandedJoystick(), log.endCommandedJoystick())) {
        out << joystick.timestamp << ' ' << joystick.forward << ' ' << joystick.left << '\n';
    }
}

max_stars_repo_name: anuranbaka/Vulcan

max_issues_repo_name: anuranbaka/Vulcan

max_forks_repo_name: anuranbaka/Vulcan


text:
#include <boost/log/common.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/channel_logger.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/utility/string_literal.hpp>
#include <boost/utility/empty_deleter.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <string>

using namespace boost::log;

BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", int)
BOOST_LOG_ATTRIBUTE_KEYWORD(channel, "Channel", std::string)

int main()
{
  typedef sinks::asynchronous_sink<sinks::text_ostream_backend>
    ostream_sink;
  boost::shared_ptr<ostream_sink> ostream =
    boost::make_shared<ostream_sink>();
  boost::shared_ptr<std::ostream> clog{&std::clog,
    boost::empty_deleter{}};
  ostream->locked_backend()->add_stream(clog);
  core::get()->add_sink(ostream);

  typedef sinks::synchronous_sink<sinks::text_multifile_backend>
    multifile_sink;
  boost::shared_ptr<multifile_sink> multifile =
    boost::make_shared<multifile_sink>();
  multifile->locked_backend()->set_file_name_composer(
    sinks::file::as_file_name_composer(expressions::stream <<
    channel.or_default<std::string>("None") << "-" <<
    severity.or_default(0) << ".log"));
  core::get()->add_sink(multifile);

  sources::severity_logger<int> severity_lg;
  sources::channel_logger<> channel_lg{keywords::channel = "Main"};

  BOOST_LOG_SEV(severity_lg, 1) << "severity message";
  BOOST_LOG(channel_lg) << "channel message";
  ostream->flush();
}

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text:
#ifndef CLIENT_HTTPS_HPP
#define	CLIENT_HTTPS_HPP

#include "client_http.hpp"
#include <boost/asio/ssl.hpp>

namespace SimpleWeb {
    typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> HTTPS;

    template<>
    class Client<HTTPS> : public ClientBase<HTTPS> {
    public:
        Client(const std::string& server_port_path, bool verify_certificate=true,
                const std::string& cert_file=std::string(), const std::string& private_key_file=std::string(),
                const std::string& verify_file=std::string()) :
                ClientBase<HTTPS>::ClientBase(server_port_path, 443), asio_context(boost::asio::ssl::context::sslv23) {
            if(verify_certificate)
                asio_context.set_verify_mode(boost::asio::ssl::verify_peer);
            else
                asio_context.set_verify_mode(boost::asio::ssl::verify_none);

            if(cert_file.size()>0 && private_key_file.size()>0) {
                asio_context.use_certificate_chain_file(cert_file);
                asio_context.use_private_key_file(private_key_file, boost::asio::ssl::context::pem);
            }

            if(verify_file.size()>0)
                asio_context.load_verify_file(verify_file);

            socket=std::make_shared<HTTPS>(asio_io_service, asio_context);
        };

    private:
        boost::asio::ssl::context asio_context;

        void connect() {
            if(socket_error || !socket->lowest_layer().is_open()) {
                boost::asio::ip::tcp::resolver::query query(host, std::to_string(port));
                boost::asio::connect(socket->lowest_layer(), asio_resolver.resolve(query));

                boost::asio::ip::tcp::no_delay option(true);
                socket->lowest_layer().set_option(option);

                socket->handshake(boost::asio::ssl::stream_base::client);

                socket_error=false;
            }
        }
    };
}

#endif	/* CLIENT_HTTPS_HPP */


text:
/* Copyright (C) 2016-2019 INRA
 *
 * 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 "problem.hpp"
#include "utils.hpp"

#include <sstream>

#include <boost/ut.hpp>

#include <baryonyx/core>

static int
get_variable(const std::vector<std::string_view>& variable_names,
             std::string_view name)
{
    for (int i = 0, e = baryonyx::length(variable_names); i != e; ++i)
        if (variable_names[i] == name)
            return i;

    return -1;
}

int
main()
{
    using namespace boost::ut;

    "test_bqp_clean"_test = [] {
        auto ctx = baryonyx::make_context(4);

        {
            const char* str_pb = "minimize\n"
                                 "-5a + [ 2a * b + 6c * d ] /2 + 10b\n"
                                 "Subject to:\n"
                                 "- a + b >= 0\n"
                                 "b + c - d >= 0\n"
                                 "Binaries\n"
                                 "a b c d\n"
                                 "End\n";

            std::istringstream iss(str_pb);
            auto pb = baryonyx::make_problem(*ctx, iss);
            expect(pb);

            auto pb_pp = baryonyx::preprocess(*ctx, pb);

            expect(pb_pp.vars.names.size() == 4u);
            expect(pb_pp.affected_vars.names.size() == 0u);
            expect(pb_pp.equal_constraints.size() == 0u);
            expect(pb_pp.less_constraints.size() == 0u);
            expect(pb_pp.greater_constraints.size() == 2u);

            auto ida = get_variable(pb.vars.names, "a");
            auto idb = get_variable(pb.vars.names, "b");
            auto idc = get_variable(pb.vars.names, "c");
            auto idd = get_variable(pb.vars.names, "d");

            expect(ida >= 0 && ida < baryonyx::length(pb.vars.names));
            expect(idb >= 0 && idb < baryonyx::length(pb.vars.names));
            expect(idc >= 0 && idc < baryonyx::length(pb.vars.names));
            expect(idd >= 0 && idd < baryonyx::length(pb.vars.names));

            expect(pb_pp.objective.elements.size() == 2u);
            expect(pb_pp.objective.elements[0].variable_index == ida);
            expect(pb_pp.objective.elements[0].factor == -5);
            expect(pb_pp.objective.elements[1].variable_index == idb);
            expect(pb_pp.objective.elements[1].factor == 10);

            expect(pb_pp.objective.qelements.size() == 2u);
            expect(pb_pp.objective.qelements[0].variable_index_a == ida);
            expect(pb_pp.objective.qelements[0].variable_index_b == idb);
            expect(pb_pp.objective.qelements[0].factor == 1);
            expect(pb_pp.objective.qelements[1].variable_index_a == idc);
            expect(pb_pp.objective.qelements[1].variable_index_b == idd);
            expect(pb_pp.objective.qelements[1].factor == 3);
        }

        {
            const char* str_pb = "minimize\n"
                                 "-5a + [ 2a * b + 6c * d ] /2 + 10b\n"
                                 "Subject to:\n"
                                 "- a + b >= 0\n"
                                 "b + c - d >= 0\n"
                                 "Binaries\n"
                                 "a b c d\n"
                                 "End\n";

            std::istringstream iss(str_pb);
            auto pb = baryonyx::make_problem(*ctx, iss);
            expect(pb);

            auto pb_pp = baryonyx::preprocess(*ctx, pb);

            expect(pb_pp.vars.names.size() == 4u);
            expect(pb_pp.affected_vars.names.size() == 0u);
            expect(pb_pp.equal_constraints.size() == 0u);
            expect(pb_pp.less_constraints.size() == 0u);
            expect(pb_pp.greater_constraints.size() == 2u);

            auto ida = get_variable(pb.vars.names, "a");
            auto idb = get_variable(pb.vars.names, "b");
            auto idc = get_variable(pb.vars.names, "c");
            auto idd = get_variable(pb.vars.names, "d");

            expect(ida >= 0 && ida < baryonyx::length(pb.vars.names));
            expect(idb >= 0 && idb < baryonyx::length(pb.vars.names));
            expect(idc >= 0 && idc < baryonyx::length(pb.vars.names));
            expect(idd >= 0 && idd < baryonyx::length(pb.vars.names));

            expect(pb_pp.objective.elements.size() == 2u);
            expect(pb_pp.objective.elements[0].variable_index == ida);
            expect(pb_pp.objective.elements[0].factor == -5);
            expect(pb_pp.objective.elements[1].variable_index == idb);
            expect(pb_pp.objective.elements[1].factor == 10);

            expect(pb_pp.objective.qelements.size() == 2u);
            expect(pb_pp.objective.qelements[0].variable_index_a == ida);
            expect(pb_pp.objective.qelements[0].variable_index_b == idb);
            expect(pb_pp.objective.qelements[0].factor == 1);
            expect(pb_pp.objective.qelements[1].variable_index_a == idc);
            expect(pb_pp.objective.qelements[1].variable_index_b == idd);
            expect(pb_pp.objective.qelements[1].factor == 3);
        }

        {
            const char* str_pb =
              "minimize\n"
              "-5a + 10a + [ 2a * b + 6c * d ] /2 + 10b - b -b "
              "-b + [2 a * b + 6 c * d] / 2\n"
              "Subject to:\n"
              "- a + b >= 0\n"
              "b + c - d >= 0\n"
              "Binaries\n"
              "a b c d\n"
              "End\n";

            std::istringstream iss(str_pb);
            auto pb = baryonyx::make_problem(*ctx, iss);
            expect(pb);

            auto pb_pp = baryonyx::preprocess(*ctx, pb);

            expect(pb_pp.vars.names.size() == 4u);
            expect(pb_pp.affected_vars.names.size() == 0u);
            expect(pb_pp.equal_constraints.size() == 0u);
            expect(pb_pp.less_constraints.size() == 0u);
            expect(pb_pp.greater_constraints.size() == 2u);

            auto ida = get_variable(pb.vars.names, "a");
            auto idb = get_variable(pb.vars.names, "b");
            auto idc = get_variable(pb.vars.names, "c");
            auto idd = get_variable(pb.vars.names, "d");

            expect(ida >= 0 && ida < baryonyx::length(pb.vars.names));
            expect(idb >= 0 && idb < baryonyx::length(pb.vars.names));
            expect(idc >= 0 && idc < baryonyx::length(pb.vars.names));
            expect(idd >= 0 && idd < baryonyx::length(pb.vars.names));

            expect(pb_pp.objective.elements.size() == 2u);
            expect(pb_pp.objective.elements[0].variable_index == ida);
            expect(pb_pp.objective.elements[0].factor == 5);
            expect(pb_pp.objective.elements[1].variable_index == idb);
            expect(pb_pp.objective.elements[1].factor == 7);

            expect(pb_pp.objective.qelements.size() == 2u);
            expect(pb_pp.objective.qelements[0].variable_index_a == ida);
            expect(pb_pp.objective.qelements[0].variable_index_b == idb);
            expect(pb_pp.objective.qelements[0].factor == 2);
            expect(pb_pp.objective.qelements[1].variable_index_a == idc);
            expect(pb_pp.objective.qelements[1].variable_index_b == idd);
            expect(pb_pp.objective.qelements[1].factor == 6);
        }
    };

    "test_bound_affectation"_test = [] {
        auto ctx = baryonyx::make_context(4);

        auto pb = baryonyx::make_problem(ctx, EXAMPLES_DIR "/bound.lp");

        expect(pb);
        expect(pb.vars.names.size() == static_cast<size_t>(6));

        // The preprocessing can not remove any constraint or variable from the
        // raw_problem.

        auto pb_pp = baryonyx::preprocess(*ctx, pb);
        expect(pb_pp.vars.names.size() == static_cast<size_t>(6));
        expect(pb_pp.affected_vars.names.size() == static_cast<size_t>(0));
        expect(pb_pp.equal_constraints.size() == static_cast<size_t>(0));
        expect(pb_pp.less_constraints.size() == static_cast<size_t>(2));
        expect(pb_pp.greater_constraints.size() == static_cast<size_t>(0));

        // We add an "affectation bound" for the variable 'f' i.e. in bound
        // section of the lp file format:
        //
        // bounds:
        // f = 0

        auto id = get_variable(pb.vars.names, "f");
        expect(id >= 0);
        expect(id < baryonyx::length(pb.vars.names));

        expect(pb.vars.names.size() == pb.vars.values.size());

        pb.vars.values[id].min = 0;
        pb.vars.values[id].max = 0;

        auto pb_pp2 = baryonyx::preprocess(*ctx, pb);
        expect(pb_pp2.vars.names.size() == static_cast<size_t>(5));
        expect(pb_pp2.affected_vars.names.size() == static_cast<size_t>(1));
        expect(pb_pp2.equal_constraints.size() == static_cast<size_t>(0));
        expect(pb_pp2.less_constraints.size() == static_cast<size_t>(2));
        expect(pb_pp2.greater_constraints.size() == static_cast<size_t>(0));
    };

    "test_cleaning_affected_variables"_test = [] {
        auto ctx = baryonyx::make_context(4);
        auto pb = baryonyx::make_problem(ctx, EXAMPLES_DIR "/prepro.lp");

        expect(pb);
        expect(pb.vars.names.size() == static_cast<size_t>(23));

        auto pb_pp = baryonyx::preprocess(*ctx, pb);

        expect(pb_pp.vars.names.size() == static_cast<size_t>(2));
        expect(pb_pp.affected_vars.names.size() == static_cast<size_t>(21));
    };

    "test_affect_variable"_test = [] {
        auto ctx = baryonyx::make_context(4);
        auto pb = baryonyx::make_problem(ctx, EXAMPLES_DIR "/prepro.lp");

        expect(pb);
        auto pb_pp = baryonyx::preprocess(*ctx, pb);

        expect(pb_pp.vars.names.size() == static_cast<size_t>(2));
        expect(pb_pp.affected_vars.names.size() == static_cast<size_t>(21));

        {
            // + d + e <= 1
            // d = 1 implies e = 0

            auto pb_af = baryonyx::affect(*ctx, pb_pp, 0, true);
            expect(pb_af.vars.names.size() == static_cast<size_t>(0));
            expect(pb_af.affected_vars.names.size() ==
                   static_cast<size_t>(23));
        }

        {
            // + d + e <= 1
            // d = 0 implies e = {0, 1} but minimize so => 0.

            auto pb_af = baryonyx::affect(*ctx, pb_pp, 0, false);
            expect(pb_af.vars.names.size() == static_cast<size_t>(0));
            expect(pb_af.affected_vars.names.size() ==
                   static_cast<size_t>(23));
        }

        {
            // + d + e <= 1
            // e = 1 implies d = 0

            auto pb_af = baryonyx::affect(*ctx, pb_pp, 1, true);
            expect(pb_af.vars.names.size() == static_cast<size_t>(0));
            expect(pb_af.affected_vars.names.size() ==
                   static_cast<size_t>(23));
        }

        {
            // + d + e <= 1
            // e = 0 implies d = {0, 1} but minimize so => 0.

            auto pb_af = baryonyx::affect(*ctx, pb_pp, 1, false);
            expect(pb_af.vars.names.size() == static_cast<size_t>(0));
            expect(pb_af.affected_vars.names.size() ==
                   static_cast<size_t>(23));
        }
    };

    "test_split"_test = [] {
        auto ctx = baryonyx::make_context(4);
        auto pb = baryonyx::make_problem(ctx, EXAMPLES_DIR "/prepro.lp");
        expect(pb);
        auto pb_pp = baryonyx::preprocess(*ctx, pb);

        expect(pb_pp.vars.names.size() == static_cast<size_t>(2));
        expect(pb_pp.affected_vars.names.size() == static_cast<size_t>(21));

        baryonyx::problem p0, p1;
        std::tie(p0, p1) = baryonyx::split(*ctx, pb_pp, 0);

        {
            // + d + e <= 1
            // d = 1 implies e = 0

            expect(p0.vars.names.size() == static_cast<size_t>(0));
            expect(p0.affected_vars.names.size() == static_cast<size_t>(23));
        }

        {
            // + d + e <= 1
            // d = 0 implies e = {0, 1}

            expect(p1.vars.names.size() == static_cast<size_t>(0));
            expect(p1.affected_vars.names.size() == static_cast<size_t>(23));
        }
    };
}

max_stars_repo_name: quesnel/baryonyx

max_issues_repo_name: quesnel/baryonyx

max_forks_repo_name: quesnel/baryonyx


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef IROHA_MUTABLE_FACTORY_HPP
#define IROHA_MUTABLE_FACTORY_HPP

#include <memory>

#include <boost/optional.hpp>
#include "ametsuchi/command_executor.hpp"
#include "ametsuchi/commit_result.hpp"
#include "common/result.hpp"

namespace shared_model {
  namespace interface {
    class Block;
  }
}  // namespace shared_model

namespace iroha {
  namespace ametsuchi {

    class MutableStorage;

    class MutableFactory {
     public:
      /**
       * Creates a mutable storage from the current state.
       * Mutable storage is the only way to commit the block to the ledger.
       * @return Created mutable storage
       */
      virtual std::unique_ptr<MutableStorage> createMutableStorage(
          std::shared_ptr<CommandExecutor> command_executor) = 0;

      /**
       * Commit mutable storage to Ametsuchi.
       * This transforms Ametsuchi to the new state consistent with
       * MutableStorage.
       * @param mutableStorage
       * @return the status of commit
       */
      virtual CommitResult commit(
          std::unique_ptr<MutableStorage> mutableStorage) = 0;

      /// Check if prepared commits are enabled.
      virtual bool preparedCommitEnabled() const = 0;

      /**
       * Try to apply prepared block to Ametsuchi.
       * @param block The previously prepared block that will be committed now.
       * @return Result of committing the prepared block.
       */
      virtual CommitResult commitPrepared(
          std::shared_ptr<const shared_model::interface::Block> block) = 0;

      virtual ~MutableFactory() = default;
    };

  }  // namespace ametsuchi
}  // namespace iroha
#endif  // IROHA_MUTABLE_FACTORY_HPP

max_stars_repo_name: akshatkarani/iroha

max_issues_repo_name: akshatkarani/iroha

max_forks_repo_name: akshatkarani/iroha


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

#ifndef FILESYSTEM_UTILITIES_HPP
#define FILESYSTEM_UTILITIES_HPP

// STD includes
#include <iostream>

// BOOST
#include <boost/filesystem.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/regex.hpp>

// Other
 #include <filesystem/alphanum.hpp>

namespace utl
{
  /** \brief Replace all occurences of a substring with a new substring
    *  \param[in,out] string_in string which is modified
    *  \param[in] substring_orig substring that needs to be replaced
    *  \param[in] substring_new new substring
    */
  inline
  void replaceSubstring(std::string &string_in, const std::string &substring_orig, const std::string &substring_new)
  {
    std::string::size_type n = 0;
    while ( ( n = string_in.find( substring_orig, n ) ) != std::string::npos )
    {
        string_in.replace( n, substring_orig.size(), substring_new );
        n += substring_new.size();
    }
  }

  /** \brief An analogue of the MATLAB dir function
    * \param[in] dir_path input directory
    * \param[out] content_list a vector of strings representing names of files/folders in the directory
    */
  inline
  void dir(const std::string &dir_path, std::vector<std::string> &content_list)
  {
    std::string dirPath (dir_path);

    // First normalize the beginning of the path
    // If directory path does not start with '/', './' or '../' append './'
    if  (!(((dirPath.length() >= 1) && (dirPath.substr(0,1) == "/")) ||
        ((dirPath.length() >= 2) && (dirPath.substr(0,2) == "./")) ||
        ((dirPath.length() >= 3) && (dirPath.substr(0,3) == "../"))))
    {
      dirPath.insert(0, "./");
    }

    // Find the rightmost '/' delimeter and split along it
    std::string left, right;
    size_t found = dirPath.find_last_of("/");
    if (found == std::string::npos)
    {
      std::cout << "[dir] something wrong\n";
      exit(EXIT_FAILURE);
    }
    else
    {
      left = dirPath.substr(0, found+1);
      right = dirPath.substr(found+1);
    }

    // Now analyze the right part
    std::string fileFormatStr;

    // If right part is empty list everything in left
    if (right.empty())
    {
      fileFormatStr = "*";
      dirPath = left;
    }

    // If right side containts a wildcard or an extension list everything in left that matches
    else if ((right.find("*") != std::string::npos) || (boost::filesystem::path(right).has_extension()))
    {
      fileFormatStr = right;
      dirPath = left;
    }

    // If right is a directory append it to left and list everything
    else if (!boost::filesystem::path(right).has_extension())
    {
      fileFormatStr = "*";
      dirPath = left + right;
    }

    // Generate regex expression
    std::string regexExpression (fileFormatStr);
    utl::replaceSubstring(regexExpression, ".", "[.]");      // Replace all occurences of '.' with '[.]'
    utl::replaceSubstring(regexExpression, "*", ".*");       // Replace all occurences of '*' with '.*'
    boost::regex filenameFormatRgx(regexExpression);

    // List
    content_list.resize(0);
    for (boost::filesystem::directory_iterator file_it(dirPath), end; file_it != end; ++file_it)
    {
      std::string curFileName = file_it->path().leaf().string();                          // Get current file name

      if (boost::regex_match(curFileName, filenameFormatRgx))                               // Check if it matches the filename format
        content_list.push_back(curFileName);
    }

    // Sort the list
    std::sort(content_list.begin(), content_list.end(), doj::alphanum_less<std::string>());
  }

  /** \brief Add trailing slash to pathname if it is missing
    * \param[in] pathname file path
    * \return path with trailing slash
    */
  inline
  std::string addTrailingSlash (const std::string &pathname)
  {
    if (boost::filesystem::path(pathname).has_extension())
      return pathname;
    if (!pathname.empty() && pathname.back() != '/')
      return pathname + '/';
    else
      return pathname;
  }

  /** \brief Add trailing slash to pathname if it is missing
    * \param[in] pathname file path
    * \return path with trailing slash
    */
  inline
  std::string removeTrailingSlash (const std::string &pathname)
  {
    if (!pathname.empty() && pathname.back() == '/')
      return pathname.substr(0, pathname.size()-1);
    else
      return pathname;
  }

  /** \brief Find filename extension of a path
    * \param[in] path path
    * \return extension
    */
  inline
  std::string getExtension (const std::string &pathname)
  {
    return boost::filesystem::extension(boost::filesystem::path(pathname));
  }

  /** \brief Find the parent directory of a path
    * \param[in] path path
    * \return parent directory
    */
  inline
  std::string getParentDir (const std::string &path)
  {
    std::string parentDir = boost::filesystem::path(removeTrailingSlash(path)).parent_path().string();
    if (parentDir == "")
      parentDir = "./";

    return parentDir;
  }

  /** \brief If input is a filename - return filename without preceeding path.
    *  If input is path - return last directory in the path
    * \param[in] path path
    * \return filename
    */
  inline
  std::string getBasename (const std::string &path)
  {
    if (boost::filesystem::path(path).has_extension())
      return boost::filesystem::path(path).filename().string();
    else if (!path.empty() && path.back() != '/')
      return boost::filesystem::path(path).stem().string();
    else
      return boost::filesystem::path(path.substr(0, path.length()-1)).stem().string();
  }

  /** \brief Get filename without extension from the path
    * \param[in] path path
    * \return filename without extension
    */
  inline
  std::string getBasenameNoExtension (const std::string &path)
  {
    return boost::filesystem::path(path).stem().string();
  }

  /** \brief Check if a path exists or not
    * \return true if path exists
    */
  inline
  bool exists (const std::string &path)
  {
    return boost::filesystem::exists(path);
  }

  /** \brief Check if a path is an existing file
    * \return true if path is a filename
    */
  inline
  bool isFile (const std::string &path)
  {
    return (boost::filesystem::is_regular_file(boost::filesystem::path(path)));
  }

  /** \brief Check if a path is a directory that exists
    * \return true if path is a directory
    */
  inline
  bool isDirectory (const std::string &path)
  {
    return (boost::filesystem::is_directory(boost::filesystem::path(path)));
  }

  /** \brief Delete a directory and all of its contents
    * \param[in] path path
    * \return false if directory does not exist or could not delete directory
    */
  inline
  bool deleteDir (const std::string &path)
  {
    if (!boost::filesystem::remove_all(path))
    {
      std::cout << "[utl::deleteDir] could not delete directory '" << path << "'\n";
      return false;
    }

    return true;
  }

  /** \brief Create a directory and all of its contents
    * \param[in] path path
    * \return false if directory already exists or could not create directory
    */
  inline
  bool createDir (const std::string &path)
  {
    if (!boost::filesystem::create_directory(boost::filesystem::path(path)))
    {
      std::cout << "[utl::createDir] Could not create directory '" << path << "'\n";
      return false;
    }

    return true;
  }

  /** \brief Join to paths to generate new path. Inspired by MATLAB's fullfile
    * \param[in] path1 first path
    * \param[in] path2 second path
    * \return joined path
    */
  inline
  std::string fullfile (const std::string &path1, const std::string &path2)
  {
    boost::filesystem::path joinedPath = boost::filesystem::path(path1) / boost::filesystem::path(path2);
    return joinedPath.string();
  }
}

#endif    // FILESYSTEM_UTILITIES_HPP

max_stars_repo_name: Cznielsen/symseg

max_issues_repo_name: Cznielsen/symseg

max_forks_repo_name: Cznielsen/symseg


text:
#ifndef EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_CHAIN_HPP
#define EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_CHAIN_HPP

#include <cmath>
#include <string>
#include <boost/math/special_functions/bessel.hpp>
#include <functional>

namespace exactsolution{

class PartitionFunctionClassicalXYChain{
public :
  static std::string name() { return "Exact partition function , classical XY, open boundary"; }
  PartitionFunctionClassicalXYChain(double J,unsigned int num) : J_(J), num_(num) {}

  double operator()(double T) const {
    double value = 0.0;
    value = 2.0 * M_PI * boost::math::cyl_bessel_i(0,J_/T);
    value = 2.0 * M_PI * std::pow(value , num_-1);
    value += std::pow( std::sqrt(2.0 * M_PI * T), num_);
    return value;
  }

  double logZ(double T) const {
    double value = std::log(2.0 * M_PI);
    value += (double)(num_ - 1) * std::log(2.0 * M_PI * boost::math::cyl_bessel_i(0,J_/T));
    value += (double)(num_) * 0.5 * std::log(2.0 * M_PI * T );
    return value;
  }

private :
  double J_;
  unsigned int num_;
};

} //end namespce

#endif //EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_CHAIN_HPP

max_stars_repo_name: FIshikawa/ClassicalStatPhys

max_issues_repo_name: FIshikawa/ClassicalStatPhys

max_forks_repo_name: FIshikawa/ClassicalStatPhys


text:
#include "../src/InclusionNotesPredicate.hpp"
#include "../src/StreamFilter.hpp"

#include <boost/test/unit_test.hpp>

#include <deque>
#include <functional>

BOOST_AUTO_TEST_SUITE(InclusionNotesPredicate);

namespace
{

class MockStream : public charge::ReadableStream
{
public:
    explicit MockStream(std::deque<std::string> const & sl)
        : input_(sl)
    {}

    virtual std::string read()
    {
        if (input_.empty()) return std::string();

        auto retval = input_.front();
        input_.pop_front();
        return retval;
    }

    std::deque<std::string> input_;

};

}

BOOST_AUTO_TEST_CASE(empty_input)
{
    MockStream mock = MockStream(std::deque<std::string>());

    charge::InclusionNotesPredicate sniffer;

    auto filter = charge::make_stream_filter(mock, std::ref(sniffer));

    BOOST_CHECK(filter.read().empty());

    BOOST_CHECK_EQUAL(sniffer.inclusions_.size(), 0);
}

BOOST_AUTO_TEST_CASE(just_warnings)
{
    MockStream mock = MockStream(
        {
            "warning: ",
            "such and such\n",
        }
    );

    charge::InclusionNotesPredicate sniffer;

    auto filter = charge::make_stream_filter(mock, std::ref(sniffer));

    auto line = filter.read();

    BOOST_CHECK_EQUAL(line, "warning: such and such\n");

    line = filter.read();

    BOOST_CHECK(line.empty());

    BOOST_CHECK_EQUAL(sniffer.inclusions_.size(), 0);
}

BOOST_AUTO_TEST_CASE(one_note)
{
    MockStream mock = MockStream(
        {
            "pgm.cpp\n",
            "Note: including file:   stdcpp/iostream\n",
            "warning: ",
            "such and such\n",
        }
    );

    charge::InclusionNotesPredicate sniffer;

    auto filter = charge::make_stream_filter(mock, std::ref(sniffer));

    auto line = filter.read();

    BOOST_CHECK_EQUAL(line, "pgm.cpp\n");

    line = filter.read();

    BOOST_CHECK_EQUAL(line, "warning: such and such\n");

    line = filter.read();

    BOOST_CHECK(line.empty());

    BOOST_REQUIRE_EQUAL(sniffer.inclusions_.size(), 1);

    BOOST_CHECK_EQUAL(sniffer.inclusions_[0], "stdcpp/iostream");
}

BOOST_AUTO_TEST_CASE(no_final_lf)
{
    MockStream mock = MockStream(
        {
            "warning: ",
            "such and such"
        }
    );

    charge::InclusionNotesPredicate sniffer;

    auto filter = charge::make_stream_filter(mock, std::ref(sniffer));

    auto line = filter.read();

    BOOST_CHECK_EQUAL(line, "warning: such and such");

    line = filter.read();

    BOOST_CHECK(line.empty());

    BOOST_CHECK_EQUAL(sniffer.inclusions_.size(), 0);
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: philtherobot/quickc

max_issues_repo_name: philtherobot/quickc

max_forks_repo_name: philtherobot/quickc


text:
#ifndef VANILLA_INIT_H
#define VANILLA_INIT_H

#include <iostream>
#include <boost/multi_array.hpp>
#include "boost/array.hpp"
#include <boost/next_prior.hpp>
#include "boost/cstdlib.hpp"
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <ctime>

class init
{
public:
    template <typename Array>
    void ones(Array& A)
    {
        const auto n = A.data() + A.num_elements();
        for (auto i = A.data(); i != n; ++i){
            *i = 1.0;
        }
    }

public:
    template <typename Array>
    void normal(Array& A)
    {
        boost::mt19937 gene;
        boost::variate_generator<boost::mt19937, boost::normal_distribution<long double> > gen(gene, boost::normal_distribution<long double>(0.01, 0.02));
        const auto n = A.data() + A.num_elements();
        for (auto i = A.data(); i != n; ++i){
            *i = gen();
        }
    }

public:
    template <typename T>
    void normal(boost::numeric::ublas::matrix<T>& M)
    {
        boost::mt19937 gene;
        boost::variate_generator<boost::mt19937, boost::normal_distribution<long double > > gen(gene, boost::normal_distribution<long double>(0.01, 0.02));
        for (unsigned i = 0; i < M.size1(); ++ i){
            for (unsigned j = 0; j < M.size2(); ++ j){
                M(i, j) = gen();
            }
        }

    }
};
#endif

max_stars_repo_name: pjavia/Vanilla

max_issues_repo_name: pjavia/Vanilla

max_forks_repo_name: pjavia/Vanilla