text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test

// Copyright (c) 2010-2015 Barend Gehrels, Amsterdam, the Netherlands.

// This file was modified by Oracle on 2016.
// Modifications copyright (c) 2016, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <iostream>
#include <string>

#include "test_intersection.hpp"
#include <algorithms/test_overlay.hpp>
#include <algorithms/overlay/multi_overlay_cases.hpp>

#include <boost/geometry/algorithms/correct.hpp>
#include <boost/geometry/algorithms/intersection.hpp>

#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/multi_point.hpp>
#include <boost/geometry/geometries/multi_linestring.hpp>
#include <boost/geometry/geometries/multi_polygon.hpp>

#include <boost/geometry/io/wkt/read.hpp>

#define TEST_INTERSECTION(caseid, clips, points, area) \
    (test_one<Polygon, MultiPolygon, MultiPolygon>) \
    ( #caseid, caseid[0], caseid[1], clips, points, area)

#define TEST_INTERSECTION_IGNORE(caseid, clips, points, area) \
    (test_one<Polygon, MultiPolygon, MultiPolygon>) \
    ( #caseid, caseid[0], caseid[1], clips, points, area, ignore_validity)

template <typename Ring, typename Polygon, typename MultiPolygon>
void test_areal()
{
    ut_settings ignore_validity;
    ignore_validity.test_validity = false;

    test_one<Polygon, MultiPolygon, MultiPolygon>("simplex_multi",
        case_multi_simplex[0], case_multi_simplex[1],
        2, 12, 6.42);

    test_one<Polygon, MultiPolygon, MultiPolygon>("case_multi_no_ip",
        case_multi_no_ip[0], case_multi_no_ip[1],
        2, 8, 8.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_multi_2",
        case_multi_2[0], case_multi_2[1],
        3, 12, 5.9);

    test_one<Polygon, MultiPolygon, Polygon>("simplex_multi_mp_p",
        case_multi_simplex[0], case_single_simplex,
        2, 12, 6.42);

    test_one<Polygon, Ring, MultiPolygon>("simplex_multi_r_mp",
        case_single_simplex, case_multi_simplex[0],
        2, 12, 6.42);
    test_one<Ring, MultiPolygon, Polygon>("simplex_multi_mp_r",
        case_multi_simplex[0], case_single_simplex,
        2, 12, 6.42);

    test_one<Polygon, MultiPolygon, MultiPolygon>("case_58_multi_a",
        case_58_multi[0], case_58_multi[3],
        3, 12, 0.666666667);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_58_multi_b",
        case_58_multi[1], case_58_multi[2],
        1, 19, 11.16666666667);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_58_multi_b4",
        case_58_multi[4], case_58_multi[2],
        1, 13, 12.66666666);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_58_multi_b5",
        case_58_multi[5], case_58_multi[2],
        1, 13, 13.25);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_58_multi_b6",
        case_58_multi[6], case_58_multi[2],
        1, 13, 13.25);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_58_multi_b7",
        case_58_multi[7], case_58_multi[2],
        1, 16, 12.5);

    // Constructed cases for multi/touch/equal/etc
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_61_multi",
        case_61_multi[0], case_61_multi[1],
        0, 0, 0.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_62_multi",
        case_62_multi[0], case_62_multi[1],
        1, 5, 1.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_63_multi",
        case_63_multi[0], case_63_multi[1],
        1, 5, 1.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_64_multi",
        case_64_multi[0], case_64_multi[1],
        1, 5, 1.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_65_multi",
        case_65_multi[0], case_65_multi[1],
        1, 5, 1.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_65_multi_inv_a",
        case_65_multi[0], case_65_multi[3],
        0, 0, 0.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_65_multi_inv_b",
        case_65_multi[1], case_65_multi[2],
        2, 10, 3.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_72_multi",
        case_72_multi[0], case_72_multi[1],
        3, 14, 2.85);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_72_multi_inv_b",
        case_72_multi[1], case_72_multi[2],
        3, 16, 6.15);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_77_multi",
        case_77_multi[0], case_77_multi[1],
        5, 33, 9.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_78_multi",
        case_78_multi[0], case_78_multi[1],
        1, 16, 22.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_101_multi",
        case_101_multi[0], case_101_multi[1],
        4, 22, 4.75);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_102_multi",
        case_102_multi[0], case_102_multi[1],
        3, 26, 19.75);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_102_multi_inv_b",
        case_102_multi[1], case_102_multi[2],
        3, 25, 3.75, ignore_validity);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_107_multi",
        case_107_multi[0], case_107_multi[1],
        2, 10, 1.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_107_multi_inv_b",
        case_107_multi[1], case_107_multi[2],
        3, 13, 3.0);

#ifdef BOOST_GEOMETRY_TEST_INCLUDE_FAILING_TESTS
    // One intersection is missing (by rescaling)
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_108_multi",
        case_108_multi[0], case_108_multi[1],
        5, 33, 7.5,
        ignore_validity);
#endif

    TEST_INTERSECTION(case_123_multi, 3, 13, 1.875);
    TEST_INTERSECTION(case_124_multi, 2, 13, 2.0625);
    TEST_INTERSECTION_IGNORE(case_125_multi, 3, 17, 2.1);

    // #1 needs self-turns to make valid
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_1",
        case_recursive_boxes_1[0], case_recursive_boxes_1[1],
        8, 97, 47.0, ignore_validity);

    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_2",
        case_recursive_boxes_2[0], case_recursive_boxes_2[1],
        1, 50, 90.0); // Area from SQL Server
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_3",
        case_recursive_boxes_3[0], case_recursive_boxes_3[1],
        19, 87, 12.5); // Area from SQL Server

    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_4",
        case_recursive_boxes_4[0], case_recursive_boxes_4[1],
        8, 179, 67.0, // Area from SQL Server
        ignore_validity);

    // Fixed by replacing handle_tangencies in less_by_segment_ratio sort order
    // Should contain 6 output polygons
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_6",
        case_recursive_boxes_6[0], case_recursive_boxes_6[1],
        6, 47, 19.0);

    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_7",
        case_recursive_boxes_7[0], case_recursive_boxes_7[1],
        2, 9, 1.5);

    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_8",
        case_recursive_boxes_8[0], case_recursive_boxes_8[1],
        3, 19, 3.75);

    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_9",
        case_recursive_boxes_9[0], case_recursive_boxes_9[1],
        5, 27, 4.25);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_10",
        case_recursive_boxes_10[0], case_recursive_boxes_10[1],
        2, 8, 0.75);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_11",
        case_recursive_boxes_11[0], case_recursive_boxes_11[1],
        2, 8, 1.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_12",
        case_recursive_boxes_12[0], case_recursive_boxes_12[1],
        1, 4, 0.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_13",
        case_recursive_boxes_13[0], case_recursive_boxes_13[1],
        0, 0, 0.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_14",
        case_recursive_boxes_14[0], case_recursive_boxes_14[1],
        0, 0, 0.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_15",
        case_recursive_boxes_15[0], case_recursive_boxes_15[1],
        1, 4, 0.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_16",
        case_recursive_boxes_16[0], case_recursive_boxes_16[1],
        9, 43, 10.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_17",
        case_recursive_boxes_17[0], case_recursive_boxes_17[1],
        7, -1, 7.75);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_18",
        case_recursive_boxes_18[0], case_recursive_boxes_18[1],
        0, 0, 0.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_19",
        case_recursive_boxes_19[0], case_recursive_boxes_19[1],
        0, 0, 0.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_20",
        case_recursive_boxes_20[0], case_recursive_boxes_20[1],
        2, 0, 1.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_21",
        case_recursive_boxes_21[0], case_recursive_boxes_21[1],
        1, 0, 0.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_22",
        case_recursive_boxes_22[0], case_recursive_boxes_22[1],
        0, 0, 0.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_23",
        case_recursive_boxes_23[0], case_recursive_boxes_23[1],
        1, 0, 0.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_24",
        case_recursive_boxes_24[0], case_recursive_boxes_24[1],
        1, 0, 0.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_25",
        case_recursive_boxes_25[0], case_recursive_boxes_25[1],
        1, 0, 0.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_26",
        case_recursive_boxes_26[0], case_recursive_boxes_26[1],
        1, 0, 2.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_27",
        case_recursive_boxes_27[0], case_recursive_boxes_27[1],
        1, 0, 0.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_28",
        case_recursive_boxes_28[0], case_recursive_boxes_28[1],
        2, 0, 1.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_29",
        case_recursive_boxes_29[0], case_recursive_boxes_29[1],
        5, 0, 3.75);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_30",
        case_recursive_boxes_30[0], case_recursive_boxes_30[1],
        4, 0, 6.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_31",
        case_recursive_boxes_31[0], case_recursive_boxes_31[1],
        2, 0, 2.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_32",
        case_recursive_boxes_32[0], case_recursive_boxes_32[1],
        2, 0, 1.75);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_33",
        case_recursive_boxes_33[0], case_recursive_boxes_33[1],
        3, 0, 2.0);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_34",
        case_recursive_boxes_34[0], case_recursive_boxes_34[1],
        2, 0, 17.25);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_35",
        case_recursive_boxes_35[0], case_recursive_boxes_35[1],
        1, 0, 20.0,
        ignore_validity);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_36",
        case_recursive_boxes_36[0], case_recursive_boxes_36[1],
        1, 0, 0.5);
    test_one<Polygon, MultiPolygon, MultiPolygon>("case_recursive_boxes_37",
        case_recursive_boxes_37[0], case_recursive_boxes_37[1],
        2, 0, 1.0);

    TEST_INTERSECTION(case_recursive_boxes_39, 3, 0, 3.00);
    TEST_INTERSECTION(case_recursive_boxes_40, 1, 0, 1.00);

    test_one<Polygon, MultiPolygon, MultiPolygon>("ggl_list_20120915_h2_a",
        ggl_list_20120915_h2[0], ggl_list_20120915_h2[1],
        2, 10, 6.0); // Area from SQL Server
    test_one<Polygon, MultiPolygon, MultiPolygon>("ggl_list_20120915_h2_b",
        ggl_list_20120915_h2[0], ggl_list_20120915_h2[2],
        2, 10, 6.0); // Area from SQL Server

    test_one<Polygon, MultiPolygon, MultiPolygon>("ticket_9081",
        ticket_9081[0], ticket_9081[1],
        2, 10, 0.0019812556);

    // qcc-arm reports 1.7791215549400884e-14
    test_one<Polygon, MultiPolygon, MultiPolygon>("ticket_11018",
        ticket_11018[0], ticket_11018[1],
        1, 4,
#ifdef BOOST_GEOMETRY_NO_ROBUSTNESS
        9.896437631745599e-09
#else
        1.7791170511070893e-14, ut_settings(0.001)
#endif

    );

    test_one<Polygon, MultiPolygon, MultiPolygon>("mysql_23023665_7",
        mysql_23023665_7[0], mysql_23023665_7[1],
        2, 11, 9.80505786783);

    test_one<Polygon, MultiPolygon, MultiPolygon>("mysql_23023665_12",
        mysql_23023665_12[0], mysql_23023665_12[1],
        1, -1, 11.812440191387557,
        ignore_validity);
}

template <typename Polygon, typename MultiPolygon, typename Box>
void test_areal_clip()
{
    static std::string const clip = "POLYGON((1 1,4 4))";
    test_one<Polygon, Box, MultiPolygon>("simplex_multi_mp_b", clip, case_multi_simplex[0],
        2, 11, 6.791666);
    test_one<Polygon, MultiPolygon, Box>("simplex_multi_b_mp", case_multi_simplex[0], clip,
        2, 11, 6.791666);
}

