text:
#pragma once

#ifndef _db_triedb_hpp
#define _db_triedb_hpp

#include <cstdint>
#include <fstream>
#include <boost/filesystem/path.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/noncopyable.hpp>
#include <boost/functional/hash.hpp>
#include <boost/intrusive_ptr.hpp>
#include <iostream>
#include <bitset>
#include <algorithm>
#include <set>
#include "../common/lru_cache.hpp"
#include "../common/bits.hpp"
#include "../common/checked_cast.hpp"
#include "util.hpp"
#include "triedb_params.hpp"

namespace prologcoin { namespace db {

class triedb;

//
// root_id: to identify a specific node in the blockchain.
//
class root_id {
public:
    static const size_t SIZE = sizeof(uint64_t);

    root_id() : value_(0) {
    }

    explicit root_id(uint64_t v) : value_(v) {
    }

    root_id(const root_id &other) = default;

    uint64_t value() const {
	return value_;
    }

    bool is_zero() const {
	return value_ == 0;
    }

    bool operator == (const root_id &other) const {
	return value_ == other.value_;
    }

    bool operator < (const root_id &other) const {
	return value_ < other.value_;
    }

    std::string str() const {
	std::stringstream ss;
	ss << value_;
	return ss.str();
    }

private:
    uint64_t value_;
};

}}

namespace std {
    template<> struct hash<prologcoin::db::root_id> {
	size_t operator () (const prologcoin::db::root_id &key) const {
	    return static_cast<size_t>(key.value());
	}
    };
}

namespace prologcoin { namespace db {

class custom_data_t {
public:
    custom_data_t() : data_(nullptr), size_(0) { }
    custom_data_t(const custom_data_t &other) : custom_data_t(other.data(), other.size()) { }
    custom_data_t(const uint8_t *data, size_t sz) {
	if (sz) {
	    data_ = new uint8_t[sz];
	    std::copy(data, data+sz, data_);
	} else {
	    data_ = nullptr;
	}
	size_ = sz;
    }
    custom_data_t(size_t sz, bool allocate) {
	data_ = allocate ? new uint8_t[sz] : nullptr;
	size_ = sz;
    }
    ~custom_data_t() {
	delete [] data_;
    }
    const uint8_t * data() const {
	return data_;
    }
    uint8_t * data() {
	return data_;
    }
    const size_t size() const {
	return size_;
    }
    void set_data(const uint8_t *dat, size_t sz) {
	if (sz != size_) {
	    delete [] data_;
	    if (sz) {
		data_ = new uint8_t[sz];
		size_ = sz;
	    } else {
		data_ = nullptr;
	    }
	}
	if (sz) std::copy(dat, dat+sz, data_);
    }
    bool operator == (const custom_data_t &other) const {
	if (size() != other.size()) {
	    return false;
	}
	return memcmp(data(), other.data(), size()) == 0;
    }
    bool operator < (const custom_data_t &other) const {
	size_t min_sz = std::min(size(), other.size());
	auto cmp = memcmp(data(), other.data(), min_sz);
	if (cmp != 0) {
	    return cmp < 0;
	}
	if (size() == other.size()) {
	    return 0;
	} else {
	    return size() < other.size();
	}
    }

private:
    uint8_t *data_;
    size_t size_;

    friend class node_hash;
};

class node_hash {
public:
    node_hash() { }
    node_hash(const node_hash &other) : data_(other.data_) { }
    node_hash(const uint8_t *hash, size_t sz) : data_(hash, sz) { }

    const uint8_t * hash() const { return data_.data(); }
    size_t hash_size() const { return data_.size(); }

    void set_hash(const uint8_t *hash, size_t sz) {
	data_.set_data(hash, sz);
    }

    bool equal_hash(const node_hash &other) const {
	return data_ == other.data_;
    }

    bool operator == (const node_hash &other) const {
	return equal_hash(other);
    }

    bool operator < (const node_hash &other) const {
	return data_ < other.data_;
    }

    const node_hash & hash_with_size() const { return *this; }

protected:
    uint8_t * hash() { return data_.data(); }

private:
    custom_data_t data_;
};

//
// This is used for bulk operations, e.g. when inserting/retrieving an
// entire sub-tree with data. Here the merkle hashes for a node can be
// inserted before there's any sub-trees to it.
//

class merkle_node : public node_hash {
public:
    enum merkle_node_t {
	LEAF, BRANCH
    };

    virtual merkle_node_t type() const = 0;

    virtual size_t size() const {
	return sizeof(merkle_node) + hash_size();
    }

    virtual bool validate(const triedb *db, uint64_t key_offset, uint64_t key_step, uint64_t from_key, uint64_t to_key) const = 0;
    virtual bool validate_end(const triedb *db, uint64_t key_offset, uint64_t key_step, uint64_t from_key) const = 0;

    virtual ~merkle_node() = default;

    void set_hash(const uint8_t *hash, size_t sz) {
	node_hash::set_hash(hash, sz);
    }

protected:
    friend class triedb;
};

}}

namespace std {
    template<> struct hash<prologcoin::db::node_hash> {
	size_t operator () (const prologcoin::db::node_hash &h) const {
	    assert(h.hash_size() >= 8);
	    auto *bytes = h.hash();
	    return static_cast<size_t>(prologcoin::db::read_uint64(bytes));
	}
    };
};

namespace prologcoin { namespace db {

class merkle_leaf : public merkle_node {
public:
    merkle_leaf() : key_(0) { }
    merkle_leaf(uint64_t key) : key_(key) { }
    merkle_leaf(uint64_t key, std::unique_ptr<custom_data_t> &data)
	: key_(key), data_(std::move(data)) { }

    merkle_node_t type() const override {
	return LEAF;
    }

    uint64_t key() const {
	return key_;
    }

    void set_key(uint64_t k) {
	key_ = k;
    }

    bool has_data() const {
	return data_ != nullptr;
    }

    const custom_data_t & data() const {
	return *data_;
    }

    void set_data(std::unique_ptr<custom_data_t> &data) {
	data_ = std::move(data);
    }

    size_t size() const override {
	return merkle_node::size() + sizeof(uint64_t) + sizeof(uint64_t) + data().size();
    }

    bool validate(const triedb *db, uint64_t key_offset, uint64_t key_step,
		  uint64_t from_key, uint64_t to_key) const override;
    bool validate_end(const triedb *db, uint64_t key_offset, uint64_t key_step,
		      uint64_t from_key) const override;

private:
    uint64_t key_;
    std::unique_ptr<custom_data_t> data_;
};

class merkle_branch : public merkle_node {
public:
    merkle_branch() : depth_(0), mask_(0), num_(0) {
    }

    merkle_node_t type() const override {
	return BRANCH;
    }

    size_t size() const override {
	return merkle_node::size() +
	       sizeof(uint8_t) + sizeof(uint32_t) +
	       sizeof(uint64_t) * triedb_params::MAX_BRANCH;
    }

    uint32_t mask() const {
	return mask_;
    }

    void set_depth(size_t d) {
	depth_ = common::checked_cast<uint8_t>(d);
    }

    size_t depth() const {
	return depth_;
    }

    uint64_t num_entries() const {
	return num_;
    }

    void set_num_entries(uint64_t n) {
	num_ = n;
    }

    bool has_child(size_t sub_index) const {
	return children_[sub_index] != nullptr;
    }

    const std::unique_ptr<merkle_node> & get_child(size_t sub_index) const {
	return children_[sub_index];
    }

    void set_child(size_t sub_index, std::unique_ptr<merkle_node> &child) {
	children_[sub_index] = std::move(child);
	mask_ |= (1 << sub_index);
    }

    merkle_branch * new_branch(size_t sub_index) {
	auto *new_br = new merkle_branch();
	children_[sub_index] = std::unique_ptr<merkle_node>(new_br);
	mask_ |= (1 << sub_index);
	return new_br;
    }

    merkle_leaf * new_leaf(size_t sub_index) {
	auto *new_lf = new merkle_leaf();
	children_[sub_index] = std::unique_ptr<merkle_node>(new_lf);
	mask_ |= (1 << sub_index);
	return new_lf;
    }

    const std::array<std::unique_ptr<merkle_node>, triedb_params::MAX_BRANCH> & get_children() const {
	return children_;
    }

    bool validate(const triedb *db, uint64_t key_offset, uint64_t key_step,
		  uint64_t from_key, uint64_t to_key) const override;
    bool validate_end(const triedb *db, uint64_t key_offset, uint64_t key_step,
		      uint64_t from_key) const override;
private:
    uint8_t depth_;
    uint32_t mask_;
    uint64_t num_;
    std::array<std::unique_ptr<merkle_node>, triedb_params::MAX_BRANCH> children_;
};

class merkle_root : public merkle_branch {
public:
    merkle_root() : limit_size_(std::numeric_limits<size_t>::max()), total_size_(0), limit_num_keys_(std::numeric_limits<size_t>::max()) { }

    bool validate(const triedb *db, uint64_t key_offset, uint64_t key_step, uint64_t from_key, uint64_t to_key) const {
	return merkle_branch::validate(db, key_offset, key_step, from_key, to_key);
    }

    bool validate_end(const triedb *db, uint64_t key_offset, uint64_t key_step, uint64_t from_key) const {
	return merkle_branch::validate_end(db, key_offset, key_step, from_key);
    }

    bool validate(const triedb *db, uint64_t from_key, uint64_t to_key) const {
	uint64_t key_offset = 0;
	uint64_t key_step =  static_cast<uint64_t>(1) << (depth() * triedb_params::MAX_BRANCH_BITS);
	uint64_t key_end = key_offset + key_step - 1;
	if (to_key > key_end) to_key = key_end;
	return merkle_branch::validate(db, key_offset, key_step, from_key, to_key);
    }

    bool validate_end(const triedb *db, uint64_t from_key) const {
	uint64_t key_offset = 0;
	uint64_t key_step = static_cast<uint64_t>(1) << (depth() *triedb_params::MAX_BRANCH_BITS);
	return merkle_branch::validate_end(db, key_offset, key_step, from_key);
    }

    void get_keys(uint64_t from_key, size_t num_keys, std::vector<uint64_t> &keys)
    {
	get_keys(this, from_key, num_keys, keys);
    }

    size_t limit_size() const {
	return limit_size_;
    }

    void set_limit(size_t limit)
    {
	limit_size_ = limit;
    }

    size_t total_size() const {
	return total_size_;
    }

    void set_total_size(size_t t) {
	total_size_ = t;
    }

    size_t num_keys() const {
	return limit_num_keys_;
    }

    void set_num_keys(size_t n) {
	limit_num_keys_ = n;
    }

private:
    void get_keys(const merkle_branch *br, uint64_t from_key, size_t num_keys, std::vector<uint64_t> &keys) {
	if (keys.size() >= num_keys) {
	    return;
	}
	auto const &children = br->get_children();
	for (auto &child : children) {
	    if (child == nullptr) {
		continue;
	    }
	    if (child->type() == merkle_node::BRANCH) {
		auto *br = reinterpret_cast<const merkle_branch *>(child.get());
		get_keys(br, from_key, num_keys, keys);
	    } else {
		auto *lf = reinterpret_cast<const merkle_leaf *>(child.get());
		auto k = lf->key();
		if (k >= from_key) {
		    keys.push_back(k);
		    if (keys.size() == num_keys) {
			return;
		    }
		}
	    }
	}
    }

    size_t limit_size_;
    size_t total_size_;
    size_t limit_num_keys_;
};

//
// root_node (stored in the root file)
//
// We have 'id' (32 bytes, typically a hash)
//         'previous_id' (so we can follow the chain backwards.)
//         'height' (so we don't have to compute it)
//         'file_offset' (where it is in the root file)
//         'ptr' (where it is in the data file)
//         'custom_data' (for more information - which will be
//                        different depending on database.)

class triedb;

class triedb_root {
private:
    friend class triedb;
    static const size_t MAX_SIZE_IN_BYTES = 4096;
public:
    triedb_root() : id_(0), previous_id_(0), ptr_(0), height_(0),
		    num_entries_(0) { }

    triedb_root(const triedb_root &parent, const root_id &child) :
	id_(child), previous_id_(parent.id()),
	ptr_(0), height_(parent.height() + 1),
	num_entries_(parent.num_entries()) { }

    triedb_root(const root_id &id)
	: id_(id), previous_id_(),
	  ptr_(0), height_(0),
	  num_entries_(0) { }

    const root_id & id() const {
	return id_;
    }

    void set_id(const root_id &id) {
	id_ = id;
    }

