text:
/*
 * Copyright Nick Thompson, 2021
 * Use, modification and distribution are subject to the
 * Boost Software License, Version 1.0. (See accompanying file
 * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
 */

#include "math_unit_test.hpp"
#include <boost/math/tools/cubic_roots.hpp>
#include <random>
#ifdef BOOST_HAS_FLOAT128
#include <boost/multiprecision/float128.hpp>
using boost::multiprecision::float128;
#endif

using boost::math::tools::cubic_root_condition_number;
using boost::math::tools::cubic_root_residual;
using boost::math::tools::cubic_roots;
using std::cbrt;

template <class Real> void test_zero_coefficients() {
    Real a = 0;
    Real b = 0;
    Real c = 0;
    Real d = 0;
    auto roots = cubic_roots(a, b, c, d);
    CHECK_EQUAL(roots[0], Real(0));
    CHECK_EQUAL(roots[1], Real(0));
    CHECK_EQUAL(roots[2], Real(0));

    a = 1;
    roots = cubic_roots(a, b, c, d);
    CHECK_EQUAL(roots[0], Real(0));
    CHECK_EQUAL(roots[1], Real(0));
    CHECK_EQUAL(roots[2], Real(0));

    a = 1;
    d = 1;
    // x^3 + 1 = 0:
    roots = cubic_roots(a, b, c, d);
    CHECK_EQUAL(roots[0], Real(-1));
    CHECK_NAN(roots[1]);
    CHECK_NAN(roots[2]);
    d = -1;
    // x^3 - 1 = 0:
    roots = cubic_roots(a, b, c, d);
    CHECK_EQUAL(roots[0], Real(1));
    CHECK_NAN(roots[1]);
    CHECK_NAN(roots[2]);

    d = -2;
    // x^3 - 2 = 0
    roots = cubic_roots(a, b, c, d);
    CHECK_ULP_CLOSE(roots[0], cbrt(Real(2)), 2);
    CHECK_NAN(roots[1]);
    CHECK_NAN(roots[2]);

    d = -8;
    roots = cubic_roots(a, b, c, d);
    CHECK_EQUAL(roots[0], Real(2));
    CHECK_NAN(roots[1]);
    CHECK_NAN(roots[2]);

    // (x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x - 6
    roots = cubic_roots(Real(1), Real(-6), Real(11), Real(-6));
    CHECK_ULP_CLOSE(roots[0], Real(1), 2);
    CHECK_ULP_CLOSE(roots[1], Real(2), 2);
    CHECK_ULP_CLOSE(roots[2], Real(3), 2);

    // Double root:
    // (x+1)^2(x-2) = x^3 - 3x - 2:
    // Note: This test is unstable wrt to perturbations!
    roots = cubic_roots(Real(1), Real(0), Real(-3), Real(-2));
    CHECK_ULP_CLOSE(Real(-1), roots[0], 2);
    CHECK_ULP_CLOSE(Real(-1), roots[1], 2);
    CHECK_ULP_CLOSE(Real(2), roots[2], 2);

    std::uniform_real_distribution<Real> dis(-2, 2);
    std::mt19937 gen(12345);
    // Expected roots
    std::array<Real, 3> r;
    int trials = 10;
    for (int i = 0; i < trials; ++i) {
        // Mathematica:
        // Expand[(x - r0)*(x - r1)*(x - r2)]
        // - r0 r1 r2 + (r0 r1 + r0 r2 + r1 r2) x
        // - (r0 + r1 + r2) x^2 + x^3
        for (auto &root : r) {
            root = static_cast<Real>(dis(gen));
        }
        std::sort(r.begin(), r.end());
        Real a = 1;
        Real b = -(r[0] + r[1] + r[2]);
        Real c = r[0] * r[1] + r[0] * r[2] + r[1] * r[2];
        Real d = -r[0] * r[1] * r[2];

        auto roots = cubic_roots(a, b, c, d);
        // I could check the condition number here, but this is fine right?
        if (!CHECK_ULP_CLOSE(r[0], roots[0], 25)) {
            std::cerr << "  Polynomial x^3 + " << b << "x^2 + " << c << "x + "
                      << d << " has roots {";
            std::cerr << r[0] << ", " << r[1] << ", " << r[2]
                      << "}, but the computed roots are {";
            std::cerr << roots[0] << ", " << roots[1] << ", " << roots[2]
                      << "}\n";
        }
        CHECK_ULP_CLOSE(r[1], roots[1], 25);
        CHECK_ULP_CLOSE(r[2], roots[2], 25);
        for (auto root : roots) {
            auto res = cubic_root_residual(a, b, c, d, root);
            CHECK_LE(abs(res[0]), res[1]);
        }
    }
}

void test_ill_conditioned() {
    // An ill-conditioned root reported by SATovstun:
    // "Exact" roots produced with a high-precision calcuation on Wolfram Alpha:
    // NSolve[x^3 + 10000*x^2 + 200*x +1==0,x]
    std::array<double, 3> expected_roots{-9999.97999997,
                                         -0.010010015026300100757327057,
                                         -0.009990014973799899662674923};
    auto roots = cubic_roots<double>(1, 10000, 200, 1);
    CHECK_ABSOLUTE_ERROR(expected_roots[0], roots[0],
                         std::numeric_limits<double>::epsilon());
    CHECK_ABSOLUTE_ERROR(expected_roots[1], roots[1], 1.01e-5);
    CHECK_ABSOLUTE_ERROR(expected_roots[2], roots[2], 1.01e-5);
    double cond =
        cubic_root_condition_number<double>(1, 10000, 200, 1, roots[1]);
    double r1 = expected_roots[1];
    // The factor of 10 is a fudge factor to make the test pass.
    // Nonetheless, it does show this is basically correct:
    CHECK_LE(abs(r1 - roots[1]) / abs(r1),
             10 * std::numeric_limits<double>::epsilon() * cond);

    cond = cubic_root_condition_number<double>(1, 10000, 200, 1, roots[2]);
    double r2 = expected_roots[2];
    // The factor of 10 is a fudge factor to make the test pass.
    // Nonetheless, it does show this is basically correct:
    CHECK_LE(abs(r2 - roots[2]) / abs(r2),
             10 * std::numeric_limits<double>::epsilon() * cond);

    // See https://github.com/boostorg/math/issues/757:
    // The polynomial is ((x+1)^2+1)*(x+1) which has roots -1, and two complex
    // roots:
    roots = cubic_roots<double>(1, 3, 4, 2);
    CHECK_ULP_CLOSE(roots[0], -1.0, 3);
    CHECK_NAN(roots[1]);
    CHECK_NAN(roots[2]);
    return;
}

int main() {
    test_zero_coefficients<float>();
    test_zero_coefficients<double>();
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
    test_zero_coefficients<long double>();
#endif
    test_ill_conditioned();
#ifdef BOOST_HAS_FLOAT128
    // For some reason, the quadmath is way less accurate than the
    // float/double/long double:
    // test_zero_coefficients<float128>();
#endif

    return boost::math::test::report_errors();
}


text:
//
// Copyright (c) 2011-2012 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// 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 QFSM_BACK_DETAIL_COMPILATION_STATE_HPP
#define QFSM_BACK_DETAIL_COMPILATION_STATE_HPP

#include <boost/type_traits/is_base_of.hpp>
#include <boost/mpl/int.hpp>
#include "QFsm/Back/Aux/FsmType.hpp"
#include "QFsm/Back/Aux/State.hpp"

namespace QFsm
{
namespace Back
{
namespace Detail
{
namespace Compilation
{

struct State
{
    explicit State(int p_id = 0)
        : id(p_id)
    { }

    int id;
};

} // namespace Compilation
} // namespace Detail

namespace Aux
{
template<typename TFsm>
class State<Back::Detail::Compilation::State, TFsm>
{
public:
    static void init(Back::Detail::Compilation::State& p_state, const boost::mpl::int_<0>&)
    {
        p_state = Back::Detail::Compilation::State(boost::mpl::find<typename TFsm::States, typename TFsm::InitialState>::type::pos::value);
    }

    template<int region> static void init(Back::Detail::Compilation::State& p_state, const boost::mpl::int_<region>&)
    {
        typedef typename boost::mpl::at_c<typename TFsm::InitialState, region - 1>::type state;
        p_state = Back::Detail::Compilation::State(boost::mpl::find<typename TFsm::States, state>::type::pos::value);
    }

    template<typename TState> static bool equals(const Back::Detail::Compilation::State& p_state)
    {
        return static_cast<int>(boost::mpl::find<typename TFsm::States, TState>::type::pos::value) == p_state.id;
    }
};
} // namespace Aux

} // namespace Back
} // namespace QFsm

#endif

ext: hpp

max_stars_repo_name: krzysztof-jusiak/qfsm

max_issues_repo_name: krzysztof-jusiak/qfsm

max_forks_repo_name: krzysztof-jusiak/qfsm


text:
/**
* Copyright 2018 Woods Hole Oceanographic Institution
*
* 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.
*/
//
// Ian Vaughn, October 2017
//
// Based on the simplified 4-DOF dynamics model
// in ROV

//#include <sentry_sim/SentryDynamics_plugin.hh>

// REV: MELODIC 1 0

#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#if GAZEBO_MAJOR_VERSION > 7
#include <gazebo/common/CommonIface.hh>
#else
#include <gazebo/common/common.hh>
#endif

#include <ros/ros.h>
#include <ros/callback_queue.h>
#include <ros/subscribe_options.h>
#include <sensor_msgs/JointState.h>
#include <thread>

#include <boost/bind.hpp>

namespace gazebo {

class DsJointStatePublisher : public ModelPlugin {
  public:
    virtual ~DsJointStatePublisher() {
       if (updateConnection) {
#if GAZEBO_MAJOR_VERSION > 7
      // Melodic API change
      // Deprecation: public: void Events::Disconnect.*(ConnectionPtr);
      // Replacement: Delete the Connection object, perhaps by calling reset() on its smart pointer.
      this->updateConnection.reset();
#else
      gazebo::event::Events::DisconnectWorldUpdateBegin(this->updateConnection);
#endif
        }

        if (rosNode) {
            rosNode->shutdown();
        }
    }

    void Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf) {
        // Check on ROS
        if (!ros::isInitialized()) {
            ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized, unable to load plugin. "
                << "Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so' in the gazebo_ros package)");
            return;
        }

        // Get the proper robot name
        this->model = _parent;
        if (_sdf->HasElement("robotNamespace")) {
            this->robotNamespace = _sdf->Get<std::string>("robotNamespace");
        } else {
            this->robotNamespace = this->model->GetName();
        }

