text:
// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_PROFILE_HPP_
#define RDB_PROTOCOL_PROFILE_HPP_

#include <string>
#include <vector>

#include "errors.hpp"
#include <boost/variant.hpp>

#include "containers/counted.hpp"
#include "containers/scoped.hpp"
#include "rpc/serialize_macros.hpp"
#include "time.hpp"

namespace ql {
class datum_t;
} //namespace ql

// This is a macro so that you can put expensive operations into the `description`
// argument (e.g. an `strprintf`) and it will only be evaluated if profiling is actually
// enabled, rather than when instantiate the macro.
#define PROFILE_STARTER_IF_ENABLED(should_profile, description, trace)              \
    scoped_ptr_t<profile::starter_t> profile_starter;                               \
    if (should_profile) {                                                           \
        profile_starter.init(new profile::starter_t(description, trace));           \
    }

namespace profile {

struct start_t {
    start_t();
    explicit start_t(const std::string &description);
    std::string description_;
    ticks_t when_;
};

RDB_DECLARE_SERIALIZABLE(start_t);

struct split_t {
    split_t();
    explicit split_t(size_t n_parallel_jobs);

    size_t n_parallel_jobs_;
};

RDB_DECLARE_SERIALIZABLE(split_t);

struct sample_t {
    sample_t();
    sample_t(const std::string &description, ticks_t mean_duration, size_t n_samples);

    std::string description_;
    ticks_t mean_duration_;
    size_t n_samples_;
};

RDB_DECLARE_SERIALIZABLE(sample_t);

struct stop_t {
    stop_t();
    ticks_t when_;
};

RDB_DECLARE_SERIALIZABLE(stop_t);

typedef boost::variant<start_t, split_t, sample_t, stop_t> event_t;

typedef std::vector<event_t> event_log_t;

/* A trace_t contains an event_log_t and provides private methods for adding
 * events to it. These methods are leveraged by the instruments. */
class trace_t {
public:
    trace_t();
    ql::datum_t as_datum() const;
    event_log_t extract_event_log() RVALUE_THIS;
private:
    friend class starter_t;
    friend class splitter_t;
    friend class sampler_t;
    friend class disabler_t;
    void start(const std::string &description);
    void stop();
    void start_split();
    void stop_split(size_t n_parallel_jobs_, const event_log_t &event_log);
    void start_sample(event_log_t *sample_event_log);
    void stop_sample(const std::string &description, ticks_t mean_duration,
        size_t n_samples, event_log_t *sample_event_log);
    void stop_sample(event_log_t *sample_event_log);
    void disable();
    void enable();

    /* returns the event_log_t that we should put events in */
    event_log_t *event_log_target();
    event_log_t event_log_;
    /* redirected_event_log_ is used during sampling to send the events to the
     * sampler to be processed. */
    event_log_t *redirected_event_log_;
    size_t disabled_ref_count_;
    bool disabled();

    DISABLE_COPYING(trace_t);
};

/* These are the instruments for adding profiling to code. You construct this
 * objects at various places in your code such that their lifetimes correspond
 * to the period of time during which you are performing an operation. */

/* starter_t is used to record a task. It records events when it is constructed
 * and when it is destroyed. Example:
 *
 *  {
 *      starter_t starter("Performing task foo.", trace);
 *
 *      Perform the task foo in here
 *  }
 */
class starter_t {
public:
    starter_t(const std::string &description, trace_t *parent);
    starter_t(const std::string &description, const scoped_ptr_t<trace_t> &parent);
    ~starter_t();
private:
    void init(const std::string &description, trace_t *parent);
    trace_t *parent_;
};

/* splitter_t is used to record several tasks happening in parallel. For each
 * parallel task you get back you need to get their event logs back,
 * concatenate them and pass them to the give_splits method. Example:
 * {
 *     splitter_t splitter(trace);
 *     event_log_t log1, log2;
 *     coro_t::spawn_*(&perform_task_1, &log1);
 *     coro_t::spawn_*(&perform_task_2, &log2);
 *
 *     wait_for_tasks_to_complete();
 *     log1.insert(log2.begin(), log2.end(), log1.end());
 *     splitter.give_splits(2, log1);
 * }
 *
 * This is used for reads and writes from and to the shards in the query
 * language layer.
 */
class splitter_t {
public:
    explicit splitter_t(trace_t *parent);
    explicit splitter_t(const scoped_ptr_t<trace_t> &parent);
    void give_splits(size_t n_parallel_jobs_, const event_log_t &event_log);
    ~splitter_t();
private:
    void init(trace_t *parent);
    trace_t *parent_;
    size_t n_parallel_jobs_;
    event_log_t event_log_;
};

/* sampler_t is used when you want to record a repeated event that would
 * otherwise swamp the event log. When it is constructed it begins sampling,
 * between samples you should call the new_sample method. Example:
 * {
 *     sampler_t sampler("Reduce elements", trace);
 *     datum_t res = stream.next();
 *     sampler.new_sample();
 *
 *     while (auto v = stream.next()) {
 *         res = reduce(res, v);
 *         sampler.new_sample();
 *     }
 * }
 *
 * This is used for map and reduce type things in the query language.
 *
 * Note: the sampler tries to be a bit flexible with where you put calls to
 * new_sample(). You need to call it between when the things you sample want to
 * happen. Calling it before the first sample and after the last sample is
 * acceptable but optional. */

class sampler_t {
public:
    sampler_t(const std::string &description, trace_t *parent);
    sampler_t(const std::string &description, const scoped_ptr_t<trace_t> &parent);
    void new_sample();
    ~sampler_t();
private:
    void init(const std::string &description, trace_t *parent);
    trace_t *parent_;
    event_log_t event_log_;

    std::string description_;
    ticks_t total_time_;
    size_t n_samples_;
};

/* disabler_t is used when you don't want a section of code to be profiled.
 * Right now this is used for parts of the code that would otherwise use
 * trace_t illegally due to their reentrancy. */
class disabler_t {
public:
    explicit disabler_t(trace_t *parent);
    explicit disabler_t(const scoped_ptr_t<trace_t> &parent);
    ~disabler_t();
private:
    void init(trace_t *parent);
    trace_t *parent_;
};

void print_event_log(const event_log_t &event_log);

}  // namespace profile

#endif  // RDB_PROTOCOL_PROFILE_HPP_

max_stars_repo_name: zadcha/rethinkdb

max_issues_repo_name: RethonkDB/rethonkdb

max_forks_repo_name: RethonkDB/rethonkdb


text:
/**
 * @file LoopClosureParameters.hpp
 * @brief Header file for LoopClosureParameters class which encompasses
 * parameters for loop detection and pose graph optimization.
 */

#ifndef INCLUDE_OKVIS_LOOP_CLOSURE_PARAMETERS_HPP_
#define INCLUDE_OKVIS_LOOP_CLOSURE_PARAMETERS_HPP_

#include <Eigen/Core>
#include <okvis/PipelineParams.h>
#include <okvis/class_macros.hpp>
#include <glog/logging.h>

namespace swift_vio {
class LoopClosureParameters : public PipelineParams {
 public:
  LoopClosureParameters();
  LoopClosureParameters(const std::string name);
  ~LoopClosureParameters();
  bool parseYAML(const std::string& filepath) override;
  void print() const override;
  bool equals(const PipelineParams& obj) const override;
};
}  // namespace swift_vio

#endif  // INCLUDE_OKVIS_LOOP_CLOSURE_PARAMETERS_HPP_

ext: hpp