template <typename LineString, typename MultiLineString, typename Box>
void test_linear()
{
    typedef typename bg::point_type<MultiLineString>::type point;
    test_one<point, MultiLineString, MultiLineString>("case_multi_ml_ml_1",
        "MULTILINESTRING((0 0,1 1))", "MULTILINESTRING((0 1,1 0))",
        1, 1, 0.0);
    test_one<point, MultiLineString, MultiLineString>("case_multi_ml_ml_2",
        "MULTILINESTRING((0 0,1 1),(0.5 0,1.5 1))", "MULTILINESTRING((0 1,1 0),(0.5 1,1.5 0))",
        4, 4, 0.0);

    test_one<point, LineString, MultiLineString>("case_multi_l_ml",
        "LINESTRING(0 0,1 1)", "MULTILINESTRING((0 1,1 0),(0.5 1,1.5 0))",
        2, 2, 0.0);
    test_one<point, MultiLineString, LineString>("case_multi_ml_l",
        "MULTILINESTRING((0 1,1 0),(0.5 1,1.5 0))", "LINESTRING(0 0,1 1)",
        2, 2, 0.0);

    test_one<LineString, MultiLineString, Box>("case_multi_ml_b",
        "MULTILINESTRING((0 0,3 3)(1 0,4 3))", "POLYGON((1 1,3 2))",
        2, 4, 2.0 * std::sqrt(2.0));
    test_one<LineString, Box, MultiLineString>("case_multi_b_ml",
        "POLYGON((1 1,3 2))", "MULTILINESTRING((0 0,3 3)(1 0,4 3))",
        2, 4, 2.0 * std::sqrt(2.0));
}

template <typename P>
void test_point_output()
{
    typedef bg::model::box<P> box;
    typedef bg::model::linestring<P> linestring;
    typedef bg::model::polygon<P> polygon;
    typedef bg::model::multi_polygon<polygon> multi_polygon;

    test_point_output<multi_polygon, multi_polygon>(case_multi_simplex[0], case_multi_simplex[1], 10);
    test_point_output<linestring, multi_polygon>("linestring(4 0,0 4)", case_multi_simplex[0], 4);
    test_point_output<box, multi_polygon>("box(3 0,4 6)", case_multi_simplex[0], 8);
}

template <typename MultiPolygon, typename MultiLineString>
void test_areal_linear()
{
    typedef typename boost::range_value<MultiPolygon>::type Polygon;
    typedef typename boost::range_value<MultiLineString>::type LineString;
    typedef typename bg::point_type<Polygon>::type Point;
    typedef bg::model::ring<Point> Ring;

    test_one_lp<LineString, MultiPolygon, LineString>("case_mp_ls_1", case_multi_simplex[0], "LINESTRING(2 0,2 5)", 2, 4, 3.70);
    test_one_lp<LineString, Polygon, MultiLineString>("case_p_mls_1", case_single_simplex, "MULTILINESTRING((2 0,2 5),(3 0,3 5))", 2, 4, 7.5);
    test_one_lp<LineString, MultiPolygon, MultiLineString>("case_mp_mls_1", case_multi_simplex[0], "MULTILINESTRING((2 0,2 5),(3 0,3 5))", 4, 8, 6.8333333);
    test_one_lp<LineString, Ring, MultiLineString>("case_r_mls_1", case_single_simplex, "MULTILINESTRING((2 0,2 5),(3 0,3 5))", 2, 4, 7.5);
}

template <typename P>
void test_all()
{
    typedef bg::model::ring<P> ring;
    typedef bg::model::polygon<P> polygon;
    typedef bg::model::multi_polygon<polygon> multi_polygon;
    test_areal<ring, polygon, multi_polygon>();

#if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE)

    typedef bg::model::ring<P, false> ring_ccw;
    typedef bg::model::polygon<P, false> polygon_ccw;
    typedef bg::model::multi_polygon<polygon_ccw> multi_polygon_ccw;
    test_areal<ring_ccw, polygon_ccw, multi_polygon_ccw>();

    typedef bg::model::ring<P, true, false> ring_open;
    typedef bg::model::polygon<P, true, false> polygon_open;
    typedef bg::model::multi_polygon<polygon_open> multi_polygon_open;
    test_areal<ring_open, polygon_open, multi_polygon_open>();

    typedef bg::model::ring<P, false, false> ring_open_ccw;
    typedef bg::model::polygon<P, false, false> polygon_open_ccw;
    typedef bg::model::multi_polygon<polygon_open_ccw> multi_polygon_open_ccw;
    test_areal<ring_open_ccw, polygon_open_ccw, multi_polygon_open_ccw>();

    typedef bg::model::box<P> box;
    test_areal_clip<polygon, multi_polygon, box>();
    test_areal_clip<polygon_ccw, multi_polygon_ccw, box>();

    typedef bg::model::linestring<P> linestring;
    typedef bg::model::multi_linestring<linestring> multi_linestring;

    test_linear<linestring, multi_linestring, box>();
    test_areal_linear<multi_polygon, multi_linestring>();
#endif

    test_point_output<P>();
    // linear

}

int test_main(int, char* [])
{
    test_all<bg::model::d2::point_xy<double> >();

#if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE)
    test_all<bg::model::d2::point_xy<float> >();

#if defined(HAVE_TTMATH)
    std::cout << "Testing TTMATH" << std::endl;
    test_all<bg::model::d2::point_xy<ttmath_big> >();
#endif

#endif

    return 0;
}


text:
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software. See LICENSE.txt for details.
//
// Author: Denis Bueno

#include "step_refiner.h"

#include <boost/algorithm/cxx11/any_of.hpp>

#include "checkersat.h"
#include "supp/reachability_graph.h"
#include "tslice.h"

namespace euforia {

//! Checks feasibility of T & (z - i -> s+). Returns either an unsat core if
//! step is infeasible, or nothing if it is feasible
boost::optional<ExprSet> StepRefiner::operator()() {
  auto model_falsifies = [&](auto&& lemma) {
    return is_literal_false(step_.step_model().Eval(lemma->as_expr()));
  };
  if (boost::algorithm::any_of(achk_.recent_lemmas(), model_falsifies)) {
    logger.Log(3,
               "skipping refining step {} because model falsifies lemma",
               step_.next_state_index());
    return boost::none;
  }

  boost::optional<ExprSet> ret;
  vector<z3::expr> assumptions;

  auto Concretize = [&](auto&& e) {
    return axsys_.Concretize(e);
  };
  auto& z_hat = step_.state();
  transform(z_hat.begin(), z_hat.end(), back_inserter(assumptions),
            Concretize);
  auto& i_hat = step_.input();
  transform(i_hat.begin(), i_hat.end(), back_inserter(assumptions),
            Concretize);
  auto& s_next_hat = step_.state_transition().target_constraints;
  transform(s_next_hat.begin(), s_next_hat.end(), back_inserter(assumptions),
            Concretize);
  // T -- projected by model
  auto& transition_model = step_.step_model();
  copy_trans_predicates(transition_model, back_inserter(assumptions));
  if (!LOG_DIR.empty()) {
    auto benchmark_name = fmt::format(
        "{}/ref{}-step{}-{}.{}.smt2", LOG_DIR, num_refinements_+1,
        step_.state_index(), step_.next_state_index(),
        solver_->version());
    ofstream outfile(benchmark_name);
    fmt::print(outfile, "; {} input constraints\n", i_hat.size());
    fmt::print(outfile, "; {} target constraints\n", s_next_hat.size());
    fmt::print(outfile, "; {} assumptions\n", assumptions.size());
    // fmt::print(outfile, "; {} trans constraints\n", num_trans_predicates);
    solver().DumpBenchmark(outfile, assumptions);
    logger.Log(3, "logging benchmark {}", benchmark_name);
  }
  stats() = CalculateStats(assumptions);
  TimerDuration d(0); {
    ScopedTimeKeeper step_time(&d);
    BTOR_LOG_UP(kBtorLogLevel);
    auto feasible = solver().Check(assumptions) == CheckResult::kSat;
    BTOR_LOG_DOWN();
    auto diff = step_time.Get();
    if (!feasible) {
      logger.Log(3, "A[{}] & In[{}] & T & A[{}]+ is CUNSAT [{} s]",
                 step_.state_index(), step_.input_index(), step_.next_state_index(),
                 diff.count());
      auto core = solver().unsat_core();
      ret = ExprSet(core.begin(), core.end());
    } else {
      logger.Log(3, "A[{}] & In[{}] & T & A[{}]+ is CSAT [{} s]",
                 step_.state_index(), step_.input_index(), step_.next_state_index(),
                 diff.count());
    }
  }
  return ret;
}

void StepRefiner::ValidateLemma(const AbstractLemmaClause& lemma) {
  assert(is_literal_false(step_.step_model().Eval(lemma.as_expr())));
  z3::expr transition(axsys_.ctx());
  boost::copy(step_.state(), ExprAndInserter(transition));
  boost::copy(step_.input(), ExprAndInserter(transition));
  boost::copy(step_.state_transition().target_constraints,
              ExprAndInserter(transition));
  copy_trans_predicates(step_.step_model(), ExprAndInserter(transition));
  achk_.ValidateLemma(lemma, transition);
}

//^----------------------------------------------------------------------------^

boost::optional<ExprSet> StepRefinerWithoutT::operator()() {
  boost::optional<ExprSet> ret;
  vector<z3::expr> assumptions;

  auto Concretize = [&](auto&& e) {
    return axsys_.Concretize(e);
  };
  auto& z_hat = step_.state();
  transform(z_hat.begin(), z_hat.end(), back_inserter(assumptions),
            Concretize);
  auto& i_hat = step_.input();
  transform(i_hat.begin(), i_hat.end(), back_inserter(assumptions),
            Concretize);
  auto& s_next_hat = step_.state_transition().target_constraints;
  transform(s_next_hat.begin(), s_next_hat.end(), back_inserter(assumptions),
            Concretize);

  if (!LOG_DIR.empty()) {
    auto benchmark_name = fmt::format("{}/ref{}-step{}-{}-without-t.smt2",
                                      LOG_DIR, num_refinements_+1,
                                      step_.state_index(),
                                      step_.next_state_index());
    ofstream outfile(benchmark_name);
    fmt::print(outfile, "; {} input constraints\n", i_hat.size());
    fmt::print(outfile, "; {} target constraints\n", s_next_hat.size());
    fmt::print(outfile, "; {} assumptions\n", assumptions.size());
    // fmt::print(outfile, "; {} trans constraints\n", num_trans_predicates);
    solver().DumpBenchmark(outfile, assumptions);
    logger.Log(3, "logging benchmark {}", benchmark_name);
  }
  stats() = CalculateStats(assumptions);
  TimerDuration d(0);
  ScopedTimeKeeper step_time(&d);
  BTOR_LOG_UP(kBtorLogLevel);
  auto feasible = solver().Check(assumptions) == CheckResult::kSat;
  BTOR_LOG_DOWN();
  auto diff = step_time.Get();
  if (!feasible) {
    logger.Log(3, "A[{}] & In[{}] & A[{}]+ is CUNSAT [{} s]",
               step_.state_index(), step_.input_index(),
               step_.next_state_index(), diff.count());
    auto core = solver().unsat_core();
    ret = ExprSet(core.begin(), core.end());
  } else {
    logger.Log(3, "A[{}] & In[{}] & A[{}]+ is CSAT [{} s]",
               step_.state_index(), step_.input_index(),
               step_.next_state_index(), diff.count());
    // XXX make the next state? return that?
  }
  return ret;
}

void StepRefinerWithoutT::ValidateLemma(const AbstractLemmaClause& lemma) {
  assert(is_literal_false(step_.step_model().Eval(lemma.as_expr())));
  z3::expr transition(axsys_.ctx());
  boost::copy(step_.state(), ExprAndInserter(transition));
  boost::copy(step_.input(), ExprAndInserter(transition));
  boost::copy(step_.state_transition().target_constraints,
              ExprAndInserter(transition));
  achk_.ValidateLemma(lemma, transition);
}
} // end namespace euforia

ext: cc

max_stars_repo_name: dbueno/euforia

max_issues_repo_name: dbueno/euforia

max_forks_repo_name: dbueno/euforia