        // Connect to the ROS node
        ROS_INFO_STREAM("ds_jointstatepublisher: Initializing internal ROS node...");
        rosNode.reset(new ros::NodeHandle(robotNamespace));

        sign = 1.0;
        if (_sdf->HasElement("invertSign")) {
            if (_sdf->Get<bool>("invertSign")) {
                sign = -1.0;
            }
        }

        // check to see if we're disabled by a rosparam
        disable = false;
        if (_sdf->HasElement("disableParam")) {
            std::string disableParam = _sdf->Get<std::string>("disableParam");

            if (rosNode->hasParam(disableParam) &&
               rosNode->getParam(disableParam, disable)) {
               ROS_INFO_STREAM("Loaded sim_jointstate_pub::disable=" <<disable);
            } else {
               ROS_ERROR_STREAM("Unable to load sim_jointstate_pub::disable from "
                               <<rosNode->resolveName(disableParam));
               disable = false;
            }

            if (disable) {
                ROS_ERROR_STREAM("jointstate publisher disabling itself!");
            }
        }

        // prepare some reference times
        double updateRate = 10;
        if (_sdf->HasElement("updateRate")) {
            updateRate = _sdf->Get<double>("updateRate");
        }
        rosPublishPeriod = gazebo::common::Time(1.0/updateRate);
        lastRosPublished = gazebo::common::Time(0.0);

        // Setup our publisher
        ROS_INFO_STREAM("ds_jointstatepublisher: Advertising topic to publish on...");
        if (!disable) {
            rosPub = rosNode->advertise<sensor_msgs::JointState>("joint_states", 10);
            // Listen to the update event
            this->updateConnection = event::Events::ConnectWorldUpdateBegin(
                boost::bind(&DsJointStatePublisher::OnUpdate, this, _1));
        }
    }

    void OnUpdate(const common::UpdateInfo& _info) {
        if (_info.simTime < lastRosPublished + rosPublishPeriod) {
            return;
        }
        if (disable) {
            lastRosPublished += rosPublishPeriod;
            return;
        }

        sensor_msgs::JointState jointState;
        jointState.header.stamp = ros::Time::now();
        jointState.name.resize(this->model->GetJointCount());
        jointState.position.resize(this->model->GetJointCount());
        jointState.velocity.resize(this->model->GetJointCount());
        jointState.effort.resize(this->model->GetJointCount());

        int i=0;
        for (const physics::JointPtr& joint : this->model->GetJoints()) {
            jointState.name[i] = joint->GetName();

            // check if the joint should be ignored
            if (joint->HasType(gazebo::physics::Base::EntityType::FIXED_JOINT)
#if GAZEBO_MAJOR_VERSION > 7
                || joint->DOF() > 1
                || joint->LowerLimit(0) == 0 && joint->UpperLimit(0) == 0) {
#else
                || joint->GetAngleCount() > 1
                || joint->GetLowerLimit(0).Radian() == 0 && joint->GetUpperLimit(0).Radian() == 0) {
#endif
                // ignore this joint
                jointState.position[i] = 0;
                jointState.velocity[i] = 0;
                jointState.effort[i] = 0;
            } else {
#if GAZEBO_MAJOR_VERSION > 7
                jointState.position[i] = sign*joint->Position(0);
#else
                jointState.position[i] = sign*joint->GetAngle(0).Radian();
#endif
                jointState.velocity[i] = joint->GetVelocity(0);
                jointState.effort[i] = joint->GetForce(0);
            }
            i++;
        }
        rosPub.publish(jointState);
        lastRosPublished += rosPublishPeriod;
    }

  protected:
    event::ConnectionPtr updateConnection;
    std::string robotNamespace;
    physics::ModelPtr model;
    double sign;
    bool disable;

    gazebo::common::Time rosPublishPeriod, lastRosPublished;

    std::unique_ptr<ros::NodeHandle> rosNode;
    ros::Publisher rosPub;

};

GZ_REGISTER_MODEL_PLUGIN(DsJointStatePublisher);

}; // namespace gazebo

ext: cc


text:
/*
 * hartman_skrekovski_color.hpp
 * Author: Aven Bross
 *
 * Implementation of Hartman-Skrekovski path 3-choosing algorithm.
 */

#ifndef __HARTMAN_SKREKOVSKI_COLOR_HPP
#define __HARTMAN_SKREKOVSKI_COLOR_HPP

// STL headers
#include <vector>
#include <utility>
#include <algorithm>

// Basic graph headers
#include <boost/graph/graph_traits.hpp>

// Local project headers
#include "disjoint_set.hpp"
#include "incidence_list_helpers.hpp"

namespace {
    // The three states a vertex may have
    const int INTERIOR_MARK = 0;

    /*
     * set_face_location
     *
     * inputs: a vertex v, the new face location for v, a read-write-able vertex
     *     property map storing the face location of each vertex, a disjoint set
     *     structure to store face location sets.
     *
     * outputs: sets the face location of v to the given face location, if the
     *     given location doesn't exist, that is, the integer new_face_location
     *     is negative, a new face location is created in the disjoint set
     *     structure.
     */
    template<typename vertex_t, typename face_location_map_t>
    inline int set_face_location(
            vertex_t v, int new_face_location,
            face_location_map_t & face_location_map,
            disjoint_set_t & face_location_sets
        )
    {
        if(!face_location_sets.exists(new_face_location)) {
            face_location_map[v] = face_location_sets.make_next();
        }
        else {
            face_location_map[v] = face_location_sets.find(new_face_location);
        }
        return face_location_map[v];
    }

    /*
     * hartman_skrekovski_color
     *
     * assumptions: There is a cycle C=v_0v_1...v_k in the weakly triangulated
     *     being colored. Suppose x, y, and p are in C such that p is between x
     *     and y clockwise around C. Suppose all vertices other than x, y, and p
     *     are uncolored. Suppose vertices x, y, and p have lists of size 1 or
     *     more, other vertices in C have lists of size 2 or more, and vertices
     *     in the subgraph bounded by C have lists of size 3 or more.
     *     Additionally, if p is colored some color c, assume vertices between x
     *     and p clockwise, including x, don't have the color c in their lists.
     *
     * inputs: A weakly triangulated planar graph with vertex indices
     *     (predefined boost property), a valid augmented planar embedding of
     *     the graph (modeling the boost AugmentedEmbedding concept defined in
     *     documentation), a read-write-able vertex property map assigning each
     *     vertex an integer to track face location, a disjoint set structure to
     *     store face location sets, a read-write-able vertex property map
     *     assigning each vertex an integer to track state, a read-able vertex
     *     property map assigning a pair of iterators from its augmented
     *     embedding list to track the range of valid neighbors, a read-write-
     *     able vertex property map to which the coloring will be assigned, the
     *     vertices x, y, and p on the outer cycle of the current subgraph, and
     *     the integers for the current face location marks.
     *
     * outputs: The coloring vertex property will contain a valid path list-
     *     coloring of the subgraph bounded by C such that x, y, and p each
     *     receive at most one same color neighbor. Moreover, if x=y=p then
     *     x,y,p receive no same color neighbors.
     */