text:
/**
 * Adobe Experience Manager (AEM) API
 * Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
 *
 * OpenAPI spec version: 3.2.0-pre.0
 * Contact: opensource@shinesolutions.com
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#include "SamlConfigurationInfo.h"

#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;

namespace org {
namespace openapitools {
namespace server {
namespace model {

SamlConfigurationInfo::SamlConfigurationInfo()
{
    m_Pid = "";
    m_Title = "";
    m_Description = "";
    m_Bundle_location = "";
    m_Service_location = "";

}

SamlConfigurationInfo::~SamlConfigurationInfo()
{
}

std::string SamlConfigurationInfo::toJsonString()
{
	std::stringstream ss;
	ptree pt;
	pt.put("Pid", m_Pid);
	pt.put("Title", m_Title);
	pt.put("Description", m_Description);
	pt.put("Bundle_location", m_Bundle_location);
	pt.put("Service_location", m_Service_location);
	write_json(ss, pt, false);
	return ss.str();
}

void SamlConfigurationInfo::fromJsonString(std::string const& jsonString)
{
	std::stringstream ss(jsonString);
	ptree pt;
	read_json(ss,pt);
	m_Pid = pt.get("Pid", "");
	m_Title = pt.get("Title", "");
	m_Description = pt.get("Description", "");
	m_Bundle_location = pt.get("Bundle_location", "");
	m_Service_location = pt.get("Service_location", "");
}

std::string SamlConfigurationInfo::getPid() const
{
    return m_Pid;
}
void SamlConfigurationInfo::setPid(std::string value)
{
    m_Pid = value;
}
std::string SamlConfigurationInfo::getTitle() const
{
    return m_Title;
}
void SamlConfigurationInfo::setTitle(std::string value)
{
    m_Title = value;
}
std::string SamlConfigurationInfo::getDescription() const
{
    return m_Description;
}
void SamlConfigurationInfo::setDescription(std::string value)
{
    m_Description = value;
}
std::string SamlConfigurationInfo::getBundleLocation() const
{
    return m_Bundle_location;
}
void SamlConfigurationInfo::setBundleLocation(std::string value)
{
    m_Bundle_location = value;
}
std::string SamlConfigurationInfo::getServiceLocation() const
{
    return m_Service_location;
}
void SamlConfigurationInfo::setServiceLocation(std::string value)
{
    m_Service_location = value;
}
std::shared_ptr<SamlConfigurationProperties> SamlConfigurationInfo::getProperties() const
{
    return m_Properties;
}
void SamlConfigurationInfo::setProperties(std::shared_ptr<SamlConfigurationProperties> value)
{
    m_Properties = value;
}

}
}
}
}

ext: cpp

max_stars_repo_name: hoomaan-kh/swagger-aem

max_issues_repo_name: hoomaan-kh/swagger-aem

max_forks_repo_name: hoomaan-kh/swagger-aem


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Vicente J. Botet Escriba 2011,2016.
// 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)
//
//////////////////////////////////////////////////////////////////////////////

/*!
 \file
 \brief
 The header \c <experimental/ordinal_range.hpp> defines a class template \c ordinal_range for viewing an ordinal as a range.
 */

#ifndef JASEL_FUNDAMENTAL_V3_ORDINAL_ORDINAL_RANGE_HPP
#define JASEL_FUNDAMENTAL_V3_ORDINAL_ORDINAL_RANGE_HPP

#include <experimental/ordinal.hpp>

#include <boost/iterator/iterator_facade.hpp>
#include <boost/range/iterator_range.hpp>
#include <iosfwd>
#include <iostream>

namespace std
{
namespace experimental
{
inline namespace fundamental_v3
{

    #ifndef JASEL_DOXYGEN_INVOKED
    namespace ordinal_detail {
        // ordinal_iterator is an iterator over an ordinal  that
        // is bounded only by the limits of the ordinal.
        //
        // This is useful for implementing the ordinal_range<E>()
        // function.
        //
        // @par Note:
        // The use of this iterator and ordinal_range<E>() is appreciably less
        // performant than the corresponding hand-written integer
        // loop on many compilers.

        //! ordinal_iterator is a model of RandomAccessIterator
        template<typename T /* , typename Traits=ordinal_range_traits<T> */ >
        class ordinal_iterator
            : public boost::iterator_facade<
                        ordinal_iterator<T>,
                        T,
                        boost::random_access_traversal_tag,
                        T,
                        std::ptrdiff_t
                    >
        {
            typedef boost::iterator_facade<
                        ordinal_iterator<T>,
                        T,
                        boost::random_access_traversal_tag,
                        T,
                        std::ptrdiff_t
                    > base_t;
        public:
            typedef typename base_t::value_type value_type;
            typedef typename base_t::difference_type difference_type;
            typedef typename base_t::reference reference;

            ordinal_iterator() : index_(0u) {}
            explicit ordinal_iterator(ordinal::index_t x) : index_(x) {}

        private:
            void increment()
            {
                ++index_;
            }

            void decrement()
            {
                --index_;
            }

            void advance(difference_type offset)
            {
                index_ += offset;
            }

            difference_type distance_to(const ordinal_iterator& other) const
            {
                return other.index_ - index_;
            }

            bool equal(const ordinal_iterator& other) const
            {
                return index_ == other.index_;
            }

            reference dereference() const
            {
                return ordinal::val<T>(index_);
            }

            friend class ::boost::iterator_core_access;
            ordinal::index_t index_;
        };
    } // namespace ordinal_detail
    #endif

    /**
     @tparam T set's element ordinal type

     @par Requires: @c T must be a model of Ordinal.

     \c ordinal_range is a model of the RandomAccessRange Concept associated to the ordinal \c T.
     */

    template<typename T/* , typename Traits=ordinal_range_traits<T> */ >
    class ordinal_range
        : public boost::iterator_range< ordinal_detail::ordinal_iterator<T/*, Traits*/> >
    {
        typedef ordinal_detail::ordinal_iterator<T/*, Traits*/> iterator_t;
        typedef boost::iterator_range<iterator_t> base_t;
    public:
        //! builds a ordinal range
        ordinal_range()
            : base_t(iterator_t(0), iterator_t(ordinal::meta::size<T>::value))
        {
        }

        //! builds a ordinal sub-range
        ordinal_range(T first, T last)
            : base_t(iterator_t(ordinal::pos(first)),
                     iterator_t(ordinal::pos(last)+1))
        {
        }
    };

    //! function to generate an ordinal range.
    //! \c make_range allows treating ordinals as a model of the \e RandomAccessRange Concept.

    //! @par Requires:
 \c T is a model of the \e Ordinal Concept.
    //! @par Returns: an ordinal range from @c T'first to @c T'last inclusive.
    template<typename T /*, typename Traits*/ >
    ordinal_range<T>
    make_range()
    {
        return ordinal_range<T/*,Traits*/>();
    }

    //! function to generate an ordinal sub-range.
    //! \c make_range allows treating ordinal as a model of the \e RandomAccessRange Concept.
    //! It should be noted that the first and last parameters denoted a closed range.
    //! @par Requires: \c T is a model of the \e Ordinal Concept.
    //! @param first element of the range
    //! @param last element of the range
    //! @par Returns: an ordinal range from @c first to @c last inclusive.

    template<typename T /*, typename Traits */ >
    ordinal_range<T>
    make_range(T first, T last)
    {
        return ordinal_range<T /*,Traits*/ >(first,last);
    }

}} // namespace experimental::fundamental_v3
} // std

#endif // header

max_stars_repo_name: jwakely/std-make

max_issues_repo_name: jwakely/std-make

max_forks_repo_name: jwakely/std-make


text:
/*
 * @file
 * @author University of Warwick
 * @version 1.0
 *
 * @section LICENSE
 *
 * @section DESCRIPTION
 *
 */

#define BOOST_TEST_MODULE UnitTest
#include <boost/test/unit_test.hpp>
#include <boost/test/output_test_stream.hpp>

#include <stdexcept>

using namespace [name];

BOOST_AUTO_TEST_CASE(test)
{
	int dummy = 0;
}

max_stars_repo_name: thorbenlouw/CUP-CFD

max_issues_repo_name: thorbenlouw/CUP-CFD

max_forks_repo_name: thorbenlouw/CUP-CFD


text: #include <boost/spirit/include/classic_typeof.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text: #include <boost/compute/algorithm/max_element.hpp>


text:
/*
 * Copyright (C) 2012 Open Source Robotics Foundation
 *
 * 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.
 *
*/
#ifdef _WIN32
  // Ensure that Winsock2.h is included before Windows.h, which can get
  // pulled in by anybody (e.g., Boost).
  #include <Winsock2.h>
#endif
#include <gazebo/gazebo_config.h>

#ifndef USE_EXTERNAL_TINYXML2
#include <gazebo/tinyxml2.h>
#else
#include <tinyxml2.h>
#endif

#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/remove_whitespace.hpp>
#include <boost/archive/iterators/istream_iterator.hpp>
#include <boost/archive/iterators/transform_width.hpp>