text:
#include "Board.hpp"
#include "BoardOrganism.hpp"
#include "GA.hpp"
#include "HexGridPrint.hpp"
#include <boost/lexical_cast.hpp>
#include <math.h>

void ShowStatistics(const std::vector<BoardOrganism *> &i_organisms)
{
  size_t j;

  double smallest = -1;
  double largest = -1;
  double meannum = 0;
  double meanden = 0;
  for (j = 0 ; j < i_organisms.size() ; ++j)
  {
    double f=i_organisms[j]->GetFitness();
    if (smallest == -1 || f < smallest)
    {
      smallest = f;
    }
    if (largest == -1 || f > largest)
    {
      largest = f;
    }

    meannum += f;
    meanden += 1;
  }
  double mean = meannum / meanden;
  double ssq = 0;
  for (j = 0 ; j < i_organisms.size() ; ++j)
  {
    double var = i_organisms[j]->GetFitness() - mean;
    ssq += var * var;
  }
  double stdev = sqrt(ssq / meanden);

  std::cout << smallest << "--|" << mean - stdev << "|||" << mean <<
    "|||" << mean+stdev << "|--" << largest << std::endl;
}

void ShowBoardOrganism(const BoardOrganism &bo,const Board &b)
{
  HexGridPrint hgp(11,12,false,true);

  int i,j;
  for (i = 0 ; i < 11 ; ++i)
  {
    for (j = 0 ; j < 11 + (i%2) ; j++)
    {
      const BoardCell &bc = b.GetCell(i,j);

      if (bc.GetType() == BoardCell::BOTTLE)
      {
        hgp.AddItem(i,j,HexGridPrint::DIR3,ColorInfo::GetColorChar(bc.GetColor()));
        hgp.AddItem(i,j,HexGridPrint::STAT1,boost::lexical_cast<char>(bc.GetBottleSize()));
      }
      else if (bc.GetType() == BoardCell::SOURCE)
      {
        hgp.AddItem(i,j,HexGridPrint::DIR0,ColorInfo::GetColorChar(bc.GetColor()));
      }
      else
      {
        size_t k;
        for (k = 0 ; k < 6 ; ++k)
        {
          const PipeDefinition &pdef = bc.GetUniquePipeRotations()[bo.GetAllele(i,j)];

          if (pdef[k] != 0)
            hgp.AddItem(i,j,(HexGridPrint::HexLoc)k,boost::lexical_cast<char>(pdef[k]));
        }
      }
    }
  }
  std::cout << hgp.Show() << "Fitness: " << bo.GetFitnessDescriptor() << std::endl << bo.GetMetaState();
}

const BoardOrganism *bestone = NULL;

void ManageBestOrganism(const std::vector<BoardOrganism *> &i_organisms,const Board &b)
{
  size_t j;

  bool bested = false;
  for (j = 0 ; j < i_organisms.size() ; ++j)
  {
    if (!bestone || bestone->GetFitness() < i_organisms[j]->GetFitness())
    {
      bestone = i_organisms[j];
      bested = true;
    }
  }
  if (bested)
  {
    ShowBoardOrganism(*bestone,b);
  }
}

int main(int argc,char **argv)
{
  if (argc != 2)
  {
    std::cout << "Bad command line; need file name." << std::endl;
    exit(1);
  }

  Board b(argv[1]);

  BoardOrganism::Initialize(b);

  GA<BoardOrganism> ga(100);

  int i;
  for (i = 0 ; i < 100 ; ++i)
  {
    std::cout << "Generation " << i << " ";

    ShowStatistics(ga.GetCurrentPopulation());
    ManageBestOrganism(ga.GetCurrentPopulation(),b);

    ga.Generate(10);
  }
}

ext: cpp

max_stars_repo_name: chiendarrendor/AlbertsMisc

max_issues_repo_name: chiendarrendor/AlbertsMisc

max_forks_repo_name: chiendarrendor/AlbertsMisc


text:
/** \file mainwindow.cpp
 *  \author Lukáš Huták, xhutak01
 *	\author Michal Kozubík, xkozub03
 */

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Client.h"
#include "mapmenu.h"
#include <boost/asio.hpp>

/**
 * \brief Konstruktor
 * \param[in] client Klient pro komunikaci
 */
MainWindow::MainWindow(Client *client) :
cl(client), ui(new Ui::MainWindow)
{
	ui->setupUi(this);
}

/**
 * \brief Destruktor
 */
MainWindow::~MainWindow()
{
	delete ui;
}

/**
 * \brief Připojení k serveru
 */
void MainWindow::on_connectBtn_clicked()
{
	try {
		cl->connect(ui->serverAddr->text().toStdString().c_str(),
				ui->serverPort->text().toStdString().c_str());
	} catch (std::exception& e) {
		ui->statusBar->showMessage(e.what());
		return;
	}

	/* vytvoření nového podokna */
	mm = new MapMenu(this, cl);
	this->hide();
	try {
		mm->exec();
	} catch (std::exception& e) {
		ui->statusBar->showMessage(e.what());
	}
}

max_stars_repo_name: mikeek/FIT

max_issues_repo_name: mikeek/FIT

max_forks_repo_name: mikeek/FIT


text:
/**********************************************************************
*  Copyright (c) 2008-2014, Alliance for Sustainable Energy.
*  All rights reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*  Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**********************************************************************/

#include <utilities/core/UpdateManager.hpp>
#include <utilities/core/Assert.hpp>
#include <utilities/core/Application.hpp>
#include <OpenStudio.hxx>

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDomDocument>
#include <QThread>
#include <QAbstractEventDispatcher>

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

#include <iostream>

namespace openstudio{

  UpdateManager::UpdateManager(const std::string& appName)
    : m_appName(appName), m_finished(false), m_error(false),
      m_newMajorRelease(false), m_newMinorRelease(false), m_newPatchRelease(false),
      m_mostRecentVersion(openStudioVersion()), m_manager(new QNetworkAccessManager(this))
  {
    Application::instance().processEvents(); // a kludge to make sure that updatemanager works correctly in a non-application environment on unix

    bool result = connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
    OS_ASSERT(result);

    result = connect(this, SIGNAL(processed()), this, SLOT(replyProcessed()));
    OS_ASSERT(result);

    QUrl url(QString::fromStdString(updateUrl()));

    m_request = new QNetworkRequest(url);
    OS_ASSERT(m_request);

    m_reply = m_manager->get(*m_request);
    OS_ASSERT(m_reply);
  }

  UpdateManager::UpdateManager(const std::string& appName, const std::string& url)
    : m_appName(appName), m_finished(false), m_error(false),
      m_newMajorRelease(false), m_newMinorRelease(false), m_newPatchRelease(false),
      m_mostRecentVersion(openStudioVersion()), m_manager(new QNetworkAccessManager(this))
  {
    Application::instance().processEvents(); // a kludge to make sure that updatemanager works correctly in a non-application environment on unix

    bool result = connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
    OS_ASSERT(result);

    result = connect(this, SIGNAL(processed()), this, SLOT(replyProcessed()));
    OS_ASSERT(result);

    m_request = new QNetworkRequest(QUrl(QString::fromStdString(url)));

    m_reply = m_manager->get(*m_request);
  }

  std::string UpdateManager::appName() const
  {
    return m_appName;
  }

  bool UpdateManager::finished() const
  {
    return m_finished;
  }

  bool UpdateManager::error() const
  {
    return m_error;
  }

  bool UpdateManager::newMajorRelease() const
  {
    return m_newMajorRelease;
  }

  bool UpdateManager::newMinorRelease() const
  {
    return m_newMinorRelease;
  }

  bool UpdateManager::newPatchRelease() const
  {
    return m_newPatchRelease;
  }

  std::string UpdateManager::mostRecentVersion() const
  {
    return m_mostRecentVersion;
  }

  std::string UpdateManager::mostRecentDownloadUrl() const
  {
    return m_mostRecentDownloadUrl;
  }

  std::vector<std::string> UpdateManager::updateMessages() const
  {
    return m_updateMessages;
  }

  std::string UpdateManager::updateUrl() const
  {
    return std::string("http://openstudio.nrel.gov/update.html?app=") + appName() + std::string("&version=") + openStudioVersion();
  }

  void UpdateManager::replyFinished(QNetworkReply* reply)
  {
    // finished after this
    m_finished = true;

    if (reply){
      // don't delete here
      reply->deleteLater();

      m_error = (reply->error() != QNetworkReply::NoError);
      if (!m_error){

        // create xml document to read the response
        QDomDocument document;
        document.setContent(reply->readAll());
        QDomNodeList openstudioelements = document.elementsByTagName("openstudio");

        if (openstudioelements.size() > 0)
        {
          // Only process the first one for now
          QDomNodeList nodes = openstudioelements.at(0).childNodes();

          // all child nodes will be releases
          for(int i = 0; i < nodes.size(); ++i){
            QDomElement release = nodes.at(i).toElement();
            if (!release.isNull()){
              if (!checkRelease(release)){
                // break if not newer than current
                break;
              }
            }
          }
        }
      }else{
        LOG(Error, "QNetworkReply " << reply->error());
      }
    }

    emit processed();
  }

  void UpdateManager::replyProcessed()
  {
  }

  bool UpdateManager::checkRelease(const QDomElement& release)
  {
    bool updateAvailable = false;

    try{

      std::string version = release.attribute("version").toStdString();
      std::string currentVersion = openStudioVersion();
      boost::regex versionRegex("^([0-9]+)\\.([0-9]+)\\.([0-9]+).*?");

      boost::smatch versionMatch;
      boost::smatch currentVersionMatch;
      if( boost::regex_search(version, versionMatch, versionRegex) &&
          boost::regex_search(currentVersion, currentVersionMatch, versionRegex)){
        std::string versionMajorString = std::string(versionMatch[1].first,versionMatch[1].second); boost::trim(versionMajorString);
        std::string versionMinorString = std::string(versionMatch[2].first,versionMatch[2].second); boost::trim(versionMinorString);
        std::string versionPatchString = std::string(versionMatch[3].first,versionMatch[3].second); boost::trim(versionPatchString);

        unsigned versionMajor = boost::lexical_cast<unsigned>(versionMajorString);
        unsigned versionMinor = boost::lexical_cast<unsigned>(versionMinorString);
        unsigned versionPatch = boost::lexical_cast<unsigned>(versionPatchString);

        std::string currentVersionMajorString = std::string(currentVersionMatch[1].first,currentVersionMatch[1].second); boost::trim(currentVersionMajorString);
        std::string currentVersionMinorString = std::string(currentVersionMatch[2].first,currentVersionMatch[2].second); boost::trim(currentVersionMinorString);
        std::string currentVersionPatchString = std::string(currentVersionMatch[3].first,currentVersionMatch[3].second); boost::trim(currentVersionPatchString);

        unsigned currentVersionMajor = boost::lexical_cast<unsigned>(currentVersionMajorString);
        unsigned currentVersionMinor = boost::lexical_cast<unsigned>(currentVersionMinorString);
        unsigned currentVersionPatch = boost::lexical_cast<unsigned>(currentVersionPatchString);

        if (versionMajor > currentVersionMajor){
          m_newMajorRelease = true;
          updateAvailable = true;
        }else if(versionMajor == currentVersionMajor){
          if (versionMinor > currentVersionMinor){
            m_newMinorRelease = true;
            updateAvailable = true;
          }else if(versionMinor == currentVersionMinor){
            if (versionPatch > currentVersionPatch){
              m_newPatchRelease = true;
              updateAvailable = true;
            }
          }
        }

        if (updateAvailable){
          // only set download url to most recent (e.g. first) release
          if (m_updateMessages.empty()){
            m_mostRecentVersion = version;
            m_mostRecentDownloadUrl = release.attribute("download").toStdString();
          }
          // add messages from all releases newer than current
          m_updateMessages.push_back(release.firstChild().toCDATASection().data().toStdString());
        }
      }
    }catch(const std::exception& e){
      LOG(Error, e.what());
    }

    return updateAvailable;
  }

} // openstudio

max_stars_repo_name: ORNL-BTRIC/OpenStudio

max_issues_repo_name: ORNL-BTRIC/OpenStudio

max_forks_repo_name: ORNL-BTRIC/OpenStudio


text:
// C++ headers
#include <algorithm>
#include <chrono>

// boost headers
#include <boost/format.hpp>

// CMSSW headers
#include "DQMServices/Core/interface/DQMStore.h"
#include "ThroughputService.h"

// local headers
#include "processor_model.h"

// describe the module's configuration
void ThroughputService::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
  edm::ParameterSetDescription desc;
  desc.addUntracked<double>("timeRange", 60000.0);
  desc.addUntracked<double>("timeResolution", 10.0);
  desc.addUntracked<std::string>("dqmPath", "HLT/Throughput");
  desc.addUntracked<bool>("dqmPathByProcesses", false);
  descriptions.add("ThroughputService", desc);
}

ThroughputService::ThroughputService(const edm::ParameterSet& config, edm::ActivityRegistry& registry)
    :  // startup time
      m_startup(std::chrono::steady_clock::now()),
      // configuration
      m_time_range(config.getUntrackedParameter<double>("timeRange")),
      m_time_resolution(config.getUntrackedParameter<double>("timeResolution")),
      m_dqm_path(config.getUntrackedParameter<std::string>("dqmPath")),
      m_dqm_bynproc(config.getUntrackedParameter<bool>("dqmPathByProcesses")) {
  registry.watchPreGlobalBeginRun(this, &ThroughputService::preGlobalBeginRun);
  registry.watchPreSourceEvent(this, &ThroughputService::preSourceEvent);
  registry.watchPostEvent(this, &ThroughputService::postEvent);
}

ThroughputService::~ThroughputService() = default;

void ThroughputService::preallocate(edm::service::SystemBounds const& bounds) {
  auto concurrent_streams = bounds.maxNumberOfStreams();
  auto concurrent_threads = bounds.maxNumberOfThreads();

  if (m_dqm_bynproc)
    m_dqm_path += (boost::format("/Running on %s with %d streams on %d threads") % processor_model %
                   concurrent_streams % concurrent_threads)
                      .str();
}

void ThroughputService::preGlobalBeginRun(edm::GlobalContext const& gc) {
  // if the DQMStore is available, book the DQM histograms
  if (edm::Service<DQMStore>().isAvailable()) {
    std::string y_axis_title = (boost::format("events / %g s") % m_time_resolution).str();
    unsigned int bins = std::round(m_time_range / m_time_resolution);
    double range = bins * m_time_resolution;

    // define a callback that can book the histograms
    auto bookTransactionCallback = [&, this](DQMStore::IBooker& booker) {
      booker.setCurrentFolder(m_dqm_path);
      m_sourced_events = booker.book1D("throughput_sourced", "Throughput (sourced events)", bins, 0., range);
      m_sourced_events->setXTitle("time [s]");
      m_sourced_events->setYTitle(y_axis_title);
      m_retired_events = booker.book1D("throughput_retired", "Throughput (retired events)", bins, 0., range);
      m_retired_events->setXTitle("time [s]");
      m_retired_events->setYTitle(y_axis_title);
    };

    // book MonitorElement's for this run
    edm::Service<DQMStore>()->bookConcurrentTransaction(bookTransactionCallback, gc.luminosityBlockID().run());
  } else {
    std::cerr << "No DQMStore service, aborting." << std::endl;
    abort();
  }
}

void ThroughputService::preSourceEvent(edm::StreamID sid) {
  auto timestamp = std::chrono::steady_clock::now();
  m_sourced_events->Fill(std::chrono::duration_cast<std::chrono::duration<double>>(timestamp - m_startup).count());
}

void ThroughputService::postEvent(edm::StreamContext const& sc) {
  auto timestamp = std::chrono::steady_clock::now();
  m_retired_events->Fill(std::chrono::duration_cast<std::chrono::duration<double>>(timestamp - m_startup).count());
}

// declare ThroughputService as a framework Service
#include "FWCore/ServiceRegistry/interface/ServiceMaker.h"
DEFINE_FWK_SERVICE(ThroughputService);

max_stars_repo_name: sebwieland/cmssw

max_issues_repo_name: sebwieland/cmssw

max_forks_repo_name: sebwieland/cmssw


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

    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)
==============================================================================*/
#if !defined(FUSION_SEQUENCE_FACADE_09252006_1044)
#define FUSION_SEQUENCE_FACADE_09252006_1044

#include <boost/fusion/support/sequence_base.hpp>
#include <boost/mpl/bool.hpp>

namespace boost { namespace fusion
{
    struct sequence_facade_tag;

    template <typename Derived, typename Category, typename IsView = mpl::false_>
    struct sequence_facade : sequence_base<Derived>
    {
        typedef fusion_sequence_tag tag;
        typedef sequence_facade_tag fusion_tag;
        typedef Derived derived_type;
        typedef Category category;
        typedef IsView is_view;
        typedef mpl::false_ is_segmented;
    };
}}

#endif

ext: hpp

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/*
 * Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
 */

#include <boost/uuid/uuid_io.hpp>
#include <cmn/agent_cmn.h>

#include <base/logging.h>
#include <init/agent_param.h>
#include <oper/operdb_init.h>
#include <oper/route_common.h>
#include <oper/vrf.h>
#include <oper/tsn_elector.h>
#include <oper/bridge_route.h>
#include <oper/inet_unicast_route.h>
#include <oper/agent_route_walker.h>
#include <oper/nexthop.h>
#include <oper/multicast.h>

using namespace std;

TsnElectorState::TsnElectorState(AgentRouteTable *inet4_table,
                                 TsnElector *elector) :
    inet4_table_(inet4_table) {
    inet4_id_ = inet4_table->Register(boost::bind(&TsnElector::RouteNotify,
                                                  elector, _1, _2));
}

TsnElectorState::~TsnElectorState() {
    inet4_table_->Unregister(inet4_id_);
}

TsnElectorWalker::TsnElectorWalker(const std::string &name, Agent *agent) :
    AgentRouteWalker(name, agent) {
}

TsnElectorWalker::~TsnElectorWalker() {
}

bool TsnElectorWalker::RouteWalkNotify(DBTablePartBase *partition,
                                       DBEntryBase *e) {
    BridgeRouteEntry *bridge_entry =
        dynamic_cast<BridgeRouteEntry*>(e);
    if (!bridge_entry || !bridge_entry->is_multicast())
        return true;

    AgentPath *evpn_path = NULL;
    for (Route::PathList::iterator it = bridge_entry->GetPathList().begin();
         it != bridge_entry->GetPathList().end(); it++) {
        AgentPath *path = static_cast<AgentPath *>(it.operator->());
        if (path->peer()->GetType() != Peer::BGP_PEER)
            continue;
        const CompositeNH *cnh = dynamic_cast<const CompositeNH *>(path->nexthop());
        if (!cnh)
            continue;

        if (cnh->composite_nh_type() != Composite::EVPN)
            continue;

        if (!evpn_path)
            evpn_path = path;
        path->set_inactive(!master_);
    }

    if (evpn_path && bridge_entry->ReComputePathAdd(evpn_path))
        partition->Notify(bridge_entry);
    return true;
}

void TsnElectorWalker::LeaveTsnMastership() {
    master_ = false;
    StartVrfWalk();
}

void TsnElectorWalker::AcquireTsnMastership() {
    master_ = true;
    StartVrfWalk();
}

TsnElector::TsnElector(Agent *agent) : agent_(agent),
    vrf_listener_id_(), active_tsn_servers_() {
    if (IsTsnNoForwardingEnabled()) {
        walker_.reset(new TsnElectorWalker("TsnElectorWalker", agent));
    }
}

TsnElector::~TsnElector() {
}

bool TsnElector::IsTsnNoForwardingEnabled() const {
    return (agent_->params()->agent_mode() ==
            AgentParam::TSN_NO_FORWARDING_AGENT);
}

void TsnElector::Register() {
    if (!IsTsnNoForwardingEnabled())
        return;
    vrf_listener_id_ = agent_->vrf_table()->Register(
        boost::bind(&TsnElector::Notify, this, _1, _2));
    agent_->oper_db()->agent_route_walk_manager()->
        RegisterWalker(static_cast<AgentRouteWalker *>(walker_.get()));
}

void TsnElector::Notify(DBTablePartBase *partition, DBEntryBase *e) {
    VrfEntry *vrf = dynamic_cast<VrfEntry *>(e);
    TsnElectorState *state = dynamic_cast<TsnElectorState *>(vrf->
                             GetState(partition->parent(), vrf_listener_id_));
    if (vrf->GetName().compare(agent_->fabric_policy_vrf_name()) != 0)
        return;

    if (vrf->IsDeleted()) {
        if (state) {
            vrf->ClearState(partition->parent(), vrf_listener_id_);
            delete state;
        }
        return;
    }

    if (!state) {
        state = new TsnElectorState(vrf->GetInet4UnicastRouteTable(), this);
        vrf->SetState(partition->parent(), vrf_listener_id_, state);
    }
    return;
}

void TsnElector::RouteNotify(DBTablePartBase *partition, DBEntryBase *e) {
    const InetUnicastRouteEntry *rt =
        static_cast<const InetUnicastRouteEntry*>(e);

    if (!agent_->params()->IsConfiguredTsnHostRoute(rt->addr().to_string()))
        return;

    const string rt_addr_str = rt->GetAddressString();
    std::vector<std::string>::iterator it =
        std::find(active_tsn_servers_.begin(), active_tsn_servers_.end(),
                  rt_addr_str);
    std::string master = "";
    if (!active_tsn_servers_.empty()) {
        master = active_tsn_servers_.front();
    }
    if (rt->IsDeleted()) {
        if (it == active_tsn_servers_.end())
            return;
        active_tsn_servers_.erase(it);
    } else {
        if (it != active_tsn_servers_.end())
            return;
        active_tsn_servers_.push_back(rt_addr_str);
    }
    std::sort(active_tsn_servers_.begin(), active_tsn_servers_.end());
    std::string new_master = "";
    if (!active_tsn_servers_.empty()) {
        new_master = active_tsn_servers_.front();
    }
    if (master == new_master)
        return;

    std::string vhost_addr = agent_->params()->vhost_addr().to_string();
    if (master == vhost_addr) {
        walker()->LeaveTsnMastership();
    }
    if (new_master == vhost_addr) {
        walker()->AcquireTsnMastership();
    }
}

void TsnElector::Shutdown() {
    if (!IsTsnNoForwardingEnabled())
        return;
    agent_->vrf_table()->Unregister(vrf_listener_id_);
    agent_->oper_db()->agent_route_walk_manager()->
        ReleaseWalker(walker_.get());
    walker_.reset(NULL);
}

bool TsnElector::IsMaster() const {
    if (active_tsn_servers_.empty())
        return false;
    return (active_tsn_servers_.front().compare(
        agent_->params()->vhost_addr().to_string()) == 0);
}

const TsnElector::ManagedPhysicalDevicesList &TsnElector::ManagedPhysicalDevices()
const {
    return agent_->oper_db()->multicast()->physical_devices();
}

max_stars_repo_name: jnpr-pranav/contrail-controller

max_issues_repo_name: jnpr-pranav/contrail-controller

max_forks_repo_name: jnpr-pranav/contrail-controller


text:
/*
# Copyright (c) 2014-2016, NVIDIA CORPORATION. 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.
#  * Neither the name of NVIDIA CORPORATION 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 ``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 OWNER 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 "vstab_nodes.hpp"

#include <Eigen/SVD>

static const char KERNEL_HOMOGRAPHY_FILTER_NAME[VX_MAX_KERNEL_NAME] = "example.nvx.homography_filter";

// Kernel implementation
static vx_status VX_CALLBACK homographyFilter_kernel(vx_node, const vx_reference *parameters, vx_uint32 num)
{
    if (num != 4)
        return VX_FAILURE;

    vx_status status = VX_SUCCESS;

    vx_matrix input = (vx_matrix)parameters[0];
    vx_matrix homography = (vx_matrix)parameters[1];
    vx_image image = (vx_image)parameters[2];
    vx_array mask = (vx_array)parameters[3];

    // Copy input to homography
    vx_float32 intputData[9] = {0};
    status |= vxCopyMatrix(input, intputData, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);
    status |= vxCopyMatrix(homography, intputData, VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);

    vx_uint32 width = 0, height = 0;
    status |= vxQueryImage(image, VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width));
    status |= vxQueryImage(image, VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height));

    vx_size nPoints;
    status |= vxQueryArray(mask, VX_ARRAY_ATTRIBUTE_NUMITEMS, &nPoints, sizeof(nPoints));

    vx_int32 nInliers = 0;
    if (nPoints > 0)
    {
        vx_map_id map_id;
        vx_size stride;
        void* ptr;
        status |= vxMapArrayRange(mask, 0, nPoints, &map_id, &stride, &ptr, VX_READ_ONLY, VX_MEMORY_TYPE_HOST, 0);

        for (vx_size i = 0; i < nPoints; i++)
        {
            vx_uint8 v = vxArrayItem(vx_uint8, ptr, i, stride);
            if (v != 0)
                ++nInliers;
        }

        status |= vxUnmapArrayRange(mask, map_id);
    }

    int inlierThresh = std::max(15, static_cast<int>(0.1 * nPoints));
    Matrix3x3f_rm eye3x3 = Matrix3x3f_rm::Identity();

    if (nInliers < inlierThresh)
    {
        status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);
        return status;
    }

    vx_float32 data[9];
    status |= vxCopyMatrix(homography, data, VX_READ_ONLY, VX_MEMORY_TYPE_HOST);

    Matrix3x3f_rm M = Matrix3x3f_rm::Map(data, 3, 3);
    M.transposeInPlace();

    // restrictions on the lenghts of the diagonals of the warped image
    Matrix3x4f_rm vertices = Matrix3x4f_rm::Zero();

    for(int i=0; i<4; ++i)
        vertices(2, i) = 1.0f;

    vertices(0, 1) = static_cast<float>(width);
    vertices(0, 2) = static_cast<float>(width);
    vertices(1, 2) = static_cast<float>(height);
    vertices(1, 3) = static_cast<float>(height);

    Matrix3x4f_rm dstVertices = M * vertices;
    for(int i=0; i<4; ++i)
    {
        dstVertices(0,i) /= dstVertices(2,i);
        dstVertices(1,i) /= dstVertices(2,i);
        dstVertices(2,i) = 1.0f;
    }

    float diagLenGold = std::sqrt(static_cast<float>(width*width + height*height));

    float dx = dstVertices(0,0) - dstVertices(0,2);
    float dy = dstVertices(1,0) - dstVertices(1,2);
    float lenDiag1 = sqrt(dx*dx + dy*dy);

    dx = dstVertices(0,1) - dstVertices(0,3);
    dy = dstVertices(1,1) - dstVertices(1,3);
    float lenDiag2 = sqrt(dx*dx + dy*dy);

    float averDiagLen = (lenDiag1 + lenDiag2) / 2;
    float diagRatio1 = std::min(diagLenGold, averDiagLen) / std::max(diagLenGold, averDiagLen);
    if (diagRatio1 < 0.5f)
    {
        status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);
        return status;
    }

    float maxDiag = std::max(lenDiag1, lenDiag2);
    if (maxDiag > 0.0f)
    {
        float diagRatio2 = std::min(lenDiag1, lenDiag2) / maxDiag;
        if (diagRatio2 < 0.25f)
        {
            status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);
            return status;
        }
    }
    else
    {
        status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);
        return status;
    }

    // restriction on min eigen value
    typedef Eigen::JacobiSVD<Matrix3x3f_rm> JacobiSVD;

    JacobiSVD svd(M);
    JacobiSVD::SingularValuesType singValues = svd.singularValues();

    if (singValues(2) < 1e-4f)
    {
        status |= vxCopyMatrix(homography, eye3x3.data(), VX_WRITE_ONLY, VX_MEMORY_TYPE_HOST);
        return status;
    }

    return status;
}

// Parameter validator
static vx_status VX_CALLBACK homographyFilter_validate(vx_node, const vx_reference parameters[],
                                                       vx_uint32 numParams, vx_meta_format metas[])
{
    if (numParams != 4) return VX_ERROR_INVALID_PARAMETERS;

    vx_matrix input = (vx_matrix)parameters[0];
    vx_array mask = (vx_array)parameters[3];

    vx_status status = VX_SUCCESS;

    vx_enum inputDataType = 0;
    vx_size inputRows = 0ul, inputCols = 0ul;
    vxQueryMatrix(input, VX_MATRIX_ATTRIBUTE_TYPE, &inputDataType, sizeof(inputDataType));
    vxQueryMatrix(input, VX_MATRIX_ATTRIBUTE_ROWS, &inputRows, sizeof(inputRows));
    vxQueryMatrix(input, VX_MATRIX_ATTRIBUTE_COLUMNS, &inputCols, sizeof(inputCols));

    vx_enum maskType = 0;
    vxQueryArray(mask, VX_ARRAY_ATTRIBUTE_ITEMTYPE, &maskType, sizeof(maskType));

    if (inputDataType != VX_TYPE_FLOAT32 || inputCols != 3 || inputRows != 3)
    {
        status = VX_ERROR_INVALID_PARAMETERS;
    }

    if (maskType != VX_TYPE_UINT8)
    {
        status = VX_ERROR_INVALID_TYPE;
    }

    vx_meta_format homographyMeta = metas[1];

    vx_enum homographyType = VX_TYPE_FLOAT32;
    vx_size homographyRows = 3;
    vx_size homographyCols = 3;

    vxSetMetaFormatAttribute(homographyMeta, VX_MATRIX_ATTRIBUTE_TYPE, &homographyType, sizeof(homographyType));
    vxSetMetaFormatAttribute(homographyMeta, VX_MATRIX_ATTRIBUTE_ROWS, &homographyRows, sizeof(homographyRows));
    vxSetMetaFormatAttribute(homographyMeta, VX_MATRIX_ATTRIBUTE_COLUMNS, &homographyCols, sizeof(homographyCols));

    return status;
}

// Register user defined kernel in OpenVX context
vx_status registerHomographyFilterKernel(vx_context context)
{
    vx_status status = VX_SUCCESS;

    vx_enum id;
    status = vxAllocateUserKernelId(context, &id);
    if (status != VX_SUCCESS)
    {
        vxAddLogEntry((vx_reference)context, status, "[%s:%u] Failed to allocate an ID for the HomographyFilter kernel",
                      __FUNCTION__, __LINE__);
        return status;
    }

    vx_kernel kernel = vxAddUserKernel(context, KERNEL_HOMOGRAPHY_FILTER_NAME,
                                       id,
                                       homographyFilter_kernel,
                                       4,
                                       homographyFilter_validate,
                                       NULL,
                                       NULL
                                       );

    status = vxGetStatus((vx_reference)kernel);
    if (status != VX_SUCCESS)
    {
        vxAddLogEntry((vx_reference)context, status, "[%s:%u] Failed to create HomographyFilter Kernel", __FUNCTION__, __LINE__);
        return status;
    }

    status |= vxAddParameterToKernel(kernel, 0, VX_INPUT, VX_TYPE_MATRIX, VX_PARAMETER_STATE_REQUIRED); // input
    status |= vxAddParameterToKernel(kernel, 1, VX_OUTPUT, VX_TYPE_MATRIX, VX_PARAMETER_STATE_REQUIRED); // homography
    status |= vxAddParameterToKernel(kernel, 2, VX_INPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED); // image
    status |= vxAddParameterToKernel(kernel, 3, VX_INPUT, VX_TYPE_ARRAY, VX_PARAMETER_STATE_REQUIRED); // mask

    if (status != VX_SUCCESS)
    {
        vxReleaseKernel(&kernel);
        vxAddLogEntry((vx_reference)context, status, "[%s:%u] Failed to initialize HomographyFilter Kernel parameters", __FUNCTION__, __LINE__);
        return VX_FAILURE;
    }

    status = vxFinalizeKernel(kernel);
    vxReleaseKernel(&kernel);

    if (status != VX_SUCCESS)
    {
        vxAddLogEntry((vx_reference)context, status, "[%s:%u] Failed to finalize HomographyFilter Kernel", __FUNCTION__, __LINE__);
        return VX_FAILURE;
    }

    return status;
}

vx_node homographyFilterNode(vx_graph graph, vx_matrix input, vx_matrix homography, vx_image image, vx_array mask)
{
    vx_node node = NULL;

    vx_kernel kernel = vxGetKernelByName(vxGetContext((vx_reference)graph), KERNEL_HOMOGRAPHY_FILTER_NAME);

    if (vxGetStatus((vx_reference)kernel) == VX_SUCCESS)
    {
        node = vxCreateGenericNode(graph, kernel);
        vxReleaseKernel(&kernel);

        if (vxGetStatus((vx_reference)node) == VX_SUCCESS)
        {
            vxSetParameterByIndex(node, 0, (vx_reference)input);
            vxSetParameterByIndex(node, 1, (vx_reference)homography);
            vxSetParameterByIndex(node, 2, (vx_reference)image);
            vxSetParameterByIndex(node, 3, (vx_reference)mask);
        }
    }

    return node;
}


text:
/*=============================================================================
    Copyright (c) 2003 Joel de Guzman
    Copyright (c) 2005 Eric Niebler

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_ITERATOR_DETAIL_CONS_ITERATOR_VALUE_TRAITS_HPP)
#define FUSION_ITERATOR_DETAIL_CONS_ITERATOR_VALUE_TRAITS_HPP

#include <boost/spirit/fusion/detail/config.hpp>

namespace boost { namespace fusion
{
    struct cons_iterator_tag;

    namespace cons_detail
    {
        template <typename Iterator>
        struct value_traits_impl
        {
            typedef typename Iterator::cons_type cons_type;
            typedef typename cons_type::car_type type;
        };
    }

    namespace meta
    {
        template <typename Tag>
        struct value_impl;

        template <>
        struct value_impl<cons_iterator_tag>
        {
            template <typename Iterator>
            struct apply : cons_detail::value_traits_impl<Iterator> {};
        };
    }

}}

#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)

namespace boost { namespace mpl
{
    template <typename Iterator>
    struct deref;

    template <typename Cons>
    struct deref<fusion::cons_iterator<Cons> >
        : fusion::cons_detail::value_traits_impl<fusion::cons_iterator<Cons> >
    {
    };
}}

#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION

#endif

max_stars_repo_name: schinmayee/nimbus

max_issues_repo_name: schinmayee/nimbus

max_forks_repo_name: schinmayee/nimbus


text:
/*
 * Copyright 2015-2019 CNRS-UM LIRMM, CNRS-AIST JRL
 */

#include <mc_rbdyn/rpy_utils.h>
#include <mc_rtc/Configuration.h>
#include <mc_rtc/logging.h>

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/filesystem.hpp>
namespace bfs = boost::filesystem;

#include "internals/json.h"
#include <fstream>
#include <stdexcept>

namespace
{
inline std::string to_lower(const std::string & in)
{
  return boost::algorithm::to_lower_copy(in);
}
} // namespace

namespace mc_rtc
{

bool Configuration::Json::isArray() const
{
  assert(value_);
  return static_cast<const internal::RapidJSONValue *>(value_)->IsArray();
}

bool Configuration::Json::isObject() const
{
  assert(value_);
  return static_cast<const internal::RapidJSONValue *>(value_)->IsObject();
}

std::vector<std::string> Configuration::Json::keys() const
{
  assert(isObject());
  std::vector<std::string> ret;
  auto v = static_cast<const internal::RapidJSONValue *>(value_);
  for(auto it = v->MemberBegin(); it != v->MemberEnd(); ++it)
  {
    ret.push_back(it->name.GetString());
  }
  return ret;
}

namespace
{

bool findPath(const internal::RapidJSONValue * root, const internal::RapidJSONValue * value, std::string & out)
{
  if(root == value)
  {
    return true;
  }
  if(root->IsArray())
  {
    for(size_t idx = 0; idx != root->Size(); ++idx)
    {
      if(findPath(&(*root)[idx], value, out))
      {
        out = fmt::format("[{}]{}", idx, out);
        return true;
      }
    }
  }
  else if(root->IsObject())
  {
    for(auto it = root->MemberBegin(); it != root->MemberEnd(); ++it)
    {
      if(findPath(&it->value, value, out))
      {
        out = fmt::format("(\"{}\"){}", it->name.GetString(), out);
        return true;
      }
    }
  }
  return false;
}

} // namespace

void Configuration::Json::path(std::string & out) const
{
  assert(doc_.get());
  assert(value_);
  auto root = static_cast<const internal::RapidJSONValue *>(doc_.get());
  auto value = static_cast<const internal::RapidJSONValue *>(value_);
  findPath(root, value, out);
}

bool Configuration::empty() const
{
  assert(v.value_);
  auto value = static_cast<const internal::RapidJSONValue *>(v.value_);
  if(v.isArray())
  {
    return value->Empty();
  }
  else if(v.isObject())
  {
    return value->ObjectEmpty();
  }
  return true;
}

size_t Configuration::Json::size() const
{
  assert(value_);
  auto value = static_cast<const internal::RapidJSONValue *>(value_);
  return value->Size();
}

Configuration::Json Configuration::Json::operator[](size_t idx) const
{
  assert(value_);
  auto value = static_cast<internal::RapidJSONValue *>(value_);
  return {static_cast<void *>(&(*value)[idx]), doc_};
}

Configuration::Json Configuration::Json::operator[](const std::string & key) const
{
  assert(value_);
  auto value = static_cast<internal::RapidJSONValue *>(value_);
  return {static_cast<void *>(&(*value)[key]), doc_};
}

bool Configuration::Json::isNumeric() const
{
  assert(value_);
  auto value = static_cast<internal::RapidJSONValue *>(value_);
  return value->IsNumber();
}

double Configuration::Json::asDouble() const
{
  assert(isNumeric());
  auto value = static_cast<internal::RapidJSONValue *>(value_);
  return value->GetDouble();
}

Configuration::Exception::Exception(const std::string & msg, const Json & v) : msg_(msg), v_(v) {}

Configuration::Exception::~Exception() noexcept
{
  if(msg().size())
  {
    log::error(msg());
  }
}

const char * Configuration::Exception::what() const noexcept
{
  return msg().c_str();
}

void Configuration::Exception::silence() const noexcept
{
  msg_.resize(0);
  v_.value_ = nullptr;
}

const std::string & Configuration::Exception::msg() const noexcept
{
  if(v_.value_)
  {
    std::string path;
    v_.path(path);
    msg_ = fmt::format("{} (error path: {})", msg_, path.size() ? path : "()");
    v_.value_ = nullptr;
  }
  return msg_;
}

Configuration::Configuration() : v{nullptr, std::shared_ptr<void>(new internal::RapidJSONDocument())}
{
  auto doc = std::static_pointer_cast<internal::RapidJSONDocument>(v.doc_);
  auto value = rapidjson::GenericPointer<internal::RapidJSONValue>("/").Get(*doc);
  if(!value)
  {
    value = doc.get();
  }
  v.value_ = value;
  doc->SetObject();
}

Configuration::Configuration(const Json & v) : v(v) {}

Configuration::Configuration(const char * path) : Configuration(std::string(path)) {}

bool Configuration::isMember(const std::string & key) const
{
  return has(key);
}

bool Configuration::has(const std::string & key) const
{
  assert(v.value_);
  auto value = static_cast<const internal::RapidJSONValue *>(v.value_);
  return v.isObject() && value->HasMember(key);
}

Configuration Configuration::operator()(const std::string & key) const
{
  if(has(key))
  {
    return Configuration(v[key]);
  }
  throw Exception("No entry named " + key + " in the configuration", v);
}

size_t Configuration::size() const
{
  if(v.isArray())
  {
    return v.size();
  }
  return 0;
}

Configuration Configuration::operator[](size_t i) const
{
  if(i >= size())
  {
    throw Exception("Out-of-bound access for a Configuration element", v);
  }
  return Configuration(v[i]);
}

Configuration::operator bool() const
{
  assert(v.value_);
  auto value = static_cast<const internal::RapidJSONValue *>(v.value_);
  if(value->IsBool())
  {
    return value->GetBool();
  }
  else if(value->IsUint())
  {
    return value->GetUint();
  }
  else if(value->IsInt())
  {
    return value->GetInt();
  }
  throw Exception("Stored Json value is not a bool", v);
}

Configuration::operator int() const
{
  assert(v.value_);
  auto value = static_cast<const internal::RapidJSONValue *>(v.value_);
  if(value->IsInt())
  {
    return value->GetInt();
  }
  throw Exception("Stored Json value is not an int", v);
}

Configuration::operator unsigned int() const
{
  assert(v.value_);
  auto value = static_cast<const internal::RapidJSONValue *>(v.value_);
  if(value->IsUint() || (value->IsInt() && value->GetInt() >= 0))
  {
    return value->GetUint();
  }
  throw Exception("Stored Json value is not an unsigned int", v);
}

Configuration::operator int64_t() const
{
  assert(v.value_);
  auto value = static_cast<const internal::RapidJSONValue *>(v.value_);
  if(value->IsInt64())
  {
    return value->GetInt64();
  }
  throw Exception("Stored Json value is not an int64_t", v);
}

Configuration::operator uint64_t() const
{
  assert(v.value_);
  auto value = static_cast<const internal::RapidJSONValue *>(v.value_);
  if(value->IsUint64() || (value->IsInt64() && value->GetInt64() >= 0))
  {
    return value->GetUint64();
  }
  throw Exception("Stored Json value is not an uint64_t", v);
}

Configuration::operator double() const
{
  assert(v.value_);
  auto value = static_cast<const internal::RapidJSONValue *>(v.value_);
  if(value->IsNumber())
  {
    return value->GetDouble();
  }
  throw Exception("Stored Json value is not a double", v);
}

Configuration::operator std::string() const
{
  assert(v.value_);
  auto value = static_cast<const internal::RapidJSONValue *>(v.value_);
  if(value->IsString())
  {
    return std::string(value->GetString(), value->GetStringLength());
  }
  throw Exception("Stored Json value is not a string", v);
}

Configuration::operator Eigen::Vector2d() const
{
  if(v.isArray() && v.size() == 2 && v[0].isNumeric())
  {
    Eigen::Vector2d ret;
    ret << v[0].asDouble(), v[1].asDouble();
    return ret;
  }
  throw Exception("Stored Json value is not a Vector2d", v);
}

Configuration::operator Eigen::Vector3d() const
{
  if(v.isArray() && v.size() == 3 && v[0].isNumeric())
  {
    Eigen::Vector3d ret;
    ret << v[0].asDouble(), v[1].asDouble(), v[2].asDouble();
    return ret;
  }
  throw Exception("Stored Json value is not a Vector3d", v);
}

Configuration::operator Eigen::Vector6d() const
{
  if(v.isArray() && v.size() == 6 && v[0].isNumeric())
  {
    Eigen::Vector6d ret;
    ret << v[0].asDouble(), v[1].asDouble(), v[2].asDouble(), v[3].asDouble(), v[4].asDouble(), v[5].asDouble();
    return ret;
  }
  throw Exception("Stored Json value is not a Vector6d", v);
}

Configuration::operator Eigen::VectorXd() const
{
  if(v.isArray() && (v.size() == 0 || v[0].isNumeric()))
  {
    Eigen::VectorXd ret(v.size());
    for(size_t i = 0; i < v.size(); ++i)
    {
      ret(static_cast<int>(i)) = v[i].asDouble();
    }
    return ret;
  }
  throw Exception("Stored Json value is not a VectorXd", v);
}

Configuration::operator Eigen::Quaterniond() const
{
  if(v.isArray() && v.size() == 4 && v[0].isNumeric())
  {
    return Eigen::Quaterniond(v[0].asDouble(), v[1].asDouble(), v[2].asDouble(), v[3].asDouble()).normalized();
  }
  throw Exception("Stored Json value is not a Quaterniond", v);
}

Configuration::operator Eigen::Matrix3d() const
{
  if(v.isArray() && v[0].isNumeric())
  {
    // Matrix representaton
    if(v.size() == 9)
    {
      Eigen::Matrix3d m;
      for(size_t i = 0; i < 3; ++i)
      {
        for(size_t j = 0; j < 3; ++j)
        {
          m(static_cast<int>(i), static_cast<int>(j)) = v[3 * i + j].asDouble();
        }
      }
      return m;
    }
    // RPY representation
    if(v.size() == 3)
    {
      return mc_rbdyn::rpyToMat(v[0].asDouble(), v[1].asDouble(), v[2].asDouble());
    }
    // Quaternion representation
    if(v.size() == 4)
    {
      return Eigen::Quaterniond(v[0].asDouble(), v[1].asDouble(), v[2].asDouble(), v[3].asDouble())
          .normalized()
          .toRotationMatrix();
    }
  }
  throw Exception("Stored Json value is not a Matrix3d", v);
}

Configuration::operator Eigen::Matrix6d() const
{
  if(v.isArray() && v.size() == 36 && v[0].isNumeric())
  {
    Eigen::Matrix6d m;
    for(size_t i = 0; i < 6; ++i)
    {
      for(size_t j = 0; j < 6; ++j)
      {
        m(static_cast<int>(i), static_cast<int>(j)) = v[6 * i + j].asDouble();
      }
    }
    return m;
  }
  throw Exception("Stored Json value is not a Matrix6d", v);
}

Configuration::operator Eigen::MatrixXd() const
{
  if(v.isArray() && v[0].isArray() && v[0][0].isNumeric())
  {
    Eigen::MatrixXd ret(v.size(), v[0].size());
    for(size_t i = 0; i < v.size(); ++i)
    {
      auto row = v[i];
      assert(row.size() == ret.cols());
      for(size_t j = 0; j < row.size(); ++j)
      {
        ret(static_cast<int>(i), static_cast<int>(j)) = row[j].asDouble();
      }
    }
    return ret;
  }
  throw Exception("Stored Json value is not a MatrixXd", v);
}

Configuration::operator sva::PTransformd() const
{
  if(has("rotation"))
  {
    Eigen::Matrix3d r = (*this)("rotation");
    if(has("translation"))
    {
      Eigen::Vector3d t = (*this)("translation");
      return {r, t};
    }
    return {r};
  }
  else if(has("translation"))
  {
    Eigen::Vector3d t = (*this)("translation");
    return {t};
  }
  else if(size() == 7)
  {
    auto & config = *this;
    return {Eigen::Quaterniond{config[0], config[1], config[2], config[3]}.normalized(),
            {config[4], config[5], config[6]}};
  }
  else if(size() == 12)
  {
    auto & config = *this;
    Eigen::Matrix3d rot;
    rot << config[0], config[1], config[2], config[3], config[4], config[5], config[6], config[7], config[8];
    return {rot, {config[9], config[10], config[11]}};
  }
  throw Exception("Stored Json value is not a PTransformd", v);
}

Configuration::operator sva::ForceVecd() const
{
  if(has("couple") && has("force"))
  {
    return {(*this)("couple"), (*this)("force")};
  }
  else if(size() == 6)
  {
    auto & config = *this;
    return {{config[0], config[1], config[2]}, {config[3], config[4], config[5]}};
  }
  throw Exception("Stored Json value is not a ForceVecd", v);
}

Configuration::operator sva::MotionVecd() const
{
  if(has("angular") && has("linear"))
  {
    return {(*this)("angular"), (*this)("linear")};
  }
  else if(size() == 6)
  {
    auto & config = *this;
    return {{config[0], config[1], config[2]}, {config[3], config[4], config[5]}};
  }
  throw Exception("Stored Json value is not a MotionVecd", v);
}

Configuration::Configuration(const std::string & path) : Configuration()
{
  auto doc = std::static_pointer_cast<internal::RapidJSONDocument>(v.doc_);
  doc->SetNull();
  load(path);
}

Configuration Configuration::fromData(const std::string & data)
{
  return Configuration::fromData(data.c_str());
}

Configuration Configuration::fromData(const char * data)
{
  mc_rtc::Configuration config;
  auto & target = *std::static_pointer_cast<internal::RapidJSONDocument>(config.v.doc_);
  mc_rtc::internal::loadData(data, target);
  return config;
}

Configuration Configuration::fromYAMLData(const std::string & data)
{
  return Configuration::fromYAMLData(data.c_str());
}

Configuration Configuration::fromYAMLData(const char * data)
{
  mc_rtc::Configuration config;
  auto & target = *std::static_pointer_cast<internal::RapidJSONDocument>(config.v.doc_);
  target.SetObject();
  mc_rtc::internal::loadYAMLData(data, config);
  return config;
}

Configuration Configuration::rootArray()
{
  mc_rtc::Configuration config;
  auto & target = *std::static_pointer_cast<internal::RapidJSONDocument>(config.v.doc_);
  target.SetArray();
  return config;
}

Configuration Configuration::fromMessagePack(const char * data, size_t size)
{
  mc_rtc::Configuration config;
  mc_rtc::internal::fromMessagePack(config, data, size);
  return config;
}

void Configuration::load(const std::string & path)
{
  auto & target = *std::static_pointer_cast<internal::RapidJSONDocument>(v.doc_);

  if(target.IsNull())
  {
    std::string extension = to_lower(bfs::path(path).extension().string());
    if(extension == ".yml" || extension == ".yaml")
    {
      target.SetObject();
      if(!mc_rtc::internal::loadYAMLDocument(path, *this))
      {
        log::warning("Configuration dump until the attempted conversion:\n{}", this->dump(true));
      }
    }
    else
    {
      mc_rtc::internal::loadDocument(path, target);
    }
  }
  else
  {
    load(mc_rtc::Configuration{path});
  }
}

void Configuration::load(const mc_rtc::Configuration & config)
{
  auto & doc = *std::static_pointer_cast<internal::RapidJSONDocument>(v.doc_);
  auto & target = *static_cast<internal::RapidJSONValue *>(v.value_);

  if(target.IsNull())
  {
    auto & docFrom = *std::static_pointer_cast<internal::RapidJSONDocument>(config.v.doc_);
    target.CopyFrom(docFrom, doc.GetAllocator());
  }
  else
  {
    const auto & v = *static_cast<internal::RapidJSONValue *>(config.v.value_);
    if(v.IsObject())
    {
      for(auto & m : v.GetObject())
      {
        if(target.HasMember(m.name))
        {
          if(m.value.IsObject() && target.FindMember(m.name)->value.IsObject())
          {
            (*this)(m.name.GetString()).load(config(m.name.GetString()));
            continue;
          }
          else
          {
            target.RemoveMember(m.name);
          }
        }
        internal::RapidJSONValue n(m.name, doc.GetAllocator());
        internal::RapidJSONValue v(m.value, doc.GetAllocator());
        target.AddMember(n, v, doc.GetAllocator());
      }
    }
    else if(v.IsArray())
    {
      if(!target.IsArray())
      {
        target.SetArray();
      }
      for(auto & value : v.GetArray())
      {
        target.PushBack(internal::RapidJSONValue{value, doc.GetAllocator()}.Move(), doc.GetAllocator());
      }
    }
    else
    {
      auto & docFrom = *std::static_pointer_cast<internal::RapidJSONDocument>(config.v.doc_);
      target.SetNull();
      target.CopyFrom(docFrom, doc.GetAllocator());
    }
  }
}

void Configuration::loadData(const std::string & data)
{
  auto & target = *std::static_pointer_cast<internal::RapidJSONDocument>(v.doc_);
  if(target.IsNull())
  {
    mc_rtc::internal::loadData(data.c_str(), target);
  }
  else
  {
    load(Configuration::fromData(data));
  }
}

void Configuration::loadYAMLData(const std::string & data)
{
  auto & target = *std::static_pointer_cast<internal::RapidJSONDocument>(v.doc_);
  if(target.IsNull())
  {
    target.SetObject();
    mc_rtc::internal::loadYAMLData(data.c_str(), *this);
  }
  else
  {
    load(Configuration::fromYAMLData(data));
  }
}

void Configuration::save(const std::string & path, bool pretty) const
{
  std::string extension = to_lower(bfs::path(path).extension().string());
  if(extension == ".yml" || extension == ".yaml")
  {
    mc_rtc::internal::saveYAML(path, *this);
  }
  else
  {
    auto & value = *static_cast<internal::RapidJSONValue *>(v.value_);
    mc_rtc::internal::saveDocument(path, value, pretty);
  }
}

std::string Configuration::dump(bool pretty, bool yaml) const
{
  if(yaml)
  {
    return mc_rtc::internal::dumpYAML(*this);
  }
  else
  {
    auto & value = *static_cast<internal::RapidJSONValue *>(v.value_);
    return mc_rtc::internal::dumpDocument(value, pretty);
  }
}

size_t Configuration::toMessagePack(std::vector<char> & data) const
{
  MessagePackBuilder builder(data);
  toMessagePack(builder);
  return builder.finish();
}

void Configuration::toMessagePack(MessagePackBuilder & builder) const
{
  auto & value = *static_cast<internal::RapidJSONValue *>(v.value_);
  mc_rtc::internal::toMessagePack(value, builder);
}

template<>
void Configuration::operator()(const std::string & key, std::string & v) const
{
  try
  {
    v = (std::string)(*this)(key);
  }
  catch(Exception & exc)
  {
    exc.silence();
  }
}

bool Configuration::operator==(const char * rhs) const
{
  return static_cast<std::string>(*this) == rhs;
}

namespace
{
template<typename T>
void add_impl(const std::string & key, T value, void * json_p, void * doc_p)
{
  auto & json = *static_cast<internal::RapidJSONValue *>(json_p);
  auto & doc = *static_cast<internal::RapidJSONDocument *>(doc_p);
  auto & allocator = doc.GetAllocator();
  internal::RapidJSONValue value_ = mc_rtc::internal::toJSON(value, allocator);
  auto member = json.FindMember(key.c_str());
  if(member == json.MemberEnd())
  {
    internal::RapidJSONValue key_(key.c_str(), allocator);
    json.AddMember(key_, value_, allocator);
  }
  else
  {
    member->value = value_;
  }
}

template<typename T>
void push_impl(const Configuration & source, T value, void * json_p, void * doc_p)
{
  auto & json = *static_cast<internal::RapidJSONValue *>(json_p);
  auto & doc = *static_cast<internal::RapidJSONDocument *>(doc_p);
  auto & allocator = doc.GetAllocator();
  internal::RapidJSONValue value_ = mc_rtc::internal::toJSON(value, allocator);
  if(!json.IsArray())
  {
    throw Configuration::Exception("Trying to push data in a non-array value", source);
  }
  json.PushBack(value_, allocator);
}
} // namespace

void Configuration::add_null(const std::string & key)
{
  auto & json = *static_cast<internal::RapidJSONValue *>(v.value_);
  auto & doc = *static_cast<internal::RapidJSONDocument *>(v.doc_.get());
  auto & allocator = doc.GetAllocator();
  internal::RapidJSONValue value_;
  value_.SetNull();
  auto member = json.FindMember(key.c_str());
  if(member == json.MemberEnd())
  {
    internal::RapidJSONValue key_(key.c_str(), allocator);
    json.AddMember(key_, value_, allocator);
  }
  else
  {
    member->value = value_;
  }
}

void Configuration::push_null()
{
  auto & json = *static_cast<internal::RapidJSONValue *>(v.value_);
  auto & doc = *static_cast<internal::RapidJSONDocument *>(v.doc_.get());
  auto & allocator = doc.GetAllocator();
  internal::RapidJSONValue value_;
  value_.SetNull();
  if(!json.IsArray())
  {
    throw Configuration::Exception("Trying to push data in a non-array value", v);
  }
  json.PushBack(value_, allocator);
}

// clang-format off
void Configuration::add(const std::string & key, bool value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, int value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, unsigned int value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, int64_t value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, uint64_t value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, double value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const char * value) { add(key, std::string(value)); }
void Configuration::add(const std::string & key, const std::string & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const Eigen::Vector2d & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const Eigen::Vector3d & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const Eigen::Vector6d & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const Eigen::VectorXd & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const Eigen::Quaterniond & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const Eigen::Matrix3d & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const Eigen::Matrix6d & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const Eigen::MatrixXd & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const sva::PTransformd & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const sva::ForceVecd & value) { add_impl(key, value, v.value_, v.doc_.get()); }
void Configuration::add(const std::string & key, const sva::MotionVecd & value) { add_impl(key, value, v.value_, v.doc_.get()); }
// clang-format on

void Configuration::add(const std::string & key, const Configuration & value)
{
  auto & doc = *static_cast<internal::RapidJSONDocument *>(v.doc_.get());
  auto & allocator = doc.GetAllocator();
  auto & json = *static_cast<internal::RapidJSONValue *>(v.value_);
  internal::RapidJSONValue key_(key.c_str(), allocator);
  internal::RapidJSONValue value_(*static_cast<internal::RapidJSONValue *>(value.v.value_), allocator);
  if(has(key))
  {
    json.RemoveMember(key.c_str());
  }
  json.AddMember(key_, value_, allocator);
}

Configuration Configuration::add(const std::string & key)
{
  auto & doc = *static_cast<internal::RapidJSONDocument *>(v.doc_.get());
  auto & allocator = doc.GetAllocator();
  auto & json = *static_cast<internal::RapidJSONValue *>(v.value_);
  internal::RapidJSONValue key_(key.c_str(), allocator);
  internal::RapidJSONValue value(rapidjson::kObjectType);
  if(has(key))
  {
    json.RemoveMember(key.c_str());
  }
  json.AddMember(key_, value, allocator);
  return (*this)(key);
}

Configuration Configuration::array(const std::string & key, size_t size)
{
  auto & doc = *static_cast<internal::RapidJSONDocument *>(v.doc_.get());
  auto & allocator = doc.GetAllocator();
  auto & json = *static_cast<internal::RapidJSONValue *>(v.value_);
  internal::RapidJSONValue key_(key.c_str(), allocator);
  internal::RapidJSONValue value(rapidjson::kArrayType);
  if(size)
  {
    value.Reserve(size, allocator);
  }
  if(has(key))
  {
    json.RemoveMember(key.c_str());
  }
  json.AddMember(key_, value, allocator);
  return (*this)(key);
}

Configuration Configuration::array(size_t reserve)
{
  if(!v.isArray())
  {
    throw Exception("Cannot store an anonymous array outside of an array", v);
  }
  auto & doc = *static_cast<internal::RapidJSONDocument *>(v.doc_.get());
  auto & allocator = doc.GetAllocator();
  auto & json = *static_cast<internal::RapidJSONValue *>(v.value_);
  internal::RapidJSONValue value(rapidjson::kArrayType);
  value.Reserve(reserve, allocator);
  json.PushBack(value, allocator);
  return (*this)[size() - 1];
}

Configuration Configuration::object()
{
  if(!v.isArray())
  {
    throw Exception("Cannot store an anonymous object outside of an array", v);
  }
  auto & doc = *static_cast<internal::RapidJSONDocument *>(v.doc_.get());
  auto & allocator = doc.GetAllocator();
  auto & json = *static_cast<internal::RapidJSONValue *>(v.value_);
  internal::RapidJSONValue value(rapidjson::kObjectType);
  json.PushBack(value, allocator);
  return (*this)[size() - 1];
}

// clang-format off
void Configuration::push(bool value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(int value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(unsigned int value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(int64_t value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(uint64_t value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(double value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const char * value) { push(std::string(value)); }
void Configuration::push(const std::string & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const Eigen::Vector2d & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const Eigen::Vector3d & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const Eigen::Vector6d & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const Eigen::VectorXd & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const Eigen::Quaterniond & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const Eigen::Matrix3d & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const Eigen::Matrix6d & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const Eigen::MatrixXd & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const sva::PTransformd & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const sva::ForceVecd & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
void Configuration::push(const sva::MotionVecd & value) { push_impl(*this, value, v.value_, v.doc_.get()); }
// clang-format on

void Configuration::push(const mc_rtc::Configuration & value)
{
  auto & doc = *static_cast<internal::RapidJSONDocument *>(v.doc_.get());
  auto & allocator = doc.GetAllocator();
  auto & json = *static_cast<internal::RapidJSONValue *>(v.value_);
  if(!json.IsArray())
  {
    throw Exception("Trying to push data in a non-array value", v);
  }
  internal::RapidJSONValue value_(*static_cast<internal::RapidJSONValue *>(value.v.value_), allocator);
  json.PushBack(value_, allocator);
}

bool Configuration::remove(const std::string & key)
{
  auto & json = *static_cast<internal::RapidJSONValue *>(v.value_);
  if(json.HasMember(key.c_str()))
  {
    json.RemoveMember(key.c_str());
    return true;
  }
  return false;
}

std::vector<std::string> Configuration::keys() const
{
  if(v.isObject())
  {
    return v.keys();
  }
  return {};
}

ConfigurationArrayIterator Configuration::begin() const
{
  return ConfigurationArrayIterator(*this);
}

ConfigurationArrayIterator Configuration::end() const
{
  auto ret = begin();
  ret.i = size();
  return ret;
}

ConfigurationArrayIterator::ConfigurationArrayIterator(const Configuration & conf) : i(0), conf(conf) {}

bool ConfigurationArrayIterator::operator!=(const ConfigurationArrayIterator & rhs) const
{
  return i != rhs.i;
}

ConfigurationArrayIterator & ConfigurationArrayIterator::operator++()
{
  ++i;
  return *this;
}

Configuration ConfigurationArrayIterator::operator*()
{
  return conf[i];
}

const Configuration ConfigurationArrayIterator::operator*() const
{
  return conf[i];
}

} // namespace mc_rtc

std::ostream & operator<<(std::ostream & os, const mc_rtc::Configuration & c)
{
  os << static_cast<std::string>(c);
  return os;
}


text:
/**
 * Copyright (c) 2016-2017, Daniel "Dadie" Korner
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Neither the source code nor the binary may be used for any military use.
 *
 * THIS SOFTWARE IS PROVIDED BY Daniel "Dadie" Korner ''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 Daniel "Dadie" Korner 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.
 **/

// Ext
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>

// Own
#include "rlib/remote/reader.h"

// StdLib
#include <algorithm>
#include <cmath>
#include <experimental/optional>
#include <fstream>
#include <iostream>
#include <string>
#include <thread>
#include <utility>

std::experimental::optional< rlib::common::sample > rlib::remote::reader::
    read_from_buffer(char* buffer, size_t length)
{
    size_t bytes_read = 0;
    // Read remote_id
    int64_t remote_id = *(reinterpret_cast< int64_t* >(buffer));
    if (remote_id != this->remote_id()) {
        return {};
    }
    buffer += sizeof(int64_t);
    bytes_read += sizeof(int64_t);

    // Read time in nanoseconds
    int64_t time_in_ns = *(reinterpret_cast< int64_t* >(buffer));
    buffer += sizeof(int64_t);
    bytes_read += sizeof(int64_t);

    // Read number of values
    int64_t num_of_values = *(reinterpret_cast< int64_t* >(buffer));
    buffer += sizeof(int64_t);
    bytes_read += sizeof(int64_t);

    rlib::common::sample sample;
    {
        sample.time = double(time_in_ns) / double(1000L * 1000L * 1000L);
    }
    while (bytes_read < length && num_of_values > 0) {
        double value = *(reinterpret_cast< double* >(buffer));
        buffer += sizeof(double);
        bytes_read += sizeof(double);
        sample.values.push_back(value);
        --num_of_values;
    }
    if (num_of_values != 0) {
        return {};
    }
    if (length < bytes_read) {
        return {};
    }
    return { sample };
}

rlib::remote::reader::reader(std::string const& filename, size_t sensors,
    uint16_t port, int64_t remote_id)
    : m_filename{ filename }
    , m_port{ port }
    , m_remote_id{ remote_id }
    , m_data(filename, std::ios::in | std::ios::out | std::ios::app)
    , m_length{ 0 }
    , m_sensors{ sensors }
    , m_io_service{}
    , m_socket(m_io_service,
          boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), m_port))
{
    size_t buffer_length = (sizeof(int64_t) * 3) + (sizeof(double) * sensors);
    char buffer[ buffer_length * 2 ];
    // Read Samples data
    auto tellp = this->m_data.tellp();
    this->m_data.seekg(std::ios_base::beg);
    while (!this->m_data.eof()) {
        this->m_data.read(buffer, std::streamsize(buffer_length));
        auto sample = this->read_from_buffer(buffer, buffer_length);
        if (sample && sample->values.size() == this->m_sensors) {
            this->m_samples.push_back(*sample);
            this->m_length = std::max(this->m_length, sample->time);
        }
    }
    std::sort(this->m_samples.begin(), this->m_samples.end(),
        [](auto& a, auto& b) { return a.time < b.time; });

    this->m_data.clear();
    this->m_data.seekg(std::ios_base::end);
    this->m_data.seekp(tellp);

    this->receive();

    this->m_io_service_thread =
        std::thread([&]() { this->m_io_service.run(); });
}

std::string rlib::remote::reader::filename()
{
    return this->m_filename;
}

std::vector< rlib::common::sensor > rlib::remote::reader::sensors()
{
    std::vector< rlib::common::sensor > sensors;
    for (size_t i = 0; i < this->m_sensors; ++i) {
        auto sensor = rlib::common::sensor();
        {
            sensor.name =
                std::to_string(this->remote_id()) + "_" + std::to_string(i);
        }
        sensors.push_back(std::move(sensor));
    }
    return sensors;
}

std::vector< rlib::common::sample > rlib::remote::reader::samples(
    double begin, double end)
{
    std::lock_guard< std::mutex > guard(this->m_samples_mutex);
    auto first = std::find_if(this->m_samples.begin(), this->m_samples.end(),
        [begin](auto& p) { return p.time >= begin; });
    auto last = std::find_if(this->m_samples.begin(), this->m_samples.end(),
        [end](auto& p) { return p.time > end; });
    return std::vector< rlib::common::sample >(first, last);
}
std::vector< rlib::common::event_data > rlib::remote::reader::events(
    double begin, double end)
{
    auto first = std::find_if(this->m_events.begin(), this->m_events.end(),
        [begin](auto& p) { return p.time >= begin; });
    auto last = std::find_if(this->m_events.begin(), this->m_events.end(),
        [end](auto& p) { return p.time > end; });
    return std::vector< rlib::common::event_data >(first, last);
}

double rlib::remote::reader::length()
{
    return this->m_length;
}

uint16_t rlib::remote::reader::port()
{
    return this->m_port;
}

int64_t rlib::remote::reader::remote_id()
{
    return this->m_remote_id;
}

void rlib::remote::reader::receive()
{
    this->m_socket.async_receive(
        boost::asio::buffer(this->m_msg_buffer, this->BUFFER_SIZE),
        [this](boost::system::error_code ec, std::size_t bytes_recvd) {
            if (!ec && bytes_recvd >= (3 * sizeof(int64_t) + sizeof(double))) {
                // Received data!
                char* buffer = this->m_msg_buffer;
                auto sample = this->read_from_buffer(buffer, bytes_recvd);
                if (sample && sample->values.size() == this->m_sensors) {
                    this->m_data.write(this->m_msg_buffer,
                        std::streamsize(3 * sizeof(int64_t) +
                                        sizeof(double) * this->m_sensors));
                    this->m_data.flush();
                    std::lock_guard< std::mutex > guard(this->m_samples_mutex);
                    this->m_samples.push_back(*sample);
                    this->m_length = std::max(this->m_length, sample->time);
                    std::sort(this->m_samples.begin(), this->m_samples.end(),
                        [](auto& a, auto& b) { return a.time < b.time; });
                }
            }
            this->receive();
        });
}

max_stars_repo_name: MeasureTools/readerlib

max_issues_repo_name: MeasureTools/readerlib

max_forks_repo_name: MeasureTools/readerlib


text:
// Copyright Vladimir Prus 2004.
// 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_PLUGIN_WRAPPER_VP_2004_08_25
#define BOOST_PLUGIN_WRAPPER_VP_2004_08_25

#include <boost/mpl/list.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>

namespace utilmm { namespace plugin {

    template<class Wrapped, class Parameters>
    struct plugin_wrapper {};

    struct dll_handle_holder {
        dll_handle_holder(dll_handle dll) : m_dll(dll) {}
        ~dll_handle_holder()
        {
            std::cout << "DLL handle is dying\n";
        }
    private:
        dll_handle m_dll;
    };

    template<class Wrapped>
    struct plugin_wrapper<Wrapped, boost::mpl::list<> >
        : public dll_handle_holder, public Wrapped {
        plugin_wrapper(dll_handle dll) : dll_handle_holder(dll) {}

    };

    template<class Wrapped, class A1>
    struct plugin_wrapper<Wrapped, boost::mpl::list<A1> >
        : public dll_handle_holder, Wrapped {
        plugin_wrapper(dll_handle dll, A1 a1)
        : dll_handle_holder(dll), Wrapped(a1) {}

    };

    template<class Wrapped, class A1, class A2>
    struct plugin_wrapper<Wrapped, boost::mpl::list<A1, A2> >
        : public dll_handle_holder, Wrapped {
        plugin_wrapper(dll_handle dll, A1 a1, A2 a2) :
        dll_handle_holder(dll), Wrapped(a1, a2) {
            std::cout << "plugin_wrapper: " << a1 << " : " << a2 << "\n";
        }
    };

}}

#endif

ext: hh

max_stars_repo_name: annaborn/utilmm

max_issues_repo_name: annaborn/utilmm

max_forks_repo_name: annaborn/utilmm


text:
#ifndef FRACTIONAL_FIT_HH
#define FRACTIONAL_FIT_HH
#include <Eigen/Dense>
#include <vector>

/* this class intends to fit probability of processes to the data
 * with sim_1(x), sim_2(x), sim_3(x) samples, a,b,c probabilities, where a+b+c=1
 * and data(x) sample
 *   a*sim_1 + b*sim_2 + c*sim_3 = data
 * is achieved, via fitting the moments of the 1,2,3 distributions to the moments of the data
 * utilized by correlation_tensor_serie
 */

template<class T>
class fractional_fit{
typedef Eigen::LDLT< Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic > > decomposition;
  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic > Matrix;
  typedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vector;
 public:

  fractional_fit(Matrix const & A, Matrix const & B, Matrix const & D,
		 //Vector const & m, Vector const & n, Vector const & d );
		 std::vector<T> const &m, std::vector<T> const &n, std::vector<T> const &d);
  ~fractional_fit(){}
//  void solve();
  void analytic_solve();
  double operator()(double a);

  T a_min, chi2;
private:
  Matrix A, B, D;
  Vector m, n, d;

  Matrix Sigma; //depends on the 'a' fraction
  Vector l;

};

#endif //FRACTIONAL_FIT_HH

max_stars_repo_name: freemeson/multinomial

max_issues_repo_name: freemeson/multinomial

max_forks_repo_name: freemeson/multinomial


text: #include <boost/range/mutable_iterator.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino