text:
/*************************************************************************
 * Copyright (C) 2017-2019 Barcelona Supercomputing Center               *
 *                         Centro Nacional de Supercomputacion           *
 * All rights reserved.                                                  *
 *                                                                       *
 * This file is part of NORNS, a service that allows other programs to   *
 * start, track and manage asynchronous transfers of data resources      *
 * between different storage backends.                                   *
 *                                                                       *
 * See AUTHORS file in the top level directory for information regarding *
 * developers and contributors.                                          *
 *                                                                       *
 * This software was developed as part of the EC H2020 funded project    *
 * NEXTGenIO (Project ID: 671951).                                       *
 *     www.nextgenio.eu                                                  *
 *                                                                       *
 * 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.                                                             *
 *************************************************************************/

#ifndef __SETTINGS_HPP__
#define __SETTINGS_HPP__

#include <list>
#include <boost/filesystem.hpp>
#include <netinet/in.h>

namespace bfs = boost::filesystem;

namespace norns {
namespace config {

struct namespace_def {

    namespace_def(const std::string& nsid,
                  bool track,
                  const bfs::path& mountpoint,
                  const std::string& alias,
                  const uint64_t capacity,
                  const std::string& visibility) :
        m_nsid(nsid),
        m_track(track),
        m_mountpoint(mountpoint),
        m_alias(alias),
        m_capacity(capacity),
        m_visibility(visibility) { }

    namespace_def(const namespace_def& other) = default;

    namespace_def(namespace_def&& rhs) = default;

    namespace_def&
    operator=(const namespace_def& other) = default;

    namespace_def&
    operator=(namespace_def&& rhs) = default;

    std::string
    nsid() const {
        return m_nsid;
    }

    bool
    track() const {
        return m_track;
    }

    bfs::path
    mountpoint() const {
        return m_mountpoint;
    }

    std::string
    alias() const {
        return m_alias;
    }

    uint64_t
    capacity() const {
        return m_capacity;
    }

    std::string
    visibility() const {
        return m_visibility;
    }

    std::string m_nsid;
    bool        m_track;
    bfs::path   m_mountpoint;
    std::string m_alias;
    uint64_t    m_capacity;
    std::string m_visibility;
};

struct settings {

    settings();

    settings(const std::string& progname,
             bool daemonize,
             bool use_syslog,
             bool use_console,
             const bfs::path& log_file,
             const uint32_t log_file_max_size,
             bool dry_run,
             uint32_t dry_run_duration,
             const bfs::path& global_socket,
             const bfs::path& control_socket,
             const std::string& bind_address,
             uint32_t remote_port,
             const bfs::path& pidfile,
             uint32_t workers,
             const bfs::path& staging_directory,
             uint32_t backlog_size,
             const bfs::path& cfgfile,
             const std::list<namespace_def>& defns);

    void
    load_defaults();

    void
    load_from_file(const bfs::path& filename);

    std::string
    to_string() const;

    settings(const settings& other) = default;

    settings(settings&& rhs) = default;

    settings&
    operator=(const settings& other) = default;

    settings&
    operator=(settings&& rhs) = default;

    ~settings() = default;

    std::string
    progname() const;

    void
    progname(const std::string& progname);

    bool
    daemonize() const;

    void
    daemonize(bool daemonize);

    bool
    use_syslog() const;

    void
    use_syslog(bool use_syslog);

    bool
    use_console() const;

    void
    use_console(bool use_console);

    bfs::path
    log_file() const;

    void
    log_file(const bfs::path& log_file);

    uint32_t
    log_file_max_size() const;

    void
    log_file_max_size(uint32_t log_file_max_size);

    bool
    dry_run() const;

    void
    dry_run(bool dry_run);

    uint32_t
    dry_run_duration() const;

    void
    dry_run_duration(uint32_t dry_run_duration);

    bfs::path
    global_socket() const;

    void
    global_socket(const bfs::path& global_socket);

    bfs::path
    control_socket() const;

    void
    control_socket(const bfs::path& control_socket);

    std::string
    bind_address() const;

    void
    bind_address(const std::string& bind_address);

    in_port_t
    remote_port() const;

    void
    remote_port(in_port_t remote_port);

    bfs::path
    pidfile() const;

    void
    pidfile(const bfs::path& pidfile);

    uint32_t
    workers_in_pool() const;

    void
    workers_in_pool(uint32_t workers_in_pool);

    bfs::path
    staging_directory() const;

    void
    staging_directory(const bfs::path& staging_directory);

    uint32_t
    backlog_size() const;

    void
    backlog_size(uint32_t backlog_size);

    bfs::path
    config_file() const;

    void
    config_file(const bfs::path& config_file);

    std::list<namespace_def>
    default_namespaces() const;

    void
    default_namespaces(const std::list<namespace_def>& default_namespaces);

    std::string m_progname;
    bool        m_daemonize;
    bool        m_use_syslog;
    bool        m_use_console;
    bfs::path   m_log_file;
    uint32_t    m_log_file_max_size;
    bool        m_dry_run;
    uint32_t    m_dry_run_duration;
    bfs::path   m_global_socket;
    bfs::path   m_control_socket;
    std::string m_bind_address;
    in_port_t   m_remote_port;
    bfs::path   m_daemon_pidfile;
    uint32_t    m_workers_in_pool;
    bfs::path   m_staging_directory;
    uint32_t    m_backlog_size;
    bfs::path   m_config_file;
    std::list<namespace_def> m_default_namespaces;
};

} // namespace config
} // namespace norns

#endif /* __SETTINGS_HPP__ */

max_stars_repo_name: bsc-ssrg/NORNS

max_issues_repo_name: bsc-ssrg/NORNS

max_forks_repo_name: bsc-ssrg/NORNS


text:
#pragma once
#include <string>

#if defined(WIN32) && defined(MSVS)
#include <filesystem>
#endif // WIN32 && MSVS

#if defined(UNIX) && defined(USE_BOOST)
#include <boost/filesystem.hpp>
#endif // UNIX && USE_BOOST

namespace blood {
    namespace sys {
#if defined(WIN32) || defined(MSVS)
    namespace fs = std::tr2::sys;
#endif
#if defined(UNIX) && defined(USE_BOOST)
    namespace fs = boost::filesystem;
#endif
}}; // end blood::sys

ext: hxx

max_stars_repo_name: vbloodv/blood

max_issues_repo_name: vbloodv/blood

max_forks_repo_name: vbloodv/blood


text:
#include <libral/context.hpp>

#include <libral/provider.hpp>

#include <boost/algorithm/string.hpp>
#include <leatherman/logging/logging.hpp>

namespace algo = boost::algorithm;
namespace logging = leatherman::logging;

namespace libral {

  static const std::string c_ensure = "ensure";
  static const value       c_absent = value("absent");

  /*
   * implementation for changes
   */

  void changes::add(const std::string &attr, const value &is,
                    const value &was) {
    push_back(change(attr, is, was));
  }

  bool changes::add(const std::string &attr, const update &upd) {
    bool changed = upd.changed(attr);
    if (changed) {
      add(attr, upd.should[attr], upd.is[attr]);
    }
    return changed;
  }

  bool changes::add(const std::vector<std::string> &attrs, const update &upd) {
    bool changed = false;
    for (auto attr : attrs) {
      if (add(attr, upd))
        changed = true;
    }
    return changed;
  }

  bool changes::maybe_add(const update& upd) {
    bool changed = false;

    if (upd[c_ensure] == value(c_absent)) {
      // Special treatment when ensure is absent: only diff the ensure
      // attribute
      if (! exists(c_ensure) && upd.changed(c_ensure)) {
        add(c_ensure, upd.should[c_ensure], upd.is[c_ensure]);
        changed = true;
      }
    } else {
      for (const auto& attr : upd.should.attrs()) {
        auto& is = upd.is[attr.first];
        if (attr.second != is && ! exists(attr.first)) {
          add(attr.first, attr.second, is);
          changed = true;
        }
      }
    }
    return changed;
  }

  bool changes::exists(const std::string &attr) {
    for (auto ch : (*this)) {
      if (ch.attr == attr)
        return true;
    }
    return false;
  }

  std::ostream& operator<<(std::ostream& os, changes const& chgs) {
    for (auto chg: chgs) {
      auto was = chg.was.to_string();
      auto is = chg.is.to_string();
      os << chg.attr << "(" << was << "->" << is << ")" << std::endl;
    }
    return os;
  }

  /*
   * implementation for context
   */
  changes& context::changes_for(const std::string& name) {
    // We do a bit of a dance here since we do not want the
    // changes constructor to be public
    auto it = _changes.find(name);
    if (it == _changes.end()) {
      return _changes.emplace(std::make_pair(name, changes())).first->second;
    } else {
      return it->second;
    }
  }

  bool context::have_changes(const std::string& name) {
    auto it = _changes.find(name);
    return (it != _changes.end());
  }

  libral::error context::error(const std::string& msg) const {
    std::ostringstream os;

    os << "[" << _prov->spec()->qname() << "] " << msg;
    return libral::error(os.str());
  }

  void log(logging::log_level level,
           const std::string& qname,
           const std::string& msg) {
    if (logging::is_enabled(level)) {
      logging::log(qname, level, 0, msg);
    }
  }

  void context::log_line(const std::string& line) {
    static const std::map<std::string, logging::log_level> levels = {
      { "debug", logging::log_level::debug },
      { "info", logging::log_level::info },
      { "warn", logging::log_level::warning },
      { "error", logging::log_level::error } };

    logging::log_level level = logging::log_level::warning;
    int start = 0;

    for (const auto &pair : levels) {
      if (algo::istarts_with(line, pair.first)) {
        level = pair.second;
        start = pair.first.size() + 1;
        break;
      }
    }
    if (logging::is_enabled(level)) {
      auto rest = line.substr(start);
      boost::trim(rest);
      log(level, _prov->spec()->qname(), rest);
    }
  }

  void context::log_debug(std::string const& msg) {
    log(logging::log_level::debug, _prov->spec()->qname(), msg);
  }

  void context::add_absent(std::vector<resource>& rsrcs,
                           const std::vector<std::string>& names) {
    for (auto& name : names) {
      auto rsrc = std::find_if(rsrcs.begin(), rsrcs.end(),
                  [&name](const resource& r) { return name == r.name(); });
      if (rsrc == rsrcs.end()) {
        rsrcs.push_back(_prov->create(name));
        rsrcs.back()["ensure"] = "absent";
      }
    }
  }

}