#include <ignition/math/Rand.hh>

#include "gazebo/common/Exception.hh"
#include "gazebo/common/Console.hh"
#include "gazebo/common/Base64.hh"
#include "gazebo/util/LogRecord.hh"

#include "gazebo/util/LogPlayPrivate.hh"
#include "gazebo/util/LogPlay.hh"

using namespace gazebo;
using namespace util;

/////////////////////////////////////////////////
LogPlay::LogPlay()
: dataPtr(new LogPlayPrivate)
{
  this->dataPtr->logStartXml = NULL;
}

/////////////////////////////////////////////////
LogPlay::~LogPlay()
{
}

/////////////////////////////////////////////////
void LogPlay::Open(const std::string &_logFile)
{
  this->dataPtr->currentChunk.clear();

  boost::filesystem::path path(_logFile);
  if (!boost::filesystem::exists(path))
    gzthrow("Invalid logfile [" + _logFile + "]. Does not exist.");

  if (boost::filesystem::is_directory(path))
    gzthrow("Invalid logfile [" + _logFile + "]. This is a directory.");

  // Flag use to indicate if a parser failure has occurred
  bool xmlParserFail = this->dataPtr->xmlDoc.LoadFile(_logFile.c_str()) !=
    tinyxml2::XML_SUCCESS;

  // Parse the log file
  if (xmlParserFail)
  {
    std::string endTag = "</gazebo_log>";
    // Open the log file for reading, we will check if the end of the log
    // file has the correct closing tag: </gazebo_log>.
    std::ifstream inFile(_logFile);
    if (inFile)
    {
      // Move to the end of the file
      int len = -1 - static_cast<int>(endTag.length());
      inFile.seekg(len, std::ios::end);

      // Get the last line
      std::string lastLine;
      std::getline(inFile, lastLine);
      inFile.close();

      // Add missing </gazebo_log> if not present.
      if (lastLine.find(endTag) == std::string::npos)
      {
        // Open the log file for append
        std::ofstream fix(_logFile, std::ios::app);
        if (fix)
        {
          // Add the end tag
          fix << endTag << std::endl;
          fix.close();

          // Retry loading the log file.
          xmlParserFail = this->dataPtr->xmlDoc.LoadFile(_logFile.c_str()) !=
            tinyxml2::XML_SUCCESS;
        }
      }
    }
  }

  // Output error and throw if the log file had a problem.
  // \todo Remove throws in this class. A failure to open a log file is not
  // a critical failure.
  if (xmlParserFail)
  {
    gzerr << "Unable to load file[" << _logFile << "]. "
      << "Check the Gazebo server log file for more information.\n";
#ifdef TINYXML2_MAJOR_VERSION_GE_6
    const char *errorStr1 = this->dataPtr->xmlDoc.ErrorStr();
    const char *errorStr2 = nullptr;
#else
    const char *errorStr1 = this->dataPtr->xmlDoc.GetErrorStr1();
    const char *errorStr2 = this->dataPtr->xmlDoc.GetErrorStr2();
#endif
    if (errorStr1)
      gzlog << "Log Error 1:\n" << errorStr1 << std::endl;
    if (errorStr2)
      gzlog << "Log Error 2:\n" << errorStr2 << std::endl;
    gzthrow("Error parsing log file");
  }

  // Get the gazebo_log element
  this->dataPtr->logStartXml =
    this->dataPtr->xmlDoc.FirstChildElement("gazebo_log");

  if (!this->dataPtr->logStartXml)
    gzthrow("Log file is missing the <gazebo_log> element");

  // Store the filename for future use.
  this->dataPtr->filename = _logFile;

  // Read in the header.
  this->ReadHeader();

  this->dataPtr->logCurrXml = this->dataPtr->logStartXml;
  this->dataPtr->encoding.clear();

  // Extract the start/end log times from the log.
  this->ReadLogTimes();

  // Extract the initial "iterations" value from the log.
  this->dataPtr->iterationsFound = this->ReadIterations();

  this->dataPtr->logCurrXml =
    this->dataPtr->logStartXml->FirstChildElement("chunk");

  if (!this->dataPtr->logCurrXml)
    gzthrow("Unable to find the first chunk");

  if (!this->dataPtr->ChunkData(this->dataPtr->logCurrXml,
                                this->dataPtr->currentChunk))
  {
    gzthrow("Unable to decode log file");
  }

  this->dataPtr->start = 0;
  this->dataPtr->end = -1 * this->dataPtr->kEndFrame.size();
}

/////////////////////////////////////////////////
std::string LogPlay::Header() const
{
  std::ostringstream stream;
  stream << "<?xml version='1.0'?>\n"
         << "<gazebo_log>\n"
         << "<header>\n"
         << "<log_version>" << this->dataPtr->logVersion << "</log_version>\n"
         << "<gazebo_version>" << this->dataPtr->gazeboVersion
         << "</gazebo_version>\n"
         << "<rand_seed>" << this->dataPtr->randSeed << "</rand_seed>\n"
         << "<log_start>" << this->dataPtr->logStartTime << "</log_start>\n"
         << "<log_end>" << this->dataPtr->logEndTime << "</log_end>\n"
         << "</header>\n";

  return stream.str();
}

/////////////////////////////////////////////////
uint64_t LogPlay::InitialIterations() const
{
  return this->dataPtr->initialIterations;
}

/////////////////////////////////////////////////
bool LogPlay::HasIterations() const
{
  return this->dataPtr->iterationsFound;
}

/////////////////////////////////////////////////
void LogPlay::ReadHeader()
{
  this->dataPtr->randSeed = ignition::math::Rand::Seed();

  tinyxml2::XMLElement *headerXml, *childXml;

  this->dataPtr->logVersion.clear();
  this->dataPtr->gazeboVersion.clear();

  // Get the header element
  headerXml = this->dataPtr->logStartXml->FirstChildElement("header");
  if (!headerXml)
    gzthrow("Log file has no header");

  // Get the log format version
  childXml = headerXml->FirstChildElement("log_version");
  if (!childXml)
    gzerr << "Log file header is missing the log version.\n";
  else
    this->dataPtr->logVersion = childXml->GetText();

  if (this->dataPtr->logVersion != GZ_LOG_VERSION)
  {
    gzwarn << "Log version[" << this->dataPtr->logVersion << "] in file["
           << this->dataPtr->filename
           << "] does not match Gazebo's log version["
           << GZ_LOG_VERSION << "]\n";
    return;
  }

  // Get the gazebo version
  childXml = headerXml->FirstChildElement("gazebo_version");
  if (!childXml)
    gzerr << "Log file header is missing the gazebo version.\n";
  else
    this->dataPtr->gazeboVersion = childXml->GetText();

  // Get the random number seed.
  childXml = headerXml->FirstChildElement("rand_seed");
  if (!childXml)
  {
    gzerr << "Log file header is missing the random number seed.\n";
  }
  else
  {
    this->dataPtr->randSeed = std::stoul(childXml->GetText());
  }

  // Set the random number seed for simulation
  ignition::math::Rand::Seed(this->dataPtr->randSeed);
}

