text:
/*******************************************************************\
Module: Unit tests for filesystem_operations class
Author: Rafael Sá Menezes

\*******************************************************************/

#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include <catch2/catch.hpp>
#include <util/filesystem.h>
#include <boost/filesystem.hpp>

TEST_CASE(
  "tmp path should be unique between two runs",
  "[core][util][filesystem]")
{
  const char *format = "esbmc-test-%%%%";
  auto first = file_operations::get_unique_tmp_path(format);
  auto second = file_operations::get_unique_tmp_path(format);
  REQUIRE(first != second);
}

TEST_CASE(
  "tmp folder should be unique between two runs",
  "[core][util][filesystem]")
{
  const char *format = "esbmc-test-%%%%";
  auto first = file_operations::create_tmp_dir(format);
  auto second = file_operations::create_tmp_dir(format);
  REQUIRE(first.path() != second.path());
}

TEST_CASE(
  "tmp file should be unique between two runs",
  "[core][util][filesystem]")
{
  const char *format = "esbmc-test-%%%%";
  auto first = file_operations::create_tmp_file(format);
  auto second = file_operations::create_tmp_file(format);
  REQUIRE(first.path() != second.path());
}

TEST_CASE("tmp dir is dir and should be removed", "[core][util][filesystem]")
{
  const char *format = "esbmc-test-%%%%";
  std::string path;
  {
    auto dir = file_operations::create_tmp_dir(format);
    path = dir.path();
    REQUIRE(boost::filesystem::is_directory(path));
  }
  REQUIRE(!boost::filesystem::exists(path));
}

TEST_CASE("tmp file is file and should be removed", "[core][util][filesystem]")
{
  const char *format = "esbmc-test-%%%%";
  std::string path;
  {
    auto file = file_operations::create_tmp_file(format);
    path = file.path();
    REQUIRE(boost::filesystem::is_regular_file(path));
  }
  REQUIRE(!boost::filesystem::exists(path));
}

max_stars_repo_name: shmarovfedor/esbmc

max_issues_repo_name: shmarovfedor/esbmc

max_forks_repo_name: shmarovfedor/esbmc


text:
/*    Copyright (c) 2010-2015, Delft University of Technology
   *    All rights reserved.
   *
   *    Redistribution and use in source and binary forms, with or without modification, are
   *    permitted provided that the following conditions are met:
   *      - Redistributions of source code must retain the above copyright notice, this list of
   *        conditions and the following disclaimer.
   *      - Redistributions in binary form must reproduce the above copyright notice, this list of
   *        conditions and the following disclaimer in the documentation and/or other materials
   *        provided with the distribution.
   *      - Neither the name of the Delft University of Technology 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.
   *
   *    Changelog
   *      YYMMDD    Author              Comment
   *      130219    D. Dirkx            File created.
   *      130227    R.C.A. Boon         Removed using directives (using namespace), added necessary
   *                                    using declarations (using ...::member), removed obsolete
   *                                    include statements
   *      130302    D. Dirkx            Updated file by putting tests in local scope;
   *                                    expanded tests.
   *
   *    References
   *
   *    Notes
   *      The unit tests use rotation matrices generated by spice, the code for the spice interface
   *      used to generate these testing values are included in this file, but commented.
   */

#define BOOST_TEST_MAIN

#include <limits>

#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>

#include <Eigen/Core>

#include "Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h"
#include "Tudat/Basics/testMacros.h"

#include "Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h"
#include "Tudat/Astrodynamics/Ephemerides/simpleRotationalEphemeris.h"
//#include "Tudat/External/SpiceInterface/spiceInterface.h"
//#include "Tudat/InputOutput/basicInputOutput.h"
#include "Tudat/Astrodynamics/ReferenceFrames/referenceFrameTransformations.h"

namespace tudat
{
namespace unit_tests
{

using unit_conversions::convertDegreesToRadians;
using ephemerides::SimpleRotationalEphemeris;
using basic_astrodynamics::JULIAN_DAY_ON_J2000;
using basic_astrodynamics::JULIAN_DAY_AT_0_MJD;
using reference_frames::getInertialToPlanetocentricFrameTransformationQuaternion;

BOOST_AUTO_TEST_SUITE( test_simple_rotational_ephemeris )

// Test simple rotational ephemeris class by compariing results to Venus-fixed frame with Spice.
BOOST_AUTO_TEST_CASE( testSimpleRotationalEphemeris )
{
    // Data from pck00010.tpc spice kernel.
    const double venusPoleRightAscension = convertDegreesToRadians( 272.76 );
    const double venusPoleDeclination = convertDegreesToRadians( 67.16 );
    const double venusPrimeMeridianAtJ2000 = convertDegreesToRadians( 160.20 );
    const double venusRotationRate = convertDegreesToRadians( -1.4813688 ) /
            physical_constants::JULIAN_DAY;

    // Define names of frames.
    const std::string baseFrame = "J2000";
    const std::string targetFrame = "IAU_VENUS";

    // Calculate initial rotation quaternion to frame.
    const Eigen::Quaterniond initialRotationToTargetFrame =
            getInertialToPlanetocentricFrameTransformationQuaternion(
                venusPoleDeclination, venusPoleRightAscension, venusPrimeMeridianAtJ2000 );

    // Create rotational ephemeris objects from (one for each type of constructor)
    SimpleRotationalEphemeris venusRotationalEphemerisFromAngles(
                venusPoleRightAscension, venusPoleDeclination, venusPrimeMeridianAtJ2000,
                venusRotationRate, 0.0, JULIAN_DAY_ON_J2000, baseFrame, targetFrame );
    SimpleRotationalEphemeris venusRotationalEphemerisFromInitialState(
                initialRotationToTargetFrame,
                venusRotationRate, 0.0, JULIAN_DAY_ON_J2000, baseFrame, targetFrame );

    // Test initial rotation matrix, both from the direct constructed object, and the one from
    // constituent angles.
    {
        // The following code block can be used to retrieve the benchmark data from Spice.
        /*
        loadSpiceKernelInTudat( getTudatRootPath( ) +
              "Astrodynamics/Ephemerides/UnitTests/pck00010.tpc" );
        Eigen::Matrix3d spiceInitialRotationToTargetFrameMatrix;
        Eigen::Quaterniond spiceInitialRotationToTargetFrame =
                computeRotationQuaternionBetweenFrames( baseFrame, targetFrame, 0.0 );
       */

        // Set initial rotation, as calculated with Spice (see above commented lines)
        Eigen::Matrix3d spiceInitialRotationToTargetFrameMatrix;
        spiceInitialRotationToTargetFrameMatrix
                << -0.9548214974296336, 0.2665104385944917, 0.1314841974018291,
                -0.296591573568662, -0.882413772579987, -0.3652114078848295,
                0.01869081416890202, -0.3877088083617989, 0.9215923900425705;

        // Check calculated with spice initial state.
        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( spiceInitialRotationToTargetFrameMatrix,
                                           Eigen::Matrix3d( initialRotationToTargetFrame ),
                                           1.0E-15 );

        // Check ephemeris calculations with Spice initial state.
        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
                    Eigen::Matrix3d(
                        venusRotationalEphemerisFromAngles.getRotationToTargetFrame(
                            0.0, JULIAN_DAY_ON_J2000 ) ),
                    Eigen::Matrix3d( initialRotationToTargetFrame ),
                    1.0E-15 );

        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
                    Eigen::Matrix3d(
                        venusRotationalEphemerisFromInitialState.getRotationToTargetFrame(
                            0.0, JULIAN_DAY_ON_J2000 ) ),
                    Eigen::Matrix3d( initialRotationToTargetFrame ),
                    1.0E-15 );
    }

    // Set time at which rotational ephemeris it to be called for subsequent tests.
    const double secondsSinceJ2000 = 1.0E6;

    // Test rotation to target frame at specified time.
    {
        /*
        spice_interface::loadSpiceKernelInTudat( input_output::getSpiceKernelPath( ) + "pck00010.tpc" );
        // The following code block can be used to retrieve the benchmark data from Spice.

        Eigen::Quaterniond spiceRotationMatrix =
               computeRotationQuaternionBetweenFrames( baseFrame, targetFrame, secondsSinceJ2000 );\
        spice_interface::computeRotationMatrixDerivativeBetweenFrames( baseFrame, targetFrame, secondsSinceJ2000 );

        */
        Eigen::Matrix3d spiceRotationMatrixDerivative;
        spiceRotationMatrixDerivative << 1.690407961416589e-07, 2.288121921543265e-07, 9.283170431475241e-08,
                -2.468632444964533e-07, 1.540516111965609e-07, 6.981529179974795e-08,
                0.0,           0.0,          0.0;

        // Set rotation at given time, as calculated with Spice (see above commented lines)
        Eigen::Matrix3d spiceRotationMatrix;
        spiceRotationMatrix << -0.8249537745726603, 0.5148010526833556, 0.2333048348715243,
                -0.5648910720519699, -0.7646317780963481, -0.3102197940834743,
                0.01869081416890206, -0.3877088083617987, 0.9215923900425707;

        // Calculate rotation to frame, and its time derivative, at certain time;
        Eigen::Quaterniond ephemerisRotation =
                venusRotationalEphemerisFromAngles.getRotationToTargetFrame(
                    secondsSinceJ2000, JULIAN_DAY_ON_J2000 );
        Eigen::Matrix3d ephemerisRotationDerivative =
                venusRotationalEphemerisFromAngles.getDerivativeOfRotationToTargetFrame(
                    secondsSinceJ2000, JULIAN_DAY_ON_J2000 );;

        // Check Spice result with ephemerides results.
        for( unsigned int i = 0; i < 3; i++ )
        {
            for( unsigned int j = 0; j < 3; j++ )
            {
                BOOST_CHECK_SMALL(
                            Eigen::Matrix3d( ephemerisRotation )( i, j ) -
                            spiceRotationMatrix( i, j ), 2.0E-15 );
                BOOST_CHECK_SMALL(
                            spiceRotationMatrixDerivative( i, j ) -
                            ephemerisRotationDerivative( i, j ), 2.0E-22 );
            }

        }

        // Compare inverse rotation and its time derivative.
        Eigen::Quaterniond inverseEphemerisRotation =
                venusRotationalEphemerisFromInitialState.getRotationToBaseFrame(
                    secondsSinceJ2000, JULIAN_DAY_ON_J2000 );
        Eigen::Matrix3d inverseEphemerisRotationDerivative =
                venusRotationalEphemerisFromAngles.getDerivativeOfRotationToBaseFrame(
                    secondsSinceJ2000, JULIAN_DAY_ON_J2000 );

        Eigen::Matrix3d inverseSpiceRotationMatrix = spiceRotationMatrix.inverse( );
        Eigen::Matrix3d inverseSpiceRotationMatrixDerivative = spiceRotationMatrixDerivative.transpose( );

        // Check Spice result with ephemerides results.
        for( unsigned int i = 0; i < 3; i++ )
        {
            for( unsigned int j = 0; j < 3; j++ )
            {
                BOOST_CHECK_SMALL(
                            Eigen::Matrix3d( inverseEphemerisRotation )( i, j ) -
                            inverseSpiceRotationMatrix( i, j ), 2.0E-15 );
                BOOST_CHECK_SMALL(
                            inverseEphemerisRotationDerivative( i, j ) -
                            inverseSpiceRotationMatrixDerivative( i, j ), 2.0E-22 );
            }

        }
    }