    template<
            typename graph_t, typename augmented_embedding_t,
            typename face_location_map_t, typename neighbor_range_map_t,
            typename color_list_map_t, typename vertex_t
                = typename boost::graph_traits<graph_t>::vertex_descriptor
        >
    void hartman_skrekovski_color_recursive(
            const graph_t & graph,
            const augmented_embedding_t & augmented_embedding,
            face_location_map_t & face_location_map,
            disjoint_set_t & face_location_sets,
            neighbor_range_map_t & neighbor_range_map,
            color_list_map_t & color_list_map,
            vertex_t x, vertex_t y, vertex_t p,
            int before_p, int before_y, int before_x
        )
    {
        // If p isn't colored yet we are starting a new path
        if(color_list_map[p].size() > 1) {
            // Color p the first color in its list
            color_list_map[p].erase(
                    ++color_list_map[p].begin(),
                    color_list_map[p].end()
                );
        }

        // Grab p's the color from p's singleton list
        auto p_color = color_list_map[p].front();

        // Track the vertices that will become x and y in the first cycle
        vertex_t new_x = x, new_y = y;

        // Iterate through p's adjacency list
        auto neighbor_iter = neighbor_range_map[p].first;
        do {
            // Wrap adjacency list
            if(neighbor_iter == augmented_embedding[p].end())
                neighbor_iter = augmented_embedding[p].begin();

            // Grab neighbor n, and the iterator to p in n's adjacency list
            vertex_t n = neighbor_iter -> vertex;
            auto back_iter = neighbor_iter -> iterator;
            int n_location = face_location_map[n];

            // Look for p_color in n's color list
            auto color_iter = std::find(
                    color_list_map[n].begin(),
                    color_list_map[n].end(), p_color
                );

            // The case n is not in C
            if(face_location_map[n] == INTERIOR_MARK) {
                // Note that n is between x and p on the first cycle
                before_p = set_face_location(
                        n, before_p, face_location_map, face_location_sets
                    );

                // Initialize n's neighbor range to start at the edge pn
                initialize_neighbor_range(
                        n, back_iter, neighbor_range_map, augmented_embedding
                    );

                // Remove the edge pn from n's neighbor range
                remove_first_neighbor(
                        n, neighbor_range_map, augmented_embedding
                    );

                // Remove the path color from n's list
                if(color_iter != color_list_map[n].end()) {
                    color_list_map[n].erase(color_iter);
                    color_iter = color_list_map[n].end();
                }
            }
            // The case n is immediately counterclockwise to p in C
            else if(neighbor_iter == neighbor_range_map[p].first) {
                // If p has a single neighbor the current subgraph is K_2
                if(neighbor_iter == neighbor_range_map[p].second) {
                    // If is neither x nor y, ensure it doesn't receive p_color
                    if(n != x && n != y) {
                        // Remove the path color from n's list
                        if(color_iter != color_list_map[n].end()) {
                            color_list_map[n].erase(color_iter);
                            color_iter = color_list_map[n].end();
                        }
                    }

                    // Color n with any color remaining in its list
                    if(color_list_map[n].size() > 1) {
                        color_list_map[n].erase(
                                ++color_list_map[n].begin(),
                                color_list_map[n].end()
                            );
                    }

                    break;
                }
                // If n is y and y has the path color, swap p and y so the
                //     path runs clockwise
                else if(n == y && color_iter != color_list_map[n].end()) {
                    if(color_list_map[n].size() > 1) {
                        // Remove all colors other than the path color
                        color_list_map[n].erase(
                                color_list_map[n].begin(),
                                color_iter
                            );
                        color_list_map[n].erase(
                                ++color_list_map[n].begin(),
                                color_list_map[n].end()
                            );
                    }

                    hartman_skrekovski_color_recursive(
                            graph, augmented_embedding,
                            face_location_map, face_location_sets,
                            neighbor_range_map, color_list_map,
                            y, p, y,
                            -1, -1, before_y
                        );

                    break;
                }
                else {
                    // If we are removing x, setup new_x as n
                    if(x == p) {
                        new_x = n;

                        // Note that n is between x and p on the first cycle
                        before_p = set_face_location(
                                n, before_p, face_location_map,
                                face_location_sets
                            );
                    }

                    // Remove path color from n's list
                    if(color_iter != color_list_map[n].end()) {
                        color_list_map[n].erase(color_iter);
                        color_iter = color_list_map[n].end();
                    }

                    // Remove the edge pn from n's adjacency list
                    remove_last_neighbor(
                            n, neighbor_range_map, augmented_embedding
                        );
                }
            }
            else {
                // Divide the neighbor range of n at the edge pn
                auto n_ranges = split_neighbor_range(
                        n, back_iter, neighbor_range_map, augmented_embedding
                    );

                // p has been removed from the first cycle so we may remove
                //     those neighbors from p's neighbor range
                neighbor_range_map[p].first = neighbor_iter;

                // The case we are removing y
                if(p == y) {
                    if(color_iter != color_list_map[n].end()) {
                        color_list_map[n].erase(color_iter);
                        color_iter = color_list_map[n].end();
                    }

                    // If p=x=y then we are removing a single vertex path
                    if(p == x) {
                        // Color the subgraph bounded by the first cycle
                        neighbor_range_map[n] = n_ranges.second;
                        hartman_skrekovski_color_recursive(
                                graph, augmented_embedding,
                                face_location_map, face_location_sets,
                                neighbor_range_map, color_list_map,
                                new_x, n, new_x,
                                -1, before_p, before_y
                            );

                        // If the edge pn is a chord, we must color the rest
                        if(back_iter != n_ranges.first.first) {
                            // Color the subgraph bounded by the second cycle
                            neighbor_range_map[n] = n_ranges.first;
                            hartman_skrekovski_color_recursive(
                                    graph, augmented_embedding,
                                    face_location_map, face_location_sets,
                                    neighbor_range_map, color_list_map,
                                    n, p, p,
                                    -1, -1, before_y
                                );
                        }

                        break;
                    }
                    // The case the edge pn is in the cycle, i.e. not a chord
                    else if(neighbor_iter == neighbor_range_map[p].second) {
                        // Color the subgraph bounded by the first cycle
                        neighbor_range_map[n] = n_ranges.second;
                        hartman_skrekovski_color_recursive(
                                graph, augmented_embedding,
                                face_location_map, face_location_sets,
                                neighbor_range_map, color_list_map,
                                new_x, n, new_x,
                                -1, before_p, before_x
                            );

                        break;
                    }
                    // Otherwise we condition on the location of n as usual

                    // Remember n will be our new y vertex for the first cycle
                    new_y = n;
                }

                // The case n is in C[p,y]
                if(face_location_sets.compare(n_location, before_y) || n == y) {
                    vertex_t new_p = n;

                    // The case n needs to be colored
                    if(color_iter != color_list_map[n].end()
                        && color_list_map[n].size() > 1)
                    {
                        // Remove all colors other than the path color
                        color_list_map[n].erase(
                                color_list_map[n].begin(),
                                color_iter
                            );
                        color_list_map[n].erase(
                                ++color_list_map[n].begin(),
                                color_list_map[n].end()
                            );
                    }
                    // The case n will not be added to the path
                    else if(color_list_map[n].size() > 1
                        || color_list_map[n].front() != p_color)
                    {
                        // Start new path at the new x on the first cycle
                        new_p = new_x;

                        // Combine the before_p and before_y segments
                        before_y = face_location_sets.take_union(
                                before_p, before_y
                            );

                        // Note before_p is gone
                        before_p = -1;
                    }

                    /*
                     * This is the most complicated case.
                     * There are two sub-cases to consider:
                     *
                     * Case 1: p_color in L[n]
                     *   In this case |L[n]|=1. In the first call we will
                     *   continue coloring the path from n. In the second
                     *   call, we will immediately find the edge pn and,
                     *   since it the first edge and in the cycle, we will
                     *   immediately remove the two vertex path np. Thus
                     *   no vertex in the path will recieve a new same color
                     *   neighbor from the second call.
                     *
                     * Case 2: p_color is not in L[n]
                     *   In this case the first call will start a new path
                     *   from the vertex new_x. By removing p_color from all
                     *   neighbors of vertices in the path, we ensure no
                     *   vertices in the path, including n, will recieve any
                     *   new same color neighbors in the first call. In the
                     *   second call we will be continuing the path from p.
                     *   Since p_color is not in L[n] and x=y=n, the vertex
                     *   n will not recieve any new same color neighbors in
                     *   the second call.

                     */

                    // Color the subgraph bounded by the first cycle
                    neighbor_range_map[n] = n_ranges.second;
                    hartman_skrekovski_color_recursive(
                            graph, augmented_embedding,
                            face_location_map, face_location_sets,
                            neighbor_range_map, color_list_map,
                            new_x, new_y, new_p,
                            before_p, before_y, before_x
                        );

                    // If the edge pn is a chord, handle the rest
                    if(back_iter != n_ranges.first.first) {
                        // Color the subgraph bounded by the second cycle
                        neighbor_range_map[n] = n_ranges.first;
                        hartman_skrekovski_color_recursive(
                                graph, augmented_embedding,
                                face_location_map, face_location_sets,
                                neighbor_range_map, color_list_map,
                                n, n, p,
                                -1, before_y, -1
                            );
                    }
                }
                // The case n is in C[y,x], n != y
                else if(face_location_sets.compare(n_location, before_x)) {
                    if(color_iter != color_list_map[n].end()) {
                        color_list_map[n].erase(color_iter);
                        color_iter = color_list_map[n].end();
                    }

                    // Color the subgraph bounded by the first cycle
                    neighbor_range_map[n] = n_ranges.second;
                    hartman_skrekovski_color_recursive(
                            graph, augmented_embedding,
                            face_location_map, face_location_sets,
                            neighbor_range_map, color_list_map,
                            new_x, n, new_x,
                            -1, before_p, before_x
                        );

                    // Color the subgraph bounded by the second cycle
                    neighbor_range_map[n] = n_ranges.first;
                    hartman_skrekovski_color_recursive(
                            graph, augmented_embedding,
                            face_location_map, face_location_sets,
                            neighbor_range_map, color_list_map,
                            n, y, p,
                            -1, before_y, before_x
                        );
                }
                // The case n is in C[x,p]
                else {
                    // Color the subgraph bounded b the second cycle
                    neighbor_range_map[n] = n_ranges.first;
                    hartman_skrekovski_color_recursive(
                            graph, augmented_embedding,
                            face_location_map, face_location_sets,
                            neighbor_range_map, color_list_map,
                            x, y, p,
                            before_p, before_y, before_x
                        );

                    // Color the subgraph bounded by the first cycle
                    neighbor_range_map[n] = n_ranges.second;
                    hartman_skrekovski_color_recursive(
                            graph, augmented_embedding,
                            face_location_map, face_location_sets,
                            neighbor_range_map, color_list_map,
                            n, n, n,
                            -1, before_p, -1
                        );
                }

                break;
            }
        } while(neighbor_iter++ != neighbor_range_map[p].second);
    }
}

/*
 * hartman_skrekovski_color
 *
 * inputs: A weakly triangulated planar graph with vertex indices (predefined
 *     boost property), a valid augmented planar embedding of the graph
 *     (modeling the boost AugmentedEmbedding concept defined in documentation),
 *     a read-able vertex property map assigning a range of colors to each
 *     vertex (each vertex must recieve a range of at least 3 colors if
 *     interior, and at least two colors if on the outer face), a read-write-
 *     able vertex property map to which the coloring will be assigned, and
 *     finally a pair of iterators for the list of vertices on the outer face of
 *     the graph in clockwise order.
 *
 * outputs: The coloring will be a valid assignment of colors from the input
 *     color lists such that each color class induces a disjoint union of paths.
 */

template<
        typename graph_t,
        typename augmented_embedding_t,
        typename color_list_map_t,
        typename neighbor_range_map_t,
        typename face_location_map_t,
        typename face_iterator_t
    >
void hartman_skrekovski_color(
        const graph_t & graph,
        const augmented_embedding_t & augmented_embedding,
        face_iterator_t face_begin, face_iterator_t face_end,
        neighbor_range_map_t & neighbor_range_map,
        face_location_map_t & face_location_map,
        color_list_map_t & color_list_map
    )
{
    // Type definitions
    typedef typename boost::graph_traits<graph_t>::vertex_descriptor vertex_t;

    // Setup face location sets (we will have only the region before_y)
    disjoint_set_t face_location_sets;

    // Make a set for 0, the location given to interior vertices
    face_location_sets.make_next();

    // Intitially all vertices will be
    int before_y = -1;

    // Initialize vertices on outer face
    for(auto face_iter = face_begin; face_iter != face_end; ++face_iter)
    {
        auto next = face_iter;
        if(++next == face_end) next = face_begin;

        vertex_t l = *face_iter;
        vertex_t v = *next;

        before_y = set_face_location(
                v, before_y, face_location_map, face_location_sets
            );

        auto back_iter = find_neighbor_iterator(
                v, l, augmented_embedding, graph
            );
        initialize_neighbor_range(
                v, back_iter, neighbor_range_map, augmented_embedding
            );
    }

    vertex_t x = *face_begin, y = *(--face_end);

    // Construct the path choosing from given color lists
    hartman_skrekovski_color_recursive(
            graph, augmented_embedding,
            face_location_map, face_location_sets,
            neighbor_range_map, color_list_map,
            x, y, x,
            -1, before_y, -1
        );
}

/*
 * A wrapper that automatically construct fast property maps for the
 * face_location_map and neighbor_range_map, but requires that graph_t is some
 * definition of boost::adjacency_list.
 */

template<
        typename graph_t,
        typename augmented_embedding_t,
        typename color_list_map_t,
        typename face_iterator_t
    >