    const root_id & previous_id() const {
	return previous_id_;
    }

    void set_previous_id(const root_id &id) {
	previous_id_ = id;
    }

    uint64_t ptr() const {
	return ptr_;
    }

    void set_ptr(uint64_t ptr) {
	ptr_ = ptr;
    }

    size_t height() const {
	return height_;
    }

    void set_height(size_t h) {
	height_ = h;
    }

    inline uint64_t num_entries() const {
	return num_entries_;
    }

    inline void set_num_entries(uint64_t n) {
	num_entries_ = n;
    }

    inline void increment_num_entries() {
	num_entries_++;
    }

    inline void decrement_num_entries() {
	num_entries_--;
    }

    static size_t serialization_size() {
	return sizeof(uint32_t) + // Total size
	       sizeof(uint32_t) + // height
	       sizeof(uint64_t) + // num entries
	       sizeof(uint64_t) + // previous root id
	       sizeof(uint64_t);  // ptr
    }

    std::string str() const {
	std::stringstream ss;
	ss << "triedb_root{";
	ss << "id=" << id_.str() << ",prev=" << previous_id_.str()
	   << ",ptr=" << ptr_ << ",height=" << height_ << ",num_entries="
	   << num_entries_ << "}";
	return ss.str();
    }

    void read(const uint8_t *buffer);
    void write(uint8_t *buffer) const;

private:
    // Not directly stored (it's identified by file offset)
    root_id id_;

    // Stored
    root_id previous_id_;
    uint64_t ptr_;
    size_t height_;
    uint64_t num_entries_;
};

class triedb_iterator;

class triedb_exception : public std::runtime_error {
public:
    triedb_exception(const std::string &msg) : std::runtime_error(msg) { }
};

class triedb_version_exception : public triedb_exception {
public:
    triedb_version_exception(const std::string &msg) : triedb_exception(msg) { }
};

class triedb_write_exception : public triedb_exception {
public:
    triedb_write_exception(const std::string &msg) : triedb_exception(msg) { }
};

class triedb_key_already_exists_exception : public triedb_exception {
public:
    triedb_key_already_exists_exception(const std::string &msg) : triedb_exception(msg) { }
};

class triedb_key_not_found_exception : public triedb_exception {
public:
    triedb_key_not_found_exception(const std::string &msg) : triedb_exception(msg) { }
};

class triedb_node : public node_hash {
};

//
// We allow custom data to be stored in the leaf nodes.
// This will typically be the bitvector (one bit per frozen closure,
// likely an UTXO), the hash value of the same bitvector, and the hash value
// of the heap block itself. If heap blocks are 64k each = 8192 cells,
// then the bitvector is 8192 bits (1024 bytes), the custom data size would
// be 1024 + 20 + 20 bytes = 1064 bytes (note that the heap block itself
// is stored in the blockdb and not here.)
//
class triedb_leaf : public triedb_node, public custom_data_t {
public:
    static const size_t MAX_SIZE_IN_BYTES = 2*triedb_params::MB;

    inline triedb_leaf()
	: key_(0) { }

    inline triedb_leaf(const triedb_leaf &other) : triedb_node(other), custom_data_t(other), key_(other.key_) { }

    inline triedb_leaf(uint64_t key, const uint8_t *custom_dat, size_t custom_sz) : custom_data_t(custom_dat, custom_sz), key_(key) {
    }

    inline uint64_t key() const {
        return key_;
    }

    inline void set_custom_data(const uint8_t *dat, size_t sz) {
	custom_data_t::set_data(dat, sz);
    }

    inline const uint8_t * custom_data() const {
        return custom_data_t::data();
    }

    inline size_t custom_data_size() const {
        return custom_data_t::size();
    }

    inline size_t serialization_size() const {
        size_t sz = sizeof(uint32_t) + // Total size
  	            sizeof(uint64_t) + // key
  	            sizeof(uint8_t) + // hash size
	            hash_size() + // hash itself
	            custom_data_size(); // Value of leaf node
        return sz;
    }

    void read(const uint8_t *buffer);
    void write(uint8_t *buffer) const;

private:
    uint64_t key_;
};

//
// The branch node of a trie.
//
class triedb_branch : public triedb_node {
public:
    static const size_t MAX_SIZE_IN_BYTES = 1024;

    inline triedb_branch() : depth_(0), mask_(0), leaf_(0), num_(0), ptr_(nullptr) { }
    inline triedb_branch(const triedb_branch &other)
        : triedb_node(other), depth_(other.depth_), mask_(other.mask_), leaf_(other.leaf_), num_(other.num_), ptr_(nullptr) {
        size_t n = num_children();
        ptr_ = new uint64_t[n];
	memcpy(ptr_, other.ptr_, sizeof(uint64_t)*n);
    }

    static inline size_t compute_max_key_bits(uint64_t key) {
        size_t required = common::msb(key) + 1;
	required = ((required + triedb_params::MAX_BRANCH_BITS - 1) / triedb_params::MAX_BRANCH_BITS) * triedb_params::MAX_BRANCH_BITS;
	return required;
    }

    inline void set_depth(size_t d) { depth_ = d; }
    inline size_t depth() const { return depth_; }

    inline uint32_t mask() const { return mask_; }
    void set_mask(uint32_t m);

    inline size_t num_children() const
        { return std::bitset<triedb_params::MAX_BRANCH>(mask_).count(); }

    inline bool is_leaf(size_t sub_index) const {
        return !is_empty(sub_index) && ((leaf_ >> sub_index) & 1) != 0;
    }
    inline void set_leaf(size_t sub_index) {
	leaf_ |= (1 << sub_index);
    }

    inline uint64_t num_entries() const {
	return num_;
    }

    void set_num_entries(uint64_t n) {
	num_ = n;
    }

    void add_num_entries(size_t dn) {
	num_ += dn;
    }

    void sub_num_entries(size_t dn) {
	num_ -= dn;
    }

    inline bool is_branch(size_t sub_index) const {
        return !is_empty(sub_index) && !is_leaf(sub_index);
    }

    inline void set_branch(size_t sub_index) {
	leaf_ &= ~(1 << sub_index);
    }

    inline bool is_empty(size_t sub_index) const {
        return ((mask_ >> sub_index) & 1) == 0;
    }

    inline void set_empty(size_t sub_index) {
        size_t child_index = std::bitset<triedb_params::MAX_BRANCH>(mask_ & ((static_cast<uint32_t>(1) << sub_index) - 1)).count();
	size_t n = num_children();
	for (size_t i = child_index; i < n; i++) {
	    ptr_[i] = ptr_[i+1];
	}
	ptr_[n-1] = 0;
        leaf_ &= ~(1 << sub_index);
        mask_ &= ~(1 << sub_index);
    }

    size_t serialization_size() const {
       size_t sz = sizeof(uint32_t) +  // total size
                   sizeof(uint8_t) +  // max key bits
	           sizeof(uint8_t) + // hash size
                   sizeof(uint32_t) + // mask
                   sizeof(uint32_t) +  // leaf
	           sizeof(uint64_t) + // total number of entries
                   sizeof(uint64_t)*num_children() + // ptrs
	           hash_size(); // hash itself
       assert(sz < MAX_SIZE_IN_BYTES);
       return sz;
    }

    void read(const uint8_t *buffer);
    void write(uint8_t *buffer) const;

    inline uint64_t get_child_pointer(size_t sub_index) const {
        size_t child_index = std::bitset<triedb_params::MAX_BRANCH>(mask_ & ((static_cast<uint32_t>(1) << sub_index) - 1)).count();
        return ptr_[child_index];
    }

    inline void set_child_pointer(size_t sub_index, uint64_t ptr) {
        size_t child_index = std::bitset<triedb_params::MAX_BRANCH>(mask_ & ((static_cast<uint32_t>(1) << sub_index) - 1)).count();
        if (is_empty(sub_index)) {
  	    size_t n = num_children();
	    uint64_t *new_ptr = new uint64_t[n+1];
	    memcpy(new_ptr, ptr_, sizeof(uint64_t)*child_index);
	    new_ptr[child_index] = ptr;
	    memcpy(&new_ptr[child_index+1], &ptr_[child_index],
		   sizeof(uint64_t)*(n-child_index));
	    delete [] ptr_;
	    ptr_ = new_ptr;
        } else {
	    ptr_[child_index] = ptr;
	}
	mask_ |= 1 << sub_index;
    }

private:
    // The biggest key in this node
    // We use this to limit the height of the trie (to avoid all prefix 0s)
    uint8_t depth_; // Depth (beneath this)
    uint32_t mask_;
    uint32_t leaf_;
    uint64_t num_;
    uint64_t *ptr_;
};

class triedb : public triedb_params {
public:
    triedb(const std::string &dir_path);
    triedb(const triedb_params &params, const std::string &dir_path);
    ~triedb();

    inline bool is_empty() const {
        return roots_.size() == 0;
    }

    inline void set_debug(bool b) {
        debug_ = b;
    }

    void erase_all();
    static void erase_all(const std::string &dir_path);

    void flush();

    void set_leaf_hasher(std::function<void (triedb_leaf *leaf)> fn) {
	leaf_hasher_fn_ = fn;
    }

    std::function<void (triedb_leaf *)> get_leaf_hasher() const {
	return leaf_hasher_fn_;
    }

    const std::set<root_id> & find_roots(size_t height) const;

    // Asserts if there are more than 1. This is useful for testing only.
    root_id find_root(size_t height) const;

    const triedb_root & get_root(const root_id &id) const;
    bool has_root(const root_id &id) const;

    root_id new_root();
    root_id new_root(const root_id &parent);

    bool is_empty(const root_id &at_root) const;
    void insert(const root_id &at_root, uint64_t key,
		const uint8_t *data, size_t data_size);
    void update(const root_id &at_root, uint64_t key,
		const uint8_t *data, size_t data_size);
    void remove(const root_id &at_root, uint64_t key);

    void update(const root_id &at_root, const merkle_root &part);

private:
    std::pair<uint64_t, uint64_t> update(const triedb_branch *br, const merkle_branch &mbr);

public:

    const triedb_leaf * find(const root_id &at_root, uint64_t key,
		       std::vector<std::pair<const triedb_branch *, size_t> >
		           *opt_path = nullptr) const;

    triedb_iterator begin(const root_id &at_root) const;
    triedb_iterator begin(const root_id &at_root, uint64_t key) const;
    triedb_iterator end(const root_id &at_root) const;

    bool get(const root_id &at_root,
	     uint64_t from_key, uint64_t to_key, bool include_data,
	     merkle_root &result);
private:
    bool get(const triedb_branch *br, uint64_t from_key, uint64_t to_key,
	     bool include_data, merkle_branch *mbr,
	     uint64_t key_offset, uint64_t key_step,
	     size_t &current_size, size_t limit_size,
	     size_t &num_keys, size_t limit_num_keys);
public:

    const triedb_leaf * get_leaf(const triedb_branch *parent, size_t sub_index) const {
        auto file_offset = parent->get_child_pointer(sub_index);
	return get_leaf(file_offset);
    }

    const triedb_branch * get_branch(const triedb_branch *parent, size_t sub_index) const {
        auto file_offset = parent->get_child_pointer(sub_index);
	return get_branch(file_offset);
    }

    const triedb_branch * get_root_branch(const root_id &at_root) const {
        auto file_offset = get_root(at_root).ptr();
	return get_branch(file_offset);
    }

    const node_hash & get_root_hash(const root_id &at_root) const {
	auto br = get_root_branch(at_root);
	return *br;
    }

    size_t num_entries(const root_id &at_root) const {
	if (at_root.is_zero()) {
	    return 0;
	}
	return get_root(at_root).num_entries();
    }

    static void leaf_hasher(triedb_leaf *leaf);

private:
    friend class triedb_iterator;

    void branch_hasher(triedb_branch *branch);

    std::function<void (triedb_leaf *leaf)> leaf_hasher_fn_{&triedb::leaf_hasher};

    // Return modified branch node
    void insert_or_update(const root_id &at_root, uint64_t key,
			  const uint8_t *data, size_t data_size, bool do_insert);

    std::pair<const triedb_branch *, uint64_t> update_part(const triedb_branch *node,
						     uint64_t key,
						     const uint8_t *data,
						     size_t data_size,
						     bool do_insert,
						     bool &new_entry);

    std::pair<const triedb_branch *, uint64_t> remove_part(const root_id &at_root,
						     const triedb_branch *node,
						     uint64_t key);