    // Test rotation matrix derivative by means of finite differences
    {
        double timeStep = 10.0;

        // Calculate rotations to frame at two times.
        Eigen::Quaterniond ephemerisRotation1 =
                venusRotationalEphemerisFromAngles.getRotationToTargetFrame(
                    secondsSinceJ2000, JULIAN_DAY_ON_J2000 );
        Eigen::Quaterniond ephemerisRotation2 =
                venusRotationalEphemerisFromAngles.getRotationToTargetFrame(
                    secondsSinceJ2000 + timeStep, JULIAN_DAY_ON_J2000 );

        // Numerically calculate matrix derivative.
        Eigen::Matrix3d numericalEphemerisRotationDerivative =
                ( Eigen::Matrix3d( ephemerisRotation2 ) - Eigen::Matrix3d( ephemerisRotation1 ) ) /
                timeStep;

        // Calculate matrix derivative directly and compare.
        Eigen::Matrix3d ephemerisRotationDerivative =
                venusRotationalEphemerisFromAngles.getDerivativeOfRotationToTargetFrame(
                    secondsSinceJ2000 + timeStep / 2.0, JULIAN_DAY_ON_J2000 );
        for( unsigned int i = 0; i < 3; i++ )
        {
            for( unsigned int j = 0; j < 3; j++ )
            {
                BOOST_CHECK_SMALL(
                            numericalEphemerisRotationDerivative( i, j ) -
                            ephemerisRotationDerivative( i, j ), 2.0E-16 );
            }

        }

        // Calculate rotations from frame at two times;
        ephemerisRotation1 =
                venusRotationalEphemerisFromAngles.getRotationToBaseFrame(
                    secondsSinceJ2000, JULIAN_DAY_ON_J2000 );
        ephemerisRotation2 =
                venusRotationalEphemerisFromAngles.getRotationToBaseFrame(
                    secondsSinceJ2000 + timeStep, JULIAN_DAY_ON_J2000 );

        // Numerically calculate matrix derivative.
        ephemerisRotationDerivative =
                venusRotationalEphemerisFromAngles.getDerivativeOfRotationToBaseFrame(
                    secondsSinceJ2000 + timeStep / 2.0, JULIAN_DAY_ON_J2000 );

        // Calculate matrix derivative directly and compare.
        numericalEphemerisRotationDerivative =
                ( Eigen::Matrix3d( ephemerisRotation2 ) - Eigen::Matrix3d( ephemerisRotation1 ) ) /
                timeStep;
        for( unsigned int i = 0; i < 3; i++ )
        {
            for( unsigned int j = 0; j < 3; j++ )
            {
                BOOST_CHECK_SMALL(
                            numericalEphemerisRotationDerivative( i, j ) -
                            ephemerisRotationDerivative( i, j ), 2.0E-16 );
            }

        }
    }

    // Test rotation from target frame at specified time (is checked by checking if it is inverse
    // of opposite rotation).
    {
        // Test orthonormality of matrices from object created from initial angles.
        Eigen::Matrix3d productOfOppositeRotations =
                Eigen::Matrix3d( venusRotationalEphemerisFromAngles.getRotationToTargetFrame(
                                     secondsSinceJ2000, JULIAN_DAY_ON_J2000 ) ) *
                Eigen::Matrix3d( venusRotationalEphemerisFromAngles.getRotationToBaseFrame(
                                     secondsSinceJ2000, JULIAN_DAY_ON_J2000 ) );

        for ( int i = 0; i < 3; i++ )
        {
            for ( int j = 0; j < 3; j++ )
            {
                BOOST_CHECK_SMALL( productOfOppositeRotations( i, j ) -
                                   Eigen::Matrix3d::Identity( )( i, j ), 1.0E-15 );
            }
        }

        // Test orthonormality of matrices from object created from initial state.
        productOfOppositeRotations =
                Eigen::Matrix3d( venusRotationalEphemerisFromInitialState.getRotationToTargetFrame(
                                     secondsSinceJ2000, JULIAN_DAY_ON_J2000 ) ) *
                Eigen::Matrix3d( venusRotationalEphemerisFromInitialState.getRotationToBaseFrame(
                                     secondsSinceJ2000, JULIAN_DAY_ON_J2000 ) );

        for( int i = 0; i < 3; i++ )
        {
            for( int j = 0; j < 3; j++ )
            {
                BOOST_CHECK_SMALL( productOfOppositeRotations( i, j ) -
                                   Eigen::Matrix3d::Identity( )( i, j ), 1.0E-15 );
            }
        }
    }

    // Test rotational ephemeris in case input epoch is not reference epoch.
    {
        // The following code block can be used to retrieve the benchmark data from Spice.
        /*
        Eigen::Quaterniond spiceInitialRotationToTargetFrame =
               computeRotationQuaternionBetweenFrames( baseFrame, targetFrame, secondsSinceJ2000 );
        */

        // Set rotation at given time, as calculated with Spice (see above commented lines)
        Eigen::Matrix3d spiceRotationMatrix;
        spiceRotationMatrix
                << -0.8249537745726603, 0.5148010526833556, 0.2333048348715243,
                -0.5648910720519699, -0.7646317780963481, -0.3102197940834743,
                0.01869081416890206, -0.3877088083617987, 0.9215923900425707;

        // Test alternative input reference epoch on object from initial angles.
        double secondsSinceMjd0 = ( JULIAN_DAY_ON_J2000 - JULIAN_DAY_AT_0_MJD ) *
                physical_constants::JULIAN_DAY + secondsSinceJ2000;

        Eigen::Quaterniond ephemerisRotation = venusRotationalEphemerisFromAngles.
                getRotationToTargetFrame( secondsSinceMjd0, JULIAN_DAY_AT_0_MJD );

        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( Eigen::Matrix3d( ephemerisRotation ),
                                           spiceRotationMatrix, 5.0E-15 );

        // Test alternative input reference epoch on object from initial state.
        ephemerisRotation = venusRotationalEphemerisFromInitialState.getRotationToTargetFrame(
                    secondsSinceMjd0, JULIAN_DAY_AT_0_MJD );

        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( Eigen::Matrix3d( ephemerisRotation ),
                                           spiceRotationMatrix, 5.0E-15 );
    }
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace tudat

ext: cpp

max_stars_repo_name: JPelamatti/ThesisTUDAT

max_issues_repo_name: JPelamatti/ThesisTUDAT

max_forks_repo_name: JPelamatti/ThesisTUDAT


text:
#ifndef PROPERTIES_HPP
#define PROPERTIES_HPP

#include <libcommon/libcommon_config.h>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <map>
#include <deque>
#include <boost/shared_ptr.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/function.hpp>
#include <libcommon/xmlrpc_datetime.hpp>

//#include <loki/Singleton.h>

// Because the datetime of XMLRPC will use dot in the tag <dateTime.iso8601>, we need to use other separator here.
/// The separator character for boost property tree
#define PT_SEP_CH '/'
/// The separator string for boost property tree
#define PT_SEP_STR "/"

namespace FBi
{
// Forward declaration
class IPropertiesValueLimitation;

class LIBCOMMON_DECL Properties
{
public:
	// Forward declaration
	struct PropertyNode;

	typedef boost::function<void (const FBi::Properties&)> NotifySlotFunc;

	class ValueType
	{
		typedef std::vector<ValueType> XMLRPCArray;
		boost::any	m_value;
	public:
		ValueType(){}
		ValueType(const std::string& str):m_value(str){}
		ValueType(const char* str):m_value(std::string(str)){}
		ValueType(int v):m_value(v){}
		ValueType(double v):m_value(v){}
		ValueType(bool v):m_value(v){}
		ValueType(const Properties& c):m_value(c){}
		ValueType(const XMLRPCArray& v):m_value(v){}
		ValueType(const XMLRPCDateTime& v):m_value(v){}

		const std::type_info& GetType() const { return m_value.type(); }

		operator bool() const
		{
			return boost::any_cast<bool>(m_value);
		}

		operator bool()
		{
			return boost::any_cast<bool>(m_value);
		}

		operator int() const
		{
			return boost::any_cast<int>(m_value);
		}

		operator int()
		{
			return boost::any_cast<int>(m_value);
		}

		operator double() const
		{
			return boost::any_cast<double>(m_value);
		}

		operator double()
		{
			return boost::any_cast<double>(m_value);
		}

		operator std::string() const
		{
			return boost::any_cast<std::string>(m_value);
		}

		operator const Properties &() const
		{
			return boost::any_cast<const Properties&>(m_value);
		}

		operator Properties &()
		{
			return boost::any_cast<Properties&>(m_value);
		}

		operator const Properties *() const
		{
			return boost::any_cast<Properties>(&m_value);
		}

		operator Properties *()
		{
			return boost::any_cast<Properties>(&m_value);
		}

		operator const XMLRPCArray &() const
		{
			return boost::any_cast<const XMLRPCArray&>(m_value);
		}

		operator XMLRPCArray &()
		{
			return boost::any_cast<XMLRPCArray&>(m_value);
		}

		operator const XMLRPCArray *() const
		{
			return boost::any_cast<XMLRPCArray>(&m_value);
		}

		operator XMLRPCArray *()
		{
			return boost::any_cast<XMLRPCArray>(&m_value);
		}

		operator const XMLRPCDateTime &() const
		{
			return boost::any_cast<const XMLRPCDateTime&>(m_value);
		}

		operator XMLRPCDateTime &()
		{
			return boost::any_cast<XMLRPCDateTime&>(m_value);
		}

		operator const XMLRPCDateTime *() const
		{
			return boost::any_cast<XMLRPCDateTime>(&m_value);
		}

		operator XMLRPCDateTime *()
		{
			return boost::any_cast<XMLRPCDateTime>(&m_value);
		}

		const ValueType& operator[](const std::string& str) const
		{
			return boost::any_cast<const Properties&>(m_value)[str];
		}

		ValueType& operator[](const std::string& str)
		{
			return boost::any_cast<Properties&>(m_value)[str];
		}

		ValueType& operator[](const char* str)
		{
			return boost::any_cast<Properties&>(m_value)[str];
		}

		const ValueType& operator[](const char* str) const
		{
			return boost::any_cast<const Properties&>(m_value)[str];
		}

		std::map< std::string, PropertyNode>* GetContainerPtr()
		{
			return boost::any_cast<Properties&>(m_value).GetContainerPtr();
		}

		bool IsBool() const
		{
			return m_value.type() == typeid(bool);
		}

		bool IsInteger() const
		{
			return m_value.type() == typeid(int);
		}

		bool IsString() const
		{
			return m_value.type() == typeid(std::string);
		}

		bool IsDouble() const
		{
			return m_value.type() == typeid(double);
		}

		bool IsProperties() const
		{
			return m_value.type() == typeid(Properties);
		}

		bool IsXMLRPCArray() const
		{
			return m_value.type() == typeid(XMLRPCArray);
		}

		bool IsXMLRPCDateTime() const
		{
			return m_value.type() == typeid(XMLRPCDateTime);
		}

		bool IsEqualType(const ValueType& v)
		{
			return m_value.type() == v.m_value.type();
		}
	};

	typedef std::vector<ValueType> XMLRPCArray;
public:
	struct PropertyNode
	{
	public:
		PropertyNode(): is_writable(true), value(Properties()) {}
        explicit PropertyNode(const ValueType& v): is_writable(true), value(v) {}
		void Reset()
		{
			is_writable = true;
			limitation_list.clear();
			value = ValueType();
		}

	public:
		bool is_writable;
		std::vector< boost::shared_ptr<IPropertiesValueLimitation> > limitation_list;
		ValueType value;
	};
public:
	typedef std::map<std::string, PropertyNode> Container;

	Properties();

	const Container* GetContainerPtr() const
	{
		return map_.get();
	}

	Container* GetContainerPtr()
	{
		return map_.get();
	}

	Properties(const Properties& rhs)
	{
		map_ = rhs.map_;
	}

	ValueType& operator[](const std::string& str)
	{
		return search(str);
	}

	const ValueType& operator[](const std::string& str) const
	{
		return search(str);
	}

	ValueType& operator[](const char* str)
	{
		return search(str);
	}

	const ValueType& operator[](const char* str) const
	{
		return search(str);
	}

	Properties& operator=(const Properties& rhs)
	{
		if(&rhs != this)
		{
			map_ = rhs.map_;
		}

		return *this;
	}

	bool Empty() const
	{
		return map_->empty();
	}

public:
	static void PropertyTreeToArray(const boost::property_tree::ptree& pt, XMLRPCArray& array);
	static void PropertyTreeToProperties(const boost::property_tree::ptree& pt, FBi::Properties& s1);
	static void ArrayToPropertyTree(const XMLRPCArray& array, boost::property_tree::ptree& pt);
	static void PropertiesToPropertyTree(const FBi::Properties& s1, boost::property_tree::ptree& pt);

	bool Import(const std::string& buf);
	bool Load(const std::string& filename);
	bool Save(const std::string& filename, bool use_indent = true) const;

	void Export(boost::property_tree::ptree&) const;

	ValueType& search(const std::string& str) const
	{
		return (*map_)[str].value;
		/*
		Container::iterator itor = map_.find(str);

		if (itor == map_.end())
		{
			return map_[str].value = Properties();
		}
		return itor->second.value;*/
	}

	// The following interface are ported from old Properties of hdvr
	boost::signals2::connection RegisterValueChangedSlot(const NotifySlotFunc& slot);

	bool Get(const std::string& node_path, ValueType& value) const;
	bool Set(const std::string& node_path, const ValueType& value);

	bool Get(const std::string& node_path, PropertyNode& extension) const;
	bool Put(const std::string& node_path, const PropertyNode& extension);

	bool Add(const std::string& node_path, const ValueType& value);
	bool Del(const std::string& node_path);

	bool ImportValues(Properties& imp_p, bool ignore_err);

	// Copy behaviour -- start
	bool GetProperties(const std::string& node_path, Properties& prop) const;
	bool Merge(const Properties&);
	static bool CopyXMLRPCArray(const XMLRPCArray& org_array, XMLRPCArray& result_array);
	// Copy behaviour -- end

private:
	void compose_map(const std::string& strPath, const boost::property_tree::ptree&);

	int tokenize(const std::string& str, const std::string& separator, std::deque<std::string>& tokens) const;
	void rollback(const std::deque<std::string>& rollback_nodes_paths, Properties& rollback_data);

	bool get_all_sub_properties(const Properties& org_prop, Properties& result_prop) const;
	bool handle_one_sub_properties(std::deque<std::string>& keys, const std::deque<std::string>::iterator& current_key_iter, const Properties& org_prop, Properties& result_prop) const;
	bool get_sub_properties(std::deque<std::string>& keys, const std::deque<std::string>::iterator& current_key_iter, const Properties& org_prop, Properties& result_prop) const;

	boost::shared_ptr<Container> map_;
	boost::signals2::signal<void (FBi::Properties&)> prop_signal_;
};

typedef std::vector<Properties::ValueType> XMLRPCArray;

} // namespace FBi
/*
typedef Loki::SingletonHolder
<
FBi::Properties
>
GlobalProperties;
*/
#endif

ext: hpp


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <boost/simd/ieee/include/functions/exponentbits.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/simd/include/functions/splat.hpp>

#include <nt2/sdk/unit/tests/relation.hpp>
#include <nt2/sdk/unit/module.hpp>

NT2_TEST_CASE_TPL ( exponentbits_real__1_0,  BOOST_SIMD_SIMD_REAL_TYPES)
{
  using boost::simd::exponentbits;
  using boost::simd::tag::exponentbits_;
  using boost::simd::native;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                 vT;

  for(int i=1; i < 10; i*= 2)
  {
    NT2_TEST_EQUAL(exponentbits(boost::simd::splat<vT>(i))[0],
                   exponentbits(T(i)));
  }
}


text:
#pragma once

#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/container/map.hpp>
#include <boost/fusion/container/map/map_fwd.hpp>
#include <boost/fusion/include/at_key.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/include/map_fwd.hpp>
#include <boost/fusion/include/zip_view.hpp>
#include <boost/fusion/sequence/intrinsic/at_key.hpp>
#include <boost/fusion/view/zip_view.hpp>
#include <boost/mpl/for_each.hpp>
#include <cassert>

#include <map>
#include "spectral/basis/spectral_function.hpp"

namespace boltzmann {

/**
 * Stores subelements (i.e. functions in phi, r coord. as std::map or std::vec)
 */
template <class... Args>
class SpectralElemCollection
{
 public:
  typedef boost::fusion::map<boost::fusion::pair<Args, std::map<typename Args::id_t, Args>>...>
      map_t;
  typedef boost::fusion::map<boost::fusion::pair<Args, std::vector<Args>>...> vec_t;

  const map_t &get_map() const
  {
    assert(is_finalized_ == true);
    return elems_;
  }
  const vec_t &get_vec() const
  {
    assert(is_finalized_ == true);
    return vec_;
  }

 private:
  typedef SpectralElemCollection<Args...> this_type;

 public:
  SpectralElemCollection()
      : finalizer_(this)
      , is_finalized_(false)
  {
  }

  // ----------------------------------------------------------------------
  // copy constructor
  SpectralElemCollection(const this_type &other)
      : finalizer_(other.finalizer_)
      , is_finalized_(other.is_finalized_)
  {
    boost::fusion::copy(other.elems_, elems_);
    boost::fusion::copy(other.vec_, vec_);
  }

  // ----------------------------------------------------------------------
  template <typename ELEM>
  void add_elem(const ELEM &elem)
  {
    assert(!is_finalized_);
    auto &elem_map = boost::fusion::at_key<ELEM>(elems_);
    if (elem_map.find(elem.get_id()) != elem_map.end()) {
      // element is already stored => do nothing
    } else {
      elem_map[elem.get_id()] = elem;
    }
  }

  // ----------------------------------------------------------------------
  void finalize()
  {
    assert(is_finalized_ == false);
    boost::fusion::for_each(elems_, finalizer_);
    is_finalized_ = true;
  }

 protected:
  struct finalizer_t
  {
    finalizer_t(this_type *ref)
        : ref_(ref)
    {
    }
    template <typename T>
    void operator()(const T &t) const
    {
      typedef typename T::first_type index_type;
      for (auto it = t.second.begin(); it != t.second.end(); ++it) {
        boost::fusion::at_key<index_type>(ref_->vec_).push_back(it->second);
      }
    }
    this_type *ref_;
  };

  finalizer_t finalizer_;
  map_t elems_;
  vec_t vec_;
  bool is_finalized_;
};
}


text:
/**
 *          Copyright Springbeats Sarl 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)
 */
#ifndef RPCMESSAGE_HPP
#define	RPCMESSAGE_HPP

#include <google/protobuf/service.h>
#include <ostream>
#include <istream>
#include <string>
#include <boost/shared_ptr.hpp>

using boost::shared_ptr;

using std::string;
using std::ostream;
using std::istream;

using google::protobuf::MethodDescriptor;
using google::protobuf::Message;

namespace pbrpcpp {
    class RpcController;

    class RpcMessage {
    public:
        enum {
            UNDEFINE_MSG = 0,
            REQUEST_MSG = 1,
            RESPONSE_MSG = 2,
            CANCEL_MSG = 3
        };

        enum {
            MAX_UDP_SIZE = 64 * 1024, //max size of UDP message
            TCP_MSG_BUFFER_SIZE = 4096 //buffer size of message over TCP/IP
        };

        /**
         * serialize a request message to the output stream out
         *
         * @param callId IN the unique callId to identify the request
         * @param method IN which method to call
         * @param request IN the request content
         * @param out OUT the serialization result output stream out
         */
        static void serializeRequest( const string& callId,
                    const MethodDescriptor& method,
                    const Message& request,
                    ostream& out );

        /**
         * serialize a response to a output stream out
         *
         * @param callId IN the unique callId passed from the request to server
         * @param controller IN the RPC controller
         * @param response IN optional response message, this message must be present if the no error indicated in the controller
         * @param out OUT the serialization result output stream out
         */
        static void serializeResponse( const string& callId,
                                            const RpcController& controller,
                                            const Message* response,
                                            ostream& out );

        /**
         * serialize a cancel request to the output stream out
         *
         * @param callId IN the unique request identifier
         * @param out OUT output stream to accept the serialization result
         */
        static void serializeCancel( const string& callId, ostream& out );

        /**
         * parse a request from a input stream in
         *
         * @param in IN the request input stream in
         * @param callId OUT user supplied buffer to accept the parsed callId
         * @param method OUT user supplied buffer to accept the parsed method
         * @param request OUT user supplied buffer to accept the parsed request message
         */
        static void parseRequestFrom( istream& in, string& callId, const MethodDescriptor*& method, shared_ptr<Message>& request );

        /**
         * parse a response from a input stream in
         * @param in IN the response input stream
         * @param callId OUT the user supplied buffer to accept the parsed request callId
         * @param controller OUT the user supplied buffer to accept the parsed controller
         * @param response OUT the user supplied buffer to accept the parsed response, this response maybe NULL if error information is in controller
         */
        static void parseResponseFrom( istream& in, string& callId, RpcController& controller, shared_ptr<Message>& response );

        /**
         * parse the cancel request from the input stream in
         * @param in the cancel request input stream in
         * @param callId OUT the user supplied buffer to accept the canceled request callId
         */
        static void parseCancelFrom( istream& in, string& callId );

        static string serializeNetPacket( const string& packet );

        /**
         * extract a Net packet serialized by serializeNetPacket() method
         *
         * @param s IN/OUT the packet serialized result by serializeNetPacket() method
         * after a packet is extracted, the string s will be shorten
         *
         * @param packet OUT the extracted packet
         * @return true if success to extract the packet from s
         */
        static bool extractNetPacket( string& s, string& packet );
    };

}//end name space pbrpcpp

#endif	/* RPCMESSAGE_HPP */

max_stars_repo_name: adanselm/pbRPCpp

max_issues_repo_name: adanselm/pbRPCpp

max_forks_repo_name: adanselm/pbRPCpp


text:
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
//  Use, modification and distribution are subject to the Boost Software
//  License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).
//
//  See http://www.boost.org/libs/type_traits for most recent version including
//  documentation.

#ifndef BOOST_TT_ADD_POINTER_HPP_INCLUDED
#define BOOST_TT_ADD_POINTER_HPP_INCLUDED

#include <boost/type_traits/remove_reference.hpp>

namespace boost
{

#if defined(__BORLANDC__) && (__BORLANDC__ < 0x5A0)
//
// For some reason this implementation stops Borlands compiler
// from dropping cv-qualifiers, it still fails with references
// to arrays for some reason though (shrug...) (JM 20021104)
//
template <typename T>
struct add_pointer
{
    typedef T* type;
};
template <typename T>
struct add_pointer<T&>
{
    typedef T* type;
};
template <typename T>
struct add_pointer<T& const>
{
    typedef T* type;
};
template <typename T>
struct add_pointer<T& volatile>
{
    typedef T* type;
};
template <typename T>
struct add_pointer<T& const volatile>
{
    typedef T* type;
};

#else

template <typename T>
struct add_pointer
{
    typedef typename remove_reference<T>::type no_ref_type;
    typedef no_ref_type* type;
};

#endif

#if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)

template <class T>
using add_pointer_t = typename add_pointer<T>::type;

#endif

} // namespace boost

#endif // BOOST_TT_ADD_POINTER_HPP_INCLUDED

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2011-2021 The Freicoin Developers
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of version 3 of the GNU Affero General Public License as published
// by the Free Software Foundation.
//
// This program 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 Affero General Public License for more
// details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#include <noui.h>

#include <ui_interface.h>
#include <util/system.h>

#include <cstdio>
#include <stdint.h>
#include <string>

#include <boost/signals2/connection.hpp>

bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
    bool fSecure = style & CClientUIInterface::SECURE;
    style &= ~CClientUIInterface::SECURE;

    std::string strCaption;
    // Check for usage of predefined caption
    switch (style) {
    case CClientUIInterface::MSG_ERROR:
        strCaption += _("Error");
        break;
    case CClientUIInterface::MSG_WARNING:
        strCaption += _("Warning");
        break;
    case CClientUIInterface::MSG_INFORMATION:
        strCaption += _("Information");
        break;
    default:
        strCaption += caption; // Use supplied caption (can be empty)
    }

    if (!fSecure)
        LogPrintf("%s: %s\n", strCaption, message);
    tfm::format(std::cerr, "%s: %s\n", strCaption.c_str(), message.c_str());
    return false;
}

bool noui_ThreadSafeQuestion(const std::string& /* ignored interactive message */, const std::string& message, const std::string& caption, unsigned int style)
{
    return noui_ThreadSafeMessageBox(message, caption, style);
}

void noui_InitMessage(const std::string& message)
{
    LogPrintf("init message: %s\n", message);
}

void noui_connect()
{
    uiInterface.ThreadSafeMessageBox_connect(noui_ThreadSafeMessageBox);
    uiInterface.ThreadSafeQuestion_connect(noui_ThreadSafeQuestion);
    uiInterface.InitMessage_connect(noui_InitMessage);
}

max_stars_repo_name: tradecraftio/tradecraft

max_issues_repo_name: tradecraftio/tradecraft

max_forks_repo_name: tradecraftio/tradecraft


text:
#include "vfxlab/RenderAdapter.h"
#include "vfxlab/PinType.h"
#include "vfxlab/RegistNodes.h"

#include <blueprint/Pin.h>

#include <unirender/Device.h>
#include <facade/ImageLoader.h>

#include <boost/filesystem.hpp>

namespace
{

std::vector<std::pair<int, vfxgraph::VarType>> PAIR_TYPES =
{
    { bp::PIN_PORT,            vfxgraph::VarType::Port },
    { bp::PIN_ANY_VAR,         vfxgraph::VarType::Any },
	{ vfxlab::PIN_TEXTURE,     vfxgraph::VarType::Texture },
	{ vfxlab::PIN_FLOAT,       vfxgraph::VarType::Float },
	{ vfxlab::PIN_FLOAT2,      vfxgraph::VarType::Float2 },
	{ vfxlab::PIN_FLOAT3,      vfxgraph::VarType::Float3 },
	{ vfxlab::PIN_FLOAT4,      vfxgraph::VarType::Float4 },
};

}

namespace vfxlab
{

int RenderAdapter::TypeBackToFront(vfxgraph::VarType type, int count)
{
    int ret = -1;

	for (auto& pair : PAIR_TYPES) {
		if (pair.second == type) {
			ret = pair.first;
			break;
		}
	}
	assert(ret >= 0);

    return ret;
}

vfxgraph::VarType RenderAdapter::TypeFrontToBack(int type)
{
	for (auto& pair : PAIR_TYPES) {
		if (pair.first == type) {
			return pair.second;
		}
	}
	assert(0);
	return vfxgraph::VarType::Unknown;
}

void RenderAdapter::Front2Back(const ur::Device& dev, const bp::Node& front,
                               dag::Node<vfxgraph::Variant>& back, const std::string& dir)
{
    auto type = front.get_type();
    if (type == rttr::type::get<node::Texture>())
    {
        auto& src = static_cast<const node::Texture&>(front);
        auto& dst = static_cast<vfxgraph::node::Texture&>(back);

        // update texture
        if (src.m_filepath != dst.GetFilepath() ||
            !dst.GetTexture())
        {
            auto filepath = boost::filesystem::absolute(src.m_filepath, dir).string();
            facade::ImageLoader loader(filepath);

            if (loader.Load(dev)) {
                dst.SetFilepath(filepath);
                dst.SetTexture(loader.GetTexture());
            } else {
                dst.SetFilepath("");
                dst.SetTexture(nullptr);
            }
        }

        // update sample
        if (src.m_wrap != dst.GetWrapping() ||
            src.m_filter != dst.GetFiltering() ||
            !dst.GetSampler())
        {
            ur::TextureWrap ur_wrap;
            switch (src.m_wrap)
            {
            case vfxgraph::node::Texture::Wrapping::Repeat:
                ur_wrap = ur::TextureWrap::Repeat;
                break;
            case vfxgraph::node::Texture::Wrapping::MirroredRepeat:
                ur_wrap = ur::TextureWrap::MirroredRepeat;
                break;
            case vfxgraph::node::Texture::Wrapping::ClampToEdge:
                ur_wrap = ur::TextureWrap::ClampToEdge;
                break;
            case vfxgraph::node::Texture::Wrapping::ClampToBorder:
                ur_wrap = ur::TextureWrap::ClampToBorder;
                break;
            default:
                assert(0);
            }

            ur::TextureMinificationFilter ur_min_filter;
            ur::TextureMagnificationFilter ur_mag_filter;
            switch (src.m_filter)
            {
            case vfxgraph::node::Texture::Filtering::Nearest:
                ur_min_filter = ur::TextureMinificationFilter::Nearest;
                ur_mag_filter = ur::TextureMagnificationFilter::Nearest;
                break;
            case vfxgraph::node::Texture::Filtering::Linear:
                ur_min_filter = ur::TextureMinificationFilter::Linear;
                ur_mag_filter = ur::TextureMagnificationFilter::Linear;
                break;
            }

            dst.SetWrapping(src.m_wrap);
            dst.SetFiltering(src.m_filter);

            auto sampler = dev.CreateTextureSampler(ur_min_filter, ur_mag_filter, ur_wrap, ur_wrap);
            dst.SetSampler(sampler);
        }
    }
}

}

max_stars_repo_name: xzrunner/vfxlab

max_issues_repo_name: xzrunner/vfxlab

max_forks_repo_name: xzrunner/vfxlab


text:
/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. 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 OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <boost/bind.hpp>

#include <OgreManualObject.h>
#include <OgreMaterialManager.h>
#include <OgreSceneManager.h>
#include <OgreSceneNode.h>
#include <OgreTextureManager.h>
#include <OgreTechnique.h>
#include <OgreSharedPtr.h>

#include <ros/ros.h>

#include <tf/transform_listener.h>

#include "rviz/frame_manager.h"
#include "rviz/ogre_helpers/custom_parameter_indices.h"
#include "rviz/ogre_helpers/grid.h"
#include "rviz/properties/enum_property.h"
#include "rviz/properties/float_property.h"
#include "rviz/properties/int_property.h"
#include "rviz/properties/property.h"
#include "rviz/properties/quaternion_property.h"
#include "rviz/properties/ros_topic_property.h"
#include "rviz/properties/vector_property.h"
#include "rviz/validate_floats.h"
#include "rviz/display_context.h"

#include "map_display.h"

namespace rviz
{

// helper class to set alpha parameter on all renderables.
class AlphaSetter: public Ogre::Renderable::Visitor
{
public:
  AlphaSetter( float alpha )
  : alpha_vec_( alpha, alpha, alpha, alpha )
  {}

  void visit( Ogre::Renderable *rend, ushort lodIndex, bool isDebug, Ogre::Any *pAny=0)
  {
    rend->setCustomParameter( ALPHA_PARAMETER, alpha_vec_ );
  }
private:
  Ogre::Vector4 alpha_vec_;
};

Swatch::Swatch(MapDisplay* parent, unsigned int x, unsigned int y, unsigned int width, unsigned int height, float resolution)
  : parent_(parent), manual_object_( NULL ), x_(x), y_(y), width_(width), height_(height)
{
  // Set up map material
  static int material_count = 0;
  std::stringstream ss;
  ss << "MapMaterial" << material_count++;
  material_ = Ogre::MaterialManager::getSingleton().getByName("rviz/Indexed8BitImage");
  material_ = material_->clone( ss.str() );

  material_->setReceiveShadows(false);
  material_->getTechnique(0)->setLightingEnabled(false);
  material_->setDepthBias( -16.0f, 0.0f );
  material_->setCullingMode( Ogre::CULL_NONE );
  material_->setDepthWriteEnabled(false);

  static int map_count = 0;
  std::stringstream ss2;
  ss2 << "MapObject" << map_count++;
  manual_object_ = parent_->scene_manager_->createManualObject( ss2.str() );

  static int node_count = 0;
  std::stringstream ss3;
  ss3 << "NodeObject" << node_count++;

  scene_node_ = parent_->scene_node_->createChildSceneNode(ss3.str());
  scene_node_->attachObject( manual_object_ );

  manual_object_->begin(material_->getName(), Ogre::RenderOperation::OT_TRIANGLE_LIST);
  {
    // First triangle
    {
      // Bottom left
      manual_object_->position( 0.0f, 0.0f, 0.0f );
      manual_object_->textureCoord(0.0f, 0.0f);
      manual_object_->normal( 0.0f, 0.0f, 1.0f );

      // Top right
      manual_object_->position( 1.0f, 1.0f, 0.0f );
      manual_object_->textureCoord(1.0f, 1.0f);
      manual_object_->normal( 0.0f, 0.0f, 1.0f );

      // Top left
      manual_object_->position( 0.0f, 1.0f, 0.0f );
      manual_object_->textureCoord(0.0f, 1.0f);
      manual_object_->normal( 0.0f, 0.0f, 1.0f );
    }

    // Second triangle
    {
      // Bottom left
      manual_object_->position( 0.0f, 0.0f, 0.0f );
      manual_object_->textureCoord(0.0f, 0.0f);
      manual_object_->normal( 0.0f, 0.0f, 1.0f );

      // Bottom right
      manual_object_->position( 1.0f, 0.0f, 0.0f );
      manual_object_->textureCoord(1.0f, 0.0f);
      manual_object_->normal( 0.0f, 0.0f, 1.0f );

      // Top right
      manual_object_->position( 1.0f, 1.0f, 0.0f );
      manual_object_->textureCoord(1.0f, 1.0f);
      manual_object_->normal( 0.0f, 0.0f, 1.0f );
    }
  }
  manual_object_->end();

  scene_node_->setPosition( x*resolution, y*resolution, 0 );
  scene_node_->setScale( width*resolution, height*resolution, 1.0 );

  if( parent_->draw_under_property_->getValue().toBool() )
  {
    manual_object_->setRenderQueueGroup(Ogre::RENDER_QUEUE_4);
  }

  // don't show map until the plugin is actually enabled
  manual_object_->setVisible( false );

}

Swatch::~Swatch()
{
  parent_->scene_manager_->destroyManualObject(manual_object_);
}

void Swatch::updateAlpha(const Ogre::SceneBlendType sceneBlending, bool depthWrite, AlphaSetter* alpha_setter)
{
  Ogre::Pass* pass = material_->getTechnique( 0 )->getPass( 0 );
  Ogre::TextureUnitState* tex_unit = NULL;

  material_->setSceneBlending( sceneBlending );
  material_->setDepthWriteEnabled( depthWrite );
  if( manual_object_ )
  {
    manual_object_->visitRenderables( alpha_setter );
  }
}

void Swatch::updateData()
{
  unsigned int pixels_size = width_ * height_;
  unsigned char* pixels = new unsigned char[pixels_size];
  memset(pixels, 255, pixels_size);
  unsigned char* ptr = pixels;
  int N = parent_->current_map_.data.size();
  unsigned int fw = parent_->current_map_.info.width;

  for(unsigned int yy=y_; yy<y_+height_;yy++){
    int index = yy * fw + x_;
    int pixels_to_copy = std::min((int)width_, N-index);
    memcpy(ptr, &parent_->current_map_.data[ index ], pixels_to_copy);
    ptr+=pixels_to_copy;
    if(index+pixels_to_copy>=N) break;
  }

  Ogre::DataStreamPtr pixel_stream;
  pixel_stream.bind( new Ogre::MemoryDataStream( pixels, pixels_size ));

  if( !texture_.isNull() )
  {
    Ogre::TextureManager::getSingleton().remove( texture_->getName() );
    texture_.setNull();
  }

  static int tex_count = 0;
  std::stringstream ss;
  ss << "MapTexture" << tex_count++;
  texture_ = Ogre::TextureManager::getSingleton().loadRawData( ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
                                                                 pixel_stream, width_, height_, Ogre::PF_L8, Ogre::TEX_TYPE_2D,
                                                                 0);

  delete pixels;
}

MapDisplay::MapDisplay()
  : Display()
  , loaded_( false )
  , resolution_( 0.0f )
  , width_( 0 )
  , height_( 0 )
{
  connect(this, SIGNAL( mapUpdated() ), this, SLOT( showMap() ));
  topic_property_ = new RosTopicProperty( "Topic", "",
                                          QString::fromStdString( ros::message_traits::datatype<nav_msgs::OccupancyGrid>() ),
                                          "nav_msgs::OccupancyGrid topic to subscribe to.",
                                          this, SLOT( updateTopic() ));

  alpha_property_ = new FloatProperty( "Alpha", 0.7,
                                       "Amount of transparency to apply to the map.",
                                       this, SLOT( updateAlpha() ));
  alpha_property_->setMin( 0 );
  alpha_property_->setMax( 1 );

  color_scheme_property_ = new EnumProperty( "Color Scheme", "map", "How to color the occupancy values.",
                                             this, SLOT( updatePalette() ));
  // Option values here must correspond to indices in palette_textures_ array in onInitialize() below.
  color_scheme_property_->addOption( "map", 0 );
  color_scheme_property_->addOption( "costmap", 1 );
  color_scheme_property_->addOption( "raw", 2 );

  draw_under_property_ = new Property( "Draw Behind", false,
                                       "Rendering option, controls whether or not the map is always"
                                       " drawn behind everything else.",
                                       this, SLOT( updateDrawUnder() ));

  resolution_property_ = new FloatProperty( "Resolution", 0,
                                            "Resolution of the map. (not editable)", this );
  resolution_property_->setReadOnly( true );

  width_property_ = new IntProperty( "Width", 0,
                                     "Width of the map, in meters. (not editable)", this );
  width_property_->setReadOnly( true );

  height_property_ = new IntProperty( "Height", 0,
                                      "Height of the map, in meters. (not editable)", this );
  height_property_->setReadOnly( true );

  position_property_ = new VectorProperty( "Position", Ogre::Vector3::ZERO,
                                           "Position of the bottom left corner of the map, in meters. (not editable)",
                                           this );
  position_property_->setReadOnly( true );

  orientation_property_ = new QuaternionProperty( "Orientation", Ogre::Quaternion::IDENTITY,
                                                  "Orientation of the map. (not editable)",
                                                  this );
  orientation_property_->setReadOnly( true );

  unreliable_property_ = new BoolProperty( "Unreliable", false,
                                           "Prefer UDP topic transport",
                                           this,
                                           SLOT( updateTopic() ));

  transform_timestamp_property_ = new BoolProperty( "Use Timestamp", false,
                                                    "Use map header timestamp when transforming",
                                                    this,
                                                    SLOT( transformMap() ));
}

MapDisplay::~MapDisplay()
{
  unsubscribe();
  clear();
  for (unsigned i=0; i < swatches.size(); i++){
      delete swatches[i];
  }
  swatches.clear();
}

unsigned char* makeMapPalette()
{
  unsigned char* palette = new unsigned char[256*4];
  unsigned char* palette_ptr = palette;
  // Standard gray map palette values
  for( int i = 0; i <= 100; i++ )
  {
    unsigned char v = 255 - (255 * i) / 100;
    *palette_ptr++ = v; // red
    *palette_ptr++ = v; // green
    *palette_ptr++ = v; // blue
    *palette_ptr++ = 255; // alpha
  }
  // illegal positive values in green
  for( int i = 101; i <= 127; i++ )
  {
    *palette_ptr++ = 0; // red
    *palette_ptr++ = 255; // green
    *palette_ptr++ = 0; // blue
    *palette_ptr++ = 255; // alpha
  }
  // illegal negative (char) values in shades of red/yellow
  for( int i = 128; i <= 254; i++ )
  {
    *palette_ptr++ = 255; // red
    *palette_ptr++ = (255*(i-128))/(254-128); // green
    *palette_ptr++ = 0; // blue
    *palette_ptr++ = 255; // alpha
  }
  // legal -1 value is tasteful blueish greenish grayish color
  *palette_ptr++ = 0x70; // red
  *palette_ptr++ = 0x89; // green
  *palette_ptr++ = 0x86; // blue
  *palette_ptr++ = 255; // alpha

  return palette;
}

unsigned char* makeCostmapPalette()
{
  unsigned char* palette = new unsigned char[256*4];
  unsigned char* palette_ptr = palette;

  // zero values have alpha=0
  *palette_ptr++ = 0; // red
  *palette_ptr++ = 0; // green
  *palette_ptr++ = 0; // blue
  *palette_ptr++ = 0; // alpha

  // Blue to red spectrum for most normal cost values
  for( int i = 1; i <= 98; i++ )
  {
    unsigned char v = (255 * i) / 100;
    *palette_ptr++ = v; // red
    *palette_ptr++ = 0; // green
    *palette_ptr++ = 255 - v; // blue
    *palette_ptr++ = 255; // alpha
  }
  // inscribed obstacle values (99) in cyan
  *palette_ptr++ = 0; // red
  *palette_ptr++ = 255; // green
  *palette_ptr++ = 255; // blue
  *palette_ptr++ = 255; // alpha
  // lethal obstacle values (100) in purple
  *palette_ptr++ = 255; // red
  *palette_ptr++ = 0; // green
  *palette_ptr++ = 255; // blue
  *palette_ptr++ = 255; // alpha
  // illegal positive values in green
  for( int i = 101; i <= 127; i++ )
  {
    *palette_ptr++ = 0; // red
    *palette_ptr++ = 255; // green
    *palette_ptr++ = 0; // blue
    *palette_ptr++ = 255; // alpha
  }
  // illegal negative (char) values in shades of red/yellow
  for( int i = 128; i <= 254; i++ )
  {
    *palette_ptr++ = 255; // red
    *palette_ptr++ = (255*(i-128))/(254-128); // green
    *palette_ptr++ = 0; // blue
    *palette_ptr++ = 255; // alpha
  }
  // legal -1 value is tasteful blueish greenish grayish color
  *palette_ptr++ = 0x70; // red
  *palette_ptr++ = 0x89; // green
  *palette_ptr++ = 0x86; // blue
  *palette_ptr++ = 255; // alpha

  return palette;
}

unsigned char* makeRawPalette()
{
  unsigned char* palette = new unsigned char[256*4];
  unsigned char* palette_ptr = palette;
  // Standard gray map palette values
  for( int i = 0; i < 256; i++ )
  {
    *palette_ptr++ = i; // red
    *palette_ptr++ = i; // green
    *palette_ptr++ = i; // blue
    *palette_ptr++ = 255; // alpha
  }

  return palette;
}

Ogre::TexturePtr makePaletteTexture( unsigned char *palette_bytes )
{
  Ogre::DataStreamPtr palette_stream;
  palette_stream.bind( new Ogre::MemoryDataStream( palette_bytes, 256*4 ));

  static int palette_tex_count = 0;
  std::stringstream ss;
  ss << "MapPaletteTexture" << palette_tex_count++;
  return Ogre::TextureManager::getSingleton().loadRawData( ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
                                                           palette_stream, 256, 1, Ogre::PF_BYTE_RGBA, Ogre::TEX_TYPE_1D, 0 );
}

void MapDisplay::onInitialize()
{
  // Order of palette textures here must match option indices for color_scheme_property_ above.
  palette_textures_.push_back( makePaletteTexture( makeMapPalette() ));
  color_scheme_transparency_.push_back( false );
  palette_textures_.push_back( makePaletteTexture( makeCostmapPalette() ));
  color_scheme_transparency_.push_back( true );
  palette_textures_.push_back( makePaletteTexture( makeRawPalette() ));
  color_scheme_transparency_.push_back( true );
}

void MapDisplay::onEnable()
{
  subscribe();
}

void MapDisplay::onDisable()
{
  unsubscribe();
  clear();
}

void MapDisplay::subscribe()
{
  if ( !isEnabled() )
  {
    return;
  }

  if( !topic_property_->getTopic().isEmpty() )
  {
    try
    {
      if(unreliable_property_->getBool())
      {
        map_sub_ = update_nh_.subscribe( topic_property_->getTopicStd(), 1, &MapDisplay::incomingMap, this,  ros::TransportHints().unreliable());
      }else{
        map_sub_ = update_nh_.subscribe( topic_property_->getTopicStd(), 1, &MapDisplay::incomingMap, this, ros::TransportHints().reliable() );
      }
      setStatus( StatusProperty::Ok, "Topic", "OK" );
    }
    catch( ros::Exception& e )
    {
      setStatus( StatusProperty::Error, "Topic", QString( "Error subscribing: " ) + e.what() );
    }

    try
    {
      update_sub_ = update_nh_.subscribe( topic_property_->getTopicStd() + "_updates", 1, &MapDisplay::incomingUpdate, this );
      setStatus( StatusProperty::Ok, "Update Topic", "OK" );
    }
    catch( ros::Exception& e )
    {
      setStatus( StatusProperty::Error, "Update Topic", QString( "Error subscribing: " ) + e.what() );
    }
  }
}

void MapDisplay::unsubscribe()
{
  map_sub_.shutdown();
  update_sub_.shutdown();
}

void MapDisplay::updateAlpha()
{
  float alpha = alpha_property_->getFloat();
  Ogre::SceneBlendType sceneBlending;
  bool depthWrite;

  if( alpha < 0.9998 || color_scheme_transparency_[ color_scheme_property_->getOptionInt() ])
  {
    sceneBlending = Ogre::SBT_TRANSPARENT_ALPHA;
    depthWrite = false;
  }
  else
  {
    sceneBlending = Ogre::SBT_REPLACE;
    depthWrite = !draw_under_property_->getValue().toBool();
  }

  AlphaSetter alpha_setter( alpha );

  for (unsigned i=0; i < swatches.size(); i++) {
    swatches[i]->updateAlpha(sceneBlending, depthWrite, &alpha_setter);
  }
}

void MapDisplay::updateDrawUnder()
{
  bool draw_under = draw_under_property_->getValue().toBool();

  if( alpha_property_->getFloat() >= 0.9998 )
  {
    for (unsigned i=0; i < swatches.size(); i++)
      swatches[i]->material_->setDepthWriteEnabled( !draw_under );
  }

  int group = draw_under ? Ogre::RENDER_QUEUE_4 : Ogre::RENDER_QUEUE_MAIN;
  for (unsigned i=0; i < swatches.size(); i++){
    if( swatches[i]->manual_object_ )
      swatches[i]->manual_object_->setRenderQueueGroup( group );
  }
}

void MapDisplay::updateTopic()
{
  unsubscribe();
  subscribe();
  clear();
}

void MapDisplay::clear()
{
  setStatus( StatusProperty::Warn, "Message", "No map received" );

  if( !loaded_ )
  {
    return;
  }

  for (unsigned i=0; i < swatches.size(); i++){
    if( swatches[i]->manual_object_ )
      swatches[i]->manual_object_->setVisible( false );

    if( !swatches[i]->texture_.isNull() )
    {
      Ogre::TextureManager::getSingleton().remove( swatches[i]->texture_->getName() );
      swatches[i]->texture_.setNull();
    }
  }

  loaded_ = false;
}

bool validateFloats(const nav_msgs::OccupancyGrid& msg)
{
  bool valid = true;
  valid = valid && validateFloats( msg.info.resolution );
  valid = valid && validateFloats( msg.info.origin );
  return valid;
}

void MapDisplay::incomingMap(const nav_msgs::OccupancyGrid::ConstPtr& msg)
{
  current_map_ = *msg;
  // updated via signal in case ros spinner is in a different thread
  Q_EMIT mapUpdated();
  loaded_ = true;
}

void MapDisplay::incomingUpdate(const map_msgs::OccupancyGridUpdate::ConstPtr& update)
{
  // Only update the map if we have gotten a full one first.
  if( !loaded_ )
  {
    return;
  }

  // Reject updates which have any out-of-bounds data.
  if( update->x < 0 ||
      update->y < 0 ||
      current_map_.info.width < update->x + update->width ||
      current_map_.info.height < update->y + update->height )
  {
    setStatus( StatusProperty::Error, "Update", "Update area outside of original map area." );
    return;
  }

  // Copy the incoming data into current_map_'s data.
  for( size_t y = 0; y < update->height; y++ )
  {
    memcpy( &current_map_.data[ (update->y + y) * current_map_.info.width + update->x ],
            &update->data[ y * update->width ],
            update->width );
  }
  // updated via signal in case ros spinner is in a different thread
  Q_EMIT mapUpdated();
}

void MapDisplay::createSwatches()
{
  int width = current_map_.info.width;
  int height = current_map_.info.height;
  float resolution = current_map_.info.resolution;

  int sw = width;
  int sh = height;
  int n_swatches = 1;

  for(int i=0;i<4;i++){
    ROS_INFO("Creating %d swatches", n_swatches);
    for (unsigned i=0; i < swatches.size(); i++){
        delete swatches[i];
    }
    swatches.clear();
    try
    {
      int x = 0;
      int y = 0;
      for(int i=0;i<n_swatches;i++){
        int tw, th;
        if(width - x - sw >= sw)
          tw = sw;
        else
          tw = width - x;

        if(height - y - sh >= sh)
          th = sh;
        else
          th = height - y;

        swatches.push_back(new Swatch(this, x, y, tw, th, resolution));
        swatches[i]->updateData();

        x += tw;
        if(x>=width){
            x = 0;
            y += sh;
        }
      }
      updateAlpha();
      return;
    }catch(Ogre::RenderingAPIException&)
    {
        ROS_WARN("Failed to create %d swatches", n_swatches);
        if(sw>sh) sw/=2;
        else      sh/=2;
        n_swatches *= 2;
    }
  }
}

void MapDisplay::showMap()
{
  if (current_map_.data.empty())
  {
    return;
  }

  if( !validateFloats( current_map_ ))
  {
    setStatus( StatusProperty::Error, "Map", "Message contained invalid floating point values (nans or infs)" );
    return;
  }

  if( current_map_.info.width * current_map_.info.height == 0 )
  {
    std::stringstream ss;
    ss << "Map is zero-sized (" << current_map_.info.width << "x" << current_map_.info.height << ")";
    setStatus( StatusProperty::Error, "Map", QString::fromStdString( ss.str() ));
    return;
  }

  setStatus( StatusProperty::Ok, "Message", "Map received" );

  ROS_DEBUG( "Received a %d X %d map @ %.3f m/pix\n",
             current_map_.info.width,
             current_map_.info.height,
             current_map_.info.resolution );

  float resolution = current_map_.info.resolution;

  int width = current_map_.info.width;
  int height = current_map_.info.height;

  if(width != width_ || height != height_){
    createSwatches();
    width_ = width;
    height_ = height;
  }

  Ogre::Vector3 position( current_map_.info.origin.position.x,
                          current_map_.info.origin.position.y,
                          current_map_.info.origin.position.z );
  Ogre::Quaternion orientation( current_map_.info.origin.orientation.w,
                                current_map_.info.origin.orientation.x,
                                current_map_.info.origin.orientation.y,
                                current_map_.info.origin.orientation.z );
  frame_ = current_map_.header.frame_id;
  if (frame_.empty())
  {
    frame_ = "/map";
  }

  bool map_status_set = false;
  if( width * height != current_map_.data.size() )
  {
    std::stringstream ss;
    ss << "Data size doesn't match width*height: width = " << width
       << ", height = " << height << ", data size = " << current_map_.data.size();
    setStatus( StatusProperty::Error, "Map", QString::fromStdString( ss.str() ));
    map_status_set = true;
  }

  for(int i=0;i<swatches.size();i++){
    swatches[i]->updateData();

    Ogre::Pass* pass = swatches[i]->material_->getTechnique(0)->getPass(0);
    Ogre::TextureUnitState* tex_unit = NULL;
    if (pass->getNumTextureUnitStates() > 0)
    {
      tex_unit = pass->getTextureUnitState(0);
    }
    else
    {
      tex_unit = pass->createTextureUnitState();
    }

    tex_unit->setTextureName(swatches[i]->texture_->getName());
    tex_unit->setTextureFiltering( Ogre::TFO_NONE );
    swatches[i]->manual_object_->setVisible( true );
  }

  if( !map_status_set )
  {
    setStatus( StatusProperty::Ok, "Map", "Map OK" );
  }
  updatePalette();

  resolution_property_->setValue( resolution );
  width_property_->setValue( width );
  height_property_->setValue( height );
  position_property_->setVector( position );
  orientation_property_->setQuaternion( orientation );

  transformMap();

  context_->queueRender();
}

void MapDisplay::updatePalette()
{
  int palette_index = color_scheme_property_->getOptionInt();

  for (unsigned i=0; i < swatches.size(); i++){
    Ogre::Pass* pass = swatches[i]->material_->getTechnique(0)->getPass(0);
    Ogre::TextureUnitState* palette_tex_unit = NULL;
    if( pass->getNumTextureUnitStates() > 1 )
    {
      palette_tex_unit = pass->getTextureUnitState( 1 );
    }
    else
    {
      palette_tex_unit = pass->createTextureUnitState();
    }
    palette_tex_unit->setTextureName( palette_textures_[ palette_index ]->getName() );
    palette_tex_unit->setTextureFiltering( Ogre::TFO_NONE );
  }

  updateAlpha();
}

void MapDisplay::transformMap()
{
  if (!loaded_)
  {
    return;
  }

  ros::Time transform_time;

  if (transform_timestamp_property_->getBool())
  {
    transform_time = current_map_.header.stamp;
  }

  Ogre::Vector3 position;
  Ogre::Quaternion orientation;
  if (!context_->getFrameManager()->transform(frame_, transform_time, current_map_.info.origin, position, orientation) &&
      !context_->getFrameManager()->transform(frame_, ros::Time(0), current_map_.info.origin, position, orientation))
  {
    ROS_DEBUG( "Error transforming map '%s' from frame '%s' to frame '%s'",
               qPrintable( getName() ), frame_.c_str(), qPrintable( fixed_frame_ ));

    setStatus( StatusProperty::Error, "Transform",
               "No transform from [" + QString::fromStdString( frame_ ) + "] to [" + fixed_frame_ + "]" );
  }
  else
  {
    setStatus(StatusProperty::Ok, "Transform", "Transform OK");
  }

  scene_node_->setPosition( position );
  scene_node_->setOrientation( orientation );
}

void MapDisplay::fixedFrameChanged()
{
  transformMap();
}

void MapDisplay::reset()
{
  Display::reset();

  clear();
  // Force resubscription so that the map will be re-sent
  updateTopic();
}

void MapDisplay::setTopic( const QString &topic, const QString &datatype )
{
  topic_property_->setString( topic );
}

void MapDisplay::update( float wall_dt, float ros_dt ) {
  transformMap();
}

} // namespace rviz

#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS( rviz::MapDisplay, rviz::Display )


text:
/*! \file ExtractACM-XMLfromCreoModels.cpp
    \brief The main(...) function for ExtractACM-XMLfromCreoModels.exe

	ExtractACM-XMLfromCreoModels.exe opens an assembly with "Creo Parametric 3.0" (i.e. PTC's ( http://www.ptc.com/ )  parametric solids modeler)
	and calls ISIS added library functions to export an XML files representing that assembly for use with GME.

	Pre-Conditions:

		1.	"Creo Parametric 3.0" must be installed and functioning properly on your machine.  The license for
			"Creo Parametric" does not need the the Toolkit license.  The toolkit license is only
			needed during development.

		2.	For information on configuring the system, see registry entry META_PATH + bin\CAD\Creo\0Readme - CreateAssembly.txt

		3.	The requirements for the arguments passed to  are defined in cc_ExtractACMInputArgumentsParser.h

	Post-Conditions:

		1.	If an exception occurs, the program will display the error message to the console,
			and exit.

			Some reasons that exceptions could occur follow:

-              Could not locate a part/assembly.

-              Missing required parameters.

-              Could not start Creo properly.

	2.	This program uses UDM 64 bit version to parse the XML file.  Therefore, UDM (http://repo.isis.vanderbilt.edu/UDM)
		64 bit must be installed.

*/
#include <isis_application_exception.h>
#include <CommonUtilities.h>
#include <ISISConstants.h>

#include <AssembleUtils.h>

#include "CADEnvironmentSettings.h"
#include "cc_ExtractACMInputArgumentsParser.h"
#include "cc_WindowsFunctions.h"
#include <ISISVersionNumber.h>

#include <string>
#include <sstream>
#include <iostream>
#include <time.h>

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <boost/thread/thread.hpp>

#include <boost/filesystem.hpp>
#include <boost/exception/all.hpp>

#include <iostream>

#include <boost/filesystem.hpp>

#include "CreoModelToCyphyXML.h"

#include "CommonFeatureUtils.h"
#include <cc_CommonUtilities.h>
#include "cc_CADFactoryAbstract.h"
#include "CADFactoryCreo.h"

static ProError ProTermAction( ProeTerminationStatus term_type )
{
	std::stringstream errorString;
	errorString << "Creo-Parametric has terminated with status : " << term_type;
						throw isis::application_exception("Creo-Parametric has terminated with status : " + term_type);
	return PRO_TK_NO_ERROR;
}

// determine if the creo file name is a part file or an assembly file
// kind of tricky since creo adds a ".number" extension for revision control
// returns true if the file is ASM, false if not (i.e. it is a PRT or unknown type)
static bool fileISasm(string sourcefile)
{
	int locateASM = sourcefile.rfind(".asm");
    int locatePRT = sourcefile.rfind(".prt");

    if (locateASM > locatePRT)
    {
		return true;
	}
    else
    {
		return false;
	}
}

static string getpartname(string sourcefile)
{
	int location = sourcefile.rfind(".asm");
	if (location == string::npos)
    {
		location = sourcefile.rfind(".prt");
	}
	return sourcefile.substr(0, location);
}

int ExtractACM_XML_main( int argc, char *argv[] )
{
	const std::string ASSEMBLE_PTC_VERSION = ISIS_PRODUCT_VERSION_WITH_v_AND_DOTS;

	int ExitCode = 0;

	std::string			creoStartCommand;
	std::string			CADExtensionsDir;

	std::string			templateFile_PathAndFileName;
	std::stringstream	exceptionErrorStringStream;
	bool				promptBeforeExiting;

	bool Pro_E_Running = false;

	isis::ExtractACMInputArguments  programInputArguments;
	programInputArguments.logFileName = "DefaultLogFile.log";
	::boost::filesystem::path    workingDir;

	std::string			exeName = "ExtractACM-XMLfromCreoModels.exe";

	std::stringstream inputLine;

	try
	{

		// Build string of input line
        for(int i = 0; i < argc; ++i)
        {
            inputLine << argv[i] << std::string(" ");
        }

		cout << "ExtractACM-XMLfromCreoModels "<< ASSEMBLE_PTC_VERSION;

// STEP 1: Parse Input Arguments
		programInputArguments.ParseInputArguments(argc, argv);

		promptBeforeExiting = programInputArguments.promptBeforeExiting;

// STEP 2: Configure the Creo start command string
		// Must get the complete path to the working directory.  This is necessary because when
		// isis_ProDirectoryChange is called to change to a STEP directory, workingDir must be fully
		// defined so that isis_ProDirectoryChange can be called to return to the original directory.
		workingDir = isis::SetupWorkingDirectory( programInputArguments.workingDirectory );

		if ( workingDir.generic_string().size() >= PRO_PATH_SIZE )  // PRO_PATH_SIZE   260
		{
			std::stringstream errorString;
			errorString << "WORKING_DIR string too long.  Maximum allowed number of characters: "  << PRO_PATH_SIZE - 1 << " WORKING_DIR string: " << workingDir;
					throw isis::application_exception(errorString);
		}
		::boost::filesystem::current_path(workingDir);

		// ***********************  Begin: Setup one one and only one time per exe ***********************************
		isis::cad::CadFactoryAbstract_global cadFactoryAbstract_global;
		isis::cad::CadFactoryAbstract_global *cadFactoryAbstract_global_ptr = isis::cad::CadFactoryAbstract_global::instance();
		// Call the following function one and only one time per executable.
		cadFactoryAbstract_global_ptr->setCadFactoryAbstract_ptr(isis::cad::creo::create());
		// ***********************  End: Setup sone one and only one time per exe *************************************

		isis::cad::CadFactoryAbstract::ptr	cAD_Factory_ptr = cadFactoryAbstract_global_ptr->getCadFactoryAbstract_ptr();
		//isis::cad::CadFactoryAbstract::ptr cAD_Factory = isis::cad::creo::create();
		isis::cad::ICADSession&           cADSession = cAD_Factory_ptr->getCADSession();

		cADSession.setupCADEnvironment(	programInputArguments,
											creoStartCommand,								// out
											CADExtensionsDir,								// out
											templateFile_PathAndFileName );					// out

// STEP 3: Start Creo in async mode
			char tempBuffer[1024];

			strcpy(tempBuffer, creoStartCommand.c_str() );

			cout << endl << "Starting Creo-Parametric, this takes about 10 seconds..." << endl ;

			ProError err = isis::isis_ProEngineerStart(tempBuffer,"");

			Pro_E_Running = true;

			// callback in case Creo ends with an error
			ProTermFuncSet(ProTermAction);

// STEP 4: Open the file
			ProMdl mdl;
			isis::MultiFormatString partstr(getpartname(programInputArguments.inputCADFileName));
			isis_ProMdlRetrieve(partstr, fileISasm(programInputArguments.inputCADFileName) ? PRO_MDL_ASSEMBLY : PRO_MDL_PART, &mdl);

// STEP 5: Request creo give us an output XML for use in CyPhy
			std::string xmlbuffer = isis::CreoModelToCyphyXML(mdl);

			if(xmlbuffer=="")
			{
				std::stringstream errorString;
				errorString << "CreotoCyPhy call resulted in an empty string. Unable to convert file";
				throw isis::application_exception(errorString);
			}

			// the above call returns a text buffer.  Dump that buffer to a file
			ofstream xmlfile;
			std::string xmlfilename;

			if(programInputArguments.outputXmlFileName == "")
			{
				xmlfilename = programInputArguments.inputCADFileName+".xml";
//				cout <<  endl << "No output file specified, creating new XML file: " << xmlfilename << std::endl ;
			}
			else
			{
				xmlfilename = programInputArguments.outputXmlFileName;
			}
			cout << "Writing to XML file: " << xmlfilename << std::endl << std::endl;
			xmlfile.open (xmlfilename);
			xmlfile << xmlbuffer;
			xmlfile.close();

//// JGG W.I.P. - Create list of part files fould in the assembly
//			// determine if we have an assembly file
//			// ASSUMING that by this point any invalid file type would have barfed by now
//			//  so the file is either .prt or .asm at this point
//			if( fileISasm(programInputArguments.inputCADFileName) )
//			{
//				isis::CreoModelAssemblyAttributes local_out_AssemblyHierarchy;
//				const ProSolid	local_p_solid_handle = (ProSolid)mdl;
//				isis::RetrieveAssemblyHierarchyInformation ( local_p_solid_handle,
//														true,
//														local_out_AssemblyHierarchy  );
//							// Temporary Check
//				cout << "Parsing assembly file..." << std::endl;
//				for each ( isis::CreoModelAssemblyAttributes j in local_out_AssemblyHierarchy.children )
//				{
//					cout << "Found assemply part:  " << j.modelname << std::endl;
//				}
//			}
	} // END Try

	catch( boost::program_options::required_option& ex)
	{
        exceptionErrorStringStream  << "application error: Missing required option when invoking " << exeName << ", " << boost::diagnostic_information(ex);
		exceptionErrorStringStream << std::endl << "Input Line: " <<  inputLine;
        ExitCode = -1;
	}
	catch( boost::program_options::error& ex)
	{
        exceptionErrorStringStream  << "application error: Error with the options passed to " << exeName << ", " << boost::diagnostic_information(ex);
		exceptionErrorStringStream << std::endl << "Input Line: " <<  inputLine;
        ExitCode = -2;
	}
	catch (boost::exception &ex)
	{
		exceptionErrorStringStream  << "application error: " << boost::diagnostic_information(ex);
        ExitCode = -3;
	}

    catch(isis::application_exception& ex)
    {
        exceptionErrorStringStream  << "application error: " << ex.what();
        ExitCode = -4;
    }
    catch(std::exception& ex)
    {
        exceptionErrorStringStream << "general exception: " << ex.what();
        ExitCode = -5;
    }
    catch(...)
    {
        exceptionErrorStringStream << "unspecified error, caught with (...):  Please report this error to the help desk.";
        ExitCode = -6;
    }

	if ( ExitCode != 0 )
	{
		LogMainNonZeroExitCode( exeName, ExitCode, inputLine.str(), false, programInputArguments.logFileName,  exceptionErrorStringStream.str() );

		std::cerr << std::endl << std::endl << exceptionErrorStringStream.str() << std::endl << std::endl;

	}

		/////// Stop Pro/E /////////
		if (Pro_E_Running) isis::isis_ProEngineerEnd();

		if ( promptBeforeExiting )
		{
			printf("\nType Enter to exit.");
			getc(stdin);
		}
	exit(ExitCode);
}

max_stars_repo_name: lefevre-fraser/openmeta-mms

max_issues_repo_name: lefevre-fraser/openmeta-mms

max_forks_repo_name: lefevre-fraser/openmeta-mms


text:
/***************************************************************************
 *
 * Copyright (c) 2013 Baidu.com, Inc. All Rights Reserved
 *
 **************************************************************************/

/**
 * @file   LazySingleton.hpp
 *
 * @author liuming03
 * @date   2014-3-24
 * @brief
 */

#ifndef OP_OPED_NOAH_BBTS_LAZY_SINGLETON_HPP_
#define OP_OPED_NOAH_BBTS_LAZY_SINGLETON_HPP_

#include <assert.h>

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

#include "bbts/TypeLock.hpp"

namespace bbts {

template<typename Type>
class LazySingleton : private boost::noncopyable {
 public:
  typedef TypeLock<LazySingleton<Type> > Lock;

  static Type* instance() {
    if (!instance_) {
      Lock lock;
      if (!instance_) {
        instance_.reset(new Type());
      }
    }
    assert(instance_);
    return instance_.get();
  }

  // construct object with arg1
  template<typename Arg1>
  static Type* instance(const Arg1& arg1) {
    if (!instance_) {
      Lock lock;
      if (!instance_) {
        instance_.reset(new Type(arg1));
      }
    }
    assert(instance_);
    return instance_.get();
  }

  template<typename Arg1, typename Arg2>
  static Type* instance(const Arg1& arg1, const Arg2& arg2) {
    if (!instance_) {
      Lock lock;
      if (!instance_) {
        instance_.reset(new Type(arg1, arg2));
      }
    }
    assert(instance_);
    return instance_.get();
  }

  template<typename Arg1, typename Arg2, typename Arg3>
  static Type* instance(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3) {
    if (!instance_) {
      Lock lock;
      if (!instance_) {
        instance_.reset(new Type(arg1, arg2, arg3));
      }
    }
    assert(instance_);
    return instance_.get();
  }

 private:
  static boost::scoped_ptr<Type> instance_;

  LazySingleton();
  ~LazySingleton();
};

template<typename Type>
boost::scoped_ptr<Type> LazySingleton<Type>::instance_;

}  // namespace bbts

#endif // OP_OPED_NOAH_BBTS_LAZY_SINGLETON_HPP_


text:
/*********************************************************************/
/* Copyright (c) 2013-2018, EPFL/Blue Brain Project                  */
/*                          Raphael Dumusc <raphael.dumusc@epfl.ch>  */
/* All rights reserved.                                              */
/*                                                                   */
/* Redistribution and use in source and binary forms, with or        */
/* without modification, are permitted provided that the following   */
/* conditions are met:                                               */
/*                                                                   */
/*   1. Redistributions of source code must retain the above         */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer.                                                  */
/*                                                                   */
/*   2. 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.                              */
/*                                                                   */
/*    THIS  SOFTWARE  IS  PROVIDED  BY  THE  ECOLE  POLYTECHNIQUE    */
/*    FEDERALE DE LAUSANNE  ''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  ECOLE    */
/*    POLYTECHNIQUE  FEDERALE  DE  LAUSANNE  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.   */
/*                                                                   */
/* The views and conclusions contained in the software and           */
/* documentation are those of the authors and should not be          */
/* interpreted as representing official policies, either expressed   */
/* or implied, of Ecole polytechnique federale de Lausanne.          */
/*********************************************************************/

#define BOOST_TEST_MODULE CommandLineOptions
#include <boost/test/unit_test.hpp>

#include "localstreamer/CommandLineOptions.h"
#include "types.h"

#include <QStringList>
#include <string>
#include <vector>

BOOST_AUTO_TEST_CASE(testCommandLineDefaults)
{
    CommandLineOptions options;

    BOOST_CHECK(!options.getHelp());
    BOOST_CHECK_EQUAL(options.streamId, "");
    BOOST_CHECK_EQUAL(options.width, 0);
    BOOST_CHECK_EQUAL(options.height, 0);
    BOOST_CHECK_EQUAL(options.url, "");
    BOOST_CHECK_EQUAL(options.contentsDir, "");
    BOOST_CHECK_EQUAL(options.sessionsDir, "");
    BOOST_CHECK_EQUAL(options.webservicePort, 0);
    BOOST_CHECK_EQUAL(options.demoServiceUrl, "");
    BOOST_CHECK_EQUAL(options.showPowerButton, false);
    BOOST_CHECK_EQUAL(options.saveDir, "");

    BOOST_CHECK_EQUAL(options.getCommandLine().toStdString(), "");
}

void setOptionParameters(CommandLineOptions& options)
{
    options.streamId = "MyStreamer";
    options.width = 480;
    options.height = 640;
    options.url = "http://www.perdu.com";
    options.contentsDir = "/var/contents";
    options.sessionsDir = "/var/sessions";
    options.webservicePort = 8888;
    options.demoServiceUrl = "http://demoservice.bbp.epfl.ch";
    options.showPowerButton = true;
    options.saveDir = "/tmp/whiteboards";
}

void checkOptionParameters(const CommandLineOptions& options)
{
    BOOST_CHECK(!options.getHelp());
    BOOST_CHECK_EQUAL(options.streamId, "MyStreamer");
    BOOST_CHECK_EQUAL(options.width, 480);
    BOOST_CHECK_EQUAL(options.height, 640);
    BOOST_CHECK_EQUAL(options.url, "http://www.perdu.com");
    BOOST_CHECK_EQUAL(options.contentsDir, "/var/contents");
    BOOST_CHECK_EQUAL(options.sessionsDir, "/var/sessions");
    BOOST_CHECK_EQUAL(options.webservicePort, 8888);
    BOOST_CHECK_EQUAL(options.demoServiceUrl, "http://demoservice.bbp.epfl.ch");
    BOOST_CHECK_EQUAL(options.showPowerButton, true);
    BOOST_CHECK_EQUAL(options.saveDir, "/tmp/whiteboards");

    BOOST_CHECK_EQUAL(options.getCommandLine().toStdString(),
                      "--streamid MyStreamer "
                      "--width 480 "
                      "--height 640 "
                      "--url http://www.perdu.com "
                      "--contentsDir /var/contents "
                      "--sessionsDir /var/sessions "
                      "--webservicePort 8888 "
                      "--demoServiceUrl http://demoservice.bbp.epfl.ch "
                      "--showPowerButton "
                      "--saveDir /tmp/whiteboards");
}

BOOST_AUTO_TEST_CASE(testCommandLineManualCreation)
{
    CommandLineOptions options;
    setOptionParameters(options);

    checkOptionParameters(options);
}

BOOST_AUTO_TEST_CASE(testCommandLineFromCommandLineArguments)
{
    CommandLineOptions options;
    setOptionParameters(options);

    // Create a c-style representation of the command line options
    QStringList arguments = options.getCommandLineArguments();
    int argc = arguments.size() + 1;
    std::vector<char*> argv(argc);
    std::vector<char>* argList = new std::vector<char>[argc];

    // Program name
    {
        const std::string tmp("/test/program");
        argList[0].assign(tmp.begin(), tmp.end());
        argList[0].push_back('\0');
        argv[0] = argList[0].data();
    }
    // Command line arguments
    for (int i = 1; i < argc; ++i)
    {
        const std::string tmp = arguments.at(i - 1).toStdString();
        argList[i].assign(tmp.begin(), tmp.end());
        argList[i].push_back('\0');
        argv[i] = argList[i].data();
    }

    CommandLineOptions optionsDeserialized(argc, argv.data());
    checkOptionParameters(optionsDeserialized);
    delete[] argList;
}

max_stars_repo_name: BlueBrain/Tide

max_issues_repo_name: BlueBrain/Tide

max_forks_repo_name: BlueBrain/Tide


text:
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <armadillo>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <time.h>
using namespace std;

arma::vec init_func(arma::vec Y, double alpha, double t);
double dx1dt(double x2);
double dx2dt(double x1, double p2, double alpha, double t);
double dp1dt(double x1, double p2, double alpha, double t);
double dp2dt(double p1);

arma::vec init_func(arma::vec Function, double alpha, double t) {
    arma::vec ODE(static_cast<arma::uword>(4), arma::fill::zeros);

    ODE(0) = dx1dt(Function(1));
    ODE(1) = dx2dt(Function(0), Function(3), alpha, t);
    ODE(2) = dp1dt(Function(0), Function(3), alpha, t);
    ODE(3) = dp2dt(Function(2));

    return ODE;
}

double dx1dt(double x2) {
    return x2;
}

double dx2dt(double x1, double p2, double alpha, double t) {
    return p2 / 2 - sqrt(2) * x1 * exp(-alpha*t);
}

double dp1dt(double x1, double p2, double alpha, double t) {
    return 2*x1 + sqrt(2) * p2 * exp(-alpha*t);
}

double dp2dt(double p1) {
    return -p1;
}

max_stars_repo_name: pmpavl/workshop

max_issues_repo_name: pmpavl/workshop

max_forks_repo_name: pmpavl/workshop


text:
//
// Created by tseyler on 3/9/16.
//

#include <boost/algorithm/string.hpp>
#include <core/protocol/urlencode/urlencode_parse_routines.hpp>

namespace proto_net
{
    namespace protocol
    {
        namespace urlencode
        {
            urlencode_key_values decode_map = {
                    {"%20", " "},
                    {"%21", "!"},
                    {"%22", "\""},
                    {"%23", "#"},
                    {"%24", "$"},
                 //   {"%25", "%"},
                    {"%26", "&"},
                    {"%27", "'"},
                    {"%28", "("},
                    {"%29", ")"},
                    {"%2A", "*"},
                    {"%2B", "+"},
                   // {"%2C", ","},
                    {"%3A", ":"},
            };

            // tokenize routines
            size_t
            tokenize_urlencode_line(const std::string line, matches_t &tokens)
            {
                std::string sep("&");
                split(line, sep, tokens);

                return tokens.size();
            }

            size_t
            tokenize_urlencode_key_value(matches_t& tokens, urlencode_key_values& key_values)
            {
                std::string sep("=");
                size_t count(0);

                matches_iterator mit = tokens.begin();
                while (mit != tokens.end())
                {
                    matches_t tokens;
                    std::string kv = *mit++;
                    split(kv, sep, tokens);
                    if (tokens.size() >= 2) // key=value = size 2
                    {
                        std::string k = ue_decode(tokens[0]);
                        std::string v = ue_decode(tokens[1]);
                        key_values.insert(urlencode_key_value_pair(k, v));
                        count++;
                    }
                }

                return count;
            }

            std::string
            ue_encode(const std::string& str_in)
            {
                std::string encoded(str_in);

                urlencode_key_values_iterator it = decode_map.begin();
                while (it != decode_map.end())
                {
                    urlencode_key_value_pair decode_pair = *it++;
                    encoded = boost::replace_all_copy(encoded, decode_pair.second, decode_pair.first);
                }

                return encoded;
            }

            std::string
            ue_decode(const std::string& str_in)
            {
                std::string decoded(str_in);

                urlencode_key_values_iterator it = decode_map.begin();
                while (it != decode_map.end())
                {
                    urlencode_key_value_pair decode_pair = *it++;
                    decoded = boost::replace_all_copy(decoded, decode_pair.first, decode_pair.second);
                }

                return decoded;
            }
        }
    }
}

max_stars_repo_name: tseyler/proto-server

max_issues_repo_name: tseyler/proto-server

max_forks_repo_name: tseyler/proto-server


text:
#include <xmorphy/morph/WordFormPrinter.h>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
namespace X
{

std::string WordFormPrinter::write(WordFormPtr wform)
{
    std::ostringstream oss;
    if (wform->getTokenType() & TokenTypeTag::SEPR)
        return "";
    for (const auto & mi : wform->getMorphInfo())
    {
        oss << wform->getWordForm().getRawString() << "\t";
        oss << mi.normalForm.toLowerCase().getRawString() << "\t";
        oss << mi.sp << "\t";
        oss << mi.tag << "\t";
        oss << mi.at << "\t";
        oss << mi.probability;
        const std::vector<PhemTag> & pheminfo = wform->getPhemInfo();
        if (!pheminfo.empty())
        {
            oss << "\t";
            oss << writePhemInfo(wform);
        }
        oss << "\n";
    }
    std::string result = oss.str();
    result.pop_back();
    return result;
}

static std::string printPhemTag(PhemTag tag)
{
    if (tag == PhemTag::B_SUFF)
        return to_string(PhemTag::SUFF);
    if (tag == PhemTag::B_ROOT)
        return to_string(PhemTag::ROOT);
    if (tag == PhemTag::B_PREF)
        return to_string(PhemTag::PREF);
    return to_string(tag);
}

static bool tagsEqual(PhemTag left, PhemTag right)
{
    if (left == PhemTag::B_PREF && right == PhemTag::B_PREF)
        return false;
    if (left == PhemTag::B_ROOT && right == PhemTag::B_ROOT)
        return false;
    if (left == PhemTag::B_SUFF && right == PhemTag::B_SUFF)
        return false;

    if (left == PhemTag::B_PREF && right == PhemTag::PREF)
        return true;
    if (left == PhemTag::B_ROOT && right == PhemTag::ROOT)
        return true;
    if (left == PhemTag::B_SUFF && right == PhemTag::SUFF)
        return true;

    return left == right;
}

std::string WordFormPrinter::writePhemInfo(WordFormPtr wform)
{
    const std::vector<PhemTag> & pheminfo = wform->getPhemInfo();
    const UniString word_form = wform->getWordForm();
    return writePhemInfo(word_form, pheminfo);
}

std::string WordFormPrinter::writePhemInfo(const UniString & word_form, const std::vector<PhemTag> & pheminfo)
{
    if (pheminfo.empty())
    {
        if (!word_form.isEmpty())
            throw std::runtime_error("PhemInfo is not parsed for word " + word_form.getRawString());
        return "";
    }
    if (pheminfo.size() < word_form.length())
        throw std::runtime_error("PhemInfo has length " + std::to_string(pheminfo.size()) + " but word has lengths " + std::to_string(word_form.length()));

    std::ostringstream oss;
    oss << word_form.charAtAsString(0);
    PhemTag prev = pheminfo[0];
    for (size_t i = 1; i < word_form.length(); ++i)
    {
        if (!tagsEqual(prev, pheminfo[i]))
        {
            oss << ":" << printPhemTag(prev) << "/";
        }
        prev = pheminfo[i];
        oss << word_form.charAtAsString(i);
    }

    oss << ":" << printPhemTag(prev);

    return oss.str();
}

boost::property_tree::ptree WordFormPrinter::writeToJSON(WordFormPtr wform)
{
    namespace pt = boost::property_tree;
    pt::ptree array;
    if (wform->getTokenType() & TokenTypeTag::SEPR)
        return array;

    std::ostringstream oss;
    size_t index = 0;
    for (auto & mi : wform->getMorphInfo())
    {
        pt::ptree elem;
        elem.put("lemma", mi.normalForm.toLowerCase().getRawString());
        elem.put("speech_part", mi.sp);
        elem.put("case", mi.tag.getCase());
        elem.put("gender", mi.tag.getGender());
        elem.put("number", mi.tag.getNumber());
        elem.put("tense", mi.tag.getTense());
        elem.put("raw_tags", mi.tag);
        elem.put("phem_info", writePhemInfo(wform));
        array.push_back(std::make_pair(std::to_string(index++), elem));
    }
    return array;
}

}


text:
/*!
 * @file
 * Forward declares logical metafunctions.
 *
 *
 * @copyright Louis Dionne 2014
 * Distributed under the Boost Software License, Version 1.0.
 *         (See accompanying file LICENSE.md or copy at
 *             http://www.boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_MPL11_FWD_LOGICAL_HPP
#define BOOST_MPL11_FWD_LOGICAL_HPP

#include <boost/mpl11/detail/config.hpp>

namespace boost { namespace mpl11 {
    /*!
     * @defgroup Logical Logical
     *
     * Logical operators and conditional branch selection.
     *
     * @{
     */

    /*!
     * Returns the result of short-circuit _logical and_ (`&&`) on its
     * arguments.
     *
     * Arguments must be `StaticConstant`s that will be unboxed from left to
     * right in a short-circuiting fashion. If no arguments are provided,
     * `and_` is equivalent to `true_`.
     */
    template <typename ...xs>
    struct and_;

    /*!
     * Returns the result of short-circuit _logical or_ (`||`) on its
     * arguments.
     *
     * Arguments must be `StaticConstant`s that will be unboxed from left to
     * right in a short-circuiting fashion. If no arguments are provided,
     * `or_` is equivalent to `false_`.
     */
    template <typename ...xs>
    struct or_;

    /*!
     * Returns the _logical negation_ (`!`) of its argument.
     *
     * Specifically, `not_<x>` is equivalent to `bool_<!x::%type::value>`.
     */
    template <typename x>
    struct not_;

    namespace logical_detail { template <bool> struct if_impl; }

    //! Equivalent to `if_<bool_<Condition>, Then, Else>`.
    template <bool Condition, typename Then, typename Else>
    BOOST_MPL11_DOXYGEN_ALIAS(if_c,
            typename logical_detail::if_impl<Condition>::
            template result<Then, Else>);

    //! Equivalent to `else_if<bool_<Condition>, Then, Else>`.
    template <bool Condition, typename Then, typename Else>
    BOOST_MPL11_DOXYGEN_ALIAS(else_if_c, if_c<Condition, Then, Else>);

    /*!
     * Evaluates one of two branches based on a condition.
     *
     * Specifically, `if_<Condition, Then, Else>` is equivalent to `Then`
     * if `Condition::%type::value` evaluates to `true`, and to `Else`
     * otherwise.
     *
     * `if_` can be combined with `else_if` and `else_` to improve
     * readability.
     */
    template <typename Condition, typename Then, typename Else>
    struct if_;

    //! Equivalent to `if_`; provided for use with `if_`.
    template <typename Condition, typename Then, typename Else>
    BOOST_MPL11_DOXYGEN_ALIAS(else_if, if_<Condition, Then, Else>);

    //! Transparent alias to its argument; provided for use with `if_`.
    template <typename Else>
    BOOST_MPL11_DOXYGEN_ALIAS(else_, Else);
    //! @}
}} // end namespace boost::mpl11

#endif // !BOOST_MPL11_FWD_LOGICAL_HPP


text:
#include <boost/asio.hpp>
#include <iostream>

void handler(const boost::system::error_code &ec)
{
  std::cout << "5 s." << std::endl;
}

int main( int argc, char * argv[] )
{
	boost::asio::io_service io_service;
	boost::asio::deadline_timer timer(io_service, boost::posix_time::seconds(5));
    timer.async_wait(handler);
	io_service.run();

	std::cout << "Do you reckon this line displays?" << std::endl;

	return 0;
}

max_stars_repo_name: harkhuang/harkcode

max_issues_repo_name: harkhuang/harkcode

max_forks_repo_name: harkhuang/harkcode