/////////////////////////////////////////////////
void LogPlay::ReadLogTimes()
{
  std::string chunk;
  bool found = false;

  auto chunkXml = this->dataPtr->logStartXml->FirstChildElement("chunk");

  // Try to read the start time of the log.
  auto numChunksToTry =
    std::min(this->ChunkCount(), this->dataPtr->kNumChunksToTry);

  for (unsigned int i = 0; i < numChunksToTry; ++i)
  {
    if (!chunkXml)
    {
      gzerr << "Unable to find the first chunk" << std::endl;
      return;
    }

    if (!this->dataPtr->ChunkData(chunkXml, chunk))
      return;

    // Find the first <sim_time> of the log.
    auto from = chunk.find(this->dataPtr->kStartTime);
    auto to = chunk.find(this->dataPtr->kEndTime,
        from + this->dataPtr->kStartTime.size());
    if (from != std::string::npos && to != std::string::npos)
    {
      auto length = to - from - this->dataPtr->kStartTime.size();
      auto startTime = chunk.substr(from + this->dataPtr->kStartTime.size(),
          length);
      std::stringstream ss(startTime);
      ss >> this->dataPtr->logStartTime;
      found = true;
      break;
    }

    chunkXml = chunkXml->NextSiblingElement("chunk");
  }

  if (!found)
    gzwarn << "Unable to find <sim_time> tags in any chunk." << std::endl;

  // Jump to the last chunk for finding the last <sim_time>.
  auto lastChunk = this->dataPtr->logStartXml->LastChildElement("chunk");
  if (!lastChunk)
  {
    gzerr << "Unable to jump to the last chunk of the log file\n";
    return;
  }

  if (!this->dataPtr->ChunkData(lastChunk, chunk))
    return;

  // Update the last <sim_time> of the log.
  auto to = chunk.rfind(this->dataPtr->kEndTime);
  auto from = chunk.rfind(this->dataPtr->kStartTime, to - 1);

  if (from != std::string::npos && to != std::string::npos)
  {
    auto length = to - from - this->dataPtr->kStartTime.size();
    auto endTime = chunk.substr(
        from + this->dataPtr->kStartTime.size(), length);
    std::stringstream ss(endTime);
    ss >> this->dataPtr->logEndTime;
  }
  else
  {
    gzwarn << "Unable to find <sim_time>...</sim_time> tags in the last chunk."
           << std::endl;
    return;
  }
}

/////////////////////////////////////////////////
bool LogPlay::ReadIterations()
{
  const std::string kStartDelim = "<iterations>";
  const std::string kEndDelim = "</iterations>";

  auto chunkXml = this->dataPtr->logStartXml->FirstChildElement("chunk");

  // Read the first "iterations" value of the log from the first chunk.
  auto numChunksToTry =
    std::min(this->ChunkCount(), this->dataPtr->kNumChunksToTry);

  for (unsigned int i = 0; i < numChunksToTry; ++i)
  {
    if (!chunkXml)
    {
      gzerr << "Unable to find the first chunk" << std::endl;
      return false;
    }

    std::string chunk;
    if (!this->dataPtr->ChunkData(chunkXml, chunk))
      return false;

    // Find the first <iterations> of the log.
    auto from = chunk.find(kStartDelim);
    auto to = chunk.find(kEndDelim, from + kStartDelim.size());
    if (from != std::string::npos && to != std::string::npos)
    {
      auto length = to - from - kStartDelim.size();
      auto iterations = chunk.substr(from + kStartDelim.size(), length);
      std::stringstream ss(iterations);
      ss >> this->dataPtr->initialIterations;
      return true;
    }

    chunkXml = chunkXml->NextSiblingElement("chunk");
  }

  gzwarn << "Unable to find <iterations>...</iterations> tags in the first "
         << "chunk. Assuming that the first <iterations> value is 0."
         << std::endl;
  return false;
}

/////////////////////////////////////////////////
bool LogPlay::IsOpen() const
{
  return this->dataPtr->logStartXml != NULL;
}

/////////////////////////////////////////////////
std::string LogPlay::LogVersion() const
{
  return this->dataPtr->logVersion;
}

/////////////////////////////////////////////////
std::string LogPlay::GazeboVersion() const
{
  return this->dataPtr->gazeboVersion;
}

/////////////////////////////////////////////////
uint32_t LogPlay::RandSeed() const
{
  return this->dataPtr->randSeed;
}

/////////////////////////////////////////////////
common::Time LogPlay::LogStartTime() const
{
  return this->dataPtr->logStartTime;
}

/////////////////////////////////////////////////
common::Time LogPlay::LogEndTime() const
{
  return this->dataPtr->logEndTime;
}

/////////////////////////////////////////////////
std::string LogPlay::Filename() const
{
  return boost::filesystem::basename(this->dataPtr->filename) +
    boost::filesystem::extension(this->dataPtr->filename);
}

/////////////////////////////////////////////////
std::string LogPlay::FullPathFilename() const
{
  const boost::filesystem::path logFilename(this->dataPtr->filename);
  return boost::filesystem::canonical(logFilename).string();
}

/////////////////////////////////////////////////
uintmax_t LogPlay::FileSize() const
{
  return boost::filesystem::file_size(this->dataPtr->filename);
}

/////////////////////////////////////////////////
bool LogPlay::Step(std::string &_data)
{
  std::lock_guard<std::mutex> lock(this->dataPtr->mutex);

  auto from = this->dataPtr->currentChunk.find(this->dataPtr->kStartFrame,
      this->dataPtr->end + this->dataPtr->kEndFrame.size());
  auto to = this->dataPtr->currentChunk.find(this->dataPtr->kEndFrame,
      this->dataPtr->end + this->dataPtr->kEndFrame.size());

  if (from == std::string::npos || to == std::string::npos)
  {
    if (!this->NextChunk())
      return false;

    from = this->dataPtr->currentChunk.find(this->dataPtr->kStartFrame);
    to = this->dataPtr->currentChunk.find(this->dataPtr->kEndFrame);
    if (from == std::string::npos || to == std::string::npos)
    {
      gzerr << "Unable to find an <sdf> frame in current chunk\n";
      return false;
    }
  }

  this->dataPtr->start = from;
  this->dataPtr->end = to;

  _data = this->dataPtr->currentChunk.substr(this->dataPtr->start,
      this->dataPtr->end + this->dataPtr->kEndFrame.size() -
      this->dataPtr->start);

  return true;
}

/////////////////////////////////////////////////
bool LogPlay::Step(const int _step, std::string &_data)
{
  bool res = false;
  for (auto i = 0; i < std::abs(_step); ++i)
  {
    if (_step >= 0)
    {
      if (!this->Step(_data))
        return res;
    }
    else
    {
      if (!this->StepBack(_data))
        return res;
    }

    // If at least one of the steps was successfuly executed we'll return true.
    res = true;
  }

  return res;
}

/////////////////////////////////////////////////
bool LogPlay::StepBack(std::string &_data)
{
  auto from = std::string::npos;
  auto to = std::string::npos;

  std::lock_guard<std::mutex> lock(this->dataPtr->mutex);

  if (this->dataPtr->start > 0)
  {
    from = this->dataPtr->currentChunk.rfind(
        this->dataPtr->kStartFrame, this->dataPtr->start - 1);
    to = this->dataPtr->currentChunk.rfind(
        this->dataPtr->kEndFrame, this->dataPtr->start - 1);
  }

  if (this->dataPtr->start <= 0 || from == std::string::npos ||
      to == std::string::npos)
  {
    if (!this->PrevChunk())
      return false;

    from = this->dataPtr->currentChunk.rfind(this->dataPtr->kStartFrame);
    to = this->dataPtr->currentChunk.rfind(this->dataPtr->kEndFrame);
    if (from == std::string::npos || to == std::string::npos)
    {
      gzerr << "Unable to find an <sdf> frame in current chunk\n";
      return false;
    }
  }

  this->dataPtr->start = from;
  this->dataPtr->end = to;

  _data = this->dataPtr->currentChunk.substr(this->dataPtr->start,
      this->dataPtr->end + this->dataPtr->kEndFrame.size() -
      this->dataPtr->start);

  return true;
}

/////////////////////////////////////////////////
bool LogPlay::Rewind()
{
  std::lock_guard<std::mutex> lock(this->dataPtr->mutex);

  this->dataPtr->currentChunk.clear();
  this->dataPtr->logCurrXml =
    this->dataPtr->logStartXml->FirstChildElement("chunk");

  if (!this->dataPtr->logCurrXml)
  {
    gzerr << "Unable to jump to the beginning of the log file\n";
    return false;
  }

  if (!this->dataPtr->ChunkData(this->dataPtr->logCurrXml,
                                this->dataPtr->currentChunk))
  {
    return false;
  }

  // Skip first <sdf> block (it doesn't have a world state).
  this->dataPtr->end = this->dataPtr->currentChunk.find(
      this->dataPtr->kEndFrame);
  if (this->dataPtr->end == std::string::npos)
  {
    std::cerr << "Unable to find the first <sdf> block" << std::endl;
    return false;
  }

  // Remove the special first <sdf> block.
  this->dataPtr->currentChunk.erase(
      0, this->dataPtr->end + this->dataPtr->kEndFrame.size());

  this->dataPtr->start = 0;
  this->dataPtr->end = -1 * this->dataPtr->kEndFrame.size();

  return true;
}

