text:
#include <ros/ros.h> //For ROS itself
#include <opencv2/highgui/highgui.hpp> //FIXME Not exactly sure why this one is here; maybe it's for displaying the images that come in?
#include <cv_bridge/cv_bridge.h> //The openCV bridge that image_transport needs
#include <ros/console.h> //This is for ROS_ERROR and stuff.
#include <boost/filesystem.hpp> //For creating directtories if needed
#include <obe_toolset/ImageAndPose.h> //Needed for the custom Image and Pose message type
#include <string>
#include <vector>
//#include <GeographicLib/UTMUPS.hpp> //for conversion from Lat Lon to UTM. In order to get this, download the source, unzip it, cd into it, mkdir build, cd build, cmake .., make, make install
#include <sensor_msgs/NavSatFix.h> //for the mavros NavSatFix message
#include <sensor_msgs/Imu.h> // for the Imu data message
#include <tf/transform_datatypes.h> //for quaternion to yaw

//#include "std_msgs/String.h"
//#define ONEATATIME //if this is defined, it will do one file at a time and pause in between files.

//Global variables and classes that need to be accessed in the callback =(
double curr_lat, prev_lat;
double curr_lon, prev_lon;
double curr_z, prev_z;
ros::Time curr_timestamp, prev_timestamp;
static const double SEARCH_AREA_ALTITUDE = 4.2672; //This needs to be updated for camera agl altitude location calculations to be correct in the Processor nodes. For the competition in MD, it's about 14 feet (from google maps, guestimate)
int fix_wait_ctr = -2;

double curr_yaw;
bool yaw_valid = false;

void orientationCallback(const sensor_msgs::Imu msg)
{
	yaw_valid = true;
	tf::Quaternion quat;
	tf::quaternionMsgToTF(msg.orientation, quat);
	double dummy1, dummy2;
	tf::Matrix3x3(quat).getRPY(dummy1, dummy2, curr_yaw); //this is how we update yaw
}

void locationCallback(const sensor_msgs::NavSatFix msg) //all this does is update the global variables listed above (for location).
{
	if (0) //(msg.status == -1)
	{
		return; //we don't have a fix and can't update anything =/
	}
	else
	{
		if (fix_wait_ctr < 0)
			fix_wait_ctr += 1;
		//move the current data to the old data slot
		prev_lat = curr_lat;
		prev_lon = curr_lon;
		prev_z = curr_z;
		prev_timestamp = curr_timestamp;

		curr_lat = msg.latitude;
		curr_lon = msg.longitude;
		curr_z = msg.altitude - SEARCH_AREA_ALTITUDE; //this is 14 for the base in Maryland (makes since that it's pretty low; it's a naval base that sits on the ocean.
		curr_timestamp = msg.header.stamp;
	}
}

int main(int argc, char** argv)
{
	ros::init(argc, argv, "image_publisher_node");
	ros::NodeHandle n;
	int numOfPipes;
	int currentPipeMinusOne = 0;
	if(!(n.hasParam("numPipes")))
		ROS_INFO("the parameter 'numPipes' for the dispatcher node hasn't been specified; assuming 1 to ensure that no images are lost. This may cause severe back-up issues in a long mission.");
	n.param<int>("numPipes", numOfPipes, 1); //gets the numPipes param (so that we know where to publish), defaulting to 1 if it can't be read.

	n.subscribe("/mavros/global_position/global", 0, locationCallback);
	std::vector<ros::Publisher> impose_pub_vector(numOfPipes); //vector of publishers
	for(int i = 1; i <= numOfPipes; ++i)
	{
		std::string topic("obe/imagePipe");
		topic += std::to_string(i);
		impose_pub_vector[i-1] = n.advertise<obe_toolset::ImageAndPose>(topic.c_str(), 512); //publishes to the obe/imagePipe<i> and buffers up to 512 images per pipe in case it can't send them all that quickly.
	}

	//This block makes sure that the needed directories are set up (I'm pretty sure they should be, since this node might end up running from one of them).
	namespace fs = boost::filesystem;

		//NOTE: Not sure how relative paths will be handled when a launchfile runs this remotely...
	fs::path new_path("../images/new/"); //Will be used to get images.
	fs::path processed_path("../images/processed/");
	fs::path roi_path("../images/rois/");
	fs::path error_path("../images/unsuccessful/");

	fs::path im_fetch_path(new_path);

	fs::create_directories(im_fetch_path);
	fs::create_directories(processed_path);
	fs::create_directories(roi_path);
	fs::create_directories(error_path);
	//NOTE:: IF THERE IS AN ISSUE WITH PERMISSIONS FOR SOME REASON, IT MIGHT BE THAT THE LINES OF CODE ABOVE ARE REMOVING EXECUTE PERMISSIONS. JUST SOMETHING TO CONSIDER

	if (!(fs::exists(im_fetch_path)))
	{
		//If it doesn't exist, something went horribly wrong =/
		ROS_ERROR("Oh no. '%s' isn't a directory =(", im_fetch_path.string().c_str());
		return(-1);
	}
	else if (fs::is_regular_file(im_fetch_path))
	{
		ROS_ERROR("Oh no. '%s' is a regular file =(", im_fetch_path.string().c_str());
		return(-1);
	}

	#ifdef ONEATATIME
	ros::Rate loop_rate(.25);
	#else
	ros::Rate loop_rate(25); //rate is the number of outer loop iterations per second
	//Also, we need the loop rate to be relatively quick becuase we don't want delay in dispatching images. Delay in dispatching images could lead to wasted execution time and potential incorrect location stamps.
	#endif //ONEATATIME

	while(n.ok())
	{
		//We need to first make sure that the GPS Fix is ready (should take 1 second if the GPS is already "warmed up"
		if(fix_wait_ctr)
		{
			ROS_INFO_THROTTLE(5,"Waiting for GPS Fix"); //Display at most once every 5 seconds
		}
		else
		{
			//We need to dispatch each of the images in the new directory
			fs::directory_iterator end_itr;
			for(fs::directory_iterator cur_path_itr(im_fetch_path); cur_path_itr != end_itr; cur_path_itr++)
			{
				ROS_INFO("I'm looking at this file: %s", cur_path_itr->path().string().c_str());
				if(fs::is_directory(cur_path_itr->path()))
				{
					ROS_INFO_STREAM_ONCE("There's a directory in the ~/images/new path; it is being moved to the error folder.");
					fs::rename(cur_path_itr->path(), error_path / cur_path_itr->path().filename());
					//FIXME Don't forget to move this file to the folder for files with errors.

				}
				else
				{
					cv::Mat newImage = cv::imread(cur_path_itr->path().string(), CV_LOAD_IMAGE_COLOR);

					if(newImage.data == NULL)//The image was read improperly if this fails...
					{
						ROS_ERROR("I was unable to read the image file.");
						fs::rename(cur_path_itr->path(), error_path / cur_path_itr->path().filename());
					}
					else
					{
						obe_toolset::ImageAndPose impose_msg; //This is the custom message type that has a sensor_msgs::Image msg and a std_msgs::Pose message.
						impose_msg.image = *(cv_bridge::CvImage(std_msgs::Header(), "bgr8", newImage).toImageMsg()); //The meat of this line is from the image_transport tutorial; I just de-reference their piece to get a sensor_msgs::Image.  Note: There's probably a better way to do this, but it will work for now.

						//This is the point where the fakeing things comes in.
						ros::Duration elapsedTime = curr_timestamp - prev_timestamp;
						double lat_offset = (2 / elapsedTime.toSec()) * (curr_lat - prev_lat); //the "2" is from Rick's estimate of time between when an image is captured and when it is finally done uploading.
						impose_msg.lat = curr_lat - lat_offset; //approximates a latitude value (linear approximation based on 2 most recent locations)
						double lon_offset = (2 / elapsedTime.toSec()) * (curr_lon - prev_lon);
						impose_msg.lon = curr_lon - lon_offset;
						double z_offset = (2 / elapsedTime.toSec()) * (curr_z - prev_z);
						impose_msg.z = curr_z - z_offset; //This is actually a decent guess (~200 ft)
						impose_msg.roll = 0.0;
						impose_msg.pitch = 0.0;
						//Concerning Yaw: we really should be using the /mavros/imu/data to give us the yaw, particularly because the plane could be "crabbing" (flying in a direction different than the one it's pointing due to wind)
						//But for now, it's simply found by
						impose_msg.yaw = 92929292; //this is the only one that's used as of 4.26.17
						//End the faking it stuff.

						//publish to the current pipe that's due for another message. NOTE: In the future, this could have a system that keeps track of busy nodes so that no particular node gets bogged down. I'm kind of assuming that we have enough nodes and a fast enough ROI algorithm and randomness is on our side so that this doesn't get out of hand.
						impose_pub_vector[currentPipeMinusOne].publish(impose_msg); //send the impose message.

						//set up the current pipe for the next time we publish something.
						currentPipeMinusOne++;
						currentPipeMinusOne %= numOfPipes; //we want to wrap around

						//Now that we've published it, we can move the file to the processed folder
						fs::rename(cur_path_itr->path(), processed_path / cur_path_itr->path().filename());
						#ifdef ONEATATIME
						break;
						#endif
					}
				}
			} //Ends the for loop
		}//ends the if statement that waits for a GPS Fix
		ros::spinOnce();
		loop_rate.sleep();
	}
	//It shouldn't get here until you hit ctrl-C, but we still need to specify a return value:
	return 0;
}


text:
#ifndef HERMIT_FORMAT_CONVERT_MESSAGEPACK_TO_JSON_HPP
#define HERMIT_FORMAT_CONVERT_MESSAGEPACK_TO_JSON_HPP

#include <string>
#include <vector>
#include <cstdint>
#include <hermit/json.hpp>
#include <hermit/messagepack.hpp>
#include <boost/variant.hpp>
#include <hermit/format/read/utf32.hpp>

namespace hermit {
  namespace format {
    namespace convert {
      struct messagepack2json : public boost::static_visitor<hermit::json> {
	hermit::json operator()( const std::vector< uint8_t > &src ) const {
          const auto str = hermit::format::read_utf32be( src );
          if( !str ) {
            return "";
          }
          return *str;
        }
	hermit::json operator()( uint8_t src ) const {
          return static_cast< double >( src );
        }
	hermit::json operator()( int8_t src ) const {
          return static_cast< double >( src );
        }
	hermit::json operator()( uint16_t src ) const {
          return static_cast< double >( src );
        }
	hermit::json operator()( int16_t src ) const {
          return static_cast< double >( src );
        }
	hermit::json operator()( uint32_t src ) const {
          return static_cast< double >( src );
        }
	hermit::json operator()( int32_t src ) const {
          return static_cast< double >( src );
        }
	hermit::json operator()( uint64_t src ) const {
          return static_cast< double >( src );
        }
	hermit::json operator()( int64_t src ) const {
          return static_cast< double >( src );
        }
	hermit::json operator()( float src ) const {
          return static_cast< double >( src );
        }
	hermit::json operator()( double src ) const {
          return src;
        }
	hermit::json operator()( const std::map< hermit::messagepack, hermit::messagepack > &src ) const {
          std::map< std::u32string, hermit::json > temp;
          std::transform( src.begin(), src.end(), std::inserter( temp, temp.end() ),
            []( const std::pair< hermit::messagepack, hermit::messagepack > &elem ) -> std::pair< std::u32string, hermit::json > {
              const auto name = hermit::format::read_utf32be( boost::get< std::vector< uint8_t > >( elem.first ) );
              if( !name ) {
                return std::make_pair( std::u32string(), apply_visitor( messagepack2json(), elem.second ) );
              }
              return std::make_pair( *name, apply_visitor( messagepack2json(), elem.second ) );
            }
          );
          return temp;
        }
	hermit::json operator()( const std::vector< hermit::messagepack > &src ) const {
          std::vector< hermit::json > temp;
          std::transform( src.begin(), src.end(), std::back_inserter( temp ),
            []( const hermit::messagepack &elem ) {
              return apply_visitor( messagepack2json(), elem );
            }
          );
          return temp;
        }
	hermit::json operator()( bool src ) const {
          return src;
        }
	hermit::json operator()( const hermit::none_type &src ) const {
          return src;
        }
      };
    }
    hermit::json convert_messagepack_to_json( const hermit::messagepack &src ) {
      return apply_visitor( convert::messagepack2json(), src );
    }
  }
}

#endif

ext: hpp

max_stars_repo_name: Fadis/hermit

max_issues_repo_name: Fadis/hermit

max_forks_repo_name: Fadis/hermit


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

#ifndef BOOST_INTRUSIVE_PACK_OPTIONS_HPP
#define BOOST_INTRUSIVE_PACK_OPTIONS_HPP

#include <boost/intrusive/detail/config_begin.hpp>

#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

namespace boost {
namespace intrusive {

#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED

#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)

template<class Prev, class Next>
struct do_pack
{
   //Use "pack" member template to pack options
   typedef typename Next::template pack<Prev> type;
};

template<class Prev>
struct do_pack<Prev, void>
{
   //Avoid packing "void" to shorten template names
   typedef Prev type;
};

template
   < class DefaultOptions
   , class O1         = void
   , class O2         = void
   , class O3         = void
   , class O4         = void
   , class O5         = void
   , class O6         = void
   , class O7         = void
   , class O8         = void
   , class O9         = void
   , class O10        = void
   , class O11        = void
   >
struct pack_options
{
   // join options
   typedef
      typename do_pack
      <  typename do_pack
         <  typename do_pack
            <  typename do_pack
               <  typename do_pack
                  <  typename do_pack
                     <  typename do_pack
                        <  typename do_pack
                           <  typename do_pack
                              <  typename do_pack
                                 <  typename do_pack
                                    < DefaultOptions
                                    , O1
                                    >::type
                                 , O2
                                 >::type
                              , O3
                              >::type
                           , O4
                           >::type
                        , O5
                        >::type
                     , O6
                     >::type
                  , O7
                  >::type
               , O8
               >::type
            , O9
            >::type
         , O10
         >::type
      , O11
      >::type
   type;
};
#else

//index_tuple
template<int... Indexes>
struct index_tuple{};

//build_number_seq
template<std::size_t Num, typename Tuple = index_tuple<> >
struct build_number_seq;

template<std::size_t Num, int... Indexes>
struct build_number_seq<Num, index_tuple<Indexes...> >
   : build_number_seq<Num - 1, index_tuple<Indexes..., sizeof...(Indexes)> >
{};

template<int... Indexes>
struct build_number_seq<0, index_tuple<Indexes...> >
{  typedef index_tuple<Indexes...> type;  };

template<class ...Types>
struct typelist
{};

//invert_typelist
template<class T>
struct invert_typelist;

template<int I, typename Tuple>
struct typelist_element;

template<int I, typename Head, typename... Tail>
struct typelist_element<I, typelist >
{
   typedef typename typelist_element<I-1, typelist<Tail...> >::type type;
};

template<typename Head, typename... Tail>
struct typelist_element<0, typelist >
{
   typedef Head type;
};

template<int ...Ints, class ...Types>
typelist<typename typelist_element<(sizeof...(Types) - 1) - Ints, typelist<Types...> >::type...>
   inverted_typelist(index_tuple<Ints...>, typelist<Types...>)
{
   return typelist<typename typelist_element<(sizeof...(Types) - 1) - Ints, typelist<Types...> >::type...>();
}

//sizeof_typelist
template<class Typelist>
struct sizeof_typelist;

template<class ...Types>
struct sizeof_typelist< typelist<Types...> >
{
   static const std::size_t value = sizeof...(Types);
};

//invert_typelist_impl
template<class Typelist, class Indexes>
struct invert_typelist_impl;

template<class Typelist, int ...Ints>
struct invert_typelist_impl< Typelist, index_tuple<Ints...> >
{
   static const std::size_t last_idx = sizeof_typelist<Typelist>::value - 1;
   typedef typelist
      <typename typelist_element<last_idx - Ints, Typelist>::type...> type;
};

template<class Typelist, int Int>
struct invert_typelist_impl< Typelist, index_tuple<Int> >
{
   typedef Typelist type;
};

template<class Typelist>
struct invert_typelist_impl< Typelist, index_tuple<> >
{
   typedef Typelist type;
};

//invert_typelist
template<class Typelist>
struct invert_typelist;

template<class ...Types>
struct invert_typelist< typelist<Types...> >
{
   typedef typelist<Types...> typelist_t;
   typedef typename build_number_seq<sizeof...(Types)>::type indexes_t;
   typedef typename invert_typelist_impl<typelist_t, indexes_t>::type type;
};

//Do pack
template<class Typelist>
struct do_pack;

template<>
struct do_pack<typelist<> >;

template<class Prev>
struct do_pack<typelist<Prev> >
{
   typedef Prev type;
};

template<class Prev, class Last>
struct do_pack<typelist<Prev, Last> >
{
   typedef typename Prev::template pack<Last> type;
};

template<class ...Others>
struct do_pack<typelist<void, Others...> >
{
   typedef typename do_pack<typelist<Others...> >::type type;
};

template<class Prev, class ...Others>
struct do_pack<typelist<Prev, Others...> >
{
   typedef typename Prev::template pack
      <typename do_pack<typelist<Others...> >::type> type;
};

template<class DefaultOptions, class ...Options>
struct pack_options
{
   typedef typelist<DefaultOptions, Options...> typelist_t;
   typedef typename invert_typelist<typelist_t>::type inverted_typelist;
   typedef typename do_pack<inverted_typelist>::type type;
};

#endif   //!defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)

#define BOOST_INTRUSIVE_OPTION_TYPE(OPTION_NAME, TYPE, TYPEDEF_EXPR, TYPEDEF_NAME) \
template< class TYPE> \
struct OPTION_NAME \
{ \
   template<class Base> \
   struct pack : Base \
   { \
      typedef TYPEDEF_EXPR TYPEDEF_NAME; \
   }; \
}; \
//

#define BOOST_INTRUSIVE_OPTION_CONSTANT(OPTION_NAME, TYPE, VALUE, CONSTANT_NAME) \
template< TYPE VALUE> \
struct OPTION_NAME \
{ \
   template<class Base> \
   struct pack : Base \
   { \
      static const TYPE CONSTANT_NAME = VALUE; \
   }; \
}; \
//

#else    //#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED

//! This class is a utility that takes:
//!   - a default options class defining initial static constant
//!   and typedefs
//!   - several options defined with BOOST_INTRUSIVE_OPTION_CONSTANT and
//! BOOST_INTRUSIVE_OPTION_TYPE
//!
//! and packs them together in a new type that defines all options as
//! member typedefs or static constant values. Given options of form:
//!
//! \code
//!   BOOST_INTRUSIVE_OPTION_TYPE(my_pointer, VoidPointer, VoidPointer, my_pointer_type)
//!   BOOST_INTRUSIVE_OPTION_CONSTANT(incremental, bool, Enabled, is_incremental)
//! \endcode
//!
//! the following expression
//!
//! \code
//!
//! struct default_options
//! {
//!   typedef long      int_type;
//!   static const int  int_constant = -1;
//! };
//!
//! pack_options< default_options, my_pointer<void*>, incremental<true> >::type
//! \endcode
//!
//! will create a type that will contain the following typedefs/constants
//!
//! \code
//!   struct unspecified_type
//!   {
//!      //Default options
//!      typedef long      int_type;
//!      static const int  int_constant  = -1;
//!
//!      //Packed options (will ovewrite any default option)
//!      typedef void*     my_pointer_type;
//!      static const bool is_incremental = true;
//!   };
//! \endcode
//!
//! If an option is specified in the default options argument and later
//! redefined as an option, the last definition will prevail.
template<class DefaultOptions, class ...Options>
struct pack_options
{
   typedef unspecified_type type;
};

//! Defines an option class of name OPTION_NAME that can be used to specify a type
//! of type TYPE...
//!
//! \code
//! struct OPTION_NAME<class TYPE>
//! {  unspecified_content  };
//! \endcode
//!
//! ...that after being combined with
//! boost::intrusive::pack_options,
//! will typedef TYPE as a typedef of name TYPEDEF_NAME. Example:
//!
//! \code
//!   //[includes and namespaces omitted for brevity]
//!
//!   //This macro will create the following class:
//!   //    template<class VoidPointer>
//!   //    struct my_pointer
//!   //    { unspecified_content };
//!   BOOST_INTRUSIVE_OPTION_TYPE(my_pointer, VoidPointer, boost::remove_pointer<VoidPointer>::type, my_pointer_type)
//!
//!   struct empty_default{};
//!
//!   typedef pack_options< empty_default, typename my_pointer<void*> >::type::my_pointer_type type;
//!
//!   BOOST_STATIC_ASSERT(( boost::is_same<type, void>::value ));
//!
//! \endcode
#define BOOST_INTRUSIVE_OPTION_TYPE(OPTION_NAME, TYPE, TYPEDEF_EXPR, TYPEDEF_NAME)

//! Defines an option class of name OPTION_NAME that can be used to specify a constant
//! of type TYPE with value VALUE...
//!
//! \code
//! struct OPTION_NAME<TYPE VALUE>
//! {  unspecified_content  };
//! \endcode
//!
//! ...that after being combined with
//! boost::intrusive::pack_options,
//! will contain a CONSTANT_NAME static constant of value VALUE. Example:
//!
//! \code
//!   //[includes and namespaces omitted for brevity]
//!
//!   //This macro will create the following class:
//!   //    template<bool Enabled>
//!   //    struct incremental
//!   //    { unspecified_content };
//!   BOOST_INTRUSIVE_OPTION_CONSTANT(incremental, bool, Enabled, is_incremental)
//!
//!   struct empty_default{};
//!
//!   const bool is_incremental = pack_options< empty_default, incremental<true> >::type::is_incremental;
//!
//!   BOOST_STATIC_ASSERT(( is_incremental == true ));
//!
//! \endcode
#define BOOST_INTRUSIVE_OPTION_CONSTANT(OPTION_NAME, TYPE, VALUE, CONSTANT_NAME)

#endif   //#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED

}  //namespace intrusive {
}  //namespace boost {

#include <boost/intrusive/detail/config_end.hpp>

#endif   //#ifndef BOOST_INTRUSIVE_PACK_OPTIONS_HPP

max_stars_repo_name: jason-fox/Fast-RTPS

max_issues_repo_name: jason-fox/Fast-RTPS

max_forks_repo_name: jason-fox/Fast-RTPS


text:
/*
 *  This file is part of Poedit (http://poedit.net)
 *
 *  Copyright (C) 2013-2014 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "transmem.h"

#include "catalog.h"
#include "errors.h"

#include <wx/stdpaths.h>
#include <wx/utils.h>
#include <wx/dir.h>
#include <wx/filename.h>

#include <mutex>

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/name_generator.hpp>
#include <boost/uuid/string_generator.hpp>

#include <Lucene.h>
#include <LuceneException.h>
#include <MMapDirectory.h>
#include <SimpleFSDirectory.h>
#include <StandardAnalyzer.h>
#include <IndexWriter.h>
#include <IndexSearcher.h>
#include <IndexReader.h>
#include <Document.h>
#include <Field.h>
#include <StringUtils.h>
#include <TermQuery.h>
#include <BooleanQuery.h>
#include <PhraseQuery.h>
#include <Term.h>
#include <ScoreDoc.h>
#include <TopDocs.h>
#include <StringReader.h>
#include <TokenStream.h>
#include <TermAttribute.h>

using namespace Lucene;

#define CATCH_AND_RETHROW_EXCEPTION                                 \
    catch (LuceneException& e)                                      \
    {                                                               \
        throw Exception(wxString::Format("%s (%d)",                 \
                        e.getError(), (int)e.getType()));           \
    }                                                               \
    catch (std::exception& e)                                       \
    {                                                               \
        throw Exception(e.what());                                  \
    }

// ----------------------------------------------------------------
// TranslationMemoryImpl
// ----------------------------------------------------------------

class TranslationMemoryImpl
{
public:
    static const int DEFAULT_MAXHITS = 10;

    typedef TranslationMemory::Results Results;

#ifdef __WXMSW__
    typedef SimpleFSDirectory DirectoryType;
#else
    typedef MMapDirectory DirectoryType;
#endif

    TranslationMemoryImpl()
        : m_dir(newLucene<DirectoryType>(GetDatabaseDir())),
          m_analyzer(newLucene<StandardAnalyzer>(LuceneVersion::LUCENE_CURRENT))
    {}

    bool Search(const std::wstring& lang,
                const std::wstring& source,
                Results& results,
                int maxHits = -1);

    std::shared_ptr<TranslationMemory::Writer> CreateWriter();

    void GetStats(long& numDocs, long& fileSize);

private:
    static std::wstring GetDatabaseDir();
    IndexReaderPtr Reader();
    SearcherPtr Searcher();

private:
    DirectoryPtr     m_dir;
    AnalyzerPtr      m_analyzer;
    IndexReaderPtr   m_reader;
    std::mutex       m_readerMutex;
};

std::wstring TranslationMemoryImpl::GetDatabaseDir()
{
    wxString data;
#if defined(__UNIX__) && !defined(__WXMAC__)
    if ( !wxGetEnv("XDG_DATA_HOME", &data) )
        data = wxGetHomeDir() + "/.local/share";
    data += "/poedit";
#else
    data = wxStandardPaths::Get().GetUserDataDir();
#endif

    // ensure the parent directory exists:
    wxFileName::Mkdir(data, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);

    data += wxFILE_SEP_PATH;
    data += "TranslationMemory";

    return data.ToStdWstring();
}

IndexReaderPtr TranslationMemoryImpl::Reader()
{
    std::lock_guard<std::mutex> guard(m_readerMutex);
    if ( m_reader )
        m_reader = m_reader->reopen();
    else
        m_reader = IndexReader::open(m_dir, true);
    return m_reader;
}

namespace
{

// Normalized score that must be met for a suggestion to be shown. This is
// an empirical guess of what constitues good matches.
static const double QUALITY_THRESHOLD = 0.6;

// Maximum allowed difference in phrase length, in #terms.
static const int MAX_ALLOWED_LENGTH_DIFFERENCE = 2;

template<typename T>
void PerformSearchWithBlock(IndexSearcherPtr searcher,
                            const std::wstring& lang,
                            QueryPtr query,
                            int maxHits,
                            double threshold,
                            T callback)
{
    // TODO: use short form of the language too (cs vs cs_CZ), boost the
    //       full form in the query
    auto langQ = newLucene<TermQuery>(newLucene<Term>(L"lang", lang));
    auto fullQuery = newLucene<BooleanQuery>();
    fullQuery->add(langQ, BooleanClause::MUST);
    fullQuery->add(query, BooleanClause::MUST);

    auto hits = searcher->search(fullQuery, maxHits);

    for (int i = 0; i < hits->scoreDocs.size(); i++)
    {
        const auto& scoreDoc = hits->scoreDocs[i];
        auto score = scoreDoc->score / hits->maxScore;
        if (score < threshold)
            continue;
        callback(searcher->doc(scoreDoc->doc));
    }
}

void PerformSearch(IndexSearcherPtr searcher,
                   const std::wstring& lang,
                   QueryPtr query,
                   TranslationMemory::Results& results, int maxHits,
                   double threshold = 1.0)
{
    PerformSearchWithBlock
    (
        searcher, lang, query, maxHits, threshold,
        [&results](DocumentPtr doc)
        {
            auto t = doc->get(L"trans");
            if (std::find(results.begin(), results.end(), t) == results.end())
                results.push_back(t);
        }
    );
}

} // anonymous namespace

bool TranslationMemoryImpl::Search(const std::wstring& lang,
                                   const std::wstring& source,
                                   Results& results,
                                   int maxHits)
{
    try
    {
        if (maxHits <= 0)
            maxHits = DEFAULT_MAXHITS;

        results.clear();

        const Lucene::String fieldName(L"source");
        auto boolQ = newLucene<BooleanQuery>();
        auto phraseQ = newLucene<PhraseQuery>();

        auto stream = m_analyzer->tokenStream(fieldName, newLucene<StringReader>(source));
        int sourceTokensCount = 0;
        while (stream->incrementToken())
        {
            sourceTokensCount++;
            auto word = stream->getAttribute<TermAttribute>()->term();
            auto term = newLucene<Term>(fieldName, word);
            boolQ->add(newLucene<TermQuery>(term), BooleanClause::SHOULD);
            phraseQ->add(term);
        }

        auto searcher = newLucene<IndexSearcher>(Reader());

        // Try exact phrase first:
        PerformSearch(searcher, lang, phraseQ, results, maxHits);
        if (!results.empty())
            return true;

        // Then, if no matches were found, permit being a bit sloppy:
        phraseQ->setSlop(1);
        PerformSearch(searcher, lang, phraseQ, results, maxHits);
        if (!results.empty())
            return true;

        // As the last resort, try terms search. This will almost certainly
        // produce low-quality results, but hopefully better than nothing.
        boolQ->setMinimumNumberShouldMatch(std::max(1, boolQ->getClauses().size() - MAX_ALLOWED_LENGTH_DIFFERENCE));
        PerformSearchWithBlock
        (
            searcher, lang, boolQ, maxHits, QUALITY_THRESHOLD,
            [=,&results](DocumentPtr doc)
            {
                auto s = doc->get(fieldName);
                auto t = doc->get(L"trans");
                auto stream2 = m_analyzer->tokenStream(fieldName, newLucene<StringReader>(s));
                int tokensCount2 = 0;
                while (stream2->incrementToken())
                    tokensCount2++;

                if (std::abs(tokensCount2 - sourceTokensCount) <= MAX_ALLOWED_LENGTH_DIFFERENCE &&
                    std::find(results.begin(), results.end(), t) == results.end())
                {
                    results.push_back(t);
                }
            }
        );

        return !results.empty();
    }
    catch (LuceneException&)
    {
        return false;
    }
}

void TranslationMemoryImpl::GetStats(long& numDocs, long& fileSize)
{
    try
    {
        auto reader = Reader();
        numDocs = reader->numDocs();
        fileSize = wxDir::GetTotalSize(GetDatabaseDir()).GetValue();
    }
    CATCH_AND_RETHROW_EXCEPTION
}

// ----------------------------------------------------------------
// TranslationMemoryWriterImpl
// ----------------------------------------------------------------

class TranslationMemoryWriterImpl : public TranslationMemory::Writer
{
public:
    TranslationMemoryWriterImpl(DirectoryPtr dir, AnalyzerPtr analyzer)
    {
        m_writer = newLucene<IndexWriter>(dir, analyzer, IndexWriter::MaxFieldLengthLIMITED);
    }

    ~TranslationMemoryWriterImpl()
    {
        if (m_writer)
            m_writer->rollback();
    }

    virtual void Commit()
    {
        try
        {
            m_writer->close();
            m_writer.reset();
        }
        CATCH_AND_RETHROW_EXCEPTION
    }

    virtual void Insert(const std::wstring& lang,
                        const std::wstring& source,
                        const std::wstring& trans)
    {
        if (lang.empty())
            return;

        // Compute unique ID for the translation:

        static const boost::uuids::uuid s_namespace =
          boost::uuids::string_generator()("6e3f73c5-333f-4171-9d43-954c372a8a02");
        boost::uuids::name_generator gen(s_namespace);

        std::wstring itemId(L"en"); // TODO: srclang
        itemId += lang;
        itemId += source;
        itemId += trans;

        const std::wstring itemUUID = boost::uuids::to_wstring(gen(itemId));

        try
        {
            // Then add a new document:
            auto doc = newLucene<Document>();

            doc->add(newLucene<Field>(L"uuid", itemUUID,
                                      Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
            doc->add(newLucene<Field>(L"srclang", L"en",
                                      Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
            doc->add(newLucene<Field>(L"lang", lang,
                                      Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
            doc->add(newLucene<Field>(L"source", source,
                                      Field::STORE_YES, Field::INDEX_ANALYZED));
            doc->add(newLucene<Field>(L"trans", trans,
                                      Field::STORE_YES, Field::INDEX_NOT_ANALYZED));

            m_writer->updateDocument(newLucene<Term>(L"uuid", itemUUID), doc);
        }
        CATCH_AND_RETHROW_EXCEPTION
    }

    virtual void Insert(const Catalog &cat)
    {
        const std::string lang = cat.GetLanguage().Code();
        if (lang.empty())
            return;
        const std::wstring wlang(lang.begin(), lang.end());

        int cnt = cat.GetCount();
        for (int i = 0; i < cnt; i++)
        {
            const CatalogItem& item = cat[i];

            // ignore translations with errors in them
            if (item.GetValidity() == CatalogItem::Val_Invalid)
                continue;

            // can't handle plurals yet (TODO?)
            if (item.HasPlural())
                continue;

            // ignore untranslated or unfinished translations
            if (item.IsFuzzy() || !item.IsTranslated())
                continue;

            // Note that dt.IsModified() is intentionally not checked - we
            // want to save old entries in the TM too, so that we harvest as
            // much useful translations as we can.

            Insert(wlang, item.GetString(), item.GetTranslation());
        }
    }

private:
    IndexWriterPtr m_writer;
};

std::shared_ptr<TranslationMemory::Writer> TranslationMemoryImpl::CreateWriter()
{
    try
    {
        return std::make_shared<TranslationMemoryWriterImpl>(m_dir, m_analyzer);
    }
    CATCH_AND_RETHROW_EXCEPTION
}

// ----------------------------------------------------------------
// Singleton management
// ----------------------------------------------------------------

TranslationMemory *TranslationMemory::ms_instance = nullptr;

TranslationMemory& TranslationMemory::Get()
{
    if (!ms_instance)
    {
        try
        {
            ms_instance = new TranslationMemory;
        }
        CATCH_AND_RETHROW_EXCEPTION
    }
    return *ms_instance;
}

void TranslationMemory::CleanUp()
{
    if (ms_instance)
    {
        delete ms_instance;
        ms_instance = nullptr;
    }
}

TranslationMemory::TranslationMemory() : m_impl(new TranslationMemoryImpl) {}
TranslationMemory::~TranslationMemory() { delete m_impl; }

// ----------------------------------------------------------------
// public API
// ----------------------------------------------------------------

bool TranslationMemory::Search(const std::wstring& lang,
                               const std::wstring& source,
                               Results& results,
                               int maxHits)
{
    return m_impl->Search(lang, source, results, maxHits);
}

std::shared_ptr<TranslationMemory::Writer> TranslationMemory::CreateWriter()
{
    return m_impl->CreateWriter();
}

void TranslationMemory::GetStats(long& numDocs, long& fileSize)
{
    m_impl->GetStats(numDocs, fileSize);
}

ext: cpp

max_stars_repo_name: laborautonomo/poedit

max_issues_repo_name: laborautonomo/poedit

max_forks_repo_name: laborautonomo/poedit


text:
//
// GraphTools library
// Copyright 2017-2019 Illumina, Inc.
// All rights reserved.
//
// Author: Felix Schlesinger <fschlesinger@illumina.com>
//
// 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.
//

#include "graphcore/GraphReferenceMapping.hh"

#include <boost/algorithm/string.hpp>
#include <unordered_map>

#include "graphcore/GraphCoordinates.hh"
#include "graphcore/PathOperations.hh"
#include "graphutils/IntervalList.hh"

using std::string;

namespace graphtools
{

ReferenceInterval::ReferenceInterval(ContigId const contig, Position const start, Position const end)
    : contig(contig)
    , start(start)
    , end(end)
{
    if ((start < 0) || (start > end))
    {
        throw std::logic_error("Invalid Interval");
    }
}
ReferenceInterval ReferenceInterval::makePosition(ContigId const& contig, Position const pos)
{
    return ReferenceInterval(contig, pos, pos);
}

ReferenceInterval ReferenceInterval::parseRegion(std::string const& regionString)
{
    std::vector<std::string> spl;
    boost::split(spl, regionString, boost::is_any_of(":"));
    if (spl.size() != 2)
    {
        throw std::runtime_error("Invalid workflow string: " + regionString);
    }
    string const contig = spl[0];
    boost::replace_all(spl[1], ",", "");
    boost::split(spl, spl[1], boost::is_any_of("-"));
    if (spl.size() != 2)
    {
        throw std::runtime_error("Invalid workflow string: " + regionString);
    }
    int const start = std::stoll(spl[0]);
    int const end = std::stoll(spl[1]);
    return ReferenceInterval(contig, start, end);
}

bool operator<(ReferenceInterval const& lhs, ReferenceInterval const& rhs)
{
    return lhs.contig < rhs.contig || (lhs.contig == rhs.contig && lhs.start < rhs.start)
        || (lhs.contig == rhs.contig && lhs.start == rhs.start && lhs.end < rhs.end);
}
bool operator==(ReferenceInterval const& lhs, ReferenceInterval const& rhs)
{
    return lhs.contig == rhs.contig && lhs.start == rhs.start && lhs.end == rhs.end;
}
std::ostream& operator<<(std::ostream& output, ReferenceInterval const& ri)
{
    output << ri.contig << ":" << ri.start << "-" << ri.end;
    return output;
}

int32_t ReferenceInterval::length() const { return end - start; }

NodeReferenceMapping::NodeReferenceMapping(Graph const& graph, NodeId const node, ReferenceInterval const& ref)
    : nodeLength_(graph.nodeSeq(node).length())
    , ref_(ref)
{
    if (nodeLength_ != ref.length())
    {
        throw std::logic_error("Length of node sequence does not match reference map length " + graph.nodeName(node));
    }
}

ReferenceInterval NodeReferenceMapping::map(int32_t const offset) const
{
    if (offset >= nodeLength_)
    {
        throw std::logic_error("Cannot map position outside node");
    }
    return ReferenceInterval::makePosition(ref_.contig, ref_.start + offset);
}

GraphReferenceMapping::GraphReferenceMapping(Graph const* graph)
    : graph_(graph)
{
}

void GraphReferenceMapping::addMapping(NodeId node, ReferenceInterval const& ref)
{
    NodeReferenceMapping const nodeMapping(*graph_, node, ref);
    mappings_.insert({ node, nodeMapping });
}

boost::optional<ReferenceInterval> GraphReferenceMapping::map(NodeId node, int32_t offset) const
{
    if (node >= graph_->numNodes())
    {
        throw std::logic_error("Invalid node " + std::to_string(node));
    }
    auto const& mapping = mappings_.find(node);
    if (mapping != mappings_.end())
    {
        return mapping->second.map(offset);
    }
    return boost::optional<ReferenceInterval>();
}

boost::optional<ReferenceInterval> GraphReferenceMapping::map(Path const& path) const
{
    for (auto const& nodePath : generateSubpathForEachNode(path))
    {
        auto const mapped = map(*nodePath.nodeIds().begin(), nodePath.startPosition());
        if (mapped)
        {
            return mapped;
        }
    }
    return boost::optional<ReferenceInterval>();
}
}

max_stars_repo_name: AlesMaver/ExpansionHunter

max_issues_repo_name: AlesMaver/ExpansionHunter

max_forks_repo_name: AlesMaver/ExpansionHunter


text:
//==================================================================================================
/*!

  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/function/scalar/sinhcosh.hpp>
#include <scalar_test.hpp>
#include <boost/simd/constant/inf.hpp>
#include <boost/simd/constant/minf.hpp>
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/mone.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/constant/mzero.hpp>
#include <boost/simd/function/cosh.hpp>
#include <boost/simd/function/sinh.hpp>

STF_CASE_TPL("sinhcosh", STF_IEEE_TYPES)
{
  namespace bs = boost::simd;
  namespace bd = boost::dispatch;
  using bs::sinhcosh;

  T a[] = {bs::Zero<T>(), bs::One<T>(), T(5), T(-5)};
  size_t N =  sizeof(a)/sizeof(T);
  STF_EXPR_IS( (sinhcosh(T()))
                  , (std::pair<T,T>)
                  );

  {
    for(size_t i=0; i < N; ++i)
    {
      std::pair<T,T> p = sinhcosh(a[i]);
      STF_ULP_EQUAL(p.first,  bs::sinh(a[i]), 1);
      STF_ULP_EQUAL(p.second, bs::cosh(a[i]), 1);
    }
  }

  T b[] = {bs::Inf<T>(), bs::Minf<T>(), bs::Nan<T>()};
  N =  sizeof(b)/sizeof(T);
#ifndef BOOST_SIMD_NO_INVALIDS

  {
    for(size_t i=0; i < N; ++i)
    {
      std::pair<T,T> p = sinhcosh(b[i]);
      STF_ULP_EQUAL(p.first,  bs::sinh(b[i]), 1);
      STF_ULP_EQUAL(p.second, bs::cosh(b[i]), 1);
    }
  }
#endif
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2013-2020 Regents of the University of California.
 *
 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
 *
 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 *
 * You should have received copies of the GNU General Public License and GNU Lesser
 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 */

#include "ndn-cxx/encoding/nfd-constants.hpp"

#include "tests/boost-test.hpp"

#include <boost/lexical_cast.hpp>
#include <iomanip>
#include <sstream>

namespace ndn {
namespace nfd {
namespace tests {

BOOST_AUTO_TEST_SUITE(Encoding)
BOOST_AUTO_TEST_SUITE(TestNfdConstants)

BOOST_AUTO_TEST_CASE(PrintFaceScope)
{
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_SCOPE_NONE), "none");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_SCOPE_NON_LOCAL), "non-local");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_SCOPE_LOCAL), "local");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(static_cast<FaceScope>(126)), "126");
}

BOOST_AUTO_TEST_CASE(PrintFacePersistency)
{
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_PERSISTENCY_NONE), "none");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_PERSISTENCY_ON_DEMAND), "on-demand");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_PERSISTENCY_PERSISTENT), "persistent");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_PERSISTENCY_PERMANENT), "permanent");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(static_cast<FacePersistency>(110)), "110");
}

BOOST_AUTO_TEST_CASE(PrintLinkType)
{
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(LINK_TYPE_NONE), "none");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(LINK_TYPE_POINT_TO_POINT), "point-to-point");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(LINK_TYPE_MULTI_ACCESS), "multi-access");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(LINK_TYPE_AD_HOC), "adhoc");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(static_cast<LinkType>(104)), "104");
}

BOOST_AUTO_TEST_CASE(PrintFaceEventKind)
{
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_EVENT_NONE), "none");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_EVENT_CREATED), "created");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_EVENT_DESTROYED), "destroyed");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_EVENT_UP), "up");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(FACE_EVENT_DOWN), "down");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(static_cast<FaceEventKind>(175)), "175");
}

BOOST_AUTO_TEST_CASE(ParseRouteOrigin)
{
  auto expectSuccess = [] (const std::string& input, RouteOrigin expected) {
    BOOST_TEST_CONTEXT("input = " << std::quoted(input)) {
      std::istringstream is(input);
      RouteOrigin routeOrigin;
      is >> routeOrigin;

      BOOST_CHECK(!is.fail());
      BOOST_CHECK_EQUAL(routeOrigin, expected);
    }
  };

  auto expectFail = [] (const std::string& input) {
    BOOST_TEST_CONTEXT("input = " << std::quoted(input)) {
      std::istringstream is(input);
      RouteOrigin routeOrigin;
      is >> routeOrigin;

      BOOST_CHECK(is.fail());
      BOOST_CHECK_EQUAL(routeOrigin, ROUTE_ORIGIN_NONE);
    }
  };

  expectSuccess("none", ROUTE_ORIGIN_NONE);
  expectSuccess("App", ROUTE_ORIGIN_APP);
  expectSuccess("AutoReg", ROUTE_ORIGIN_AUTOREG);
  expectSuccess("Client", ROUTE_ORIGIN_CLIENT);
  expectSuccess("AutoConf", ROUTE_ORIGIN_AUTOCONF);
  expectSuccess("NLSR", ROUTE_ORIGIN_NLSR);
  expectSuccess("PrefixAnn", ROUTE_ORIGIN_PREFIXANN);
  expectSuccess("static", ROUTE_ORIGIN_STATIC);
  expectSuccess("27", static_cast<RouteOrigin>(27));

  expectSuccess(" app", ROUTE_ORIGIN_APP);
  expectSuccess("app ", ROUTE_ORIGIN_APP);
  expectSuccess(" app ", ROUTE_ORIGIN_APP);

  expectFail("unrecognized");
  expectFail("-1");
  expectFail("0.1");
  expectFail("65537");
  expectFail("");
}

BOOST_AUTO_TEST_CASE(PrintRouteOrigin)
{
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_ORIGIN_NONE), "none");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_ORIGIN_APP), "app");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_ORIGIN_AUTOREG), "autoreg");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_ORIGIN_CLIENT), "client");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_ORIGIN_AUTOCONF), "autoconf");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_ORIGIN_NLSR), "nlsr");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_ORIGIN_PREFIXANN), "prefixann");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_ORIGIN_STATIC), "static");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(static_cast<RouteOrigin>(27)), "27");
}

BOOST_AUTO_TEST_CASE(PrintRouteFlags)
{
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_FLAGS_NONE), "none");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_FLAG_CHILD_INHERIT), "child-inherit");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(ROUTE_FLAG_CAPTURE), "capture");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(static_cast<RouteFlags>(
                    ROUTE_FLAG_CHILD_INHERIT | ROUTE_FLAG_CAPTURE)), "child-inherit|capture");
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(static_cast<RouteFlags>(
                    ROUTE_FLAG_CAPTURE | 0x9c)), "capture|0x9c");
}

BOOST_AUTO_TEST_SUITE_END() // TestNfdConstants
BOOST_AUTO_TEST_SUITE_END() // Encoding

} // namespace tests
} // namespace nfd
} // namespace ndn

max_stars_repo_name: Pesa/ndn-cxx

max_issues_repo_name: Pesa/ndn-cxx

max_forks_repo_name: Pesa/ndn-cxx


text:
//
// Copyright (c) 2009 Rutger ter Borg
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_NUMERIC_BINDINGS_UBLAS_MATRIX_PROXY_HPP
#define BOOST_NUMERIC_BINDINGS_UBLAS_MATRIX_PROXY_HPP

#include <boost/numeric/bindings/bandwidth.hpp>
#include <boost/numeric/bindings/begin.hpp>
#include <boost/numeric/bindings/detail/adaptor.hpp>
#include <boost/numeric/bindings/detail/offset.hpp>
#include <boost/numeric/bindings/detail/property_map.hpp>
#include <boost/numeric/bindings/end.hpp>
#include <boost/numeric/bindings/size.hpp>
#include <boost/numeric/bindings/stride.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>

namespace boost {
namespace numeric {
namespace bindings {
namespace detail {

template< typename T, typename Id, typename Enable >
struct adaptor< ublas::matrix_range< T >, Id, Enable > {

    typedef typename copy_const< Id, T >::type adapted_type;
    typedef typename property_map_of< adapted_type >::type property_map;

    static std::ptrdiff_t size1( const Id& id ) {
        return id.size1();
    }

    static std::ptrdiff_t size2( const Id& id ) {
        return id.size2();
    }

    static typename result_of::begin_value< adapted_type >::type begin_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.start1(), id.start2() );
    }

    static typename result_of::end_value< adapted_type >::type end_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.start1() + id.size1(), id.start2() + id.size2() );
    }

    static std::ptrdiff_t stride1( const Id& id ) {
        return bindings::stride1( id.data() );
    }

    static std::ptrdiff_t stride2( const Id& id ) {
        return bindings::stride2( id.data() );
    }

    static std::ptrdiff_t bandwidth1( const Id& id ) {
        return bindings::bandwidth1( id.data() );
    }

    static std::ptrdiff_t bandwidth2( const Id& id ) {
        return bindings::bandwidth2( id.data() );
    }

};

template< typename T, typename Id, typename Enable >
struct adaptor< ublas::matrix_slice< T >, Id, Enable > {

    typedef typename copy_const< Id, T >::type adapted_type;
    typedef typename property_map_of< adapted_type >::type property_map;

    static std::ptrdiff_t size1( const Id& id ) {
        return id.size1();
    }

    static std::ptrdiff_t size2( const Id& id ) {
        return id.size2();
    }

    static typename result_of::begin_value< adapted_type >::type begin_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.start1(), id.start2() );
    }

    static typename result_of::end_value< adapted_type >::type end_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.start1() + id.size1(), id.start2() + id.size2() );
    }

    static std::ptrdiff_t stride1( const Id& id ) {
        return id.stride1();
    }

    static std::ptrdiff_t stride2( const Id& id ) {
        return id.stride2();
    }

    static std::ptrdiff_t bandwidth1( const Id& id ) {
        return bindings::bandwidth1( id.data() );
    }

    static std::ptrdiff_t bandwidth2( const Id& id ) {
        return bindings::bandwidth2( id.data() );
    }

};

template< typename T, typename Id, typename Enable >
struct adaptor< ublas::matrix_column< T >, Id, Enable > {

    typedef typename copy_const< Id, typename bindings::value_type< T>::type >::type value_type;
    typedef mpl::map<
        mpl::pair< tag::value_type, value_type >,
        mpl::pair< tag::entity, tag::vector >,
        mpl::pair< tag::size_type<1>, std::ptrdiff_t >,
        mpl::pair< tag::data_structure, tag::linear_array >,
        // TODO in case of column major, this could be contiguous
        mpl::pair< tag::stride_type<1>, std::ptrdiff_t >
    > property_map;

    static std::ptrdiff_t size1( const Id& id ) {
        return id.size();
    }

    static value_type* begin_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), 0, id.index() );
    }

    static value_type* end_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), bindings::size(id), id.index() );
    }

    static std::ptrdiff_t stride1( const Id& id ) {
        return bindings::stride1( id.data() );
    }

};

template< typename T, typename Id, typename Enable >
struct adaptor< ublas::matrix_row< T >, Id, Enable > {

    typedef typename copy_const< Id, typename bindings::value_type< T>::type >::type value_type;
    typedef mpl::map<
        mpl::pair< tag::value_type, value_type >,
        mpl::pair< tag::entity, tag::vector >,
        mpl::pair< tag::size_type<1>, std::ptrdiff_t >,
        mpl::pair< tag::data_structure, tag::linear_array >,
        // TODO in case of row major, this could be contiguous
        mpl::pair< tag::stride_type<1>, std::ptrdiff_t >
    > property_map;

    static std::ptrdiff_t size1( const Id& id ) {
        return id.size();
    }

    static value_type* begin_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.index(), 0 );
    }

    static value_type* end_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.index(), bindings::size(id) );
    }

    static std::ptrdiff_t stride1( const Id& id ) {
        return bindings::stride2( id.data() );
    }

};

template< typename T, typename Id, typename Enable >
struct adaptor< ublas::matrix_vector_range< T >, Id, Enable > {

    typedef typename copy_const< Id, T >::type adapted_type;
    typedef typename property_insert< adapted_type,
        mpl::pair< tag::entity, tag::vector >,
        mpl::pair< tag::stride_type<1>, std::ptrdiff_t >
    >::type property_map;

    static std::ptrdiff_t size1( const Id& id ) {
        return id.size();
    }

    static typename result_of::begin_value< adapted_type >::type begin_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.start1(), id.start2() );
    }

    static typename result_of::end_value< adapted_type >::type end_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.start1() + id.size1(), id.start2() + id.size2() );
    }

    static std::ptrdiff_t stride1( const Id& id ) {
        return bindings::stride1( id.data() ) + bindings::stride2( id.data() );
    }

};

template< typename T, typename Id, typename Enable >
struct adaptor< ublas::matrix_vector_slice< T >, Id, Enable > {

    typedef typename copy_const< Id, T >::type adapted_type;
    typedef typename property_insert< adapted_type,
        mpl::pair< tag::entity, tag::vector >,
        mpl::pair< tag::stride_type<1>, std::ptrdiff_t >
    >::type property_map;

    static std::ptrdiff_t size1( const Id& id ) {
        return id.size();
    }

    static typename result_of::begin_value< adapted_type >::type begin_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.start1(), id.start2() );
    }

    static typename result_of::end_value< adapted_type >::type end_value( Id& id ) {
        return bindings::begin_value( id.data() ) +
               offset( id.data(), id.start1() + id.size1(), id.start2() + id.size2() );
    }

    static std::ptrdiff_t stride1( const Id& id ) {
        return id.stride1() * bindings::stride1( id.data() ) +
               id.stride2() * bindings::stride2( id.data() );
    }

};

} // namespace detail
} // namespace bindings
} // namespace numeric
} // namespace boost

#endif

max_stars_repo_name: ljktest/siconos

max_issues_repo_name: ljktest/siconos

max_forks_repo_name: ljktest/siconos


text:
/*
 * AnyNodeTest.cpp
 *
 *  Created on: Jun 13, 2017
 *      Author: quang
 */

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

#include "../../../AnyGraph.h"

using namespace anygraph;

BOOST_AUTO_TEST_CASE(AnyNodeTest) {
	AnyNode node;
	//constructor test
	BOOST_CHECK(node.get_ID() == std::string(""));

	std::string id = "id0";
	node.set_ID(id);

	BOOST_CHECK(node.get_ID() == id);

	Attributes attr1, attr2;

	attr1.set_id("id1");
	attr2.set_id("id2");

	std::vector<Attributes> attrList;

	attrList.push_back(attr1);
	attrList.push_back(attr2);

	node.add_attributes(attr1);
	node.add_attributes(attr2);

	BOOST_CHECK(node.get_attribute_list().size() == attrList.size());
	BOOST_CHECK(
			node.get_attribute_at(0).get_attribute_id()
					== attr1.get_attribute_id());
	BOOST_CHECK(
			node.get_attribute_at(1).get_attribute_id()
					== attr2.get_attribute_id());

}


text:
//  Copyright (c) 2005 Stephan Hirmer (shirmer@cct.lsu.edu)
//
//  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 SAGA_IMPL_ENGINE_BULK_ANALYSER_IMPR_HPP
#define SAGA_IMPL_ENGINE_BULK_ANALYSER_IMPR_HPP

#include <map>

#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>

#include <saga/saga/task_container.hpp>

///////////////////////////////////////////////////////////////////////////////
namespace saga
{
    namespace impl
    {
        /**
          * Class to cluster tasks together from a given task container in
          * terms of same session, same function and same cpi class.
          */
        class bulk_analyser_impr
        : private boost::noncopyable
        {
            enum mode
            {
                Default        = 0,
                Same_Operation = 1,
                Same_Cpi_Type  = 2
            };

        public:
            struct compare_keys
            {
                bool operator()(const std::string s1, const std::string s2) const
                {
                    return strcmp(s1.c_str(), s2.c_str()) < 0;
                }
            };

            typedef std::map<std::string, saga::task_container, compare_keys> sorted_tc_type;

        private:
            /**
              * Helper function to add a new taskcontainer to the list
              * of already existing task containers.
              */
            void operation_add_tc(
                    std::pair< std::vector<saga::task>::iterator,
                               std::vector<saga::task>::iterator >& sorted_session_range_,
                    std::vector<saga::task>& session_sorted_,
                    sorted_tc_type& ret);
            /**
              * Helper function, which sorts the tasks according to the function.
              */
            void operation_sort(std::vector<saga::task>& session_sorted_,
                                sorted_tc_type& ret);
            /**
              * Helper function to sort the tasks according to their sessions.
              */
            void session_sort(std::vector<saga::task>& task_list_);
        public:
            /*the default constructor*/
            bulk_analyser_impr(void);

            /*the destructor*/
            ~bulk_analyser_impr(void);

            /**
              * The function to do the actual analysis.
              *
              */
            void analyse_bulk(task_container& tc, sorted_tc_type& ret,
                                                           mode m = Default);
        }; // class bulk_analyser

    } // namespace impl

} // namespace saga

#endif  // SAGA_IMPL_ENGINE_BULK_ANALYSER_IMPR_HPP

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp


text:
#include <mdw/formula/CString.hpp>
#include <mdw/formula/Grammar.hpp>
#include <mdw/formula/Operator.hpp>
#include <mdw/formula/Repeated.hpp>
#include <mdw/formula/Parser.hpp>
#include <mdw/formula/Expression.hpp>
#include <mdw/formula/Casts.hpp>
#include <mdw/formula/Facts.hpp>
#include <functional>
#include <string>
#include <ctype.h>
#include <boost/mem_fn.hpp>

namespace mdw { namespace formula {

  const char TypeTraits<const char *>::kTypeAsString[] = "CString";

  template <> class ExpressionCast<const char *, int, void>:
    public TypedExpression<int>
    {
      const TypedExpression<const char *>& _expression;
    public:
      typedef TypeTraits<int>::ReturnType ReturnType;

      ExpressionCast(const TypedExpression<const char *>& iExpression,
                     const Grammar& iGrammar,
                     const std::string& iSymbol):
        _expression(iExpression)
      {}

      ReturnType evaluate(IContext& ioContext) const
      {
        const char *aValue = _expression.evaluate(ioContext);
        if (aValue && isdigit(*aValue))
        {
          return atoi(aValue);
        } else {
          ioContext.setNaN();
          return 0;
        }
      }

      std::string toString() const
      {
        return "(int)(" + _expression.toString() + ")";
      }
    };

  template <> class ExpressionCast<const char *, double, void>:
    public TypedExpression<double>
    {
      const TypedExpression<const char *>& _expression;
    public:
      typedef TypeTraits<double>::ReturnType ReturnType;

      ExpressionCast(const TypedExpression<const char *>& iExpression,
                     const Grammar& iGrammar,
                     const std::string& iSymbol):
        _expression(iExpression)
      {}

      ReturnType evaluate(IContext& ioContext) const
      {
        const char *aValue = _expression.evaluate(ioContext);
        if (aValue)
        {
          return atof(aValue);
        } else {
          ioContext.setNaN();
          return 0;
        }
      }

      std::string toString() const
      {
        return "(double)(" + _expression.toString() + ")";
      }
    };

  template <> class ExpressionCast<const char *, std::string, void>:
    public TypedExpression<std::string>
    {
      const TypedExpression<const char *>& _expression;
    public:
      typedef TypeTraits<std::string>::ReturnType ReturnType;

      ExpressionCast(const TypedExpression<const char *>& iExpression,
                     const Grammar& iGrammar,
                     const std::string& iSymbol):
        _expression(iExpression)
      {}

      ReturnType evaluate(IContext& ioContext) const
      {
        const char *aValue = _expression.evaluate(ioContext);
        if (aValue)
        {
          return ioContext.getAllocator().create<std::string>(aValue);
        } else {
          static std::string kEmptyString;
          ioContext.setNaN();
          return kEmptyString;
        }
      }

      std::string toString() const
      {
        return "(string)(" + _expression.toString() + ")";
      }
    };

  class StrLen: public TypedExpression<int>
  {
    const TypedExpression<const char *>& _expression;
  public:
    typedef TypeTraits<int>::ReturnType ReturnType;

    StrLen(const TypedExpression<const char *>& iExpression,
           const Grammar& iGrammar,
           const std::string& iSymbol):
      _expression(iExpression)
    {}

    ReturnType evaluate(IContext& ioContext) const
    {
      const char *aValue = _expression.evaluate(ioContext);
      if (aValue)
      {
        return strlen(aValue);
      } else {
        static std::string kEmptyString;
        ioContext.setNaN();
        return 0;
      }
    }

    std::string toString() const
    {
      return _expression.toString() + ".count";
    }
  };

  class CEmpty: public TypedExpression<bool>
  {
    const TypedExpression<const char *>& _expression;
  public:
    typedef TypeTraits<bool>::ReturnType ReturnType;

    CEmpty(const TypedExpression<const char *>& iExpression,
           const Grammar& iGrammar,
           const std::string& iSymbol):
      _expression(iExpression)
    {}

    ReturnType evaluate(IContext& ioContext) const
    {
      const char *aValue = _expression.evaluate(ioContext);
      return !aValue || (*aValue == 0);
    }

    std::string toString() const
    {
      return _expression.toString() + ".empty";
    }
  };

  Expression& CString::CStringUnary::instantiate(ArenaAllocator& ioAllocator,
                                                   const Grammar& iGrammar,
                                                   const std::string& iSymbol,
                                                   const Expression& iChild) const
  {
    ExpressionType aCStringType = iGrammar.findType<const char *>();
    if (iChild.getType() == aCStringType)
    {
      if (iSymbol == "(int)") {
        return ioAllocator.create<ExpressionCast<const char *, int> >(iChild.get<const char *>(),
                                                                      iGrammar, iSymbol);
      } else if (iSymbol == "(double)") {
        return ioAllocator.create<ExpressionCast<const char *, double> >(iChild.get<const char *>(),
                                                                         iGrammar, iSymbol);
      } else if (iSymbol == "(string)") {
        return ioAllocator.create<ExpressionCast<const char *, std::string> >(iChild.get<const char *>(),
                                                                              iGrammar, iSymbol);
      } else if (iSymbol == "count") {
        return ioAllocator.create<StrLen>(iChild.get<const char *>(), iGrammar, iSymbol);
      } else if (iSymbol == "empty") {
        return ioAllocator.create<CEmpty>(iChild.get<const char *>(), iGrammar, iSymbol);
      } else if (iSymbol == "!") {
        return ioAllocator.create<CEmpty>(iChild.get<const char *>(), iGrammar, iSymbol);
      } else {
        throw mdw::UnknownException("Unary operator not supported on C string: " + iSymbol);
      }
    } else {
      throw mdw::UnknownException("Unsupported unary operator: " + iSymbol + " on type " +
                                  std::string(iChild.getTypeAsString()));
    }
  }

  void CString::CStringUnary::RegisterMe(Grammar& ioGrammar, ArenaAllocator& ioAllocator)
  {
    CStringUnary& aUnaryInstantiator = ioAllocator.create<CStringUnary>();
    ExpressionType aCStringType = ioGrammar.registerType<const char *>();
    ioGrammar.registerUnaryOperator(aCStringType, kExprInt, "(int)", aUnaryInstantiator);
    ioGrammar.registerUnaryOperator(aCStringType, kExprDouble, "(double)", aUnaryInstantiator);
    ioGrammar.registerUnaryOperator(aCStringType, kExprString, "(string)", aUnaryInstantiator);
    ioGrammar.registerAttributeResolver(aCStringType, kExprInt, "count", aUnaryInstantiator);
    ioGrammar.registerAttributeResolver(aCStringType, kExprBool, "empty", aUnaryInstantiator);
    ioGrammar.registerUnaryOperator(aCStringType, kExprBool, "!", aUnaryInstantiator);
  }

  CStringComparator::CStringComparator(const TypedExpression<const char *>& iLeft,
                                       const TypedExpression<const char *>& iRight,
                                       const std::string& iSymbol):
    _left(iLeft), _right(iRight), _symbol(iSymbol)
  {
    _isEqualOK = false;
    _isGreaterOK = false;
    _isLowerOK = false;

    if (iSymbol.find('=') != std::string::npos)
    {
      _isEqualOK = true;
    }
    if (iSymbol.find('>') != std::string::npos)
    {
      _isGreaterOK = true;
    }
    if (iSymbol.find('<') != std::string::npos)
    {
      _isLowerOK = true;
    }
    if (iSymbol == "!=")
    {
      _isEqualOK = false;
      _isLowerOK = true;
      _isGreaterOK = true;
    }
  }

  std::string CStringComparator::toString() const
  {
    return "(" + _left.toString() + ") " + _symbol + " (" + _right.toString() + ")";
  }

  bool CStringComparator::evaluate(IContext& ioContext) const
  {
    const char *aLeft = _left.evaluate(ioContext);
    const char *aRight = _right.evaluate(ioContext);
    if (aLeft == aRight)
    {
      return _isEqualOK;
    } else if ((aLeft == NULL) || (aRight == NULL)) {
      // Only != matches
      return !_isEqualOK && !_isLowerOK && !_isGreaterOK;
    } else {
      int aDiff = strcmp(aLeft, aRight);
      if (aDiff > 0)
      {
        return _isGreaterOK;
      } else if (aDiff < 0) {
        return _isLowerOK;
      } else {
        return _isEqualOK;
      }
    }
  }

  class CStringAt:
    public TypedExpression<__TypeTraits<char>::actual_type>
  {
    const TypedExpression<__TypeTraits<int>::actual_type>& _index;
    const TypedExpression<const char*>& _cstring;

  public:
    CStringAt(const TypedExpression<const char*>& iCString,
              const TypedExpression<__TypeTraits<int>::actual_type>& iIndex):
      _index(iIndex), _cstring(iCString)
    {}

    std::string toString() const
    {
      return "(" + _cstring.toString() + "[" + _index.toString() + "])";
    }

    TypeTraits<char>::ReturnType evaluate(IContext& ioContext) const
    {
      TypeTraits<int>::ReturnType anIndex = _index.evaluate(ioContext);
      const char *aCString = _cstring.evaluate(ioContext);
      if (aCString && (anIndex >= 0) && (anIndex < (TypeTraits<int>::ReturnType)strlen(aCString)))
      {
        return aCString[anIndex];
      } else {
        ioContext.setNaN();
        return '\0';
      }
    }
  };

  StringToCStringComparator::StringToCStringComparator(const TypedExpression<std::string>& iLeft,
                                                       const TypedExpression<const char *>& iRight,
                                                       const std::string& iSymbol,
                                                       bool iRevert):
    _left(iLeft), _right(iRight), _symbol(iSymbol), _revert(iRevert)
  {
    _isEqualOK = false;
    _isGreaterOK = false;
    _isLowerOK = false;

    if (iSymbol.find('=') != std::string::npos)
    {
      _isEqualOK = true;
    }
    if (iSymbol.find('>') != std::string::npos)
    {
      if (iRevert)
      {
        _isLowerOK = true;
      } else {
        _isGreaterOK = true;
      }
    }
    if (iSymbol.find('<') != std::string::npos)
    {
      if (iRevert)
      {
        _isGreaterOK = true;
      } else {
        _isLowerOK = true;
      }
    }
    if (iSymbol == "!=")
    {
      _isEqualOK = false;
      _isLowerOK = true;
      _isGreaterOK = true;
    }
  }

  std::string StringToCStringComparator::toString() const
  {
    if (_revert)
    {
      return "(" + _right.toString() + ") " + _symbol + " (" + _left.toString() + ")";
    } else {
      return "(" + _left.toString() + ") " + _symbol + " (" + _right.toString() + ")";
    }
  }

  bool StringToCStringComparator::evaluate(IContext& ioContext) const
  {
    const std::string& aLeft = _left.evaluate(ioContext);
    const char *aRight = _right.evaluate(ioContext);
    if (aRight == NULL)
    {
      ioContext.setNaN();
      return false;
    } else {
      int aDiff = aLeft.compare(aRight);
      if (aDiff > 0)
      {
        return _isGreaterOK;
      } else if (aDiff < 0) {
        return _isLowerOK;
      } else {
        return _isEqualOK;
      }
    }
  }

  Expression& CString::CStringBinary::instantiate(ArenaAllocator& ioAllocator,
                                                  const Grammar& iGrammar,
                                                  const std::string& iSymbol,
                                                  const Expression& iLeft,
                                                  const Expression& iRight) const
  {
    ExpressionType aCStringType = iGrammar.findType<const char *>();
    if (iLeft.getType() == aCStringType)
    {
      if (iRight.getType() == aCStringType)
      {
        if ((iSymbol == "==") || (iSymbol == "!=") || (iSymbol == ">") || (iSymbol == "<") ||
            (iSymbol == "<=") || (iSymbol == ">="))
        {
          return ioAllocator.create<CStringComparator>(iLeft.get<const char*>(),
                                                       iRight.get<const char*>(),
                                                       iSymbol);
        } else {
          throw mdw::UnknownException("Binary operator not supported on C string: " + iSymbol);
        }
      } else if (iRight.getType() == kExprString) {
        if ((iSymbol == "==") || (iSymbol == "!=") || (iSymbol == ">") || (iSymbol == "<") ||
            (iSymbol == "<=") || (iSymbol == ">="))
        {
          bool aRevert = true;
          return ioAllocator.create<StringToCStringComparator>(iRight.getString(),
                                                               iLeft.get<const char*>(),
                                                               iSymbol, aRevert);
        } else {
          throw mdw::UnknownException("Binary operator not supported on C string: " + iSymbol);
        }
      } else if (iRight.getType() == kExprInt) {
        if (iSymbol == "[]")
        {
          return ioAllocator.create<CStringAt>(iLeft.get<const char *>(), iRight.get<__TypeTraits<int>::actual_type>());
        } else {
          throw mdw::UnknownException("Binary operator not supported on C string: " + iSymbol);
        }
      } else {
        throw mdw::UnknownException("Unsupported binary operator: " + iSymbol + " on types " +
                                    std::string(iLeft.getTypeAsString()) + " and " +
                                    std::string(iRight.getTypeAsString()));
      }
    } else if (iLeft.getType() == kExprString) {
      if (iRight.getType() == aCStringType)
      {
        if ((iSymbol == "==") || (iSymbol == "!=") || (iSymbol == ">") || (iSymbol == "<") ||
            (iSymbol == "<=") || (iSymbol == ">="))
        {
          bool aRevert = false;
          return ioAllocator.create<StringToCStringComparator>(iLeft.getString(),
                                                               iRight.get<const char*>(),
                                                               iSymbol, aRevert);
        } else {
          throw mdw::UnknownException("Binary operator not supported on string: " + iSymbol);
        }
      } else {
        throw mdw::UnknownException("Binary operator not supported on string: " + iSymbol);
      }
    } else {
      throw mdw::UnknownException("Unsupported binary operator: " + iSymbol + " on types " +
                                  std::string(iLeft.getTypeAsString()) + " and " +
                                  std::string(iRight.getTypeAsString()));
    }
  }

  void CString::CStringBinary::RegisterMe(Grammar& ioGrammar, ArenaAllocator& ioAllocator)
  {
    CStringBinary& aBinaryInstantiator = ioAllocator.create<CStringBinary>();
    ExpressionType aCStringType = ioGrammar.findType<const char *>();

    ioGrammar.registerBinaryOperator(aCStringType, kExprString, kExprBool, "==",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, kExprString, kExprBool, "!=",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, kExprString, kExprBool, ">",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, kExprString, kExprBool, ">=",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, kExprString, kExprBool, "<",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, kExprString, kExprBool, "<=",
                                     aBinaryInstantiator);

    ioGrammar.registerBinaryOperator(kExprString, aCStringType, kExprBool, "==",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(kExprString, aCStringType, kExprBool, "!=",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(kExprString, aCStringType, kExprBool, ">",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(kExprString, aCStringType, kExprBool, ">=",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(kExprString, aCStringType, kExprBool, "<",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(kExprString, aCStringType, kExprBool, "<=",
                                     aBinaryInstantiator);

    ioGrammar.registerBinaryOperator(aCStringType, aCStringType, kExprBool, "==",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, aCStringType, kExprBool, "!=",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, aCStringType, kExprBool, ">",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, aCStringType, kExprBool, ">=",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, aCStringType, kExprBool, "<",
                                     aBinaryInstantiator);
    ioGrammar.registerBinaryOperator(aCStringType, aCStringType, kExprBool, "<=",
                                     aBinaryInstantiator);

    ioGrammar.registerBinaryOperator(aCStringType, kExprInt, kExprInt, "[]", aBinaryInstantiator);
  }

  void CString::RegisterMe(Grammar& ioGrammar, ArenaAllocator& ioAllocator)
  {
    ioGrammar.registerType<const char *>();
    CStringUnary::RegisterMe(ioGrammar, ioAllocator);
    CStringBinary::RegisterMe(ioGrammar, ioAllocator);
  }

}}

max_stars_repo_name: AmadeusITGroup/Formula

max_issues_repo_name: AmadeusITGroup/Formula

max_forks_repo_name: AmadeusITGroup/Formula


text:
#include <fstream>
#include <sstream>
#include <iterator>
#include <iostream>
#include <fmt/format.h>
#include <string>
#include <numeric>
#include <execution>
#include <utility>
#include <algorithm>
#include <map>
#include <cstdint>
#include <boost/integer/mod_inverse.hpp>
using std::int64_t;
using gint = int64_t;
using std::int64_t;
template<class T>
constexpr T mymod(T n, T N) noexcept
{
  n %= N;
  if (n < 0) {
    n += N;
  }
  return n;
}
struct TimeStamp
{

  static constexpr int64_t firstvalid(int r, int pos) noexcept
  {
    std::array<std::pair<int64_t, int64_t>, 2> primeposs{
      std::pair{ 91l, r },
      std::pair{ pos, 0l },
    };

    int64_t sum = 0;

    int64_t M = 1;
    for (auto [p, i] : primeposs) {
      M *= p;
    }
    for (int i = 0; i < primeposs.size(); ++i) {
      auto [mi, a] = primeposs[i];
      auto Mi = M / mi;
      auto ti = boost::integer::mod_inverse(Mi, mi);
      sum += Mi * ti * a;
    }
    return sum % M;
  }
};
int main(int argc, char **argv)
{
  if (argc > 1) {
    std::ifstream ifs(argv[1]);
    int r, p;
    int sum = 0;
    std::vector<std::pair<int, int>> v;
    for (int i = 0; ifs >> r >> p; ++i) {
      v.push_back(std::pair{ r, 2 * (p - 1) });
    }
    bool notfound = true;
    auto t = 0;
    for (; notfound; ++t) {
      bool alltrue = true;
      for (auto [f, s] : v) {
        if (!((t + f) % s)) {
          //fmt::print("f:{},s:{}\n", f, s);
          alltrue = false;
          break;
        }
      }
      if (alltrue) {
        //fmt::print("foundt:{}\n", t);
        break;
      }
      notfound = !alltrue;
    }
    fmt::print("t:{}\n", t);
  }
}

max_stars_repo_name: jiayuehua/adventOfCode

max_issues_repo_name: jiayuehua/adventOfCode

max_forks_repo_name: jiayuehua/adventOfCode


text:
#include <ros/ros.h>
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <thread>
#include <iostream>

#include "udp_broadcast.h"
#include <multiwar/share_info.h>

using namespace std;

multiwar::share_info field_info;

void battle_callback(const multiwar::share_info& info)
{
    ;
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "udp_publisher");
    ros::NodeHandle nh;
    ros::Subscriber sub_vision = nh.subscribe("my_info", 5, battle_callback); // update data

    int udp_port = 8888;
    int udp_rate = 10;
    ros::param::get("udp_port",udp_port);
    ros::param::get("udp_rate",udp_rate);

    ros::Rate loop_rate(udp_rate);

    namespace ip = boost::asio::ip;
    boost::asio::io_service io_service;

    // Server binds to any address and any port.
    ip::udp::socket socket(io_service, ip::udp::endpoint(ip::udp::v4(), 0));
    socket.set_option(boost::asio::socket_base::broadcast(true));

    // Broadcast will go to port 8888.
    ip::udp::endpoint broadcast_endpoint(ip::address_v4::broadcast(), udp_port);

    // Broadcast data.
    RobotMsg msg;
    msg.yaw = 3.14;
    msg.pitch = 4.16231311312;
    msg.distance = 48;

    uint8_t send_bytes[8];

    udp_encode(msg, send_bytes);

    while(ros::ok())
    {
        socket.send_to(boost::asio::buffer(send_bytes), broadcast_endpoint);
        //ros::spinOnce();
        loop_rate.sleep();
    }
    io_service.run();

    return EXIT_SUCCESS;
}

max_stars_repo_name: hukcc/autocar-test-ros

max_issues_repo_name: hukcc/autocar-test-ros

max_forks_repo_name: hukcc/autocar-test-ros


text:
#include "assimp_processor.h"

#include <cstdint>
#include <iostream>
#include <string>

#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <boost/filesystem.hpp>
#include <FreeImage.h>
#include "material.h"
#include "mesh.h"
#include "model.h"
#include "output_util.h"
#include "vector.h"
#include "texture.h"

using namespace std;

size_t total_vertices(const vector<unique_ptr<Mesh>> &meshes)
{
	size_t total = 0;
	for(const auto &mesh : meshes) {
		total += mesh->m_vertices.size();
	}

	return total;
}

void print_model_metrics(const shared_ptr<Model> &model)
{
	size_t vertex_count = total_vertices(model->m_meshes);
	cout << "Total vertices: " << vertex_count << ". Total meshes: " << model->m_meshes.size() << ". ";
	model->print_memory_usage();
}

shared_ptr<Model> AssimpModelProcessor::load(const string &path, size_t vertex_limit, bool allow_cached_materials)
{
	cout << "=== Loading model: '" << path << "' === \n";

	Assimp::Importer importer;

	importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, vertex_limit);

	const aiScene *scene = importer.ReadFile(path,
		aiProcess_CalcTangentSpace			|
		aiProcess_Triangulate				|
		aiProcess_GenSmoothNormals			|
		aiProcess_SplitLargeMeshes			|
		aiProcess_ImproveCacheLocality		|
		aiProcess_RemoveRedundantMaterials	|
		aiProcess_OptimizeMeshes			|
		aiProcess_FixInfacingNormals		|
		aiProcess_FindInvalidData			|
		//aiProcess_OptimizeGraph				|
		aiProcess_JoinIdenticalVertices		|
		aiProcess_SortByPType);

	if(!scene) {
		cerr << "Failed to load model!\n" << importer.GetErrorString() << "\n";
		return nullptr;
	}

	cout << "Loading materials...";
	map<size_t, shared_ptr<Material>> materials;
	for(size_t i = 0; i < scene->mNumMaterials; ++i)
	{
		//display_progress((i+1) / (float)scene->mNumMaterials);
		const shared_ptr<Material> &material = load_single_material(i, scene->mMaterials[i], path, allow_cached_materials);
		if(material)
			materials.emplace(material->index(), material);
	}
	cout << materials.size() << " loaded.\n";

	cout << "Loading meshes...";
	vector<unique_ptr<Mesh>> meshes;
	for(size_t i = 0; i < scene->mNumMeshes; ++i)
	{
		//display_progress((i+1) / (float)scene->mNumMeshes);
		meshes.push_back(load_single_mesh(scene->mMeshes[i], materials));
	}
	cout << meshes.size() << " loaded.\n";

	cout << "Done.\n\n";
	//

	Matrix transform;
	transform.make_identity();
	auto model = make_shared<Model>(transform, meshes);
	print_model_metrics(model);

	return model;
}

Texture* AssimpModelProcessor::load_texture(const aiString &path, const string &modelPath)
{
	boost::filesystem::path texturePath(path.C_Str());

	if(texturePath.is_relative()) {
		boost::filesystem::path modelDirectory(modelPath);
		modelDirectory = modelDirectory.parent_path();

		texturePath = boost::filesystem::canonical(texturePath, modelDirectory);
	}

	FREE_IMAGE_FORMAT type = FreeImage_GetFileType(texturePath.string().c_str());
	if(type == FIF_UNKNOWN) {
		type = FreeImage_GetFIFFromFilename(texturePath.string().c_str());

		if(type == FIF_UNKNOWN)
			throw runtime_error("Unable to determine texture format.");
	}

	FIBITMAP *bitmap = FreeImage_Load(type, texturePath.string().c_str());
	Texture *texture = new Texture(bitmap);
	FreeImage_Unload(bitmap);

	return texture;
}

shared_ptr<Material> AssimpModelProcessor::load_single_material(size_t index, aiMaterial *material, const string &model_path, bool allow_cached_materials)
{
	aiString name;
	aiGetMaterialString(material, AI_MATKEY_NAME, &name);

	string cache_key = model_path + "_" + string(name.C_Str());

	if(allow_cached_materials) {

		auto cached_material = m_material_cache.get(cache_key);
		if(cached_material)
			return cached_material;

	}

	// material->Get does NOT return colors as their documentation states. aiGetMaterialColor does however. Perhaps the same problem exists with Textures?

	aiColor4D fooo;
	aiGetMaterialColor(material,AI_MATKEY_COLOR_DIFFUSE, &fooo);

	float refracti;
	aiGetMaterialFloat(material, AI_MATKEY_REFRACTI, &refracti);
	//material->Get<float>(AI_MATKEY_REFRACTI, refracti);

	float opacity;
	aiGetMaterialFloat(material, AI_MATKEY_OPACITY, &opacity);
	//material->Get<float>(AI_MATKEY_OPACITY, opacity);

	float shininess;
	aiGetMaterialFloat(material, AI_MATKEY_SHININESS, &shininess);
	//material->Get<float>(AI_MATKEY_SHININESS, shininess);

	int shading_model;
	aiGetMaterialInteger(material, AI_MATKEY_SHADING_MODEL, &shading_model);
	//material->Get<int>(AI_MATKEY_SHADING_MODEL, shading_model);

	aiColor4D ambient_color;
	aiGetMaterialColor(material,AI_MATKEY_COLOR_AMBIENT, &ambient_color);

	aiColor4D diffuse_color;
	aiGetMaterialColor(material,AI_MATKEY_COLOR_DIFFUSE, &diffuse_color);

	aiColor4D emissive_color;
	aiGetMaterialColor(material,AI_MATKEY_COLOR_EMISSIVE, &emissive_color);

	aiColor4D specular_color;
	aiGetMaterialColor(material,AI_MATKEY_COLOR_SPECULAR, &specular_color);

	aiString p;
	unsigned int texCount = 0;
	for(int i = 0; i < aiTextureType_UNKNOWN; ++i) {
		texCount += material->GetTextureCount((aiTextureType)i);
	}

	Texture* diffuseTexture = nullptr;
	if(material->GetTexture(aiTextureType_DIFFUSE, 0, &p) == AI_SUCCESS) {
		diffuseTexture = load_texture(p, model_path);

	}

	Texture* normalTexture = nullptr;
	if(material->GetTexture(aiTextureType_NORMALS, 0, &p) == AI_SUCCESS) {
		normalTexture = load_texture(p, model_path);
	}

	//return shared_ptr<Material>(nullptr);
	auto mat = make_shared<Material>(index,
		Color(diffuse_color.r, diffuse_color.g, diffuse_color.b),
		Color(emissive_color.r, emissive_color.g, emissive_color.b),
		diffuseTexture, normalTexture);

	m_material_cache.insert(cache_key, mat);

	return mat;
}

unique_ptr<Mesh> AssimpModelProcessor::load_single_mesh(aiMesh *mesh, const map<size_t, shared_ptr<Material>> &materials) const
{
	vector<Vector3f> vertices;
	vector<uint16_t> indices;
	vector<Vector3f> normals;
	vector<Vector3f> tangents;
	vector<Vector3f> bitangents;
	vector<Vector2f> texture_coords;

	for(size_t i = 0; i < mesh->mNumVertices; ++i)
	{
		aiVector3D &vertice = mesh->mVertices[i];
		vertices.push_back(Vector3f(vertice.x, vertice.y, vertice.z));

		aiVector3D &normal = mesh->mNormals[i];
		normals.push_back(Vector3f(normal.x, normal.y, normal.z));

		if(mesh->HasTangentsAndBitangents()) {

			aiVector3D &tangent = mesh->mTangents[i];
			tangents.push_back(Vector3f(tangent.x, tangent.y, tangent.z));

			aiVector3D &bitangent = mesh->mBitangents[i];
			bitangents.push_back(Vector3f(bitangent.x, bitangent.y, bitangent.z));

		}
		if(mesh->HasTextureCoords(0)) {
			aiVector3D &texture_coord = mesh->mTextureCoords[0][i];
			texture_coords.push_back(Vector2f(texture_coord.x, texture_coord.y));
		}
	}

	for(size_t i = 0; i < mesh->mNumFaces; ++i)
	{
		indices.push_back(mesh->mFaces[i].mIndices[0]);
		indices.push_back(mesh->mFaces[i].mIndices[1]);
		indices.push_back(mesh->mFaces[i].mIndices[2]);
	}

	auto iterator = materials.find(mesh->mMaterialIndex);

	shared_ptr<Material> material(nullptr);

	if(iterator != materials.end())
		material = iterator->second;

	return unique_ptr<Mesh>(new Mesh(mesh->mName.C_Str(), vertices, indices, normals, tangents,
		bitangents, texture_coords, material));
}

const vector<string> AssimpModelProcessor::handled_extensions() const
{
	string ext[] = {".dae", ".blend", ".3ds", ".ase", ".obj", ".ifc", ".xgl",
		".zgl", ".ply", ".dxf", ".lwo", ".lws", ".lxo", ".stl", ".x", ".ac", ".ms3d", ".cob", ".scn",
	".bvh", ".csm", ".xml", ".irrmesh", ".irr", ".mdl", ".md2", ".md3", ".pk3", ".mdc", ".md5", ".smd",
	".vta", ".m3", ".3d", ".b3d", ".q3d", ".q3s", ".nff", ".off", ".raw", ".ter", ".hmp", ".ndo", ".fbx" };

	return vector<string>(begin(ext), end(ext));
}

max_stars_repo_name: EmilNorden/candle

max_issues_repo_name: EmilNorden/candle

max_forks_repo_name: EmilNorden/candle