text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file testValues.cpp
 * @author Richard Roberts
 */

#include <gtsam/nonlinear/Values.h>
#include <gtsam/nonlinear/Symbol.h>
#include <gtsam/geometry/Pose2.h>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/base/Testable.h>
#include <gtsam/base/TestableAssertions.h>
#include <gtsam/base/LieVector.h>

#include <CppUnitLite/TestHarness.h>
#include <boost/assign/std/list.hpp> // for operator +=
using namespace boost::assign;
#include <stdexcept>
#include <limits>

using namespace gtsam;
using namespace std;
static double inf = std::numeric_limits<double>::infinity();

// Convenience for named keys
using symbol_shorthand::X;
using symbol_shorthand::L;

const Symbol key1('v',1), key2('v',2), key3('v',3), key4('v',4);

class TestValueData {
public:
	static int ConstructorCount;
	static int DestructorCount;
	TestValueData(const TestValueData& other) { cout << "Copy constructor" << endl; ++ ConstructorCount; }
	TestValueData() { cout << "Default constructor" << endl; ++ ConstructorCount; }
	~TestValueData() { cout << "Destructor" << endl; ++ DestructorCount; }
};
int TestValueData::ConstructorCount = 0;
int TestValueData::DestructorCount = 0;
class TestValue : public DerivedValue<TestValue> {
	TestValueData data_;
public:
	virtual void print(const std::string& str = "") const {}
	bool equals(const TestValue& other, double tol = 1e-9) const { return true; }
	virtual size_t dim() const { return 0; }
	TestValue retract(const Vector&) const { return TestValue(); }
	Vector localCoordinates(const TestValue&) const { return Vector(); }
};

/* ************************************************************************* */
TEST( Values, equals1 )
{
  Values expected;
  LieVector v(3, 5.0, 6.0, 7.0);
  expected.insert(key1,v);
  Values actual;
  actual.insert(key1,v);
  CHECK(assert_equal(expected,actual));
}

/* ************************************************************************* */
TEST( Values, equals2 )
{
  Values cfg1, cfg2;
  LieVector v1(3, 5.0, 6.0, 7.0);
  LieVector v2(3, 5.0, 6.0, 8.0);
  cfg1.insert(key1, v1);
  cfg2.insert(key1, v2);
  CHECK(!cfg1.equals(cfg2));
  CHECK(!cfg2.equals(cfg1));
}

/* ************************************************************************* */
TEST( Values, equals_nan )
{
  Values cfg1, cfg2;
  LieVector v1(3, 5.0, 6.0, 7.0);
  LieVector v2(3, inf, inf, inf);
  cfg1.insert(key1, v1);
  cfg2.insert(key1, v2);
  CHECK(!cfg1.equals(cfg2));
  CHECK(!cfg2.equals(cfg1));
}

/* ************************************************************************* */
TEST( Values, insert_good )
{
  Values cfg1, cfg2, expected;
  LieVector v1(3, 5.0, 6.0, 7.0);
  LieVector v2(3, 8.0, 9.0, 1.0);
  LieVector v3(3, 2.0, 4.0, 3.0);
  LieVector v4(3, 8.0, 3.0, 7.0);
  cfg1.insert(key1, v1);
  cfg1.insert(key2, v2);
  cfg2.insert(key3, v4);

  cfg1.insert(cfg2);

  expected.insert(key1, v1);
  expected.insert(key2, v2);
  expected.insert(key3, v4);

  CHECK(assert_equal(expected, cfg1));
}

/* ************************************************************************* */
TEST( Values, insert_bad )
{
  Values cfg1, cfg2;
  LieVector v1(3, 5.0, 6.0, 7.0);
  LieVector v2(3, 8.0, 9.0, 1.0);
  LieVector v3(3, 2.0, 4.0, 3.0);
  LieVector v4(3, 8.0, 3.0, 7.0);
  cfg1.insert(key1, v1);
  cfg1.insert(key2, v2);
  cfg2.insert(key2, v3);
  cfg2.insert(key3, v4);

  CHECK_EXCEPTION(cfg1.insert(cfg2), ValuesKeyAlreadyExists);
}

/* ************************************************************************* */
TEST( Values, update_element )
{
  Values cfg;
  LieVector v1(3, 5.0, 6.0, 7.0);
  LieVector v2(3, 8.0, 9.0, 1.0);

  cfg.insert(key1, v1);
  CHECK(cfg.size() == 1);
  CHECK(assert_equal(v1, cfg.at<LieVector>(key1)));

  cfg.update(key1, v2);
  CHECK(cfg.size() == 1);
  CHECK(assert_equal(v2, cfg.at<LieVector>(key1)));
}

///* ************************************************************************* */
//TEST(Values, dim_zero)
//{
//  Values config0;
//  config0.insert(key1, LieVector(2, 2.0, 3.0));
//  config0.insert(key2, LieVector(3, 5.0, 6.0, 7.0));
//  LONGS_EQUAL(5, config0.dim());
//
//  VectorValues expected;
//  expected.insert(key1, zero(2));
//  expected.insert(key2, zero(3));
//  CHECK(assert_equal(expected, config0.zero()));
//}

/* ************************************************************************* */
TEST(Values, expmap_a)
{
  Values config0;
  config0.insert(key1, LieVector(3, 1.0, 2.0, 3.0));
  config0.insert(key2, LieVector(3, 5.0, 6.0, 7.0));

  Ordering ordering(*config0.orderingArbitrary());
  VectorValues increment(config0.dims(ordering));
  increment[ordering[key1]] = Vector_(3, 1.0, 1.1, 1.2);
  increment[ordering[key2]] = Vector_(3, 1.3, 1.4, 1.5);

  Values expected;
  expected.insert(key1, LieVector(3, 2.0, 3.1, 4.2));
  expected.insert(key2, LieVector(3, 6.3, 7.4, 8.5));

  CHECK(assert_equal(expected, config0.retract(increment, ordering)));
}

/* ************************************************************************* */
TEST(Values, expmap_b)
{
  Values config0;
  config0.insert(key1, LieVector(3, 1.0, 2.0, 3.0));
  config0.insert(key2, LieVector(3, 5.0, 6.0, 7.0));

  Ordering ordering(*config0.orderingArbitrary());
  VectorValues increment(VectorValues::Zero(config0.dims(ordering)));
  increment[ordering[key2]] = LieVector(3, 1.3, 1.4, 1.5);

  Values expected;
  expected.insert(key1, LieVector(3, 1.0, 2.0, 3.0));
  expected.insert(key2, LieVector(3, 6.3, 7.4, 8.5));

  CHECK(assert_equal(expected, config0.retract(increment, ordering)));
}

/* ************************************************************************* */
//TEST(Values, expmap_c)
//{
//  Values config0;
//  config0.insert(key1, LieVector(3, 1.0, 2.0, 3.0));
//  config0.insert(key2, LieVector(3, 5.0, 6.0, 7.0));
//
//  Vector increment = LieVector(6,
//      1.0, 1.1, 1.2,
//      1.3, 1.4, 1.5);
//
//  Values expected;
//  expected.insert(key1, LieVector(3, 2.0, 3.1, 4.2));
//  expected.insert(key2, LieVector(3, 6.3, 7.4, 8.5));
//
//  CHECK(assert_equal(expected, config0.retract(increment)));
//}

/* ************************************************************************* */
TEST(Values, expmap_d)
{
  Values config0;
  config0.insert(key1, LieVector(3, 1.0, 2.0, 3.0));
  config0.insert(key2, LieVector(3, 5.0, 6.0, 7.0));
  //config0.print("config0");
  CHECK(equal(config0, config0));
  CHECK(config0.equals(config0));

  Values poseconfig;
  poseconfig.insert(key1, Pose2(1,2,3));
  poseconfig.insert(key2, Pose2(0.3, 0.4, 0.5));

  CHECK(equal(config0, config0));
  CHECK(config0.equals(config0));
}

/* ************************************************************************* */
TEST(Values, localCoordinates)
{
	Values valuesA;
	valuesA.insert(key1, LieVector(3, 1.0, 2.0, 3.0));
	valuesA.insert(key2, LieVector(3, 5.0, 6.0, 7.0));

	Ordering ordering = *valuesA.orderingArbitrary();

	VectorValues expDelta = valuesA.zeroVectors(ordering);
//	expDelta.at(ordering[key1]) = Vector_(3, 0.1, 0.2, 0.3);
//	expDelta.at(ordering[key2]) = Vector_(3, 0.4, 0.5, 0.6);

	Values valuesB = valuesA.retract(expDelta, ordering);

	EXPECT(assert_equal(expDelta, valuesA.localCoordinates(valuesB, ordering)));
}

/* ************************************************************************* */
TEST(Values, extract_keys)
{
	Values config;

	config.insert(key1, Pose2());
	config.insert(key2, Pose2());
	config.insert(key3, Pose2());
	config.insert(key4, Pose2());

	FastList<Key> expected, actual;
	expected += key1, key2, key3, key4;
	actual = config.keys();

	CHECK(actual.size() == expected.size());
	FastList<Key>::const_iterator itAct = actual.begin(), itExp = expected.begin();
	for (; itAct != actual.end() && itExp != expected.end(); ++itAct, ++itExp) {
		EXPECT(*itExp == *itAct);
	}
}

/* ************************************************************************* */
TEST(Values, exists_)
{
	Values config0;
	config0.insert(key1, LieVector(Vector_(1, 1.)));
	config0.insert(key2, LieVector(Vector_(1, 2.)));

	boost::optional<const LieVector&> v = config0.exists<LieVector>(key1);
	CHECK(assert_equal(Vector_(1, 1.),*v));
}

/* ************************************************************************* */
TEST(Values, update)
{
	Values config0;
	config0.insert(key1, LieVector(1, 1.));
	config0.insert(key2, LieVector(1, 2.));

	Values superset;
	superset.insert(key1, LieVector(1, -1.));
	superset.insert(key2, LieVector(1, -2.));
	config0.update(superset);

	Values expected;
	expected.insert(key1, LieVector(1, -1.));
	expected.insert(key2, LieVector(1, -2.));
	CHECK(assert_equal(expected,config0));
}

/* ************************************************************************* */
TEST(Values, filter) {
	Pose2 pose0(1.0, 2.0, 0.3);
	Pose3 pose1(Pose2(0.1, 0.2, 0.3));
	Pose2 pose2(4.0, 5.0, 0.6);
	Pose3 pose3(Pose2(0.3, 0.7, 0.9));

  Values values;
  values.insert(0, pose0);
  values.insert(1, pose1);
  values.insert(2, pose2);
  values.insert(3, pose3);

  // Filter by key
  int i = 0;
  Values::Filtered<Value> filtered = values.filter(boost::bind(std::greater_equal<Key>(), _1, 2));
  EXPECT_LONGS_EQUAL(2, filtered.size());
  BOOST_FOREACH(const Values::Filtered<>::KeyValuePair& key_value, filtered) {
    if(i == 0) {
      LONGS_EQUAL(2, key_value.key);
      EXPECT(typeid(Pose2) == typeid(key_value.value));
      EXPECT(assert_equal(pose2, dynamic_cast<const Pose2&>(key_value.value)));
    } else if(i == 1) {
      LONGS_EQUAL(3, key_value.key);
      EXPECT(typeid(Pose3) == typeid(key_value.value));
      EXPECT(assert_equal(pose3, dynamic_cast<const Pose3&>(key_value.value)));
    } else {
      EXPECT(false);
    }
    ++ i;
  }
  EXPECT_LONGS_EQUAL(2, i);

  // construct a values with the view
  Values actualSubValues1(filtered);
  Values expectedSubValues1;
  expectedSubValues1.insert(2, pose2);
  expectedSubValues1.insert(3, pose3);
  EXPECT(assert_equal(expectedSubValues1, actualSubValues1));

  // Filter by type
  i = 0;
  Values::ConstFiltered<Pose3> pose_filtered = values.filter<Pose3>();
  EXPECT_LONGS_EQUAL(2, pose_filtered.size());
  BOOST_FOREACH(const Values::ConstFiltered<Pose3>::KeyValuePair& key_value, pose_filtered) {
    if(i == 0) {
    	EXPECT_LONGS_EQUAL(1, key_value.key);
      EXPECT(assert_equal(pose1, key_value.value));
    } else if(i == 1) {
    	EXPECT_LONGS_EQUAL(3, key_value.key);
      EXPECT(assert_equal(pose3, key_value.value));
    } else {
      EXPECT(false);
    }
    ++ i;
  }
  EXPECT_LONGS_EQUAL(2, i);

  // construct a values with the view
  Values actualSubValues2(pose_filtered);
  Values expectedSubValues2;
  expectedSubValues2.insert(1, pose1);
  expectedSubValues2.insert(3, pose3);
  EXPECT(assert_equal(expectedSubValues2, actualSubValues2));
}

/* ************************************************************************* */
TEST(Values, Symbol_filter) {
  Pose2 pose0(1.0, 2.0, 0.3);
  Pose3 pose1(Pose2(0.1, 0.2, 0.3));
  Pose2 pose2(4.0, 5.0, 0.6);
  Pose3 pose3(Pose2(0.3, 0.7, 0.9));

  Values values;
  values.insert(X(0), pose0);
  values.insert(Symbol('y',1), pose1);
  values.insert(X(2), pose2);
  values.insert(Symbol('y',3), pose3);

  int i = 0;
  BOOST_FOREACH(const Values::Filtered<Value>::KeyValuePair& key_value, values.filter(Symbol::ChrTest('y'))) {
    if(i == 0) {
      LONGS_EQUAL(Symbol('y',1), key_value.key);
      EXPECT(assert_equal(pose1, dynamic_cast<const Pose3&>(key_value.value)));
    } else if(i == 1) {
      LONGS_EQUAL(Symbol('y',3), key_value.key);
      EXPECT(assert_equal(pose3, dynamic_cast<const Pose3&>(key_value.value)));
    } else {
      EXPECT(false);
    }
    ++ i;
  }
  LONGS_EQUAL(2, i);
}

/* ************************************************************************* */
TEST(Values, Destructors) {
	// Check that Value destructors are called when Values container is deleted
	{
		Values values;
		{
			TestValue value1;
			TestValue value2;
			LONGS_EQUAL(2, TestValueData::ConstructorCount);
			LONGS_EQUAL(0, TestValueData::DestructorCount);
			values.insert(0, value1);
			values.insert(1, value2);
		}
		LONGS_EQUAL(4, TestValueData::ConstructorCount);
		LONGS_EQUAL(2, TestValueData::DestructorCount);
	}
	LONGS_EQUAL(4, TestValueData::ConstructorCount);
	LONGS_EQUAL(4, TestValueData::DestructorCount);
}

/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr); }
/* ************************************************************************* */


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

    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_VALUE_AT_IMPL_20060124_2129)
#define FUSION_VALUE_AT_IMPL_20060124_2129

#include <boost/config.hpp>
#include <boost/fusion/algorithm/transformation/transform.hpp>
#include <boost/fusion/container/vector/convert.hpp>
#include <boost/fusion/sequence/intrinsic/value_at.hpp>
#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/unused.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_reference.hpp>

namespace boost {
namespace fusion {

struct zip_view_tag;

namespace detail {
template <typename N> struct poly_value_at {
  template <typename T> struct result;

  template <typename N1, typename Seq>
  struct result<poly_value_at<N1>(Seq)>
      : mpl::eval_if<
            is_same<Seq, unused_type const &>, mpl::identity<unused_type>,
            result_of::value_at<typename remove_reference<Seq>::type, N>> {};

  // never called, but needed for decltype-based result_of (C++0x)
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
  template <typename Seq>
  BOOST_FUSION_GPU_ENABLED typename result<poly_value_at(Seq)>::type
  operator()(Seq &&) const;
#endif
};
} // namespace detail

namespace extension {
template <typename Tag> struct value_at_impl;

template <> struct value_at_impl<zip_view_tag> {
  template <typename Sequence, typename N> struct apply {
    typedef
        typename result_of::transform<typename Sequence::sequences,
                                      detail::poly_value_at<N>>::type values;
    typedef typename result_of::as_vector<values>::type type;
  };
};
} // namespace extension
} // namespace fusion
} // namespace boost

#endif

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text: #include <boost/range/algorithm/lower_bound.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com

#include <iostream>
#include <cstdint>
#include <cmath>
#include <cassert>
#include <bitset>
#include <fstream>
#include <regex>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/float128.hpp>
#include "kyiv.h"
#include "asm_disasm.h"
typedef uint64_t addr_t;
typedef uint64_t word_t;
typedef int64_t  signed_word_t;
typedef uint32_t opcode_t;
typedef boost::multiprecision::int128_t mul_word_t;

constexpr addr3_t word_to_addr3(word_t w){
    constexpr word_t Addr_1_mask_shift = (40-6-11)+1;
    constexpr word_t Addr_1_mask = 0b11'111'111'111ULL << (Addr_1_mask_shift);  // also was -1
    constexpr word_t Addr_2_mask_shift = (40-6-12-11)+1;
    constexpr word_t Addr_2_mask = 0b11'111'111'111ULL << (Addr_2_mask_shift);  // also was -1
    constexpr word_t Addr_3_mask_shift = 0; // Для одноманітності
    constexpr word_t Addr_3_mask = 0b11'111'111'111ULL;

    addr3_t res;
    res.source_1    = (w & Addr_1_mask) >> Addr_1_mask_shift;
    res.source_2    = (w & Addr_2_mask) >> Addr_2_mask_shift;
    res.destination = (w & Addr_3_mask);
    return res;
}

constexpr opcode_t word_to_opcode(word_t w) {
    constexpr word_t op_code_shift = (40-5)+1;
    constexpr word_t op_code_mask = 0b11'111ULL << (op_code_shift);
    opcode_t opcode = (w & op_code_mask) >> op_code_shift;
    return opcode;
}

static constexpr word_t mask_40_bits = (1ULL << 40) - 1; // 0b111...11 -- 40 1-bits, std::pow(2, 41) === 1 << 41
static constexpr word_t mask_41_bit = (1ULL << 40);      // 0b1000...00 -- 40 zeros after the 1

constexpr bool is_negative(word_t w){
    return w & mask_41_bit; // 0 - додатнє, не нуль -- від'ємне
}

constexpr word_t to_negative(word_t w){
    return w | mask_41_bit;
}

constexpr word_t to_positive(word_t w){
    return w & (~mask_41_bit);
}

constexpr uint16_t leftmost_one(word_t w){
    uint16_t ct = 0;
    while (w > 1) {
        ct++;
        w = w >> 1;
    }
    return ct;
}

//hz looks like kostyl but whatever
uint16_t leftmost_one(mul_word_t w){
    uint16_t ct = 0;
    while (w > 1) {
        ct++;
        w = w >> 1;
    }
    return ct;
}

signed_word_t get_absolute(word_t w){
    return static_cast<signed_word_t>(w & mask_40_bits);
}

signed_word_t word_to_number(word_t w){
    signed_word_t sign1 = (is_negative(w) ? -1 : 1);
    signed_word_t abs_val1 = get_absolute(w);
    return sign1 * abs_val1;
}

constexpr bool get_A1(word_t w){
    constexpr word_t A_1_mask = 1ULL << (40-5);
    return w & A_1_mask;
}

constexpr bool get_A2(word_t w){
    constexpr word_t A_2_mask = 1ULL << (40-5-12);
    return w & A_2_mask;
}

constexpr bool get_A3(word_t w){
    constexpr uint64_t A_3_mask = 1ULL << (40-5-24);
    return w & A_3_mask;
}

constexpr addr3_t shift_addr3_byA(addr3_t addr3, uint64_t offset, word_t w){
    if(get_A1(w))
        addr3.source_1 += offset;
    if(get_A2(w))
        addr3.source_2 += offset;
    if(get_A3(w))
        addr3.destination += offset;
    return  addr3;
}

//! Returns: True -- continue, false -- ситуація останову.
bool Kyiv_t::execute_opcode(){
    K_reg = kmem.read_memory(C_reg);
    std::cout << K_reg << std::endl;
    opcode_t opcode = word_to_opcode(K_reg);

    if (opcode == 0) {
        ++C_reg;

    }
//    std::cout << "opcode: " << opcode << std::endl;
    addr3_t addr3 = word_to_addr3(K_reg); // Парі команд потрібна
    std::cout << "A_reg_2: " << A_reg << std::endl;
    std::cout << "Cycle_reg" << Loop_reg << std::endl;
    addr3_t addr3_shifted = shift_addr3_byA(addr3, A_reg, K_reg); // Решта використовують цю змінну

    std::cout << "source 1: " << addr3_shifted.source_1 << std::endl;
    std::cout << "source 2: " << addr3_shifted.source_2 << std::endl;

    disassembly(K_reg, kmem, addr3_shifted);
    //! Ймовірно, потім це діло треба буде відрефакторити -- відчуваю, но де буде проблема - поки не знаю :+)
    switch(opcode){

        //TODO: Тестував лише opcode_add !!! -- решта вважайте невірними, поки не буде тестів. opcode_div
        case arythm_operations_t::opcode_div: [[fallthrough]];
        case arythm_operations_t::opcode_norm: [[fallthrough]];
        case arythm_operations_t::opcode_add: [[fallthrough]];
        case arythm_operations_t::opcode_sub: [[fallthrough]];
        case arythm_operations_t::opcode_addcmd: [[fallthrough]];
        case arythm_operations_t::opcode_subabs: [[fallthrough]];
        case arythm_operations_t::opcode_mul: [[fallthrough]];
        case arythm_operations_t::opcode_addcyc: [[fallthrough]];
        case arythm_operations_t::opcode_mul_round:
            opcode_arythm(addr3_shifted, opcode);
            break;
            //==========================================================================================================
        case flow_control_operations_t::opcode_jmp_less_or_equal: [[fallthrough]];
        case flow_control_operations_t::opcode_jmp_abs_less_or_equal: [[fallthrough]];
        case flow_control_operations_t::opcode_jmp_equal: [[fallthrough]];
        case flow_control_operations_t::opcode_fork_negative: [[fallthrough]];
        case flow_control_operations_t::opcode_call_negative: [[fallthrough]];
        case flow_control_operations_t::opcode_ret: [[fallthrough]];
        case flow_control_operations_t::opcode_group_op_begin: [[fallthrough]];
        case flow_control_operations_t::opcode_group_op_end: [[fallthrough]];
        case flow_control_operations_t::opcode_F: [[fallthrough]];
        case flow_control_operations_t::opcode_stop:
            opcode_flow_control(addr3_shifted, opcode, addr3);
            break;
//==========================================================================================================
        case logic_operations_t::opcode_log_shift:{
            //! TODO: Мені не повністю зрозуміло з обох книг, величина зсуву береться із RAM за адресою,
            //! чи закодована в команді? Швидше перше -- але перевірити!
            word_t shift = kmem.read_memory(addr3_shifted.source_1) ; // Глушко-Ющенко, стор 12, сверджує: "на число разрядов,
            // равное абсолютной величине константы сдвига, размещаемой в шести младших разрядах ячейки а1"
            // 2^6 -- 64, тому решта бітів справді просто дадуть нуль на виході, але все рівно маскую, щоб
            // не було невизначеної поведінки С. Та й зразу знак викидаємо
            std::cout << "shift: " << shift << std::endl;
            shift &= 0b111'111;
            std::cout << "shift after some and: " << shift << std::endl;
            if(is_negative(kmem.read_memory(addr3_shifted.source_1))) {
                kmem.write_memory(addr3_shifted.destination, kmem.read_memory(addr3_shifted.source_2) >> shift);
            } else {
                kmem.write_memory(addr3_shifted.destination , kmem.read_memory(addr3_shifted.source_2) << shift);
                kmem.write_memory(addr3_shifted.destination,  kmem.read_memory(addr3_shifted.destination) & (mask_40_bits | mask_41_bit)); // Зануляємо зайві біти
            }
            ++C_reg;
        }
            break;
        case logic_operations_t::opcode_log_or:{
            kmem.write_memory(addr3_shifted.destination, kmem.read_memory(addr3_shifted.source_1) | kmem.read_memory(addr3_shifted.source_2));
            ++C_reg;
            std::cout << "orr" << kmem.read_memory(addr3_shifted.destination) << std::endl;
        }
            break;
        case logic_operations_t::opcode_log_and:{

            kmem.write_memory(addr3_shifted.destination, kmem.read_memory(addr3_shifted.source_1) & kmem.read_memory(addr3_shifted.source_2));

            ++C_reg;
        }
            break;
        case logic_operations_t::opcode_log_xor:{
            kmem.write_memory(addr3_shifted.destination, kmem.read_memory(addr3_shifted.source_1) ^ kmem.read_memory(addr3_shifted.source_2));
            ++C_reg;
        }
            break;
//==========================================================================================================
        case IO_operations_t::opcode_read_perfo_data:{
                std::ifstream punch_cards;
                std::string line;
                std::string perfo;
                std::vector<std::string> argv;
                signed_word_t number;

                punch_cards.open("../../mem/punch_cards_in.txt");

                int counter = 0;
                int num_counter = 0;
                bool flag;

                while (punch_cards) {
                    std::getline(punch_cards, line);
                    if (counter == perfo_num) {
                        perfo = line.substr(addr3_shifted.destination, line.size());
                        boost::split(argv, perfo, boost::is_any_of(" "), boost::algorithm::token_compress_off);
                        for(auto num : argv){
                            if(num_counter == addr3_shifted.source_2 - addr3_shifted.source_1){
                                flag = true;
                                break;
                            }
                            number = std::stol(num);
                            if(number >= 0){
                                kmem.write_memory(addr3_shifted.source_1 + num_counter, number);
                            }else{
                                kmem.write_memory(addr3_shifted.source_1 + num_counter, to_negative(std::abs(number)));
                            }
                            num_counter++;
                        }
                    }else if(counter > num_counter){
                        perfo = line;
                        boost::split(argv, perfo, boost::is_any_of(" "), boost::algorithm::token_compress_off);
                        for(auto num : argv){
                            if(num_counter == addr3_shifted.source_2 - addr3_shifted.source_1){
                                flag = true;
                                break;
                            }
                            number = std::stoi(num);
                            if (number >= 0) {
                                kmem.write_memory(addr3_shifted.source_1 + num_counter, number);
                            } else {
                                kmem.write_memory(addr3_shifted.source_1 + num_counter, to_negative(std::abs(number)));
                            }
                            num_counter ++;
                        }
                    }
                    if(flag == true){
                        break;
                    }
                    counter++;
                }
                punch_cards.close();
        }
            break;

        case IO_operations_t::opcode_read_perfo_binary:{
            std::ifstream punch_cards;
            std::ifstream heads;
            std::string head;
            std::string line;

            punch_cards.open("../punched_tape.txt");
            heads.open("../heads.txt");

            std::getline(heads, head);
            std::getline(heads, head);
            // int num = std::stoi(head);
            size_t num = h;
            int counter = 0;
            int com_counter = 0;
            bool flag = false;

            while(punch_cards){
                std::getline(punch_cards, line);
                int pos = 0;
                if(counter == num){
                    if(com_counter < addr3_shifted.source_2 - addr3_shifted.source_1){
                        kmem.write_memory(addr3_shifted.source_1 + com_counter, std::stol(line, 0, 8));
                        com_counter++;
                    }else{
                        flag = true;
                        break;
                    }
                }else if(counter > num){
                    if(com_counter < addr3_shifted.source_2 - addr3_shifted.source_1){
                        kmem.write_memory(addr3_shifted.source_1 + com_counter, std::stol(line, 0, 8));
                        com_counter ++;
                    }else{
                        flag = true;
                        break;
                    }

                }
                if(flag){
                    break;
                }
            }
            h += com_counter;
        }
            break;

        case IO_operations_t::opcode_read_magnetic_drum:{
            std::ifstream magnetic_drum;
            std::string line;
            std::string data;
            std::vector<std::string> argv;
            signed_word_t number;

            magnetic_drum.open("../../mem/drum_in.txt");

            int counter = 0;
            int num_counter = 0;
            bool flag;
            while (magnetic_drum) {
                std::getline(magnetic_drum, line);
                if(counter == drum_num_read){
                    data = line.substr(drum_zone_read, line.size());
                    boost::split(argv, data, boost::is_any_of(" "), boost::algorithm::token_compress_off);
                    for(const auto& num : argv){
                        if(num_counter == addr3_shifted.source_2 - addr3_shifted.source_1){
                            flag = true;
                            break;
                        }
                        number = std::stoi(num);
                        if(number >= 0){
                            kmem.write_memory(addr3_shifted.source_1 + num_counter, number);
                        }else{
                            kmem.write_memory(addr3_shifted.source_1 + num_counter, to_negative(std::abs(number)));
                        }
                        num_counter ++;
                    }
                }else if(counter > drum_num_read){
                    data = line;
                    boost::split(argv, data, boost::is_any_of(" "), boost::algorithm::token_compress_off);
                    for(const auto& num : argv){
                        if(num_counter == addr3_shifted.source_2 - addr3_shifted.source_1){
                            flag = true;
                            break;
                        }
                        number = std::stoi(num);
                        if(number >= 0){
                            kmem.write_memory(addr3_shifted.source_1 + num_counter, number);
                        }else{
                            kmem.write_memory(addr3_shifted.source_1 + num_counter, to_negative(std::abs(number)));
                        }
                        num_counter ++;
                    }
                }
                if(flag){
                    break;
                }
                counter ++;
            }

            magnetic_drum.close();
        }
            break;

        case IO_operations_t::opcode_write_perfo_binary:{
            std::ofstream myfile;
            myfile.open("../punc_cards_out.txt");
            if (myfile.is_open())
            {
                for(uint64_t i = 0; i <= addr3_shifted.source_2; i++){
                    myfile << word_to_number(kmem.read_memory(addr3_shifted.source_1 + i));
                    myfile << ' ';
                }
                myfile.close();
            }else {
                std::cout << "Unable to open file";
            }
            C_reg = addr3_shifted.destination;
            K_reg = kmem.read_memory(C_reg);
        }

        case IO_operations_t::opcode_write_magnetic_drum:{
            std::ofstream myfile;
            myfile.open("../magnetic_drum.txt");
            if (myfile.is_open())
            {
                for(uint64_t i = 0; i <= addr3_shifted.source_2; i++){
                    myfile << word_to_number(kmem.read_memory(addr3_shifted.source_1 + i));
                    myfile << ' ';
                }
                myfile.close();
            }else {
                std::cout << "Unable to open file";
            }
            C_reg = addr3_shifted.destination;
            K_reg = kmem.read_memory(C_reg);
        }
            break;

        case IO_operations_t::opcode_init_magnetic_drum:{
            if (addr3_shifted.source_1 == 0) {
                drum_num_read = addr3_shifted.source_2;
                drum_zone_read = addr3_shifted.destination;
            } else if (addr3_shifted.source_1 == 1) {
                drum_num_write = addr3_shifted.source_2;
                drum_zone_write = addr3_shifted.destination;
            }
        }
            break;
//==========================================================================================================
        default:
            T_reg = true; // ! TODO: Не пам'ятаю, яка там точно реакція на невідому команду
    }
    return !T_reg;
}

void Kyiv_t::opcode_arythm(const addr3_t& addr3, opcode_t opcode){
    //! TODO: Додати перевірку на можливість запису. Що робила машина при спробі запису в ПЗП?
    //! TODO: Додати перевірку на вихід за границю пам'яті -- воно ніби зациклювалося при тому
    //! (зверталося до байта add mod 2^11, в сенсі), але точно не знаю.
    signed_word_t sign1 = (is_negative(kmem.read_memory(addr3.source_1)) ? -1 : 1);
    signed_word_t sign2 = (is_negative(kmem.read_memory(addr3.source_2)) ? -1 : 1);
    std::cout << "sign 2" << sign2 << std::endl;
    std::cout << "gfuigfalhf: " << addr3.source_2 << std::endl;
    word_t abs_val1 = static_cast<signed_word_t>(kmem.read_memory(addr3.source_1) & mask_40_bits);
    word_t abs_val2 = static_cast<signed_word_t>(kmem.read_memory(addr3.source_2) & mask_40_bits);;
    signed_word_t res = sign1 * (signed_word_t) abs_val1;

    signed_word_t res_for_norm;
    mul_word_t res_mul;
    uint16_t power = 40 - leftmost_one(abs_val1) -1;

    std::cout << sign1 * (signed_word_t) abs_val1 << "gifhdaflvdjasbh\t" << sign2 * (signed_word_t) abs_val2 << std::endl;
    switch(opcode){
        case arythm_operations_t::opcode_add:
            res += sign2 * (signed_word_t) abs_val2;
            break;
        case arythm_operations_t::opcode_sub:
            res -= sign2 * (signed_word_t) abs_val2;
            break;
        case arythm_operations_t::opcode_addcmd:
            res += (signed_word_t) abs_val2;
            break;
        case arythm_operations_t::opcode_subabs:
            res = (signed_word_t) abs_val1 - (signed_word_t) abs_val2;
            break;
        case arythm_operations_t::opcode_addcyc:
            res += sign2 * (signed_word_t) abs_val2; // Те ж, що і для opcode_add, але подальша обробка інша
            break;
        case arythm_operations_t::opcode_mul: [[fallthrough]];
        case arythm_operations_t::opcode_mul_round:
            res_mul = sign1 * (mul_word_t) abs_val1 * sign2 * (mul_word_t) abs_val2;
            std::cout << "H : " << res_mul << std::endl;
            break;
        case arythm_operations_t::opcode_norm: {
            res_for_norm = sign1 * (abs_val1 << power);
        }
            break;
        case arythm_operations_t::opcode_div: {
            if ((abs_val2 == 0) || (abs_val2 < abs_val1)) {
                T_reg = true;
                ++C_reg;
                return;
            }
            res_mul = ((mul_word_t) abs_val1 << 40) / (mul_word_t) abs_val2;
            // std::cout << "Div " << res_mul << std::endl;
        }
            break;

        default:
            assert(false && "Should never been here!");
    }

    if(opcode == arythm_operations_t::opcode_add ||
       opcode == arythm_operations_t::opcode_sub ||
       opcode == arythm_operations_t::opcode_subabs     //! TODO: Я не плутаю, результат може мати знак?
            ) {
        //! TODO: До речі, а якщо переповнення, воно кінцевий регістр змінювало до останову, чи ні?
        // Тут я зробив, ніби ні -- але ХЗ, могло. Щоб точно знати -- треба моделювати на рівні схем ;=) --
        // як ви і поривалися. Але це не має бути важливим.
        bool is_negative = (res < 0);
        if (is_negative)
            res = -res;
        assert(res >= 0);
        if (res & mask_41_bit) { // if sum & CPU1.mask_41_bit == 1 -- overflow to sign bit
            T_reg = true;
            ++C_reg;
            return;
        }
        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res) & mask_40_bits);
        // std::cout << -1 * res << std::endl;
        if (is_negative)
            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);
        //! "Нуль, получаемый как разность двух равных чисел, имеет отрицательный знак" -- стор. 13 Глушко-Ющенко, опис УПЧ
        if(opcode == arythm_operations_t::opcode_sub && res == 0
           && abs_val2 == 0 //! TODO: Моє припущення -- перевірити!
                ){
            kmem.write_memory(addr3.destination, res | mask_41_bit);
            std::cout << "NEGATIVE 0" << (res | mask_41_bit) << std::endl;
        }
    } else if(opcode == arythm_operations_t::opcode_addcmd){
        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res) & mask_40_bits);
        kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | (kmem.read_memory(addr3.source_2) & mask_41_bit)); // Копіюємо біт знаку з source_2 // edited тут наче так має бути
    } else if(opcode == arythm_operations_t::opcode_addcyc){
        //! TODO: Вияснити, а як ця команда функціонує.
        // "Отличается от обычного сложения лишь тем, что  в нем отсутствует блокировка при выходе
        // из разполагаемого числа разрядов. Перенос из знакового разряда поступает в младший разряд
        // сумматора".
        // Питання (нумеруючи біти з 1 до 41):
        // 1. Перенос із 40 в 41 біт тут можливий? З фрази виглядає, що так.
        // 2. Якщо додавання переносу до молодшого біту виникло переповнення, що далі?
        //    Так виглядає, що воно не може виникнути, але чи я не помилився? -- не може, десь через переніс буде 0
        bool is_negative = (res < 0);
        // std::cout << (res) << std::endl;
        if (is_negative)
            res = -res;
        assert(res >= 0);

        // std::cout << std::bitset<41> (res) << std::endl;
        if(res & mask_41_bit){
            res += 1; // Маємо перенос із знакового біту
        }

        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res) & mask_40_bits);
        if (is_negative)
            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);
    } else if(opcode == arythm_operations_t::opcode_mul ||
              opcode == arythm_operations_t::opcode_mul_round
            ) {
        bool is_negative = (res_mul < 0);
        //std::cout << res_mul << std::endl;
        if (is_negative)
            res_mul = -res_mul;
        assert(res_mul >= 0);

        uint16_t leftmost = leftmost_one(res_mul);

        if (opcode == arythm_operations_t::opcode_mul_round) {
            res_mul += 1ULL << 41;
        }
        res_mul = res_mul >> 40;

        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res_mul) & mask_40_bits);
        std::cout << "DEBUUUUUUUUG2 " << static_cast<uint64_t>(res_mul) << std::endl;
        // std::cout << is_negative << std::endl;
        if (is_negative)
            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);
        std::cout << "DEBUUUUUUUUG " << word_to_number(kmem.read_memory(addr3.destination)) << std::endl;
//        std::cout << std::bitset<41>(kmem[addr3.destination]) << std::endl;
//        std::cout << "Mult res: " << word_to_number(kmem[addr3.destination]) << std::endl;

    } else if (opcode == arythm_operations_t::opcode_norm) {
        bool is_negative = (res_for_norm < 0);

        if (is_negative)
            res_for_norm = -res_for_norm;
        assert(res_for_norm >= 0);
//
//        std::cout << "norm_val: " << (res_for_norm) << std::endl;
//        std::cout << "norm_power: " << (power) << std::endl;
//        std::cout << "norm_val_64: " << std::bitset<64>(res_for_norm) << std::endl;
//        std::cout << "norm_val_41: " << std::bitset<41>(res_for_norm) << std::endl;

        kmem.write_memory(addr3.source_2, power);
        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res_for_norm) & mask_40_bits);
        if (is_negative)
            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);
//
//        std::cout << "norm_val_mem: " << kmem[addr3.destination] << std::endl;
//        std::cout << "norm_val_pow: " << kmem[addr3.source_2] << std::endl;
    } else if (opcode == arythm_operations_t::opcode_div) {
        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res_mul) & mask_40_bits);
        if ((sign1 * sign2) == -1)
            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);
//        std::cout << "Div res: " << word_to_number(kmem[addr3.destination]) << std::endl;
    }
    ++C_reg;
}

void Kyiv_t::opcode_flow_control(const addr3_t& addr3_shifted, opcode_t opcode, const addr3_t &addr3){
    signed_word_t sign1 = (is_negative(kmem.read_memory(addr3_shifted.source_1)) ? -1 : 1);
    signed_word_t sign2 = (is_negative(kmem.read_memory(addr3_shifted.source_2)) ? -1 : 1);
    signed_word_t abs_val1 = static_cast<signed_word_t>(kmem.read_memory(addr3_shifted.source_1) & mask_40_bits);
    signed_word_t abs_val2 = static_cast<signed_word_t>(kmem.read_memory(addr3_shifted.source_2) & mask_40_bits);;

    switch (opcode) {
        case flow_control_operations_t::opcode_jmp_less_or_equal: {
            if((sign1 * abs_val1) <= (sign2 * abs_val2)){
                C_reg = addr3_shifted.destination;
            } else {
                ++C_reg;
            }
        }
            break;
        case flow_control_operations_t::opcode_jmp_abs_less_or_equal: {
//            std::cout << "Num1 " << get_absolute(kmem[addr3_shifted.source_1]) << std::endl;
//            std::cout << "Num2 " << get_absolute(kmem[addr3_shifted.source_2]) << std::endl;
            if (abs_val1 <= abs_val2) {
                C_reg = addr3_shifted.destination;
            } else {
                ++C_reg;
            }
        }
            break;
        case flow_control_operations_t::opcode_jmp_equal: {
            if( (sign1 * abs_val1) == (sign2 * abs_val2)){
                C_reg = addr3_shifted.destination;
            } else {
                ++C_reg;
            }
        }
            break;
        case flow_control_operations_t::opcode_fork_negative: {
            if( is_negative(kmem.read_memory(addr3_shifted.source_1)) ){
                C_reg = addr3_shifted.destination;
            }else{
                C_reg = addr3_shifted.source_2;
            }
        }
            break;
        case flow_control_operations_t::opcode_call_negative:{
            if( is_negative(kmem.read_memory(addr3_shifted.source_1)) ){
                P_reg = addr3_shifted.source_2; //! TODO: Згідно тексту стор 342 (пункт 18) Гнеденко-Королюк-Ющенко-1961
                //! Глушков-Ющенко, стор 13, УПП не до кінця однозначна -- a1 без штриха, це зрозуміло,
                //! але з врахуванням A і біта модифікатора, чи без?
                //! Виглядає, що в таблиці на стор 180 -- помилка ('A2 => P -- зайвий штрих точно помилка,
                //! чи помилка, що, немає зсуву на А?).
                //! Однак, в  Гнеденко-Королюк-Ющенко-1961 опкод (32) суперечить опкоду в Глушко-Ющенко.
                //! Перевірити!
                C_reg = addr3_shifted.destination;
            }else{
                ++C_reg; //! Тут P_reg не мала б змінювати
            }
        }
            break;
        case flow_control_operations_t::opcode_ret:{
            C_reg = P_reg;
        }
            break;
        case flow_control_operations_t::opcode_group_op_begin:{
            // У книжці Глушков-Ющенко на ст. 14, ймовірно, помилка, бо навіть словами пояснено,
            // що береться значення а1 і а2, але разом із тим наголошено, що береться не 'а1 чи 'а2,
            // а саме а1 і а2. В кінці цієї книжки та у Гнеденко-Королюк-Ющенко пише,
            // ніби беруться значення, тому тут реалізовано саме так.
            Loop_reg =  addr3_shifted.source_1; //word_to_number(kmem.read_memory(addr3_shifted.source_1));
            A_reg = addr3_shifted.source_2; // word_to_number(kmem.read_memory(addr3_shifted.source_2));
            if (A_reg == Loop_reg) {
                C_reg = addr3_shifted.destination;
            } else {
                ++C_reg;
            }

            std::cout << "A_reg: " << A_reg << std::endl;
        }
            break;
        case flow_control_operations_t::opcode_group_op_end:{
            // Такий самий прикол, як з НГО
            // not a value
            A_reg += addr3.source_1;// word_to_number(kmem.read_memory(addr3_shifted.source_1));
            if (A_reg == Loop_reg) {
                C_reg = word_to_number(addr3_shifted.destination);
            } else {
                C_reg = (addr3_shifted.source_2);
            }
        }
            break;
        case flow_control_operations_t::opcode_F:{
            // Якщо я правильно розібралася з 2 попередними командами, то тут все зрозуміло і немає суперечностей
            A_reg = word_to_addr3(kmem.read_memory(addr3_shifted.source_1)).source_2;
            word_t res = kmem.read_memory(A_reg);
            kmem.write_memory(addr3_shifted.destination, res);
            ++C_reg;
        }
            break;
        case flow_control_operations_t::opcode_stop:{ //! TODO: Вона враховує стан кнопки на пульті?
            // From Glushkov-Iushchenko p. 55
            // If B_tumb == 0 -> neutral mode -> full stop
            // If B_tumb > 0 -> just skip one command without full stop
            // From Glushkov-Iushchenko pp. 163-164
            // If B_tumb == 1 -> stop by 3d address
            // If B_tumb == 2 -> stop by command number
            // I'm not sure what to do with 1st and 2nd B_tumb (maybe that should be handled in main???)
            if (!B_tumb) {
                T_reg = true;
                ++C_reg;
            }
            else {
                C_reg += 2;
            }
        }
            break;
    }
}

ext: cpp


text:
/************************************************************************
MIT License

Copyright (c) 2021 Deqi Tang

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
************************************************************************/

#include "atomsciflow/vasp/vasp_poscar.h"

#include <boost/algorithm/string.hpp>
#include <armadillo>
#include <iostream>
#include <vector>

#include "atomsciflow/utils/structure.h"
#include "atomsciflow/base/element.h"

namespace atomsciflow {

namespace ba = boost::algorithm;

VaspPoscar::VaspPoscar() {
    selective_dynamics = false;
}

void VaspPoscar::get_xyz(std::string xyzfile) {
    auto element_map = get_element_number_map();
    this->xyz.read_xyz_file(xyzfile);
    for (const auto& elem : this->xyz.elements_set) {
        this->elem_natom_in_number_order.push_back(std::pair<std::string, int>{elem, element_map[elem].number});
    }
    std::sort(
        this->elem_natom_in_number_order.begin(),
        this->elem_natom_in_number_order.end(),
        [](const std::pair<std::string, int>& a, const std::pair<std::string, int>& b) -> bool {
            return a.second < b.second;
        }
    );
    for (auto& item : this->elem_natom_in_number_order) {
        item.second = 0;
        for (const auto& atom : this->xyz.atoms) {
            if (item.first == atom.name) {
                ++item.second;
            }
        }
    }
}

/**
 * @brief VaspPoscar::to_string
 * @param coordtype
 *  candidates:
 *      "direct" | "cartesian", ignoring upper or lower case
 * @return The vasp POSCAR as a string
 * Note:
 *  THe order of atoms in the gnerated POSCAR string might be
 *  different from the input xyz file. Because, the atoms in
 *  POSCAR is grouped considering the element type.
 */
std::string VaspPoscar::to_string(std::string coordtype = "Cartesian") {
    std::string out = "";
    auto cell = this->xyz.cell;
    out += "general comment\n";
    out += "1.0\n";
    for (const auto& vec : cell) {
        out += std::to_string(vec[0]);
        out += "\t";
        out += std::to_string(vec[1]);
        out += "\t";
        out += std::to_string(vec[2]);
        out += "\n";
    }
    for (const auto& item : this->elem_natom_in_number_order) {
        out += item.first;
        out += " ";
    }
    out += "\n";
    for (const auto& item : this->elem_natom_in_number_order) {
        out += std::to_string(item.second);
        out += " ";
    }
    out += "\n";
    if (this->selective_dynamics == true) {
        out += "Selective dynamics\n";
        if (ba::to_lower_copy(coordtype) == "cartesian") {
            out += "Cartesian\n";
            for (const auto& element_pair : this->elem_natom_in_number_order) {
                for (const auto& atom : this->xyz.atoms) {
                    if (element_pair.first == atom.name) {
                        out += std::to_string(atom.x);
                        out += "\t";
                        out += std::to_string(atom.y);
                        out += "\t";
                        out += std::to_string(atom.z);
//                        for (auto fix : atom.fix) {
//                            if (fix == true) {
//                                out += "\tF";
//                            } else if (fix == False) {
//                                out += "\tT";
//                            }
//                        }
                        out += "\n";
                    }
                }
            }
        } else if (ba::to_lower_copy(coordtype) == "direct") {

            std::vector<Atom> atoms_frac;
            atoms_cart_to_frac(atoms_frac, this->xyz.atoms, this->xyz.cell);

            out += "Direct\n";
            for (const auto& element_pair : this->elem_natom_in_number_order) {
                for (int k = 0; k < this->xyz.atoms.size(); k++) {
                    if (element_pair.first == this->xyz.atoms[k].name) {
                        out += std::to_string(atoms_frac[k].x);
                        out += std::to_string(atoms_frac[k].y);
                        out += std::to_string(atoms_frac[k].z);
//                        for (auto fix in this->xyz.atoms[k].fix) {
//                            if (fix == true) {
//                                out += "\tF";
//                            } else if (fix == false) {
//                                out += "\tT";
//                            }
//                        }
                        out += "\n";
                    }
                }
            }
        }
    } else if (false == this->selective_dynamics) {
        if (ba::to_lower_copy(coordtype) == "cartesian") {
            out += "Cartesian\n";
            for (const auto& item : this->elem_natom_in_number_order) {
                for (const auto& atom : this->xyz.atoms) {
                    if (atom.name == item.first) {
                        out += std::to_string(atom.x);
                        out += "\t";
                        out += std::to_string(atom.y);
                        out += "\t";
                        out += std::to_string(atom.z);
                        out += "\n";
                    }
                }
            }
        } else if (ba::to_lower_copy(coordtype) == "direct") {
            std::vector<Atom> atoms_frac;
            atoms_cart_to_frac(atoms_frac, this->xyz.atoms, this->xyz.cell);

            out += "Direct\n";
            for (const auto& item : this->elem_natom_in_number_order) {
                for (int k = 0; k < this->xyz.atoms.size(); k++) {
                    if (this->xyz.atoms[k].name == item.first) {
                        out += std::to_string(atoms_frac[k].x);
                        out += "\t";
                        out += std::to_string(atoms_frac[k].y);
                        out += "\t";
                        out += std::to_string(atoms_frac[k].z);
                        out += "\n";
                    }
                }
            }
        }
    } else {
        std::cout << "------------------------------------------------------------------------" << "\n";
        std::cout << "Warning: atomsciflow::Vasp::VaspPoscar\n";
        std::cout << "ifstatic could only be true or false\n";
        std::cout << "------------------------------------------------------------------------" << "\n";
        std::exit(1);
    }
    out += "\n";
    return out;
}

} // namespace atomsciflow

max_stars_repo_name: DeqiTang/build-test-atomsciflow

max_issues_repo_name: DeqiTang/build-test-atomsciflow

max_forks_repo_name: DeqiTang/build-test-atomsciflow


text:
/*
 * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include <gtest/gtest.h>
#include "base_consts.h"
#include "base_mns_consts.h"
#include "base_errors_consts.h"
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include "service_channels.h"
#define private public
#define protected public
#include "discovery_zk_client.h"
#undef private
#undef protected
using namespace meituan_mns;

class DiscZkClientTest : public testing::Test {
 public:
  void SetUp() {
    std::vector<SGService> service_list;
    SGService service1;
    service1.__set_ip("127.0.0.1");
    service1.__set_protocol("protocol");
    service1.__set_appkey("octo.naming.service.tmy");
    service1.__set_port(5266);
    service1.__set_version("test");
    service1.__set_weight(-1);
    service1.__set_fweight(101);
    service_list.push_back(service1);
    node = boost::make_shared<getservice_res_param_t>();
    node->__set_localAppkey("");
    node->__set_remoteAppkey("octo.naming.service.tmy");
    node->__set_serviceList(service_list);
    node->__set_protocol("thrift");
    discovery_service_ = DiscoveryZkClient::GetInstance();

    req.protocol = "thrift";
    req.remoteAppkey = "octo.naming.service.tmy";
    req.serviceName = "http://mns.octo.com";
    service_channel = boost::make_shared<ServiceChannels>();
    service_channel->SetAllChannel(false);
    service_channel->SetBankboneChannel(false);
    service_channel->SetOriginChannel(false);
    service_channel->SetSwimlaneChannel(false);
  }
 public:
  boost::shared_ptr<getservice_res_param_t> node;
  DiscoveryZkClient *discovery_service_;
  ProtocolRequest req;
  boost::shared_ptr<ServiceChannels> service_channel;
};

TEST_F(DiscZkClientTest, DiscSrvListByProtocolTest) {
  EXPECT_EQ(0, discovery_service_->DiscSrvListByProtocol(node));
  node->__set_remoteAppkey("octo.naming.service.mtconfig");
  EXPECT_EQ(0, discovery_service_->DiscSrvListByProtocol(node));
  node->__set_remoteAppkey("test");
  EXPECT_EQ(-101, discovery_service_->DiscSrvListByProtocol(node));
}

TEST_F(DiscZkClientTest, DiscRouteListByProtocolTest) {
  std::vector<CRouteData> routeList;
  std::string localAppkey = "test";
  std::string appKey = "octo.naming.service.tmy";
  std::string version = "";
  std::string protocol = "thrift";
  bool route_flag = false;
  EXPECT_EQ(0, discovery_service_->DiscRouteListByProtocol(routeList,
    localAppkey,appKey, version,protocol, route_flag));
  EXPECT_EQ(ERR_ZK_LIST_SAME_BUFFER, discovery_service_->DiscRouteListByProtocol(routeList,
      localAppkey,appKey, version,protocol, route_flag));
  appKey = "test";
  EXPECT_EQ(ERR_NODE_NOTFIND,discovery_service_->DiscRouteListByProtocol(routeList,
      localAppkey,appKey, version,protocol, route_flag));
}

TEST_F(DiscZkClientTest, DiscAppkeyByServiceNameTest) {
  std::set<std::string> appkeys;
  std::string local_appkey = "test";
  std::string service_name = "http://mns.octo.com";
  std::string version = "0";
  std::string protocol = "thrift";
  EXPECT_EQ(0, discovery_service_->DiscAppkeyByServiceName(appkeys,
      local_appkey,service_name,version, protocol));
  service_name = "test";
  EXPECT_EQ(ERR_NODE_NOTFIND, discovery_service_->DiscAppkeyByServiceName(appkeys,
    local_appkey,service_name,version, protocol));
}

TEST_F(DiscZkClientTest, DiscoveryListFromCacheTest) {
  std::vector<SGService> srvlist;
  GetMnsCacheParams params;
  params.appkey = "octo.naming.service.mtconfig";
  params.version = "octo.naming.service.mtconfig";
  params.env = "test";
  params.protocol = "thrift";
  //EXPECT_EQ(0, discovery_service_->
  // DiscoveryListFromCache(srvlist, params)) ; //todo for private

}

TEST_F(DiscZkClientTest, DivRangeDiscIndexTest) {
  int index = 1;
  int begin = 0;
  int end = 3;
  int child_count = 5;
  discovery_service_->DivRangeDiscIndex(index, begin, end, child_count);
}

ext: cc

max_stars_repo_name: wuxianxingkong/octo-ns

max_issues_repo_name: wuxianxingkong/octo-ns

max_forks_repo_name: wuxianxingkong/octo-ns


text:
/**
 * DataFileManager.cpp
 *
 * History:
 * David Cox on Wed Oct 06 2004 - Created.
 * Paul Jankunas on 09/06/05 - Added initialzation code for filename
 *  and copying of filename to the open file routine.
 *
 * Copyright (c) 2004 MIT. All rights reserved.
 */

#include "DataFileManager.h"

#include <boost/filesystem/convenience.hpp>

#include "PlatformDependentServices.h"

BEGIN_NAMESPACE_MW

bool DataFileManager::DataFile::create(const std::string &filename,
                                       bool overwrite,
                                       std::unique_ptr<DataFile> &dataFile)
{
    const auto filepath = boost::filesystem::path(filename);

    // Check for an existing file
    if (boost::filesystem::exists(filepath)) {
        if (!overwrite) {
            merror(M_FILE_MESSAGE_DOMAIN, "Can't overwrite existing file \"%s\"", filename.c_str());
            return false;
        }
        try {
            boost::filesystem::remove(filepath);
        } catch (const std::exception &e) {
            merror(M_FILE_MESSAGE_DOMAIN, "Can't remove existing file \"%s\": %s", filename.c_str(), e.what());
            return false;
        }
    }

    // Ensure that the destination directory exists
    try {
        boost::filesystem::create_directories(filepath.parent_path());
    } catch (const std::exception &e) {
        merror(M_FILE_MESSAGE_DOMAIN, "Could not create data file destination directory: %s", e.what());
        return false;
    }

    // Create the file
    try {
        dataFile.reset(new DataFile(filename));
    } catch (const SimpleException &e) {
        merror(M_FILE_MESSAGE_DOMAIN, "Could not create file \"%s\": %s", filename.c_str(), e.what());
        return false;
    }

    return true;
}

DataFileManager::DataFile::~DataFile() {
    if (eventHandlerThread.joinable()) {
        running = false;
        eventHandlerThread.join();
    }
}

static std::unordered_set<int> getExcludedEventCodes() {
    std::unordered_set<int> excludedEventCodes;
    for (auto &var : global_variable_registry->getGlobalVariables()) {
        if (var->getProperties()->getExcludeFromDataFile()) {
            excludedEventCodes.insert(var->getCodecCode());
        }
    }
    return excludedEventCodes;
}

DataFileManager::DataFile::DataFile(const std::string &filename) :
    filename(filename),
    excludedEventCodes(getExcludedEventCodes()),
    mwk2Writer(filename),
    eventBufferReader(global_outgoing_event_buffer),
    running(true),
    eventHandlerThread([this]() { handleEvents(); })
{ }

void DataFileManager::DataFile::handleEvents() {
    constexpr MWTime nextEventTimeout = 500 * 1000;  // 500ms
    constexpr std::size_t maxPendingEvents = 1000;

    std::vector<boost::shared_ptr<Event>> pendingEvents;

    while (running) {
        // Wait for next event or timeout
        auto event = eventBufferReader.getNextEvent(nextEventTimeout);

        // Process all currently-available events
        while (event) {
            // Collect all currently-available events (up to maxPendingEvents)
            do {
                if (!excludedEventCodes.count(event->getEventCode())) {
                    pendingEvents.push_back(event);
                }
                event = eventBufferReader.getNextEvent();
            } while (event && (pendingEvents.size() < maxPendingEvents));

            // Write pending events
            if (!pendingEvents.empty()) {
                try {
                    mwk2Writer.writeEvents(pendingEvents);
                } catch (const SimpleException &e) {
                    merror(M_FILE_MESSAGE_DOMAIN,
                           "Failed to write %lu events to data file: %s",
                           pendingEvents.size(),
                           e.what());
                }
                pendingEvents.clear();
            }
        }
    }

    // Write termination event
    try {
        mwk2Writer.writeEvent(boost::make_shared<Event>(RESERVED_TERMINATION_CODE, Datum()));
    } catch (const SimpleException &e) {
        merror(M_FILE_MESSAGE_DOMAIN, "Failed to write termination event to data file: %s", e.what());
    }
}

SINGLETON_INSTANCE_STATIC_DECLARATION(DataFileManager)

static inline std::string getFullFilename(const std::string &filename) {
    return appendDataFileExtension(prependDataFilePath(filename).string());
}

bool DataFileManager::openFile(const std::string &filename, bool overwrite) {
    lock_guard lock(mutex);
    if (dataFile) {
        mwarning(M_FILE_MESSAGE_DOMAIN, "Data file already open at \"%s\"", dataFile->getFilename().c_str());
        return true;
    }
    return openFile(getFullFilename(filename), overwrite, dataFile);
}

bool DataFileManager::openFile(const std::string &filename, bool overwrite, std::unique_ptr<DataFile> &dataFile) {
    if (!DataFile::create(filename, overwrite, dataFile)) {
        global_outgoing_event_buffer->putEvent(SystemEventFactory::dataFileOpenedResponse(filename, M_COMMAND_FAILURE));
        return false;
    }

    // Announce component codec, variable codec, experiment state, and all current
    // variable values
    global_outgoing_event_buffer->putEvent(SystemEventFactory::componentCodecPackage());
    global_outgoing_event_buffer->putEvent(SystemEventFactory::codecPackage());
    global_outgoing_event_buffer->putEvent(SystemEventFactory::currentExperimentState());
    global_variable_registry->announceAll();

    mprintf(M_FILE_MESSAGE_DOMAIN, "Opened data file: %s", filename.c_str());

    // everything went ok so issue the success event
    global_outgoing_event_buffer->putEvent(SystemEventFactory::dataFileOpenedResponse(filename, M_COMMAND_SUCCESS));
    return true;
}

void DataFileManager::closeFile() {
    lock_guard lock(mutex);
    if (dataFile) {
        closeFile(dataFile);
    }
}

void DataFileManager::closeFile(std::unique_ptr<DataFile> &dataFile) {
    mprintf(M_FILE_MESSAGE_DOMAIN, "Closing data file...");
    auto filename = dataFile->getFilename();  // Make a copy to use after dataFile is destroyed
    dataFile.reset();
    mprintf(M_FILE_MESSAGE_DOMAIN, "Closed data file: %s", filename.c_str());
    global_outgoing_event_buffer->putEvent(SystemEventFactory::dataFileClosedResponse(filename, M_COMMAND_SUCCESS));
}

std::string DataFileManager::getFilename() const {
    lock_guard lock(mutex);
    std::string filename;
    if (dataFile) {
        filename = dataFile->getFilename();
    }
    return filename;
}

void DataFileManager::setAutoOpenFilename(const boost::shared_ptr<Variable> &filename) {
    lock_guard lock(mutex);
    if (autoOpenFilename) {
        throw SimpleException(M_FILE_MESSAGE_DOMAIN, "Automatic data-file management is already configured");
    }
    autoOpenFilename = filename;
}

void DataFileManager::clearAutoOpenFilename() {
    lock_guard lock(mutex);
    autoOpenFilename.reset();
}

bool DataFileManager::canAutoOpenFile() const {
    lock_guard lock(mutex);
    return bool(autoOpenFilename);
}

bool DataFileManager::autoOpenFile() {
    lock_guard lock(mutex);

    if (!autoOpenFilename) {
        // Nothing to do
        return true;
    }

    // Evaluate the filename
    std::string filename;
    try {
        filename = autoOpenFilename->getValue().getString();
    } catch (const SimpleException &e) {
        merror(M_FILE_MESSAGE_DOMAIN, "Filename evaluation failed: %s", e.what());
        return false;
    }
    if (filename.empty()) {
        merror(M_FILE_MESSAGE_DOMAIN, "Evaluated filename is empty");
        return false;
    }
    filename = getFullFilename(filename);

    if (dataFile) {
        if (dataFile->getFilename() == filename) {
            // The desired file is already open.  Nothing else to do.
            return true;
        }
        // Close the current file
        closeFile(dataFile);
    }

    return openFile(filename, false, dataFile);  // Never overwrite
}

END_NAMESPACE_MW

max_stars_repo_name: esayui/mworks

max_issues_repo_name: esayui/mworks

max_forks_repo_name: esayui/mworks


text:
#ifndef BOOST_CERTIFY_CRLSET_PARSER_HPP
#define BOOST_CERTIFY_CRLSET_PARSER_HPP

#include <boost/asio/buffer.hpp>
#include <boost/endian/arithmetic.hpp>
#include <boost/system/system_error.hpp>

namespace boost
{

namespace certify
{

namespace detail
{

template<class T>
struct inline_global
{
    static T value;
};

template<class T>
T inline_global<T>::value{};

} // namespace detail

enum class crlset_error
{
    header_length_truncated,
    header_truncated,
    serial_truncated
};

class crlset_parser_category : public system::error_category
{
public:
    char const* name() const noexcept override;

    std::string message(int ev) const override;
};

system::error_code
make_error_code(crlset_error ev);

struct crlset
{
    std::array<std::uint8_t, 32> parent_spki_hash;
    std::vector<std::string> serials;
};

std::vector<crlset>
parse_crlset(asio::const_buffer b, system::error_code& ec);

std::vector<crlset>
parse_crlset(boost::asio::const_buffer b);

} // namespace certify

namespace system
{
template<>
struct is_error_code_enum<::boost::certify::crlset_error>
{
    static bool const value = true;
};
} // namespace system

} // namespace boost

#include <boost/certify/impl/crlset_parser.ipp>

#endif // BOOST_CERTIFY_CRLSET_PARSER_HPP

max_stars_repo_name: amenshov/certify

max_issues_repo_name: amenshov/certify

max_forks_repo_name: amenshov/certify


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

// Copyright (c) 2014, Oracle and/or its affiliates.

// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_GEOMETRY_TO_SEGMENT_OR_BOX_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_GEOMETRY_TO_SEGMENT_OR_BOX_HPP

#include <iterator>

#include <boost/range.hpp>

#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/strategies/distance.hpp>
#include <boost/geometry/strategies/tags.hpp>

#include <boost/geometry/algorithms/assign.hpp>
#include <boost/geometry/algorithms/intersects.hpp>
#include <boost/geometry/algorithms/num_points.hpp>

#include <boost/geometry/iterators/point_iterator.hpp>
#include <boost/geometry/iterators/segment_iterator.hpp>

#include <boost/geometry/algorithms/dispatch/distance.hpp>

#include <boost/geometry/algorithms/detail/closest_feature/geometry_to_range.hpp>
#include <boost/geometry/algorithms/detail/closest_feature/point_to_range.hpp>

#include <boost/geometry/algorithms/detail/distance/is_comparable.hpp>

#include <boost/geometry/util/condition.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace distance
{

// closure of segment or box point range
template
<
    typename SegmentOrBox,
    typename Tag = typename tag<SegmentOrBox>::type
>
struct segment_or_box_point_range_closure
    : not_implemented<SegmentOrBox>
{};

template <typename Segment>
struct segment_or_box_point_range_closure<Segment, segment_tag>
{
    static const closure_selector value = closed;
};

template <typename Box>
struct segment_or_box_point_range_closure<Box, box_tag>
{
    static const closure_selector value = open;
};

template
<
    typename Geometry,
    typename SegmentOrBox,
    typename Strategy,
    typename Tag = typename tag<Geometry>::type
>
class geometry_to_segment_or_box
{
private:
    typedef typename point_type<SegmentOrBox>::type segment_or_box_point;

    typedef typename strategy::distance::services::comparable_type
       <
           Strategy
       >::type comparable_strategy;

    typedef detail::closest_feature::point_to_point_range
        <
            typename point_type<Geometry>::type,
            std::vector<segment_or_box_point>,
            segment_or_box_point_range_closure<SegmentOrBox>::value,
            comparable_strategy
        > point_to_point_range;

    typedef detail::closest_feature::geometry_to_range geometry_to_range;

    typedef typename strategy::distance::services::return_type
        <
            comparable_strategy,
            typename point_type<Geometry>::type,
            segment_or_box_point
        >::type comparable_return_type;

    // assign the new minimum value for an iterator of the point range
    // of a segment or a box
    template
    <
        typename SegOrBox,
        typename SegOrBoxTag = typename tag<SegOrBox>::type
    >
    struct assign_new_min_iterator
        : not_implemented<SegOrBox>
    {};

    template <typename Segment>
    struct assign_new_min_iterator<Segment, segment_tag>
    {
        template <typename Iterator>
        static inline void apply(Iterator&, Iterator)
        {
        }
    };

    template <typename Box>
    struct assign_new_min_iterator<Box, box_tag>
    {
        template <typename Iterator>
        static inline void apply(Iterator& it_min, Iterator it)
        {
            it_min = it;
        }
    };

    // assign the points of a segment or a box to a range
    template
    <
        typename SegOrBox,
        typename PointRange,
        typename SegOrBoxTag = typename tag<SegOrBox>::type
    >
    struct assign_segment_or_box_points
    {};

    template <typename Segment, typename PointRange>
    struct assign_segment_or_box_points<Segment, PointRange, segment_tag>
    {
        static inline void apply(Segment const& segment, PointRange& range)
        {
            detail::assign_point_from_index<0>(segment, range[0]);
            detail::assign_point_from_index<1>(segment, range[1]);
        }
    };

    template <typename Box, typename PointRange>
    struct assign_segment_or_box_points<Box, PointRange, box_tag>
    {
        static inline void apply(Box const& box, PointRange& range)
        {
            detail::assign_box_corners_oriented<true>(box, range);
        }
    };

public:
    typedef typename strategy::distance::services::return_type
        <
            Strategy,
            typename point_type<Geometry>::type,
            segment_or_box_point
        >::type return_type;

    static inline return_type apply(Geometry const& geometry,
                                    SegmentOrBox const& segment_or_box,
                                    Strategy const& strategy,
                                    bool check_intersection = true)
    {
        typedef geometry::point_iterator<Geometry const> point_iterator_type;
        typedef geometry::segment_iterator
            <
                Geometry const
            > segment_iterator_type;

        typedef typename std::vector
            <
                segment_or_box_point
            >::const_iterator seg_or_box_iterator_type;

        typedef assign_new_min_iterator<SegmentOrBox> assign_new_value;

        if (check_intersection
            && geometry::intersects(geometry, segment_or_box))
        {
            return 0;
        }

        comparable_strategy cstrategy =
            strategy::distance::services::get_comparable
                <
                    Strategy
                >::apply(strategy);

        // get all points of the segment or the box
        std::vector<segment_or_box_point>
            seg_or_box_points(geometry::num_points(segment_or_box));

        assign_segment_or_box_points
            <
                SegmentOrBox,
                std::vector<segment_or_box_point>
            >::apply(segment_or_box, seg_or_box_points);

        // consider all distances of the points in the geometry to the
        // segment or box
        comparable_return_type cd_min1(0);
        point_iterator_type pit_min;
        seg_or_box_iterator_type it_min1 = seg_or_box_points.begin();
        seg_or_box_iterator_type it_min2 = ++seg_or_box_points.begin();
        bool first = true;

        for (point_iterator_type pit = points_begin(geometry);
             pit != points_end(geometry); ++pit, first = false)
        {
            comparable_return_type cd;
            std::pair
                <
                    seg_or_box_iterator_type, seg_or_box_iterator_type
                > it_pair
                = point_to_point_range::apply(*pit,
                                              seg_or_box_points.begin(),
                                              seg_or_box_points.end(),
                                              cstrategy,
                                              cd);

            if (first || cd < cd_min1)
            {
                cd_min1 = cd;
                pit_min = pit;
                assign_new_value::apply(it_min1, it_pair.first);
                assign_new_value::apply(it_min2, it_pair.second);
            }
        }

        // consider all distances of the points in the segment or box to the
        // segments of the geometry
        comparable_return_type cd_min2(0);
        segment_iterator_type sit_min;
        typename std::vector<segment_or_box_point>::const_iterator it_min;

        first = true;
        for (typename std::vector<segment_or_box_point>::const_iterator it
                 = seg_or_box_points.begin();
             it != seg_or_box_points.end(); ++it, first = false)
        {
            comparable_return_type cd;
            segment_iterator_type sit
                = geometry_to_range::apply(*it,
                                           segments_begin(geometry),
                                           segments_end(geometry),
                                           cstrategy,
                                           cd);

            if (first || cd < cd_min2)
            {
                cd_min2 = cd;
                it_min = it;
                sit_min = sit;
            }
        }

        if (BOOST_GEOMETRY_CONDITION(is_comparable<Strategy>::value))
        {
            return (std::min)(cd_min1, cd_min2);
        }

        if (cd_min1 < cd_min2)
        {
            return strategy.apply(*pit_min, *it_min1, *it_min2);
        }
        else
        {
            return dispatch::distance
                <
                    segment_or_box_point,
                    typename std::iterator_traits
                        <
                            segment_iterator_type
                        >::value_type,
                    Strategy
                >::apply(*it_min, *sit_min, strategy);
        }
    }

    static inline return_type
    apply(SegmentOrBox const& segment_or_box, Geometry const& geometry,
          Strategy const& strategy, bool check_intersection = true)
    {
        return apply(geometry, segment_or_box, strategy, check_intersection);
    }
};

template <typename MultiPoint, typename SegmentOrBox, typename Strategy>
class geometry_to_segment_or_box
    <
        MultiPoint, SegmentOrBox, Strategy, multi_point_tag
    >
{
private:
    typedef detail::closest_feature::geometry_to_range base_type;

    typedef typename boost::range_iterator
        <
            MultiPoint const
        >::type iterator_type;

    typedef detail::closest_feature::geometry_to_range geometry_to_range;

public:
    typedef typename strategy::distance::services::return_type
        <
            Strategy,
            typename point_type<SegmentOrBox>::type,
            typename point_type<MultiPoint>::type
        >::type return_type;

    static inline return_type apply(MultiPoint const& multipoint,
                                    SegmentOrBox const& segment_or_box,
                                    Strategy const& strategy)
    {
        namespace sds = strategy::distance::services;

        typename sds::return_type
            <
                typename sds::comparable_type<Strategy>::type,
                typename point_type<SegmentOrBox>::type,
                typename point_type<MultiPoint>::type
            >::type cd_min;

        iterator_type it_min
            = geometry_to_range::apply(segment_or_box,
                                       boost::begin(multipoint),
                                       boost::end(multipoint),
                                       sds::get_comparable
                                           <
                                               Strategy
                                           >::apply(strategy),
                                       cd_min);

        return
            is_comparable<Strategy>::value
            ?
            cd_min
            :
            dispatch::distance
                <
                    typename point_type<MultiPoint>::type,
                    SegmentOrBox,
                    Strategy
                >::apply(*it_min, segment_or_box, strategy);
    }
};

}} // namespace detail::distance
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template <typename Linear, typename Segment, typename Strategy>
struct distance
    <
        Linear, Segment, Strategy, linear_tag, segment_tag,
        strategy_tag_distance_point_segment, false
    > : detail::distance::geometry_to_segment_or_box<Linear, Segment, Strategy>
{};

template <typename Areal, typename Segment, typename Strategy>
struct distance
    <
        Areal, Segment, Strategy, areal_tag, segment_tag,
        strategy_tag_distance_point_segment, false
    > : detail::distance::geometry_to_segment_or_box<Areal, Segment, Strategy>
{};

template <typename Segment, typename Areal, typename Strategy>
struct distance
    <
        Segment, Areal, Strategy, segment_tag, areal_tag,
        strategy_tag_distance_point_segment, false
    > : detail::distance::geometry_to_segment_or_box<Areal, Segment, Strategy>
{};

template <typename Linear, typename Box, typename Strategy>
struct distance
    <
        Linear, Box, Strategy, linear_tag, box_tag,
        strategy_tag_distance_point_segment, false
    > : detail::distance::geometry_to_segment_or_box
        <
            Linear, Box, Strategy
        >
{};

template <typename Areal, typename Box, typename Strategy>
struct distance
    <
        Areal, Box, Strategy, areal_tag, box_tag,
        strategy_tag_distance_point_segment, false
    > : detail::distance::geometry_to_segment_or_box<Areal, Box, Strategy>
{};

template <typename MultiPoint, typename Segment, typename Strategy>
struct distance
    <
        MultiPoint, Segment, Strategy,
        multi_point_tag, segment_tag,
        strategy_tag_distance_point_segment, false
    > : detail::distance::geometry_to_segment_or_box
        <
            MultiPoint, Segment, Strategy
        >
{};

template <typename MultiPoint, typename Box, typename Strategy>
struct distance
    <
        MultiPoint, Box, Strategy,
        multi_point_tag, box_tag,
        strategy_tag_distance_point_box, false
    > : detail::distance::geometry_to_segment_or_box
        <
            MultiPoint, Box, Strategy
        >
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISTANCE_GEOMETRY_TO_SEGMENT_OR_BOX_HPP

max_stars_repo_name: Abce/boost

max_issues_repo_name: Abce/boost

max_forks_repo_name: Abce/boost


text:
#include <ndt_map/ndt_map_hmt.h>
#include <ndt_map/lazy_grid.h>
#include <ndt_map/cell_vector.h>

#include <pcl_conversions/pcl_conversions.h>
#include "pcl/point_cloud.h"
#include "sensor_msgs/PointCloud2.h"
#include "pcl/io/pcd_io.h"

#include "ros/ros.h"
#include "pcl/point_cloud.h"
#include "sensor_msgs/PointCloud2.h"
#include "pcl/io/pcd_io.h"
#include "pcl/features/feature.h"
#include <cstdio>

#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>

#include <Eigen/Eigen>

static int ctr = 0, ctr2 = 0;
static boost::mutex mutex;
static bool fresh = false;

void ndtCallback(const sensor_msgs::PointCloud2ConstPtr &msg)
{
    pcl::PointCloud<pcl::PointXYZ> cloud;
    pcl::fromROSMsg(*msg,cloud);

    ROS_INFO ("Received %d data points with the following fields: %s", (int)(msg->width * msg->height),
              pcl::getFieldsList (*msg).c_str ());

    perception_oru::NDTMap nd(new perception_oru::LazyGrid(2));

    Eigen::Affine3d T;
    T.setIdentity();
    nd.addPointCloud(T.translation(),cloud);
    nd.computeNDTCells();

    ROS_INFO("Loaded point cloud");
    if(ctr%10 == 0) {
	nd.writeToJFF("maps02.jff");
    }
    ctr++;

}

int
main (int argc, char** argv)
{

    ros::init(argc, argv, "ndt_builder");
    ros::NodeHandle n;
    ros::Subscriber sub1 = n.subscribe("points2_in", 10, ndtCallback);
    ros::spin();

    return (0);
}

max_stars_repo_name: lllray/ndt-loam

max_issues_repo_name: lllray/ndt-loam

max_forks_repo_name: lllray/ndt-loam


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2014-2014. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#include <boost/container/vector.hpp>
#include <boost/container/deque.hpp>
#include <boost/container/stable_vector.hpp>
#include <boost/container/static_vector.hpp>
#include <boost/container/string.hpp>
#include <boost/container/list.hpp>
#include <boost/container/slist.hpp>
#include <boost/container/map.hpp>
#include <boost/container/set.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/intrusive/detail/mpl.hpp>

#include <boost/core/lightweight_test.hpp>
#include <boost/static_assert.hpp>
#include <cstring>
#include <new>

using namespace boost::container;

typedef boost::container::container_detail::aligned_storage<sizeof(void*)*4>::type buffer_t;

static buffer_t buffer_0x00;
static buffer_t buffer_0xFF;

template<class Iterator>
const Iterator &on_0x00_buffer()
{
   BOOST_STATIC_ASSERT(sizeof(buffer_t) >= sizeof(Iterator));
   return * ::new(std::memset(&buffer_0x00, 0x00, sizeof(buffer_0x00))) Iterator();
}

template<class Iterator>
const Iterator &on_0xFF_buffer()
{
   BOOST_STATIC_ASSERT(sizeof(buffer_t) >= sizeof(Iterator));
   return * ::new(std::memset(&buffer_0xFF, 0xFF, sizeof(buffer_0xFF))) Iterator();
}

namespace boost {
namespace container {
namespace test {

BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(reverse_iterator)
BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_reverse_iterator)

}}}   //namespace boost::container::test {

template<class Container>
void check_null_iterators()
{
   typedef typename Container::iterator               iterator;
   typedef typename Container::const_iterator         const_iterator;
   typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT
      (boost::container::test::, Container
      ,reverse_iterator, iterator)                    reverse_iterator;
   typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT
      (boost::container::test::, Container
      ,const_reverse_iterator, const_iterator)        const_reverse_iterator;

   BOOST_TEST(on_0xFF_buffer<iterator>()               == on_0x00_buffer<iterator>());
   BOOST_TEST(on_0xFF_buffer<const_iterator>()         == on_0x00_buffer<const_iterator>());
   BOOST_TEST(on_0xFF_buffer<reverse_iterator>()       == on_0x00_buffer<reverse_iterator>());
   BOOST_TEST(on_0xFF_buffer<const_reverse_iterator>() == on_0x00_buffer<const_reverse_iterator>());
}

int main()
{
   check_null_iterators< vector<int> >();
   check_null_iterators< deque<int> >();
   check_null_iterators< stable_vector<int> >();
   check_null_iterators< static_vector<int, 1> >();
   check_null_iterators< string >();
   check_null_iterators< list<int> >();
   check_null_iterators< slist<int> >();
   check_null_iterators< map<int, int> >();
   check_null_iterators< multimap<int, int> >();
   check_null_iterators< set<int> >();
   check_null_iterators< multiset<int> >();
   check_null_iterators< flat_set<int> >();
   check_null_iterators< flat_multiset<int> >();
   check_null_iterators< flat_map<int, int> >();
   check_null_iterators< flat_multimap<int, int> >();

   return boost::report_errors();
}

max_stars_repo_name: lijgame/boost

max_issues_repo_name: nxplatform/nx-mobile

max_forks_repo_name: nxplatform/nx-mobile


text:
#include <iostream>
#include <memory>
#include <utility>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include "lib/factory.hh"
#include "lib/joystick.hh"
#include "lib/service.hh"

namespace bfs = boost::filesystem;
namespace bpo = boost::program_options;

class Args
{
 public:
  craebot::sensors::joystick::app_params_t params{};
  std::string device_filename{};

 public:
  bool parse(int argc, char *argv[])
  {
    bpo::options_description description{
        "ZCM driver for a generic Linux joystick. This app publishes messages containing "
        "the current state of each one of the joystick's buttons and axes"};
    description.add_options()("help,h", "Show this help text and exit.")(
        "deadzone,d",
        bpo::value<double>()->default_value(0.2),
        "Amount by which the joystick has to move before it is considered to be off-center.")(
        "auto-repeat-rate,a",
        bpo::value<double>()->default_value(0.0),
        "Rate in Hz at which a joystick that has a non-changing state will resend the previously sent message.")(
        "coalesce-interval,c",
        bpo::value<double>()->default_value(0.01),
        "This option can be used to limit the rate of outgoing messages.")(
        "sticky-buttons,s", bpo::bool_switch(), "Enables toggling the state of the button on every button press.")(
        "filename,f", bpo::value<std::string>()->default_value("/dev/input/js1"), "The joystick device filename.");

    bpo::variables_map vm;
    bpo::store(bpo::parse_command_line(argc, argv, description), vm);
    bpo::notify(vm);

    if (vm.count("help") != 0u)
    {
      std::cout << description << std::endl;
      return true;
    }

    try
    {
      params.deadzone = vm["deadzone"].as<double>();
      params.auto_repeat_rate = vm["auto-repeat-rate"].as<double>();
      params.coalesce_interval = vm["coalesce-interval"].as<double>();
      params.sticky_buttons = vm["sticky-buttons"].as<bool>();
      device_filename = vm["filename"].as<std::string>();
    }
    catch (const bpo::error &err)
    {
      std::cerr << "Invalid Argument: " << err.what() << std::endl;
      return false;
    }

    if (!bfs::exists(device_filename))
    {
      std::cerr << "The device " << device_filename << " does not exist." << std::endl;
      return false;
    }

    return true;
  }
};

int main(int argc, char *argv[])
{
  Args args;
  if (!args.parse(argc, argv))
  {
    return EXIT_FAILURE;
  }

  try
  {
    auto joystick_uptr = craebot::sensors::joystick::factory::create_concrete_joystick(args.device_filename);
    craebot::sensors::joystick::JoystickService service{std::move(joystick_uptr), args.params};

    service.init();
    service.run();
  }
  catch (const std::exception &x)
  {
    std::cerr << "CraebotJoystick: " << x.what() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

max_stars_repo_name: sudhanvas/Craebot

max_issues_repo_name: sudhanvas/Craebot

max_forks_repo_name: sudhanvas/Craebot


text:
#include <rai/secure/http.hpp>
#include <boost/property_tree/json_parser.hpp>

rai::HttpClient::HttpClient(boost::asio::io_service& service)
    : service_(service),
      used_(false),
      resolver_(service),
      ctx_(boost::asio::ssl::context::tlsv12_client)
{
}

std::shared_ptr<rai::HttpClient> rai::HttpClient::Shared()
{
    return shared_from_this();
}

bool rai::HttpClient::CheckUpdateUsed()
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (used_)
    {
        return true;
    }
    used_ = true;
    return false;
}

rai::ErrorCode rai::HttpClient::Get(const rai::Url& url,
                                    const rai::HttpCallback& callback)
{
    IF_ERROR_RETURN(CheckUpdateUsed(), rai::ErrorCode::HTTP_CLIENT_USED);

    url_ = url;
    callback_ = callback;
    IF_ERROR_RETURN(CheckUrl_(), rai::ErrorCode::INVALID_URL);
    if (url_.protocol_ == "https")
    {
        IF_ERROR_RETURN(LoadCert_(), rai::ErrorCode::LOAD_CERT);
    }
    PrepareGetReq_();

    Resolve();
    return rai::ErrorCode::SUCCESS;
}

rai::ErrorCode rai::HttpClient::Post(const rai::Url& url,
                                     const rai::Ptree& ptree,
                                     const rai::HttpCallback& callback)
{
    IF_ERROR_RETURN(CheckUpdateUsed(), rai::ErrorCode::HTTP_CLIENT_USED);

    url_ = url;
    callback_ = callback;
    IF_ERROR_RETURN(CheckUrl_(), rai::ErrorCode::INVALID_URL);
    if (url_.protocol_ == "https")
    {
        IF_ERROR_RETURN(LoadCert_(), rai::ErrorCode::LOAD_CERT);
    }
    PreparePostReq_(ptree);

    Resolve();
    return rai::ErrorCode::SUCCESS;
}

void rai::HttpClient::Resolve()
{
    std::shared_ptr<rai::HttpClient> client(Shared());
    boost::asio::ip::tcp::resolver::query query(url_.host_,
                                                std::to_string(url_.port_));
    resolver_.async_resolve(
        query, [client](const boost::system::error_code& ec,
                        boost::asio::ip::tcp::resolver::iterator results) {
            client->OnResolve(ec, results);
        });
}

void rai::HttpClient::OnResolve(
    const boost::system::error_code& ec,
    boost::asio::ip::tcp::resolver::iterator results)
{
    if (ec)
    {
        // log
        std::cout << "Failed to resolve: " << ec.message() << std::endl;
        Callback_(rai::ErrorCode::DNS_RESOLVE);
        return;
    }

    std::shared_ptr<rai::HttpClient> client(Shared());
    if (url_.protocol_ == "http")
    {
        socket_ = std::make_shared<boost::asio::ip::tcp::socket>(service_);
        boost::asio::async_connect(
            *socket_, results,
            [client](const boost::system::error_code& ec,
                     boost::asio::ip::tcp::resolver::iterator iterator) {
                client->OnConnect(ec);
            });
    }
    else
    {
        ssl_stream_ = std::make_shared<
            boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>(service_,
                                                                    ctx_);
        boost::asio::async_connect(
            ssl_stream_->next_layer(), results,
            [client](const boost::system::error_code& ec,
                     boost::asio::ip::tcp::resolver::iterator iterator) {
                client->OnConnect(ec);
            });
    }
}

void rai::HttpClient::OnConnect(const boost::system::error_code& ec)
{
    if (ec)
    {
        // log
        std::cout << "Failed to connect: " << ec.message() << std::endl;
        Callback_(rai::ErrorCode::TCP_CONNECT);
        return;
    }

    if (url_.protocol_ == "https")
    {
        // Set SNI Hostname (many hosts need this to handshake successfully)
        if (!SSL_set_tlsext_host_name(ssl_stream_->native_handle(),
                                      url_.host_.c_str()))
        {
            // log
            std::cout << "Failed to set SNI: " << url_.host_ << std::endl;
            Callback_(rai::ErrorCode::SET_SSL_SNI);
            return;
        }
        ssl_stream_->set_verify_mode(
            boost::asio::ssl::verify_peer
            | boost::asio::ssl::verify_fail_if_no_peer_cert);
        ssl_stream_->set_verify_callback(
            boost::asio::ssl::rfc2818_verification(url_.host_));
        std::shared_ptr<rai::HttpClient> client(Shared());
        ssl_stream_->async_handshake(
            boost::asio::ssl::stream_base::client,
            [client](const boost::system::error_code& ec) {
                client->OnSslHandshake(ec);
            });
    }
    else
    {
        Write();
    }
}

void rai::HttpClient::OnSslHandshake(const boost::system::error_code& ec)
{
    if (ec)
    {
        // log
        std::cout << "Ssl handshake failed: " << ec.message() << std::endl;
        Callback_(rai::ErrorCode::SSL_HANDSHAKE);
        return;
    }

    Write();
}

void rai::HttpClient::Onwrite(const boost::system::error_code& ec, size_t size)
{
    if (ec || size == 0)
    {
        // log
        std::cout << "Failed to write stream: " << ec.message() << std::endl;
        Callback_(rai::ErrorCode::WRITE_STREAM);
        return;
    }
    Read();
}

void rai::HttpClient::OnRead(const boost::system::error_code& ec, size_t size)
{
    if (ec)
    {
        // log
        std::cout << "Failed to read stream: " << ec.message() << std::endl;
        Callback_(rai::ErrorCode::STREAM);
        return;
    }

    if (res_.result() != boost::beast::http::status::ok)
    {
        if (post_req_)
        {
            // log
            std::cout << "Http post failed, status: "
                      << static_cast<uint32_t>(res_.result()) << std::endl;
            Callback_(rai::ErrorCode::HTTP_POST);
        }
        else
        {
            // log
            std::cout << "Http get failed, status: "
                      << static_cast<uint32_t>(res_.result()) << std::endl;
            Callback_(rai::ErrorCode::HTTP_GET);
        }
        return;
    }

    Callback_(rai::ErrorCode::SUCCESS, res_.body());

    if (url_.protocol_ == "https")
    {
        std::shared_ptr<rai::HttpClient> client(Shared());
        ssl_stream_->async_shutdown(
            [client](const boost::system::error_code&) {});
    }
    else
    {
        boost::system::error_code ignore;
        socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
    }
}

void rai::HttpClient::Write()
{
    std::shared_ptr<rai::HttpClient> client(Shared());
    if (url_.protocol_ == "https")
    {
        if (post_req_)
        {
            boost::beast::http::async_write(
                *ssl_stream_, *post_req_,
                [client](const boost::system::error_code& ec, size_t size) {
                    client->Onwrite(ec, size);
                });
        }
        else
        {
            boost::beast::http::async_write(
                *ssl_stream_, *get_req_,
                [client](const boost::system::error_code& ec, size_t size) {
                    client->Onwrite(ec, size);
                });
        }
    }
    else
    {
        if (post_req_)
        {
            boost::beast::http::async_write(
                *socket_, *post_req_,
                [client](const boost::system::error_code& ec, size_t size) {
                    client->Onwrite(ec, size);
                });
        }
        else
        {
            boost::beast::http::async_write(
                *socket_, *get_req_,
                [client](const boost::system::error_code& ec, size_t size) {
                    client->Onwrite(ec, size);
                });
        }
    }
}

void rai::HttpClient::Read()
{
    std::shared_ptr<rai::HttpClient> client(Shared());
    if (url_.protocol_ == "https")
    {
        boost::beast::http::async_read(
            *ssl_stream_, buffer_, res_,
            [client](const boost::system::error_code& ec, size_t size) {
                client->OnRead(ec, size);
            });
    }
    else
    {
        boost::beast::http::async_read(
            *socket_, buffer_, res_,
            [client](const boost::system::error_code& ec, size_t size) {
                client->OnRead(ec, size);
            });
    }
}

bool rai::HttpClient::CheckUrl_() const
{
    if (!url_ || (url_.protocol_ != "http" && url_.protocol_ != "https"))
    {
        return true;
    }
    return false;
}

void rai::HttpClient::Callback_(rai::ErrorCode error_code,
                                const std::string& response)
{
    if (callback_)
    {
        callback_(error_code, response);
    }
}

bool rai::HttpClient::LoadCert_()
{
    try
    {
        ctx_.load_verify_file("cacert.pem");
        return false;
    }
    catch(...)
    {
        return true;
    }
}

void rai::HttpClient::PrepareGetReq_()
{
    get_req_ = std::make_shared<
        boost::beast::http::request<boost::beast::http::empty_body>>();
    get_req_->version(11);
    get_req_->method(boost::beast::http::verb::get);
    get_req_->target(url_.path_);
    get_req_->insert(boost::beast::http::field::host, url_.host_);
}

void rai::HttpClient::PreparePostReq_(const rai::Ptree& ptree)
{
    std::stringstream stream;
    boost::property_tree::write_json(stream, ptree);
    stream.flush();

    post_req_ = std::make_shared<
        boost::beast::http::request<boost::beast::http::string_body>>();
    post_req_->method(boost::beast::http::verb::post);
    post_req_->target(url_.path_);
    post_req_->version(11);
    post_req_->insert(boost::beast::http::field::host, url_.host_);
    post_req_->insert(boost::beast::http::field::content_type,
                "application/json");
    post_req_->body() = stream.str();
    post_req_->prepare_payload();
}

max_stars_repo_name: gokoo/Raicoin