ext: cc

max_stars_repo_name: puppetlabs/libral

max_issues_repo_name: puppetlabs-toy-chest/libral

max_forks_repo_name: puppetlabs-toy-chest/libral


text:
#include <config.h>

#include "msfem_solver.hh"

#include <sstream>
#include <assert.h>
#include <boost/assert.hpp>

#include <dune/common/exceptions.hh>
#include <dune/common/timer.hh>

#include <dune/multiscale/msfem/coarse_scale_operator.hh>
#include <dune/multiscale/msfem/localproblems/localgridsearch.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/multiscale/common/traits.hh>
#include <dune/multiscale/common/heterogenous.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/msfem/localproblems/localgridlist.hh>
#include <dune/multiscale/tools/misc/outputparameter.hh>
#include <dune/multiscale/common/df_io.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/msfem/localproblems/localproblemsolver.hh>

#include <dune/xt/common/logging.hh>
#include <dune/xt/common/configuration.hh>
#include <dune/xt/common/timings.hh>
#include <dune/xt/common/ranges.hh>

#include <dune/gdt/operators/prolongations.hh>
#include <dune/gdt/spaces/cg.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/functionals/l2.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/operators/projections.hh>

#include <dune/multiscale/msfem/localsolution_proxy.hh>

namespace Dune {
namespace Multiscale {

void Elliptic_MsFEM_Solver::identify_fine_scale_part(const Problem::ProblemContainer& problem,
                                                     LocalGridList& localgrid_list,
                                                     const CommonTraits::DiscreteFunctionType& coarse_msfem_solution,
                                                     const CommonTraits::SpaceType& coarse_space,
                                                     std::unique_ptr<LocalsolutionProxy>& msfem_solution) const
{
  Dune::XT::Common::ScopedTiming st("msfem.idFine");
  const int rank = Dune::MPIHelper::getCollectiveCommunication().rank();

  auto& coarse_indexset = coarse_space.grid_view().grid().leafIndexSet();
  const bool is_simplex_grid = DSG::is_simplex_grid(coarse_space);

  LocalsolutionProxy::CorrectionsMapType local_corrections;
  const auto interior = coarse_space.grid_view().grid().leafGridView<InteriorBorder_Partition>();
  for (const auto& coarse_entity : Dune::elements(interior)) {
    LocalproblemSolutionManager localSolutionManager(coarse_space, coarse_entity, localgrid_list);
    localSolutionManager.load();
    auto& localproblem_solutions = localSolutionManager.getLocalSolutions();
    const auto coarse_index = coarse_indexset.index(coarse_entity);
    local_corrections[coarse_index] = Dune::XT::Common::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>(
        localSolutionManager.space(), "correction");

    auto& local_correction = *local_corrections[coarse_index];
    local_correction.vector() *= 0;
    const auto coarseSolutionLF = coarse_msfem_solution.local_discrete_function(coarse_entity);

    //! @warning At this point, we assume to have the same types of elements in the coarse and fine grid!
    //            BOOST_ASSERT_MSG(
    //                static_cast<long long>(localSolutions.size() - localSolManager.numBoundaryCorrectors()) ==
    //                    static_cast<long long>(coarseSolutionLF.size()),
    //                "The current implementation relies on having thesame types of elements on coarse and fine
    // level!");
    for (std::size_t dof = 0; dof < coarseSolutionLF->vector().size(); ++dof) {
      localproblem_solutions[dof]->vector() *= coarseSolutionLF->vector().get(dof);
      local_correction.vector() += localproblem_solutions[dof]->vector();
    }

    // oversampling : restrict the local correctors to the element T
    // ie set all dofs not "covered" by the coarse cell to 0
    // also adds lg-prolongation of coarse_solution to local_correction
    const auto cut_overlay = problem.config().get("msfem.oversampling_layers", 0) > 0;
    const auto& reference_element = DSG::reference_element(coarse_entity);
    const auto& coarse_geometry = coarse_entity.geometry();
    for (const auto& local_entity : Dune::elements(localSolutionManager.space().grid_view())) {
      const auto& lg_points = localSolutionManager.space().lagrange_points(local_entity);
      auto entity_local_correction = local_correction.local_discrete_function(local_entity);

      for (const auto lg_i : Dune::XT::Common::value_range(int(lg_points.size()))) {
        const auto local_point = lg_points[lg_i];
        const auto global_lg_point = local_entity.geometry().global(local_point);
        const auto local_coarse_point = coarse_geometry.local(global_lg_point);
        auto& vec = entity_local_correction->vector();
        if (cut_overlay) {
          const bool covered = reference_element.checkInside(local_coarse_point);
          vec.set(lg_i, covered ? vec.get(lg_i) : 0);
        }
      }
    }

    // add dirichlet corrector
    local_correction.vector() += localproblem_solutions[coarseSolutionLF->vector().size() + 1]->vector();
    // substract neumann corrector
    local_correction.vector() -= localproblem_solutions[coarseSolutionLF->vector().size()]->vector();

    if (problem.config().get("msfem.local_corrections_vtk_output", false)) {
      const std::string name = (boost::format("local_%04d_correction_%03d_") % rank % coarse_index).str();
      Dune::Multiscale::OutputParameters outputparam(problem.config().get("global.datadir", "data"));
      outputparam.set_prefix(name);
      local_correction.visualize(outputparam.fullpath(local_correction.name()));
    }
    localproblem_solutions.clear();
  }

  MS_LOG_INFO_0 << "Dirichlet correctors are broken and disabled\n";
  msfem_solution =
      Dune::XT::Common::make_unique<LocalsolutionProxy>(std::move(local_corrections), coarse_space, localgrid_list);
}

void Elliptic_MsFEM_Solver::apply(DMP::ProblemContainer& problem,
                                  const CommonTraits::SpaceType& coarse_space,
                                  std::unique_ptr<LocalsolutionProxy>& solution,
                                  LocalGridList& localgrid_list) const
{
  Dune::XT::Common::ScopedTiming st("msfem.Elliptic_MsFEM_Solver.apply");
  const auto clearGuard = DiscreteFunctionIO::clear_guard();

  CommonTraits::DiscreteFunctionType coarse_msfem_solution(coarse_space, "Coarse Part MsFEM Solution");
  coarse_msfem_solution.vector() *= 0;

  //! Solutions are kept in-memory via DiscreteFunctionIO::MemoryBackend by LocalsolutionManagers
  LocalProblemSolver(problem, coarse_space, localgrid_list).solve_for_all_cells();

  CoarseScaleOperator elliptic_msfem_op(problem, coarse_space, localgrid_list);
  elliptic_msfem_op.apply_inverse(coarse_msfem_solution);

  //! identify fine scale part of MsFEM solution (including the projection!)
  identify_fine_scale_part(problem, localgrid_list, coarse_msfem_solution, coarse_space, solution);
  //  solution->visualize_parts(problem.config());
  solution->add(coarse_msfem_solution);
}

} // namespace Multiscale {
} // namespace Dune {

max_stars_repo_name: wwu-numerik/DUNE-Multiscale

max_issues_repo_name: wwu-numerik/DUNE-Multiscale

max_forks_repo_name: wwu-numerik/DUNE-Multiscale


text:
/*
 * prismatic_model.cpp
 *
 *  Created on: Oct 21, 2009
 *      Author: sturm
 */

#include "articulation_models/models/prismatic_model.h"
#include "articulation_models/utils.h"

using namespace std;

#include "Eigen/Core"
#include <Eigen/SVD>

using namespace Eigen;

using namespace articulation_msgs;

#include <iomanip>
#define VEC(a) setprecision(5)<<fixed<<a.x()<<" "<<a.y()<<" "<<a.z()<<" "<<a.w()<<" l="<<a.length()
#define VEC2(a) "t=["<<VEC(a.getOrigin())<<"] r=[]"<<VEC(a.getRotation())<<"]"
#define PRINT(a) cout << #a <<"=" << VEC(a)<<endl;
#define PRINT2(a) cout << #a <<"=" << VEC2(a)<<endl;

namespace articulation_models {

PrismaticModel::PrismaticModel() {
	prismatic_dir = tf::Vector3(0,0,0);

	complexity = 6+2; // rigid + 2 (orientation, without yaw)
}

// -- params
void PrismaticModel::readParamsFromModel() {
	RigidModel::readParamsFromModel();
	getParam("prismatic_dir",prismatic_dir);
}

void PrismaticModel::writeParamsToModel() {
	RigidModel::writeParamsToModel();
	setParam("prismatic_dir",prismatic_dir,ParamMsg::PARAM);
}

V_Configuration PrismaticModel::predictConfiguration(geometry_msgs::Pose pose) {
	tf::Vector3 diff = (positionToVector(pose.position) - rigid_position);

	V_Configuration q( 1 );
	q(0) = diff.dot(prismatic_dir);

	return q;
}

geometry_msgs::Pose PrismaticModel::predictPose(V_Configuration q) {
//	cout << "predictPose q(0)=" <<q(0) << endl;
//	PRINT(rigid_orientation);
//	PRINT(rigid_position);
//	PRINT(prismatic_dir);
	return transformToPose( tf::Transform( rigid_orientation, rigid_position + q(0) * prismatic_dir ) );
}

M_CartesianJacobian PrismaticModel::predictHessian(V_Configuration q,double delta) {
	M_CartesianJacobian H;
	H.setZero(3*getDOFs(),getDOFs());
	return H;
}

bool PrismaticModel::guessParameters() {
	if(model.track.pose.size() < 2)
		return false;

	size_t i,j;
	do{
		i = rand() % getSamples();
		j = rand() % getSamples();
	} while (i==j);

	tf::Transform pose1 = poseToTransform(model.track.pose[i]);
	tf::Transform pose2 = poseToTransform(model.track.pose[j]);

	rigid_position = pose1.getOrigin();
	rigid_orientation = pose1.getRotation();
	prismatic_dir =  pose2.getOrigin() - pose1.getOrigin();
	prismatic_dir.normalize();

	if(!check_values(rigid_position)) return false;
	if(!check_values(rigid_orientation)) return false;
	if(!check_values(prismatic_dir)) return false;

	return true;
}

void PrismaticModel::updateParameters(std::vector<double> delta) {
	RigidModel::updateParameters(delta);

	tf::Quaternion q;
	q.setRPY(delta[6],delta[7],0.00);
	prismatic_dir = tf::Matrix3x3(q) * prismatic_dir;
}
bool PrismaticModel::normalizeParameters() {
	if(model.track.pose.size()>2) {
		rigid_position = rigid_position + predictConfiguration(model.track.pose.front())[0] * prismatic_dir;
		if(predictConfiguration(model.track.pose.back())[0]<0)
			prismatic_dir *= -1;
	}
	return true;
}

}

ext: cpp

max_stars_repo_name: tum-vision/articulation

max_issues_repo_name: AbdelrahmanElsaid/articulation

max_forks_repo_name: AbdelrahmanElsaid/articulation


text:
#ifndef SHIROSE_PARTICLE_SYSTEM_HPP
#define SHIROSE_PARTICLE_SYSTEM_HPP

#include <Eigen/Core>
#include <Eigen/StdVector>
#include <type_traits>
#include <cassert>

namespace shirose {

struct ParticleSystem {
  /// Use Eigen::aligned allocator for Eigen::Vector2d.
  /// This is because Eigen::Vector2d requires aligned memory allocator.
  /// Please refer to:
  /// https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html
  template <typename T>
  using StdVector = std::vector<T, Eigen::aligned_allocator<T>>;

  StdVector<Eigen::Vector2d> positions;
  StdVector<Eigen::Vector2d> velocities;
  std::vector<double> masses;
  std::vector<double> radii;

   /// @brief Returns the number of particles.
  std::size_t size() const noexcept {
    assert(this->positions.size() == this->velocities.size() &&
           this->positions.size() == this->masses.size() &&
           this->positions.size() == this->radii.size());
    return this->positions.size();
  }
};

}  // namespace shirose

#endif  // SHIROSE_PARTICLE_SYSTEM_HPP

ext: hpp

max_stars_repo_name: shohirose/hard-sphere-simulation

max_issues_repo_name: shohirose/hard-sphere-simulation

max_forks_repo_name: shohirose/hard-sphere-simulation


text:
// Copyright (C) 2017 Michel Morin.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_ITERATOR_ADVANCE_HPP
#define BOOST_ITERATOR_ADVANCE_HPP

#include <boost/config.hpp>
#include <boost/iterator/iterator_categories.hpp>

namespace bx {
namespace iterators {

    namespace detail {
        template <typename InputIterator, typename Distance>
        inline BOOST_CXX14_CONSTEXPR void
        advance_impl(
            InputIterator& it
          , Distance n
          , incrementable_traversal_tag
        )
        {
            while (n > 0) {
                ++it;
                --n;
            }
        }

        template <typename BidirectionalIterator, typename Distance>
        inline BOOST_CXX14_CONSTEXPR void
        advance_impl(
            BidirectionalIterator& it
          , Distance n
          , bidirectional_traversal_tag
        )
        {
            if (n >= 0) {
                while (n > 0) {
                    ++it;
                    --n;
                }
            }
            else {
                while (n < 0) {
                    --it;
                    ++n;
                }
            }
        }

        template <typename RandomAccessIterator, typename Distance>
        inline BOOST_CXX14_CONSTEXPR void
        advance_impl(
            RandomAccessIterator& it
          , Distance n
          , random_access_traversal_tag
        )
        {
            it += n;
        }
    }

    namespace advance_adl_barrier {
        template <typename InputIterator, typename Distance>
        inline BOOST_CXX14_CONSTEXPR void
        advance(InputIterator& it, Distance n)
        {
            detail::advance_impl(
                it, n, typename iterator_traversal<InputIterator>::type()
            );
        }
    }

    using namespace advance_adl_barrier;

} // namespace iterators

using iterators::advance;

} // namespace bx

#endif


text:
// Copyright 2015-2017 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <algorithm>
#include <boost/core/lightweight_test.hpp>
#include <boost/histogram/storage_adaptor.hpp>
#include <boost/histogram/unlimited_storage.hpp>
#include <limits>
#include <memory>
#include <sstream>
#include <vector>
#include "utility_meta.hpp"

namespace bh = boost::histogram;
using unlimited_storage_type = bh::unlimited_storage<>;
template <typename T>
using vector_storage = bh::storage_adaptor<std::vector<T>>;
using mp_int = unlimited_storage_type::mp_int;

std::ostream& operator<<(std::ostream& os, const mp_int& x) {
  os << "mp_int";
  os << x.data;
  return os;
}

template <typename T = std::uint8_t>
unlimited_storage_type prepare(std::size_t n, T x = T()) {
  std::unique_ptr<T[]> v(new T[n]);
  std::fill(v.get(), v.get() + n, static_cast<T>(0));
  v.get()[0] = x;
  return unlimited_storage_type(n, v.get());
}

template <class T>
auto max() {
  return std::numeric_limits<T>::max();
}

template <>
inline auto max<mp_int>() {
  return mp_int(std::numeric_limits<uint64_t>::max());
}

template <class... Ts>
auto make_mp_int(Ts... ts) {
  mp_int r;
  r.data = {static_cast<uint64_t>(ts)...};
  return r;
}

template <typename T>
void copy() {
  const auto b = prepare<T>(1);
  auto a(b);
  BOOST_TEST(a == b);
  ++a[0];
  BOOST_TEST(!(a == b));
  a = b;
  BOOST_TEST(a == b);
  ++a[0];
  BOOST_TEST(!(a == b));
  a = prepare<T>(2);
  BOOST_TEST(!(a == b));
  a = b;
  BOOST_TEST(a == b);
}

template <typename T>
void equal_1() {
  auto a = prepare(1);
  auto b = prepare(1, T(0));
  BOOST_TEST_EQ(a[0], 0.0);
  BOOST_TEST(a == b);
  ++b[0];
  BOOST_TEST(!(a == b));
}

template <typename T, typename U>
void equal_2() {
  auto a = prepare<T>(1);
  vector_storage<U> b;
  b.reset(1);
  BOOST_TEST(a == b);
  ++b[0];
  BOOST_TEST(!(a == b));
}

template <typename T>
void increase_and_grow() {
  auto tmax = std::numeric_limits<T>::max();
  auto s = prepare(2, tmax);
  auto n = s;
  auto n2 = s;

  ++n[0];

  auto x = prepare(2);
  ++x[0];
  n2[0] += x[0];

  auto v = static_cast<double>(tmax);
  ++v;
  BOOST_TEST_EQ(n[0], v);
  BOOST_TEST_EQ(n2[0], v);
  BOOST_TEST_EQ(n[1], 0.0);
  BOOST_TEST_EQ(n2[1], 0.0);
}

template <typename T>
void convert_array_storage() {
  vector_storage<uint8_t> s;
  s.reset(1);
  ++s[0];
  BOOST_TEST_EQ(s[0], 1);

  // test "copy" ctor
  unlimited_storage_type b(s);
  BOOST_TEST_EQ(b[0], 1.0);
  BOOST_TEST(b == s);
  ++b[0];
  BOOST_TEST_NOT(b == s);

  // test assign and equal
  auto a = prepare<T>(1);
  a = s;
  BOOST_TEST_EQ(a[0], 1.0);
  BOOST_TEST(a == s);
  ++a[0];
  BOOST_TEST_NOT(a == s);

  // test radd
  auto c = prepare<T>(1);
  c[0] += s[0];
  BOOST_TEST_EQ(c[0], 1);
  BOOST_TEST(c == s);
  c[0] += s[0];
  BOOST_TEST_EQ(c[0], 2);
  BOOST_TEST_NOT(c == s);

  // test assign from float
  vector_storage<float> t;
  t.reset(1);
  t[0] = 1.5;
  auto d = prepare<T>(1);
  d = t;
  BOOST_TEST(d == t);
  BOOST_TEST(d[0] == 1.5);

  // test "copy" ctor from float
  unlimited_storage_type f(t);
  BOOST_TEST_EQ(f[0], 1.5);
  BOOST_TEST(f == t);

  // test radd from float
  auto g = prepare<T>(1);
  g[0] += t[0];
  BOOST_TEST_EQ(g[0], 1.5);
  BOOST_TEST(g == t);

  vector_storage<int8_t> u;
  u.reset(1);
  u[0] = -10;
  auto h = prepare<T>(1);
  BOOST_TEST_NOT(h == u);
  h = u;
  BOOST_TEST(h == u);
  BOOST_TEST_EQ(h[0], -10);
  h[0] -= u[0];
  BOOST_TEST_EQ(h[0], 0);
}

template <typename LHS, typename RHS>
void add() {
  auto a = prepare<LHS>(1);
  auto b = prepare<RHS>(1);
  b[0] += 2;
  a[0] += b[0];
  BOOST_TEST_EQ(a[0], 2);
  a[0] -= b[0];
  BOOST_TEST_EQ(a[0], 0);
  a[0] -= b[0];
  BOOST_TEST_EQ(a[0], -2);

  auto c = prepare<RHS>(1);
  c[0] = max<RHS>();
  auto d = prepare<LHS>(1);
  d[0] += c[0];
  BOOST_TEST_EQ(d[0], max<RHS>());
  auto e = prepare<LHS>(1);
  e[0] -= c[0];
  BOOST_TEST_EQ(e[0], -double(max<RHS>()));
}

template <typename LHS>
void add_all_rhs() {
  add<LHS, uint8_t>();
  add<LHS, uint16_t>();
  add<LHS, uint32_t>();
  add<LHS, uint64_t>();
  add<LHS, mp_int>();
  add<LHS, double>();
}

int main() {
  // low-level tools
  {
    uint8_t c = 0;
    BOOST_TEST_EQ(bh::detail::safe_increment(c), true);
    BOOST_TEST_EQ(c, 1);
    c = 255;
    BOOST_TEST_EQ(bh::detail::safe_increment(c), false);
    BOOST_TEST_EQ(c, 255);
    c = 0;
    BOOST_TEST_EQ(bh::detail::safe_radd(c, 255u), true);
    BOOST_TEST_EQ(c, 255);
    c = 1;
    BOOST_TEST_EQ(bh::detail::safe_radd(c, 255u), false);
    BOOST_TEST_EQ(c, 1);
    c = 255;
    BOOST_TEST_EQ(bh::detail::safe_radd(c, 1u), false);
    BOOST_TEST_EQ(c, 255);
  }

  // mp_int
  {
    const auto vmax = max<uint64_t>();

    BOOST_TEST_EQ(mp_int(), 0u);
    BOOST_TEST_EQ(mp_int(1u), 1u);
    BOOST_TEST_EQ(mp_int(1u), 1.0);
    BOOST_TEST_EQ(mp_int(1u), mp_int(1u));
    BOOST_TEST_NE(mp_int(1u), 2u);
    BOOST_TEST_NE(mp_int(1u), 2.0);
    BOOST_TEST_NE(mp_int(1u), mp_int(2u));
    BOOST_TEST_LT(mp_int(1u), 2u);
    BOOST_TEST_LT(mp_int(1u), 2.0);
    BOOST_TEST_LT(mp_int(1u), mp_int(2u));
    BOOST_TEST_LE(mp_int(1u), 2u);
    BOOST_TEST_LE(mp_int(1u), 2.0);
    BOOST_TEST_LE(mp_int(1u), mp_int(2u));
    BOOST_TEST_LE(mp_int(1u), 1u);
    BOOST_TEST_GT(mp_int(1u), 0u);
    BOOST_TEST_GT(mp_int(1u), 0.0);
    BOOST_TEST_GT(mp_int(1u), mp_int(0u));
    BOOST_TEST_GE(mp_int(1u), 0u);
    BOOST_TEST_GE(mp_int(1u), 0.0);
    BOOST_TEST_GE(mp_int(1u), 1u);
    BOOST_TEST_GE(mp_int(1u), mp_int(0u));
    BOOST_TEST_NOT(mp_int(1u) < mp_int(1u));
    BOOST_TEST_NOT(mp_int(1u) > mp_int(1u));

    auto a = mp_int();
    ++a;
    BOOST_TEST_EQ(a.data.size(), 1);
    BOOST_TEST_EQ(a.data[0], 1);
    ++a;
    BOOST_TEST_EQ(a.data[0], 2);
    a = vmax;
    BOOST_TEST_EQ(a, vmax);
    BOOST_TEST_EQ(a, static_cast<double>(vmax));
    ++a;
    BOOST_TEST_EQ(a, make_mp_int(0, 1));
    ++a;
    BOOST_TEST_EQ(a, make_mp_int(1, 1));
    a += a;
    BOOST_TEST_EQ(a, make_mp_int(2, 2));
    BOOST_TEST_EQ(a, 2 * static_cast<double>(vmax) + 2);

    // carry once A
    a.data[0] = vmax;
    a.data[1] = 1;
    ++a;
    BOOST_TEST_EQ(a, make_mp_int(0, 2));
    // carry once B
    a.data[0] = vmax;
    a.data[1] = 1;
    a += 1;
    BOOST_TEST_EQ(a, make_mp_int(0, 2));
    // carry once C
    a.data[0] = vmax;
    a.data[1] = 1;
    a += make_mp_int(1, 1);
    BOOST_TEST_EQ(a, make_mp_int(0, 3));

    a.data[0] = vmax - 1;
    a.data[1] = vmax;
    ++a;
    BOOST_TEST_EQ(a, make_mp_int(vmax, vmax));

    // carry two times A
    ++a;
    BOOST_TEST_EQ(a, make_mp_int(0, 0, 1));
    // carry two times B
    a = make_mp_int(vmax, vmax);
    a += 1;
    BOOST_TEST_EQ(a, make_mp_int(0, 0, 1));
    // carry two times C
    a = make_mp_int(vmax, vmax);
    a += mp_int(1);
    BOOST_TEST_EQ(a, make_mp_int(0, 0, 1));

    // carry and enlarge
    a = make_mp_int(vmax, vmax);
    a += a;
    BOOST_TEST_EQ(a, make_mp_int(vmax - 1, vmax, 1));

    // add smaller to larger
    a = make_mp_int(1, 1, 1);
    a += make_mp_int(1, 1);
    BOOST_TEST_EQ(a, make_mp_int(2, 2, 1));

    // add larger to smaller
    a = make_mp_int(1, 1);
    a += make_mp_int(1, 1, 1);
    BOOST_TEST_EQ(a, make_mp_int(2, 2, 1));

    a = mp_int(1);
    auto b = 1.0;
    BOOST_TEST_EQ(a, b);
    for (unsigned i = 0; i < 80; ++i) {
      b += b;
      BOOST_TEST_NE(a, b);
      a += a;
      BOOST_TEST_EQ(a, b);
    }
    BOOST_TEST_GT(a.data.size(), 1u);
  }

  // empty state
  {
    unlimited_storage_type a;
    BOOST_TEST_EQ(a.size(), 0);
  }

  // copy
  {
    copy<uint8_t>();
    copy<uint16_t>();
    copy<uint32_t>();
    copy<uint64_t>();
    copy<mp_int>();
    copy<double>();
  }

  // equal_operator
  {
    equal_1<uint8_t>();
    equal_1<uint16_t>();
    equal_1<uint32_t>();
    equal_1<uint64_t>();
    equal_1<mp_int>();
    equal_1<double>();

    equal_2<uint8_t, unsigned>();
    equal_2<uint16_t, unsigned>();
    equal_2<uint32_t, unsigned>();
    equal_2<uint64_t, unsigned>();
    equal_2<mp_int, unsigned>();
    equal_2<double, unsigned>();

    equal_2<mp_int, double>();

    auto a = prepare<double>(1);
    auto b = prepare<mp_int>(1);
    BOOST_TEST(a == b);
    ++a[0];
    BOOST_TEST_NOT(a == b);
  }

  // increase_and_grow
  {
    increase_and_grow<uint8_t>();
    increase_and_grow<uint16_t>();
    increase_and_grow<uint32_t>();
    increase_and_grow<uint64_t>();

    // only increase for mp_int
    auto a = prepare<mp_int>(2, static_cast<mp_int>(1));
    BOOST_TEST_EQ(a[0], 1);
    BOOST_TEST_EQ(a[1], 0);
    ++a[0];
    BOOST_TEST_EQ(a[0], 2);
    BOOST_TEST_EQ(a[1], 0);
  }

  // add
  {
    add_all_rhs<uint8_t>();
    add_all_rhs<uint16_t>();
    add_all_rhs<uint32_t>();
    add_all_rhs<uint64_t>();
    add_all_rhs<mp_int>();
    add_all_rhs<double>();
  }

  // add_and_grow
  {
    auto a = prepare(1);
    a[0] += a[0];
    BOOST_TEST_EQ(a[0], 0);
    ++a[0];
    double x = 1;
    auto b = prepare(1);
    ++b[0];
    BOOST_TEST_EQ(b[0], x);
    for (unsigned i = 0; i < 80; ++i) {
      x += x;
      a[0] += a[0];
      b[0] += b[0];
      BOOST_TEST_EQ(a[0], x);
      BOOST_TEST_EQ(b[0], x);
      auto c = prepare(1);
      c[0] += a[0];
      BOOST_TEST_EQ(c[0], x);
      c[0] += 0;
      BOOST_TEST_EQ(c[0], x);
      auto d = prepare(1);
      d[0] += x;
      BOOST_TEST_EQ(d[0], x);
    }
  }

  // multiply
  {
    auto a = prepare(2);
    ++a[0];
    a *= 3;
    BOOST_TEST_EQ(a[0], 3);
    BOOST_TEST_EQ(a[1], 0);
    a[1] += 2;
    a *= 3;
    BOOST_TEST_EQ(a[0], 9);
    BOOST_TEST_EQ(a[1], 6);
  }

  // convert_array_storage
  {
    convert_array_storage<uint8_t>();
    convert_array_storage<uint16_t>();
    convert_array_storage<uint32_t>();
    convert_array_storage<uint64_t>();
    convert_array_storage<mp_int>();
    convert_array_storage<double>();
  }

  // reference
  {
    auto a = prepare(1);
    auto b = prepare<uint32_t>(1);
    BOOST_TEST_EQ(a[0], b[0]);
    BOOST_TEST_GE(a[0], b[0]);
    BOOST_TEST_LE(a[0], b[0]);
    a[0] = 1;
    BOOST_TEST_NE(a[0], b[0]);
    BOOST_TEST_LT(b[0], a[0]);
    BOOST_TEST_GT(a[0], b[0]);
    BOOST_TEST_EQ(a[0], 1);
    BOOST_TEST_GE(a[0], 1);
    BOOST_TEST_LE(a[0], 1);
    ++b[0];
    BOOST_TEST_EQ(a[0], b[0]);
    b[0] += 2;
    a[0] = b[0];
    BOOST_TEST_EQ(a[0], 3);
    a[0] -= 10;
    BOOST_TEST_EQ(a[0], -7);
  }

  // iterators
  {
    auto a = prepare(2);
    for (auto&& x : a) BOOST_TEST_EQ(x, 0);

    std::vector<double> b(2, 1);
    std::copy(b.begin(), b.end(), a.begin());

    const auto aconst = a;
    BOOST_TEST(std::equal(aconst.begin(), aconst.end(), b.begin(), b.end()));

    unlimited_storage_type::iterator it1 = a.begin();
    *it1 = 3;
    unlimited_storage_type::const_iterator it2 = a.begin();
    BOOST_TEST_EQ(*it2, 3);
    unlimited_storage_type::const_iterator it3 = aconst.begin();
    BOOST_TEST_EQ(*it3, 1);
    // unlimited_storage_type::iterator it3 = aconst.begin();
  }

  return boost::report_errors();
}

max_stars_repo_name: henryiii/histogram

max_issues_repo_name: henryiii/histogram

max_forks_repo_name: henryiii/histogram


text:
/*
 * fasta.hh
 *
 * License: Artistic License, see file LICENSE.TXT or
 *          https://opensource.org/licenses/artistic-license-1.0
 */

#ifndef _FASTA_HH
#define _FASTA_HH

#include <iostream>
#include <fstream>

#ifdef ZIPINPUT
#include <boost/iostreams/filtering_stream.hpp>
using boost::iostreams::filtering_istream;
void readOneFastaSeq(filtering_istream &ifstrm, char* &sequence, char* &name, int &length);
#endif

void readOneFastaSeq(std::stringstream &ifstrm, char* &sequence, char* &name, int &length);
void readOneFastaSeq(std::ifstream &ifstrm, char* &sequence, char* &name, int &length);
void readFastaHeader(std::ifstream &ifstrm, char* &name);
bool isFasta(std::ifstream &ifstrm);

#endif   //  _FASTA_HH

ext: hh

max_stars_repo_name: sestaton/Augustus

max_issues_repo_name: sestaton/Augustus

max_forks_repo_name: sestaton/Augustus


text:
#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>

//____________________________________________________________________________//

struct my_exception {
    explicit my_exception( int ec = 0 ) : m_error_code( ec ) {}

    int m_error_code;
};

bool is_critical( my_exception const& ex ) { return ex.m_error_code < 0; }

BOOST_AUTO_TEST_CASE( test )
{
    BOOST_CHECK_EXCEPTION( throw my_exception( 1 ), my_exception, is_critical );
}

//____________________________________________________________________________//

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
//
// Created by AIYOJ on 2019-03-04.
//

#include "gtest/gtest.h"
#include <iostream>
#include "calibration/prior_correction.h"
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

namespace algocomp_test {

    class TestPriorCorrection : public ::testing::Test {
    protected:
        std::unique_ptr<algocomp::PriorCorrection> calibration;

        virtual void SetUp() {
            calibration.reset(new algocomp::PriorCorrection());
        }

        virtual void TearDown() {

        }
    };

    TEST_F(TestPriorCorrection, prior_correction) {
        calibration->update(1);
        std::vector<float> scores;
        scores.push_back(0.8);
        scores.push_back(0.9);
        scores.push_back(0.4);
        std::vector<float> calibrated_scores = calibration->calibrate(scores);
        for (int i = 0; i < scores.size(); ++i) {
            EXPECT_EQ(calibrated_scores[i], scores[i]);
        }

        calibration->update(0.5);
        scores.clear();
        scores.push_back(0.5);
        scores.push_back(0.7);
        scores.push_back(0.8);
        calibrated_scores = calibration->calibrate(scores);
        for (int i = 0; i < scores.size(); ++i) {
            float score = scores[i] / (scores[i] + (1 - scores[i]) * 2);
            EXPECT_EQ(calibrated_scores[i], score);
        }
    }

    TEST_F(TestPriorCorrection, load_prior_correction){
        calibration = algocomp::PriorCorrection::load("test/test-data/1-calibrations/1-prior-correction.txt");

        std::vector<float> scores;
        scores.push_back(0.8);
        scores.push_back(0.9);
        scores.push_back(0.4);
        std::vector<float> calibrated_scores = calibration->calibrate(scores);
        for (int i = 0; i < scores.size(); ++i) {
            float score = scores[i] / (scores[i] + (1 - scores[i]) * 2);
            EXPECT_EQ(calibrated_scores[i], score);
        }
    }
}


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_DISPATCH_DSL_CALL_HPP_INCLUDED
#define BOOST_DISPATCH_DSL_CALL_HPP_INCLUDED

////////////////////////////////////////////////////////////////////////////////
// This file generate basic EDSL expression wrapper over any nt2 function
////////////////////////////////////////////////////////////////////////////////
#include <boost/proto/make_expr.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/not.hpp>
#include <boost/dispatch/meta/any.hpp>
#include <boost/dispatch/meta/as_ref.hpp>
#include <boost/dispatch/dsl/category.hpp>
#include <boost/dispatch/functor/functor.hpp>
#include <boost/dispatch/functor/meta/call.hpp>
#include <boost/dispatch/functor/meta/hierarchy.hpp>
#include <boost/dispatch/functor/preprocessor/call.hpp>

#if defined(BOOST_DISPATCH_DONT_USE_PREPROCESSED_FILES)
#include <boost/dispatch/details/parameters.hpp>
#include <boost/preprocessor/selection/min.hpp>
#include <boost/dispatch/functor/preprocessor/dispatch.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#endif

namespace boost { namespace dispatch { namespace tag
{
  /// INTERNAL ONLY
  struct ast_ {};
}
namespace meta
{
  template<class T>
  struct proto_tag
  {
    typedef T type;
  };

  template<class T>
  struct is_formal : is_formal<typename T::parent>
  {
  };

  template<>
  struct is_formal<tag::formal_>
   : mpl::true_
  {
  };

  template<class T>
  struct is_formal<unknown_<T> >
   : mpl::false_
  {
  };
} } }

////////////////////////////////////////////////////////////////////////////////
// Defines the catch-all call for proto expression
////////////////////////////////////////////////////////////////////////////////
#if !defined(BOOST_DISPATCH_DONT_USE_PREPROCESSED_FILES)
#include <boost/dispatch/dsl/preprocessed/call.hpp>
#else
#if defined(__WAVE__) && defined(BOOST_DISPATCH_CREATE_PREPROCESSED_FILES) && __INCLUDE_LEVEL__ == 0
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/call.hpp")
#undef BOOST_FORCEINLINE
#endif

#define M1(z,n,t) boost::dispatch::meta::as_child(BOOST_PP_CAT(a,n))
#define M2(z,n,t) (BOOST_PP_CAT(A,n))
#define M3(z,n,t) (unspecified_<BOOST_PP_CAT(A,n)>)
#define M4(z,n,t) boost::reference_wrapper<A##n>(a##n)

#define M5(z,n,t)                                                               \
BOOST_DISPATCH_REGISTER_TO_IF ( (boost)(dispatch)(meta), unspecified_<Func>     \
                              , tag::formal_                                    \
                              , (Func)BOOST_PP_REPEAT(n,M2,~)                   \
                              , (mpl::and_< mpl::not_< is_formal<Func> >        \
                                          , any < boost::proto::                \
                                                  is_expr<boost::mpl::_>        \
                                                , BOOST_PP_ENUM_PARAMS(n,A)     \
                                                >                               \
                                          >                                     \
                          )                                                     \
                      , BOOST_PP_REPEAT(n,M3,~)                                 \
                      , (implement<Func(tag::ast_), tag::formal_>)              \
                      )                                                         \
/**/

#define M0(z,n,t)                                                              \
template<class This,BOOST_PP_ENUM_PARAMS(n,class A)>                           \
struct result<This(BOOST_PP_ENUM_PARAMS(n,A))>                                 \
{                                                                              \
  typedef typename boost::proto::result_of::                                   \
  make_expr < typename meta::proto_tag<Func>::type                             \
            , BOOST_PP_ENUM_BINARY_PARAMS(n, typename meta::                   \
                                   as_ref<A, >::type BOOST_PP_INTERCEPT)       \
            >::type type;                                                      \
};                                                                             \
template<BOOST_PP_ENUM_PARAMS(n,class A)>                                      \
BOOST_FORCEINLINE                                                              \
typename result<implement                                                      \
                (BOOST_PP_ENUM_BINARY_PARAMS(n, A, & a))                       \
               >::type                                                         \
operator()(BOOST_PP_ENUM_BINARY_PARAMS(n, A, & a)) const                       \
{                                                                              \
  return boost::proto::                                                        \
  make_expr< typename meta::proto_tag<Func>::type >                            \
           ( BOOST_PP_ENUM(n, M4, ~) );                                        \
}                                                                              \
/**/

namespace boost { namespace dispatch { namespace meta
{
  BOOST_PP_REPEAT_FROM_TO ( 1
                          , BOOST_PP_INC(BOOST_PP_MIN ( BOOST_DISPATCH_MAX_ARITY
                                                      , BOOST_PROTO_MAX_ARITY
                                                      )
                                        )
                          ,M5,~
                          )

  template<class Func,class Dummy>
  struct implement<Func(tag::ast_),tag::formal_,Dummy>
  {
    template<class Sig> struct result;
    BOOST_PP_REPEAT_FROM_TO ( 1
                            , BOOST_PP_INC(BOOST_PP_MIN ( BOOST_DISPATCH_MAX_ARITY
                                                        , BOOST_PROTO_MAX_ARITY
                                                        )
                                          )
                            ,M0,~
                            )
  };
} } }

#undef M0
#undef M1
#undef M2
#undef M3
#undef M4
#undef M5

#if defined(__WAVE__) && defined(BOOST_DISPATCH_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#endif

#endif


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <boost/program_options.hpp>

#include "bc/binary.h"

#include "isdf/isdf.h"
#include "isdf/reader.h"

namespace po = boost::program_options;

using namespace flint;

namespace {

class NumberOfRowsHandler {
public:
	NumberOfRowsHandler(const NumberOfRowsHandler &) = delete;
	NumberOfRowsHandler &operator=(const NumberOfRowsHandler &) = delete;

	NumberOfRowsHandler(std::uint32_t num_rows, std::ostream *os) : n_(), num_rows_(num_rows), os_(os) {}

	int GetStep(std::uint32_t buf_size, const char *buf) {
		os_->write(buf, buf_size);
		if (!os_->good()) {
			std::cerr << "could not write step" << std::endl;
			return -1;
		}
		if (++n_ == num_rows_) {
			os_->flush();
			return 0;
		}
		return 1;
	}

private:
	std::uint32_t n_;
	std::uint32_t num_rows_;
	std::ostream *os_;
};

class EndOfTimeHandler {
public:
	EndOfTimeHandler(const EndOfTimeHandler &) = delete;
	EndOfTimeHandler &operator=(const EndOfTimeHandler &) = delete;

	EndOfTimeHandler(double eot, std::ostream *os) : eot_(eot), os_(os) {}

	int GetStep(std::uint32_t buf_size, const char *buf) {
		double t = 0;
		memcpy(&t, buf, sizeof(t));
		if (t < eot_) {
			os_->write(buf, buf_size);
			if (!os_->good()) {
				std::cerr << "could not write step" << std::endl;
				return -1;
			}
		} else {
			os_->flush();
			return 0;
		}
		return 1;
	}

private:
	double eot_;
	std::ostream *os_;
};

class Dam {
public:
	Dam(const Dam &) = delete;
	Dam &operator=(const Dam &) = delete;

	explicit Dam(std::uint32_t num_rows) : num_rows_(num_rows), eot_(), reader_() {}
	explicit Dam(double eot) : num_rows_(), eot_(eot), reader_() {}

	bool Pass(std::istream *is, std::ostream *os) {
		if (!reader_.ReadHeader(is)) return false;
		char harr[sizeof(isdf::ISDFHeader)];
		std::memcpy(harr, &reader_.header(), sizeof(isdf::ISDFHeader));
		os->write(harr, sizeof(isdf::ISDFHeader));
		if (!reader_.ReadComment(is)) return false;
		os->write(reader_.comment(), reader_.num_bytes_comment());
		if (!reader_.ReadDescriptions(is)) return false;
		os->write(reader_.descriptions(), reader_.num_bytes_descs());
		if (!reader_.ReadUnits(is)) return false;
		os->write(reader_.units(), reader_.num_bytes_units());
		if (num_rows_ > 0) {
			NumberOfRowsHandler handler(num_rows_, os);
			return reader_.ReadSteps(handler, is);
		} else {
			EndOfTimeHandler handler(eot_, os);
			return reader_.ReadSteps(handler, is);
		}
	}

private:
	std::uint32_t num_rows_;
	double eot_;
	isdf::Reader reader_;
};

} // namespace

int main(int argc, char *argv[])
{
	RequestBinaryStdio();

	po::options_description opts("options");
	po::positional_options_description popts;
	po::variables_map vm;
	std::uint32_t num_rows = 0;
	double eot = 0;
	std::string input_file, output_file;
	int print_help = 0;

	opts.add_options()
		("rows,n", po::value<std::uint32_t>(&num_rows), "Specify the number of rows to be extracted")
		("eot,t", po::value<double>(&eot), "Specify the end of time")
		("help,h", "Show this message")
		("output,o", po::value<std::string>(&output_file), "Output file name")
		("input", po::value<std::string>(&input_file), "Input file name");
	popts.add("input", 1);

	try {
		po::store(po::command_line_parser(argc, argv).options(opts).positional(popts).run(), vm);
		po::notify(vm);
		if (vm.count("help")) print_help = 1;
	} catch (const po::error &) {
		print_help = 2;
	}
	if (print_help != 0) {
		std::cerr << "usage: isdhead [OPTIONS] [PATH]" << std::endl;
		std::cerr << opts << std::endl;
		return (print_help == 1) ? EXIT_SUCCESS : EXIT_FAILURE;
	}

	std::unique_ptr<Dam> dam;
	if (vm.count("rows") > 0) {
		if (vm.count("eot") > 0) {
			std::cerr << "please specify one and only one of the following options: --rows(-n) / --eot(-t)" << std::endl;
			return EXIT_FAILURE;
		}
		dam.reset(new Dam(num_rows));
	} else if (vm.count("eot") > 0) {
		dam.reset(new Dam(eot));
	} else {
		std::cerr << "please specify one and only one of the following options: --rows(-n) / --eot(-t)" << std::endl;
		return EXIT_FAILURE;
	}
	if (vm.count("input")) {
		std::ifstream ifs(input_file.c_str(), std::ios::in|std::ios::binary);
		if (!ifs.is_open()) {
			std::cerr << "could not open file: " << input_file << std::endl;
			return EXIT_FAILURE;
		}
		if (vm.count("output")) {
			std::ofstream ofs(output_file.c_str(), std::ios::out|std::ios::binary);
			if (!ofs.is_open()) {
				std::cerr << "could not open output file: " << output_file << std::endl;
				return EXIT_FAILURE;
			}
			if (!dam->Pass(&ifs, &ofs)) return EXIT_FAILURE;
			ofs.close();
		} else {
			if (!dam->Pass(&ifs, &std::cout)) return EXIT_FAILURE;
		}
		ifs.close();
	} else if (vm.count("output")) {
		std::ofstream ofs(output_file.c_str(), std::ios::out|std::ios::binary);
		if (!ofs.is_open()) {
			std::cerr << "could not open output file: " << output_file << std::endl;
			return EXIT_FAILURE;
		}
		if (!dam->Pass(&std::cin, &ofs)) return EXIT_FAILURE;
		ofs.close();
	} else {
		if (!dam->Pass(&std::cin, &std::cout)) return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

max_stars_repo_name: Abhisheknishant/Flint

max_issues_repo_name: Abhisheknishant/Flint

max_forks_repo_name: Abhisheknishant/Flint


text:
/* Copyright (c) 2017, CNRS-LAAS
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

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

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

#include "../neptus/imc_message_factories.hpp"

enum { max_length = 1024 };

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 3)
    {
      std::cerr << "Usage: blocking_udp_echo_client <host> <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    udp::socket s(io_service, udp::endpoint(udp::v4(), 0));

    udp::resolver resolver(io_service);
    udp::resolver::query query(udp::v4(), argv[1], argv[2]);
    udp::resolver::iterator iterator = resolver.resolve(query);

    using namespace std; // For strlen.
//    std::cout << "Enter message: ";
//    char request[max_length];
//    std::cin.getline(request, max_length);
//    size_t request_length = strlen(request);
    auto pk = IMC::Packet();
    IMC::ByteBuffer bb = IMC::ByteBuffer();
    bb.setSize(max_length);
    auto hbb = SAOP::neptus::PlanDBFactory::make_message();
    hbb.setSource(3088);
    hbb.setSourceEntity(25);
    hbb.setDestination(24290);
    hbb.setDestinationEntity(8);
    hbb.setTimeStamp();
    pk.serialize(&hbb, bb);

    std::cout << "Sent: " << hbb.toString() << std::endl;

    s.send_to(boost::asio::buffer(bb.getBuffer(), bb.getSize()), *iterator);
//
//    char reply[max_length];
//    udp::endpoint sender_endpoint;
//    size_t reply_length = s.receive_from(
//        boost::asio::buffer(reply, max_length), sender_endpoint);
//    std::cout << "Reply is: ";
//    std::cout.write(reply, reply_length);
//    std::cout << "\n";
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

max_stars_repo_name: arthur-bit-monnot/fire-rs-saop

max_issues_repo_name: fire-rs-laas/fire-rs-saop

max_forks_repo_name: fire-rs-laas/fire-rs-saop


text:
/***************************************************************************
 *   Software License Agreement (BSD License)                              *
 *   Copyright (C) 2012 by Markus Bader <markus.bader@tuwien.ac.at>        *
 *                                                                         *
 *   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.                                           *
 ***************************************************************************/

#include <iostream>
#include <stdlib.h>
#include <signal.h>

#include <opencv2/highgui/highgui.hpp>
#include <shmfw/allocator.h>
#include <shmfw/variable.h>
#include <shmfw/objects/grid_map.h>
#include <shmfw/objects/opencv.h>
#include <boost/program_options.hpp>

struct Prarmeters {
    int reload;
    std::string  cvtype;
    double grid;
    bool on_change;
    int border;
    std::string shm_memory_name;
    unsigned int shm_memory_size;
    std::string variable_name;
};

Prarmeters readArgs ( int argc, char **argv ) {
    namespace po = boost::program_options;

    Prarmeters params;
    po::options_description desc ( "Allowed Parameters" );
    desc.add_options()
    ( "help", "get this help message" )
    ( "on_change,c", "updates only on change" )
    ( "border", po::value< int > ( &params.border )->default_value ( 20 ), "view border" )
    ( "reload,r", po::value< int > ( &params.reload )->default_value ( 100 ), "reload time in ms, 0 means reload on signal, -1 means relaod owns to load image into shm" )
    ( "cvtype,t", po::value<std::string> ( &params.cvtype ), "opencv type: CV_8UC3, CV_8U, ..." )
    ( "grid,g", po::value< double > ( &params.grid )->default_value ( 1.0 ), "grid size, -1 means no grid" )
    ( "shm_memory_name,m", po::value<std::string> ( &params.shm_memory_name )->default_value ( ShmFw::DEFAULT_SEGMENT_NAME() ), "shared memory segment name" )
    ( "shm_memory_size,s", po::value<unsigned int> ( &params.shm_memory_size )->default_value ( ShmFw::DEFAULT_SEGMENT_SIZE() ), "shared memory segment size" )
    ( "variable_name,v", po::value<std::string> ( &params.variable_name )->default_value ( "image_grid" ), "shared variable name" );

    po::variables_map vm;
    try {
        po::store ( po::parse_command_line ( argc, argv, desc ), vm );
    } catch ( const std::exception &ex ) {
        std::cout << desc << std::endl;;
        exit ( 1 );
    }
    po::notify ( vm );

    if ( vm.count ( "help" ) )  {
        std::cout << desc << std::endl;
        exit ( 1 );
    }
    params.on_change = (vm.count ( "on_change" ) > 0);

    return params;
}

bool loop_program = true;

void terminate ( int param ) {
    std::cout << "Program was trying to abort or terminate." << std::endl;
    loop_program = false;
}

void draw_grid ( const Prarmeters &params,  const ShmFw::Var<ShmFw::GridMapInterprocess<uchar> > &grid,  cv::Mat &des ) {
    cv::Scalar colorOrigin ( 0,0,0 );
    cv::Scalar colorGrid ( 200,200,200 );
    cv::Scalar colorText ( 0,0,0 );
    double textHeight = 0.3;
    int xc = grid->x2idx ( 0 ) + params.border;
    int yc = grid->y2idx ( 0 ) + params.border;
    char text[0xFF];
    {
        /// vertical
        double x_max = round ( grid->getXMax() / params.grid );
        double x_min = round ( grid->getXMin() / params.grid );
        for ( double x0 = x_min; x0 <= x_max; x0+= params.grid ) {
            int x = grid->x2idx ( x0 )  + params.border;
            cv::line ( des, cv::Point ( x, 0 ), cv::Point ( x, des.rows ), colorGrid, 1 );
            if ( ( x0 != x_min ) && ( x0 != x_max ) ) {
		sprintf(text, "%4.2f", x0);
                //cv::putText ( des, boost::lexical_cast<std::string> ( x0 ), cv::Point (   x, yc+2 ), cv::FONT_HERSHEY_SIMPLEX, textHeight, colorText, 1, CV_AA );
                cv::putText ( des, text, cv::Point ( x+2, des.rows-10 ), cv::FONT_HERSHEY_SIMPLEX, textHeight, colorText, 1, CV_AA );
            }
        }
        cv::putText ( des, "Y", cv::Point ( 10, 10 ), cv::FONT_HERSHEY_SIMPLEX, textHeight, colorText, 1, CV_AA );
    }
    {
        /// horizontal
        double y_max = round ( grid->getYMax() / params.grid );
        double y_min = round ( grid->getYMin() / params.grid );
        for ( double y0 = y_min; y0 <= y_max; y0+= params.grid ) {
            int y = grid->y2idx ( y0 ) + params.border;
            cv::line ( des, cv::Point ( 0, y ), cv::Point ( des.cols, y ), colorGrid, 1 );
            if ( ( y0 != y_min ) && ( y0 != y_max ) ) {
		sprintf(text, "%4.2f", y0);
                //cv::putText ( des, boost::lexical_cast<std::string> ( y0 ), cv::Point ( xc+2, y+2 ), cv::FONT_HERSHEY_SIMPLEX, textHeight, colorText, 1, CV_AA );
                cv::putText ( des, text, cv::Point ( 2, y-6 ), cv::FONT_HERSHEY_SIMPLEX, textHeight, colorText, 1, CV_AA );
            }
        }
        cv::putText ( des, "X", cv::Point ( des.cols-10, des.rows-10 ), cv::FONT_HERSHEY_SIMPLEX, textHeight, colorText, 1, CV_AA );

    }
    {
        /// origin
        cv::line ( des, cv::Point ( xc, 0 ), cv::Point ( xc, des.rows ), colorOrigin, 2 );
        cv::line ( des, cv::Point ( 0, yc ), cv::Point ( des.cols, yc ), colorOrigin, 2 );
    }

}
void view_image ( const Prarmeters &params, ShmFw::HandlerPtr &shmHdl ) {
    ShmFw::Var<ShmFw::GridMapInterprocess<uchar> > grid ( params.variable_name, shmHdl );
    std::cout << *grid << std::endl;
    int cvtype = -1;
    if ( params.cvtype.empty() ) {
        if ( grid->getDepth() == 1 ) cvtype = CV_8U;
        else if ( grid->getDepth() == 2 ) cvtype = CV_16U;
        else if ( grid->getDepth() == 3 ) cvtype = CV_8UC3;
    } else {
        cvtype = cv::solveCvType ( params.cvtype );
    }
    if ( cvtype == -1 ) {
        std::cerr << "could not detect image cvtype!" << std::endl;
    }

    int key;
    cv::Mat img;
    cv::Mat des;
    do {
        cv::Mat src = grid->cvMat ( cvtype );
        img.create ( src.rows+params.border*2, src.cols + params.border*2, cvtype );
        img.setTo ( 0xFF );
        des = cv::Mat ( img, cv::Rect ( params.border,params.border, src.cols, src.rows ) );
        src.copyTo ( des );
        if ( params.grid > 0 ) {
            draw_grid ( params,  grid, img );
        }
        cv::imshow ( params.variable_name.c_str(), img );
	if(params.on_change){
	  key = cv::waitKey ( params.reload );
	  while(grid.timed_wait(10000) == false){
	    boost::posix_time::time_duration d = ShmFw::now() - grid.timestampShm();
	    std::cout << "Last change " << d.total_milliseconds() << " ms ago!" << std::endl;
	  }
	} else {
	  key = cv::waitKey ( params.reload );
	}
    } while ( loop_program && ( key < 0 ) );
    cv::destroyWindow ( params.variable_name.c_str() );
}
int main ( int argc, char **argv ) {

    signal ( SIGABRT,	terminate );
    signal ( SIGTERM,	terminate );
    Prarmeters params = readArgs ( argc, argv );
    ShmFw::HandlerPtr shmHdl = ShmFw::Handler::create ( params.shm_memory_name, params.shm_memory_size );
    ShmFw::Header *header = ( ShmFw::Header * ) shmHdl->findName ( params.variable_name );
    if ( header ) {
        view_image ( params, shmHdl );
    }

    exit ( 0 );
}

max_stars_repo_name: ShmFw/shmfw

max_issues_repo_name: ShmFw/shmfw

max_forks_repo_name: ShmFw/shmfw


text:
#pragma once

#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "../include/ros/omni_ros_interface.hpp"

typedef boost::shared_ptr<OmniRosInterface> OmniBasePtr;
typedef boost::unique_lock<boost::shared_mutex>            LockUnique;          ///< The unique lock, used to protect data while writing.
typedef boost::shared_lock<boost::shared_mutex>            LockShared;          ///< The shared lock, used to protect data while reading.
typedef boost::upgrade_lock<boost::shared_mutex>           LockUpgrade;         ///< The upgradeable lock, used to protect data while reading.
typedef boost::upgrade_to_unique_lock<boost::shared_mutex> LockUpgradeToUnique; ///< The upgraded lock, used to protect data while writing.
typedef boost::posix_time::microsec_clock Clock;
typedef boost::posix_time::ptime Time;
typedef boost::posix_time::time_duration TimeDuration;


text:
// QObject handling all node interaction
// Author: Max Schwarz <max.schwarz@uni-bonn.de>

#include "node_backend.h"

#include <QtCore/QTimer>

#include <ros/master.h>
#include <ros/service.h>
#include <ros/this_node.h>

#include <roscpp/GetLoggers.h>
#include <roscpp/SetLoggerLevel.h>

#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>

namespace rqt_log_viewer
{

void Node::updateFlags()
{
	debug = TRISTATE_INVALID;
	shown = TRISTATE_INVALID;

	Q_FOREACH(const Logger& logger, loggers)
	{
		if(debug == TRISTATE_INVALID)
			debug = logger.debug ? TRISTATE_TRUE : TRISTATE_FALSE;
		else if(logger.debug && debug == TRISTATE_FALSE)
			debug = TRISTATE_TRISTATE;
		else if(!logger.debug && debug == TRISTATE_TRUE)
			debug = TRISTATE_TRISTATE;
	}
}

NodeBackend::NodeBackend(QObject* parent)
 : QObject(parent)
{
	qRegisterMetaType<rqt_log_viewer::NodeList>();

	// Discover nodes periodically
	QTimer* timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), SLOT(discoverNodes()));
	timer->start(2000);
}

NodeBackend::~NodeBackend()
{
}

void NodeBackend::discoverNodes()
{
	ros::V_string nodes;
	ros::master::getNodes(nodes);

	QList<Node> results;

// 	BOOST_FOREACH(const std::string& str, nodes)
// 	{
// 		// HACK: Ignore some known uninteresting nodes
// 		if(str == "/rosout" || str.substr(0, 5) == "/rqt_" || str == ros::this_node::getName())
// 			continue;
//
// 		Node node;
// 		node.name = QString::fromStdString(str);
// 		node.shown = true;
// 		node.debug = TRISTATE_INVALID;
// 		node.logLevel = ros::console::levels::Info;
//
// 		roscpp::GetLoggersRequest req;
// 		roscpp::GetLoggersResponse resp;
// 		if(!ros::service::call(str + "/get_loggers", req, resp))
// 		{
// 			// silently ignore errors, they are mostly caused by startup delays.
// 			continue;
// 		}
//
// 		BOOST_FOREACH(const roscpp::Logger& msg_logger, resp.loggers)
// 		{
// 			// HACK: Ignore some common system loggers
// 			if(msg_logger.name.substr(0, 5) == "rospy"
// 				|| msg_logger.name.substr(0, 10) == "ros.roscpp"
// 				|| msg_logger.name.substr(0, 8) == "rosgraph"
// 				|| msg_logger.name == "xmlrpc"
// 				|| msg_logger.name == "ros")
// 			{
// 				continue;
// 			}
//
// 			Logger logger;
// 			logger.name = QString::fromStdString(msg_logger.name);
// 			logger.debug = (boost::to_upper_copy(msg_logger.level) == "DEBUG");
//
// 			QList<Logger>::iterator it;
// 			it = qLowerBound(node.loggers.begin(), node.loggers.end(), logger);
// 			node.loggers.insert(it, logger);
// 		}
//
// 		node.updateFlags();
//
// 		QList<Node>::iterator it = qLowerBound(results.begin(), results.end(), node);
// 		results.insert(it, node);
// 	}

	nodeListChanged(results);
}

void NodeBackend::changeLogLevel(const QString& nodeName, const QString& logger, const QString& level)
{
	roscpp::SetLoggerLevelRequest req;
	roscpp::SetLoggerLevelResponse resp;

	req.logger = logger.toStdString();
	req.level = level.toStdString();

	if(!ros::service::call(nodeName.toStdString() + "/set_logger_level", req, resp))
	{
		ROS_WARN("Could not set logger '%s' level of node '%s' to '%s'",
			req.logger.c_str(), qPrintable(logger), req.level.c_str()
		);
		return;
	}

	logLevelChanged(nodeName, logger, level);
}

}


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE HSMM
#include <armadillo>
#include <boost/test/unit_test.hpp>
#include <HSMM.hpp>
#include <iostream>
#include <memory>
#include <Multivariate_Gaussian_emission.hpp>
#include <robotics/utils/random.hpp>

#define EPSILON 1e-6

using namespace arma;
using namespace hsmm;
using namespace robotics;
using namespace std;

mat transition = {{0.0, 0.1, 0.4, 0.5},
                  {0.3, 0.0, 0.6, 0.1},
                  {0.2, 0.2, 0.0, 0.6},
                  {0.4, 0.4, 0.2, 0.0}};

mat duration = {{0.0, 0.1, 0.4, 0.5},
                {0.3, 0.0, 0.6, 0.1},
                {0.2, 0.2, 0.0, 0.6},
                {0.4, 0.4, 0.2, 0.0}};

int min_duration = 4;

vec pi = {0.25, 0.25, 0.25, 0.25};

int ndurations = duration.n_cols;

int nstates = duration.n_rows;

int ndimension = 7;

ivec expand_vit_mat(const imat& vit) {
    vector<int> ret;
    for(int i = 0; i < vit.n_rows; i++)
        for(int j = 0; j < vit(i, 1); j++)
            ret.push_back(vit(i, 0));
    return conv_to<ivec>::from(ret);
}

BOOST_AUTO_TEST_CASE(OnlineHSMMRunlengthBased_Multivariate_Gaussian_Emission) {
    vector<random::NormalDist> states;
    for(int i = 0; i < nstates; i++) {
        vec mean = ones<vec>(ndimension) * i * 10;
        mat cov = eye(ndimension, ndimension);
        random::NormalDist a(mean, cov);
        states.push_back(a);
    }
    shared_ptr<MultivariateGaussianEmission> emission(
            new MultivariateGaussianEmission(states));
    OnlineHSMMRunlengthBased model(emission, transition, pi, duration,
            min_duration);
    ivec hs, hd;
    field<mat> test_features = model.sampleSegments(50, hs, hd);
    imat vit_mat = join_horiz(hs, hd);
    mat runlength_marginals(min_duration + ndurations - 1,
            test_features.n_elem);
    mat state_marginals(nstates, test_features.n_elem);
    mat state_marginals_2(nstates, test_features.n_elem);
    mat residualtime_marginals(min_duration + ndurations - 1,
            test_features.n_elem);
    ivec filtering_labels(test_features.n_elem);
    ivec residual_time_filtering_labels(test_features.n_elem);
    vec loglikelihood1(test_features.n_elem);
    vec loglikelihood2(test_features.n_elem);
    for(int i = 0; i < test_features.n_elem; i++) {
        const auto& f = test_features.at(i);
        loglikelihood1(i) = model.oneStepAheadLoglikelihood(f);
        loglikelihood2(i) = model.oneStepAheadLoglikelihood2(f);
        model.addNewObservation(f);
        runlength_marginals.col(i) = model.getRunlengthMarginal();
        state_marginals.col(i) = model.getStateMarginal();
        state_marginals_2.col(i) = model.getStateMarginal2();
        residualtime_marginals.col(i) = model.getResidualTimeMarginal();
        filtering_labels(i) = (int) state_marginals.col(i).index_max();
        residual_time_filtering_labels(i) = (int) state_marginals_2.col(
                i).index_max();
    }
    ivec gt_labels = expand_vit_mat(vit_mat);
    BOOST_CHECK(all(gt_labels == filtering_labels));
    BOOST_CHECK(all(gt_labels == residual_time_filtering_labels));
    BOOST_CHECK(approx_equal(state_marginals, state_marginals_2,
                "absdiff", 1e-10));
    BOOST_CHECK(approx_equal(loglikelihood1, loglikelihood2,
                "absdiff", 1e-10));

    // Saving posteriors for debugging purposes.
    //runlength_marginals.save("rl.txt", raw_ascii);
    //residualtime_marginals.save("rt.txt", raw_ascii);
    //vit_mat.save("gt.txt", raw_ascii);
    //state_marginals.save("sm.txt", raw_ascii);
    //state_marginals_2.save("sm2.txt", raw_ascii);
}

max_stars_repo_name: DiegoAE/BOSD

max_issues_repo_name: DiegoAE/BOSD

max_forks_repo_name: DiegoAE/BOSD


text:
#pragma once

#include <algorithm>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>

namespace cinja {

    namespace detail {

        class value {
        public:
            template <typename T, typename = std::enable_if_t<std::is_arithmetic<T>::value>>
            value(T item): _content(boost::lexical_cast<std::string>(item)), _isdigit(true) {
            }

            value(std::string &item): _content(item) {}

            value(std::string &&item): _content(item) {}

            value(std::vector<std::string> &item): _vector(item) {}

            value(std::vector<std::string> &&item): _vector(item) {}

            bool b() {
                bool retval{ true };
                if (_content.empty()) retval = false;
                if (_isdigit && boost::lexical_cast<double>(_content) == 0.0) retval = false;
                if (boost::algorithm::to_upper_copy(_content) == "FALSE") retval = false;
                return retval;
            }

            std::string s() {
                return _content;
            }

            std::vector<std::string> v() {
                return _vector;
            }

        private:
            std::string _content;
            std::vector<std::string> _vector;
            bool _isdigit{false};
        };

        std::string substitude(std::string raw, std::map<std::string, std::unique_ptr<value>> &context) {
            for (std::map<std::string, std::unique_ptr<value>>::iterator s = context.begin(); s != context.end(); s++) {
                boost::regex r{ "{{[[:space:]]*" + s->first + "[[:space:]]*}}" };
                raw = boost::regex_replace(raw, r, s->second->s());
            }
            return raw;
        }

        class section {
        public:
            virtual ~section()
            {}
            virtual std::string render(std::map<std::string, std::unique_ptr<value>> &context)
            {}
        };

        class forsection: public section {
        public:
            forsection(): section() {}
            void addChild(std::unique_ptr<section> &&p) {
                _children.emplace_back(std::forward<std::unique_ptr<section>>(p));
            }
            void setIter(std::string &&iterName, std::string &&iterRange) {
                this->iterName = iterName;
                this->iterRange = iterRange;
            }
            std::string render(std::map<std::string, std::unique_ptr<value>> &context) override {
                std::string retval;
                for (auto item: context[iterRange]->v()) {
                    std::string cur;

                    context.insert(std::make_pair(iterName, std::make_unique<value>(item)));
                    for (size_t i = 0; i < _children.size(); i++) {
                        cur += _children[i]->render(context);
                    }
                    substitude(cur, context);
                    context.erase(iterName);

                    retval += cur;
                }
                return retval;
            }
        private:
            std::vector<std::unique_ptr<section>> _children;
            std::string iterName, iterRange;
        };

        class ifsection: public section {
        public:
            ifsection(): section()  {}
            void addChild(std::unique_ptr<section> &&p) {
                _children.emplace_back(std::forward<std::unique_ptr<section>>(p));
            }
            void setCondition(std::string &&condition) {
                this->condition = condition;
            }
            std::string render(std::map<std::string, std::unique_ptr<value>> &context) override {
                std::string retval;
                if (context[condition]->b()) {
                    for (size_t i = 0; i < _children.size(); i++) {
                        retval += _children[i]->render(context);
                    }
                    substitude(retval, context);
                }
                else retval = "";
                return retval;
            }
        private:
            std::vector<std::unique_ptr<section>> _children;
            std::string condition;
        };

        class plainsection: public section {
        public:
            plainsection(std::string &&s): section(), _content(s) {
            }
            std::string render(std::map<std::string, std::unique_ptr<value>> &context) override {
                return substitude(_content, context);
            }
        private:
            std::string _content;
        };

        std::unique_ptr<section> _parse(std::string &raw, size_t &pos, std::string::size_type instrStart) {
            auto instrEnd{ raw.find("%}", instrStart) };
            std::string instr{raw.substr(instrStart+2, instrEnd-instrStart-2)};
            std::vector<std::string> v;
            boost::algorithm::split(v, instr, boost::algorithm::is_space());
            v.erase(std::remove_if(v.begin(), v.end(), [](std::string &s) {
                return s.empty();
            }), v.end());
            std::unique_ptr<section> ret;

            if (v[0] == "for") {
                std::string iterName{v[1]};
                std::string iterRange{v[3]};
                auto nextInstrStart{ raw.find("{%", instrEnd) };
                auto nextInstrEnd{ raw.find("%}", nextInstrStart) };
                auto retval{ std::make_unique<forsection>() };
                retval->setIter(std::move(iterName), std::move(iterRange));
                retval->addChild(std::make_unique<plainsection>(raw.substr(instrEnd+2, nextInstrStart-instrEnd-2)));

                while (boost::algorithm::trim_copy(
                        raw.substr(nextInstrStart+2, nextInstrEnd-nextInstrStart-2)) != "endfor") {
                    retval->addChild(_parse(raw, pos, nextInstrStart));
                    nextInstrStart = raw.find("{%", pos);
                    if (nextInstrStart > pos)
                        retval->addChild(std::make_unique<plainsection>(raw.substr(pos, nextInstrStart-pos)));
                    nextInstrEnd = raw.find("%}", pos);
                }

                pos = nextInstrEnd + 2;
                ret = std::move(retval);
            }
            else if (v[0] == "if") {
                std::string condition{v[1]};
                auto nextInstrStart{ raw.find("{%", instrEnd) };
                auto nextInstrEnd{ raw.find("%}", nextInstrStart) };
                auto retval{ std::make_unique<ifsection>() };
                retval->setCondition(std::move(condition));
                retval->addChild(std::make_unique<plainsection>(raw.substr(instrEnd+2, nextInstrStart-instrEnd-2)));

                while (boost::algorithm::trim_copy(
                        raw.substr(nextInstrStart+2, nextInstrEnd-nextInstrStart-2)) != "endif") {

                    retval->addChild(_parse(raw, pos, nextInstrStart));
                    nextInstrStart = raw.find("{%", pos);
                    if (nextInstrStart > pos)
                        retval->addChild(std::make_unique<plainsection>(raw.substr(pos, nextInstrStart-pos)));
                    nextInstrEnd = raw.find("%}", pos);
                }

                pos = nextInstrEnd + 2;
                ret = std::move(retval);
            }

            return ret;
        }

    }

    class Template {

    public:
        Template(std::string source): _body(std::move(source)) {
            parse(_body);
        };

        void parse(std::string &raw) {
            size_t pos = 0;
            auto size = raw.size();
            while (pos < size) {
                auto instrStart = raw.find("{%", pos);
                if (instrStart == std::string::npos) {
                    _sections.push_back(std::make_unique<detail::plainsection>(raw.substr(pos, raw.size())));
                    break;
                }
                _sections.push_back(std::make_unique<detail::plainsection>(raw.substr(pos, instrStart-pos)));
                _sections.push_back(detail::_parse(raw, pos, instrStart));
            }
        }

        std::string render() {
            std::string retval;
            for (auto i = _sections.cbegin(); i !=  _sections.cend(); i++) {
                retval += (*i)->render(_context);
            }
            return retval;
        }

        template <typename T, typename = std::enable_if<std::is_arithmetic<T>::value>>
        void setValue(std::string name, T value) {
            _context.insert(std::make_pair(name, std::make_unique<detail::value>(value)));
        }

        void setValue(std::string name, std::string value) {
            _context.insert(std::make_pair(name, std::make_unique<detail::value>(value)));
        }

        void setValue(std::string name, std::vector<std::string> &value) {
            _context.insert(std::make_pair(name, std::make_unique<detail::value>(value)));
        }

        void setValue(std::string name, std::vector<std::string> &&value) {
            _context.insert(std::make_pair(name, std::make_unique<detail::value>(value)));
        }

    private:
        std::string _body;
        std::vector<std::unique_ptr<detail::section>> _sections;
        std::map<std::string, std::unique_ptr<detail::value>> _context;
    };
}

max_stars_repo_name: cctvbtx/cinja

max_issues_repo_name: cctvbtx/cinja

max_forks_repo_name: cctvbtx/cinja