/////////////////////////////////////////////////
bool LogPlay::Forward()
{
  std::lock_guard<std::mutex> lock(this->dataPtr->mutex);

  // Get the last chunk.
  this->dataPtr->logCurrXml =
    this->dataPtr->logStartXml->LastChildElement("chunk");

  if (!this->dataPtr->logCurrXml)
  {
    gzerr << "Unable to jump to the end of the log file\n";
    return false;
  }

  if (!this->dataPtr->ChunkData(this->dataPtr->logCurrXml,
                                this->dataPtr->currentChunk))
  {
    return false;
  }

  this->dataPtr->start = this->dataPtr->currentChunk.size() - 1;
  this->dataPtr->end = this->dataPtr->currentChunk.size() - 1;

  return true;
}

/////////////////////////////////////////////////
bool LogPlay::Seek(const common::Time &_time)
{
  if (_time >= this->dataPtr->logEndTime)
  {
    this->Forward();
    std::string frame;
    this->Step(-2, frame);
    return true;
  }

  common::Time logTime = this->dataPtr->logStartTime;

  // 1st step: Locate the chunk: We're looking for the first chunk that has
  // a time greater than the target time.
  int64_t imin = 0;
  int64_t imax = this->ChunkCount() - 1;
  while (imin <= imax)
  {
    int64_t imid = imin + ((imax - imin) / 2);
    this->Chunk(imid, this->dataPtr->currentChunk);

    this->dataPtr->start = 0;
    this->dataPtr->end = -1 * this->dataPtr->kEndFrame.size();

    // We try a few times looking for <sim_time>.
    for (unsigned int i = 0; i < 2; ++i)
    {
      std::string frame;
      if (!this->Step(frame))
        return false;

      // Search the <sim_time> in the first frame of the current chunk.
      auto from = frame.find(this->dataPtr->kStartTime);
      auto to = frame.find(
          this->dataPtr->kEndTime, from + this->dataPtr->kStartTime.size());
      if (from != std::string::npos && to != std::string::npos)
      {
        auto length = to - from - this->dataPtr->kStartTime.size();
        auto logTimeStr = frame.substr(
            from + this->dataPtr->kStartTime.size(), length);
        std::stringstream ss(logTimeStr);
        ss >> logTime;
        break;
      }
    }

    // Chunk found.
    if (logTime == _time)
      break;
    else if (logTime < _time)
      imin = imid + 1;
    else
      imax = imid - 1;
  }

  if (logTime < _time)
  {
    if (!this->NextChunk())
      this->Forward();
  }

  // 2nd step: Locate the frame in the previous chunk.
  while (true)
  {
    std::string frame;
    if (!this->StepBack(frame))
      break;

    // Search the <sim_time> in the frame of the current chunk.
    auto from = frame.find(this->dataPtr->kStartTime);
    auto to = frame.find(
        this->dataPtr->kEndTime, from + this->dataPtr->kStartTime.size());
    if (from != std::string::npos && to != std::string::npos)
    {
      auto length = to - from - this->dataPtr->kStartTime.size();
      auto logTimeStr = frame.substr(
          from + this->dataPtr->kStartTime.size(), length);
      std::stringstream ss(logTimeStr);
      ss >> logTime;

      // frame found.
      if (logTime < _time)
        break;
    }
  }

  return true;
}

/////////////////////////////////////////////////
bool LogPlay::Chunk(unsigned int _index, std::string &_data) const
{
  unsigned int count = 0;
  this->dataPtr->logCurrXml =
    this->dataPtr->logStartXml->FirstChildElement("chunk");

  while (this->dataPtr->logCurrXml && count < _index)
  {
    count++;
    this->dataPtr->logCurrXml =
      this->dataPtr->logCurrXml->NextSiblingElement("chunk");
  }

  if (this->dataPtr->logCurrXml && count == _index)
    return this->dataPtr->ChunkData(this->dataPtr->logCurrXml, _data);
  else
    return false;
}

/////////////////////////////////////////////////
bool LogPlayPrivate::ChunkData(
    tinyxml2::XMLElement *_xml,
    std::string &_data)
{
  // Make sure we have valid xml pointer
  if (!_xml)
  {
    gzerr << "NULL XML element" << std::endl;
    return false;
  }

  /// Get the chunk's encoding
  this->encoding = _xml->Attribute("encoding");

  // Make sure there is an encoding value.
  if (this->encoding.empty())
  {
    gzthrow("Encoding missing for a chunk in log file[" + this->filename + "]");
  }

  if (this->encoding == "txt")
    _data = _xml->GetText();
  else if (this->encoding == "bz2")
  {
    std::string data = _xml->GetText();
    std::string buffer;

    // Decode the base64 string
    buffer = Base64Decode(data);

    // Decompress the bz2 data
    {
      boost::iostreams::filtering_istream in;
      in.push(boost::iostreams::bzip2_decompressor());
      in.push(boost::make_iterator_range(buffer));

      // Get the data
      std::getline(in, _data, '\0');
      _data += '\0';
    }
  }
  else if (this->encoding == "zlib")
  {
    std::string data = _xml->GetText();
    std::string buffer;

    // Decode the base64 string
    buffer = Base64Decode(data);

    // Decompress the zlib data
    {
      boost::iostreams::filtering_istream in;
      in.push(boost::iostreams::zlib_decompressor());
      in.push(boost::make_iterator_range(buffer));

      // Get the data
      std::getline(in, _data, '\0');
      _data += '\0';
    }
  }
  else
  {
    gzerr << "Invalid encoding[" << this->encoding << "] in log file["
      << this->filename << "]\n";
    return false;
  }

  return true;
}

/////////////////////////////////////////////////
std::string LogPlay::Encoding() const
{
  return this->dataPtr->encoding;
}

/////////////////////////////////////////////////
unsigned int LogPlay::ChunkCount() const
{
  unsigned int count = 0;
  auto xml = this->dataPtr->logStartXml->FirstChildElement("chunk");

  while (xml)
  {
    count++;
    xml = xml->NextSiblingElement("chunk");
  }

  return count;
}

/////////////////////////////////////////////////
bool LogPlay::NextChunk()
{
  auto next = this->dataPtr->logCurrXml->NextSiblingElement("chunk");
  if (!next)
    return false;

  this->dataPtr->logCurrXml = next;
  if (!this->dataPtr->ChunkData(this->dataPtr->logCurrXml,
                                this->dataPtr->currentChunk))
  {
    return false;
  }

  this->dataPtr->start = 0;
  this->dataPtr->end = -1 * this->dataPtr->kEndFrame.size();

  return true;
}

/////////////////////////////////////////////////
bool LogPlay::PrevChunk()
{
  auto prev = this->dataPtr->logCurrXml->PreviousSiblingElement("chunk");
  if (!prev)
    return false;

  this->dataPtr->logCurrXml = prev;
  if (!this->dataPtr->ChunkData(this->dataPtr->logCurrXml,
                                this->dataPtr->currentChunk))
  {
    return false;
  }

  this->dataPtr->start = this->dataPtr->currentChunk.size() - 1;
  this->dataPtr->end = this->dataPtr->currentChunk.size() - 1;

  return true;
}

ext: cc


text:
//          Copyright Camille Gillot 2012 - 2015.
// 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 RTTI_MPH_HIERARCHY_HPP
#define RTTI_MPH_HIERARCHY_HPP

#include <cstddef>
#include <map>

#include "early.hpp"

#include "klass.hpp"

#include <boost/unordered_map.hpp>

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

#include <boost/range/adaptor/transformed.hpp>

/*!\brief Class hierarchy object
 *
 * This class acts as a factory for \c klass objects.
 */
class hierarchy_t
{
public:
  //!\brief Ctor
   hierarchy_t();
  //!\brief Dtor
  ~hierarchy_t();

public:
  //!\brief Compute poles for \c *this
  //!\arg input The static arguments of mmethods
  //!\c *this is filled with the poles
  void compute_poles(std::vector<rtti_hierarchy> const& input);

  //!poles are sorted in reverse subtyping order :
  //!base classes first
  //@{
  typedef std::vector<klass_t* > range_type;
  range_type const& range() const {
      return klasses;
  }
  //@}

