text:
#ifndef EDBA_ROWSET_HPP
#define EDBA_ROWSET_HPP

#include <edba/backend/interfaces.hpp>

#include <boost/logic/tribool.hpp>

namespace edba {

namespace detail {
    template<typename T>
    struct value_holder { T value_; };
}

class row;
template<typename Row> class rowset_iterator;
template<typename Row> class rowset;

/// Represent single row in row set.
class row
{
    template<typename T> friend class rowset_iterator;
    template<typename T> friend class rowset;

    // Row doesn`t support construction by user, only by rowset
    row(const backend::connection_ptr& conn
      , const backend::statement_ptr& stmt
      , const backend::result_ptr& res
      )
      : res_(res)
      , stmt_(stmt)
      , conn_(conn)
      , current_col_(0)
    {
    }

public:
    ///
    /// Return true if the column number \a col (starting from 0) has NULL value
    ///
    bool is_null(int col) const
    {
        return res_->is_null(col);
    }

    ///
    /// Return true if the column named \a n has NULL value
    ///
    bool is_null(const string_ref& n) const
    {
        int c = res_->name_to_column(n);
        if (c < 0)
            throw invalid_column(std::string(n.begin(), n.end()));

        res_->is_null(c);
    }

    ///
    /// Reset current column index to 0
    ///
    void rewind_column() const
    {
        current_col_ = 0;
    }

    ///
    /// Fetch a value from column \a col (starting from 0) into \a v. Returns false
    /// if the value in NULL and \a v is not updated, otherwise returns true.
    ///
    /// If the data type is not same it tries to cast the data, if casting fails or the
    /// data is out of the type range, throws bad_value_cast().
    ///
    bool fetch(int col, const fetch_types_variant& v) const
    {
        return res_->fetch(col, v);
    }

    ///
    /// Fetch a value from column \a col (starting from 0) into \a v. Returns false
    /// if the value in NULL and \a v is not updated, otherwise returns true.
    ///
    /// If the data type is not same it tries to cast the data, if casting fails or the
    /// data is out of the type range, throws bad_value_cast().
    ///
    template<typename T>
    bool fetch(int col, T& v) const
    {
        return fetch_conversion<T>::fetch(*this, col, v);
    }

    ///
    /// Fetch a value from column named \a n into \a v. Returns false
    /// if the value in NULL and \a v is not updated, otherwise returns true.
    ///
    /// If the data type is not same it tries to cast the data, if casting fails or the
    /// data is out of the type range, throws bad_value_cast().
    ///
    /// If the \a n value is invalid throws invalid_column exception
    ///
    template<typename T>
    bool fetch(const string_ref& n, T& v) const
    {
        int c = res_->name_to_column(n);
        if (c < 0)
            throw invalid_column(std::string(n.begin(), n.end()));
        return fetch(c, v);
    }

    ///
    /// Fetch a value from the next column in the row starting from the first one. Returns false
    /// if the value in NULL and \a v is not updated, otherwise returns true.
    ///
    /// If the data type is not same it tries to cast the data, if casting fails or the
    /// data is out of the type range, throws bad_value_cast().
    ///
    /// If fetch was called more times then cols() it throws invalid_column exception, to use
    /// it once again from the beginning on the same row call rewind_column() member function.
    /// It is not required to call rewind_column() after calling next() as column index is reset
    /// automatically.
    ///
    template<typename T>
    bool fetch(T& v) const
    {
        int old_current_col = current_col_;
        bool res = fetch(current_col_, v);
        if (old_current_col == current_col_)
            ++current_col_;

        return res;
    }

    ///
    /// Get a value of type \a T from column named \a name (starting from 0). If the column
    /// is null throws null_value_fetch(), if the column \a name is invalid throws invalid_column,
    /// if the column value cannot be converted to type T (see fetch functions) it throws bad_value_cast.
    ///
    template<typename T>
    T get(const string_ref& name) const
    {
        T v = T();
        get(name, v);
        return v;
    }

    ///
    /// Get a value of type \a T from column named \a name (starting from 0). If the column
    /// is null throws null_value_fetch(), if the column \a name is invalid throws invalid_column,
    /// if the column value cannot be converted to type T (see fetch functions) it throws bad_value_cast.
    ///
    template<typename T>
    void get(const string_ref& name, T& value) const
    {
        if(!fetch(name, value))
            throw null_value_fetch(std::string(name.begin(), name.end()));
    }

    ///
    /// Get a value of type \a T from column \a col (starting from 0). If the column
    /// is null throws null_value_fetch(), if the column index is invalid throws invalid_column,
    /// if the column value cannot be converted to type T (see fetch functions) it throws bad_value_cast.
    ///
    template<typename T>
    T get(int col) const
    {
        T v = T();
        get(col, v);
        return v;
    }

    ///
    /// Get a value of type \a T from column \a col (starting from 0). If the column
    /// is null throws null_value_fetch(), if the column index is invalid throws invalid_column,
    /// if the column value cannot be converted to type T (see fetch functions) it throws bad_value_cast.
    ///
    template<typename T>
    void get(int col, T& value) const
    {
        if(!fetch(col, value))
            throw null_value_fetch(res_->column_to_name(col));
    }

    ///
    /// Get a value of type \a T from next column. If the column
    /// is null throws null_value_fetch(), if the column index is invalid throws invalid_column,
    /// if the column value cannot be converted to type T (see fetch functions) it throws bad_value_cast.
    ///
    template<typename T>
    T get() const
    {
        T v = T();
        get(v);
        return v;
    }

    ///
    /// Get a value of type \a T from next column. If the column
    /// is null throws null_value_fetch(), if the column index is invalid throws invalid_column,
    /// if the column value cannot be converted to type T (see fetch functions) it throws bad_value_cast.
    ///
    template<typename T>
    void get(T& value) const
    {
        if(!fetch(value))
            throw null_value_fetch(res_->column_to_name(current_col_ - 1));
    }

private:
    // Note that order of members is not random.
    // It is very important to destroy result set then statement then connection

    backend::connection_ptr conn_;
    backend::statement_ptr stmt_;
    backend::result_ptr res_;
    mutable int current_col_;
};

// -------- free functions related to row ---------

///
/// \brief Fetch value by column name
///
template<typename T>
detail::tag<string_ref, T&> into(const string_ref& name, T& v)
{
    return detail::tag<string_ref, T&>(name, v);
}

///
/// \brief Fetch value by index (starting from 0)
///
template<typename T>
detail::tag<int, T&> into(int index, T& v)
{
    return detail::tag<int, T&>(index, v);
}

///
/// Syntactic sugar, used together with into() function.
///
template<typename T1, typename T2>
const row& operator>>(const row& r, detail::tag<T1, T2> tag)
{
    r.get(tag.first_, tag.second_);
    return r;
}

///
/// Syntactic sugar, same as
/// \code
/// v = row.get();
/// \endcode
template<typename T>
const row& operator>>(const row& r, T& v)
{
    r.get(v);;
    return r;
}

///
/// Iterator over rows in rowset.
///
template<typename T>
class rowset_iterator
  : public boost::iterator_facade<
        rowset_iterator<T>
      , T
      , boost::single_pass_traversal_tag
      >
{
    typedef boost::iterator_facade<
        rowset_iterator<T>
      , T
      , boost::single_pass_traversal_tag
      > base_type;

    typedef typename boost::remove_cv<T>::type mutable_value_type;
    typedef mutable_value_type& mutable_reference;

    typedef rowset<mutable_value_type> mutable_rowset_type;

    // Type of rowset passed into constructor and stored in iterator
    typedef typename boost::mpl::if_<
        boost::is_const<T>
      , const mutable_rowset_type
      , mutable_rowset_type
      >::type rowset_type;

    template<typename> friend class rowset_iterator;

public:
    typedef typename base_type::reference reference;

    rowset_iterator(rowset_type* rs = 0)
      : rs_(rs)
    {
        increment();
    }

    ///
    /// Copy construction and conversion from mutable to const iterator
    ///
    template<typename T1>
    rowset_iterator(rowset_iterator<T1> other, typename boost::enable_if< boost::is_convertible<T1*, T*> >::type* = 0)
      : rs_(other.rs_)
    {
    }

    boost::tribool has_next() const
    {
        backend::result_iface::next_row nr = rs_->row_.res_->has_next();
        if (backend::result_iface::next_row_exists == nr)
            return true;
        else if (backend::result_iface::last_row_reached == nr)
            return false;
        else
            return boost::tribool();
    }

private:
    friend class boost::iterator_core_access;

    reference dereference() const
    {
        BOOST_ASSERT(rs_ && "Attempt to dereference end rowset_iterator");
        return static_cast<T&>(rs_->value_);
    }

    void increment()
    {
        if (!rs_)
            return;

        if (rs_->row_.res_->next())
        {
            rs_->row_.rewind_column();
            if (!fetch_conversion<mutable_value_type>::fetch(rs_->row_, 0, const_cast<mutable_reference>(rs_->value_)))
                throw null_value_fetch(rs_->row_.res_->column_to_name(0));
        }
        else
            rs_ = 0;
    }

    bool equal(rowset_iterator const& other) const
    {
        return rs_ == other.rs_;
    }

    rowset_type* rs_;
};

///
/// Represent select query result set. Implements SinglePassRange concept. rowset can be iterated only once.
/// That means when begin has been called once, all subsequent calls to begin will give undefined behavior.
///
template<typename T = row>
class rowset : private boost::mpl::if_<boost::is_same<T, row>, null_type, detail::value_holder<T> >::type
{
    template<typename T1> friend class rowset_iterator;

public:
    typedef rowset_iterator<T> iterator;
    typedef rowset_iterator<T const> const_iterator;

    ///
    /// Construct rowset from backend result
    ///
    rowset(
        const backend::connection_ptr& conn
      , const backend::statement_ptr& stmt
      , const backend::result_ptr& res
      )
      : row_(conn, stmt, res)
      , opened_(false)
    {
    }

    ///
    /// Open rowset for traversion and return begin iterator
    ///
    iterator begin()
    {
        if (opened_)
            throw multiple_rowset_traverse("attempt to open rowset_iterator twice");

        iterator iter(this);
        opened_ = true;
        return iter;
    }

    ///
    /// Open rowset for traversion and return begin iterator
    ///
    const_iterator begin() const
    {
        if (opened_)
            throw multiple_rowset_traverse("attempt to open rowset_iterator twice");

        const_iterator iter(this);
        opened_ = true;
        return iter;
    }

    ///
    /// Return end iterator for rowset
    ///
    iterator end()
    {
        return iterator();
    }

    ///
    /// Return end iterator for rowset
    ///
    const_iterator end() const
    {
        return const_iterator();
    }

    ///
    /// Provide conversion between rowset`s of different types.
    ///
    template<typename T1>
    operator rowset<T1>() const
    {
        return rowset<T1>(row_.conn_, row_.stmt_, row_.res_);
    }

    ///
    /// Return total number of rows in rowset, or -1 if backend doesn`t provide this information
    ///
    boost::uint64_t rows() const
    {
        return row_.res_->rows();
    }

    ///
    /// Return number of columns in rowset
    ///
    int columns() const
    {
        return row_.res_->cols();
    }

    ///
    /// Get column name by index. Throw invalid_column or error
    ///
    std::string column_name(int col) const
    {
        if (col < 0 || col >= columns())
            throw invalid_column(col);

        return row_.res_->column_to_name(col);
    }

    ///
    /// Get column index by name. Throw invalid_column or error
    ///
    int column_index(const string_ref& n) const
    {
        int c = row_.res_->name_to_column(n);
        if (c < 0)
            throw invalid_column(std::string(n.begin(), n.end()));

        return c;
    }

    ///
    /// Return column index by name or -1 if column with provided name doesn`t exists
    ///
    int find_column(const string_ref& name) const
    {
        int c = row_.res_->name_to_column(name);
        if (c < 0)
            return -1;
        return c;
    }

private:
    row row_;
    mutable bool opened_;                                   //!< User have already called begin method
};

// -------- rowset_iterator<T> implementation ---------

// row_iterator::dereference specialization for row. We should not call fetch, instead we just return stored row object;
template<>
inline rowset_iterator<row>::reference rowset_iterator<row>::dereference() const
{
    BOOST_ASSERT(rs_ && "Attempt to dereference end rowset_iterator");
    return rs_->row_;
}

// row_iterator::dereference specialization for row. We should not call fetch, instead we just return stored row object;
template<>
inline rowset_iterator<const row>::reference rowset_iterator<const row>::dereference() const
{
    BOOST_ASSERT(rs_ && "Attempt to dereference end rowset_iterator");
    return rs_->row_;
}

template<>
inline void rowset_iterator<row>::increment()
{
    if (!rs_)
        return;

    if (rs_->row_.res_->next())
        rs_->row_.rewind_column();
    else
        rs_ = 0;
}

template<>
inline void rowset_iterator<const row>::increment()
{
    if (!rs_)
        return;

    if (rs_->row_.res_->next())
        rs_->row_.rewind_column();
    else
        rs_ = 0;
}

/// Specialization of fetch_conversion for native types.
template<typename T>
struct fetch_conversion<T, typename boost::enable_if< boost::mpl::contains<fetch_types, T*> >::type >
{
    static bool fetch(const row& r, int col, T& v)
    {
        return r.fetch(col, fetch_types_variant(&v));
    }
};

/// Specialization for fetch_conversion for types derived from ostream
template<typename T>
struct fetch_conversion<
    T
  , typename boost::enable_if<
        boost::mpl::and_<
            boost::is_convertible<T*, std::ostream*>
          , boost::mpl::not_< boost::mpl::contains<fetch_types, T*> >
          >
      >::type
  >
{
    static bool fetch(const row& r, int col, T& v)
    {
        return r.fetch(col, fetch_types_variant(&v));
    }
};

}

#endif // EDBA_ROWSET_HPP


text:
#include "stdafx.h"
#include "PackageReferencePattern.h"
#include <JCDT_Lib/internal/util/CharOperation.h>
#include <JCDT_Lib/internal/lookup/PackageSymbol.h>
#include <boost/algorithm/string.hpp>
#include <JCDT_Lib/internal/lookup/TypeSymbol.h>
#include <JCDT_Lib/internal/lookup/Symbol.h>
#include <SearchLib/internal/matching/MatchLocator.h>
#include <SearchLib/internal/matching/MatchSet.h>

namespace Jikes { // Open namespace Jikes block

namespace Search{

	 int PackageReferencePattern::matchLevel(Ast* node , bool resolve)
	{
		 if (!node)
			 return IMPOSSIBLE_MATCH;

		if(node->kind != Ast::NAME)
		{
			return IMPOSSIBLE_MATCH;
		}
		AstName* qNameRef = reinterpret_cast<AstName*>(node);
		if (!resolve) {
			if (pkgName.empty() == true) {
				return _needsResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
			}
			else {
				switch (matchMode) {
				case EXACT_MATCH:
				case PREFIX_MATCH:
				{
					vector<wstring> tokens;
					GetAstNameAllNames(qNameRef, tokens);
					if (CharOperation::prefixEquals(pkgName, boost::join(tokens,L"."), isCaseSensitive)) {
						return _needsResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
					}
					else {
						return IMPOSSIBLE_MATCH;
					}
				}

				case PATTERN_MATCH:
				{
					auto pattern = pkgName[pkgName.length() - 1] == '*' ? pkgName
						: pkgName + L".*"; //$NON-NLS-1$
					vector<wstring> tokens;
					GetAstNameAllNames(qNameRef, tokens);
					if (CharOperation::match(pattern, boost::join(tokens, L"."), isCaseSensitive)) {
						return _needsResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
					}
					else {
						return IMPOSSIBLE_MATCH;
					}
				}

				default:
					return IMPOSSIBLE_MATCH;
				}
			}
		}
		else {
			return matchLevel(qNameRef->symbol);
		}
	}

	int PackageReferencePattern::matchLevel(Symbol* binding)
	{
		if (binding == nullptr) {
			return INACCURATE_MATCH;
		}
		if (binding->_kind == Symbol::PACKAGE ) {
			PackageSymbol* pkgBinding = reinterpret_cast<PackageSymbol*>(binding);
			wstring compoundName = pkgBinding->getNameString();
			boost::replace_all(compoundName, L"/", L".");

			if (matchesName(pkgName, compoundName)) {
				return ACCURATE_MATCH;
			}
			else {
				return IMPOSSIBLE_MATCH;
			}
		}
		else if (binding->_kind == Symbol::TYPE) {

			auto typeBinding = reinterpret_cast<TypeSymbol*>(binding);
			if (typeBinding->IsArray()) {
				typeBinding = typeBinding->base_type;
			}

			if (typeBinding == nullptr) {
				return INACCURATE_MATCH;
			}

			auto pkgBinding = typeBinding->ContainingPackage();
			wstring compoundName = pkgBinding->getNameString();
			boost::replace_all(compoundName, L"/", L".");

			if (matchesName(pkgName, compoundName)) {
				return ACCURATE_MATCH;
			}
			else {
				return IMPOSSIBLE_MATCH;
			}
		}
		else {
			return IMPOSSIBLE_MATCH;
		}
	}
}

} // Close namespace Jikes block

ext: cpp

max_stars_repo_name: kuafuwang/JCDT

max_issues_repo_name: kuafuwang/JCDT

max_forks_repo_name: kuafuwang/JCDT


text:
#pragma once

#include <boost/variant.hpp>
#include <boost/mpl/vector.hpp>

namespace metaSMT {

  namespace SAT {
    namespace tag {

    // sat literal tag
    // 0 is invalid
    // n is variable n
    // -m is variable n negated
    struct lit_tag {
      int id;
      template<typename STREAM>
      friend STREAM & operator<< (STREAM & out, lit_tag const & self)
      {  out << "sat_lit[" << self.id  << "]"; return out; }
      bool operator< (lit_tag const & other) const { return id < other.id; }
      lit_tag operator- () const { lit_tag l = { -id }; return l; }
      int var() const {return id >= 0 ? id: -id; }
    };

    struct c_tag {
      template<typename STREAM>
      friend STREAM & operator<< (STREAM & out, c_tag const & )
      {  out << "or"; return out; }
      bool operator< (c_tag const & ) const { return false; }
    };

    struct not_tag {
      template<typename STREAM>
      friend STREAM & operator<< (STREAM & out, not_tag const & )
      {  out << "not"; return out; }
      bool operator< (not_tag const & ) const { return false; }
    };

      // tag variant SAT
      typedef boost::mpl::vector<
          lit_tag
        , c_tag
      >::type SAT_Tags;

      typedef boost::make_variant_over< SAT_Tags >::type SAT_Tag;

    } // namespace tag
  } // namespace SAT
} // namespace metaSMT

//  vim: ft=cpp:ts=2:sw=2:expandtab

ext: hpp

max_stars_repo_name: voertler/metaSMT

max_issues_repo_name: voertler/metaSMT

max_forks_repo_name: voertler/metaSMT


text:
// property_map.cpp

//----------------------------------------------------------
// Test various types of containers and property maps
// compatible with Point_set_processing_3 package.
//----------------------------------------------------------
// Usage: no parameters

#include <CGAL/Simple_cartesian.h>
#include <CGAL/property_map.h>
#include <CGAL/value_type_traits.h>

#include <algorithm>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_io.hpp>

typedef CGAL::Simple_cartesian<double> K;
typedef K::Point_3 Point_3;
typedef K::Vector_3 Vector_3;

// Point with normal vector stored in a std::pair.
typedef std::pair<Point_3, Vector_3> PointVectorPair;

// Data type = index, followed by the point, followed by a boolean
// that tells us whether the normal is oriented or not, followed by the normal vector.
typedef boost::tuple<int, Point_3, bool, Vector_3> IndexedPointWithOrientableNormalTuple;

// This is an implementation detail of the process_point_set function.
// We need this function because in process_point_set() we use std::sort.
// We sort arbitrary objects of type T, and the property map will allow
// us to access the Point_3 associated to it.

template <typename T, typename PointPMap>
struct MyLess {

  PointPMap pmap;

  MyLess(const PointPMap& p)
    : pmap(p)
  {}

  bool operator()(const T& t0, const T& t1) const
  {
    return get(pmap, t0) < get(pmap, t1);
  }
};

// In this example we have a function that only operates on the point part.
// It sorts them lexicographically.

template <typename Iterator, typename PointPMap >
void process_point_set(Iterator beg, Iterator end, PointPMap pmap)
{
  MyLess<typename std::iterator_traits<Iterator>::value_type,PointPMap> less(pmap);
  std::sort(beg,end,less);
}

// We can call it just with points. Then interally we use a property map
// that maps point iterators on points.

template <typename Iterator>
void process_point_set(Iterator beg, Iterator end)
{
  process_point_set(beg,end,
    CGAL::make_identity_property_map(
      typename CGAL::value_type_traits<Iterator>::type())
    );
}

// Here comes a function that changes the orientation and the normal

template <typename Iterator, typename OrientationPMap, typename NormalPMap >
void orient_normals(Iterator beg, Iterator end, OrientationPMap orient_pmap, NormalPMap normal_pmap)
{
  for(;beg!= end;++beg){
    const Vector_3& v = get(normal_pmap, *beg);
    put(orient_pmap, *beg, (v == CGAL::NULL_VECTOR));

    if(v.x() < 0){
      put(normal_pmap,*beg, -v);
    }
  }
}

int main()
{
  CGAL::set_pretty_mode(std::cout);

  // Here we run it on plain points. No need for a property map
  {
    std::vector<Point_3> points;

    process_point_set(points.begin(), points.end());
  }

  // Here we run it on points with normal vectors stored in a std::pair.
  // We use a property map that accesses pair::first.
  {
    std::vector<PointVectorPair> points;

    for(int i = 0; i < 10; i++){
      points.push_back(std::make_pair(Point_3(9-i,0,0), Vector_3(i,0,0)));
    }

    process_point_set(points.begin(),
                      points.end(),
                      CGAL::First_of_pair_property_map<PointVectorPair>());

    for(int i = 0; i < 10; i++){
      std::cout << points[i].first << "\t" << points[i].second << std::endl;
    }
  }

  // Here we run it on tuples. To see the interest I made up my own
  // data type = index, followed by the point, followed by a boolean
  // that tells us whether the normal is oriented or not, followed by the normal vector.
  // As the point is the second element of the tuple (that is with index 1)
  // we use a property map that accesses the 1st element of the tuple.
  {
    std::vector<IndexedPointWithOrientableNormalTuple> points;

    for(int i = 0; i < 10; i++){
      double x = (i%2)?i:-i;
      points.push_back(boost::make_tuple(i,Point_3(9-i,0,0), false, Vector_3(x,0,0)));
    }

    process_point_set(points.begin(),
                      points.end(),
                      CGAL::Nth_of_tuple_property_map<1,IndexedPointWithOrientableNormalTuple>());

    std::cout << boost::tuples::set_open('[') << boost::tuples::set_close(']') << boost::tuples::set_delimiter(',');

    for(int i = 0; i < 10; i++){
      std::cout << points[i]  << std::endl;
    }

    //We keep the sequence in order, but determine the normal and if it is different from zero set the Boolean to true
    orient_normals(points.begin(),
                   points.end(),
                   CGAL::make_nth_of_tuple_property_map<2>(IndexedPointWithOrientableNormalTuple()),
                   CGAL::make_nth_of_tuple_property_map<3>(IndexedPointWithOrientableNormalTuple()));

    std::cout << "\nAfter orient_normals\n";
    for(int i = 0; i < 10; i++){
      std::cout << points[i]  << std::endl;
    }
  }
  return 0;
}

max_stars_repo_name: hlzz/dotfiles

max_issues_repo_name: hlzz/dotfiles

max_forks_repo_name: hlzz/dotfiles


text:
/**
 * vanilla: VOCAnnotation.cpp
 * Copyright (c) Torr Vision Group, University of Oxford, 2016. All rights reserved.
 */

#include "VOCAnnotation.h"

#include <iostream>
#include <algorithm>

#include <boost/assign/list_of.hpp>
#include <boost/format.hpp>

#include <opencv2/highgui/highgui.hpp>

//#################### PRIVATE STATIC MEMBER VARIABLES ####################

size_t VOCAnnotation::m_categoryCount = 0;
std::map<std::string,size_t> VOCAnnotation::m_categoryNameToId = std::map<std::string,size_t>();
std::map<size_t,std::string> VOCAnnotation::m_categoryIdToName = std::map<size_t,std::string>();
boost::unordered_map<cv::Vec3b,size_t,Vec3bHash> VOCAnnotation::m_colourToCategoryIdHash = boost::unordered_map<cv::Vec3b,size_t,Vec3bHash>();

//#################### CONSTRUCTORS ####################

VOCAnnotation::VOCAnnotation()
{}

VOCAnnotation::VOCAnnotation(const std::string& imageName_, const Size& size_)
: imageName(imageName_),
  size(size_)
{}

//#################### DESTRUCTORS ####################

VOCAnnotation::~VOCAnnotation()
{}

//#################### PUBLIC MEMBER FUNCTIONS ####################

void VOCAnnotation::save(const std::string& saveDir) const
{
  boost::format threeDigits("%03d");
  const std::vector<VOCObject>& objects = get_objects();
  for(size_t i = 0; i < objects.size(); ++i)
  {
    const VOCObject& obj = objects[i];
    std::string categoryName(obj.categoryName);
    // Make sure thte categoryName has no spaces.
    categoryName.erase(std::remove_if(categoryName.begin(), categoryName.end(), ::isspace), categoryName.end());
    size_t instanceId = i;
    std::string fileName = this->imageName + '_' + categoryName  + '_' + "inst" + (threeDigits % instanceId).str() + ".png";
    std::string filePath = saveDir + '/' + fileName;
    std::cout << "Saving: " << filePath << '\n';
    // Save as png with least compression
    if(obj.rep.get_mask().data)
    {
      cv::imwrite(filePath, obj.rep.get_mask(), boost::assign::list_of(0));
    }
  }
}

//#################### PUBLIC STATIC MEMBER FUNCTIONS ####################

size_t VOCAnnotation::get_category_count()
{
  return m_categoryCount;
}

const std::map<std::string,size_t>& VOCAnnotation::get_category_name_to_id()
{
  return m_categoryNameToId;
}

const std::map<size_t,std::string>& VOCAnnotation::get_category_id_to_name()
{
  return m_categoryIdToName;
}

const boost::unordered_map<cv::Vec3b,size_t,Vec3bHash>& VOCAnnotation::get_colour_to_category_id_hash()
{
  return m_colourToCategoryIdHash;
}

void VOCAnnotation::set_category_count(size_t categoryCount)
{
  m_categoryCount = categoryCount;
}

void VOCAnnotation::set_category_id_to_name(const std::map<size_t,std::string>& categoryIdToName)
{
  m_categoryIdToName = categoryIdToName;
}

void VOCAnnotation::set_category_name_to_id(const std::map<std::string,size_t>& categoryNameToId)
{
  m_categoryNameToId = categoryNameToId;
}

void VOCAnnotation::set_colour_to_category_id_hash(const boost::unordered_map<cv::Vec3b,size_t,Vec3bHash>& colourToCategoryIdHash)
{
  m_colourToCategoryIdHash = colourToCategoryIdHash;
}

size_t VOCAnnotation::calculate_object_count(const std::vector<VOCObject>& objects, size_t categoryId)
{
  size_t objectCount(0);
  for(size_t i = 0, size = objects.size(); i < size; ++i)
  {
    if(categoryId == static_cast<size_t>(objects[i].categoryId))
    {
      if(!objects[i].difficult) ++objectCount;
    }
  }

  return objectCount;
}

//#################### OUTPUT ####################

std::ostream& operator<<(std::ostream& os, const VOCAnnotation& a)
{
  os << "ID: " << a.imageName << '\n';
  os << "Size: " << a.size << '\n';
  return os;
}

max_stars_repo_name: torrvision/straighttoshapes

max_issues_repo_name: torrvision/straighttoshapes

max_forks_repo_name: torrvision/straighttoshapes


text:
/**
 *   Copyright (C) 2012 ciere consulting, ciere.com
 *   Copyright (C) 2010, 2011 Object Modeling Designs
 *
 *   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 CIERE_JSON_DETAIL_GRAMMAR_HPP
#define CIERE_JSON_DETAIL_GRAMMAR_HPP

#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS

#include <string>
#include <boost/spirit/include/qi.hpp>
#include "../value.hpp"

namespace ciere { namespace json { namespace parser
{
   namespace qi      = boost::spirit::qi;
   namespace ascii   = boost::spirit::ascii;

   namespace detail
   {
      template <typename Iterator>
      struct unicode_string : qi::grammar<Iterator, std::string()>
      {
         unicode_string();
         qi::rule<Iterator, void(std::string&)> escape;
         qi::rule<Iterator, void(std::string&)> char_esc;
         qi::rule<Iterator, std::string()> double_quoted;
      };
   }

   template< typename Iterator >
   struct grammar : qi::grammar< Iterator, json::value(), ascii::space_type >
   {
      grammar();
      qi::rule< Iterator, json::value()           , ascii::space_type > value;
      qi::rule< Iterator, json::object_t()        , ascii::space_type > object;
      qi::rule< Iterator, json::object_member_t() , ascii::space_type > member_pair;
      qi::rule< Iterator, json::array_t()         , ascii::space_type > array;
      detail::unicode_string< Iterator                                > string_value;
      qi::rule< Iterator, json::null_t()          , ascii::space_type > null_value;
   };

}}}

#endif  // CIERE_JSON_DETAIL_GRAMMAR_HPP

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text: #include <boost/thread/pthread/thread_data.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef SHIFT_RESOURCE_DB_FILESYSTEM_HPP
#define SHIFT_RESOURCE_DB_FILESYSTEM_HPP

#include <cstdint>
#include <array>
#include <unordered_map>
#include <fstream>
#include <shared_mutex>
#include <filesystem>
#include <shift/core/bit_field.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include "shift/resource_db/resource.hpp"
#include "shift/resource_db/mountable.hpp"

namespace shift::resource_db
{
///
class filesystem final : public mountable
{
public:
  ///
  filesystem(const std::filesystem::path& path);

  ///
  ~filesystem() override;

  ///
  bool open(bool read_only = true) override;

  ///
  void close() override;

  ///
  resource_id lookup_id(const std::filesystem::path& relative_path) override;

  ///
  bool load(resource_id id, resource_base& resource,
            resource_type type) override;

  ///
  bool save(const resource_base& resource, resource_type type, resource_id id,
            const std::filesystem::path& relative_path) override;

  ///
  void erase(resource_id id) override;

private:
  struct index_entry
  {
    resource_id id;
    std::string generic_path;
  };

  struct by_id
  {
  };

  struct by_path
  {
  };

  using index_map = boost::multi_index_container<
    index_entry,
    boost::multi_index::indexed_by<
      boost::multi_index::ordered_non_unique<
        boost::multi_index::tag<by_id>,
        boost::multi_index::member<index_entry, resource_id, &index_entry::id>>,
      boost::multi_index::hashed_unique<
        boost::multi_index::tag<by_path>,
        boost::multi_index::member<index_entry, std::string,
                                   &index_entry::generic_path>>>>;

  ///
  bool save_impl(const resource_base& resource, resource_type type,
                 resource_id id, const std::filesystem::path& relative_path);

  bool _read_only;
  std::shared_mutex _index_mutex;
  index_map _index;
};
}

#endif

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
/* This is the city side */
#include <string>
#include <iostream>
#include <fstream>
#include "socket_link2.h"
#include "socket_utils2.h"
#include "http.h"
#include "../clink2dtn/ProcessManager.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include "clink2dtnUtils.h"
#include "sendall.h"

string IP = "127.0.0.1";
string PORT = "8118";
int TIMEOUT = 10000;

// Gets file based on the parsed request; gets links for scraping, if request
void getFile(string outputfiledir, string outputfilename, string username, string hash, HttpRequest& request, ProcessManager& pm, bool link)
{
	// Write out the meta file
	string metafilename = outputfilename + ".desc";
	string metafilepath = outputfiledir + "/" + metafilename;
	ofstream metafile(metafilepath);
	metafile.write(username.c_str(), strlen(username.c_str()));
	metafile.put('\n');
	metafile.close();

	// Open connection to HTTP proxy
	SockWrapper connection(IP, PORT, TIMEOUT);
	connection.sendM(request.unparse());

	string outputfilefullpath = outputfiledir + "/" + outputfilename;
	ofstream outputfile(outputfilefullpath);
	outputfile.write(hash.c_str(), strlen(hash.c_str()));
	outputfile.put('\n');

	// Write out response to output file
	while (true)
	{
		std::vector<char> response;
		int numbytes = connection.recvM(response);
		if (numbytes < 1)
		{
			break;
		}
		outputfile.write(response.data(), response.size());
	}
	outputfile.close();

	// Create tar file with the .desc and output
	string command = "tar --create --file=" + outputfilename + ".tar " + outputfilename + " " + outputfilename + ".desc";
	pm.startNewCommand(command, true, outputfiledir);

	// Call python script to parse out the links
	if (link)
	{
		// Get the host / path from the parsed header
		string hoststring = request.m_host;
		string pathstring = request.m_path;

		string base_url = hoststring + pathstring;

	    // go down a level and scrape
	    string outputfilepath = outputfiledir + "/" + outputfilename;
	    string command = "python2 fileproxy/scrape.py " + outputfilepath + " " + outputfilepath + ".link " + base_url;
	    pm.startNewCommand(command, true);
	}

	// Remove all but the tar files
	command = "rm " + outputfilename + " " + metafilename;
	pm.startNewCommand(command, true, outputfiledir);
}

void evaluateLinks(string linkfilename, HttpRequest parsed, string outputfilename, string outputfiledir, string username, ProcessManager& pm)
{
	//Now read the links and get them
	ifstream linkfile;
	linkfile.open(linkfilename);

	char buffer[1024];

	int count = 0;

	while (!linkfile.fail() && count < 10)
	{
		linkfile.getline(buffer, sizeof(buffer), '\n');
		string line = string{buffer};

		// First, split the command into components
		std::vector<string> splitUrl;
		boost::split(splitUrl, line, boost::is_any_of(" "));

		if (splitUrl.size() != 2)
		{
			continue;
		}

		string hostName = string{splitUrl[0]};
		string pathName = string{splitUrl[1]};

		if (pathName.empty() || hostName.empty())
		{
			continue;
		}

		if (pathName.compare("/") == 0)
		{
			pathName += "index.html";
		}

		string urlToHash = "http://" + hostName + pathName;
		string hash = urlhash(urlToHash.c_str(), urlToHash.size());

		//ParsedHeader_set(parsed, "Host", hostName.c_str());
		//ParsedHeader_set(parsed, "Path", pathName.c_str());
		parsed.changeHost(hostName);
		parsed.m_path = pathName;

		string outputfilenamenew{outputfilename};
		outputfilenamenew += "_" + boost::lexical_cast<std::string>(count);
		getFile(outputfiledir, outputfilenamenew, username, hash, parsed, pm, false);

		count++;
	}
}

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

	// output file in same dir
    if(argc==2)
    {
      outputfiledir=".";
    }
    else if (argc==3)
    {
      outputfiledir=argv[2];
    }
    else
    {
    	std::cerr << "Wrong number of arguments. Usage: fileproxy file [destination]" << std::endl;;
    	return 1;
    }

    ifstream inputfile;
    inputfile.open(argv[1]);

    char buffer[1024];

    // Get the name for the output file
    inputfile.getline(buffer ,sizeof(buffer),'\r');
    inputfile.ignore();
    string outputfilename = string{buffer};

    //Now get the username
    inputfile.getline(buffer, sizeof(buffer), '\r');
	inputfile.ignore();
	string username = string{buffer};

	// This is the hash of the filename
	inputfile.getline(buffer, sizeof(buffer),'\r');
	string hash = string{buffer};

	inputfile.ignore();

	// Read request from the input file
    std::vector<char> request;
    while(!inputfile.fail())
    {
    	inputfile.read(buffer, sizeof(buffer));
    	int numbytes = inputfile.gcount();

    	for (int i = 0; i < numbytes; i++)
    	{
    		request.push_back(buffer[i]);
    	}
    }

    HttpRequest parsed = parseRequest(request, true);

    ProcessManager pm("/");
    getFile(outputfiledir, outputfilename, username, hash, parsed, pm, false);

    // Can close the request file
    inputfile.close();

    //Now read the links and get them
    string linkfilename = outputfiledir + "/" + outputfilename + ".link";

    //evaluateLinks(linkfilename, parsed, outputfilename, outputfiledir, username, pm);
    //ParsedRequest_destroy(parsed);

    string command = "rm " + linkfilename;
	pm.startNewCommand(command, true);

    return 0;
}

max_stars_repo_name: jonathanmeisel/C-LINK

max_issues_repo_name: jonathanmeisel/C-LINK

max_forks_repo_name: jonathanmeisel/C-LINK


text:
#include <boost/test/unit_test.hpp>

#include <boost/filesystem.hpp>

#include <dsv_parser.h>
#include "test_detail.h"

#include <errno.h>
#include <stdio.h>

#include <string>
#include <sstream>
#include <algorithm>
#include <memory>
#include <cstdio>

/** \file
 *  \brief Unit tests for basic parsing
 */

namespace dsv {
namespace test {

namespace b = boost;
namespace fs = boost::filesystem;

namespace detail {

// note escaped '\'
const char *rfc4180_charset_field = " !#$%&'()*+-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

const char rfc4180_quoted_charset_field[] = {
  ' ','!',0x22,'#','$','%','&',0x27,'(',')','*','+',',','-','.','/','0','1','2','3','4',
  '5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K',
  'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\\',']','^','_','`',
  'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
  'w','x','y','z','{','|','}','~',0x0D,0x0A
};

}

BOOST_AUTO_TEST_SUITE( alt_parse_suite )

#if 0
/** CHECK BASIC RECOGNITION OF THE CHARACTERSET **/

/** \test Attempt to parse an named file with a single field consisting of the
 *    the rfc4180 character set
 */
BOOST_AUTO_TEST_CASE( parse_named_single_field_rfc4180_charset_crlf )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set RFC4180 strict
  dsv_parser_set_newline_handling(parser,dsv_newline_RFC4180_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context header_context;
  header_context.field_matrix.resize(1);
  header_context.field_matrix[0].push_back(detail::rfc4180_charset_field);
  dsv_set_header_callback(detail::field_callback,&header_context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/single_field_rfc4180_charset_crlf.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed for a valid file: " << filename);
}

/** \test Attempt to parse an named file with a single field consisting of the
 *    quoted rfc4180 character set
 */
BOOST_AUTO_TEST_CASE( parse_named_single_field_quoted_rfc4180_charset_crlf )
{
std::cerr << "START SINGLE CHARSET\n";
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set RFC4180 strict
  dsv_parser_set_newline_handling(parser,dsv_newline_RFC4180_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context header_context;
  header_context.field_matrix.resize(1);
  header_context.field_matrix[0].push_back(detail::rfc4180_quoted_charset_field);
  dsv_set_header_callback(detail::field_callback,&header_context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/single_field_quoted_rfc4180_charset_crlf.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed for a valid file: " << filename);
}

/** CHECK BASIC NEWLINE HANDLING **/

/** \test Attempt to parse an named file with a single field consisting of the
 *    the rfc4180 character set. This file is not line terminated. If this test seems to
 *    be failing for unknown reasons, make sure that the test data file is not appended
 *    with an auto-generated newline as many text editors tend to do (as well as git if
 *    it isn't set up correctly to handle this case).
 */
BOOST_AUTO_TEST_CASE( parse_named_single_field_rfc4180_charset )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set RFC4180 strict
  dsv_parser_set_newline_handling(parser,dsv_newline_RFC4180_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context header_context;
  header_context.field_matrix.resize(1);
  header_context.field_matrix[0].push_back(detail::rfc4180_charset_field);
  dsv_set_header_callback(detail::field_callback,&header_context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/single_field_rfc4180_charset.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed for a valid file: " << filename);
}

// todo, update this when logging gets worked out
/** \test Attempt to parse an named file with a single field consisting of the
 *    the rfc4180 character set terminated with just a linefeed. When the parser is
 *    set to be RFC4180 strict, this is an error.
 */
BOOST_AUTO_TEST_CASE( parse_named_single_field_rfc4180_charset_lf )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set RFC4180 strict
  dsv_parser_set_newline_handling(parser,dsv_newline_RFC4180_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  std::vector<std::string> context;
  dsv_set_header_callback(detail::fill_vector_with_fields,&context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/single_field_rfc4180_charset_lf.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  std::stringstream out;
  for(std::size_t i=0; i<context.size(); ++i)
    out << context[i] << " ";
  out << "\n";

  BOOST_REQUIRE_MESSAGE(result != 0,
    "dsv_parse incorrectly accepted a non-quoted linefeed when set to be RFC4180-strict: "
      << filename << ". Received '" << out.str() << "'");
}

// todo, update this when logging gets worked out
/** \test Attempt to parse an named file with a single field consisting of the
 *    the POSIX character set terminated with just a linefeed.
 */
BOOST_AUTO_TEST_CASE( parse_named_single_field_POSIX_charset_lf )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set LF strict
  dsv_parser_set_newline_handling(parser,dsv_newline_lf_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context header_context;
  header_context.field_matrix.resize(1);
  header_context.field_matrix[0].push_back(detail::rfc4180_charset_field);
  dsv_set_header_callback(detail::field_callback,&header_context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/single_field_rfc4180_charset_lf.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed for a valid file: " << filename);
}

// todo, update this when logging gets worked out
/** \test Attempt to parse an named file with a single field consisting of the
 *    the POSIX character set terminated with a carriage return and line feed. When the
 *    parser is set to be LF strict, this is an error.
 */
BOOST_AUTO_TEST_CASE( parse_named_single_field_POSIX_charset_crlf )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set LF strict
  dsv_parser_set_newline_handling(parser,dsv_newline_lf_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  std::vector<std::string> context;
  dsv_set_header_callback(detail::fill_vector_with_fields,&context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/single_field_rfc4180_charset_crlf.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  std::stringstream out;
  for(std::size_t i=0; i<context.size(); ++i)
    out << context[i] << " ";
  out << "\n";

  BOOST_REQUIRE_MESSAGE(result != 0,
    "dsv_parse incorrectly accepted a CRLF when set to be LF-strict: "
      << filename << ". Received '" << out.str() << "'");
}

/** CHECK BASIC DELIMITER HANDLING **/

/** \test Attempt to parse an named file with multiple fields consisting of the
 *    rfc4180 character set
 */
BOOST_AUTO_TEST_CASE( parse_named_multifield_rfc4180_charset_crlf )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set RFC4180 strict
  dsv_parser_set_newline_handling(parser,dsv_newline_RFC4180_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context header_context;
  header_context.field_matrix.resize(1);
  header_context.field_matrix[0].push_back(detail::rfc4180_charset_field);
  header_context.field_matrix[0].push_back(detail::rfc4180_charset_field);
  dsv_set_header_callback(detail::field_callback,&header_context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/multifield_rfc4180_charset_crlf.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed for a valid file: " << filename);
}

/** \test Attempt to parse an named file with multiple fields consisting of the
 *    quoted rfc4180 character set
 */
BOOST_AUTO_TEST_CASE( parse_named_multifield_rfc4180_quoted_charset_crlf )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set RFC4180 strict
  dsv_parser_set_newline_handling(parser,dsv_newline_RFC4180_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context header_context;
  header_context.field_matrix.resize(1);
  header_context.field_matrix[0].push_back(detail::rfc4180_quoted_charset_field);
  header_context.field_matrix[0].push_back(detail::rfc4180_quoted_charset_field);
  dsv_set_header_callback(detail::field_callback,&header_context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/multifield_quoted_rfc4180_charset_crlf.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed for a valid file: " << filename);
}

/** CHECK NEWLINE HANDLING FOR MULTIFIELDS **/

/** \test Attempt to parse an named file with multiple fields consisting of the
 *    rfc4180 character set. This file is not newline terminated
 */
BOOST_AUTO_TEST_CASE( parse_named_multifield_rfc4180_charset )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set RFC4180 strict
  dsv_parser_set_newline_handling(parser,dsv_newline_RFC4180_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context header_context;
  header_context.field_matrix.resize(1);
  header_context.field_matrix[0].push_back(detail::rfc4180_charset_field);
  header_context.field_matrix[0].push_back(detail::rfc4180_charset_field);
  dsv_set_header_callback(detail::field_callback,&header_context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/multifield_rfc4180_charset.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed for a valid file: " << filename);
}

/** \test Attempt to parse an named file with multiple fields consisting of the
 *    quoted rfc4180 character set. This file is not newline terminated.
 */
BOOST_AUTO_TEST_CASE( parse_named_multifield_rfc4180_quoted_charset )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  // set RFC4180 strict
  dsv_parser_set_newline_handling(parser,dsv_newline_RFC4180_strict);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  std::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context header_context;
  header_context.field_matrix.resize(1);
  header_context.field_matrix[0].push_back(detail::rfc4180_quoted_charset_field);
  header_context.field_matrix[0].push_back(detail::rfc4180_quoted_charset_field);
  dsv_set_header_callback(detail::field_callback,&header_context,operations);

  detail::field_context record_context;
  record_context.invocation_limit = 0;
  dsv_set_record_callback(detail::field_callback,&record_context,operations);

  std::string filename(detail::testdatadir+"/multifield_quoted_rfc4180_charset.dsv");
  int result = dsv_parse(filename.c_str(),0,parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed for a valid file: " << filename);
}

#if 0
/** \test Parse a file with no records but has a single LF using permissive newline
 *  handling
 */
BOOST_AUTO_TEST_CASE( permissively_parse_recordless_file_w_LF )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  assert(dsv_parser_set_newline_handling(parser,dsv_newline_permissive) == 0);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  boost::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context context;
  dsv_set_record_callback(detail::field_callback,&context,operations);

  fs::path filename(detail::testdatadir/"empty_lf.dsv");

  int result = dsv_parse(filename.string().c_str(),parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed on '" << filename << "' with message \""
      << detail::msg_log(parser,dsv_log_all) << "\"");
}

/** \test Parse a file with no records but has a single CRLF using permissive newline
 *  handling
 */
BOOST_AUTO_TEST_CASE( permissively_parse_recordless_file_w_CRLF )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  assert(dsv_parser_set_newline_handling(parser,dsv_newline_permissive) == 0);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  boost::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context context;
  dsv_set_record_callback(detail::field_callback,&context,operations);

  fs::path filename(detail::testdatadir/"empty_crlf.dsv");

  int result = dsv_parse(filename.string().c_str(),parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed on '" << filename << "' with message \""
      << detail::msg_log(parser,dsv_log_all) << "\"");
}

/**
 *  \test Parse a file with no records using strict LF newline handling
 */
BOOST_AUTO_TEST_CASE( strictly_parse_recordless_LF_handling )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  assert(dsv_parser_set_newline_handling(parser,dsv_newline_lf_strict) == 0);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  boost::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context context;
  dsv_set_record_callback(detail::field_callback,&context,operations);

  fs::path filename(detail::testdatadir/"empty_lf.dsv");

  int result = dsv_parse(filename.string().c_str(),parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed on '" << filename << "' with message \""
      << detail::msg_log(parser,dsv_log_all) << "\"");

  filename = fs::path(detail::testdatadir/"empty_crlf.dsv");

  result = dsv_parse(filename.string().c_str(),parser,operations);

  BOOST_REQUIRE_MESSAGE(result == -1,
    "dsv_parse succeeded or failed for incorrect reasons on '" << filename
      << "' with message \"" << detail::msg_log(parser,dsv_log_all) << "\"");
}

/**
 *  \test Parse a file with no records using strict CRLF newline handling
 */
BOOST_AUTO_TEST_CASE( strictly_parse_recordless_CRLF_handling )
{
  dsv_parser_t parser;
  assert(dsv_parser_create(&parser) == 0);
  boost::shared_ptr<dsv_parser_t> parser_sentry(&parser,detail::parser_destroy);

  assert(dsv_parser_set_newline_handling(parser,dsv_newline_crlf_strict) == 0);

  dsv_operations_t operations;
  assert(dsv_operations_create(&operations) == 0);
  boost::shared_ptr<dsv_operations_t> operations_sentry(&operations,detail::operations_destroy);

  detail::field_context context;
  dsv_set_record_callback(detail::field_callback,&context,operations);

  fs::path filename(detail::testdatadir/"empty_crlf.dsv");

  int result = dsv_parse(filename.string().c_str(),parser,operations);

  BOOST_REQUIRE_MESSAGE(result == 0,
    "dsv_parse failed on '" << filename << "' with message \""
      << detail::msg_log(parser,dsv_log_all) << "\"");

  filename = fs::path(detail::testdatadir/"empty_lf.dsv");

  result = dsv_parse(filename.string().c_str(),parser,operations);

  BOOST_REQUIRE_MESSAGE(result == -1,
    "dsv_parse succeeded or failed for incorrect reasons on '" << filename
      << "' with message \"" << detail::msg_log(parser,dsv_log_all) << "\"");
}

#endif
#endif

BOOST_AUTO_TEST_SUITE_END()

}
}

ext: cc

max_stars_repo_name: tegtmeye/libdsv

max_issues_repo_name: tegtmeye/libdsv

max_forks_repo_name: tegtmeye/libdsv


text:
/*

Copyright (c) 2005-2016, University of Oxford.
All rights reserved.

University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.

This file is part of Chaste.

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 the University of Oxford 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.

*/

#ifndef CELLBETACATENINWRITER_HPP_
#define CELLBETACATENINWRITER_HPP_

#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>
#include "AbstractCellWriter.hpp"
#include "AbstractVanLeeuwen2009WntSwatCellCycleModel.hpp"

/** A class written using the visitor pattern for writing cell beta catenin levels to file. */
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class CellBetaCateninWriter : public AbstractCellWriter<ELEMENT_DIM, SPACE_DIM>
{
private:
    /** Needed for serialization. */
    friend class boost::serialization::access;
    /**
     * Serialize the object and its member variables.
     *
     * @param archive the archive
     * @param version the current version of this class
     */
    template<class Archive>
    void serialize(Archive & archive, const unsigned int version)
    {
        archive & boost::serialization::base_object<AbstractCellWriter<ELEMENT_DIM, SPACE_DIM> >(*this);
    }

public:

    /**
     * Default constructor.
     */
    CellBetaCateninWriter();

    /**
     * Overridden GetCellDataForVtkOutput() method.
     *
     * Get a double associated with a cell. This method reduces duplication
     * of code between the methods VisitCell() and AddVtkData().
     *
     * In this overridden method, since we are only able to output one double
     * for each cell, we choose to output the cytoplasmic beta catenin
     * concentration. Thus, at present, the membrane-bound and nuclear beta
     * catenin concentrations cannot be visualized as VTK output. If this
     * were required, it would be straightforward to implement within the
     * current framework, for example by defined two new writer classes.
     *
     * @param pCell a cell
     * @param pCellPopulation a pointer to the cell population owning the cell
     *
     * @return data associated with the cell
     */
    double GetCellDataForVtkOutput(CellPtr pCell, AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>* pCellPopulation);

    /**
     * Overridden VisitCell() method.
     * Visit a cell and write its data.
     *
     * @param pCell the cell to write
     * @param pCellPopulation a pointer to the cell population owning the cell.
     */
    virtual void VisitCell(CellPtr pCell, AbstractCellPopulation<ELEMENT_DIM, SPACE_DIM>* pCellPopulation);
};

#include "SerializationExportWrapper.hpp"
EXPORT_TEMPLATE_CLASS_ALL_DIMS(CellBetaCateninWriter)

#endif /*CELLBETACATENINWRITER_HPP_*/

max_stars_repo_name: uofs-simlab/ChasteOS

max_issues_repo_name: uofs-simlab/ChasteOS

max_forks_repo_name: uofs-simlab/ChasteOS


text:
/*
 * @Description: velocity 数据
 * @Author: Ren Qian
 * @Date: 2019-07-17 18:27:40
 */
#ifndef LIDAR_LOCALIZATION_SENSOR_DATA_VELOCITY_DATA_HPP_
#define LIDAR_LOCALIZATION_SENSOR_DATA_VELOCITY_DATA_HPP_

#include <deque>
#include <Eigen/Dense>

namespace lidar_localization {
class VelocityData {
  public:
    struct LinearVelocity {
      double x = 0.0;
      double y = 0.0;
      double z = 0.0;
    };

    struct AngularVelocity {
      double x = 0.0;
      double y = 0.0;
      double z = 0.0;
    };

    double time = 0.0;
    LinearVelocity linear_velocity;
    AngularVelocity angular_velocity;

  public:
    static bool SyncData(std::deque<VelocityData>& UnsyncedData, std::deque<VelocityData>& SyncedData, double sync_time);
    void TransformCoordinate(Eigen::Matrix4f transform_matrix);
};
}
#endif


text:
/* Copyright (C) 2012-2020 IBM Corp.
 * This program is Licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. See accompanying LICENSE file.
 */

#include <NTL/ZZ.h>
#include <NTL/BasicThreadPool.h>
#include <helib/helib.h>
#include <NTL/lzz_pXFactoring.h>

#include <cstdio>

#include "gtest/gtest.h"
#include "test_common.h"

#include <helib/debugging.h>

/**************

  1. c1.multiplyBy(c0)
  2. c0 += random constant
  3. c2 *= random constant
  4. tmp = c1
  5. ea.shift(tmp, random amount in [-nSlots/2, nSlots/2])
  6. c2 += tmp
  7. ea.rotate(c2, random amount in [1-nSlots, nSlots-1])
  8. c1.negate()
  9. c3.multiplyBy(c2)
  10. c0 -= c3

 **************/

namespace {

::testing::AssertionResult ciphertextMatches(const helib::EncryptedArray& ea,
                                             const helib::SecKey& sk,
                                             const helib::PlaintextArray& p,
                                             const helib::Ctxt& c)
{
  helib::PlaintextArray pp(ea);
  ea.decrypt(c, sk, pp);
  if (equals(ea, pp, p)) {
    return ::testing::AssertionSuccess();
  } else {
    return ::testing::AssertionFailure()
           << "Ciphertext does not match plaintext:" << std::endl
           << "p = " << p << std::endl
           << "pp = " << pp << std::endl;
  }
}

struct Parameters
{
  Parameters(long R,
             long p,
             long r,
             long d,
             long c,
             long k,
             long L,
             long s,
             long m,
             NTL::Vec<long> mvec,
             NTL::Vec<long> gens,
             NTL::Vec<long> ords,
             long seed,
             long nt) :
      R(R),
      p(p),
      r(r),
      d(d),
      c(c),
      k(k),
      L(L),
      s(s),
      m(m),
      mvec(mvec),
      gens(gens),
      ords(ords),
      seed(seed),
      nt(nt){};

  long R; // number of rounds
  long p; // plaintext base
  long r; // lifting
  long d; // degree of the field extension
  // Note: d == 0 => factors[0] defines extension
  long c;              // number of columns in the key-switching matrices
  long k;              // security parameter
  long L;              // # of bits in the modulus chain
  long s;              // minimum number of slots
  long m;              // use specified value as modulus
  NTL::Vec<long> mvec; // use product of the integers as modulus
  // Note: mvec takes priority over m
  NTL::Vec<long> gens; // use specified vector of generators
  NTL::Vec<long> ords; // use specified vector of orders
  // e.g., ords=[4 2 -4], negative means 'bad'
  long seed; // PRG seed
  long nt;   // num threads

  // Let googletest know how to print the Parameters
  friend std::ostream& operator<<(std::ostream& os, const Parameters& params)
  {
    return os << "{"
              << "R=" << params.R << ","
              << "p=" << params.p << ","
              << "r=" << params.r << ","
              << "d=" << params.d << ","
              << "c=" << params.c << ","
              << "k=" << params.k << ","
              << "L=" << params.L << ","
              << "s=" << params.s << ","
              << "m=" << params.m << ","
              << "mvec=" << params.mvec << ","
              << "gens=" << params.gens << ","
              << "ords=" << params.ords << ","
              << "seed=" << params.seed << ","
              << "nt=" << params.nt << "}";
  };
};

class GTestGeneral : public ::testing::TestWithParam<Parameters>
{
protected:
  long R;
  long p;
  long r;
  long d;
  long c;
  long k;
  long w;
  long L;
  long m;

  std::vector<long> gens;
  std::vector<long> ords;

  helib::Context context;

  helib::SecKey secretKey;

  const helib::PubKey& publicKey;

  GTestGeneral() :
      R(GetParam().R),
      p(GetParam().p),
      r(GetParam().r),
      d(GetParam().d),
      c(GetParam().c),
      k(GetParam().k),
      w(64),
      L(GetParam().L),
      m(helib::FindM(k,
                     L,
                     c,
                     p,
                     d,
                     GetParam().s,
                     GetParam().mvec.length() > 0
                         ? helib::computeProd(GetParam().mvec)
                         : GetParam().m,
                     true)),
      gens(helib::convert<std::vector<long>, NTL::Vec<long>>(GetParam().gens)),
      ords(helib::convert<std::vector<long>, NTL::Vec<long>>(GetParam().ords)),
      context(m, p, r, gens, ords),
      secretKey((buildModChain(context, L, c), context)),
      publicKey(secretKey)
  {}

  virtual void SetUp() override
  {
    NTL::SetSeed(NTL::ZZ(GetParam().seed));
    NTL::SetNumThreads(GetParam().nt);
    secretKey.GenSecKey(w); // A Hamming-weight-w secret key
    helib::addSome1DMatrices(
        secretKey); // compute key-switching matrices that we need

    helib::setupDebugGlobals(&secretKey, context.ea);
  };

  virtual void TearDown() override { helib::cleanupDebugGlobals(); }
};

TEST_P(GTestGeneral, correctlyImplementsMixOfOperationsOverFourCiphertexts)
{
  char buffer[32];
  if (!helib_test::noPrint) {
    std::cout << "\n\n******** " << (helib_test::dry ? "(dry run):" : ":");
    std::cout << " R=" << R << ", p=" << p << ", r=" << r << ", d=" << d
              << ", c=" << c << ", k=" << k << ", w=" << w << ", L=" << L
              << ", m=" << m << ", gens=" << helib::vecToStr(gens)
              << ", ords=" << helib::vecToStr(ords) << std::endl;
  }

  NTL::ZZX G;
  if (d == 0)
    G = context.alMod.getFactorsOverZZ()[0];
  else
    G = helib::makeIrredPoly(p, d);

  if (!helib_test::noPrint) {
    context.zMStar.printout();
    std::cout << std::endl;

    std::cout << "security=" << context.securityLevel() << std::endl;
    std::cout << "# small primes = " << context.smallPrimes.card() << "\n";
    std::cout << "# ctxt primes = " << context.ctxtPrimes.card() << "\n";
    std::cout << "# bits in ctxt primes = "
              << long(context.logOfProduct(context.ctxtPrimes) / log(2.0) + 0.5)
              << "\n";
    std::cout << "# special primes = " << context.specialPrimes.card() << "\n";
    std::cout << "# bits in special primes = "
              << long(context.logOfProduct(context.specialPrimes) / log(2.0) +
                      0.5)
              << "\n";
    std::cout << "G = " << G << "\n";
  }
  std::shared_ptr<helib::EncryptedArray> ea_ptr =
      std::make_shared<helib::EncryptedArray>(context, G);
  helib::EncryptedArray& ea(*ea_ptr);
  long nslots = ea.size();

  // Debugging additions
  helib::setupDebugGlobals(&secretKey, ea_ptr);

  helib::PlaintextArray p0(ea);
  helib::PlaintextArray p1(ea);
  helib::PlaintextArray p2(ea);
  helib::PlaintextArray p3(ea);

  helib::random(ea, p0);
  helib::random(ea, p1);
  helib::random(ea, p2);
  helib::random(ea, p3);

  helib::Ctxt c0(publicKey), c1(publicKey), c2(publicKey), c3(publicKey);
  ea.encrypt(c0, publicKey, p0);
  // {ZZX ppp0; ea.encode(ppp0, p0); c0.DummyEncrypt(ppp0);} // dummy encryption
  ea.encrypt(c1, publicKey, p1); // real encryption
  ea.encrypt(c2, publicKey, p2); // real encryption
  ea.encrypt(c3, publicKey, p3); // real encryption

  helib::resetAllTimers();

  HELIB_NTIMER_START(Circuit);

  for (long i = 0; i < R; i++) {

    if (!helib_test::noPrint)
      std::cout << "*** round " << i << "..." << std::endl;

    long shamt = NTL::RandomBnd(2 * (nslots / 2) + 1) - (nslots / 2);
    // random number in [-nslots/2..nslots/2]
    long rotamt = NTL::RandomBnd(2 * nslots - 1) - (nslots - 1);
    // random number in [-(nslots-1)..nslots-1]

    // two random constants
    helib::PlaintextArray const1(ea);
    helib::PlaintextArray const2(ea);
    helib::random(ea, const1);
    helib::random(ea, const2);

    NTL::ZZX const1_poly, const2_poly;
    ea.encode(const1_poly, const1);
    ea.encode(const2_poly, const2);

    mul(ea, p1, p0); // c1.multiplyBy(c0)
    c1.multiplyBy(c0);
    if (!helib_test::noPrint)
      CheckCtxt(c1, "c1*=c0");
    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p1, c1));

    add(ea, p0, const1); // c0 += random constant
    c0.addConstant(const1_poly);
    if (!helib_test::noPrint)
      CheckCtxt(c0, "c0+=k1");
    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p0, c0));

    mul(ea, p2, const2); // c2 *= random constant
    c2.multByConstant(const2_poly);
    if (!helib_test::noPrint)
      CheckCtxt(c2, "c2*=k2");
    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p2, c2));

    helib::PlaintextArray tmp_p(p1); // tmp = c1
    helib::Ctxt tmp(c1);
    sprintf(buffer, "tmp=c1>>=%d", (int)shamt);
    shift(ea,
          tmp_p,
          shamt); // ea.shift(tmp, random amount in [-nSlots/2,nSlots/2])
    ea.shift(tmp, shamt);
    if (!helib_test::noPrint)
      CheckCtxt(tmp, buffer);
    EXPECT_TRUE(ciphertextMatches(ea, secretKey, tmp_p, tmp));

    add(ea, p2, tmp_p); // c2 += tmp
    c2 += tmp;
    if (!helib_test::noPrint)
      CheckCtxt(c2, "c2+=tmp");
    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p2, c2));

    sprintf(buffer, "c2>>>=%d", (int)rotamt);
    rotate(ea,
           p2,
           rotamt); // ea.rotate(c2, random amount in [1-nSlots, nSlots-1])
    ea.rotate(c2, rotamt);
    if (!helib_test::noPrint)
      CheckCtxt(c2, buffer);
    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p2, c2));

    ::helib::negate(ea, p1); // c1.negate()
    c1.negate();
    if (!helib_test::noPrint)
      CheckCtxt(c1, "c1=-c1");
    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p1, c1));

    mul(ea, p3, p2); // c3.multiplyBy(c2)
    c3.multiplyBy(c2);
    if (!helib_test::noPrint)
      CheckCtxt(c3, "c3*=c2");
    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p3, c3));

    sub(ea, p0, p3); // c0 -= c3
    c0 -= c3;
    if (!helib_test::noPrint)
      CheckCtxt(c0, "c0=-c3");
    EXPECT_TRUE(ciphertextMatches(ea, secretKey, p0, c0));
  }

  c0.cleanUp();
  c1.cleanUp();
  c2.cleanUp();
  c3.cleanUp();

  HELIB_NTIMER_STOP(Circuit);

  if (!helib_test::noPrint) {
    std::cout << std::endl;
    helib::printAllTimers();
    std::cout << std::endl;
  }
  helib::resetAllTimers();
  HELIB_NTIMER_START(Check);

  EXPECT_TRUE(ciphertextMatches(ea, secretKey, p0, c0));
  EXPECT_TRUE(ciphertextMatches(ea, secretKey, p1, c1));
  EXPECT_TRUE(ciphertextMatches(ea, secretKey, p2, c2));
  EXPECT_TRUE(ciphertextMatches(ea, secretKey, p3, c3));

  HELIB_NTIMER_STOP(Check);

  std::cout << std::endl;
  if (!helib_test::noPrint) {
    helib::printAllTimers();
    std::cout << std::endl;
  }
}

// clang-format off
INSTANTIATE_TEST_SUITE_P(variousParameters, GTestGeneral, ::testing::Values(
    //         R, p, r, d, c,  k,   L, s,  m,             mvec,             gens,             ords, seed, nt
    //DEEP
    Parameters(1, 2, 2, 1, 2, 10, 500, 0, 91, NTL::Vec<long>{}, NTL::Vec<long>{}, NTL::Vec<long>{},    0,  1),
    Parameters(1, 2, 1, 2, 2, 10, 500, 0, 91, NTL::Vec<long>{}, NTL::Vec<long>{}, NTL::Vec<long>{},    0,  1),
    Parameters(2, 7, 2, 1, 2, 10, 500, 0, 91, NTL::Vec<long>{}, NTL::Vec<long>{}, NTL::Vec<long>{},    0,  1)
    //FAST
    //Parameters(1, 2, 1, 1, 2, 80, 500, 0, 91, NTL::Vec<long>{}, NTL::Vec<long>{}, NTL::Vec<long>{},    0,  1)
    ));
// clang-format on

// parameters to get an example where phi(m) is very
// close to m:
// m=18631 L=10 R=5

} // anonymous namespace

max_stars_repo_name: TomMD/HElib

max_issues_repo_name: TomMD/HElib

max_forks_repo_name: TomMD/HElib


text:
#include "baldr/graphconstants.h"
#include "gurka.h"
#include <boost/format.hpp>
#include <gtest/gtest.h>

using namespace valhalla;

class TopSpeedTest : public ::testing::Test {
protected:
  static gurka::map speed_map;

  static void SetUpTestSuite() {
    constexpr double gridsize = 10;

    const std::string ascii_map = R"(
      B------C
      |      |
      |      |
      A      D
      |      |
      E------F
    )";

    const gurka::ways ways = {{"ABCD", {{"highway", "residential"}, {"maxspeed", "45"}}},
                              {"AEFD", {{"highway", "residential"}, {"maxspeed", "20"}}}};

    const auto layout = gurka::detail::map_to_coordinates(ascii_map, gridsize);
    speed_map = gurka::buildtiles(layout, ways, {}, {}, "test/data/topspeed");
  }

  inline float getDuration(const valhalla::Api& route) {
    return route.directions().routes(0).legs(0).summary().time();
  }

  void doTests(const std::string& costing,
               const std::unordered_map<std::string, std::string>& options) {

    valhalla::Api default_route =
        gurka::do_action(valhalla::Options::route, speed_map, {"A", "D"}, costing);
    float default_time = getDuration(default_route);

    valhalla::Api capped_route =
        gurka::do_action(valhalla::Options::route, speed_map, {"A", "D"}, costing, options);
    float capped_time = getDuration(capped_route);

    gurka::assert::raw::expect_path(default_route, {"ABCD"});
    gurka::assert::raw::expect_path(capped_route, {"AEFD"});
    gurka::assert::raw::expect_eta(capped_route, 19.8f, 0.001f);
    ASSERT_GT(capped_time, default_time);
  }
};

gurka::map TopSpeedTest::speed_map = {};

TEST_F(TopSpeedTest, AutoTopSpeed) {
  doTests("auto", {{"/costing_options/auto/top_speed", "20"}});
}

TEST_F(TopSpeedTest, TruckTopSpeed) {
  doTests("truck", {{"/costing_options/truck/top_speed", "20"}});
}

TEST_F(TopSpeedTest, ScooterTopSpeed) {
  doTests("motor_scooter", {{"/costing_options/motor_scooter/top_speed", "20"}});
}

TEST_F(TopSpeedTest, MotorcycleTopSpeed) {
  doTests("motorcycle", {{"/costing_options/motorcycle/top_speed", "20"}});
}

TEST_F(TopSpeedTest, BusTopSpeed) {
  doTests("bus", {{"/costing_options/bus/top_speed", "20"}});
}

TEST_F(TopSpeedTest, TaxiTopSpeed) {
  doTests("taxi", {{"/costing_options/taxi/top_speed", "20"}});
}

TEST_F(TopSpeedTest, ClampMaxSpeed) {
  Options options;
  rapidjson::Document dom;
  rapidjson::SetValueByPointer(dom, "/top_speed", 500);

  options.set_costing(Costing::auto_);
  auto& co = (*options.mutable_costing_options())[Costing::auto_];
  sif::ParseBaseCostOptions(*rapidjson::GetValueByPointer(dom, ""), &co, {});

  ASSERT_EQ(co.top_speed(), baldr::kMaxAssumedSpeed);
}

max_stars_repo_name: CanalTP/valhalla

max_issues_repo_name: CanalTP/valhalla

max_forks_repo_name: CanalTP/valhalla


text:
#include <boost/any.hpp>

int main()
{
  boost::any a = 1;
  a = 3.14;
  a = true;
}

max_stars_repo_path: Boost/The Boost C++ Libraries/src/14.3.1/main.cpp


text:
#ifndef LAYERED_HARDWARE_EPOS_OPERATION_MODE_BASE_HPP
#define LAYERED_HARDWARE_EPOS_OPERATION_MODE_BASE_HPP

#include <string>

#include <layered_hardware_epos/epos_actuator_data.hpp>
#include <ros/duration.h>
#include <ros/time.h>

#include <boost/shared_ptr.hpp>

namespace layered_hardware_epos {

class OperationModeBase {
public:
  OperationModeBase(const std::string &name, const EposActuatorDataPtr &data)
      : name_(name), data_(data) {}

  virtual ~OperationModeBase() {}

  std::string getName() const { return name_; }

  // TODO: retrun bool to inform result of mode switching to the upper class
  virtual void starting() = 0;

  virtual void read(const ros::Time &time, const ros::Duration &period) = 0;

  virtual void write(const ros::Time &time, const ros::Duration &period) = 0;

  virtual void stopping() = 0;

protected:
  const std::string name_;
  const EposActuatorDataPtr data_;
};

typedef boost::shared_ptr< OperationModeBase > OperationModePtr;
typedef boost::shared_ptr< const OperationModeBase > OperationModeConstPtr;
} // namespace layered_hardware_epos

#endif


text:
 //============================================================================
// Name        :
// Author      : Avi
// Revision    : $Revision$
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
//============================================================================

//#include <iostream>

#include <boost/date_time/posix_time/posix_time_types.hpp>

#include "SimulatorVisitor.hpp"
#include "Defs.hpp"
#include "Suite.hpp"
#include "Family.hpp"
#include "Task.hpp"
#include "Log.hpp"

using namespace std;
using namespace boost::gregorian;
using namespace boost::posix_time;

namespace ecf {

// Please note: we can speed up simulation, by using a calendar increment of 1 hour
// However this will *ONLY* work *IF*
//   o All the time based attributes time,today,cron have no minutes, i.e only i hour resolution
//   o The calendar start time, must also have hour resolution, otherwise time/cron based attributes
//     will be missed. i.e we increment calendar start time , with calendar increment
//     If calendar start time is minutes based, and increment in hour based, time attributes will be missed
//     Note: today is different, to time/cron, as it does not require a exact match

///////////////////////////////////////////////////////////////////////////////
SimulatorVisitor::SimulatorVisitor(const std::string& defs_filename)
: defs_filename_(defs_filename),
  foundTasks_(false),
  foundCrons_(false),
  foundTime_(false),
  hasTimeDependencies_(false),
  has_end_clock_(false),
  max_sim_duration_(hours(24)),
  max_suite_duration_(hours(24)),
  ci_(hours(1))
  {}

void SimulatorVisitor::visitDefs( Defs* d) {
	for(suite_ptr s: d->suiteVec()) { s->acceptVisitTraversor(*this); }
}

void SimulatorVisitor::visitSuite( Suite* s)
{
	/// begin , will cause creation of generated variables. The generated variables
	/// are use in client scripts and used to locate the ecf files.
	s->begin();

	// Found time dependencies use calendar increment of one minute
	if (s->hasTimeDependencies()) {
		hasTimeDependencies_ = true;
	}

	if ( s->clockAttr() && s->clock_end_attr()) {
	   max_suite_duration_ = s->clock_end_attr()->ptime() - s->clockAttr()->ptime();
	   has_end_clock_ = true; // no need to determine max_length, user specified
	}

 	visitNodeContainer(s);

   // IF the suite has no task  (i.e could consist of just limits, set suite to complete
   // Since we rely on it for termination of tests
   // make setting NState::COMPLETE is after begin(), which will set Node into the queued state
 	if (!foundTasks_) {
      s->set_state(NState::COMPLETE);
      std::stringstream ss; ss <<  "The defs file " <<  defs_filename_ << " has a suite '/" << s->suite()->name() << "' which has no tasks. Ignoring \n";
 	   log(Log::WAR,ss.str());
 	}

 	// If we have cron/time with calendar increment of 1 hour, where calendar start time is in minutes
 	// we will miss the time/cron based attributes, hence use 1 minute resolution
 	if ((foundCrons_ || foundTime_) && ci_ == hours(1)) {
 	   // simulation has not started so, suiteTime same as start time.
 	   boost::posix_time::time_duration start_time = s->calendar().suiteTime().time_of_day();
 	   if (start_time.minutes() != 0) {
 	      // cout << " start_time " << start_time << "   " << defs_filename_ << "\n";
 	      log(Log::WAR,"Found cron or time based attributes, with 1 hour resolution, however suite calendar start time has minute resolution, reverting to minute resolution for simulation.");
 	      log(Log::WAR,"To speed up resolution use suite calendar with hour setting only, i.e where minutes is zero");
 	      ci_ = minutes(1);
 	   }
 	}

 	// record the max simulation period for THIS suite. i.e different suites can have different simulation period
 	suite_duration_vec_.emplace_back(s,max_suite_duration_);

 	// make sure total simulation period cover all the suites.
 	if ( max_suite_duration_ > max_sim_duration_) {
 	   max_sim_duration_ = max_suite_duration_;
 	}
}

boost::posix_time::time_duration SimulatorVisitor::max_simulation_period(Suite* s) const {
   size_t suite_duration_vec_size = suite_duration_vec_.size();
   for(size_t i =0; i < suite_duration_vec_size; i++) {
      if ( suite_duration_vec_[i].first == s) return suite_duration_vec_[i].second;
   }
   return max_sim_duration_;
}

void SimulatorVisitor::visitFamily( Family* f) { visitNodeContainer(f);}

void SimulatorVisitor::visitNodeContainer(NodeContainer* nc)
{
   if (ci_ == hours(1)) nc->get_time_resolution_for_simulation(ci_);
   if (!has_end_clock_) nc->get_max_simulation_duration(max_suite_duration_);

   if (!nc->crons().empty()) {
      foundCrons_ = true;
      std::stringstream ss; ss  << defs_filename_ << ": Found crons on NodeContainer\n";
      log(Log::MSG,ss.str());
   }

   if (!nc->timeVec().empty()) {
      foundTime_= true;
   }

	for(node_ptr t: nc->nodeVec()) { t->acceptVisitTraversor(*this);}
}

void SimulatorVisitor::visitTask( Task* t )
{
   if (ci_ == hours(1))  t->get_time_resolution_for_simulation(ci_);
   if (!has_end_clock_)  t->get_max_simulation_duration(max_suite_duration_);

   foundTasks_ = true;

   if (!t->crons().empty()) {
      foundCrons_ = true;
   }
   if (!t->timeVec().empty()) {
      foundTime_= true;
   }
}

}

max_stars_repo_name: mpartio/ecflow

max_issues_repo_name: mpartio/ecflow

max_forks_repo_name: mpartio/ecflow


text:
/*!
  @author Shin'ichiro Nakaoka
*/

#include <boost/python.hpp>
#include <QObject>
#include <QTimer>

using namespace boost;
using namespace boost::python;

namespace {

struct QString_to_python_str {
    static PyObject* convert(QString const& s){
        return boost::python::incref(
            boost::python::object(
                s.toUtf8().constData()).ptr());
    }
};

struct QString_from_python_str {
    QString_from_python_str(){
        python::converter::registry::push_back(
            &convertible, &construct, python::type_id<QString>());
    }
    static void* convertible(PyObject* obj_ptr){
        if(!PyString_Check(obj_ptr)) return 0;
        return obj_ptr;
    }
    static void construct(PyObject* obj_ptr, python::converter::rvalue_from_python_stage1_data* data){
        const char* value = PyString_AsString(obj_ptr);
        assert(value);
        void* storage = ((python::converter::rvalue_from_python_storage<QString>*)data)->storage.bytes;
        new (storage) QString(value);
        data->convertible = storage;
    }
};

void (QTimer::*QTimer_start1)() = &QTimer::start;
void (QTimer::*QTimer_start2)(int) = &QTimer::start;

}

BOOST_PYTHON_MODULE(QtCore)
{
    to_python_converter<QString, QString_to_python_str>();
    QString_from_python_str();

    class_<QObject, QObject*, boost::noncopyable>("QObject")
        .def("blockSignals", &QObject::blockSignals)
        .def("inherits", &QObject::inherits)
        .def("isWidgetType", &QObject::isWidgetType)
        .def("killTimer", &QObject::killTimer)
        .def("objectName", &QObject::objectName)
        .def("parent", &QObject::parent, return_value_policy<reference_existing_object>())
        .def("setObjectName", &QObject::setObjectName)
        .def("setParent", &QObject::setParent)
        .def("startTimer", &QObject::startTimer)
        .def("deleteLater", &QObject::deleteLater);

    class_<QTimer, QTimer*, boost::noncopyable>("QTimer")
        .def("interval", &QTimer::interval)
        .def("isActive", &QTimer::isActive)
        .def("isSingleShot", &QTimer::isSingleShot)
        .def("setInterval", &QTimer::setInterval)
        .def("setSingleShot", &QTimer::singleShot)
        .def("timerId", &QTimer::timerId)
        .def("start", QTimer_start1)
        .def("start", QTimer_start2)
        .def("stop", &QTimer::stop)
        .def("singleShot", &QTimer::singleShot).staticmethod("singleShot");
}

max_stars_repo_name: geenux/choreonoid

max_issues_repo_name: geenux/choreonoid

max_forks_repo_name: geenux/choreonoid


text:
#ifndef LUCCA_IMAGE_CACHE_HPP
#define LUCCA_IMAGE_CACHE_HPP

#include "lucca_qt/config.hpp"

#include "lucca_qt/serialization/image_cache_serializer.hpp"

#include <boost/noncopyable.hpp>

#include <unordered_map>

namespace ayla {
	class Image;
}

namespace lucca_qt {

/**
 * @author O Programador
 */
class LUCCA_QT_API ImageCache final : boost::noncopyable {
public:
	ImageCache();
	~ImageCache();

	std::shared_ptr<ayla::Image> getImage(const std::string& fileName);

private:
	using MapType = std::unordered_map<std::string, std::shared_ptr<ayla::Image> >;
	MapType _images;

	template <class Archive> friend void boost::serialization::serialize(Archive&, lucca_qt::ImageCache&, const unsigned int);
	template <class Archive> friend void boost::serialization::load_construct_data(Archive&, lucca_qt::ImageCache*, const unsigned int);
};

}

#endif // LUCCA_IMAGE_CACHE_HPP

max_stars_repo_name: oprogramadorreal/vize

max_issues_repo_name: oprogramadorreal/vize

max_forks_repo_name: oprogramadorreal/vize


text:
#include "orwell/Application.hpp"
#include "orwell/proxy/AgentProxy.hpp"
#include "orwell/Server.hpp"

#include "orwell/com/RawMessage.hpp"

#include "controller.pb.h"

#include "Common.hpp"

#include <gtest/gtest.h>

#include <boost/lexical_cast.hpp>

#include <sys/types.h>

uint32_t const gGameDuration = 10;

class TestAgentProxy: public ::testing::Test
{
protected:

	TestAgentProxy()
		: m_agentPort(9003)
		, m_replierPort(9002)
	{
	}

	void SetUp()
	{
		SetUp(boost::none);
	}

	void SetUp(boost::optional< std::string > iGameFilePath)
	{
		orwell::Application::CommandLineParameters aCommandLineArguments;
		aCommandLineArguments.m_publisherPort = 9001;
		aCommandLineArguments.m_pullerPort = 9000;
		aCommandLineArguments.m_replierPort = m_replierPort;
		aCommandLineArguments.m_agentPort = m_agentPort;
		aCommandLineArguments.m_tickInterval = 500;
		aCommandLineArguments.m_gameDuration = 300;
		aCommandLineArguments.m_dryRun = true;
		aCommandLineArguments.m_broadcast = false;
		aCommandLineArguments.m_gameDuration = gGameDuration;
		if (iGameFilePath)
		{
			aCommandLineArguments.m_gameFilePath = *iGameFilePath;
		}

		Arguments aArguments = Common::GetArguments(
				aCommandLineArguments, true);
		orwell::Application::Parameters aParameters;
		orwell::Application::ReadParameters(
				aArguments.m_argc,
				aArguments.m_argv,
				aParameters);
		m_application.reset(new orwell::Application());
		m_application->run(aParameters);
	}

	std::unique_ptr< orwell::Application > m_application;
	uint16_t const m_agentPort;
	uint16_t const m_replierPort;
};

TEST_F(TestAgentProxy, Test1)
{
	TestAgent aTestAgent(m_agentPort);
	ORWELL_LOG_DEBUG("test_1");
	orwell::proxy::AgentProxy aAgentProxy(*m_application);
	std::string aAgentReply;
	std::string aTeamList;
	std::string aPlayerList;
	std::string aRobotList;
	std::string const aFakeAddress("1.2.3.4");
	std::string const aTeamName = "TEAM";
	EXPECT_TRUE(aAgentProxy.step("add team " + aTeamName, aAgentReply));
	// view team {
	EXPECT_TRUE(aAgentProxy.step("view team TEAM", aAgentReply));
	std::string aExpectedTeam(R"(Team TEAM:
	score = 0 ; robots = [])");
	EXPECT_EQ(aAgentReply, aExpectedTeam) << "view team KO";
	// } view team
	EXPECT_TRUE(aAgentProxy.step("add player Player1", aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("add robot Robot1 TEAM", aAgentReply));
	// list team {
	EXPECT_TRUE(aAgentProxy.step("list team", aTeamList));
	ORWELL_LOG_DEBUG("aTeamList = " << aTeamList);
	std::string aExpectedTeamList(R"(Teams:
	TEAM
)");
	ASSERT_EQ(aTeamList, aExpectedTeamList) << "list team KO";
	// } list team
	// list player {
	EXPECT_TRUE(aAgentProxy.step("list player", aPlayerList));
	ORWELL_LOG_DEBUG("aPlayerList = " << aPlayerList);
	std::string aExpectedPlayerList(R"(Players:
	Player1 -> Player name = Player1 ; address =  ; robot =
)");
	EXPECT_EQ(aPlayerList, aExpectedPlayerList) << "list player KO";
	// } list player
	// get / set player {
	EXPECT_TRUE(aAgentProxy.step("get player Player1", aAgentReply));
	ORWELL_LOG_DEBUG("Player1 = " << aAgentReply);
	{
		std::string const aExpectedPlayer(
				R"(Player name = Player1 ; address =  ; robot = )");
		EXPECT_EQ(aAgentReply, aExpectedPlayer) << "get player KO";
	}
	EXPECT_TRUE(
			aAgentProxy.step("set player Player1 address " + aFakeAddress,
				aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("get player Player1", aAgentReply));
	ORWELL_LOG_DEBUG("Player1 = " << aAgentReply);
	{
		std::string const aExpectedPlayer = Common::Replace(
				R"(Player name = Player1 ; address = %address% ; robot = )",
				std::vector< Common::Replacement >{
				Common::Replacement { "%address%", aFakeAddress }
				}
				);
		EXPECT_EQ(aAgentReply, aExpectedPlayer)
			<< "get player (with address) KO";
	}
	// } get / set player
	// list robot {
	EXPECT_TRUE(aAgentProxy.step("list robot", aRobotList));
	ORWELL_LOG_DEBUG("aRobotList = " << aRobotList);
	std::string aExpectedRobotList(R"(Robots:
	Robot1 -> Robot name = Robot1 ; not registered ; video_url =  ; player =
)");
	EXPECT_EQ(aRobotList, aExpectedRobotList) << "list robot KO";
	// } list robot
	// register robot {
	EXPECT_TRUE(aAgentProxy.step("register robot Robot1", aAgentReply));
	// make sure that Robot1 is now registered
	EXPECT_TRUE(aAgentProxy.step("list robot", aRobotList));
	ORWELL_LOG_DEBUG("aRobotList = " << aRobotList);
	aExpectedRobotList = (R"(Robots:
	Robot1 -> Robot name = Robot1 ; registered ; video_url =  ; player =
)");
	EXPECT_EQ(aRobotList, aExpectedRobotList) << "register KO";
	// } register robot
	// get robot {
	EXPECT_TRUE(aAgentProxy.step("get robot Robot1", aAgentReply));
	ORWELL_LOG_DEBUG("Robot1 = " << aAgentReply);
	std::string const aExpectedRobot =
		(R"(Robot name = Robot1 ; registered ; video_url =  ; player = )");
	EXPECT_EQ(aAgentReply, aExpectedRobot) << "get robot KO";
	// } get robot
	// set robot {
	EXPECT_TRUE(aAgentProxy.step("set robot Robot1 video_url titi", aAgentReply));
	// } set robot

	orwell::messages::Hello aHelloMessage;
	aHelloMessage.set_name("PlayerWithAddress");
	aHelloMessage.set_address(aFakeAddress);
	orwell::com::RawMessage aMessage(
			"randomid", "Hello", aHelloMessage.SerializeAsString());
	std::string const aRequesterUrl =
		"tcp://127.0.0.1:" + std::to_string(m_replierPort);
	ORWELL_LOG_INFO("create requester");
	zmq::context_t aContext;
	orwell::com::Socket aRequester(
			aRequesterUrl,
			ZMQ_REQ,
			orwell::com::ConnectionMode::CONNECT,
			aContext);
	aRequester.send(aMessage);

	// make the application handle the Hello message
	m_application->loopUntilOneMessageIsProcessed();
	orwell::com::RawMessage aResponse;
	aRequester.receive(aResponse, true);
	EXPECT_EQ(aResponse._type, "Welcome")
		<< "The response to Hello should be Welcome";
	std::string aPlayerAddress;
	EXPECT_TRUE(aAgentProxy.step(
				"get player PlayerWithAddress address", aPlayerAddress));
	EXPECT_EQ(aPlayerAddress, aFakeAddress);
	EXPECT_TRUE(aAgentProxy.step(
				"remove player PlayerWithAddress", aAgentReply));

	// get / set team score {
	std::string const aScore = "2";
	EXPECT_TRUE(aAgentProxy.step("get team " + aTeamName + " score 0", aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("set team " + aTeamName + " score " + aScore, aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("get team " + aTeamName + " score " + aScore, aAgentReply));
	EXPECT_EQ(aScore, aAgentReply);
	// } get / set team score
	// unregister robot {
	EXPECT_TRUE(aAgentProxy.step("unregister robot Robot1", aAgentReply));
	// make sure that Robot1 is now unregistered
	EXPECT_TRUE(aAgentProxy.step("list robot", aRobotList));
	ORWELL_LOG_DEBUG("aRobotList = " << aRobotList);
	aExpectedRobotList = (R"(Robots:
	Robot1 -> Robot name = Robot1 ; not registered ; video_url = titi ; player =
)");
	EXPECT_EQ(aRobotList, aExpectedRobotList) << "unregister KO";
	// } unregister robot
	EXPECT_TRUE(aAgentProxy.step("start game", aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("stop game", aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("remove robot Robot1", aAgentReply));
	// add robot with space in the name {
	EXPECT_TRUE(aAgentProxy.step("add robot \"Robot One\" TEAM", aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("list robot", aRobotList));
	ORWELL_LOG_DEBUG("aRobotList = " << aRobotList);
	std::string aExpectedRobotListWithSpace(R"(Robots:
	Robot One -> Robot name = Robot One ; not registered ; video_url =  ; player =
)");
	EXPECT_EQ(aRobotList, aExpectedRobotListWithSpace) << "list robot KO";
	EXPECT_TRUE(aAgentProxy.step("remove robot \"Robot One\"", aAgentReply));
	// } add robot with space in the name
	// view team {
	EXPECT_TRUE(aAgentProxy.step("view team TEAM", aAgentReply));
	aExpectedTeam = R"(Team TEAM:
	score = 0 ; robots = ["Robot1", "Robot One"])";
	EXPECT_EQ(aAgentReply, aExpectedTeam) << "view team KO";
	// } view team

	EXPECT_TRUE(aAgentProxy.step("remove player Player1", aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("remove team TEAM", aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("list team", aTeamList));
	ORWELL_LOG_DEBUG("aTeamList = " << aTeamList);
	aExpectedTeamList = (R"(Teams:
)");
	EXPECT_EQ(aTeamList, aExpectedTeamList) << "empty team KO";
	EXPECT_TRUE(aAgentProxy.step("list player", aPlayerList));
	ORWELL_LOG_DEBUG("aPlayerList = " << aPlayerList);
	aExpectedPlayerList = (R"(Players:
)");
	EXPECT_EQ(aPlayerList, aExpectedPlayerList) << "empty player KO";
	EXPECT_TRUE(aAgentProxy.step("list robot", aRobotList));
	ORWELL_LOG_DEBUG("aRobotList = " << aRobotList);
	aExpectedRobotList = (R"(Robots:
)");
	EXPECT_EQ(aRobotList, aExpectedRobotList) << "empty robot KO";
	// get and set game duration {
	EXPECT_TRUE(aAgentProxy.step("get game duration", aAgentReply));
	ASSERT_EQ(aAgentReply, std::to_string(gGameDuration));
	std::string const aNewGameDuration = "30";
	EXPECT_TRUE(aAgentProxy.step("set game duration " + aNewGameDuration, aAgentReply));
	EXPECT_TRUE(aAgentProxy.step("get game duration", aAgentReply));
	ASSERT_EQ(aNewGameDuration, aAgentReply);
	EXPECT_TRUE(aAgentProxy.step("get game", aAgentReply));
	std::string const aExpectedGame = Common::Replace(
			R"(Game time = %time% ; running = 0 ; duration = %duration%)",
			std::vector< Common::Replacement >{
			Common::Replacement { "%duration%", aNewGameDuration },
			Common::Replacement { "%time%", aNewGameDuration }
			}
			);
	ASSERT_EQ(aExpectedGame, aAgentReply);
	// } get and set game duration
	EXPECT_TRUE(aAgentProxy.step("stop application", aAgentReply));
}

TEST_F(TestAgentProxy, TestFlags)
{
	SetUp(std::string("orwell-game_test.ini"));
	TestAgent aTestAgent(m_agentPort);
	ORWELL_LOG_DEBUG("test_flags");
	orwell::proxy::AgentProxy aAgentProxy(*m_application);
	std::string aFlagList;
	std::string const aBlueFlag { R"(Item name = blue ; RFID = BBB ; colour = -1 ; team = )" };
	std::string const aGreenFlag { R"(Item name = green ; RFID = GGG ; colour = -1 ; team = )" };
	std::string const aYellowFlag { R"(Item name = yellow ; RFID = YYY ; colour = -1 ; team = )" };
	EXPECT_TRUE(aAgentProxy.step("list flag", aFlagList));
	EXPECT_EQ(
			Common::Replace(
				R"(Flags:
	%blue_flag%
	%green_flag%
	%yellow_flag%
)",
				std::vector< Common::Replacement >{
				Common::Replacement { "%blue_flag%", aBlueFlag },
				Common::Replacement { "%green_flag%", aGreenFlag },
				Common::Replacement { "%yellow_flag%", aYellowFlag },
				}
				),
			aFlagList
			);
}

int main(int argc, char **argv)
{
	return RunTest(argc, argv, "test_agent_proxy");
}

max_stars_repo_name: orwell-int/server-game

max_issues_repo_name: orwell-int/server-game

max_forks_repo_name: orwell-int/server-game