    boost::filesystem::path roots_file_path() const;
    fstream * get_roots_stream();
    void read_roots();
    inline void increment_num_entries(const root_id &id) {
	roots_[id].increment_num_entries();
    }
    inline void decrement_num_entries(const root_id &id) {
	roots_[id].decrement_num_entries();
    }
    inline void set_num_entries(const root_id &id, uint64_t n) {
	roots_[id].set_num_entries(n);
    }
    void set_root(const root_id &at_root, uint64_t offset);
    boost::filesystem::path bucket_dir_location(size_t bucket_index) const;
    boost::filesystem::path bucket_file_path(size_t bucket_index) const;
    fstream * get_bucket_stream(size_t bucket_index) const;
    size_t scan_last_bucket() const;
    uint64_t scan_last_offset() const;
    fstream * set_file_offset(uint64_t offset) const;
    const triedb_root & get_root(const root_id &id);

    void read_leaf_node(uint64_t offset, triedb_leaf &node) const;
    uint64_t append_leaf_node(const triedb_leaf &node) const;

    void read_branch_node(uint64_t offset, triedb_branch &node) const;
    uint64_t append_branch_node(triedb_branch *node) const;

    inline const triedb_leaf * get_leaf(uint64_t file_offset) const {
        auto *r = leaf_cache_.find(file_offset);
	if (r == nullptr) {
	     auto *lf = new triedb_leaf();
	     read_leaf_node(file_offset, *lf);
	     leaf_cache_.insert(file_offset, lf);
	     return lf;
	} else {
	     return *r;
	}
    }

    inline const triedb_branch * get_branch(uint64_t file_offset) const {
        auto *r = branch_cache_.find(file_offset);
	if (r == nullptr) {
	     auto *br = new triedb_branch();
	     read_branch_node(file_offset, *br);
	     branch_cache_.insert(file_offset, br);
	     return br;
	} else {
	     return *r;
	}
    }

    std::string dir_path_;

    struct stream_flusher {
        void evicted(size_t, fstream *f) {
	    f->close();
	    delete f;
        }
    };

    struct leaf_flusher {
        void evicted(size_t, triedb_leaf *leaf) {
	    delete leaf;
        }
    };

    struct branch_flusher {
        void evicted(size_t, triedb_branch *br) {
	    delete br;
        }
    };

    // Bucket index to stream
    typedef common::lru_cache<size_t, fstream *, stream_flusher> stream_cache;
    stream_flusher stream_flusher_;
    mutable stream_cache stream_cache_;

    // Leaf cache
    typedef common::lru_cache<size_t, triedb_leaf *, leaf_flusher> leaf_cache;
    leaf_flusher leaf_flusher_;
    mutable leaf_cache leaf_cache_;

    // Branch cache
    typedef common::lru_cache<size_t, triedb_branch *, branch_flusher> branch_cache;
    branch_flusher branch_flusher_;
    mutable branch_cache branch_cache_;

    // Root references
    std::unordered_map<root_id, triedb_root> roots_;
    std::unordered_map<size_t, std::set<root_id> > roots_at_height_;
    fstream *roots_stream_;

    mutable uint64_t last_offset_;

    bool cache_shutdown_;

    bool debug_;
};

class triedb_iterator {
public:
    inline triedb_iterator(const triedb_iterator &other) :
        db_(other.db_), root_(other.root_), spine_(other.spine_) {
    }

    inline triedb_iterator(const triedb &db, const root_id &at_root)
      : db_(db), root_(at_root) {
        if (db.is_empty()) {
	    return;
	}
        auto parent_ptr = db.get_root(at_root).ptr();
	auto *parent = db.get_branch(parent_ptr);
	if (parent->mask() != 0) {
	    spine_.push_back(cursor(parent,
				    parent_ptr,
				    common::lsb(parent->mask())));
	    leftmost();
	}
    }

    inline triedb_iterator(const triedb &db, const root_id &at_root, uint64_t key)
	: db_(db), root_(at_root)  {
	if (!db.is_empty()) {
	    start_from_key(db.get_root(at_root).ptr(), key);
	}
    }

    inline triedb_iterator(const triedb &db, const root_id &at_root, bool)
        : db_(db), root_(at_root) {
    }

    inline triedb_iterator & operator = (const triedb_iterator &other) {
	assert(&db_ == &other.db_);
	root_ = other.root_;
	spine_ = other.spine_;
	return *this;
    }

    inline triedb_iterator & operator ++ () {
        next();
        return *this;
    }

    inline triedb_iterator & operator -- () {
        previous();
	return *this;
    }

    inline triedb_iterator operator - (int i) {
        auto copy_it = *this;
        while (i > 0) {
	    --i;
	    --copy_it;
        }
	return copy_it;
    }

    inline triedb_iterator operator + (int i) {
        auto copy_it = *this;
        while (i > 0) {
	    --i;
	    ++copy_it;
        }
	return copy_it;
    }

    inline bool operator == (const triedb_iterator &other) const {
        if (other.at_end()) {
	    return at_end();
        }
	return spine_ == other.spine_;
    }

    inline bool operator != (const triedb_iterator &other) const {
        return ! operator == (other);
    }

    inline const triedb_leaf & operator * () const {
        auto parent_ptr = spine_.back().parent_ptr;
        auto sub_index = spine_.back().sub_index;
	auto parent = db_.get_branch(parent_ptr);
        return *db_.get_leaf(parent, sub_index);
    }

    inline const triedb_leaf * operator -> () const {
        auto parent_ptr = spine_.back().parent_ptr;
        auto sub_index = spine_.back().sub_index;
	auto parent = db_.get_branch(parent_ptr);
        return db_.get_leaf(parent, sub_index);
    }

    inline bool at_end() const {
        return spine_.empty();
    }

private:
    void leftmost();
    void rightmost();
    inline size_t get_sub_index(const triedb_branch *parent, uint64_t key) const {
	return (key >> ((parent->depth()-1) * triedb_params::MAX_BRANCH_BITS))
	        & (triedb_params::MAX_BRANCH-1);
    }

    void start_from_key(uint64_t parent_ptr, uint64_t key);
    void adjust(uint64_t key);

    void next();
    void previous();

public:
    struct cursor {
        cursor(const triedb_branch *_parent, uint64_t _parent_ptr, size_t _sub_index)
	    : parent(_parent),parent_ptr(_parent_ptr), sub_index(_sub_index) { }
        const triedb_branch *parent;
        uint64_t parent_ptr;
        size_t sub_index;

        inline bool operator == (const cursor &other) const {
	    return parent_ptr == other.parent_ptr &&
		   sub_index == other.sub_index;
        }
    };

private:
    const triedb &db_;
    root_id root_;
    std::vector<cursor> spine_;

public:
    inline const std::vector<cursor> & path() const {
        return spine_;
    }
};

inline triedb_iterator triedb::begin(const root_id &at_root) const {
    return triedb_iterator(*this, at_root);
}

inline triedb_iterator triedb::begin(const root_id &at_root, uint64_t key) const {
    return triedb_iterator(*this, at_root, key);
}

inline triedb_iterator triedb::end(const root_id &at_root) const {
    return triedb_iterator(*this, at_root, true);
}

inline const triedb_leaf * triedb::find(const root_id &at_root, uint64_t key,
				  std::vector<
				    std::pair<const triedb_branch *, size_t> >
				      *path_opt) const
{
    if (at_root.is_zero()) {
	return nullptr;
    }
    auto it = begin(at_root, key);
    if (it == end(at_root)) {
        return nullptr;
    }
    auto &leaf = *it;
    if (leaf.key() != key) {
        return nullptr;
    }
    if (path_opt != nullptr) {
        path_opt->clear();
        for (auto &e : it.path()) {
	    path_opt->push_back(std::make_pair(e.parent, e.sub_index));
        }
    }
    return &leaf;
}

}}

#endif

max_stars_repo_name: datavetaren/prologcoin

max_issues_repo_name: datavetaren/prologcoin

max_forks_repo_name: datavetaren/prologcoin


text:
#include <spdlog/sinks/ostream_sink.h>
#include <spdlog/spdlog.h>
#include <boost/algorithm/string.hpp>

#include <clipper/logging.hpp>

namespace clipper {

Logger::Logger() {
  // Establishes asynchronous logging and defines an
  // asynchronous logging qeueue with a capacity of 8192 elements
  spdlog::set_async_mode(8192, spdlog::async_overflow_policy::block_retry);
  spdlogger_ = spdlog::stdout_color_mt(LOGGER_NAME);
  spdlogger_->set_pattern(LOGGING_FORMAT);
}

Logger::Logger(std::ostringstream &output_stream) {
  // Establishes asynchronous logging and defines an
  // asynchronous logging qeueue with a capacity of 8192 elements
  spdlog::set_async_mode(8192, spdlog::async_overflow_policy::block_retry);
  auto oss_sink =
      std::make_shared<spdlog::sinks::ostream_sink_mt>(output_stream);
  spdlogger_ = std::make_shared<spdlog::logger>(LOGGER_NAME, oss_sink);
  spdlogger_->set_pattern(LOGGING_FORMAT);
}

Logger &Logger::get() {
  // References a global singleton Logger object.
  // This object is created if it does not already exist,
  // and it is automatically memory managed
  static Logger instance;
  return instance;
}

const std::string Logger::get_formatted_tag(const std::string tag,
                                            LogLevel log_level) const {
  std::string tag_string(tag);
  boost::to_upper(tag_string);
  size_t tag_length = tag_string.length();
  std::stringstream ss;
  size_t level_padding = 0;
  switch (log_level) {
    case LogLevel::Info:
      level_padding =
          MAX_LOGGING_LEVEL_FORMAT_LENGTH - LOGGING_LEVEL_FORMAT_INFO_LENGTH;
      break;
    case LogLevel::Error:
      level_padding =
          MAX_LOGGING_LEVEL_FORMAT_LENGTH - LOGGING_LEVEL_FORMAT_ERROR_LENGTH;
      break;
    case LogLevel::Debug:
      level_padding =
          MAX_LOGGING_LEVEL_FORMAT_LENGTH - LOGGING_LEVEL_FORMAT_DEBUG_LENGTH;
      break;
    default: break;
  }
  ss << std::string(level_padding, ' ');
  if (tag_length < MAX_TAG_LENGTH) {
    ss << std::string(MAX_TAG_LENGTH - tag_length, ' ');
  } else if (tag_length > MAX_TAG_LENGTH) {
    tag_string = tag_string.substr(0, MAX_TAG_LENGTH - 3) + "...";
  }
  ss << "[" << tag_string << "] ";
  return ss.str();
}

void Logger::pad_logging_stream_for_alignment(std::stringstream &ss,
                                              LogLevel log_level,
                                              size_t tag_length) const {
  ss << std::string(LOGGING_FORMAT_LENGTH + tag_length, ' ');
  size_t log_padding = 0;
  switch (log_level) {
    case LogLevel::Info: log_padding = LOGGING_LEVEL_FORMAT_INFO_LENGTH; break;
    case LogLevel::Error:
      log_padding = LOGGING_LEVEL_FORMAT_ERROR_LENGTH;
      break;
    case LogLevel::Debug:
      log_padding = LOGGING_LEVEL_FORMAT_DEBUG_LENGTH;
      break;
    default: break;
  }
  ss << std::string(log_padding, ' ');
}

}  // namespace clipper

ext: cpp

max_stars_repo_name: mukkachaitanya/parity-models

max_issues_repo_name: mukkachaitanya/parity-models

max_forks_repo_name: mukkachaitanya/parity-models


text:
/*
 * Copyright (C) 2018 CESNET, https://photonics.cesnet.cz/
 * Copyright (C) 2018 FIT CVUT, https://fit.cvut.cz/
 *
 * Written by Václav Kubernát <kubervac@fit.cvut.cz>
 *
*/

#include "trompeloeil_doctest.hpp"
#include <boost/core/demangle.hpp>
#include "ast_commands.hpp"
#include "leaf_data_helpers.hpp"
#include "parser.hpp"
#include "pretty_printers.hpp"
#include "static_schema.hpp"
#include "utils.hpp"

TEST_CASE("leaf editing")
{
    auto schema = std::make_shared<StaticSchema>();
    schema->addModule("mod");
    schema->addModule("pizza-module");
    schema->addContainer("/", "mod:contA");
    schema->addLeaf("/", "mod:leafString", yang::String{});
    schema->addLeaf("/", "mod:leafDecimal", yang::Decimal{});
    schema->addLeaf("/", "mod:leafBool", yang::Bool{});
    schema->addLeaf("/", "mod:leafInt8", yang::Int8{});
    schema->addLeaf("/", "mod:leafInt16", yang::Int16{});
    schema->addLeaf("/", "mod:leafInt32", yang::Int32{});
    schema->addLeaf("/", "mod:leafInt64", yang::Int64{});
    schema->addLeaf("/", "mod:leafUint8", yang::Uint8{});
    schema->addLeaf("/", "mod:leafUint16", yang::Uint16{});
    schema->addLeaf("/", "mod:leafUint32", yang::Uint32{});
    schema->addLeaf("/", "mod:leafUint64", yang::Uint64{});
    schema->addLeaf("/", "mod:leafBinary", yang::Binary{});
    schema->addIdentity(std::nullopt, identityRef_{"mod", "food"});
    schema->addIdentity(std::nullopt, identityRef_{"mod", "vehicle"});
    schema->addIdentity(identityRef_{"mod", "food"}, identityRef_{"mod", "pizza"});
    schema->addIdentity(identityRef_{"mod", "food"}, identityRef_{"mod", "spaghetti"});
    schema->addIdentity(identityRef_{"mod", "pizza"}, identityRef_{"pizza-module", "hawaii"});
    schema->addLeaf("/", "mod:foodIdentRef", yang::IdentityRef{schema->validIdentities("mod", "food")});
    schema->addLeaf("/", "mod:pizzaIdentRef", yang::IdentityRef{schema->validIdentities("mod", "pizza")});
    schema->addLeaf("/mod:contA", "mod:identInCont", yang::IdentityRef{schema->validIdentities("mod", "pizza")});
    schema->addLeaf("/", "mod:leafEnum", createEnum({"lol", "data", "coze"}));
    schema->addLeaf("/mod:contA", "mod:leafInCont", yang::String{});
    schema->addList("/", "mod:list", {"number"});
    schema->addLeaf("/mod:list", "mod:number", yang::Int32{});
    schema->addLeaf("/mod:list", "mod:leafInList", yang::String{});
    schema->addLeaf("/", "mod:refToString", yang::LeafRef{"/mod:leafString", std::make_unique<yang::TypeInfo>(schema->leafType("/mod:leafString"))});
    schema->addLeaf("/", "mod:refToInt8", yang::LeafRef{"/mod:leafInt8", std::make_unique<yang::TypeInfo>(schema->leafType("/mod:leafInt8"))});
    schema->addLeaf("/", "mod:refToLeafInCont", yang::LeafRef{"/mod:contA/identInCont", std::make_unique<yang::TypeInfo>(schema->leafType("/mod:contA/mod:identInCont"))});
    schema->addLeaf("/", "mod:intOrString", yang::Union{{yang::TypeInfo{yang::Int32{}}, yang::TypeInfo{yang::String{}}}});
    schema->addLeaf("/", "mod:twoInts", yang::Union{{yang::TypeInfo{yang::Uint8{}}, yang::TypeInfo{yang::Int16{}}}});
    schema->addLeaf("/", "mod:unionStringEnumLeafref", yang::Union{{
            yang::LeafDataType{yang::String{}},
        yang::LeafDataType{createEnum({"foo", "bar"})},
        yang::LeafDataType{yang::LeafRef{"/mod:leafEnum", std::make_unique<yang::TypeInfo>(schema->leafType("/mod:leafEnum"))}}
    }});

    schema->addList("/", "mod:portSettings", {"port"});
    schema->addLeaf("/mod:portSettings", "mod:port", createEnum({"eth0", "eth1", "eth2"}));
    schema->addList("/", "mod:portMapping", {"port"});
    schema->addLeaf("/mod:portMapping", "mod:port", createEnum({"utf1", "utf2", "utf3"}));
    schema->addLeaf("/", "mod:activeMappedPort", yang::LeafRef{"/mod:portMapping/mod:port", std::make_unique<yang::TypeInfo>(schema->leafType("/mod:portMapping/mod:port"))});
    schema->addLeaf("/", "mod:activePort", yang::Union{{
        yang::TypeInfo{createEnum({"wlan0", "wlan1"})},
        yang::TypeInfo{yang::LeafRef{"/mod:portSettings/mod:port", std::make_unique<yang::TypeInfo>(schema->leafType("/mod:portSettings/mod:port"))}},
        yang::TypeInfo{yang::LeafRef{"/mod:activeMappedPort", std::make_unique<yang::TypeInfo>(schema->leafType("/mod:activeMappedPort"))}},
        yang::TypeInfo{yang::Empty{}},
    }});
    schema->addLeaf("/", "mod:dummy", yang::Empty{});
    schema->addLeaf("/", "mod:readonly", yang::Int32{}, yang::AccessType::ReadOnly);

    schema->addLeaf("/", "mod:flags", yang::Bits{{"carry", "sign"}});

    Parser parser(schema);
    std::string input;
    std::ostringstream errorStream;

    SECTION("valid input")
    {
        set_ expected;

        SECTION("set mod:leafString \"some_data\"")
        {
            input = "set mod:leafString \'some_data\'";
            expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafString"));
            expected.m_data = std::string("some_data");
        }

        SECTION("set mod:contA/leafInCont 'more_data'")
        {
            input = "set mod:contA/leafInCont 'more_data'";
            expected.m_path.m_nodes.emplace_back(module_{"mod"}, container_("contA"));
            expected.m_path.m_nodes.emplace_back(leaf_("leafInCont"));
            expected.m_data = std::string("more_data");
        }

        SECTION("set mod:contA/leafInCont \"data with' a quote\"")
        {
            input = "set mod:contA/leafInCont \"data with' a quote\"";
            expected.m_path.m_nodes.emplace_back(module_{"mod"}, container_("contA"));
            expected.m_path.m_nodes.emplace_back(leaf_("leafInCont"));
            expected.m_data = std::string("data with' a quote");
        }

        SECTION("set mod:contA/leafInCont 'data with\" a quote'")
        {
            input = "set mod:contA/leafInCont 'data with\" a quote'";
            expected.m_path.m_nodes.emplace_back(module_{"mod"}, container_("contA"));
            expected.m_path.m_nodes.emplace_back(leaf_("leafInCont"));
            expected.m_data = std::string("data with\" a quote");
        }

        SECTION("set mod:contA/leafInCont   'more   d\tata'") // spaces in string
        {
            input = "set mod:contA/leafInCont 'more   d\tata'";
            expected.m_path.m_nodes.emplace_back(module_{"mod"}, container_("contA"));
            expected.m_path.m_nodes.emplace_back(leaf_("leafInCont"));
            expected.m_data = std::string("more   d\tata");
        }

        SECTION("set mod:list[number=1]/leafInList \"another_data\"")
        {
            input = "set mod:list[number=1]/leafInList \"another_data\"";
            auto keys = ListInstance{
                {"number", int32_t{1}}};
            expected.m_path.m_nodes.emplace_back(module_{"mod"}, listElement_("list", keys));
            expected.m_path.m_nodes.emplace_back(leaf_("leafInList"));
            expected.m_data = std::string("another_data");
        }

        SECTION("data types")
        {
            SECTION("string")
            {
                input = "set mod:leafString \"somedata\"";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafString"));
                expected.m_data = std::string("somedata");
            }

            SECTION("more spaces before value")
            {
                input = "set mod:leafString   \"somedata\"";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafString"));
                expected.m_data = std::string("somedata");
            }

            SECTION("int8")
            {
                input = "set mod:leafInt8 2";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafInt8"));
                expected.m_data = int8_t{2};
            }

            SECTION("negative int8")
            {
                input = "set mod:leafInt8 -10";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafInt8"));
                expected.m_data = int8_t{-10};
            }

            SECTION("uint8")
            {
                input = "set mod:leafUint8 2";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafUint8"));
                expected.m_data = uint8_t{2};
            }

            SECTION("int16")
            {
                input = "set mod:leafInt16 30000";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafInt16"));
                expected.m_data = int16_t{30'000};
            }

            SECTION("uint16")
            {
                input = "set mod:leafUint16 30000";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafUint16"));
                expected.m_data = uint16_t{30'000};
            }

            SECTION("int32")
            {
                input = "set mod:leafInt32 30000";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafInt32"));
                expected.m_data = int32_t{30'000};
            }

            SECTION("uint32")
            {
                input = "set mod:leafUint32 30000";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafUint32"));
                expected.m_data = uint32_t{30'000};
            }

            SECTION("int32")
            {
                input = "set mod:leafInt32 30000";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafInt32"));
                expected.m_data = int32_t{30'000};
            }

            SECTION("uint64")
            {
                input = "set mod:leafUint64 30000";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafUint64"));
                expected.m_data = uint64_t{30'000};
            }

            SECTION("decimal")
            {
                input = "set mod:leafDecimal 3.14159";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafDecimal"));
                expected.m_data = 3.14159;
            }

            SECTION("enum")
            {
                input = "set mod:leafEnum coze";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafEnum"));
                expected.m_data = enum_("coze");
            }

            SECTION("bool")
            {
                input = "set mod:leafBool true";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafBool"));
                expected.m_data = true;
            }

            SECTION("union")
            {
                SECTION("int")
                {
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("intOrString"));
                    input = "set mod:intOrString 90";
                    expected.m_data = int32_t{90};
                }
                SECTION("string")
                {
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("intOrString"));
                    input = "set mod:intOrString \"test\"";
                    expected.m_data = std::string{"test"};
                }

                SECTION("union with two integral types")
                {
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("twoInts"));
                    SECTION("uint8")
                    {
                        input = "set mod:twoInts 100";
                        expected.m_data = uint8_t{100};
                    }
                    SECTION("int16")
                    {
                        input = "set mod:twoInts 6666";
                        expected.m_data = int16_t{6666};
                    }
                }

                SECTION("union with enum and leafref to enum")
                {
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("unionStringEnumLeafref"));
                    SECTION("string")
                    {
                        input = "set mod:unionStringEnumLeafref \"AHOJ\"";
                        expected.m_data = std::string{"AHOJ"};
                    }
                    SECTION("enum")
                    {
                        input = "set mod:unionStringEnumLeafref bar";
                        expected.m_data = enum_("bar");
                    }
                    SECTION("enum leafref")
                    {
                        input = "set mod:unionStringEnumLeafref coze";
                        expected.m_data = enum_("coze");
                    }
                }

                SECTION("activePort")
                {
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("activePort"));
                    input = "set mod:activePort ";
                    SECTION("1. anonymous enum")
                    {
                        SECTION("wlan0")
                        {
                            input += "wlan0";
                            expected.m_data = enum_("wlan0");
                        }
                        SECTION("wlan1")
                        {
                            input += "wlan1";
                            expected.m_data = enum_("wlan1");
                        }
                    }
                    SECTION("2. leafref to enum")
                    {
                        SECTION("eth0")
                        {
                            input += "eth0";
                            expected.m_data = enum_("eth0");
                        }
                        SECTION("eth1")
                        {
                            input += "eth1";
                            expected.m_data = enum_("eth1");
                        }
                        SECTION("eth2")
                        {
                            input += "eth2";
                            expected.m_data = enum_("eth2");
                        }
                    }
                    SECTION("3. leafref to leafref")
                    {
                        SECTION("utf1")
                        {
                            input += "utf1";
                            expected.m_data = enum_("utf1");
                        }
                        SECTION("utf2")
                        {
                            input += "utf2";
                            expected.m_data = enum_("utf2");
                        }
                        SECTION("utf3")
                        {
                            input += "utf3";
                            expected.m_data = enum_("utf3");
                        }
                    }
                    SECTION("4. empty")
                    {
                        expected.m_data = empty_{};
                    }
                }
            }

            SECTION("binary")
            {
                SECTION("zero ending '='")
                {
                    input = "set mod:leafBinary This/IsABase64EncodedSomething++/342431++";
                    expected.m_data = binary_{"This/IsABase64EncodedSomething++/342431++"};
                }

                SECTION("one ending '='")
                {
                    input = "set mod:leafBinary This/IsABase64EncodedSomething++/342431++=";
                    expected.m_data = binary_{"This/IsABase64EncodedSomething++/342431++="};
                }

                SECTION("two ending '='")
                {
                    input = "set mod:leafBinary This/IsABase64EncodedSomething++/342431++==";
                    expected.m_data = binary_{"This/IsABase64EncodedSomething++/342431++=="};
                }
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafBinary"));
            }

            SECTION("identityRef")
            {
                SECTION("foodIdentRef")
                {
                    input = "set mod:foodIdentRef ";
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("foodIdentRef"));

                    SECTION("food")
                    {
                        input += "food";
                        expected.m_data = identityRef_("food");
                    }
                    SECTION("mod:food")
                    {
                        input += "mod:food";
                        expected.m_data = identityRef_("mod", "food");
                    }
                    SECTION("pizza")
                    {
                        input += "pizza";
                        expected.m_data = identityRef_("pizza");
                    }
                    SECTION("mod:pizza")
                    {
                        input += "mod:pizza";
                        expected.m_data = identityRef_("mod", "pizza");
                    }
                    SECTION("pizza-module:hawaii")
                    {
                        input += "pizza-module:hawaii";
                        expected.m_data = identityRef_("pizza-module", "hawaii");
                    }
                }
                SECTION("pizzaIdentRef")
                {
                    input = "set mod:pizzaIdentRef ";
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("pizzaIdentRef"));
                    SECTION("pizza")
                    {
                        input += "pizza";
                        expected.m_data = identityRef_("pizza");
                    }
                    SECTION("mod:pizza")
                    {
                        input += "mod:pizza";
                        expected.m_data = identityRef_("mod", "pizza");
                    }
                    SECTION("pizza-module:hawaii")
                    {
                        input += "pizza-module:hawaii";
                        expected.m_data = identityRef_("pizza-module", "hawaii");
                    }
                }
                SECTION("mod:contA/identInCont")
                {
                    input = "set mod:contA/identInCont ";
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, container_("contA"));
                    expected.m_path.m_nodes.emplace_back(leaf_("identInCont"));
                    SECTION("pizza")
                    {
                        input += "pizza";
                        expected.m_data = identityRef_("pizza");
                    }
                    SECTION("mod:pizza")
                    {
                        input += "mod:pizza";
                        expected.m_data = identityRef_("mod", "pizza");
                    }
                    SECTION("pizza-module:hawaii")
                    {
                        input += "pizza-module:hawaii";
                        expected.m_data = identityRef_("pizza-module", "hawaii");
                    }
                }
            }
            SECTION("leafRef")
            {
                SECTION("refToString")
                {
                    input = "set mod:refToString \"blabal\"";
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("refToString"));
                    expected.m_data = std::string("blabal");
                }

                SECTION("refToInt8")
                {
                    input = "set mod:refToInt8 42";
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("refToInt8"));
                    expected.m_data = int8_t{42};
                }

                SECTION("refToLeafInCont")
                {
                    input = "set mod:refToLeafInCont pizza";
                    expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("refToLeafInCont"));
                    expected.m_data = identityRef_{"pizza"};
                }
            }
            SECTION("empty")
            {
                input = "set mod:dummy ";
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("dummy"));
                expected.m_data = empty_{};
            }

            SECTION("bits")
            {
                input = "set mod:flags ";
                decltype(bits_::m_bits) bits;
                SECTION("<nothing>")
                {
                    bits = {};
                }
                SECTION("carry")
                {
                    input += "carry";
                    bits = {"carry"};
                }
                SECTION("sign")
                {
                    input += "sign";
                    bits = {"sign"};
                }
                SECTION("carry sign")
                {
                    input += "carry sign";
                    bits = {"carry", "sign"};
                }
                SECTION("sign carry")
                {
                    input += "sign carry";
                    bits = {"sign", "carry"};
                }
                expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("flags"));
                expected.m_data = bits_{bits};
            }
        }

        command_ command = parser.parseCommand(input, errorStream);
        REQUIRE(command.type() == typeid(set_));
        REQUIRE(boost::get<set_>(command) == expected);
    }

    SECTION("invalid input")
    {
        std::string expectedError;
        SECTION("missing space between a command and its arguments")
        {
            SECTION("setmod:leafString some_data")
            {
                input = "setmod:leafString 'some_data'";
            }
        }

        SECTION("missing space between arguments")
        {
            SECTION("set mod:leafString'lol'")
            {
                input = "set mod:leafString'lol'";
            }
        }

        SECTION("non-leaf identifiers")
        {
            SECTION("set mod:nonexistent 'blabla'")
            {
                input = "set mod:nonexistent 'blabla'";
            }

            SECTION("set mod:contA 'abde'")
            {
                input = "set mod:contA 'abde'";
            }
        }

        SECTION("wrong types")
        {
            expectedError = "leaf data type mismatch";
            SECTION("set mod:leafBool 'blabla'")
            {
                input = "set mod:leafBool 'blabla'";
            }
            SECTION("set mod:leafUint8 'blabla'")
            {
                input = "set mod:leafUint8 'blabla'";
            }
            SECTION("set mod:leafUint8 -5")
            {
                input = "set mod:leafUint8 -5";
            }
            SECTION("set mod:leafInt8 'blabla'")
            {
                input = "set mod:leafInt8 'blabla'";
            }
            SECTION("set mod:leafInt8 130")
            {
                input = "set mod:leafInt8 130";
            }
            SECTION("set mod:leafUint16 'blabla'")
            {
                input = "set mod:leafUint16 'blabla'";
            }
            SECTION("set mod:leafInt16 'blabla'")
            {
                input = "set mod:leafInt16 'blabla'";
            }
            SECTION("set mod:leafUint32 'blabla'")
            {
                input = "set mod:leafUint32 'blabla'";
            }
            SECTION("set mod:leafInt32 'blabla'")
            {
                input = "set mod:leafInt32 'blabla'";
            }
            SECTION("set mod:leafUint64 'blabla'")
            {
                input = "set mod:leafUint64 'blabla'";
            }
            SECTION("set mod:leafInt64 'blabla'")
            {
                input = "set mod:leafInt64 'blabla'";
            }
            SECTION("set mod:leafEnum 'blabla'")
            {
                input = "set mod:leafEnum 'blabla'";
            }
            SECTION("set mod:refToInt8 'blabla'")
            {
                input = "set mod:refToInt8 'blabla'";
            }
        }

        SECTION("wrong base64 strings")
        {
            SECTION("invalid character")
            {
                input = "set mod:leafBinary dbahj-";
            }
            SECTION("equal sign in the middle")
            {
                input = "set mod:leafBinary db=ahj";
            }
            SECTION("enclosing in quotes")
            {
                input = "set mod:leafBinary 'dbahj'";
            }
        }

        SECTION("non-existing identity")
        {
            input = "set mod:foodIdentRef identityBLABLA";
        }

        SECTION("identity with non-existing module")
        {
            expectedError = "Invalid module name";
            input = "set mod:foodIdentRef xd:haha";
        }

        SECTION("setting identities with wrong bases")
        {
            SECTION("set mod:foodIdentRef mod:vehicle")
            {
                input = "set mod:foodIdentRef mod:vehicle";
            }
            SECTION("set mod:pizzaIdentRef mod:food")
            {
                input = "set mod:pizzaIdentRef mod:food";
            }
        }
        SECTION("setting different module identities without prefix")
        {
            input = "set mod:pizzaIdentRef hawaii";
        }
        SECTION("identity prefix without name")
        {
            input = "set mod:contA/identInCont pizza-module:";
        }

        SECTION("set a union path to a wrong type")
        {
            input = "set mod:intOrString true";
        }

        SECTION("no space for empty data")
        {
            input = "set mod:dummy";
        }

        SECTION("empty path")
        {
            input = "set ";
        }

        SECTION("setting readonly data")
        {
            input = "set mod:readonly 123";
        }

        SECTION("nonexistent bits")
        {
            input = "set mod:flags daw";
        }

        SECTION("same bit more than once")
        {
            input = "set mod:flags carry carry";
        }

        REQUIRE_THROWS_AS(parser.parseCommand(input, errorStream), InvalidCommandException);
        REQUIRE(errorStream.str().find(expectedError) != std::string::npos);
    }

    SECTION("deleting a leaf")
    {
        delete_ expected;
        input = "delete mod:leafString";
        expected.m_path.m_nodes.emplace_back(module_{"mod"}, leaf_("leafString"));

        command_ command = parser.parseCommand(input, errorStream);
        REQUIRE(command.type() == typeid(delete_));
        REQUIRE(boost::get<delete_>(command) == expected);
    }
}

max_stars_repo_name: CESNET/netconf-cli

max_issues_repo_name: CESNET/netconf-cli

max_forks_repo_name: CESNET/netconf-cli


text:
/*=============================================================================
    Copyright (c) 2016 Kohei Takahashi

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef boost_phoenix_core_detail_index_sequence_hpp
#define boost_phoenix_core_detail_index_sequence_hpp

#include <boost/fusion/support/detail/index_sequence.hpp>

namespace boost { namespace phoenix { namespace detail {
using ::boost::fusion::detail::index_sequence;
using ::boost::fusion::detail::make_index_sequence;
}}}

#endif

ext: hpp

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
/*************************************************************************************
Copyright (c) 2013, Carnegie Mellon University
All rights reserved.
Authors: Anurag Jakhotia<ajakhoti@andrew.cmu.edu>, Prasanna Velagapudi<pkv@cs.cmu.edu>

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

 -    Redistributions of source code must retain the above copyright notice, this list
     of conditions and the following disclaimer.
 -    Redistributions in binary form must reproduce the above copyright notice, this
     list of conditions and the following disclaimer in the documentation and/or other
     materials provided with the     distribution.
 -    Neither the name of Carnegie Mellon University nor the names of its contributors
     may be used to endorse or promote products derived from this software without
     specific prior written     permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************************/
#include "k2_client/BodyArray.h"

#include <boost/asio.hpp>
#include <ros/ros.h>
#include <array>
#include <yaml-cpp/yaml.h>

#include <iostream>
#include <fstream>
using namespace std;

using boost::asio::ip::tcp;

const std::array<std::string, 25> joint_names = {
    "SpineBase", "SpineMid", "SpineShoulder", "Neck", "Head",
    "ShoulderLeft", "ElbowLeft", "WristLeft", "HandLeft",
    "ShoulderRight", "ElbowRight", "WristRight", "HandRight",
    "HipLeft", "KneeLeft", "AnkleLeft", "FootLeft",
    "HipRight", "KneeRight", "AnkleRight", "FootRight",
    "HandTipLeft", "ThumbLeft",
    "HandTipRight", "ThumbRight"
};

int main(int argc, char *argv[])
{
    // Initialize this ROS node.
    // ros::init(argc, argv, "k2_body", ros::init_options::AnonymousName);
    ros::init(argc, argv, ros::this_node::getName(), ros::init_options::AnonymousName);
    ros::NodeHandle n("~");

    // Retrieve the hostname and port of the k2_server.
    std::string server_host, server_port, frame_id;
    n.getParam("host", server_host);
    n.param<std::string>("port", server_port, "9003"); // default for k2_server bodies
    n.param<std::string>("frame_id", frame_id, "/k2/depth_frame");

    // Create a Boost ASIO service to handle server connection.
    boost::asio::io_service io_service;

    // Create a Boost ASIO stream buffer to hold the unparsed input from the server.
    boost::asio::streambuf buffer;

    // Get a list of endpoints corresponding to the server hostname and port.
    tcp::resolver resolver(io_service);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve({server_host, server_port});

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_service);
    try
    {
        boost::asio::connect(socket, endpoint_iterator);
    }
    catch (boost::system::system_error const& e)
    {
        ROS_FATAL("Failed to connect to k2 server '%s:%s': %s",
                  server_host.c_str(), server_port.c_str(), e.what());
        return -1;
    }

    // Create a ROS publisher for the deserialized stream output.
    ros::Publisher bodyPublisher = n.advertise<k2_client::BodyArray>("bodies", 1);

    while(ros::ok())
    {
        // Read the next line from the server.
        boost::asio::read_until(socket, buffer, "\n");  //Make sure that the message being sent has '\n' at the end
        std::istream is(&buffer);
        std::string message;
        std::getline(is, message);

        // Parse the line from the server as JSON/YAML.
        const YAML::Node node = YAML::Load(message);
        if (!node)
        {
            ROS_WARN("Received malformed message '%s'.", message.c_str());
            continue;
        }

        // Convert the JSON message to a ROS message.
        const YAML::Node bodies_node = node["Bodies"];
        k2_client::BodyArray body_array;

            for (const YAML::Node body_node : bodies_node)
            {
                k2_client::Body body;

                body.header.stamp =              ros::Time(node["Time"].as<double>());  //needs to be a double, not an unsigned long
                body.header.frame_id =           frame_id;
                body.leanTrackingState =         body_node["LeanTrackingState"].as<int>();
                body.lean.leanX =                body_node["Lean"]["X"].as<double>();
                body.lean.leanY =                body_node["Lean"]["Y"].as<double>();
                body.trackingId =                body_node["TrackingId"].as<unsigned long>();
                body.clippedEdges =              body_node["ClippedEdges"].as<int>();
                body.handRightConfidence =       body_node["HandRightConfidence"].as<int>();
                body.handRightState =            body_node["HandRightState"].as<int>();
                body.handLeftConfidence =        body_node["HandLeftConfidence"].as<int>();
                body.handLeftState =             body_node["HandLeftState"].as<int>();
                body.ipAddress = server_host;

                for (const std::string joint_name : joint_names)
                {
                    k2_client::JointPositionAndState JPAS;
                    JPAS.trackingState = body_node["Joints"][joint_name]["TrackingState"].as<int>();
                    JPAS.position.x =    body_node["Joints"][joint_name]["Position"]["X"].as<double>();
                    JPAS.position.y =    body_node["Joints"][joint_name]["Position"]["Y"].as<double>();
                    JPAS.position.z =    body_node["Joints"][joint_name]["Position"]["Z"].as<double>();
                    JPAS.jointType =     body_node["Joints"][joint_name]["JointType"].as<int>();
                    body.jointPositions.push_back(JPAS);

                    k2_client::JointOrientationAndType JOAT;
                    JOAT.orientation.x = body_node["JointOrientations"][joint_name]["Orientation"]["X"].as<double>();
                    JOAT.orientation.y = body_node["JointOrientations"][joint_name]["Orientation"]["Y"].as<double>();
                    JOAT.orientation.z = body_node["JointOrientations"][joint_name]["Orientation"]["Z"].as<double>();
                    JOAT.orientation.w = body_node["JointOrientations"][joint_name]["Orientation"]["W"].as<double>();
                    JOAT.jointType =     body_node["JointOrientations"][joint_name]["JointType"].as<int>();
                    body.jointOrientations.push_back(JOAT);
                }

                body_array.bodies.push_back(body);

            }

        // Send out the resulting message and request a new message.
        bodyPublisher.publish(body_array);
        boost::asio::write(socket, boost::asio::buffer("OK\n"));
        ros::spinOnce();
    }

    return 0;
}


text:
#include "CondCore/CondDB/interface/FileUtils.h"
#include "CondCore/CondDB/interface/Exception.h"
#include "CondCore/CondDB/interface/Auth.h"
#include "RelationalAccess/AuthenticationCredentials.h"
#include "CoralCommon/Cipher.h"
#include "RelationalAccess/AuthenticationServiceException.h"
#include "CoralKernel/IPropertyManager.h"
#include "CoralKernel/Property.h"
#include "CoralKernel/Context.h"
#include "CondCore/CondDB/interface/CoralServiceMacros.h"
#include "FWCore/Concurrency/interface/Xerces.h"
#include "xercesc/parsers/XercesDOMParser.hpp"
#include "xercesc/framework/MemBufInputSource.hpp"
#include "xercesc/dom/DOM.hpp"
#include "xercesc/sax/HandlerBase.hpp"
#include "xercesc/util/XMLString.hpp"
#include "xercesc/util/PlatformUtils.hpp"
#include "XMLAuthenticationService.h"

#include <memory>
#include <cstdlib>
#include <fstream>
#include <sys/stat.h>
#include <fcntl.h>
#include <boost/filesystem.hpp>
#include <boost/version.hpp>
#include <boost/bind.hpp>
//#include <iostream>
#include "CoralBase/MessageStream.h"

constexpr char XML_AUTHENTICATION_FILE[] = "authentication.xml";

cond::XMLAuthenticationService::DataSourceEntry::DataSourceEntry( const std::string& serviceName,
                                                                  const std::string& connectionName ):
  m_serviceName( serviceName ),
  m_connectionName( connectionName ),
  m_default( new coral::AuthenticationCredentials( serviceName ) ),
  m_data()
{}

cond::XMLAuthenticationService::DataSourceEntry::~DataSourceEntry()
{
  delete m_default;
  for ( std::map< std::string, coral::AuthenticationCredentials* >::iterator iData = m_data.begin();
        iData != m_data.end(); ++iData )
    delete iData->second;
}

void
cond::XMLAuthenticationService::DataSourceEntry::appendCredentialItem( const std::string& item,
                                                                       const std::string& value )
{
  m_default->registerItem( item, value );
}

void
cond::XMLAuthenticationService::DataSourceEntry::appendCredentialItemForRole( const std::string& item,
                                                                              const std::string& value,
                                                                              const std::string& role )
{
  std::map< std::string, coral::AuthenticationCredentials* >::iterator iRole = m_data.find( role );
  if ( iRole == m_data.end() ) {
    iRole = m_data.insert( std::make_pair( role, new coral::AuthenticationCredentials( m_serviceName ) ) ).first;
  }
  iRole->second->registerItem( item, value );
}

const coral::IAuthenticationCredentials&
cond::XMLAuthenticationService::DataSourceEntry::credentials() const
{
  return *m_default;
}

const coral::IAuthenticationCredentials&
cond::XMLAuthenticationService::DataSourceEntry::credentials( const std::string& role ) const
{
  /**
  std::map< std::string, coral::AuthenticationCredentials* >::const_iterator iRole = m_data.find( role );
  if ( iRole == m_data.end() )
    throw coral::UnknownRoleException( m_serviceName,
                                       m_connectionName,
                                       role );
  return *( iRole->second );
  **/
  return *m_default;
}

cond::XMLAuthenticationService::XMLAuthenticationService::XMLAuthenticationService( const std::string& key )
  : coral::Service( key ),
    m_isInitialized( false ),
    m_inputFileName( "" ),
    m_data(),
    m_mutexLock(),
    m_callbackID(0)
{
  boost::function1<void, std::string> cb(boost::bind(&cond::XMLAuthenticationService::XMLAuthenticationService::setAuthenticationPath, this, _1));

  coral::Property* pm = dynamic_cast<coral::Property*>(coral::Context::instance().PropertyManager().property(auth::COND_AUTH_PATH_PROPERTY));
  if(pm){
    setAuthenticationPath( pm->get() );
    m_callbackID = pm->registerCallback(cb);
  }
}

cond::XMLAuthenticationService::XMLAuthenticationService::~XMLAuthenticationService()
{
  for ( std::map< std::string, cond::XMLAuthenticationService::DataSourceEntry* >::iterator iConnection = m_data.begin();
        iConnection != m_data.end(); ++iConnection ) delete iConnection->second;
}

void
cond::XMLAuthenticationService::XMLAuthenticationService::setAuthenticationPath(  const std::string& inputPath )
{
  boost::filesystem::path boostAuthPath( inputPath );
  if(boost::filesystem::is_directory(boostAuthPath)){
    boostAuthPath /= boost::filesystem::path(XML_AUTHENTICATION_FILE);
  }

  m_inputFileName = boostAuthPath.string();
  reset();
}

bool
cond::XMLAuthenticationService::XMLAuthenticationService::processFile( const std::string& inputFileName )
{
  coral::MessageStream log("cond::XMLAuthenticationService::processFile");
  //std::cout<< "Processing file \""<< inputFileName<<"\"" <<std::endl;
  bool result = true;

  cond::FileReader inputFile;
  std::string cont("");
  try{
    inputFile.read(inputFileName);
    cont = inputFile.content();
  } catch (const cond::Exception& exc){
    log << coral::Error << "File \"" << inputFileName << "\" not found."<<std::string(exc.what())<<coral::MessageStream::endmsg;
   return false;
  }

  // check the
  boost::filesystem::path filePath( inputFileName );
#if (BOOST_VERSION / 100000) >= 1 && ((BOOST_VERSION / 100) % 1000) >= 47
  std::string name = filePath.filename().string();
#else
  std::string name = filePath.leaf();
#endif
  /**
  if(name!=XML_AUTHENTICATION_FILE){
    cond::DecodingKey key;
    try{
      key.readUserKeyString(cont);
      log << coral::Debug << "Decoding content of file \""<< key.dataSource()<<"\""<<coral::MessageStream::endmsg;
      cond::FileReader dataFile;
      dataFile.read(key.dataSource());
      cont = dataFile.content();
      cont = coral::Cipher::decode(cont,key.key());
    } catch (const cond::Exception& exc){
      log << coral::Error << std::string(exc.what())<<coral::MessageStream::endmsg;
      return false;
    }

  } else {
    //seal::MessageStream log( this, this->name(),seal::Msg::Verbose );
    log<<coral::Debug<< "Authentication file is expected standard XML."<<coral::MessageStream::endmsg;
  }
  **/

  xercesc::MemBufInputSource* memBufInputSource = nullptr;

  try
  {
    xercesc::XercesDOMParser parser;
    parser.setValidationScheme( xercesc::XercesDOMParser::Val_Always );
    parser.setDoNamespaces( true );

    xercesc::HandlerBase errorHandler;
    parser.setErrorHandler( &errorHandler );

    const char* bufferId="InMemoryDocument";
    const char* buffer = cont.c_str();

    memBufInputSource = new xercesc::MemBufInputSource( (const XMLByte*)buffer,strlen(buffer),bufferId,false );

    parser.parse(*memBufInputSource);

    xercesc::DOMDocument* document = parser.getDocument();

    XMLCh tempStr[20];
    xercesc::XMLString::transcode( "connection", tempStr, 19);

    xercesc::DOMNodeList* connectionList = document->getElementsByTagName( tempStr );

    if ( connectionList )
    {
      XMLSize_t numberOfConnections = connectionList->getLength();

      for ( XMLSize_t iConnection = 0; iConnection < numberOfConnections; ++iConnection )
      {
        xercesc::DOMNode* connectionNode = connectionList->item( iConnection );

        if ( connectionNode )
        {
          char*       connectionName  = xercesc::XMLString::transcode( connectionNode->getAttributes()->item( 0 )->getNodeValue() );
          std::string sConnectionName = connectionName;
          xercesc::XMLString::release( &connectionName );

          // Locate the credential
          cond::XMLAuthenticationService::DataSourceEntry* credential = nullptr;
          std::map< std::string, cond::XMLAuthenticationService::DataSourceEntry* >::iterator iConnection = m_data.find( sConnectionName );
          if ( iConnection != m_data.end() ) {
            credential = iConnection->second;
            // Issue a warning here.
            //coral::MessageStream log( this, this->name(),seal::Msg::Verbose );
	    log<<coral::Debug<<"Credential parameters for connection string \""
	      << sConnectionName
		     << "\" have already been defined. Only new elements are appended, while existing will be ignored."
		     << coral::MessageStream::endmsg;
          } else {
            credential = new cond::XMLAuthenticationService::DataSourceEntry( this->name(), sConnectionName );
            m_data.insert( std::make_pair( sConnectionName, credential ) );
          }

          xercesc::DOMNodeList* parameterList = connectionNode->getChildNodes();

          if ( parameterList )
	    {
            XMLSize_t numberOfParameters = parameterList->getLength();

            for ( XMLSize_t iParameter = 0; iParameter < numberOfParameters; ++iParameter )
            {
              xercesc::DOMNode* parameterNode = parameterList->item( iParameter );

              if ( parameterNode && parameterNode->getNodeType() == xercesc::DOMNode::ELEMENT_NODE )
              {
                char* nodeName = xercesc::XMLString::transcode( parameterNode->getNodeName() );
                std::string sNodeName = nodeName;
                xercesc::XMLString::release( &nodeName );

                if ( sNodeName == "parameter" ) { // The default parameters
                  char* parameterName = xercesc::XMLString::transcode( parameterNode->getAttributes()->item( 0 )->getNodeValue() );
                  std::string sParameterName = parameterName;
                  xercesc::XMLString::release( &parameterName );
                  char* parameterValue = xercesc::XMLString::transcode( parameterNode->getAttributes()->item( 1 )->getNodeValue() );
                  std::string sParameterValue = parameterValue;
                  xercesc::XMLString::release( &parameterValue );

                  credential->appendCredentialItem( sParameterName, sParameterValue );
                }
                else if ( sNodeName == "role" ) { // A role
                  char* roleName  = xercesc::XMLString::transcode( parameterNode->getAttributes()->item( 0 )->getNodeValue() );
                  std::string sRoleName = roleName;
                  xercesc::XMLString::release( &roleName );

                  // Retrieve the parameters for the role
                  xercesc::DOMNodeList* roleParameterList = parameterNode->getChildNodes();

                  if ( roleParameterList )
                  {
                    XMLSize_t numberOfRoleParameters = roleParameterList->getLength();

                    for ( XMLSize_t iRoleParameter = 0; iRoleParameter < numberOfRoleParameters; ++iRoleParameter )
                    {
                      xercesc::DOMNode* roleParameterNode = roleParameterList->item( iRoleParameter );
                      if ( roleParameterNode && roleParameterNode->getNodeType() == xercesc::DOMNode::ELEMENT_NODE )
                      {
                        char* roleNodeName = xercesc::XMLString::transcode( roleParameterNode->getNodeName() );
                        std::string sRoleNodeName = roleNodeName;
                        xercesc::XMLString::release( &roleNodeName );

                        if ( sRoleNodeName == "parameter" ) {
                          char* roleParameterName = xercesc::XMLString::transcode( roleParameterNode->getAttributes()->item( 0 )->getNodeValue() );
                          std::string sRoleParameterName = roleParameterName;
                          xercesc::XMLString::release( &roleParameterName );
                          char* roleParameterValue = xercesc::XMLString::transcode( roleParameterNode->getAttributes()->item( 1 )->getNodeValue() );
                          std::string sRoleParameterValue = roleParameterValue;
                          xercesc::XMLString::release( &roleParameterValue );

                          credential->appendCredentialItemForRole( sRoleParameterName, sRoleParameterValue, sRoleName );
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    parser.reset();
  }
  catch ( const xercesc::XMLException& toCatch )
  {
    char* message = xercesc::XMLString::transcode( toCatch.getMessage() );
    //coral::MessageStream log( this, this->name(),coral::Msg::Verbose );
    //log << coral::Msg::Error << message << coral::flush;
    log<<coral::Error<<std::string(message)<<coral::MessageStream::endmsg;
    xercesc::XMLString::release( &message );
    result = false;
  }
  catch ( const xercesc::DOMException& toCatch )
  {
    char* message = xercesc::XMLString::transcode( toCatch.msg );
    //seal::MessageStream log( this, this->name(),seal::Msg::Verbose );
    //log << seal::Msg::Error << message << seal::flush;
    log<<coral::Error<<std::string(message)<<coral::MessageStream::endmsg;
    xercesc::XMLString::release( &message );
    result = false;
  }
  catch ( const xercesc::SAXException& toCatch )
  {
    char* message = xercesc::XMLString::transcode( toCatch.getMessage() );
    //seal::MessageStream log( this, this->name(),seal::Msg::Verbose );
    //log << seal::Msg::Error << message << seal::flush;
    log<<coral::Error<<std::string(message)<<coral::MessageStream::endmsg;
    xercesc::XMLString::release( &message );
    result = false;
  }
  catch (...){
    //seal::MessageStream log( this, this->name(),seal::Msg::Verbose );
    //log << seal::Msg::Error << "Unexpected Exception parsing file \"" << inputFileName << "\"" << seal::flush;
    log<<coral::Error<<"Unexpected Exception parsing file \"" << inputFileName << "\"" <<coral::MessageStream::endmsg;
    result = false;
  }
  if(memBufInputSource) delete memBufInputSource;
  return result;
}

bool
cond::XMLAuthenticationService::XMLAuthenticationService::initialize()
{
  coral::MessageStream log("cond::XMLAuthenticationService::initialize");
  std::set< std::string > inputFileNames = this->verifyFileName();
  if ( inputFileNames.empty() )
  {
    //seal::MessageStream log( this, this->name(),seal::Msg::Verbose );
    //std::cout<< "Could not open \"" << m_inputFileName << "\" for reading" << std::endl;
    log<<coral::Debug<<"Could not open \"" << m_inputFileName << "\" for reading" <<coral::MessageStream::endmsg;
    return false;
  }

  try
  {
    cms::concurrency::xercesInitialize();
  }
  catch ( const xercesc::XMLException& toCatch )
  {
    char* message = xercesc::XMLString::transcode( toCatch.getMessage() );
    //seal::MessageStream log( this, this->name(),seal::Msg::Verbose );
    //log << seal::Msg::Error << message << seal::flush;
    log<<coral::Error<<std::string(message)<<coral::MessageStream::endmsg;
    xercesc::XMLString::release( &message );
    return false;
  }

  bool result = false;
  for ( std::set< std::string >::const_reverse_iterator iFileName = inputFileNames.rbegin();
        iFileName != inputFileNames.rend(); ++iFileName ) {
    if ( this->processFile( *iFileName ) ) {
      result = true;
    }
  }

  cms::concurrency::xercesTerminate();

  m_isInitialized = result;
  if(!m_isInitialized) reset();
  return result;
}

void cond::XMLAuthenticationService::XMLAuthenticationService::reset(){
  for ( std::map< std::string, cond::XMLAuthenticationService::DataSourceEntry* >::iterator iConnection = m_data.begin();
        iConnection != m_data.end(); ++iConnection ) delete iConnection->second;
  m_data.clear();
  m_isInitialized = false;
}

const coral::IAuthenticationCredentials&
cond::XMLAuthenticationService::XMLAuthenticationService::credentials( const std::string& connectionString ) const
{
  boost::mutex::scoped_lock lock(m_mutexLock);
  if ( ! m_isInitialized ) {
    const_cast< cond::XMLAuthenticationService::XMLAuthenticationService* >( this )->initialize();
  }
  std::map< std::string, cond::XMLAuthenticationService::DataSourceEntry* >::const_iterator iConnection = m_data.find( connectionString );
  if ( iConnection == m_data.end() )
    throw coral::UnknownConnectionException( this->name(), connectionString );
  return iConnection->second->credentials();
}

const coral::IAuthenticationCredentials&
cond::XMLAuthenticationService::XMLAuthenticationService::credentials( const std::string& connectionString,
                                                                       const std::string& role ) const
{
  boost::mutex::scoped_lock lock(m_mutexLock);
  if ( ! m_isInitialized ) {
    const_cast< cond::XMLAuthenticationService::XMLAuthenticationService* >( this )->initialize();
  }
  std::map< std::string, cond::XMLAuthenticationService::DataSourceEntry* >::const_iterator iConnection = m_data.find( connectionString );
  if ( iConnection == m_data.end() )
    throw coral::UnknownConnectionException( this->name(), connectionString );
  return iConnection->second->credentials( role );
}

std::set< std::string >
cond::XMLAuthenticationService::XMLAuthenticationService::verifyFileName()
{
  coral::MessageStream log("cond::XMLAuthenticationService::verifyFileName");
  std::set< std::string > fileNames;

  // Try the file name as is...
  boost::filesystem::path filePath( m_inputFileName );
  if ( boost::filesystem::exists( m_inputFileName ) ) {
    if(boost::filesystem::is_directory( m_inputFileName )){
      //seal::MessageStream log( this, this->name(),seal::Msg::Verbose );
      log <<coral::Error << "Provided path \"" << m_inputFileName << "\" is a directory." <<coral::MessageStream::endmsg;
      return fileNames;
    }
    boost::filesystem::path& fullPath = filePath.normalize();
    fileNames.insert( fullPath.string() );
    if(filePath.is_complete()) return fileNames;
  }

  // Try to find other files in the path variable
  const char* thePathVariable = ::getenv( "CORAL_AUTH_PATH" );
  if ( ! thePathVariable ) return fileNames;
  log<<coral::Debug<< "File \"" << m_inputFileName << "\" not found in the current directory. Trying in the search path." <<coral::MessageStream::endmsg;

  std::string searchPath(thePathVariable);
  //std::cout<<"searchPath "<<searchPath<<std::endl;
  if(boost::filesystem::exists(searchPath)){
    if(!boost::filesystem::is_directory( searchPath )){
      log<<coral::Debug<<"Search path \"" << searchPath << "\" is not a directory."<<coral::MessageStream::endmsg;
      return fileNames;
    }
    boost::filesystem::path fullPath( searchPath );
    fullPath /= filePath;
    fileNames.insert( fullPath.string() );
  } else {
    log<<coral::Debug<<"Search path \"" << searchPath << "\" does not exist."<<coral::MessageStream::endmsg;
    return fileNames;
  }

  return fileNames;
}

DEFINE_CORALSERVICE(cond::XMLAuthenticationService::XMLAuthenticationService,"COND/Services/XMLAuthenticationService");

ext: cc

max_stars_repo_name: nistefan/cmssw

max_issues_repo_name: nistefan/cmssw

max_forks_repo_name: nistefan/cmssw


text:
//============================================================================
// Name        : OctoROACH_Framework.cpp
// Author      : Luis Valbuena
// Version     :
// Copyright   : Marhes laboratory UNM
// Description : OctoROACH Framework.
//============================================================================

#include "vicon_pos.h"
#include "stdlib.h"
#include "Client.h"
#include "librerialuis.h"
#include "math.h"

#include <boost/python.hpp>
using namespace boost::python;

using namespace std;

//#define ROBOTIP  "localhost"
//#define ROBOTPORT 6665

struct cpluspluscode_Wrap4Python
{
	cpluspluscode_Wrap4Python()
	{
		a_11= -0.019709753875392;
		a_21= -0.015173074449847;
		a_31= -0.999690603843965;
		a_12= -0.861839978997550;
		a_22= -0.506579426897183;
		a_32=  0.024680657325591;
		a_13= -0.506797174620847;
		a_23=  0.862059778702301;
		a_33= -0.003092206342704;

		std::string Models[4];
		std::string temp;

		temp="OctoROACH";
		Models[0]=temp;

		temp="OctoROACH2";
		Models[1]=temp;

		temp="quadrotor_2b";
		Models[2]=temp;

		temp="quadrotor_3";
		Models[3]=temp;

		//v = new vicon_pos("OctoROACH","OctoROACH");
		v = new vicon_pos();
		v->update();
		indexx_OCTO=v->find_sub("OctoROACH");
		indexx_OCTO2=v->find_sub("OctoROACH2");
	 	indexx_Quad1=v->find_sub("quadrotor_2b");
	 	indexx_Quad2=v->find_sub("quadrotor_3");
		cout << "Index OctoROACH = " << indexx_OCTO <<", "<< "Index OctoROACH2 = "<< indexx_OCTO2 <<", "<< "Index quad 1 = "<< indexx_Quad1 <<", "<< "Index quad 2 = "<< indexx_Quad2 <<", "  <<"\n";
	}
	void retrievePositioning()
	{

		float s_euler_x,c_euler_x,s_euler_y,c_euler_y,s_euler_z,c_euler_z;
		float r_11,r_12,r_13,r_21,r_22,r_23,r_31,r_32,r_33;
		float euler_x,euler_y,euler_z;
		float tempx,tempy;

		//cout << "index = " << indexx << " \n";

		v->update();

///////////////////////OCTOROACH_ONE////////////////////
		v->get_subject_marker(indexx_OCTO,"Origin",tempx,tempy,pos_z_octo1);
		v->get_subject_euler_xyz(indexx_OCTO,euler_x,euler_y,euler_z);

		s_euler_x=sin(euler_x);
		c_euler_x=cos(euler_x);
		s_euler_y=sin(euler_y);
		c_euler_y=cos(euler_y);
		s_euler_z=sin(euler_z);
		c_euler_z=cos(euler_z);

		r_11=c_euler_y*c_euler_z;
		r_12=-c_euler_y*s_euler_z;
		r_13=s_euler_y;
		r_21=c_euler_x*s_euler_z + c_euler_z*s_euler_x*s_euler_y;
		r_22=c_euler_x*c_euler_z - s_euler_x*s_euler_y*s_euler_z;
		r_23=-c_euler_y*s_euler_x;
		r_31=s_euler_x*s_euler_z - c_euler_x*c_euler_z*s_euler_y;
		r_32=c_euler_z*s_euler_x + c_euler_x*s_euler_y*s_euler_z;
		r_33=c_euler_x*c_euler_y;

		alpha_octo1=-atan2Mia(a_13*r_21 + a_23*r_22 + a_33*r_23,a_13*r_31 + a_23*r_32 + a_33*r_33);
		betha_octo1= asin( a_13*r_11 + a_23*r_12 + a_33*r_13 );
		theta_octo1=-atan2Mia(a_12*r_11 + a_22*r_12 + a_32*r_13,a_11*r_11 + a_21*r_12 + a_31*r_13);

		//Fixing origin offset
		pos_x_octo1 = (76.2*cos(theta_octo1)) + (20.3*sin(theta_octo1)) + tempx;
		pos_y_octo1 = (76.2*sin(theta_octo1)) + (-20.3*cos(theta_octo1)) + tempy;

	//cout << "position Octo 1= [" << pos_x_octo1<<" "<<pos_y_octo1<<" "<<pos_z_octo1 <<"]"<< "   orientation = ["<<(180/PI)*alpha_octo1<<" "<< (180/PI)*betha_octo1<<" "<< (180/PI)*theta_octo1 <<"]"  <<"\n";
///////////////////////OCTOROACH_ONE////////////////////

///////////////////////OCTOROACH_TWO////////////////////
		v->get_subject_marker(indexx_OCTO2,"Origin",tempx,tempy,pos_z_octo2);
		v->get_subject_euler_xyz(indexx_OCTO2,euler_x,euler_y,euler_z);

		s_euler_x=sin(euler_x);
		c_euler_x=cos(euler_x);
		s_euler_y=sin(euler_y);
		c_euler_y=cos(euler_y);
		s_euler_z=sin(euler_z);
		c_euler_z=cos(euler_z);

		r_11=c_euler_y*c_euler_z;
		r_12=-c_euler_y*s_euler_z;
		r_13=s_euler_y;
		r_21=c_euler_x*s_euler_z + c_euler_z*s_euler_x*s_euler_y;
		r_22=c_euler_x*c_euler_z - s_euler_x*s_euler_y*s_euler_z;
		r_23=-c_euler_y*s_euler_x;
		r_31=s_euler_x*s_euler_z - c_euler_x*c_euler_z*s_euler_y;
		r_32=c_euler_z*s_euler_x + c_euler_x*s_euler_y*s_euler_z;
		r_33=c_euler_x*c_euler_y;

		alpha_octo2=-atan2Mia(a_13*r_21 + a_23*r_22 + a_33*r_23,a_13*r_31 + a_23*r_32 + a_33*r_33);
		betha_octo2= asin( a_13*r_11 + a_23*r_12 + a_33*r_13 );
		theta_octo2=-atan2Mia(a_12*r_11 + a_22*r_12 + a_32*r_13,a_11*r_11 + a_21*r_12 + a_31*r_13);

		//Fixing origin offset
		pos_x_octo2 = (76.2*cos(theta_octo2)) + (20.3*sin(theta_octo2)) + tempx;
		pos_y_octo2 = (76.2*sin(theta_octo2)) + (-20.3*cos(theta_octo2)) + tempy;

	//cout << "position Octo 2= [" << pos_x_octo2<<" "<<pos_y_octo2<<" "<<pos_z_octo2 <<"]"<< "   orientation = ["<<(180/PI)*alpha_octo2<<" "<< (180/PI)*betha_octo2<<" "<< (180/PI)*theta_octo2 <<"]"  <<"\n";
///////////////////////OCTOROACH_TWO////////////////////

///////////////////////QUAD_ONE////////////////////
		v->get_subject_marker(indexx_Quad1,"CoG",pos_x_quad1,pos_y_quad1,pos_z_quad1);
		v->get_subject_euler_xyz(indexx_Quad1,alpha_quad1,betha_quad1,theta_quad1);

	//cout << "position Quad 1= [" << pos_x_quad1<<" "<<pos_y_quad1<<" "<<pos_z_quad1<<"]"<< "   orientation = ["<<(180/PI)*alpha_quad1<<" "<< (180/PI)*betha_quad1<<" "<< (180/PI)*theta_quad1<<"]"  <<"\n";
///////////////////////QUAD_ONE////////////////////

///////////////////////QUAD_TWO////////////////////
		v->get_subject_marker(indexx_Quad2,"CoG",pos_x_quad2,pos_y_quad2,pos_z_quad2);
		v->get_subject_euler_xyz(indexx_Quad2,alpha_quad2,betha_quad2,theta_quad2);

	//cout << "position Quad 2= [" << pos_x_quad2<<" "<<pos_y_quad2<<" "<<pos_z_quad2<<"]"<< "   orientation = ["<<(180/PI)*alpha_quad2<<" "<< (180/PI)*betha_quad2<<" "<< (180/PI)*theta_quad2<<"]"  <<"\n";
///////////////////////QUAD_TWO////////////////////
	}
	double octo1_return_pos_x(){return double(pos_x_octo1);}
	double octo1_return_pos_y(){return double(pos_y_octo1);}
	double octo1_return_pos_z(){return double(pos_z_octo1);}
	double octo1_return_orientation_alpha(){return double(alpha_octo1);}
	double octo1_return_orientation_betha(){return double(betha_octo1);}
	double octo1_return_orientation_theta(){return theta_octo1;}

	double octo2_return_pos_x(){return double(pos_x_octo2);}
	double octo2_return_pos_y(){return double(pos_y_octo2);}
	double octo2_return_pos_z(){return double(pos_z_octo2);}
	double octo2_return_orientation_alpha(){return double(alpha_octo2);}
	double octo2_return_orientation_betha(){return double(betha_octo2);}
	double octo2_return_orientation_theta(){return theta_octo2;}

	double quad1_return_pos_x(){return double(pos_x_quad1);}
	double quad1_return_pos_y(){return double(pos_y_quad1);}
	double quad1_return_pos_z(){return double(pos_z_quad1);}
	double quad1_return_orientation_alpha(){return double(alpha_quad1);}
	double quad1_return_orientation_betha(){return double(betha_quad1);}
	double quad1_return_orientation_theta(){return theta_quad1;}

	double quad2_return_pos_x(){return double(pos_x_quad2);}
	double quad2_return_pos_y(){return double(pos_y_quad2);}
	double quad2_return_pos_z(){return double(pos_z_quad2);}
	double quad2_return_orientation_alpha(){return double(alpha_quad2);}
	double quad2_return_orientation_betha(){return double(betha_quad2);}
	double quad2_return_orientation_theta(){return theta_quad2;}

	float a_11,a_12,a_13,a_21,a_22,a_23,a_31,a_32,a_33;
	float pos_x_octo1,pos_y_octo1,pos_z_octo1;
	float alpha_octo1,betha_octo1,theta_octo1;

	float pos_x_octo2,pos_y_octo2,pos_z_octo2;
	float alpha_octo2,betha_octo2,theta_octo2;

	float pos_x_quad1,pos_y_quad1,pos_z_quad1;
	float alpha_quad1,betha_quad1,theta_quad1;

	float pos_x_quad2,pos_y_quad2,pos_z_quad2;
	float alpha_quad2,betha_quad2,theta_quad2;

	int indexx_OCTO;
	int indexx_OCTO2;
	int indexx_Quad1;
	int indexx_Quad2;

	vicon_pos* v;
};

BOOST_PYTHON_MODULE(cpluspluscode_Wrap4Python_ext)
{
	class_<cpluspluscode_Wrap4Python>("cpluspluscode_Wrap4Python", init<>())
			.def("retrievePositioning", &cpluspluscode_Wrap4Python::retrievePositioning)
			.def("octo1_return_pos_x",&cpluspluscode_Wrap4Python::octo1_return_pos_x)
			.def("octo1_return_pos_y",&cpluspluscode_Wrap4Python::octo1_return_pos_y)
			.def("octo1_return_pos_z",&cpluspluscode_Wrap4Python::octo1_return_pos_z)
			.def("octo1_return_orientation_alpha",&cpluspluscode_Wrap4Python::octo1_return_orientation_alpha)
			.def("octo1_return_orientation_betha",&cpluspluscode_Wrap4Python::octo1_return_orientation_betha)
			.def("octo1_return_orientation_theta",&cpluspluscode_Wrap4Python::octo1_return_orientation_theta)
			.def("octo2_return_pos_x",&cpluspluscode_Wrap4Python::octo2_return_pos_x)
			.def("octo2_return_pos_y",&cpluspluscode_Wrap4Python::octo2_return_pos_y)
			.def("octo2_return_pos_z",&cpluspluscode_Wrap4Python::octo2_return_pos_z)
			.def("octo2_return_orientation_alpha",&cpluspluscode_Wrap4Python::octo2_return_orientation_alpha)
			.def("octo2_return_orientation_betha",&cpluspluscode_Wrap4Python::octo2_return_orientation_betha)
			.def("octo2_return_orientation_theta",&cpluspluscode_Wrap4Python::octo2_return_orientation_theta)
			.def("quad1_return_pos_x",&cpluspluscode_Wrap4Python::quad1_return_pos_x)
			.def("quad1_return_pos_y",&cpluspluscode_Wrap4Python::quad1_return_pos_y)
			.def("quad1_return_pos_z",&cpluspluscode_Wrap4Python::quad1_return_pos_z)
			.def("quad1_return_orientation_alpha",&cpluspluscode_Wrap4Python::quad1_return_orientation_alpha)
			.def("quad1_return_orientation_betha",&cpluspluscode_Wrap4Python::quad1_return_orientation_betha)
			.def("quad1_return_orientation_theta",&cpluspluscode_Wrap4Python::quad1_return_orientation_theta)
			.def("quad2_return_pos_x",&cpluspluscode_Wrap4Python::quad2_return_pos_x)
			.def("quad2_return_pos_y",&cpluspluscode_Wrap4Python::quad2_return_pos_y)
			.def("quad2_return_pos_z",&cpluspluscode_Wrap4Python::quad2_return_pos_z)
			.def("quad2_return_orientation_alpha",&cpluspluscode_Wrap4Python::quad2_return_orientation_alpha)
			.def("quad2_return_orientation_betha",&cpluspluscode_Wrap4Python::quad2_return_orientation_betha)
			.def("quad2_return_orientation_theta",&cpluspluscode_Wrap4Python::quad2_return_orientation_theta)
	;
}
/*
int main(){

	float s_euler_x,c_euler_x,s_euler_y,c_euler_y,s_euler_z,c_euler_z;
	float a_11,a_12,a_13,a_21,a_22,a_23,a_31,a_32,a_33;
	float r_11,r_12,r_13,r_21,r_22,r_23,r_31,r_32,r_33;

	float alpha,betha,theta;

	a_11= -0.019709753875392;
	a_21= -0.015173074449847;
	a_31= -0.999690603843965;
	a_12= -0.861839978997550;
	a_22= -0.506579426897183;
	a_32=  0.024680657325591;
	a_13= -0.506797174620847;
	a_23=  0.862059778702301;
	a_33= -0.003092206342704;

	int a=0, indexx;

	float pos_x,pos_y,pos_z,euler_x,euler_y,euler_z;

	vicon_pos* v = new vicon_pos("OctoROACH","OctoROACH");
	v->update();

	indexx=v->find_sub("OctoROACH");
	cout << "index = " << indexx << " \n";

	for(a=0;a<500;a++)
	{
		v->update();

		//v->get_subject_coord(indexx,pos_x,pos_y,pos_z);

		v->get_subject_marker(indexx,"Origin",pos_x,pos_y,pos_z);
		v->get_subject_euler_xyz(indexx,euler_x,euler_y,euler_z);

		s_euler_x=sin(euler_x);
		c_euler_x=cos(euler_x);
		s_euler_y=sin(euler_y);
		c_euler_y=cos(euler_y);
		s_euler_z=sin(euler_z);
		c_euler_z=cos(euler_z);

		r_11=c_euler_y*c_euler_z;
		r_12=-c_euler_y*s_euler_z;
		r_13=s_euler_y;
		r_21=c_euler_x*s_euler_z + c_euler_z*s_euler_x*s_euler_y;
		r_22=c_euler_x*c_euler_z - s_euler_x*s_euler_y*s_euler_z;
		r_23=-c_euler_y*s_euler_x;
		r_31=s_euler_x*s_euler_z - c_euler_x*c_euler_z*s_euler_y;
		r_32=c_euler_z*s_euler_x + c_euler_x*s_euler_y*s_euler_z;
		r_33=c_euler_x*c_euler_y;

		alpha=-atan2Mia(a_13*r_21 + a_23*r_22 + a_33*r_23,a_13*r_31 + a_23*r_32 + a_33*r_33);
		betha= asin( a_13*r_11 + a_23*r_12 + a_33*r_13 );
		theta=-atan2Mia(a_12*r_11 + a_22*r_12 + a_32*r_13,a_11*r_11 + a_21*r_12 + a_31*r_13);

		cout << "position = [" << pos_x<<" "<<pos_y<<" "<<pos_z <<"]"<< "   orientation("<< 1+a<<",:) = ["<<(180/PI)*alpha<<" "<< (180/PI)*betha<<" "<< (180/PI)*theta <<"]"  <<"\n";
	//	cout <<"orientation("<< 1+a<<",:) = ["<< euler_x<<" "<<euler_y<<" "<<euler_z <<"]"  <<"\n";
	}

	return 0;
}
*/

max_stars_repo_name: valbuenaster/OctoRoach

max_issues_repo_name: valbuenaster/OctoRoach

max_forks_repo_name: valbuenaster/OctoRoach