  //!\brief Fetch klass from rtti_hierarchy
  klass_t const* fetch(rtti_hierarchy) const;
  //!\brief Like fetch
  //!\return NULL is not found
  klass_t const* try_fetch(rtti_hierarchy) const;

  //!\brief Like try_fetch, but upcast until found
  klass_t const* try_fetch_from(rtti_hierarchy) const;
  //!\brief Like fetch, but upcast until found
  klass_t const* fetch_from(rtti_hierarchy) const;

private:
  //!\brief Register new node in hierarchy.
  void add_pole(rtti_hierarchy, klass_t::bases_type&);
  //!\brief Compute that bases that are also poles.
  void effective_bases(rtti_hierarchy, klass_t::bases_type*);
  //!\brief pseudo_closest algorithm to find upwards poles.
  std::size_t pseudo_closest(
    rtti_hierarchy
  , klass_t::bases_type const&
  , klass_t const**
  );

private:
  std::vector<klass_t*> klasses;

  typedef boost::unordered_map<rtti_hierarchy, klass_t const*> poles_map_t;
  poles_map_t poles;

  std::size_t current_rank;
};

typedef std::vector<hierarchy_t> pole_table_t;

#include "signature.hpp"

namespace hierarchy_detail {
  struct hierarchy_adder {
    klass_t const* operator()(rtti_hierarchy a0, hierarchy_t& a1) const
    {
      klass_t const* ret = a1.fetch(a0);
      BOOST_ASSERT(ret);
      return ret;
    }
  };
} // namespace hierarchy_detail

template<typename R0>
signature_t make_signature(R0 const& r0, pole_table_t& r1) {
  signature_t ret ( r1.size() );

  std::transform(
    r0.begin(), r0.end(),
    r1.begin(),

    ret.array_ref().begin(),

    hierarchy_detail::hierarchy_adder()
  );

  return ret;
}

#endif

max_stars_repo_name: cjgillot/rtti

max_issues_repo_name: cjgillot/rtti

max_forks_repo_name: cjgillot/rtti


text:
#pragma once

#include "boost_defs.hpp"

#include <boost/signals2.hpp>

namespace krbn {
class boost_utility final {
public:
  struct signal2_combiner_call_while_true {
    typedef bool result_type;

    template <typename input_iterator>
    result_type operator()(input_iterator first_observer,
                           input_iterator last_observer) const {
      result_type value = true;
      for (;
           first_observer != last_observer && value;
           std::advance(first_observer, 1)) {
        value = *first_observer;
      }
      return value;
    }
  };
};
} // namespace krbn

max_stars_repo_name: trueneu/Karabiner-Elements

max_issues_repo_name: trueneu/Karabiner-Elements

max_forks_repo_name: trueneu/Karabiner-Elements


text:
#include "catch.hpp"
#include <boost/icl/interval.hpp>
#include <boost/icl/interval_set.hpp>
#include <boost/icl/map.hpp> // required only for boost::icl::partial_enricher.
#include <boost/icl/separate_interval_set.hpp>
#include <boost/icl/split_interval_set.hpp>
#include <boost/icl/interval_map.hpp>
#include <boost/optional.hpp>
#include <iostream>

TEST_CASE("interval tests", "[boost]")
{
    typedef boost::icl::interval<int> Interval;

    SECTION("closed intervals")
    {
        auto ival = Interval::closed(1, 3);
        REQUIRE(ival.lower() == 1);
        REQUIRE(ival.upper() == 3);
        REQUIRE(contains(ival, 1) == true);
        REQUIRE(contains(ival, 3) == true);
    }

    SECTION("open intervals")
    {
        auto ival = Interval::open(1, 3);
        REQUIRE(ival.lower() == 1);
        REQUIRE(ival.upper() == 3);
        REQUIRE(contains(ival, 1) == false);
        REQUIRE(contains(ival, 3) == false);
    }

    SECTION("right open intervals")
    {
        auto ival = Interval::right_open(1, 3);
        REQUIRE(ival.lower() == 1);
        REQUIRE(ival.upper() == 3);
        REQUIRE(contains(ival, 1) == true);
        REQUIRE(contains(ival, 3) == false);
    }

    SECTION("left open intervals")
    {
        auto ival = Interval::left_open(1, 3);
        REQUIRE(ival.lower() == 1);
        REQUIRE(ival.upper() == 3);
        REQUIRE(contains(ival, 1) == false);
        REQUIRE(contains(ival, 3) == true);
    }
}

TEST_CASE("interval set tests", "[boost]")
{
    typedef boost::icl::interval<int> Interval;

    SECTION("interval sets")
    {
        // intervals joined on overlap or touch.
        typedef boost::icl::interval_set<int> IntervalSet;
        auto iset = IntervalSet{};

        iset += Interval::closed(1, 3);
        REQUIRE((iset == IntervalSet(Interval::closed(1, 3))));

        iset += Interval::open(2, 5);
        REQUIRE((iset == IntervalSet(Interval::right_open(1, 5))));

        iset += Interval::closed(5, 7);
        REQUIRE((iset == IntervalSet(Interval::closed(1, 7))));

        iset += Interval::closed(10, 12);
        REQUIRE(contains(iset, Interval::closed(2, 6)));
        REQUIRE(contains(iset, Interval::closed(10, 12)));
        REQUIRE_FALSE(contains(iset, Interval::closed(8, 9)));
        REQUIRE_FALSE(contains(iset, Interval::closed(8, 11)));
    }

    SECTION("separate interval sets")
    {
        // intervals joined on overlap, not touch.
        typedef boost::icl::separate_interval_set<int> SeparateIntervalSet;
        auto se_iset = SeparateIntervalSet{};

        se_iset += Interval::right_open(1, 3);
        se_iset += Interval::closed(3, 5);

        // As se_iset is {[1, 3), [3, 5]}, it cannot equal [1,5].
        REQUIRE_FALSE((se_iset == SeparateIntervalSet(Interval::closed(1, 5))));

        se_iset += Interval::closed(2, 4);

        // Now, the disjoint intervals are connected and make se_iset [1,5].
        REQUIRE((se_iset == SeparateIntervalSet(Interval::closed(1, 5))));
    }

    SECTION("split interval sets")
    {
        // intervals split on overlap, borders preserved.
        typedef boost::icl::split_interval_set<int> SplitIntervalSet;
        auto sp_iset = SplitIntervalSet{};

        sp_iset += Interval::right_open(1, 3);
        sp_iset += Interval::right_open(2, 5);

        auto res = SplitIntervalSet{};
        res += Interval::right_open(1, 2);
        res += Interval::right_open(2, 3);
        res += Interval::right_open(3, 5);
        REQUIRE((sp_iset == res));
    }
}

TEST_CASE("interval map tests", "[boost]")
{
    // interval maps have the "identity absorber" property. This prevents
    // storing identities as values. For example, the following values cannot
    // be stored:
    // - int values cannot store 0.
    // - std::string values cannot store "".
    // - set<T> values cannot store {}.
    typedef boost::icl::interval<int> Interval;
    typedef boost::icl::discrete_interval<int> DiscreteInterval;

    SECTION("interval maps")
    {
        typedef boost::icl::interval_map<int, int> IntervalMap;
        auto imap = IntervalMap{};

        imap += std::make_pair(Interval::closed(6, 8), 1);
        imap += std::make_pair(Interval::closed(7, 9), 2);

        std::vector<int> key_lowers, key_uppers, vals;
        std::vector<DiscreteInterval> keys;
        for (auto it = imap.begin(); it != imap.end(); ++it)
        {
            key_lowers.push_back(it->first.lower());
            key_uppers.push_back(it->first.upper());
            vals.push_back(it->second);
            keys.push_back(it->first);
        }

        REQUIRE((key_lowers == std::vector<int>({6, 7, 8})));
        REQUIRE((key_uppers == std::vector<int>({7, 8, 9})));
        REQUIRE((vals == std::vector<int>({1, 3, 2})));
        REQUIRE((keys == std::vector<DiscreteInterval>(
                             {DiscreteInterval::right_open(6, 7),
                              DiscreteInterval::closed(7, 8),
                              DiscreteInterval::left_open(8, 9)})));
    }

    SECTION("enriched interval maps")
    {
        typedef boost::icl::interval_map<int, int, boost::icl::partial_enricher> EIMap;

        // The third template above is a trait of the interval map.
        // There are 4 possible traits:
        // - partial_absorber
        // - partial_enricher
        // - total absorber
        // - total enricher
        // "partial" means that the map is defined only for keys that have been
        // inserted.
        // "total" means that the map is considered to have a "neutral" value
        // for all keys not stored in the map.
        // "absorber" means that the identity element with respect to "+"
        // cannot be stored as a value. For example, 0 for int types and "" for
        // std::string types.
        // "enricher" allows storing the identity element.

        auto eimap = EIMap{};

        eimap += std::make_pair(Interval::closed(1, 10), 0);
        eimap += std::make_pair(Interval::closed(3, 5), 1);
        eimap += std::make_pair(Interval::closed(8, 10), 3);

        std::vector<DiscreteInterval> keys;
        std::vector<int> vals;
        for (auto it = eimap.begin(); it != eimap.end(); ++it)
        {
            keys.push_back(it->first);
            vals.push_back(it->second);
        }

        REQUIRE((keys == std::vector<DiscreteInterval>(
                             {DiscreteInterval::right_open(1, 3),
                              DiscreteInterval::closed(3, 5),
                              DiscreteInterval::open(5, 8),
                              DiscreteInterval::closed(8, 10)})));
        REQUIRE((vals == std::vector<int>({0, 1, 0, 3})));
    }
}