void hartman_skrekovski_color(
        const graph_t & graph,
        const augmented_embedding_t & augmented_embedding,
        face_iterator_t face_begin, face_iterator_t face_end,
        color_list_map_t & color_list_map
    )
{
    // Vertex property map to store vertex marks
    typedef boost::iterator_property_map<
            std::vector<int>::iterator,
            typename boost::property_map<
                    graph_t, boost::vertex_index_t
                >::const_type
        > integer_property_map_t;

    // Vertex property map type for the neighbor ranges of planar_embedding_t
    typedef typename boost::property_traits<augmented_embedding_t>::value_type
            ::const_iterator embedding_iterator_t;
    typedef typename std::vector<
            std::pair<embedding_iterator_t, embedding_iterator_t>
        > neighbor_range_storage_t;
    typedef boost::iterator_property_map<
            typename neighbor_range_storage_t::iterator,
            typename boost::property_map<
                    graph_t, boost::vertex_index_t
                >::const_type
        > neighbor_range_map_t;

    // Construct a vertex property for neighbor ranges
    neighbor_range_storage_t neighbor_range_storage(boost::num_vertices(graph));
    neighbor_range_map_t neighbor_range_map(
            neighbor_range_storage.begin(),
            boost::get(boost::vertex_index, graph)
        );

    // Construct a vertex property map to store face location marks
    std::vector<int> face_location_storage(boost::num_vertices(graph));
    integer_property_map_t face_location_map(
            face_location_storage.begin(),
            boost::get(boost::vertex_index, graph)
        );

    // Call Hartman-Skrekovski with the given cycle and
    hartman_skrekovski_color(
            graph,
            augmented_embedding,
            face_begin, face_end,
            neighbor_range_map,
            face_location_map,
            color_list_map
        );
}

#endif


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2007. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
//[doc_managed_multiple_allocation
#include <boost/interprocess/managed_shared_memory.hpp>
#include <cassert>//assert
#include <cstring>//std::memset
#include <new>    //std::nothrow
#include <vector> //std::vector

int main()
{
   using namespace boost::interprocess;
   typedef managed_shared_memory::multiallocation_iterator multiallocation_iterator;

   //Try to erase any previous managed segment with the same name
   shared_memory_object::remove("MyManagedShm");

   try{
      managed_shared_memory managed_shm(create_only, "MyManagedShm", 65536);

      //Allocate 16 elements of 100 bytes in a single call. Non-throwing version.
      multiallocation_iterator beg_it = managed_shm.allocate_many(100, 16, std::nothrow);

      //To check for an error, we can use a boolean expression
      //or compare it with a default constructed iterator
      assert(!beg_it == (beg_it == multiallocation_iterator()));

      //Check if the memory allocation was successful
      if(!beg_it)  return 1;

      //Allocated buffers
      std::vector<char*> allocated_buffers;

      //Initialize our data
      for( multiallocation_iterator it = beg_it, end_it; it != end_it; ){
         allocated_buffers.push_back(&*it);
         //The iterator must be incremented before overwriting memory
         //because otherwise, the iterator is invalidated.
         std::memset(&*it++, 0, 100);
      }

      //Now deallocate
      while(!allocated_buffers.empty()){
         managed_shm.deallocate(allocated_buffers.back());
         allocated_buffers.pop_back();
      }

      //Allocate 10 buffers of different sizes in a single call. Throwing version
      std::size_t sizes[10];
      for(std::size_t i = 0; i < 10; ++i)
         sizes[i] = i*3;

      beg_it  = managed_shm.allocate_many(sizes, 10);

      //Iterate each allocated buffer and deallocate
      //The "end" condition can be also checked with operator!
      for(multiallocation_iterator it = beg_it; it;){
         //The iterator must be incremented before overwriting memory
         //because otherwise, the iterator is invalidated.
         managed_shm.deallocate(&*it++);
      }
   }
   catch(...){
      shared_memory_object::remove("MyManagedShm");
      throw;
   }
   shared_memory_object::remove("MyManagedShm");
   return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>

ext: cpp


text:
/*
   +----------------------------------------------------------------------+
   | HipHop for PHP                                                       |
   +----------------------------------------------------------------------+
   | Copyright (c) 2010-2015 Facebook, Inc. (http://www.facebook.com)     |
   +----------------------------------------------------------------------+
   | This source file is subject to version 3.01 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.php.net/license/3_01.txt                                  |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
*/

#include "hphp/runtime/vm/jit/vasm.h"
#include "hphp/runtime/vm/jit/vasm-gen.h"
#include "hphp/runtime/vm/jit/vasm-instr.h"
#include "hphp/runtime/vm/jit/vasm-print.h"
#include "hphp/runtime/vm/jit/vasm-unit.h"
#include "hphp/runtime/vm/jit/vasm-util.h"
#include "hphp/runtime/vm/jit/vasm-visit.h"

#include <boost/dynamic_bitset.hpp>

TRACE_SET_MOD(hhir);

namespace HPHP { namespace jit {

namespace {

struct Simplifier {
  Vunit& unit;
  jit::vector<uint32_t> uses;

  explicit Simplifier(Vunit& unit_in, const jit::vector<Vlabel>& blocks)
  : unit(unit_in), uses(unit.next_vr) {
    // Use count for each register.  Used to keep peepholes from
    // firing if results are used beyond the scope of the instructions
    // being checked.
    for (auto b : blocks) {
      for (auto& inst : unit.blocks[b].code) {
        visitUses(unit, inst, [&](Vreg r) { ++uses[r]; });
      }
    }
  }

  bool match_instr(const Vblock& block, size_t iIdx, Vinstr::Opcode op) const {
    auto const& code = block.code;
    return (iIdx < code.size() && code[iIdx].op == op);
  }

  // Compute register use counts for the given range of instructions.
  // Check to expand uses vector in case a new register was introduced.
  void compute_uses(const Vblock& block, size_t iIdx, size_t num) {
    for(auto i = iIdx; i < iIdx + num; ++i) {
      visitUses(unit,
                block.code[iIdx],
                [&](Vreg r) {
                  if (r > uses.size()) { uses.resize((size_t)r+1); }
                  ++uses[r];
                });
    }
  }

  // Undo any register uses from the given range of instructions.
  void undo_uses(const Vblock& block, size_t iIdx, size_t num) {
    for(auto i = iIdx; i < iIdx + num; ++i) {
      visitUses(unit, block.code[iIdx], [&](Vreg r) { --uses[r]; });
    }
  }

  // If there is an adjacent setcc/xorbi pair where the xor is being used
  // to invert the result of the setcc, just invert the setcc condition and
  // omit the xor.
  bool match_setcc_xorbi(const Vblock& block,
                         size_t& iIdx,
                         Vinstr& sinst,
                         Vreg& xdst) {
    if (match_instr(block, iIdx, Vinstr::setcc)) {
      auto const& code = block.code;
      auto const& inst = code[iIdx].setcc_;
      auto const dst = inst.d;
      // Make sure setcc result is only used by xor.
      if (uses[inst.d] == 1 && match_instr(block, iIdx + 1, Vinstr::xorbi)) {
        auto const& xor = code[iIdx + 1].xorbi_;
        if (xor.s0.b() == 1 && xor.s1 == dst && uses[xor.sf] == 0) {
          sinst = code[iIdx++];  // setcc instruction being modified.
          xdst = xor.d;          // destination for xor result.
          return true;
        }
      }
    }
    return false;
  }

  // Whether we have a copyargs where none of its sources is a dest.
  bool match_copyargs_no_overlap(const Vblock& block, size_t iIdx) {
    if (!match_instr(block, iIdx, Vinstr::copyargs)) return false;

    auto const& inst = block.code[iIdx].copyargs_;
    auto const& dsts = unit.tuples[inst.d];
    auto const& srcs = unit.tuples[inst.s];
    assertx(dsts.size() == srcs.size());

    for (auto const src : srcs) {
      for (auto const dst : dsts) {
        if (src == dst) return false;
      }
    }
    return true;
  }

  // Perform any simplification steps for the instructions beginning
  // at the given index.  Add additional simplification matchers here.
  size_t simplify(Vout& v, const Vblock& block, size_t iIdx) {
    Vinstr inst;
    Vreg dst;
    if (match_setcc_xorbi(block, iIdx, inst, dst)) {
      // Rewrite setcc/xorbi pair as setcc with inverted condition.
      v << setcc{ccNegate(inst.setcc_.cc), inst.setcc_.sf, dst};
    }

    // Convert simple copyargs to a list of copies.
    if (match_copyargs_no_overlap(block, iIdx)) {
      auto const& inst = block.code[iIdx].copyargs_;
      auto const& dsts = unit.tuples[inst.d];
      auto const& srcs = unit.tuples[inst.s];

      for (size_t i = 0; i < srcs.size(); ++i) {
        v << copy{srcs[i], dsts[i]};
      }
    }
    return iIdx;
  }
};

/*
 * The main work routine for the simplifier.  It runs a platform specific
 * simplify method on each instruction in the code stream.  The simplify
 * method is allowed to look ahead in the instruction stream in order to
 * match more than a single instruction if needed.  The simplify routines
 * are responsible for checking for the end of the instruction buffer.  If
 * a simplify routine finds a match, it emits the new instructions into
 * the provided emitter and returns the number of instructions to be replaced
 * in the original buffer by the newly emitted instructions.  The work()
 * routine then replaces the old instructions and calls work() again on
 * modified stream in case there are more simplifications to be had.
 */
size_t work(Simplifier& s, Vlabel b, size_t iIdx) {
  if (iIdx >= s.unit.blocks[b].code.size()) return iIdx;

  auto scratch = s.unit.makeScratchBlock();
  SCOPE_EXIT { s.unit.freeScratchBlock(scratch); };
  Vout v(s.unit, scratch, s.unit.blocks[b].code[iIdx].origin);

  auto& blocks = s.unit.blocks;
  auto& code = blocks[b].code;

  size_t mIdx = s.simplify(v, blocks[b], iIdx);
  if (!blocks[scratch].code.empty()) {
    const auto numNewInsts = blocks[scratch].code.size();
    const auto numInsts = mIdx - iIdx + 1;
    s.undo_uses(blocks[b], iIdx, numInsts);
    vector_splice(code, iIdx, numInsts, blocks[scratch].code);
    s.compute_uses(blocks[b], iIdx, numNewInsts);
    return work(s, b, iIdx);
  }
  return iIdx + 1;
}

}

/*
 * Perform a simplification pass for an entire unit.
 */
void simplify(Vunit& unit) {
  assertx(check(unit)); // especially, SSA
  // block order doesn't matter, but only visit reachable blocks.
  auto blocks = sortBlocks(unit);

  Simplifier simplifier(unit, blocks);

  // now mutate instructions
  for (auto b : blocks) {
    size_t iIdx = 0;
    while (iIdx < unit.blocks[b].code.size()) {
      iIdx = work(simplifier, b, iIdx);
    }
  }
  printUnit(kVasmSimplifyLevel, "after vasm simplify", unit);
}

}
}

max_stars_repo_name: jmarrama/hhvm

max_issues_repo_name: jmarrama/hhvm

max_forks_repo_name: jmarrama/hhvm


text:
//Save and Load for Spring 2020 CSCI 221 Deadline Project
//(Serialize and Deserialize)
//Made by Mathew Nitz

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/vector.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>

using namespace std;

// map<string, string> myMapPersonal;
// map<string, string> myMapClass;
// map<string, string> myMapPersonalHidden;
// map<string, string> myMapClassHidden;

// template <typename T, typename S>
// ostream& operator<<(ostream& os, const map<T, S>& v)
// {
//     for (auto it : v)
//         os << it.first << " , "
//            << it.second << "\n";

//     return os;
// }

void saveDeadlines()
{
	//personal
	ofstream ofile0((string)getenv("HOME") + "/personal.deadline");
	boost::archive::text_oarchive oa0(ofile0);
	oa0 << myMapPersonal;

	//personal hidden
	ofstream ofile1((string)getenv("HOME") + "/personalhidden.deadline");
	boost::archive::text_oarchive oa1(ofile1);
	oa1 << myMapPersonalHidden;

	//class
	ofstream ofile2("/var/lib/deadline/class.deadline");
	boost::archive::text_oarchive oa2(ofile2);
	oa2 << myMapClass;

	//class hidden
	ofstream ofile3("/var/lib/deadline/classhidden.deadline");
	boost::archive::text_oarchive oa3(ofile3);
	oa3 << myMapClassHidden;
}

void loadDeadlines()
{
	//personal
	ifstream file0((string)getenv("HOME") + "/personal.deadline");
	boost::archive::text_iarchive ia0(file0);
	ia0 >> myMapPersonal;
	// cout << "Personal Deadlines:\n" << myMapPersonal << endl;

	//personal hidden
	ifstream file1((string)getenv("HOME") + "/personalhidden.deadline");
	boost::archive::text_iarchive ia1(file1);
	ia1 >> myMapPersonalHidden;
	// cout << "Personal Hidden Deadlines:\n" << myMapPersonalHidden << endl;

	//class
	ifstream file2("/var/lib/deadline/class.deadline");
	boost::archive::text_iarchive ia2(file2);
	ia2 >> myMapClass;
	// cout << "Class Deadlines:\n" << myMapClass << endl;

	//class hidden
	ifstream file3("/var/lib/deadline/classhidden.deadline");
	boost::archive::text_iarchive ia3(file3);
	ia3 >> myMapClassHidden;
	// cout << "Class Hidden Deadlines:\n" << myMapClassHidden << endl;
}

int main()
{
	// myMapPersonal.insert(pair<string, string>("Walk the dog", "2020-05-24 16:35"));
	// myMapPersonalHidden.insert(pair<string, string>("Hide the dog", "2020-05-24 16:35"));
	// myMapClass.insert(pair<string, string>("Class Project", "2020-05-24 16:35"));
	// myMapClassHidden.insert(pair<string, string>("Hidden Class Project", "2020-05-24 16:35"));

	saveDeadlines();

	loadDeadlines();

}

max_stars_repo_name: StetsonMathCS/deadline

max_issues_repo_name: StetsonMathCS/deadline

max_forks_repo_name: StetsonMathCS/deadline


text:
// External libraries
#include <boost/property_tree/ptree.hpp>

// Local libraries
#include <fparameters/Dimension.h>

// Local headers
#include "Particle.h"

template<typename T> T Particle::getpar(boost::property_tree::ptree& cfg,
				const std::string &path, const T& def )
				{
					return cfg.get<T>("particle." + id + "." + path,
										cfg.get<T>("particle.default." + path, def));
				}

template int Particle::getpar<int>(boost::property_tree::ptree& cfg, const std::string &path, const int& def );
template double Particle::getpar<double>(boost::property_tree::ptree& cfg, const std::string &path, const double& def );

namespace {
	void zeroToN(Vector& v) {
		for (int i = 0; i < (int)v.size(); ++i) {
			v[i] = i;
		}
	}
}

Particle::Particle(const std::string& id):
	id(id),
 	mass{ 0.0 },
	injection{ ps, false }, // these PSVs are not initialized immediately, only after this PS has been constructed
 	distribution{ ps, false }
{
}

Particle::Particle(Particle&& other):
	ps(other.ps),
	injection(this->ps, false),
	distribution(this->ps, false),
	id(other.id),
	mass(other.mass),
	logEmax(other.logEmax),
	logEmin(other.logEmin)
{
	injection.values = std::move(other.injection.values);
	distribution.values = std::move(other.distribution.values);
}

void Particle::configure(boost::property_tree::ptree& cfg) {
	mass = cfg.get<double>("mass", mass);
	logEmin = cfg.get<double>("dim.energy.min", logEmin);
	logEmax= cfg.get<double>("dim.energy.max", logEmax);
}

void Particle::initialize() {
	injection.initialize();
	distribution.initialize();
}

Dimension* Particle::eDim() const { return ps.dimensions[0]; }


text:
#include "TimerTask.h"

#include <boost/bind.hpp>

#include <cassert>
#include <iostream>

#include <sys/time.h>

using namespace std;
namespace empool
{

    // TimeValue GetCurrentTime()
    // {
    //     struct timeval now;
    //     gettimeofday(&now, NULL);
    //     TimeValue now_in_ms = now.tv_sec;
    //     now_in_ms = now_in_ms * 1000 + now.tv_usec / 1000;
    //     return now_in_ms;
    // }

    TimerTask::TimerTask()
        : m_deadline(0), m_interval(0)
    {}

    TimeValue TimerTask::GetDeadline() const
    {
        MutexLocker lock(m_time_guard);
        return m_deadline;
    }

    void TimerTask::SetDeadline(const TimeValue deadline)
    {
        MutexLocker lock(m_time_guard);
        m_deadline = deadline;
    }

    bool TimerTask::IsIntervalTask() const
    {
        MutexLocker lock(m_time_guard);
        return m_interval > 0;
    }

    TimeValue TimerTask::GetInterval() const
    {
        MutexLocker lock(m_time_guard);
        return m_interval;
    }

    void TimerTask::SetInterval(const TimeValue interval)
    {
        MutexLocker lock(m_time_guard);
        m_interval = interval;
    }

} //namespace empool

max_stars_repo_name: zhanMingming/Empool

max_issues_repo_name: zhanMingming/Empool

max_forks_repo_name: zhanMingming/Empool


text:
//
// Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
//    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.
//

#pragma once

#include <boost/asio/steady_timer.hpp>

#include <chrono>

#include "asset/asset.hpp"
#include "observation/observation.hpp"
#include "transform.hpp"

namespace mtconnect {
  namespace pipeline {
    struct ComputeMetrics
    {
      ComputeMetrics(boost::asio::io_context::strand &st, PipelineContract *contract,
                     const std::optional<std::string> &dataItem, std::shared_ptr<size_t> &count)
        : m_count(count),
          m_contract(contract),
          m_dataItem(dataItem),
          m_strand(st),
          m_timer(st.context())
      {}

      void compute(boost::system::error_code ec);

      void stop() { m_timer.cancel(); }

      void start();

      std::shared_ptr<size_t> m_count;
      PipelineContract *m_contract {nullptr};
      std::optional<std::string> m_dataItem;
      std::chrono::time_point<std::chrono::steady_clock> m_lastTime;

      boost::asio::io_context::strand &m_strand;
      boost::asio::steady_timer m_timer;
      bool m_first {true};
      size_t m_last {0};
      double m_lastAvg {0.0};
    };

    class MeteredTransform : public Transform
    {
    public:
      MeteredTransform(const std::string &name, PipelineContextPtr context,
                       const std::optional<std::string> &metricsDataItem = std::nullopt)
        : Transform(name),
          m_contract(context->m_contract.get()),
          m_count(std::make_shared<size_t>(0)),
          m_dataItem(metricsDataItem)
      {}

      ~MeteredTransform() override
      {
        if (m_metrics)
          m_metrics->stop();
      }

      void stop() override
      {
        if (m_metrics)
          m_metrics->stop();

        Transform::stop();
      }

      void start(boost::asio::io_context::strand &st) override
      {
        if (m_dataItem)
        {
          m_metrics = std::make_shared<ComputeMetrics>(st, m_contract, m_dataItem, m_count);
          m_metrics->start();
        }
        Transform::start(st);
      }

    protected:
      friend struct ComputeMetrics;

      PipelineContract *m_contract;
      std::shared_ptr<size_t> m_count;
      std::shared_ptr<ComputeMetrics> m_metrics;
      std::optional<std::string> m_dataItem;
    };

    class DeliverObservation : public MeteredTransform
    {
    public:
      using Deliver = std::function<void(observation::ObservationPtr)>;
      DeliverObservation(PipelineContextPtr context,
                         const std::optional<std::string> &metricDataItem = std::nullopt)
        : MeteredTransform("DeliverObservation", context, metricDataItem)
      {
        m_guard = TypeGuard<observation::Observation>(RUN);
      }
      const entity::EntityPtr operator()(const entity::EntityPtr entity) override;
    };

    class DeliverAsset : public MeteredTransform
    {
    public:
      using Deliver = std::function<void(asset::AssetPtr)>;
      DeliverAsset(PipelineContextPtr context,
                   const std::optional<std::string> &metricsDataItem = std::nullopt)
        : MeteredTransform("DeliverAsset", context, metricsDataItem)
      {
        m_guard = TypeGuard<asset::Asset>(RUN);
      }
      const entity::EntityPtr operator()(const entity::EntityPtr entity) override;
    };

    class DeliverConnectionStatus : public Transform
    {
    public:
      using Deliver = std::function<void(entity::EntityPtr)>;
      DeliverConnectionStatus(PipelineContextPtr context, const StringList &devices,
                              bool autoAvailable)
        : Transform("DeliverConnectionStatus"),
          m_contract(context->m_contract.get()),
          m_devices(devices),
          m_autoAvailable(autoAvailable)
      {
        m_guard = EntityNameGuard("ConnectionStatus", RUN);
      }
      const entity::EntityPtr operator()(const entity::EntityPtr entity) override;

    protected:
      PipelineContract *m_contract;
      std::list<std::string> m_devices;
      bool m_autoAvailable;
    };

    class DeliverAssetCommand : public Transform
    {
    public:
      using Deliver = std::function<void(entity::EntityPtr)>;
      DeliverAssetCommand(PipelineContextPtr context)
        : Transform("DeliverAssetCommand"), m_contract(context->m_contract.get())
      {
        m_guard = EntityNameGuard("AssetCommand", RUN);
      }
      const entity::EntityPtr operator()(const entity::EntityPtr entity) override;

    protected:
      PipelineContract *m_contract;
    };

    class DeliverCommand : public Transform
    {
    public:
      using Deliver = std::function<void(entity::EntityPtr)>;
      DeliverCommand(PipelineContextPtr context, const std::optional<std::string> &device)
        : Transform("DeliverCommand"),
          m_contract(context->m_contract.get()),
          m_defaultDevice(device)
      {
        m_guard = EntityNameGuard("Command", RUN);
      }
      const entity::EntityPtr operator()(const entity::EntityPtr entity) override;

    protected:
      PipelineContract *m_contract;
      std::optional<std::string> m_defaultDevice;
    };
  }  // namespace pipeline
}  // namespace mtconnect

max_stars_repo_name: bburns/cppagent

max_issues_repo_name: bburns/cppagent

max_forks_repo_name: bburns/cppagent


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   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
//==============================================================================
#define NT2_UNIT_MODULE "boost::simd::meta::as_integer SIMD"

#include <boost/simd/sdk/simd/native.hpp>
#include <boost/simd/sdk/simd/pack.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <boost/type_traits/is_same.hpp>

#include <nt2/sdk/unit/tests/basic.hpp>
#include <nt2/sdk/unit/module.hpp>

////////////////////////////////////////////////////////////////////////////////
// Test that as_integer on SIMD with unsigned target
////////////////////////////////////////////////////////////////////////////////
NT2_TEST_CASE_TPL(as_uinteger_simd_native, BOOST_SIMD_TYPES)
{
  using boost::simd::native;
  using boost::dispatch::meta::as_integer;
  using boost::is_same;
  using boost::mpl::_;

  typedef BOOST_SIMD_DEFAULT_EXTENSION                ext_t;
  typedef native<typename as_integer<T,unsigned>::type,ext_t> dst_t;

  NT2_TEST( (is_same< typename as_integer<native<T,ext_t>,unsigned>::type
                    , dst_t
                    >::value
            )
          );
}

////////////////////////////////////////////////////////////////////////////////
// Test that as_integer on pack with signed target
////////////////////////////////////////////////////////////////////////////////
NT2_TEST_CASE_TPL(as_integer_simd_pack, BOOST_SIMD_TYPES)
{
  using boost::simd::pack;
  using boost::dispatch::meta::as_integer;
  using boost::is_same;
  using boost::mpl::_;

  typedef pack<typename as_integer<T,signed>::type>   dst_t;

  NT2_TEST( (is_same< typename as_integer< pack<T>,signed >::type
                    , dst_t
                    >::value
            )
          );
}


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman
    Copyright (c) 2011 Thomas Bernard

    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 <string>
#include <vector>

#include <boost/detail/lightweight_test.hpp>
#include <boost/utility/enable_if.hpp>

#include <boost/spirit/include/qi_operator.hpp>
#include <boost/spirit/include/qi_char.hpp>
#include <boost/spirit/include/qi_string.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/qi_directive.hpp>
#include <boost/spirit/include/qi_action.hpp>
#include <boost/spirit/include/support_argument.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_container.hpp>
#include <boost/spirit/repository/include/qi_kwd.hpp>
#include <boost/spirit/repository/include/qi_keywords.hpp>

#include <string>
#include <iostream>
#include "test.hpp"

struct x_attr
{

};

namespace boost { namespace spirit { namespace traits
{

    template <>
    struct container_value<x_attr>
    {
        typedef char type; // value type of container
    };

    template <>
    struct push_back_container<x_attr, char>
    {
        static bool call(x_attr& /*c*/, char /*val*/)
        {
            // push back value type into container
            return true;
        }
    };
}}}

int
main()
{
    using spirit_test::test_attr;
    using spirit_test::test;
    using namespace boost::spirit;
    using namespace boost::spirit::ascii;
    using boost::spirit::repository::kwd;
    using boost::spirit::repository::ikwd;
    using boost::spirit::qi::inf;
    using boost::spirit::qi::omit;
    using boost::spirit::qi::int_;
    using boost::spirit::qi::lit;
    using boost::spirit::qi::_1;
    using boost::spirit::qi::lexeme;

    {

        // no constraints
        boost::fusion::vector<char,char,int> data;
        BOOST_TEST( test_attr("c=1 a=a", kwd("a")[ '=' > char_] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_], data, space));
        BOOST_TEST( test("a=a c=1", kwd("a")[ '=' > char_] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_], space));

        // Exact
        BOOST_TEST(test("a=a b=b c=1", kwd("a",1)[ '=' > char_] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_], space));
        BOOST_TEST(test("a=a b=c b=e c=1", kwd("a",1)[ '=' > char_] / kwd("b",2)[ '=' > char_] / kwd("c")['=' > int_], space));
        BOOST_TEST(!test("b=c b=e c=1", kwd("a",1)[ '=' > char_] / kwd("b",2)[ '=' > char_] / kwd("c")['=' > int_], space));

        // Min - Max
        BOOST_TEST(test("a=f b=c b=e c=1", kwd("a",1,2)[ '=' > char_] / kwd("b",0,2)[ '=' > char_] / kwd("c",1,2)['=' > int_], space));
        BOOST_TEST(!test("b=c b=e c=1", kwd("a",1,2)[ '=' > char_] / kwd("b",0,1)[ '=' > char_] / kwd("c",1,2)['=' > int_], space));
        BOOST_TEST(test("a=g a=f b=c b=e c=1", kwd("a",1,2)[ '=' > char_] / kwd("b",0,2)[ '=' > char_] / kwd("c",1,2)['=' > int_], space));
        BOOST_TEST(!test("a=f a=e b=c b=e a=p c=1", kwd("a",1,2)[ '=' > char_] / kwd("b",0,1)[ '=' > char_] / kwd("c",1,2)['=' > int_], space));

        // Min - inf
        BOOST_TEST(test("a=f b=c b=e c=1", kwd("a",1,inf)[ '=' > char_] / kwd("b",0,inf)[ '=' > char_] / kwd("c",1,inf)['=' > int_], space ));
        BOOST_TEST(!test("b=c b=e c=1", kwd("a",1,inf)[ '=' > char_] / kwd("b",0,inf)[ '=' > char_] / kwd("c",1,inf)['=' > int_], space ));
        BOOST_TEST(test("a=f a=f a=g b=c b=e c=1 a=e", kwd("a",1,inf)[ '=' > char_] / kwd("b",0,inf)[ '=' > char_] / kwd("c",1,inf)['=' > int_], space ));
    }

    {   // Single keyword, empty string
        BOOST_TEST(test(" ", kwd("aad")[char_],space));
        BOOST_TEST(test("aad E ", kwd("aad")[char_],space));
        //BOOST_TEST(test("AaD E ", ikwd("aad")[char_],space));

    }

    {
        // Vector container
        boost::fusion::vector<std::vector<int>,std::vector<int>,std::vector<int> > data;
        BOOST_TEST(test_attr(" a=1 b=2 b=5 c=3",kwd("a")[ '=' > int_] / kwd("b")[ '=' > int_] / kwd("c")['=' > int_] , data, space)
                    && (boost::fusion::at_c<0>(data).size()==1)
                    && (boost::fusion::at_c<0>(data)[0]==1)

                    &&(boost::fusion::at_c<1>(data).size()==2)
                    &&(boost::fusion::at_c<1>(data)[0]==2)
                    &&(boost::fusion::at_c<1>(data)[1]==5)

                    &&(boost::fusion::at_c<2>(data).size()==1)
                    &&(boost::fusion::at_c<2>(data)[0]==3)
            );
    }

    {
        // no_case test
        BOOST_TEST( test("B=a c=1 a=E", no_case[kwd("a")[ "=E" ] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_]], space));
        BOOST_TEST( test("B=a c=1 a=e", no_case[kwd("a")[ "=E" ] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_]], space));
        BOOST_TEST( !test("B=a c=1 A=E", no_case[kwd("a")[ '=' > char_]] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_], space));
        BOOST_TEST( test("b=a c=1 A=E", no_case[kwd("a")[ '=' > char_]] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_], space));
        BOOST_TEST( !test("A=a c=1 a=E", kwd("a")[ '=' > char_] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_], space));
        BOOST_TEST( test("A=a c=1 a=E", ikwd("a")[ '=' > char_] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_], space));
        BOOST_TEST( !test("A=a C=1 a=E", ikwd("a")[ '=' > char_] / kwd("b")[ '=' > char_] / kwd("c")['=' > int_], space));
    }

    {
        // iterator restoration
        BOOST_TEST( test("a=a c=1 ba=d", (kwd("a")[ '=' > char_] / kwd("b")[ '=' > int_] / kwd("c")['=' > int_] ) | lit("ba=") > char_, space));
        BOOST_TEST( test("A=a c=1 ba=d", (ikwd("a")[ '=' > char_] / kwd("b")[ '=' > int_] / kwd("c")['=' > int_] ) | lit("ba=") > char_, space));
    }

    { // actions
        namespace phx = boost::phoenix;

        std::vector<int> v;
        BOOST_TEST(test("b=2 c=4", kwd("b")['=' > int_][phx::ref(v)=_1] / kwd("c")[ '=' > int_ ],space) &&
            v[0] == 2 );
    }

    { // attribute customization

        x_attr x;
//        test_attr("a = b c = d", kwd("a")['=' > char_] / kwd("c")['=' > char_], x);
    }

    return boost::report_errors();
}


text:
// Copyright 2009, 2010, 2011 Dean Michael Berris, Jeroen Habraken, Glyn Matthews.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt of copy at
// http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_TEST_MODULE URL Test
#include <boost/config/warning_disable.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/network/uri.hpp>
#include <boost/network/uri/uri.hpp>
#include <boost/network/uri/uri_io.hpp>
#include <boost/range/algorithm/equal.hpp>
#include <map>

using namespace boost::network;

BOOST_AUTO_TEST_CASE(basic_uri_test) {
    uri::uri instance("http://www.example.com/");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "http");
    BOOST_CHECK_EQUAL(uri::user_info(instance), "");
    BOOST_CHECK_EQUAL(uri::host(instance), "www.example.com");
    BOOST_CHECK_EQUAL(uri::port(instance), "");
    BOOST_CHECK_EQUAL(uri::path(instance), "/");
    BOOST_CHECK_EQUAL(uri::query(instance), "");
    BOOST_CHECK_EQUAL(uri::fragment(instance), "");
}

BOOST_AUTO_TEST_CASE(basic_uri_range_test) {
    uri::uri instance("http://www.example.com/");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK(instance.scheme_range());
    BOOST_CHECK(boost::equal(instance.scheme_range(), boost::as_literal("http")));
    BOOST_CHECK(!instance.user_info_range());
    BOOST_CHECK(instance.host_range());
    BOOST_CHECK(boost::equal(instance.host_range(), boost::as_literal("www.example.com")));
    BOOST_CHECK(!instance.port_range());
    BOOST_CHECK(instance.path_range());
    BOOST_CHECK(boost::equal(instance.path_range(), boost::as_literal("/")));
    BOOST_CHECK(!instance.query_range());
    BOOST_CHECK(!instance.fragment_range());
}

BOOST_AUTO_TEST_CASE(full_uri_test) {
    uri::uri instance("http://user:password@www.example.com:80/path?query#fragment");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "http");
    BOOST_CHECK_EQUAL(uri::user_info(instance), "user:password");
    BOOST_CHECK_EQUAL(uri::host(instance), "www.example.com");
    BOOST_CHECK(uri::port_us(instance));
    BOOST_CHECK_EQUAL(uri::port_us(instance).get(), 80);
    BOOST_CHECK_EQUAL(uri::port(instance), "80");
    BOOST_CHECK_EQUAL(uri::path(instance), "/path");
    BOOST_CHECK_EQUAL(uri::query(instance), "query");
    BOOST_CHECK_EQUAL(uri::fragment(instance), "fragment");
}

BOOST_AUTO_TEST_CASE(full_uri_range_test) {
    uri::uri instance("http://user:password@www.example.com:80/path?query#fragment");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK(instance.scheme_range());
    BOOST_CHECK(boost::equal(instance.scheme_range(), boost::as_literal("http")));
    BOOST_CHECK(instance.user_info_range());
    BOOST_CHECK(boost::equal(instance.user_info_range(), boost::as_literal("user:password")));
    BOOST_CHECK(instance.host_range());
    BOOST_CHECK(boost::equal(instance.host_range(), boost::as_literal("www.example.com")));
    BOOST_CHECK(instance.port_range());
    BOOST_CHECK(boost::equal(instance.port_range(), boost::as_literal("80")));
    BOOST_CHECK(instance.path_range());
    BOOST_CHECK(boost::equal(instance.path_range(), boost::as_literal("/path")));
    BOOST_CHECK(instance.query_range());
    BOOST_CHECK(boost::equal(instance.query_range(), boost::as_literal("query")));
    BOOST_CHECK(instance.fragment_range());
    BOOST_CHECK(boost::equal(instance.fragment_range(), boost::as_literal("fragment")));
}

BOOST_AUTO_TEST_CASE(mailto_test) {
    uri::uri instance("mailto:john.doe@example.com");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "mailto");
    BOOST_CHECK_EQUAL(uri::path(instance), "john.doe@example.com");
}

BOOST_AUTO_TEST_CASE(file_test) {
    uri::uri instance("file:///bin/bash");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "file");
    BOOST_CHECK_EQUAL(uri::path(instance), "/bin/bash");
}

BOOST_AUTO_TEST_CASE(xmpp_test) {
    uri::uri instance("xmpp:example-node@example.com?message;subject=Hello%20World");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "xmpp");
    BOOST_CHECK_EQUAL(uri::path(instance), "example-node@example.com");
    BOOST_CHECK_EQUAL(uri::query(instance), "message;subject=Hello%20World");
}

BOOST_AUTO_TEST_CASE(ipv4_address_test) {
    uri::uri instance("http://129.79.245.252/");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "http");
    BOOST_CHECK_EQUAL(uri::host(instance), "129.79.245.252");
    BOOST_CHECK_EQUAL(uri::path(instance), "/");
}

BOOST_AUTO_TEST_CASE(ipv6_address_test_1) {
    uri::uri instance("http://[1080:0:0:0:8:800:200C:417A]/");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "http");
    BOOST_CHECK_EQUAL(uri::host(instance), "[1080:0:0:0:8:800:200C:417A]");
    BOOST_CHECK_EQUAL(uri::path(instance), "/");
}

BOOST_AUTO_TEST_CASE(ipv6_address_test_2) {
    uri::uri instance("http://[2001:db8:85a3:8d3:1319:8a2e:370:7348]/");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "http");
    BOOST_CHECK_EQUAL(uri::host(instance), "[2001:db8:85a3:8d3:1319:8a2e:370:7348]");
    BOOST_CHECK_EQUAL(uri::path(instance), "/");
}

BOOST_AUTO_TEST_CASE(ftp_test) {
    uri::uri instance("ftp://john.doe@ftp.example.com/");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "ftp");
    BOOST_CHECK_EQUAL(uri::user_info(instance), "john.doe");
    BOOST_CHECK_EQUAL(uri::host(instance), "ftp.example.com");
    BOOST_CHECK_EQUAL(uri::path(instance), "/");
}

BOOST_AUTO_TEST_CASE(news_test) {
    uri::uri instance("news:comp.infosystems.www.servers.unix");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "news");
    BOOST_CHECK_EQUAL(uri::path(instance), "comp.infosystems.www.servers.unix");
}

BOOST_AUTO_TEST_CASE(tel_test) {
    uri::uri instance("tel:+1-816-555-1212");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "tel");
    BOOST_CHECK_EQUAL(uri::path(instance), "+1-816-555-1212");
}

BOOST_AUTO_TEST_CASE(encoded_uri_test) {
    uri::uri instance("http://www.example.com/Path%20With%20%28Some%29%20Encoded%20Characters%21");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::scheme(instance), "http");
    BOOST_CHECK_EQUAL(uri::host(instance), "www.example.com");
    BOOST_CHECK_EQUAL(uri::path(instance), "/Path%20With%20%28Some%29%20Encoded%20Characters%21");
    BOOST_CHECK_EQUAL(uri::decoded_path(instance), "/Path With (Some) Encoded Characters!");
}

BOOST_AUTO_TEST_CASE(copy_constructor_test) {
    uri::uri instance("http://www.example.com/");
    uri::uri copy = instance;
    BOOST_CHECK(instance == copy);
}

BOOST_AUTO_TEST_CASE(assignment_test) {
    uri::uri instance("http://www.example.com/");
    uri::uri copy;
    copy = instance;
    BOOST_CHECK_EQUAL(instance.string(), copy.string());
    BOOST_CHECK_EQUAL(instance, copy);
}

BOOST_AUTO_TEST_CASE(username_test) {
    uri::uri instance("ftp://john.doe:password@ftp.example.com/");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::username(instance), "john.doe");
    BOOST_CHECK_EQUAL(uri::password(instance), "password");
}

BOOST_AUTO_TEST_CASE(authority_test) {
    uri::uri instance("http://user:password@www.example.com:80/path?query#fragment");
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK_EQUAL(uri::authority(instance), "user:password@www.example.com:80");
}

BOOST_AUTO_TEST_CASE(http_query_map_test) {
    uri::uri instance("http://user:password@www.example.com:80/path?query=something#fragment");
    BOOST_REQUIRE(uri::valid(instance));

    std::map<std::string, std::string> queries;
    uri::query_map(instance, queries);
    BOOST_REQUIRE_EQUAL(queries.size(), std::size_t(1));
    BOOST_CHECK_EQUAL(queries.begin()->first, "query");
    BOOST_CHECK_EQUAL(queries.begin()->second, "something");
}

BOOST_AUTO_TEST_CASE(xmpp_query_map_test) {
    uri::uri instance("xmpp:example-node@example.com?message;subject=Hello%20World");
    BOOST_REQUIRE(uri::valid(instance));

    std::map<std::string, std::string> queries;
    uri::query_map(instance, queries);
    BOOST_REQUIRE_EQUAL(queries.size(), std::size_t(2));
    BOOST_CHECK_EQUAL(queries.begin()->first, "message");
    BOOST_CHECK_EQUAL(queries.begin()->second, "");
    BOOST_CHECK_EQUAL((++queries.begin())->first, "subject");
    BOOST_CHECK_EQUAL((++queries.begin())->second, "Hello%20World");
}

BOOST_AUTO_TEST_CASE(range_test)
{
    const std::string url("http://www.example.com/");
    uri::uri instance(url);
    BOOST_REQUIRE(uri::valid(instance));
    BOOST_CHECK(boost::equal(instance, url));
}

BOOST_AUTO_TEST_CASE(issue_67_test)
{
    const std::string site_name("http://www.google.com");
    uri::uri bar0;
    uri::uri bar1 = site_name;
    bar0 = site_name;
    BOOST_CHECK(uri::is_valid(bar0));
    BOOST_CHECK(uri::is_valid(bar1));
}

max_stars_repo_name: antoinelefloch/cpp-netlib

max_issues_repo_name: antoinelefloch/cpp-netlib

max_forks_repo_name: antoinelefloch/cpp-netlib


text:
#ifndef CAFFE_DETECTION_OUTPUT_LAYER_HPP_
#define CAFFE_DETECTION_OUTPUT_LAYER_HPP_

#ifdef WITH_JSON
#include <boost/property_tree/json_parser.hpp>
#endif
#include <boost/property_tree/ptree.hpp>
#include <boost/regex.hpp>

#include <map>
#include <string>
#include <utility>
#include <vector>

#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/bbox_util.hpp"

using namespace boost::property_tree;  // NOLINT(build/namespaces)

namespace caffe {

/**
 * @brief Generate the detection output based on location and confidence
 * predictions by doing non maximum suppression.
 *
 * Intended for use with MultiBox detection method.
 *
 * NOTE: does not implement Backwards operation.
 */
template <typename Ftype, typename Btype>
class DetectionOutputLayer : public Layer<Ftype,Btype> {
 typedef Ftype Dtype;
 public:
  explicit DetectionOutputLayer(const LayerParameter& param)
      : Layer<Ftype,Btype>(param) {}
  virtual void LayerSetUp(const vector<Blob*>& bottom,
      const vector<Blob*>& top);
  virtual void Reshape(const vector<Blob*>& bottom,
      const vector<Blob*>& top);

  virtual inline const char* type() const { return "DetectionOutput"; }
  virtual inline int MinBottomBlobs() const { return 3; }
  virtual inline int MaxBottomBlobs() const { return 4; }
  virtual inline int ExactNumTopBlobs() const { return 1; }

 protected:
  /**
   * @brief Do non maximum suppression (nms) on prediction results.
   *
   * @param bottom input Blob vector (at least 2)
   *   -# @f$ (N \times C1 \times 1 \times 1) @f$
   *      the location predictions with C1 predictions.
   *   -# @f$ (N \times C2 \times 1 \times 1) @f$
   *      the confidence predictions with C2 predictions.
   *   -# @f$ (N \times 2 \times C3 \times 1) @f$
   *      the prior bounding boxes with C3 values.
   * @param top output Blob vector (length 1)
   *   -# @f$ (1 \times 1 \times N \times 7) @f$
   *      N is the number of detections after nms, and each row is:
   *      [image_id, label, confidence, xmin, ymin, xmax, ymax]
   */
  virtual void Forward_cpu(const vector<Blob*>& bottom,
      const vector<Blob*>& top);
  virtual void Forward_gpu(const vector<Blob*>& bottom,
      const vector<Blob*>& top);
  /// @brief Not implemented
  virtual void Backward_cpu(const vector<Blob*>& top,
      const vector<bool>& propagate_down, const vector<Blob*>& bottom) {
    NOT_IMPLEMENTED;
  }
  virtual void Backward_gpu(const vector<Blob*>& top,
      const vector<bool>& propagate_down, const vector<Blob*>& bottom) {
    NOT_IMPLEMENTED;
  }

  int num_classes_;
  bool share_location_;
  int num_loc_classes_;
  int background_label_id_;
  CodeType code_type_;
  bool variance_encoded_in_target_;
  int keep_top_k_;
  float confidence_threshold_;

  int num_;
  int num_priors_;

  float nms_threshold_;
  int top_k_;
  float eta_;

  bool need_save_;
  string output_directory_;
  string output_name_prefix_;
  string output_format_;
  map<int, string> label_to_name_;
  map<int, string> label_to_display_name_;
  vector<string> names_;
  vector<pair<int, int> > sizes_;
  int num_test_image_;
  int name_count_;
  bool has_resize_;
  ResizeParameter resize_param_;

  ptree detections_;

  bool visualize_;
  float visualize_threshold_;
  shared_ptr<DataTransformer<Ftype> > data_transformer_;
  string save_file_;
  TBlob<Dtype> bbox_preds_;
  TBlob<Dtype> bbox_permute_;
  TBlob<Dtype> conf_permute_;
};

}  // namespace caffe

#endif  // CAFFE_DETECTION_OUTPUT_LAYER_HPP_

max_stars_repo_name: whitenightwu/caffe-quant-TI

max_issues_repo_name: whitenightwu/caffe-quant-TI

max_forks_repo_name: whitenightwu/caffe-quant-TI


text:
#include <omni/core/model/statement.hpp>
#include <omni/core/model/meta_info.hpp>
#include <omni/core/model/block.hpp>
#include <omni/core/model/expression.hpp>
#include <omni/core/model/if_statement.hpp>
#include <omni/core/model/return_statement.hpp>
#include <omni/core/model/while_statement.hpp>
#include <omni/core/model/do_while_statement.hpp>

#include <omni/tests/test_utils.hpp>

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE (statementTests)

BOOST_AUTO_TEST_CASE (metaInfo)
{
    using namespace omni::core::model;

    meta_info & meta = statement::getStaticMetaInfo ();
    BOOST_CHECK_EQUAL (meta.getName (), "statement");
    BOOST_CHECK_EQUAL (meta.getParent (), & scope::getStaticMetaInfo ());
    BOOST_CHECK_EQUAL (meta.getChildCount (), 6u);

    BOOST_CHECK (omni::tests::checkMetaInfoChildren (meta, {
        & block::getStaticMetaInfo (),
        & expression::getStaticMetaInfo (),
        & if_statement::getStaticMetaInfo (),
        & return_statement::getStaticMetaInfo (),
        & while_statement::getStaticMetaInfo (),
        & do_while_statement::getStaticMetaInfo ()
    }));
}

BOOST_AUTO_TEST_SUITE_END ();

max_stars_repo_name: daniel-kun/omni

max_issues_repo_name: daniel-kun/omni

max_forks_repo_name: daniel-kun/omni


text:
#include "dataslinger/backend/sharedvector/sharedvector.h"

#include <functional>

#include <boost/scope_exit.hpp>

#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/segment_manager.hpp>

#include "dataslinger/slinger.h"
#include "dataslinger/event/eventhelpers.h"

namespace
{

class SharedData
{
public:
    SharedData(boost::interprocess::managed_shared_memory::segment_manager* segmentManager) :
        m_vector(segmentManager) {}

    boost::interprocess::vector<dataslinger::message::Message, boost::interprocess::allocator<dataslinger::message::Message, boost::interprocess::managed_shared_memory::segment_manager>> m_vector;
    boost::interprocess::interprocess_mutex mutex;
    boost::interprocess::interprocess_condition cond_empty;
};

}

namespace dataslinger::sharedvector
{

class SharedVector::SharedVectorImpl
{
public:
    SharedVectorImpl(const std::function<void(const dataslinger::message::Message&)>& onReceive, const std::function<void(const dataslinger::event::Event&)>& onEvent, const dataslinger::connection::ConnectionOptions& info) : m_sharedData{nullptr}, m_onReceive{onReceive}, m_onEvent{onEvent}, m_info{info}
    {
        // Create a new segment with given name and size
        boost::interprocess::managed_shared_memory segment(boost::interprocess::create_only, "MySharedMemory", 65536);

        // Initialize shared memory STL-compatible allocator
        //boost::interprocess::allocator<SharedData, boost::interprocess::managed_shared_memory::segment_manager> allocatorInstance();

        // Construct shared data in shared memory
        //m_sharedData = segment.construct<SharedData>("MySharedData")(allocatorInstance);
    }

    ~SharedVectorImpl()
    {
        boost::interprocess::shared_memory_object::remove("MySharedMemory");
    }

    SharedVectorImpl(const SharedVectorImpl&) = delete;
    SharedVectorImpl& operator=(const SharedVectorImpl&) = delete;
    SharedVectorImpl(SharedVectorImpl&&) = default;
    SharedVectorImpl& operator=(SharedVectorImpl&&) = default;

    void run()
    {
    }

    void send(const dataslinger::message::Message& /*message*/)
    {
    }

    void poll()
    {
    }

private:
    SharedData* m_sharedData;

    const std::function<void(const dataslinger::message::Message&)> m_onReceive; ///< Callback triggered when the slinger receives a message
    const std::function<void(const dataslinger::event::Event&)> m_onEvent; ///< Callback triggered when the slinger produces an event
    const dataslinger::connection::ConnectionOptions m_info; ///< Connection info
};

SharedVector::SharedVector(const std::function<void(const dataslinger::message::Message&)>& onReceive, const std::function<void(const dataslinger::event::Event&)>& onEvent, const dataslinger::connection::ConnectionOptions& info) : d{std::make_unique<SharedVectorImpl>(onReceive, onEvent, info)}
{
}

SharedVector::~SharedVector()
{
}

void SharedVector::run()
{
    d->run();
}

void SharedVector::send(const dataslinger::message::Message& message)
{
    d->send(message);
}

void SharedVector::poll()
{
    d->poll();
}

}


text: #include <boost/bimap/container_adaptor/map_adaptor.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "mArchitecture.h"
#include "mCircuit.h"

#include <list>
#include <map>
#include <string>
#include <iostream>

#include <boost/range.hpp>

int main()
{

    std::map<int,std::list<int>> back;

    back[1].push_back(0);

    back[2].push_back(0);
    back[2].push_back(1);

    back[3].push_back(2);

    back[4].push_back(2);
    back[4].push_back(3);

    //back[4].push_back(4);

    mArchitecture b(back);

    std::list<std::string> lines;
    //lines.push_back("H q[2];");
    lines.push_back("CX q[4],q[0];");
    lines.push_back("H q[2];");
    //lines.push_back("CX q[2],q[1];");
    lines.push_back("H q[2];");
    //lines.push_back("CX q[2],q[3];");
    //lines.push_back("H q[2];");
    //lines.push_back("CX q[2],q[4];");
    //lines.push_back("H q[2];");

    //lines.push_back("CX q[1],q[0];");

    //lines.push_back("");
    //lines.push_back("");
    //lines.push_back("");
    //lines.push_back("");

    mCircuit circ(b,lines);

    std::cout << "backend: "<< std::endl;
    for(std::map<int,std::list<int>>::value_type lists : b.connection){
        for(int i : lists.second){
            std::cout << lists.first << " --> " << i << std::endl;
            std::cout << circ.GetBackEnd().indexVertexTable[lists.first] << std::endl;
            std::cout << circ.GetBackEnd().indexVertexTable[i] << std::endl;
        }
    }

    std::cout << "edges: " << std::endl;

    std::cout << circ.GetBackEnd().generalGraph.num_edges() << std::endl;

    std::cout << "predicessor" << std::endl;
    std::map<int,int> predecessors = circ.GetBackEnd().getIndexedPredecessorMap(circ.GetBackEnd().getPredecessorMapFrom(0));

    mArchitecture arc = circ.GetBackEnd();
    for(std::map<int,int>::value_type v : predecessors)
    {

        std::cout << v.first << " pred " << v.second << std::endl;
    }

    std::cout << circ.GetGates() << std::endl;

    std::cout << "my dictioary: " << back.size() << std::endl;

    std::cout << "Count of Vertecies: " << circ.GetBackEnd().indexVertexTable.size() << std::endl;

    std::cout << "Count of connections: " << circ.GetBackEnd().connection.size() << std::endl;

    //std::cout << "distances: " << boost::size(circ.GetBackEnd().distances) << std::endl;

    std::cout << "Architecture Fitting: " << circ.Fit() << std::endl;

    std::cout << circ.GetGates() << std::endl;

    std::cout << "Auto Collapse!" << std::endl;

    circ.AutoCollapse();

    std::cout << circ.GetGates() << std::endl;

    std::cout << "It works a bit" << std::endl;

    return 0;
}

max_stars_repo_name: CptKappa/qiskit-api-cpp

max_issues_repo_name: CptKappa/qiskit-api-cpp

max_forks_repo_name: CptKappa/qiskit-api-cpp