TEST_CASE("optional test", "[boost]")
{
    SECTION("optional construction")
    {
        auto optInt = boost::optional<int>{};
        REQUIRE_FALSE(optInt.is_initialized());
        optInt = 1;
        REQUIRE(optInt.is_initialized());
        REQUIRE(optInt.get() == 1);
    }

    SECTION("optional returning function")
    {
        auto positivePart = [](int num) -> boost::optional<int> {
            return num > 0 ? num : boost::optional<int>{};
        };

        auto optVal = positivePart(5);
        REQUIRE(optVal.is_initialized());
        REQUIRE(optVal.get() == 5);
        REQUIRE_FALSE(positivePart(-5).is_initialized());
    }
}


text:
/*
 *  OutputEHDB.cpp
 *  Trogdor6
 *
 *  Created by Paul Hansen on 6/24/10.
 *  Copyright 2010 Stanford University. All rights reserved.
 *
 *  This file is covered by the MIT license.  See LICENSE.txt.
 */

#include "OutputEHDB.h"

#include "TimeWrapper.h"
#include "../YeeUtilities.h"
#include "../GridFields.h"
#include "../OutputDirectory.h"

//#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>

using namespace std;
//using namespace boost::posix_time;
using namespace YeeUtilities;

HandleRawField::
HandleRawField(const OutputField & field, const vector<RunlineOutput> & runlines) :
    HandleOutput<RunlineOutput>(field, runlines),
    mHead(0L)
{
}

long HandleRawField::
calc(std::ostream & binaryStream)
{
    if (mRunlines.size() > 0)
    {
        assert(mHead != 0L);
    }

    long numCells = 0;
    for (int rr = 0; rr < mRunlines.size(); rr++)
    {
        numCells += runlines()[rr].length();
        if (runlines()[rr].head() == -1)
        {
            const Precision::Float zed = 0.0;
            for (int nn = 0; nn < runlines()[rr].length(); nn++)
                binaryStream.write((char*) &zed, sizeof(Precision::Float));
        }
        else
        {
            binaryStream.write((char*) (mHead + runlines()[rr].head()),
                (std::streamsize)(runlines()[rr].length()*sizeof(Precision::Float)));
        }
    }
    return numCells;
}

void HandleRawField::
setPointers(GridFields & fields)
{
    std::cout << "Field name " << field().fieldAsString() << "\n";
    assert(field().ii() == field().jj());
    mHead = fields.field(field().field(), field().ii());
}

//HandleSparseField::
//HandleSparseField(const OutputField & field, const vector<RunlineOutput> & runlines) :
//    HandleOutput<RunlineOutput>(field, runlines),
//    mHead(0L)
//{
//}
//
//long HandleSparseField::
//calc(std::ostream & binaryStream)
//{
//    assert(mHead != 0L);
//    long numCells = 0;
//    for (int rr = 0; rr < mRunlines.size(); rr++)
//    {
//        numCells += runlines()[rr].length();
//        if (runlines()[rr].head() != -1)
//        {
//            binaryStream.write((char*) (mHead + runlines()[rr].head()),
//                (std::streamsize)(runlines()[rr].length()*sizeof(Precision::Float)));
//        }
//        else
//        {
//            const Precision::Float zed = 0.0;
//            for (int nn = 0; nn < runlines()[rr].length(); nn++)
//                binaryStream.write((char*) &zed, sizeof(Precision::Float));
//        }
//    }
//}

//void HandleSparseField::
//setPointers(GridFields & fields)
//{
//    mHead = fields.field(field().field(), field().ii());
//}

HandleTensorialDiagonalField::
HandleTensorialDiagonalField(const OutputField & field,
    const vector<RunlineTensorialOutput> & runlines) :
    HandleOutput<RunlineTensorialOutput>(field, runlines),
    mHead0(0L),
    mHead1(0L)
{
}

long HandleTensorialDiagonalField::
calc(ostream & binaryStream)
{
    //assert(mHead0 != 0L); // might be null!
    assert(mHead1 != 0L); // should never be null.
    long numCells = 0;
    for (int rr = 0; rr < mRunlines.size(); rr++)
    {
        Precision::Float* headPointer;
        unsigned long offset;
        if (runlines()[rr].head_ii() != -1)
        {
            headPointer = mHead0;
            offset = runlines()[rr].head_ii();
        }
        else
        {
            headPointer = mHead1;
            offset = runlines()[rr].head_i();
        }
        numCells += runlines()[rr].length();
        binaryStream.write((char*) (headPointer + offset),
            (std::streamsize)(runlines()[rr].length()*sizeof(Precision::Float)));
    }
    return numCells;
}

void HandleTensorialDiagonalField::
setPointers(GridFields & fields)
{
    assert(field().ii() == field().jj());
    mHead0 = fields.field(field().field(), field().ii(), field().ii()); // may be null

    if (field().field() == kEE)
        mHead1 = fields.field(kE, field().ii());
    else if (field().field() == kHH)
        mHead1 = fields.field(kH, field().ii());
    else
        throw(std::logic_error("Bad field"));

    assert(mHead1 != 0L);
}

HandleTensorialOffDiagonalField::
HandleTensorialOffDiagonalField(const OutputField & field,
    const vector<RunlineTensorialOutput> & runlines) :
    HandleOutput<RunlineTensorialOutput>(field, runlines),
    mHead(0L)
{
}

long HandleTensorialOffDiagonalField::
calc(ostream & binaryStream)
{
    long numCells = 0;
    for (int rr = 0; rr < mRunlines.size(); rr++)
    {
        if (runlines()[rr].head_ii() != -1)
        {
            assert(mHead != 0L);
            binaryStream.write((char*) (mHead + runlines()[rr].head_ii()),
                (std::streamsize)(runlines()[rr].length()*sizeof(Precision::Float)));
            numCells += runlines()[rr].length();
        }
        else
        {
            const Precision::Float ZED(0.0);
            for (int ll = 0; ll < runlines()[rr].length(); ll++)
            {
                binaryStream.write((char*) &ZED,
                    (std::streamsize)sizeof(Precision::Float));
                numCells += 1;
            }
        }
    }
    return numCells;
}

void HandleTensorialOffDiagonalField::
setPointers(GridFields & fields)
{
    assert(field().ii() != field().jj());
    mHead = fields.field(field().field(), field().ii(), field().jj());
}

HandleAveragedField::
HandleAveragedField(const OutputField & field,
    const vector<RunlineAverageTwo> & runlines) :
    HandleOutput<RunlineAverageTwo>(field, runlines),
    mHead(0L)
{
}

long HandleAveragedField::
calc(ostream & binaryStream)
{
    assert(mHead != 0L);
    long numCells = 0;
    Precision::Float meanVal;
    for (int rr = 0; rr < mRunlines.size(); rr++)
    for (int ll = 0; ll < mRunlines[rr].length(); ll++)
    {
        meanVal = 0.5*(*(mHead + runlines()[rr].head0() + ll) +
            *(mHead + runlines()[rr].head1() + ll));

        binaryStream.write((char*) &meanVal,
            (std::streamsize)sizeof(Precision::Float));
        numCells += 1;
    }
    return numCells;
}

void HandleAveragedField::
setPointers(GridFields & fields)
{
    assert(field().ii() == field().jj());
    mHead = fields.field(field().field(), field().ii());
}

OutputEHDB::
OutputEHDB(const OutputDescription & description,
    Precision::Vec3 dxyz, Precision::Float dt, Precision::Vec3 origin) :
    mFileName(description.file()),
    mDurations(description.durations()),
    mCurrentDuration(0)
{
    string fileName = description.file() + ".txt";
    ofstream file(OutputDirectory::path(fileName).c_str());
    writeOutputHeader(file, fileName, description.file(), dxyz, dt, origin);
    writeOutputFields(file, description);
    writeOutputRegions(file, description.regions());
    writeOutputDurations(file, description.durations());
    file.close();

    mDataFile.open(OutputDirectory::path(description.file()).c_str());

    if (!mDataFile)
    {
        cerr << "Error opening file " << OutputDirectory::path(description.file()) << "\n";
        throw(std::runtime_error("Could not open output file!"));
    }

    mDataFile << setprecision(10);
}

OutputEHDB::
~OutputEHDB()
{
    mDataFile.close();

    for (int ff = 0; ff < mFields.size(); ff++)
        delete mFields.at(ff);
}

void OutputEHDB::
appendField(const OutputField & field, const vector<RunlineOutput> & runlines)
{
    mFields.push_back((HandleOutputBase*) new HandleRawField(field, runlines));
}

void OutputEHDB::
appendField(const OutputField & field,
    const vector<RunlineAverageTwo> & runlines)
{
    mFields.push_back((HandleOutputBase*) new HandleAveragedField(field, runlines));
}

void OutputEHDB::
appendTensorialDiagonalField(const OutputField & field,
    const vector<RunlineTensorialOutput> & runlines)
{
    mFields.push_back((HandleOutputBase*)
        new HandleTensorialDiagonalField(field, runlines));
}

void OutputEHDB::
appendTensorialOffDiagonalField(const OutputField & field,
    const vector<RunlineTensorialOutput> & runlines)
{
    mFields.push_back((HandleOutputBase*)
        new HandleTensorialOffDiagonalField(field, runlines));
}

void OutputEHDB::
setPointers(GridFields & fields)
{
    for (int ff = 0; ff < mFields.size(); ff++)
        mFields[ff]->setPointers(fields);
}

void OutputEHDB::
calc(int timestep)
{
    if (mCurrentDuration >= mDurations.size())
        return;
    if (timestep < mDurations[mCurrentDuration].first())
        return;
    while (mCurrentDuration < mDurations.size() &&
        timestep > mDurations[mCurrentDuration].last())
        mCurrentDuration++;
    if (mCurrentDuration >= mDurations.size())
        return;

    if ( (timestep - mDurations[mCurrentDuration].first()) %
        (mDurations[mCurrentDuration].period()) != 0)
        return;

    long numCells = 0;
    for (int ff = 0; ff < mFields.size(); ff++)
        numCells += mFields[ff]->calc(mDataFile);

//    LOG << "Timestep " << timestep << " wrote " << numCells << " cells.\n";
}

void OutputEHDB::
writeOutputHeader(ostream & file,
    string fileName,
    string dataFileName,
    Precision::Vec3 dxyz,
    Precision::Float dt,
    Precision::Vec3 origin) const
{
//    ptime now(second_clock::local_time());
    // Header: all IO description files will have this.
    file << "trogdor5data\n";
//    file << "trogdorMajorVersion " << TROGDOR_MAJOR_VERSION << "\n";
//    file << "trogdorSVNVersion NOTUSED\n";
    file << "trogdorBuildDate " << __DATE__ << "\n";
    if (sizeof(Precision::Float) == sizeof(float))
        file << "precision float32\n";
    else if (sizeof(Precision::Float) == sizeof(double))
        file << "precision float64\n";
    else
        throw(std::logic_error("Precision is not 32-bit or 64-bit."));
    file << "date " << TimeWrapper::timestampNow() << "\n";
    file << "dxyz " << dxyz << "\n";
    file << "dt " << dt << "\n";
    file << "origin " << setprecision(10) << origin << "\n";
//    file << "runlineDirection " << vp.lattice().runlineDirection() << "\n";
    file << "specfile " << OutputDirectory::path(fileName) << "\n";
    file << "datafile " << OutputDirectory::path(dataFileName) << "\n";
}

void OutputEHDB::
writeOutputFields(ostream & file, const OutputDescription & description) const
{
    for (int nn = 0; nn < description.fields().size(); nn++)
    {
        file << "field " << description.fields().at(nn).fieldAsString() << " "
            << description.fields().at(nn).cellOffset() << " "
            << description.fields().at(nn).timeOffset() << "\n";
    }
}

void OutputEHDB::
writeOutputRegions(ostream & file,
    const vector<Region> & regions) const
{
    for (int nn = 0; nn < regions.size(); nn++)
    {
        file << "region "
            << regions[nn].yeeCells()
            << " stride "
            << regions[nn].stride();

        if (regions[nn].hasBounds())
        {
            file << " bounds " << regions[nn].bounds();
        }

        file << "\n";
    }
}

void OutputEHDB::
writeOutputDurations(ostream & file,
    const vector<Duration> & durations) const
{
    for (int nn = 0; nn < durations.size(); nn++)
    {
        file << "duration from "
            << durations[nn].first() << " to "
            << durations[nn].last() << " period "
            << durations[nn].period();

        if (durations[nn].hasInterval())
            file << " interval " << durations[nn].interval() << "\n";

        file << "\n";
    }
}


text:
/*=============================================================================
    Copyright (c) 2002-2003 Joel de Guzman
    http://spirit.sourceforge.net/

    Use, modification and distribution is 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)
=============================================================================*/
///////////////////////////////////////////////////////////////////////////////
//
//  A primitive calculator that knows how to add and subtract.
//  [ demonstrating phoenix ]
//
//  [ JDG 6/28/2002 ]
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/core.hpp>
#include <boost/spirit/phoenix/primitives.hpp>
#include <boost/spirit/phoenix/operators.hpp>
#include <iostream>
#include <string>

///////////////////////////////////////////////////////////////////////////////
using namespace std;
using namespace boost::spirit;
using namespace phoenix;

///////////////////////////////////////////////////////////////////////////////
//
//  Our primitive calculator
//
///////////////////////////////////////////////////////////////////////////////
template <typename IteratorT>
bool primitive_calc(IteratorT first, IteratorT last, double& n)
{
    return parse(first, last,

        //  Begin grammar
        (
            real_p[var(n) = arg1]
            >> *(   ('+' >> real_p[var(n) += arg1])
                |   ('-' >> real_p[var(n) -= arg1])
                )
        )
        ,
        //  End grammar

        space_p).full;
}

////////////////////////////////////////////////////////////////////////////
//
//  Main program
//
////////////////////////////////////////////////////////////////////////////
int
main()
{
    cout << "/////////////////////////////////////////////////////////\n\n";
    cout << "\t\tA primitive calculator...\n\n";
    cout << "/////////////////////////////////////////////////////////\n\n";

    cout << "Give me a list of numbers to be added or subtracted.\n";
    cout << "Example: 1 + 10 + 3 - 4 + 9\n";
    cout << "The result is computed using Phoenix.\n";
    cout << "Type [q or Q] to quit\n\n";

    string str;
    while (getline(cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        double n;
        if (primitive_calc(str.begin(), str.end(), n))
        {
            cout << "-------------------------\n";
            cout << "Parsing succeeded\n";
            cout << str << " Parses OK: " << endl;

            cout << "result = " << n;
            cout << "\n-------------------------\n";
        }
        else
        {
            cout << "-------------------------\n";
            cout << "Parsing failed\n";
            cout << "-------------------------\n";
        }
    }

    cout << "Bye... :-) \n\n";
    return 0;
}

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM