text:
/////////////////////////////////////////////////////////////////////////
///@file master_server.cpp
///@brief	交易代理服务器
///@copyright	上海信易信息科技股份有限公司 版权所有
/////////////////////////////////////////////////////////////////////////

#include "master_server.h"
#include "SerializerTradeBase.h"
#include "log.h"
#include "version.h"

#include <boost/asio/io_context.hpp>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/asio/write.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>

#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <cstdlib>
#include <sstream>
#include <functional>

using namespace std;

master_server::master_server(boost::asio::io_context& ios
	, MasterConfig& masterConfig)
	:io_context_(ios)
	,masterConfig_(masterConfig)
	,client_endpoint_(boost::asio::ip::tcp::v4(),masterConfig.port)
	,client_acceptor_(io_context_)
	,client_connection_(0)
	,client_connection_manager_()
{
}

bool master_server::init()
{
	if (!InitClientAcceptor())
	{
		LogMs().WithField("fun","init")
			.WithField("key","gatewayms")
			.Log(LOG_ERROR, "open trade gateway master InitClientAcceptor fail!");
		return false;
	}

	return true;
}

bool  master_server::InitClientAcceptor()
{
	boost::system::error_code ec;
	client_acceptor_.open(client_endpoint_.protocol(),ec);
	if (ec)
	{
		LogMs().WithField("fun","InitClientAcceptor")
			.WithField("key","gatewayms")
			.WithField("errmsg",ec.message())
			.Log(LOG_WARNING,"open trade gateway master client acceptor open fail");
		return false;
	}

	client_acceptor_.set_option(boost::asio::socket_base::reuse_address(true),ec);
	if (ec)
	{
		LogMs().WithField("fun","InitClientAcceptor")
			.WithField("key","gatewayms")
			.WithField("errmsg",ec.message())
			.Log(LOG_WARNING,"open trade gateway master client acceptor set option fail");
		return false;
	}

	client_acceptor_.bind(client_endpoint_,ec);
	if (ec)
	{
		LogMs().WithField("fun","InitClientAcceptor")
			.WithField("key","gatewayms")
			.WithField("errmsg",ec.message())
			.Log(LOG_WARNING,"open trade gateway master client acceptor bind fail");
		return false;
	}

	client_acceptor_.listen(boost::asio::socket_base::max_listen_connections,ec);
	if (ec)
	{
		LogMs().WithField("fun","InitClientAcceptor")
			.WithField("key","gatewayms")
			.WithField("errmsg",ec.message())
			.Log(LOG_WARNING,"open trade gateway master client acceptor listen fail");
		return false;
	}

	do_client_accept();

	return true;
}

void master_server::do_client_accept()
{
	client_acceptor_.async_accept(
		std::bind(&master_server::OnClientAccept,
			this,
			std::placeholders::_1,
			std::placeholders::_2));
}

void master_server::OnClientAccept(boost::system::error_code ec
	, boost::asio::ip::tcp::socket socket)
{
	if (!client_acceptor_.is_open())
	{
		LogMs().WithField("fun","OnClientAccept")
			.WithField("key","gatewayms")
			.Log(LOG_WARNING,"open trade gateway master client acceptor is not open!");
		return;
	}

	if (ec)
	{
		LogMs().WithField("fun","OnClientAccept")
			.WithField("key","gatewayms")
			.WithField("errmsg",ec.message())
			.Log(LOG_WARNING,"open trade gateway master client acceptor accept error");

		do_client_accept();
		return;
	}

	client_connection_manager_.start(std::make_shared<client_connection>(
		io_context_
		,std::move(socket)
		,client_connection_manager_
		,++client_connection_
		,masterConfig_));

	do_client_accept();
}

void master_server::stop()
{
	client_acceptor_.close();
	client_connection_manager_.stop_all();
}

max_stars_repo_name: yuanfengyun/helloctp

max_issues_repo_name: yuanfengyun/helloctp

max_forks_repo_name: yuanfengyun/helloctp


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

#include "logs.h"
#include "route.h"
#include "track.h"

const bool isFileName = true;
using namespace GPS;

BOOST_AUTO_TEST_SUITE( totalTime_N0702007 )

/*
	Function: Total Time

	Returns the difference in seconds between the earliest and latest points.
	gridworld_track uses a timeUnitDuration variable, but I don't think it applies to regular Track calculations, so we'll do these functions in terms of GPX time units.

	Tests/Considerations & Explanations:

        IMPLEMENTATION CONSIDERATIONS:
                Data out of order:
                When passed data is out of order, namely, when time isn't necessarily increasing with each point in a track, it would be reasonable to throw an error; but
                given that the implementation of totalTime could simply find the difference between the first and last points in time, it is simple to implement a function
                that would handle this data correctly.

	CORRECT:

		Regular input:
		Testing correct input ensures the function works as expected.

		Regular input, non-zero starting value:
		Ensures the Total Time function isn't assuming the start time is zero

                Regular input, two points at the same start time:
                Ensures that the code can handle two identical start times

                Only two points at the same time
                Similarly ensures the code can handle the start times being the same as end times

		Correct input, data not ordered correctly by time:
		Though there are arguments for data that isn't ordered being invalid, providing functionality for time going back and forth will help in the case of
		manually-typed data being slightly incorrect.

		The multiple cases for this test I'll cover are:
			Time going backwards
			Latest time out of place (Not first nor last)
			Smallest time out of place (Not first nor last)
			Smallest time immediately before largest time
			Smallest time immediately after largest time
                        Two start points at same time, not at beginning of code
                        Two end points at same time, not at end of code
                        Two start and end points, flipped

		Correct input, maximum values for time:
		Maximum time unit given that time is ULL = 18446744073709551615
		This ensures that the function won't fail given large input values (which could cause errors if the function doesn't allocate a large enough variable)

		Correct input, minimum values for inputs (No time taken):
		This test can catch issues with handlng small numbers, such as DIV/0 exceptions

		Correct input, large quantity of points:
		Choosing a quantity of points to test is a little difficult, as file size and runtime length may become unacceptably large after a few thousand points.
		Should this program frequently need to track hundreds of thousands of points, this test should be scaled accordingly.
		For the sake of the other students having to download any file, I'll keep this to using 'TrackMultiplePoints'.

	INCORRECT:

		After considering the many ways to incorrectly input time values into the GPX files, a lot of the errors will throw exceptions either at parsing time or
		be completely undetectable for the function itself.

        OTHER UNIMPLEMENTED TESTS:

		Malformatted XML:
		This error would instead be handled by the parser.

                Empty track containing no points:
		If there are no points for the track, the parser will throw an error.

		Negative time values:
		This error is impossible to be detected by the function itself; negative values wouldn't be handled by the XML parser, which through using stull results in an
		integer value with the first bit flipped, exactly the same as a very large positive value.

		Wrong type for time:
		Incorrect types would throw an error at 'StringToTime' and would not reach this function.

		Incorrect & Correct input, multiple track segments
		The transformation from XML to Route or Track combines all track segments into a single set of data.

		Incorrect values for variables other than 'Time'
		Given the functions' purpose doesn't utilise any variables other than 'Time' in the given track,

*/

// Tests for correct, ordered values
BOOST_AUTO_TEST_CASE( totaltime_correct_set1)
{
   Track track = Track(LogFiles::GPXTracksDir + "TrackDuration10.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 40 );

}
BOOST_AUTO_TEST_CASE( totaltime_correct_set2)
{
   Track track = Track(LogFiles::GPXTracksDir + "TrackDuration1.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 3 );

}

// This test also covers the 'large quantity of points' point to a reasonable standard
BOOST_AUTO_TEST_CASE( totaltime_large_quantity)
{
   Track track = Track(LogFiles::GPXTracksDir + "TrackMultiplePoints.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 21000 );

}

// Test for disordered first value
BOOST_AUTO_TEST_CASE( totaltime_earliest_disordered)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeEarliestOffset.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 40 );

}

// Test for disordered last value
BOOST_AUTO_TEST_CASE( totaltime_latest_disordered)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeLatestOffset.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 40 );

}

// Test for time going backwards
BOOST_AUTO_TEST_CASE( totaltime_backwards)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeBackwards.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 60 );

}

// Test for disordered first & last values, first before last
BOOST_AUTO_TEST_CASE( totaltime_disordered_fbl)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeFirstBeforeLast.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 60 );

}

// Test for disordered first & last values, last before first
BOOST_AUTO_TEST_CASE( totaltime_disordered_lbf)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeLastBeforeFirst.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 60 );

}

// Test for largest integer
BOOST_AUTO_TEST_CASE( totaltime_maxull)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeLargestPossible.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 18446744073709551615ull );

}

// Tests for duplicate values
BOOST_AUTO_TEST_CASE( totaltime_start_duplicate)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeSameValuesStart.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 40 );

}
BOOST_AUTO_TEST_CASE( totaltime_end_duplicate)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeSameValuesEnd.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 40 );

}
BOOST_AUTO_TEST_CASE( totaltime_startend_duplicate)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeSameValuesStartEnd.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 40 );

}
BOOST_AUTO_TEST_CASE( totaltime_startend_duplicate_disordered)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeSameValuesStartEndDisordered.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 40 );

}
BOOST_AUTO_TEST_CASE( totaltime_startend_duplicate_disordered_lbf)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeSameValuesStartEndDisorderedEndBeforeStart.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 40 );

}

// Tests for same start & end
BOOST_AUTO_TEST_CASE( totaltime_same_startend)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeSameStartEnd.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 0 );

}
BOOST_AUTO_TEST_CASE( totaltime_same_startend_nonzero)
{
   Track track = Track(LogFiles::GPXTracksDir + "N0702007TrackTimeSameStartEndNonzero.gpx", isFileName);
   BOOST_CHECK_EQUAL( track.totalTime(), 0 );

}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: EdwinLangley/GPX-Route-and-Track

max_issues_repo_name: EdwinLangley/GPX-Route-and-Track

max_forks_repo_name: EdwinLangley/GPX-Route-and-Track


text:
#pragma once

#include <cassert>
#include <list>
#include <memory>
#include <mutex>
#include <utility>
#include <boost/asio/ts/executor.hpp>

namespace cppcon {
namespace test {

template<typename Signature>
class pending_service;

template<typename R,
         typename... Args>
class pending_service<R(Args...)> : public boost::asio::execution_context::service {
public:
  using key_type = pending_service;
  explicit pending_service(boost::asio::execution_context& ctx)
    : boost::asio::execution_context::service(ctx),
      shutdown_                              (false)
  {}
  inline static boost::asio::execution_context::id id;
private:
  class storage_base {
  public:
    storage_base() = default;
    storage_base(const storage_base&) = delete;
    storage_base& operator=(const storage_base&) = delete;
    virtual ~storage_base() noexcept {}
    virtual R invoke(Args...) = 0;
  };
  template<typename T>
  class storage : public storage_base {
  public:
    explicit storage(T t) noexcept(std::is_nothrow_move_constructible_v<T>)
      : obj_(std::move(t))
    {}
    virtual R invoke(Args... args) override {
      return obj_(std::forward<Args>(args)...);
    }
  private:
    T obj_;
  };
  class function_type {
  public:
    function_type() = default;
    function_type(const function_type&) = delete;
    function_type& operator=(const function_type&) = delete;
    template<typename T>
    function_type& operator=(T&& t) {
      storage_ = std::make_unique<storage<T>>(std::forward<T>(t));
      return *this;
    }
    explicit operator bool() const noexcept {
      return bool(storage_);
    }
    R operator()(Args... args) {
      assert(storage_);
      class guard {
      public:
        explicit guard(std::unique_ptr<storage_base>& ptr) noexcept
          : ptr_(ptr)
        {
          assert(ptr_);
        }
        guard(const guard&) = delete;
        ~guard() noexcept {
          ptr_.reset();
        }
      private:
        std::unique_ptr<storage_base>& ptr_;
      };
      guard g(storage_);
      return storage_->invoke(std::forward<Args>(args)...);
    }
  private:
    std::unique_ptr<storage_base> storage_;
  };
  using functions_type = std::list<function_type>;
public:
  using pointer = typename functions_type::iterator;
  pointer acquire() {
    std::scoped_lock l(m_);
    assert(!shutdown_);
    fs_.emplace_front();
    return fs_.begin();
  }
  void release(pointer p) noexcept {
    std::scoped_lock l(m_);
    if (shutdown_) {
      return;
    }
    fs_.erase(p);
  }
private:
  virtual void shutdown() noexcept override {
    shutdown_ = true;
    fs_.clear();
  }
  mutable std::mutex m_;
  bool               shutdown_;
  functions_type     fs_;
};

}
}

ext: hpp


text:
/******************************************************
/ Synchronous Client Program
/ @author Cody Martin
/ Using Boost 1.69.0 C++ Library.
/ Client must provide their Username ID and password,
/ as well as data to be parsed.
/*****************************************************/

#include <boost/asio.hpp>
#include <iostream>
#include <string>

using namespace std;
using namespace boost::asio;
using namespace boost::asio::ip;

/*****************************************************************************
/ Writes Client's Message on socket to send to Server
/ @param socket: Provides reference to interface communication with Server
/ @param message: The message being sent through socket and buffer
/ Adds newline character to provide a delimiter for processing data
/****************************************************************************/
void writeData(tcp::socket &socket, const string &message)
{
	write(socket, buffer(message + "\n"));
}

/**********************************************************************************
/ Main program to set up socket network programming connection
/ Desc:	Sets up io_service to use Boost functions
/	Sets up socket for client to connect with Server on localhost on port 1234
/	User provides value for username, password, and data via terminal input
/*********************************************************************************/
int main()
{
	io_service io_service;
	ip::tcp::socket clientSocket(io_service);

	clientSocket.connect( tcp::endpoint(address::from_string("127.0.0.1"), 1234));

	string username, password, data;

	cout << "Please enter your Username: ";
	getline(cin, username);
	writeData(clientSocket, username);

	cout << "Please enter your Password: ";
	getline(cin, password);
	writeData(clientSocket, password);

	//Infinite loop to send multiple data messages to Server
	cout << "\n(Enter \"exit\" after you are finished entering the last line of Data)\n";
	while(true)
	{
		cout << "Enter sequence of numbers, each separated by a space, to be parsed\n";
		getline(cin, data);
		writeData(clientSocket, data);

		if(data == "exit")
			break;
	}

	return 0;
}

max_stars_repo_name: ExtinctStar/boostnetworking

max_issues_repo_name: ExtinctStar/boostnetworking

max_forks_repo_name: ExtinctStar/boostnetworking


text:
/*
 * glob.hpp - Find pathnames matching a pattern
 *
 *   Copyright 2010 Jesús Torres <jmtorres@ull.es>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef GLOB_HPP_
#define GLOB_HPP_

#include <string>
#include <utility>
#include <vector>

#include <boost/filesystem.hpp>

#include <cli/internals.hpp>

namespace glob
{
    namespace posix {
        #include <glob.h>
    }

    using namespace boost;

    //
    // Class Glob
    //

    class Glob
    {
        public:

            typedef std::vector<std::pair<
                std::string, std::error_code> > ErrorsType;

            enum GlobFlags
            {
                NONE                                = 0,
                STOP_ON_ERRORS                      = GLOB_ERR,
                END_DIRECTORIES_WITH_PATH_SEPARATOR = GLOB_MARK,
                NO_PATH_NAMES_SORT                  = GLOB_NOSORT,
                NO_PATH_NAMES_CHECK                 = GLOB_NOCHECK,
                NO_ESCAPE_CHARACTER                 = GLOB_NOESCAPE,
#if defined(_GNU_SOURCE)
                NO_MAGIC                            = GLOB_NOMAGIC,
                MATCH_LEADING_PERIOD                = GLOB_PERIOD,
                FIND_DIRECTORIES_ONLY               = GLOB_ONLYDIR,
                EXPAND_BRACE_EXPRESSIONS            = GLOB_BRACE,
                EXPAND_TILDE                        = GLOB_TILDE,
                EXPAND_TILDE_WITH_CHECK             = GLOB_TILDE_CHECK,
#endif /* _GNU_SOURCE */
            };

            Glob(const std::string& pattern, GlobFlags flags = NONE);

            //
            // Overloaded cast operators to get the list of path names found
            //

            operator const std::vector<std::string>&() const;
            operator std::vector<filesystem::path>() const;

            //
            // Error handling
            //

            const ErrorsType& getErrors() const
                { return errors_; }

            //
            // Meta characters escaping
            //

            static std::string escape(const std::string& pattern);

        protected:
             ErrorsType errors_;

             virtual bool onError(const std::string& pathName,
                 std::error_code errorCode);

        private:
             std::vector<std::string> pathNames_;

             friend int onGlobError(const char* epath, int eerrno);
    };

    inline Glob::operator const std::vector<std::string>&() const
    {
        return pathNames_;
    }

    inline Glob::operator std::vector<filesystem::path>() const
    {
        std::vector<filesystem::path> pathNames;
        for (std::vector<std::string>::const_iterator iter =
            pathNames_.begin(); iter < pathNames_.end(); ++iter)
        {
            pathNames.push_back(filesystem::path(*iter));
        }
        return pathNames;
    }

    //
    // Boolean operators overload for Glob::GlobFlags
    //

    inline Glob::GlobFlags
    operator&(Glob::GlobFlags a, Glob::GlobFlags b)
    {
        return Glob::GlobFlags(static_cast<int>(a)
            & static_cast<int>(b));
    }

    inline Glob::GlobFlags
    operator|(Glob::GlobFlags a, Glob::GlobFlags b)
    {
        return Glob::GlobFlags(static_cast<int>(a)
            | static_cast<int>(b));
    }

    inline Glob::GlobFlags
    operator^(Glob::GlobFlags a, Glob::GlobFlags b)
    {
        return Glob::GlobFlags(static_cast<int>(a)
            ^ static_cast<int>(b));
    }

    inline Glob::GlobFlags
    operator&=(Glob::GlobFlags &a, Glob::GlobFlags b)
    {
        return a = a & b;
    }

    inline Glob::GlobFlags
    operator|=(Glob::GlobFlags &a, Glob::GlobFlags b)
    {
        return a = a | b;
    }

    inline Glob::GlobFlags
    operator^=(Glob::GlobFlags a, Glob::GlobFlags b)
    {
        return a = a ^ b;
    }

    inline Glob::GlobFlags
    operator~(Glob::GlobFlags a)
    {
        return Glob::GlobFlags(~static_cast<int>(a));
    }
}

#endif /* GLOB_HPP_ */

max_stars_repo_name: JonathanTrEs/Shell

max_issues_repo_name: JonathanTrEs/Shell

max_forks_repo_name: JonathanTrEs/Shell


text:
#ifndef CURVATURE_HH
#define CURVATURE_HH

#include <Eigen/Dense>
#include <MeshFEM/Utilities/MeshConversion.hh>

struct CurvatureInfo {
    // Per vertex curvature quantities
    Eigen::MatrixX3d d_1, d_2;
    Eigen::VectorXd kappa_1, kappa_2;

    Eigen::VectorXd     meanCurvature() const { return 0.5 * (kappa_1 + kappa_2); }
    Eigen::VectorXd gaussianCurvature() const { return kappa_1.array() * kappa_2.array(); }

    const Eigen::MatrixX3d &d(size_t i) const {
        if (i == 0) return d_1;
        if (i == 1) return d_2;
        throw std::runtime_error("Index i out of bounds");
    }

    CurvatureInfo(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F);

    template<class Mesh>
    CurvatureInfo(const Mesh &m) : CurvatureInfo(getV(m), getF(m)) { }
};

#endif /* end of include guard: CURVATURE_HH */

ext: hh

max_stars_repo_name: jpanetta/Inflatables

max_issues_repo_name: jpanetta/Inflatables

max_forks_repo_name: jpanetta/Inflatables


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

#include "extensions/webos_base/launch_point/handler/ordering_handler_4_base.h"

#include <boost/bind.hpp>

#include "extensions/webos_base/base_logs.h"
#include "extensions/webos_base/base_settings.h"

OrderingHandler4Base::OrderingHandler4Base() {
}

OrderingHandler4Base::~OrderingHandler4Base() {
}

void OrderingHandler4Base::Init() {
}

void OrderingHandler4Base::HandleDbState(bool connection) {
}

void OrderingHandler4Base::ReloadDbData(bool connection) {
}

void OrderingHandler4Base::MakeLaunchPointsInOrder(const std::vector<LaunchPointPtr>& visible_lps, const pbnjson::JValue& changed_reason) {
  visible_lps_ = visible_lps;
  reorder();
}

int OrderingHandler4Base::InsertLpInOrder(const std::string& lp_id, const pbnjson::JValue& data, int position) {
  return 0;
}

int OrderingHandler4Base::UpdateLpInOrder(const std::string& lp_id, const pbnjson::JValue& data, int position) {
  return 0;
}

void OrderingHandler4Base::DeleteLpInOrder(const std::string& lp_id) {
}

void OrderingHandler4Base::reorder() {
  ordered_list_.clear();
  for (auto it = visible_lps_.begin(); it != visible_lps_.end(); ++it) {
    ordered_list_.push_back(it->get()->LaunchPointId());
  }
  signal_launch_points_ordered_(OrderChangeState::FULL);
}

max_stars_repo_name: webosce/sam

max_issues_repo_name: webosce/sam

max_forks_repo_name: webosce/sam


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
 Copyright (C) 2003, 2004, 2005, 2006, 2009 StatPro Italia srl
 Copyright (C) 2004 Ferdinando Ametrano

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 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 license for more details.
*/

/*! \file array.hpp
    \brief 1-D array used in linear algebra.
*/

#ifndef quantlib_array_hpp
#define quantlib_array_hpp

#include <ql/types.hpp>
#include <ql/errors.hpp>
#include <ql/utilities/disposable.hpp>
#include <ql/utilities/null.hpp>
#include <boost/iterator/reverse_iterator.hpp>
#include <boost/scoped_array.hpp>
#include <boost/type_traits.hpp>
#include <functional>
#include <numeric>
#include <vector>
#include <iomanip>

namespace QuantLib {

    //! 1-D array used in linear algebra.
    /*! This class implements the concept of vector as used in linear
        algebra.
        As such, it is <b>not</b> meant to be used as a container -
        <tt>std::vector</tt> should be used instead.

        \test construction of arrays is checked in a number of cases
    */
    class Array {
      public:
        //! \name Constructors, destructor, and assignment
        //@{
        //! creates the array with the given dimension
        explicit Array(Size size = 0);
        //! creates the array and fills it with <tt>value</tt>
        Array(Size size, Real value);
        /*! \brief creates the array and fills it according to
            \f$ a_{0} = value, a_{i}=a_{i-1}+increment \f$
        */
        Array(Size size, Real value, Real increment);
        Array(const Array&);
        Array(const Disposable<Array>&);
        //! creates the array from an iterable sequence
        template <class ForwardIterator>
        Array(ForwardIterator begin, ForwardIterator end);

        Array& operator=(const Array&);
        Array& operator=(const Disposable<Array>&);
        bool operator==(const Array&) const;
        bool operator!=(const Array&) const;
        //@}
        /*! \name Vector algebra

            <tt>v += x</tt> and similar operation involving a scalar value
            are shortcuts for \f$ \forall i : v_i = v_i + x \f$

            <tt>v *= w</tt> and similar operation involving two vectors are
            shortcuts for \f$ \forall i : v_i = v_i \times w_i \f$

            \pre all arrays involved in an algebraic expression must have
            the same size.
        */
        //@{
        const Array& operator+=(const Array&);
        const Array& operator+=(Real);
        const Array& operator-=(const Array&);
        const Array& operator-=(Real);
        const Array& operator*=(const Array&);
        const Array& operator*=(Real);
        const Array& operator/=(const Array&);
        const Array& operator/=(Real);
        //@}
        //! \name Element access
        //@{
        //! read-only
        Real operator[](Size) const;
        Real at(Size) const;
        Real front() const;
        Real back() const;
        //! read-write
        Real& operator[](Size);
        Real& at(Size);
        Real& front();
        Real& back();
        //@}
        //! \name Inspectors
        //@{
        //! dimension of the array
        Size size() const;
        //! whether the array is empty
        bool empty() const;
        //@}
        typedef Size size_type;
        typedef Real value_type;
        typedef Real* iterator;
        typedef const Real* const_iterator;
        typedef boost::reverse_iterator<iterator> reverse_iterator;
        typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
        //! \name Iterator access
        //@{
        const_iterator begin() const;
        iterator begin();
        const_iterator end() const;
        iterator end();
        const_reverse_iterator rbegin() const;
        reverse_iterator rbegin();
        const_reverse_iterator rend() const;
        reverse_iterator rend();
        //@}
        //! \name Utilities
        //@{
        void swap(Array&);  // never throws
        //@}

      private:
        boost::scoped_array<Real> data_;
        Size n_;
    };

    //! specialization of null template for this class
    template <>
    class Null<Array> {
      public:
        Null() {}
        operator Array() const { return Array(); }
    };

    /*! \relates Array */
    Real DotProduct(const Array&, const Array&);

    /*! \relates Array */
    Real Norm2(const Array&);

    // unary operators
    /*! \relates Array */
    const Disposable<Array> operator+(const Array& v);
    /*! \relates Array */
    const Disposable<Array> operator-(const Array& v);

    // binary operators
    /*! \relates Array */
    const Disposable<Array> operator+(const Array&, const Array&);
    /*! \relates Array */
    const Disposable<Array> operator+(const Array&, Real);
    /*! \relates Array */
    const Disposable<Array> operator+(Real, const Array&);
    /*! \relates Array */
    const Disposable<Array> operator-(const Array&, const Array&);
    /*! \relates Array */
    const Disposable<Array> operator-(const Array&, Real);
    /*! \relates Array */
    const Disposable<Array> operator-(Real, const Array&);
    /*! \relates Array */
    const Disposable<Array> operator*(const Array&, const Array&);
    /*! \relates Array */
    const Disposable<Array> operator*(const Array&, Real);
    /*! \relates Array */
    const Disposable<Array> operator*(Real, const Array&);
    /*! \relates Array */
    const Disposable<Array> operator/(const Array&, const Array&);
    /*! \relates Array */
    const Disposable<Array> operator/(const Array&, Real);
    /*! \relates Array */
    const Disposable<Array> operator/(Real, const Array&);

    // math functions
    /*! \relates Array */
    const Disposable<Array> Abs(const Array&);
    /*! \relates Array */
    const Disposable<Array> Sqrt(const Array&);
    /*! \relates Array */
    const Disposable<Array> Log(const Array&);
    /*! \relates Array */
    const Disposable<Array> Exp(const Array&);
    /*! \relates Array */
    const Disposable<Array> Pow(const Array&, Real);

    // utilities
    /*! \relates Array */
    void swap(Array&, Array&);

    // format
    /*! \relates Array */
    std::ostream& operator<<(std::ostream&, const Array&);

    // inline definitions

    inline Array::Array(Size size)
    : data_(size ? new Real[size] : (Real*)(0)), n_(size) {}

    inline Array::Array(Size size, Real value)
    : data_(size ? new Real[size] : (Real*)(0)), n_(size) {
        std::fill(begin(),end(),value);
    }

    inline Array::Array(Size size, Real value, Real increment)
    : data_(size ? new Real[size] : (Real*)(0)), n_(size) {
        for (iterator i=begin(); i!=end(); ++i, value+=increment)
            *i = value;
    }

    inline Array::Array(const Array& from)
    : data_(from.n_ ? new Real[from.n_] : (Real*)(0)), n_(from.n_) {
        #if defined(QL_PATCH_MSVC) && defined(QL_DEBUG)
        if (n_)
        #endif
        std::copy(from.begin(),from.end(),begin());
    }

    inline Array::Array(const Disposable<Array>& from)
    : data_((Real*)(0)), n_(0) {
        swap(const_cast<Disposable<Array>&>(from));
    }

    namespace detail {

        template <class I>
        inline void _fill_array_(Array& a,
                                 boost::scoped_array<Real>& data_,
                                 Size& n_,
                                 I begin, I end,
                                 const boost::true_type&) {
            // we got redirected here from a call like Array(3, 4)
            // because it matched the constructor below exactly with
            // ForwardIterator = int.  What we wanted was fill an
            // Array with a given value, which we do here.
            Size n = begin;
            Real value = end;
            data_.reset(n ? new Real[n] : (Real*)(0));
            n_ = n;
            std::fill(a.begin(),a.end(),value);
        }

        template <class I>
        inline void _fill_array_(Array& a,
                                 boost::scoped_array<Real>& data_,
                                 Size& n_,
                                 I begin, I end,
                                 const boost::false_type&) {
            // true iterators
            Size n = std::distance(begin, end);
            data_.reset(n ? new Real[n] : (Real*)(0));
            n_ = n;
            #if defined(QL_PATCH_MSVC) && defined(QL_DEBUG)
            if (n_)
            #endif
            std::copy(begin, end, a.begin());
        }

    }

    template <class ForwardIterator>
    inline Array::Array(ForwardIterator begin, ForwardIterator end) {
        // Unfortunately, calls such as Array(3, 4) match this constructor.
        // We have to detect integral types and dispatch.
        detail::_fill_array_(*this, data_, n_, begin, end,
                             boost::is_integral<ForwardIterator>());
    }

    inline Array& Array::operator=(const Array& from) {
        // strong guarantee
        Array temp(from);
        swap(temp);
        return *this;
    }

    inline bool Array::operator==(const Array& to) const {
        return (n_ == to.n_) && std::equal(begin(), end(), to.begin());
    }

    inline bool Array::operator!=(const Array& to) const {
        return !(this->operator==(to));
    }

    inline Array& Array::operator=(const Disposable<Array>& from) {
        swap(const_cast<Disposable<Array>&>(from));
        return *this;
    }

    inline const Array& Array::operator+=(const Array& v) {
        QL_REQUIRE(n_ == v.n_,
                   "arrays with different sizes (" << n_ << ", "
                   << v.n_ << ") cannot be added");
        std::transform(begin(),end(),v.begin(),begin(),
                       std::plus<Real>());
        return *this;
    }

    inline const Array& Array::operator+=(Real x) {
        std::transform(begin(),end(),begin(),
                       std::bind2nd(std::plus<Real>(),x));
        return *this;
    }

    inline const Array& Array::operator-=(const Array& v) {
        QL_REQUIRE(n_ == v.n_,
                   "arrays with different sizes (" << n_ << ", "
                   << v.n_ << ") cannot be subtracted");
        std::transform(begin(),end(),v.begin(),begin(),
                       std::minus<Real>());
        return *this;
    }

    inline const Array& Array::operator-=(Real x) {
        std::transform(begin(),end(),begin(),
                       std::bind2nd(std::minus<Real>(),x));
        return *this;
    }

    inline const Array& Array::operator*=(const Array& v) {
        QL_REQUIRE(n_ == v.n_,
                   "arrays with different sizes (" << n_ << ", "
                   << v.n_ << ") cannot be multiplied");
        std::transform(begin(),end(),v.begin(),begin(),
                       std::multiplies<Real>());
        return *this;
    }

    inline const Array& Array::operator*=(Real x) {
        std::transform(begin(),end(),begin(),
                       std::bind2nd(std::multiplies<Real>(),x));
        return *this;
    }

    inline const Array& Array::operator/=(const Array& v) {
        QL_REQUIRE(n_ == v.n_,
                   "arrays with different sizes (" << n_ << ", "
                   << v.n_ << ") cannot be divided");
        std::transform(begin(),end(),v.begin(),begin(),
                       std::divides<Real>());
        return *this;
    }

    inline const Array& Array::operator/=(Real x) {
        std::transform(begin(),end(),begin(),
                       std::bind2nd(std::divides<Real>(),x));
        return *this;
    }

    inline Real Array::operator[](Size i) const {
        #if defined(QL_EXTRA_SAFETY_CHECKS)
        QL_REQUIRE(i<n_,
                   "index (" << i << ") must be less than " << n_ <<
                   ": array access out of range");
        #endif
        return data_.get()[i];
    }

    inline Real Array::at(Size i) const {
        QL_REQUIRE(i<n_,
                   "index (" << i << ") must be less than " << n_ <<
                   ": array access out of range");
        return data_.get()[i];
    }

    inline Real Array::front() const {
        #if defined(QL_EXTRA_SAFETY_CHECKS)
        QL_REQUIRE(n_>0, "null Array: array access out of range");
        #endif
        return data_.get()[0];
    }

    inline Real Array::back() const {
        #if defined(QL_EXTRA_SAFETY_CHECKS)
        QL_REQUIRE(n_>0, "null Array: array access out of range");
        #endif
        return data_.get()[n_-1];
    }

    inline Real& Array::operator[](Size i) {
        #if defined(QL_EXTRA_SAFETY_CHECKS)
        QL_REQUIRE(i<n_,
                   "index (" << i << ") must be less than " << n_ <<
                   ": array access out of range");
        #endif
        return data_.get()[i];
    }

    inline Real& Array::at(Size i) {
        QL_REQUIRE(i<n_,
                   "index (" << i << ") must be less than " << n_ <<
                   ": array access out of range");
        return data_.get()[i];
    }

    inline Real& Array::front() {
        #if defined(QL_EXTRA_SAFETY_CHECKS)
        QL_REQUIRE(n_>0, "null Array: array access out of range");
        #endif
        return data_.get()[0];
    }

    inline Real& Array::back() {
        #if defined(QL_EXTRA_SAFETY_CHECKS)
        QL_REQUIRE(n_>0, "null Array: array access out of range");
        #endif
        return data_.get()[n_-1];
    }

    inline Size Array::size() const {
        return n_;
    }

    inline bool Array::empty() const {
        return n_ == 0;
    }

    inline Array::const_iterator Array::begin() const {
        return data_.get();
    }

    inline Array::iterator Array::begin() {
        return data_.get();
    }

    inline Array::const_iterator Array::end() const {
        return data_.get()+n_;
    }

    inline Array::iterator Array::end() {
        return data_.get()+n_;
    }

    inline Array::const_reverse_iterator Array::rbegin() const {
        return const_reverse_iterator(end());
    }

    inline Array::reverse_iterator Array::rbegin() {
        return reverse_iterator(end());
    }

    inline Array::const_reverse_iterator Array::rend() const {
        return const_reverse_iterator(begin());
    }

    inline Array::reverse_iterator Array::rend() {
        return reverse_iterator(begin());
    }

    inline void Array::swap(Array& from) {
        using std::swap;
        data_.swap(from.data_);
        swap(n_,from.n_);
    }

    // dot product and norm

    inline Real DotProduct(const Array& v1, const Array& v2) {
        QL_REQUIRE(v1.size() == v2.size(),
                   "arrays with different sizes (" << v1.size() << ", "
                   << v2.size() << ") cannot be multiplied");
        return std::inner_product(v1.begin(),v1.end(),v2.begin(),0.0);
    }

    inline Real Norm2(const Array& v) {
        return std::sqrt(DotProduct(v, v));
    }

    // overloaded operators

    // unary

    inline const Disposable<Array> operator+(const Array& v) {
        Array result = v;
        return result;
    }

    inline const Disposable<Array> operator-(const Array& v) {
        Array result(v.size());
        std::transform(v.begin(),v.end(),result.begin(),
                       std::negate<Real>());
        return result;
    }

    // binary operators

    inline const Disposable<Array> operator+(const Array& v1,
                                             const Array& v2) {
        QL_REQUIRE(v1.size() == v2.size(),
                   "arrays with different sizes (" << v1.size() << ", "
                   << v2.size() << ") cannot be added");
        Array result(v1.size());
        std::transform(v1.begin(),v1.end(),v2.begin(),result.begin(),
                       std::plus<Real>());
        return result;
    }

    inline const Disposable<Array> operator+(const Array& v1, Real a) {
        Array result(v1.size());
        std::transform(v1.begin(),v1.end(),result.begin(),
                       std::bind2nd(std::plus<Real>(),a));
        return result;
    }

    inline const Disposable<Array> operator+(Real a, const Array& v2) {
        Array result(v2.size());
        std::transform(v2.begin(),v2.end(),result.begin(),
                       std::bind1st(std::plus<Real>(),a));
        return result;
    }

    inline const Disposable<Array> operator-(const Array& v1,
                                             const Array& v2) {
        QL_REQUIRE(v1.size() == v2.size(),
                   "arrays with different sizes (" << v1.size() << ", "
                   << v2.size() << ") cannot be subtracted");
        Array result(v1.size());
        std::transform(v1.begin(),v1.end(),v2.begin(),result.begin(),
                       std::minus<Real>());
        return result;
    }

    inline const Disposable<Array> operator-(const Array& v1, Real a) {
        Array result(v1.size());
        std::transform(v1.begin(),v1.end(),result.begin(),
                       std::bind2nd(std::minus<Real>(),a));
        return result;
    }

    inline const Disposable<Array> operator-(Real a, const Array& v2) {
        Array result(v2.size());
        std::transform(v2.begin(),v2.end(),result.begin(),
                       std::bind1st(std::minus<Real>(),a));
        return result;
    }

    inline const Disposable<Array> operator*(const Array& v1,
                                             const Array& v2) {
        QL_REQUIRE(v1.size() == v2.size(),
                   "arrays with different sizes (" << v1.size() << ", "
                   << v2.size() << ") cannot be multiplied");
        Array result(v1.size());
        std::transform(v1.begin(),v1.end(),v2.begin(),result.begin(),
                       std::multiplies<Real>());
        return result;
    }

    inline const Disposable<Array> operator*(const Array& v1, Real a) {
        Array result(v1.size());
        std::transform(v1.begin(),v1.end(),result.begin(),
                       std::bind2nd(std::multiplies<Real>(),a));
        return result;
    }

    inline const Disposable<Array> operator*(Real a, const Array& v2) {
        Array result(v2.size());
        std::transform(v2.begin(),v2.end(),result.begin(),
                       std::bind1st(std::multiplies<Real>(),a));
        return result;
    }

    inline const Disposable<Array> operator/(const Array& v1,
                                             const Array& v2) {
        QL_REQUIRE(v1.size() == v2.size(),
                   "arrays with different sizes (" << v1.size() << ", "
                   << v2.size() << ") cannot be divided");
        Array result(v1.size());
        std::transform(v1.begin(),v1.end(),v2.begin(),result.begin(),
                       std::divides<Real>());
        return result;
    }

    inline const Disposable<Array> operator/(const Array& v1, Real a) {
        Array result(v1.size());
        std::transform(v1.begin(),v1.end(),result.begin(),
                       std::bind2nd(std::divides<Real>(),a));
        return result;
    }

    inline const Disposable<Array> operator/(Real a, const Array& v2) {
        Array result(v2.size());
        std::transform(v2.begin(),v2.end(),result.begin(),
                       std::bind1st(std::divides<Real>(),a));
        return result;
    }

    // functions

    inline const Disposable<Array> Abs(const Array& v) {
        Array result(v.size());
        std::transform(v.begin(),v.end(),result.begin(),
                       std::ptr_fun<Real,Real>(std::fabs));
        return result;
    }

    inline const Disposable<Array> Sqrt(const Array& v) {
        Array result(v.size());
        std::transform(v.begin(),v.end(),result.begin(),
                       std::ptr_fun<Real,Real>(std::sqrt));
        return result;
    }

    inline const Disposable<Array> Log(const Array& v) {
        Array result(v.size());
        std::transform(v.begin(),v.end(),result.begin(),
                       std::ptr_fun<Real,Real>(std::log));
        return result;
    }

    inline const Disposable<Array> Exp(const Array& v) {
        Array result(v.size());
        std::transform(v.begin(),v.end(),result.begin(),
                       std::ptr_fun<Real,Real>(std::exp));
        return result;
    }

    inline const Disposable<Array> Pow(const Array& v, Real alpha) {
        Array result(v.size());
        std::transform(v.begin(), v.end(), result.begin(),
            std::bind2nd(std::ptr_fun<Real, Real, Real>(std::pow), alpha));

        return result;
    }

    inline void swap(Array& v, Array& w) {
        v.swap(w);
    }

    inline std::ostream& operator<<(std::ostream& out, const Array& a) {
        std::streamsize width = out.width();
        out << "[ ";
        if (!a.empty()) {
            for (Size n=0; n<a.size()-1; ++n)
                out << std::setw(int(width)) << a[n] << "; ";
            out << std::setw(int(width)) << a.back();
        }
        out << " ]";
        return out;
    }

}

#endif

max_stars_repo_name: markxio/Quantuccia

max_issues_repo_name: markxio/Quantuccia

max_forks_repo_name: markxio/Quantuccia


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

#ifndef SAGA_IMPL_ENGINE_PREFERENCES_HPP
#define SAGA_IMPL_ENGINE_PREFERENCES_HPP

#include <string>
#include <set>

#include <saga/saga/context.hpp>
#include <boost/assert.hpp>

///////////////////////////////////////////////////////////////////////////////
namespace saga { namespace impl { namespace v1_0
{
    // used for adaptor and method preferences
    struct preferences
    {
        typedef std::set<std::string> data_type;
        typedef data_type::iterator iterator;
        typedef data_type::const_iterator const_iterator;

        void set(std::string const& key, std::string const& value)
        {
            BOOST_ASSERT(saga::attributes::context_type == key);
            data_.insert(value);
        }
        void clear()
        {
            data_.clear();
        }

        friend bool operator< (preferences const& lhs, preferences const& rhs)
        {
            return lhs.data_ < rhs.data_;
        }

        data_type data_;
    };

    typedef preferences preference_type;

}}}

#endif

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp


text:
/*
 [auto_generated]
 boost/numeric/odeint/integrate/detail/integrate_adaptive.hpp

 [begin_description]
 Default Integrate adaptive implementation.
 [end_description]

 Copyright 2009-2011 Karsten Ahnert
 Copyright 2009-2011 Mario Mulansky

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

#ifndef BOOST_NUMERIC_ODEINT_INTEGRATE_DETAIL_INTEGRATE_ADAPTIVE_HPP_INCLUDED
#define BOOST_NUMERIC_ODEINT_INTEGRATE_DETAIL_INTEGRATE_ADAPTIVE_HPP_INCLUDED

#include <stdexcept>

#include <boost/numeric/odeint/stepper/stepper_categories.hpp>
#include <boost/numeric/odeint/stepper/controlled_step_result.hpp>
#include <boost/numeric/odeint/iterator/integrate/detail/integrate_const.hpp>
#include <boost/numeric/odeint/iterator/adaptive_time_iterator.hpp>
#include <boost/numeric/odeint/iterator/integrate/detail/functors.hpp>
#include <boost/numeric/odeint/util/bind.hpp>
#include <boost/numeric/odeint/util/unwrap_reference.hpp>
#include <boost/numeric/odeint/util/copy.hpp>

#include <boost/numeric/odeint/util/detail/less_with_sign.hpp>

namespace boost {
namespace numeric {
namespace odeint {
namespace detail {

// forward declaration
template< class Stepper , class System , class State , class Time , class Observer>
size_t integrate_const(
        Stepper stepper , System system , State &start_state ,
        Time start_time , Time end_time , Time dt ,
        Observer observer , stepper_tag );

/*
 * integrate_adaptive for simple stepper is basically an integrate_const + some last step
 */
template< class Stepper , class System , class State , class Time , class Observer >
size_t integrate_adaptive(
        Stepper stepper , System system , State &start_state ,
        Time start_time , Time end_time , Time dt ,
        Observer observer , stepper_tag
)
{
    size_t steps = detail::integrate_const( stepper , system , start_state , start_time ,
                                            end_time , dt , observer , stepper_tag() );
    typename odeint::unwrap_reference< Observer >::type &obs = observer;
    typename odeint::unwrap_reference< Stepper >::type &st = stepper;

    Time end = start_time + dt*steps;
    if( less_with_sign( end , end_time , dt ) )
    {   //make a last step to end exactly at end_time
        st.do_step( system , start_state , end , end_time - end );
        steps++;
        obs( start_state , end_time );
    }
    return steps;
}

/*
 * classical integrate adaptive
 */
template< class Stepper , class System , class State , class Time , class Observer >
size_t integrate_adaptive(
        Stepper stepper , System system , State &start_state ,
        Time &start_time , Time end_time , Time &dt ,
        Observer observer , controlled_stepper_tag
)
{
    size_t obs_calls = 0;

    boost::for_each( make_adaptive_time_range( stepper , system , start_state ,
                                               start_time , end_time , dt ) ,
                     obs_caller< Observer >( obs_calls , observer ) );

    return obs_calls-1;
}

/*
 * integrate adaptive for dense output steppers
 *
 * step size control is used if the stepper supports it
 */
template< class Stepper , class System , class State , class Time , class Observer >
size_t integrate_adaptive(
        Stepper stepper , System system , State &start_state ,
        Time start_time , Time end_time , Time dt ,
        Observer observer , dense_output_stepper_tag )
{
    size_t obs_calls = 0;

    boost::for_each( make_adaptive_time_range( stepper , system , start_state ,
                                               start_time , end_time , dt ) ,
                     obs_caller< Observer >( obs_calls , observer ) );

    return obs_calls-1;
}

} // namespace detail
} // namespace odeint
} // namespace numeric
} // namespace boost

#endif // BOOST_NUMERIC_ODEINT_INTEGRATE_DETAIL_INTEGRATE_ADAPTIVE_HPP_INCLUDED

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
#pragma once

#include <tuple>
#include <Eigen/Core>
#include <Eigen/Eigenvalues>

#include "geometry.hpp"

namespace rt {
	class OnlineCovarianceMatrix2x2 {
	public:
		void addSample(Vec2 x) {
			_00.addSample(x[0], x[0]);
			_11.addSample(x[1], x[1]);
			_01.addSample(x[0], x[1]);
		}
		Eigen::Matrix2d sampleCovarianceMatrix() const {
			Eigen::Matrix2d cov;
			cov(0, 0) = _00.sampleCovariance();
			cov(1, 1) = _11.sampleCovariance();
			cov(0, 1) = cov(1, 0) = _01.sampleCovariance();
			return cov;
		}
	private:
		OnlineCovariance _00;
		OnlineCovariance _11;
		OnlineCovariance _01;
	};
	class OnlineCovarianceMatrix3x3 {
	public:
		void addSample(Vec3 x) {
			_00.addSample(x[0], x[0]);
			_11.addSample(x[1], x[1]);
			_22.addSample(x[2], x[2]);
			_01.addSample(x[0], x[1]);
			_02.addSample(x[0], x[2]);
			_12.addSample(x[1], x[2]);
		}
		Eigen::Matrix3d sampleCovarianceMatrix() const {
			Eigen::Matrix3d cov;
			cov(0, 0) = _00.sampleCovariance();
			cov(1, 1) = _11.sampleCovariance();
			cov(2, 2) = _22.sampleCovariance();
			cov(0, 1) = cov(1, 0) = _01.sampleCovariance();
			cov(0, 2) = cov(2, 0) = _02.sampleCovariance();
			cov(1, 2) = cov(2, 1) = _12.sampleCovariance();
			return cov;
		}
	private:
		OnlineCovariance _00;
		OnlineCovariance _11;
		OnlineCovariance _22;
		OnlineCovariance _01;
		OnlineCovariance _02;
		OnlineCovariance _12;
	};

	/*
	主成分分析 2x2 mat
	*/
	inline std::tuple<Vec2, Vec2> PCA(const Eigen::Matrix2d covarianceMatrix) {
		Eigen::EigenSolver<Eigen::Matrix2d> es(covarianceMatrix);
		auto eigenvectors = es.eigenvectors();
		Vec2 xaxis(
			eigenvectors(0, 0).real(),
			eigenvectors(1, 0).real()
		);
		Vec2 yaxis(
			eigenvectors(0, 1).real(),
			eigenvectors(1, 1).real()
		);
		return{ xaxis, yaxis };
	}

	/*
	主成分分析 3x3 mat
	*/
	inline std::tuple<Vec3, Vec3, Vec3> PCA(const Eigen::Matrix3d covarianceMatrix) {
		Eigen::EigenSolver<Eigen::Matrix3d> es(covarianceMatrix);
		auto eigenvectors = es.eigenvectors();
		Vec3 xaxis(
			eigenvectors(0, 0).real(),
			eigenvectors(1, 0).real(),
			eigenvectors(2, 0).real()
		);
		Vec3 yaxis(
			eigenvectors(0, 1).real(),
			eigenvectors(1, 1).real(),
			eigenvectors(2, 1).real()
		);
		Vec3 zaxis(
			eigenvectors(0, 2).real(),
			eigenvectors(1, 2).real(),
			eigenvectors(2, 2).real()
		);

		return{ xaxis , yaxis, zaxis };
	}
}

max_stars_repo_name: Ushio/MofuMofuRender

max_issues_repo_name: Ushio/MofuMofuRender

max_forks_repo_name: Ushio/MofuMofuRender


text:
// actual google test classes
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/assign/ptr_list_of.hpp>
#include <boost/uuid/uuid.hpp>
#include "testing/gunit.h"
#include "base/logging.h"
#include <query.h>
#include <analytics_query_mock.h>
#include "contrail-collector/db_handler.h"
#include "contrail-collector/test/cql_if_mock.h"
#include "base/test/task_test_util.h"

using ::testing::_;
using ::testing::Return;
using ::testing::AnyNumber;

TtlMap ttl_map = g_viz_constants.TtlValuesDefault;

struct map_value {
    GenDb::GenDbIf::DbGetRowCb cb;
    const void * ctx;
    void * privdata;
};

class DbQueryUnitTest: public ::testing::Test {
 public:
    bool GetRowAsyncSuccess(const std::string& cfname,
        const GenDb::DbDataValueVec& rowkey,
        const GenDb::ColumnNameRange &crange,
        const GenDb::WhereIndexInfoVec &where_vec,
        GenDb::DbConsistency::type dconsistency,
        GenDb::GenDbIf::DbGetRowCb cb);
    bool GetRowAsyncFailure(const std::string& cfname,
        const GenDb::DbDataValueVec& rowkey,
        const GenDb::ColumnNameRange &crange,
        const GenDb::WhereIndexInfoVec &where_vec,
        GenDb::DbConsistency::type dconsistency,
        GenDb::GenDbIf::DbGetRowCb cb);
    bool StatTableGetRowAsyncSuccess(const std::string& cfname,
        const GenDb::DbDataValueVec& rowkey,
        const GenDb::ColumnNameRange &crange,
        const GenDb::WhereIndexInfoVec& where_vec,
        GenDb::DbConsistency::type dconsistency,
        GenDb::GenDbIf::DbGetRowCb cb);
    bool TestFailureHandling(const std::string& cfname,
             const GenDb::DbDataValueVec& rowkey,
             const GenDb::ColumnNameRange &crange,
             const GenDb::WhereIndexInfoVec& where_vec,
             GenDb::DbConsistency::type dconsistency,
             GenDb::GenDbIf::DbGetRowCb cb);
    void subquery_processed(QueryUnit *subquery);
    void cb(void *handle, QEOpServerProxy::QPerfInfo qpi, std::auto_ptr<WhereResultT> where_result);

    std::map<uint64_t, map_value> m;
    std::map<uint64_t, const std::auto_ptr<GenDb::NewColVec> > kv;
};

bool DbQueryUnitTest::TestFailureHandling(const std::string& cfname,
             const GenDb::DbDataValueVec& rowkey,
             const GenDb::ColumnNameRange &crange,
             const GenDb::WhereIndexInfoVec& where_vec,
             GenDb::DbConsistency::type dconsistency,
             GenDb::GenDbIf::DbGetRowCb cb) {
    std::auto_ptr<GetRowInput> rip(new GetRowInput());
    rip->rowkey = rowkey;
    std::auto_ptr<GenDb::ColList> collist;
    cb(GenDb::DbOpResult::ERROR, collist);
    return true;
}

bool DbQueryUnitTest::GetRowAsyncSuccess(const std::string& cfname,
    const GenDb::DbDataValueVec& rowkey, const GenDb::ColumnNameRange &crange,
    const GenDb::WhereIndexInfoVec &where_vec,
    GenDb::DbConsistency::type dconsistency, GenDb::GenDbIf::DbGetRowCb cb) {
    // Return the following for every row
    boost::uuids::random_generator rgen_;
    boost::uuids::uuid unm(rgen_());
    GenDb::DbDataValueVec *colname(new GenDb::DbDataValueVec());
    colname->reserve(3);
    colname->push_back("a6s9");
    colname->push_back(unm);
    colname->push_back((uint32_t)(21212));
    GenDb::DbDataValueVec *colvalue(new GenDb::DbDataValueVec());
    colvalue->push_back(unm);
    std::auto_ptr<GenDb::ColList> columns(new GenDb::ColList());
    int ttl = 5;
    columns->columns_ = boost::assign::ptr_list_of<GenDb::NewCol>
        (GenDb::NewCol(colname, colvalue, ttl));
    cb(GenDb::DbOpResult::OK, columns);
    return true;
}

bool DbQueryUnitTest::StatTableGetRowAsyncSuccess(const std::string& cfname,
    const GenDb::DbDataValueVec& rowkey, const GenDb::ColumnNameRange &crange,
    const GenDb::WhereIndexInfoVec& where_vec,
    GenDb::DbConsistency::type dconsistency, GenDb::GenDbIf::DbGetRowCb cb) {
    // Return the following for every row
    boost::uuids::random_generator rgen_;
    boost::uuids::uuid unm(rgen_());
    GenDb::DbDataValueVec *colname(new GenDb::DbDataValueVec());
    colname->reserve(3);
    colname->push_back("a6s9");
    //colname->push_back(unm);
    colname->push_back((uint32_t)(21212));
    colname->push_back(unm);
    GenDb::DbDataValueVec *colvalue(new GenDb::DbDataValueVec());
    colvalue->push_back("Attrval1");
    std::auto_ptr<GenDb::ColList> columns(new GenDb::ColList());
    int ttl = 5;
    columns->columns_ = boost::assign::ptr_list_of<GenDb::NewCol>
        (GenDb::NewCol(colname, colvalue, ttl));
    cb(GenDb::DbOpResult::OK, columns);
    return true;
}

bool DbQueryUnitTest::GetRowAsyncFailure(const std::string& cfname,
    const GenDb::DbDataValueVec& rowkey, const GenDb::ColumnNameRange &crange,
    const GenDb::WhereIndexInfoVec& where_vec,
    GenDb::DbConsistency::type dconsistency, GenDb::GenDbIf::DbGetRowCb cb) {
    std::auto_ptr<GenDb::ColList> columns(new GenDb::ColList());
    cb(GenDb::DbOpResult::ERROR, columns);
    return true;
}

void DbQueryUnitTest::subquery_processed(QueryUnit *subquery) {
    EXPECT_EQ(QUERY_SUCCESS, subquery->query_status);
    EXPECT_EQ(119, subquery->query_result->size());
    return;
}

void DbQueryUnitTest::cb(void *handle, QEOpServerProxy::QPerfInfo qpi, std::auto_ptr<WhereResultT> where_result) {
    EXPECT_EQ(1, where_result->size());
    return;
}

TEST_F(DbQueryUnitTest, ProcessQuery) {
    AnalyticsQueryMock analytics_query_mock;
    AnalyticsQueryMock parent;
    analytics_query_mock.parallel_batch_num = 1;
    analytics_query_mock.query_id = "abcd";
    std::auto_ptr<QueryEngine> qe(new QueryEngine());
    analytics_query_mock.qe_ = qe.get();
    analytics_query_mock.qe_->max_tasks_ = 15;

    DbQueryUnit *dbq = new DbQueryUnit(&analytics_query_mock, &analytics_query_mock);
    EXPECT_CALL(*(CqlIfMock *)(analytics_query_mock.dbif_.get()),
        Db_GetRowAsync(_,_,_,_,_,_))
            .Times(AnyNumber())
            .WillRepeatedly(Invoke(this,
                &DbQueryUnitTest::GetRowAsyncSuccess));
    EXPECT_CALL(analytics_query_mock, table()).Times(AnyNumber()).WillRepeatedly(Return("table1"));
    EXPECT_CALL(analytics_query_mock, end_time()).Times(AnyNumber()).WillRepeatedly(Return(1473385977637609));
    EXPECT_CALL(analytics_query_mock, from_time()).Times(AnyNumber()).WillRepeatedly(Return(1473384977637609));
    EXPECT_CALL(analytics_query_mock, subquery_processed(_)).Times(1).WillOnce(Invoke(this, &DbQueryUnitTest::subquery_processed));
    EXPECT_CALL(analytics_query_mock, is_stat_table_query()).Times(AnyNumber())
        .WillRepeatedly(Return(false));
    bool status = dbq->process_query();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(QUERY_IN_PROGRESS, status);
}

TEST_F(DbQueryUnitTest, ProcessQueryFailure) {
    AnalyticsQueryMock analytics_query_mock;
    AnalyticsQueryMock parent;
    analytics_query_mock.parallel_batch_num = 1;
    analytics_query_mock.query_id = "abcd";
    std::auto_ptr<QueryEngine> qe(new QueryEngine());
    analytics_query_mock.qe_ = qe.get();
    analytics_query_mock.qe_->max_tasks_ = 15;

    DbQueryUnit *dbq = new DbQueryUnit(&analytics_query_mock, &analytics_query_mock);
    EXPECT_CALL(*(CqlIfMock *)(analytics_query_mock.dbif_.get()),
        Db_GetRowAsync(_,_,_,_,_,_))
            .Times(AnyNumber())
            .WillRepeatedly(Invoke(this,
                &DbQueryUnitTest::GetRowAsyncFailure));
    EXPECT_CALL(analytics_query_mock, table()).Times(AnyNumber()).WillRepeatedly(Return("table1"));
    EXPECT_CALL(analytics_query_mock, end_time()).Times(AnyNumber()).WillRepeatedly(Return(1473385977637609));
    EXPECT_CALL(analytics_query_mock, from_time()).Times(AnyNumber()).WillRepeatedly(Return(1473384977637609));
    EXPECT_CALL(analytics_query_mock, subquery_processed(_)).Times(1).WillOnce(Return());
    bool status = dbq->process_query();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(QUERY_IN_PROGRESS, status);
    TASK_UTIL_EXPECT_EQ(QUERY_FAILURE, dbq->query_status);
}

TEST_F(DbQueryUnitTest, QueryFailureCallback) {
    AnalyticsQueryMock analytics_query_mock;
    AnalyticsQueryMock parent;
    analytics_query_mock.parallel_batch_num = 1;
    analytics_query_mock.query_id = "abcd";
    std::auto_ptr<QueryEngine> qe(new QueryEngine());
    analytics_query_mock.qe_ = qe.get();
    analytics_query_mock.qe_->max_tasks_ = 15;

    DbQueryUnit *dbq = new DbQueryUnit(&analytics_query_mock,
        &analytics_query_mock);
    GenDb::DbDataValueVec rowkey;
    uint32_t t2=12345;
    rowkey.push_back(t2);
    std::vector<GenDb::DbDataValueVec> keys;
    EXPECT_CALL(*(CqlIfMock *)(analytics_query_mock.dbif_.get()),
        Db_GetRowAsync(_,_,_,_,_,_)).Times(AnyNumber()).WillRepeatedly(
        Invoke(this, &DbQueryUnitTest::TestFailureHandling));
    EXPECT_CALL(analytics_query_mock, table()).Times(AnyNumber()).
        WillRepeatedly(Return("table1"));
    EXPECT_CALL(analytics_query_mock, end_time()).Times(AnyNumber()).
        WillRepeatedly(Return(1473385977637609));
    EXPECT_CALL(analytics_query_mock, from_time()).Times(AnyNumber()).
        WillRepeatedly(Return(1473384977637609));
    EXPECT_CALL(analytics_query_mock, subquery_processed(_)).Times(1).
        WillOnce(Return());
    bool status = dbq->process_query();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(QUERY_IN_PROGRESS, status);
    TASK_UTIL_EXPECT_EQ(QUERY_FAILURE, dbq->query_status);
}

TEST_F(DbQueryUnitTest, WhereQueryProcessing) {
    AnalyticsQueryMock mq;
    mq.query_id = "abcd";
    std::auto_ptr<QueryEngine> qe(new QueryEngine());
    mq.qe_ = qe.get();
    mq.qe_->max_tasks_ = 15;

    DbQueryUnit *mdbq = new DbQueryUnit(&mq,&mq);
    EXPECT_CALL(mq, table()).Times(AnyNumber()).WillRepeatedly(Return("table1"));
    EXPECT_CALL(mq, is_object_table_query(_)).Times(AnyNumber()).WillRepeatedly(Return(false));
    WhereQuery *wq= new WhereQuery(mdbq);
    wq->main_query = &mq;
    wq->where_result_.reset(new std::vector<query_result_unit_t>);
    wq->where_query_cb_ = boost::bind(&DbQueryUnitTest::cb, this, _1, _2, _3);
    AnalyticsQueryMock *q1 = new AnalyticsQueryMock();
    AnalyticsQueryMock *q2 = new AnalyticsQueryMock();
    DbQueryUnit *dbq1 = new DbQueryUnit(wq, q1);
    DbQueryUnit *dbq2 = new DbQueryUnit(wq, q2);
    EXPECT_CALL(*q1, table()).Times(AnyNumber()).WillRepeatedly(Return("table1"));
    EXPECT_CALL(*q2, table()).Times(AnyNumber()).WillRepeatedly(Return("table1"));
    EXPECT_CALL(*q1, is_object_table_query(_)).Times(AnyNumber()).WillRepeatedly(Return(false));
    EXPECT_CALL(*q2, is_object_table_query(_)).Times(AnyNumber()).WillRepeatedly(Return(false));
    dbq1->sub_query_id = 0;
    dbq2->sub_query_id = 1;
    wq->query_status = QUERY_SUCCESS;
    dbq1->query_status = QUERY_SUCCESS;
    dbq2->query_status = QUERY_SUCCESS;

    // Populate the subquery1 result
    boost::shared_ptr<std::vector<query_result_unit_t> >where_query_result_;
    where_query_result_ = boost::shared_ptr<std::vector<query_result_unit_t> >
                              (new std::vector<query_result_unit_t>());
    query_result_unit_t res1, res2, res3, res4;
    res1.timestamp = 121212;
    res2.timestamp = 121213;
    where_query_result_->push_back(res1);
    where_query_result_->push_back(res2);
    (dbq1->query_result) = where_query_result_;
    wq->subquery_processed(dbq1);

    // populate the subquery2 result
    //std::vector<query_result_unit_t> where_query_result_2;
    boost::shared_ptr<std::vector<query_result_unit_t> >where_query_result_2;
    where_query_result_2 = boost::shared_ptr<std::vector<query_result_unit_t> >
                              (new std::vector<query_result_unit_t>());
    res3.timestamp = 121213;
    res4.timestamp = 121215;
    where_query_result_2->push_back(res3);
    where_query_result_2->push_back(res4);
    (dbq2->query_result) = where_query_result_2;
    wq->subquery_processed(dbq2);
    delete q1;
    delete q2;
}

/*
 * push uuid and object_id into query_result_unit_t.info
 * check if GetObjectId returns the object id correctly
 */
TEST_F(DbQueryUnitTest, GetObjectId) {
    query_result_unit_t res1;
    boost::uuids::random_generator rgen_;
    boost::uuids::uuid unm(rgen_());
    std::string object_id("id1");
    res1.info.push_back(unm);
    res1.info.push_back(object_id);
    std::string returned_val;
    res1.get_objectid(returned_val);
    EXPECT_EQ(object_id, returned_val);
}

/*
 * check if the stats attribute are updated properly for successful and
 * unsuccessful stats table reads
 */
TEST_F(DbQueryUnitTest, TestStatsUpdate) {
    AnalyticsQueryMock analytics_query_mock;
    AnalyticsQueryMock parent;
    analytics_query_mock.parallel_batch_num = 1;
    analytics_query_mock.query_id = "abcd";
    std::auto_ptr<QueryEngine> qe(new QueryEngine());
    analytics_query_mock.qe_ = qe.get();
    analytics_query_mock.qe_->max_tasks_ = 15;
    analytics_query_mock.stat_name_attr = "Statattr";

    DbQueryUnit *dbq = new DbQueryUnit(&analytics_query_mock, &analytics_query_mock);
    EXPECT_CALL(*(CqlIfMock *)(analytics_query_mock.dbif_.get()),
        Db_GetRowAsync(_,_,_,_,_,_))
            .Times(AnyNumber())
            .WillRepeatedly(Invoke(this,
                &DbQueryUnitTest::StatTableGetRowAsyncSuccess));
    EXPECT_CALL(analytics_query_mock, table()).Times(AnyNumber()).WillRepeatedly(Return("StatTable1"));
    EXPECT_CALL(analytics_query_mock, end_time()).Times(AnyNumber()).WillRepeatedly(Return(1473385977637609));
    EXPECT_CALL(analytics_query_mock, from_time()).Times(AnyNumber()).WillRepeatedly(Return(1473384977637609));
    EXPECT_CALL(analytics_query_mock, subquery_processed(_)).Times(1).WillOnce(Invoke(this, &DbQueryUnitTest::subquery_processed));
    EXPECT_CALL(analytics_query_mock, is_stat_table_query())
            .Times(AnyNumber())
            .WillRepeatedly(Return(true));
    bool status = dbq->process_query();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(QUERY_IN_PROGRESS, status);
    std::vector<GenDb::DbTableInfo> vstats_dbti, vstats_dbti_fail;
    // Only StatsTable stats can be tested in UT,
    // stats for other tables are checked in systemtest
    analytics_query_mock.qe_->stable_stats_.GetDiffs(&vstats_dbti);
    // Only one stat attribute is being read
    TASK_UTIL_EXPECT_EQ(vstats_dbti.size(), 1);
    // Each read increments the read count of the stat attribute
    TASK_UTIL_EXPECT_EQ(vstats_dbti[0].table_name, "Statattr" );
    TASK_UTIL_EXPECT_EQ(vstats_dbti[0].reads, 120);
    EXPECT_CALL(*(CqlIfMock *)(analytics_query_mock.dbif_.get()),
        Db_GetRowAsync(_,_,_,_,_,_))
            .Times(AnyNumber())
            .WillRepeatedly(Invoke(this,
                &DbQueryUnitTest::GetRowAsyncFailure));
    EXPECT_CALL(analytics_query_mock, table()).Times(AnyNumber()).WillRepeatedly(Return("StatTable1"));
    EXPECT_CALL(analytics_query_mock, end_time()).Times(AnyNumber()).WillRepeatedly(Return(1473385977637609));
    EXPECT_CALL(analytics_query_mock, from_time()).Times(AnyNumber()).WillRepeatedly(Return(1473384977637609));
    EXPECT_CALL(analytics_query_mock, subquery_processed(_)).Times(1).WillOnce(Return());
    status = dbq->process_query();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(QUERY_IN_PROGRESS, status);
    TASK_UTIL_EXPECT_EQ(QUERY_FAILURE, dbq->query_status);
    // stats for other tables are checked in systemtest
    analytics_query_mock.qe_->stable_stats_.GetDiffs(&vstats_dbti_fail);
    // Read failures should be recorded
    TASK_UTIL_EXPECT_GT(vstats_dbti_fail[0].read_fails, 0);
}

int main(int argc, char **argv) {
    LoggingInit();
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

ext: cc

max_stars_repo_name: atsgen/tf-analytics

max_issues_repo_name: atsgen/tf-analytics

max_forks_repo_name: atsgen/tf-analytics


text:
/*!
 * \file ObjectSearcher.cpp
 * \brief The main object search node class.
 *
 * The object searcher node is responsible for searching for a given object given information obtained from the
 * interactive world project. Associated ROS information is maintained in this class.
 *
 * \author Russell Toris, WPI - rctoris@wpi.edu
 * \date March 18, 2015
 */

#include <boost/algorithm/string.hpp>
#include <informed_object_search/ObjectSearcher.h>
#include <interactive_world_msgs/LoadModels.h>
#include <interactive_world_msgs/FindObservations.h>
#include <interactive_world_msgs/GetSurfaces.h>
#include <informed_object_search/ObjectOnSurfaceModel.h>

using namespace std;
using namespace rail::interactive_world;

ObjectSearcher::ObjectSearcher()
    : private_node_("~"), search_ac_("/high_level_action_server/drive_and_search", true), ac_wait_time_(AC_WAIT_TIME),
      as_(private_node_, "object_search", boost::bind(&ObjectSearcher::objectSearch, this, _1), false)
{
  // setup any services/topics we need
  model_fetcher_srv_ = node_.serviceClient<interactive_world_msgs::LoadModels>(
      "/interactive_world_model_fetcher/load_models"
  );
  find_observations_srv_ = node_.serviceClient<interactive_world_msgs::FindObservations>(
      "/spatial_world_model_server/find_observations"
  );
  get_surfaces_srv_ = node_.serviceClient<interactive_world_msgs::GetSurfaces>(
      "/high_level_action_server/get_surfaces"
  );

  // start the action server
  as_.start();

  // wait for the action server
  search_ac_.waitForServer(ac_wait_time_);

  ROS_INFO("Object Searcher Successfully Initialized");
}

void ObjectSearcher::objectSearch(const interactive_world_msgs::ObjectSearchGoalConstPtr &goal)
{
  // final list based on confidence
  map<string, double> confidences;

  // seed every surface
  interactive_world_msgs::GetSurfaces surfaces_req;
  get_surfaces_srv_.call(surfaces_req);
  for (size_t i = 0; i < surfaces_req.response.surfaces.size(); i++)
  {
    cout << surfaces_req.response.surfaces[i] << endl;
    confidences[surfaces_req.response.surfaces[i]] = 0.001;
  }

  // ignore case
  string item = boost::to_upper_copy(goal->item);
  ROS_INFO("Searching for '%s'...", item.c_str());

  interactive_world_msgs::ObjectSearchFeedback feedback;
  interactive_world_msgs::ObjectSearchResult result;
  // default to false
  result.success = false;

  // check the world model
  feedback.message = "Requesting world model history...";
  as_.publishFeedback(feedback);

  interactive_world_msgs::FindObservations find_observations;
  find_observations.request.item = item;
  find_observations_srv_.call(find_observations);

  // each surface has an exponential distribution
  map<string, map<string, ObjectOnSurfaceModel> > distributions;
  ros::Time now = ros::Time::now();
  for (size_t i = 0; i < find_observations.response.surfaces.size(); i++)
  {
    ObjectOnSurfaceModel &model = distributions[find_observations.response.surfaces[i]][item];
    model.setObject(item);
    model.setSurface(find_observations.response.surfaces[i]);
    model.addObservation(find_observations.response.times[i].sec, find_observations.response.removals[i].sec);
  }

  for (map<string, map<string, ObjectOnSurfaceModel> >::iterator iter = distributions.begin();
       iter != distributions.end(); ++iter)
  {
    double p = iter->second[item].getCurrentProbability();
    cout << "P(" << item << " on " << iter->first << ")=" << p << endl;
    confidences[iter->first] = p;
  }

//  // request models
//  feedback.message = "Requesting trainied models...";
//  as_.publishFeedback(feedback);
//
//  // grab each model from the database
//  vector<interactive_world_msgs::Model> models;
//  for (size_t i = 0; i < goal->models.size(); i++)
//  {
//    // create and send a request
//    interactive_world_msgs::LoadModels loader;
//    loader.request.condition_id = goal->models[i];
//    if (model_fetcher_srv_.call(loader))
//    {
//      // search for the object we are looking for
//      vector<interactive_world_msgs::Model> &cur = loader.response.models.models;
//      for (size_t j = 0; j < cur.size(); j++)
//      {
//        // check if the names match and restrict search to surfaces
//        string placement_item = boost::to_upper_copy(cur[j].placement.item.name);
//        string placement_reference = boost::to_upper_copy(cur[j].placement.reference_frame_id);
//        if (cur[j].placement.surface.name.size() > 0 && (placement_item == item || placement_reference == item))
//        {
//          models.push_back(cur[j]);
//        }
//      }
//    } else
//    {
//      ROS_WARN("Could not load model %i.", goal->models[i]);
//      as_.setSucceeded(result, "Could not load all models from the RMS database.");
//      return;
//    }
//  }
//
//  // tally up confidences for each surface
//  for (size_t i = 0; i < models.size(); i++)
//  {
//    // get the current surface name
//    const interactive_world_msgs::Model &m = models[i];
//    string surface_name = m.placement.surface.name;
//    if (confidences.find(surface_name) == confidences.end())
//    {
//      confidences[surface_name] = 0.0;
//    }
//
//    // add to the confidence
//    confidences[surface_name] += m.decision_value;
//  }

  while (!confidences.empty())
  {
    // check for the current best
    //double lowest = numeric_limits<double>::infinity();
    double highest = -numeric_limits<double>::infinity();
    string best_surface;
    for (map<string, double>::iterator iter = confidences.begin(); iter != confidences.end(); ++iter)
    {
      string key = iter->first;
      double value = iter->second;
      if (value > highest)
      {
        best_surface = key;
        highest = value;
      }
    }

    // search for the highest confidence
    feedback.message = "Searching " + best_surface;
    cout << feedback.message << endl;
    as_.publishFeedback(feedback);

    // perform a higher level search request
    interactive_world_msgs::DriveAndSearchGoal search_goal;
    search_goal.item = item;
    search_goal.surface = best_surface;
    search_ac_.sendGoal(search_goal);
    bool completed = search_ac_.waitForResult(ac_wait_time_);
    bool succeeded = (search_ac_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED);
    bool success = search_ac_.getResult()->success;
    if (!completed || !succeeded || !success)
    {
      feedback.message = "Object not found on " + search_goal.surface;
      cout << feedback.message << endl;
      as_.publishFeedback(feedback);
    } else
    {
      // TODO object found
      cout << "FOUND THE OBJECT" << endl;
    }

    confidences.erase(best_surface);
  }

  // success
  as_.setSucceeded(result, "Object search failed.");
}


text:
//  Unit test for boost::lexical_cast.
//
//  See http://www.boost.org for most recent version, including documentation.
//
//  Copyright Terje Sletteb and Kevlin Henney, 2005.
//  Copyright Alexander Nasonov, 2006.
//  Copyright Antony Polukhin, 2011-2019.
//
//  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).
//
// Note: The unit test no longer compile on MSVC 6, but lexical_cast itself works for it.

//
// We need this #define before any #includes: otherwise msvc will emit warnings
// deep within std::string, resulting from our (perfectly legal) use of basic_string
// with a custom traits class:
//
#define _SCL_SECURE_NO_WARNINGS

#include <boost/config.hpp>

#if defined(__INTEL_COMPILER)
#pragma warning(disable: 193 383 488 981 1418 1419)
#elif defined(BOOST_MSVC)
#pragma warning(disable: 4097 4100 4121 4127 4146 4244 4245 4511 4512 4701 4800)
#endif

#include <boost/lexical_cast.hpp>

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

#include <boost/type_traits/integral_promotion.hpp>
#include <boost/type_traits/make_unsigned.hpp>
#include <string>
#include <vector>
#include <memory>

#if (defined(BOOST_HAS_LONG_LONG) || defined(BOOST_HAS_MS_INT64)) \
    && !(defined(BOOST_MSVC) && BOOST_MSVC < 1300)
#define LCAST_TEST_LONGLONG
#endif

#if defined(BOOST_NO_STRINGSTREAM) || defined(BOOST_NO_STD_WSTRING)
#define BOOST_LCAST_NO_WCHAR_T
#endif

// Test all 65536 values if true:
bool const lcast_test_small_integral_types_completely = false;

// lcast_integral_test_counter: use when testing all values of an integral
// types is not possible. Max. portable value is 32767.
int const lcast_integral_test_counter=500;

using namespace boost;

void test_conversion_from_to_short();
void test_conversion_from_to_ushort();
void test_conversion_from_to_int();
void test_conversion_from_to_uint();
void test_conversion_from_to_long();
void test_conversion_from_to_ulong();
void test_conversion_from_to_intmax_t();
void test_conversion_from_to_uintmax_t();
#ifdef LCAST_TEST_LONGLONG
void test_conversion_from_to_longlong();
void test_conversion_from_to_ulonglong();
#endif
#ifdef BOOST_HAS_INT128
void test_conversion_from_to_int128();
void test_conversion_from_to_uint128();
#endif
void test_integral_conversions_on_min_max();

unit_test::test_suite *init_unit_test_suite(int, char *[])
{
    unit_test::test_suite *suite =
        BOOST_TEST_SUITE("lexical_cast unit test on integral types");

    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_short));
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_ushort));
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_int));
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_uint));
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_long));
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_ulong));
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_intmax_t));
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_uintmax_t));
#ifdef LCAST_TEST_LONGLONG
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_longlong));
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_ulonglong));
#endif
#ifdef BOOST_HAS_INT128
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_int128));
    suite->add(BOOST_TEST_CASE(&test_conversion_from_to_uint128));
#endif
    suite->add(BOOST_TEST_CASE(&test_integral_conversions_on_min_max));

    return suite;
}

template<class T, class CharT>
void test_conversion_from_integral_to_char(CharT zero)
{
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(0)) == zero + 0);
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(1)) == zero + 1);
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(2)) == zero + 2);
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(3)) == zero + 3);
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(4)) == zero + 4);
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(5)) == zero + 5);
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(6)) == zero + 6);
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(7)) == zero + 7);
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(8)) == zero + 8);
    BOOST_CHECK(lexical_cast<CharT>(static_cast<T>(9)) == zero + 9);

    BOOST_CHECK_THROW(lexical_cast<CharT>(static_cast<T>(10)), bad_lexical_cast);

    T t = (std::numeric_limits<T>::max)();
    BOOST_CHECK_THROW(lexical_cast<CharT>(t), bad_lexical_cast);
}

template<class T, class CharT>
void test_conversion_from_char_to_integral(CharT zero)
{
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 0)) == static_cast<T>(0) );
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 1)) == static_cast<T>(1) );
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 2)) == static_cast<T>(2) );
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 3)) == static_cast<T>(3) );
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 4)) == static_cast<T>(4) );
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 5)) == static_cast<T>(5) );
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 6)) == static_cast<T>(6) );
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 7)) == static_cast<T>(7) );
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 8)) == static_cast<T>(8) );
    BOOST_CHECK(lexical_cast<T>( static_cast<CharT>(zero + 9)) == static_cast<T>(9) );

    BOOST_CHECK_THROW(lexical_cast<T>( static_cast<CharT>(zero + 10)), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>( static_cast<CharT>(zero - 1)), bad_lexical_cast);
}

template<class T>
void test_conversion_from_integral_to_integral()
{
    T t = 0;
    BOOST_CHECK(lexical_cast<T>(t) == t);

    // Next two variables are used to suppress warnings.
    int st = 32767; unsigned int ut = st;
    t = st;
    BOOST_CHECK(lexical_cast<short>(t) == st);
    BOOST_CHECK(lexical_cast<unsigned short>(t) == ut);
    BOOST_CHECK(lexical_cast<int>(t) == st);
    BOOST_CHECK(lexical_cast<unsigned int>(t) == ut);
    BOOST_CHECK(lexical_cast<long>(t) == st);
    BOOST_CHECK(lexical_cast<unsigned long>(t) == ut);

    t = (std::numeric_limits<T>::max)();
    BOOST_CHECK(lexical_cast<T>(t) == t);

    t = (std::numeric_limits<T>::min)();
    BOOST_CHECK(lexical_cast<T>(t) == t);
}

// Replace "-,999" with "-999".
template<class CharT>
std::basic_string<CharT> to_str_gcc_workaround(std::basic_string<CharT> str)
{
    std::locale loc;
    std::numpunct<CharT> const& np = BOOST_USE_FACET(std::numpunct<CharT>, loc);
    std::ctype<CharT> const& ct = BOOST_USE_FACET(std::ctype<CharT>, loc);

    if(np.grouping().empty())
        return str;

    CharT prefix[3] = { ct.widen('-'), np.thousands_sep(), CharT() };

    if(str.find(prefix) != 0)
        return str;

    prefix[1] = CharT();
    str.replace(0, 2, prefix);
    return str;
}

template<class CharT, class T>
std::basic_string<CharT> to_str(T t)
{
    std::basic_ostringstream<CharT> o;
    o << t;
    return to_str_gcc_workaround(o.str());
}

template<class T, class CharT>
void test_conversion_from_integral_to_string(CharT)
{
    typedef std::numeric_limits<T> limits;
    typedef std::basic_string<CharT> string_type;

    T t;

    t = (limits::min)();
    BOOST_CHECK(lexical_cast<string_type>(t) == to_str<CharT>(t));

    t = (limits::max)();
    BOOST_CHECK(lexical_cast<string_type>(t) == to_str<CharT>(t));

    if(limits::digits <= 16 && lcast_test_small_integral_types_completely)
        // min and max have already been tested.
        for(t = 1 + (limits::min)(); t != (limits::max)(); ++t)
            BOOST_CHECK(lexical_cast<string_type>(t) == to_str<CharT>(t));
    else
    {
        T const min_val = (limits::min)();
        T const max_val = (limits::max)();
        T const half_max_val = max_val / 2;
        T const cnt = lcast_integral_test_counter; // to suppress warnings
        unsigned int const counter = cnt < half_max_val ? cnt : half_max_val;

        unsigned int i;

        // Test values around min:
        t = min_val;
        for(i = 0; i < counter; ++i, ++t)
            BOOST_CHECK(lexical_cast<string_type>(t) == to_str<CharT>(t));

        // Test values around max:
        t = max_val;
        for(i = 0; i < counter; ++i, --t)
            BOOST_CHECK(lexical_cast<string_type>(t) == to_str<CharT>(t));

        // Test values around zero:
        if(limits::is_signed)
            for(t = static_cast<T>(-counter); t < static_cast<T>(counter); ++t)
                BOOST_CHECK(lexical_cast<string_type>(t) == to_str<CharT>(t));

        // Test values around 100, 1000, 10000, ...
        T ten_power = 100;
        for(int e = 2; e < limits::digits10; ++e, ten_power *= 10)
        {
            // ten_power + 100 probably never overflows
            for(t = ten_power - 100; t != ten_power + 100; ++t)
                BOOST_CHECK(lexical_cast<string_type>(t) == to_str<CharT>(t));
        }
    }
}

template<class T, class CharT>
void test_conversion_from_string_to_integral(CharT)
{
    typedef std::numeric_limits<T> limits;
    typedef std::basic_string<CharT> string_type;

    string_type s;
    string_type const zero = to_str<CharT>(0);
    string_type const nine = to_str<CharT>(9);
    T const min_val = (limits::min)();
    T const max_val = (limits::max)();

    s = to_str<CharT>(min_val);
    BOOST_CHECK_EQUAL(lexical_cast<T>(s), min_val);
    if(limits::is_signed)
    {
        BOOST_CHECK_THROW(lexical_cast<T>(s + zero), bad_lexical_cast);
        BOOST_CHECK_THROW(lexical_cast<T>(s + nine), bad_lexical_cast);
    }

    s = to_str<CharT>(max_val);
    BOOST_CHECK_EQUAL(lexical_cast<T>(s), max_val);
    {
        BOOST_CHECK_THROW(lexical_cast<T>(s + zero), bad_lexical_cast);
        BOOST_CHECK_THROW(lexical_cast<T>(s + nine), bad_lexical_cast);

        s = to_str<CharT>(max_val);
        for (int i =1; i <=10; ++i) {
            s[s.size()-1] += 1;
            BOOST_CHECK_THROW(lexical_cast<T>( s ), bad_lexical_cast);
        }

        s = to_str<CharT>(max_val);
        std::locale loc;
        typedef std::numpunct<char> numpunct;
        if ( BOOST_USE_FACET(numpunct, loc).grouping().empty() ) {
            // Following tests work well for locale C
            BOOST_CHECK_EQUAL(lexical_cast<T>(to_str<CharT>(0)+s), max_val);
            BOOST_CHECK_EQUAL(lexical_cast<T>(to_str<CharT>(0)+to_str<CharT>(0)+s), max_val);
            BOOST_CHECK_EQUAL(lexical_cast<T>(to_str<CharT>(0)+to_str<CharT>(0)+to_str<CharT>(0)+s), max_val);
        }

        for (int i =1; i <=256; ++i) {
            BOOST_CHECK_THROW(lexical_cast<T>( to_str<CharT>(i)+s ), bad_lexical_cast);
        }

        typedef BOOST_DEDUCED_TYPENAME boost::integral_promotion<T>::type promoted;
        if ( !(boost::is_same<T, promoted>::value) )
        {
            promoted prom = max_val;
            s = to_str<CharT>(max_val);
            for (int i =1; i <=256; ++i) {
                BOOST_CHECK_THROW(lexical_cast<T>( to_str<CharT>(prom+i) ), bad_lexical_cast);
                BOOST_CHECK_THROW(lexical_cast<T>( to_str<CharT>(i)+s ), bad_lexical_cast);
            }
        }
    }

    if(limits::digits <= 16 && lcast_test_small_integral_types_completely)
        // min and max have already been tested.
        for(T t = 1 + min_val; t != max_val; ++t)
            BOOST_CHECK(lexical_cast<T>(to_str<CharT>(t)) == t);
    else
    {
        T const half_max_val = max_val / 2;
        T const cnt = lcast_integral_test_counter; // to suppress warnings
        unsigned int const counter = cnt < half_max_val ? cnt : half_max_val;

        T t;
        unsigned int i;

        // Test values around min:
        t = min_val;
        for(i = 0; i < counter; ++i, ++t)
            BOOST_CHECK(lexical_cast<T>(to_str<CharT>(t)) == t);

        // Test values around max:
        t = max_val;
        for(i = 0; i < counter; ++i, --t)
            BOOST_CHECK(lexical_cast<T>(to_str<CharT>(t)) == t);

        // Test values around zero:
        if(limits::is_signed)
            for(t = static_cast<T>(-counter); t < static_cast<T>(counter); ++t)
                BOOST_CHECK(lexical_cast<T>(to_str<CharT>(t)) == t);

        // Test values around 100, 1000, 10000, ...
        T ten_power = 100;
        for(int e = 2; e < limits::digits10; ++e, ten_power *= 10)
        {
            // ten_power + 100 probably never overflows
            for(t = ten_power - 100; t != ten_power + 100; ++t)
                BOOST_CHECK(lexical_cast<T>(to_str<CharT>(t)) == t);
        }
    }
}

template<class T>
void test_conversion_from_to_integral_for_locale()
{
    std::locale current_locale;
    typedef std::numpunct<char> numpunct;
    numpunct const& np = BOOST_USE_FACET(numpunct, current_locale);
    if ( !np.grouping().empty() )
    {
        BOOST_CHECK_THROW(
                lexical_cast<T>( std::string("100") + np.thousands_sep() + np.thousands_sep() + "0" )
                , bad_lexical_cast);
        BOOST_CHECK_THROW(lexical_cast<T>( std::string("100") + np.thousands_sep() ), bad_lexical_cast);
        BOOST_CHECK_THROW(lexical_cast<T>( np.thousands_sep() + std::string("100") ), bad_lexical_cast);

        // Exception must not be thrown, when we are using no separators at all
        BOOST_CHECK( lexical_cast<T>("30000") == static_cast<T>(30000) );
    }

    test_conversion_from_integral_to_integral<T>();

    // This is a part of test_conversion_from_integral_to_string<T>('0') method,
    // but with BOOST_CHECK_EQUAL instead of BOOST_CHECK. It is required to see
    // what is produced by the to_str<char>(t) method in situations when result
    // is different. BOOST_CHECK does not work with wchar_t.
    typedef std::numeric_limits<T> limits;
    T t = (limits::min)();
    BOOST_CHECK_EQUAL(lexical_cast<std::string>(t), to_str<char>(t));

    test_conversion_from_integral_to_string<T>('0');
    test_conversion_from_string_to_integral<T>('0');
#if !defined(BOOST_LCAST_NO_WCHAR_T)
    if (lexical_cast<std::wstring>(t) != to_str<wchar_t>(t)) {
        // Something went wrong, and now we are attempting to find and print the
        // difference.
        std::wstring wstr = to_str<wchar_t>(t);
        std::string lcast_str = lexical_cast<std::string>(t);
        std::string str;
        str.reserve(wstr.size());
        for (std::size_t i = 0; i < wstr.size(); ++i) {
            str.push_back(static_cast<char>(wstr[i]));
        }

        BOOST_CHECK_EQUAL(lcast_str.length(), lexical_cast<std::wstring>(t).length());
        BOOST_CHECK_EQUAL(to_str<char>(t), str);
        BOOST_CHECK_EQUAL(lcast_str, str);
    }

    test_conversion_from_integral_to_string<T>(L'0');
    test_conversion_from_string_to_integral<T>(L'0');
#endif
}

struct restore_oldloc
{
    std::locale oldloc;
    ~restore_oldloc() { std::locale::global(oldloc); }
};

template<class T>
void test_conversion_from_to_integral_minimal()
{
    char const zero = '0';
    signed char const szero = '0';
    unsigned char const uzero = '0';
    test_conversion_from_integral_to_char<T>(zero);
    test_conversion_from_char_to_integral<T>(zero);
    test_conversion_from_integral_to_char<T>(szero);
    test_conversion_from_char_to_integral<T>(szero);
    test_conversion_from_integral_to_char<T>(uzero);
    test_conversion_from_char_to_integral<T>(uzero);
#if !defined(BOOST_LCAST_NO_WCHAR_T) && !defined(BOOST_NO_INTRINSIC_WCHAR_T)
    wchar_t const wzero = L'0';
    test_conversion_from_integral_to_char<T>(wzero);
    test_conversion_from_char_to_integral<T>(wzero);
#endif
#if !defined(BOOST_NO_CXX11_CHAR16_T) && !defined(BOOST_NO_CXX11_UNICODE_LITERALS) && !defined(_LIBCPP_VERSION) && !defined(BOOST_MSVC)
    char16_t const u16zero = u'0';
    test_conversion_from_integral_to_char<T>(u16zero);
    test_conversion_from_char_to_integral<T>(u16zero);
#endif
#if !defined(BOOST_NO_CXX11_CHAR32_T) && !defined(BOOST_NO_CXX11_UNICODE_LITERALS) && !defined(_LIBCPP_VERSION) && !defined(BOOST_MSVC)
    char32_t const u32zero = u'0';
    test_conversion_from_integral_to_char<T>(u32zero);
    test_conversion_from_char_to_integral<T>(u32zero);
#endif

    BOOST_CHECK(lexical_cast<T>("-1") == static_cast<T>(-1));
    BOOST_CHECK(lexical_cast<T>("-9") == static_cast<T>(-9));
    BOOST_CHECK(lexical_cast<T>(-1) == static_cast<T>(-1));
    BOOST_CHECK(lexical_cast<T>(-9) == static_cast<T>(-9));

    BOOST_CHECK_THROW(lexical_cast<T>("-1.0"), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>("-9.0"), bad_lexical_cast);
    BOOST_CHECK(lexical_cast<T>(-1.0) == static_cast<T>(-1));
    BOOST_CHECK(lexical_cast<T>(-9.0) == static_cast<T>(-9));

    BOOST_CHECK(lexical_cast<T>(static_cast<T>(1)) == static_cast<T>(1));
    BOOST_CHECK(lexical_cast<T>(static_cast<T>(9)) == static_cast<T>(9));
    BOOST_CHECK_THROW(lexical_cast<T>(1.1f), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>(1.1), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>(1.1L), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>(1.0001f), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>(1.0001), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>(1.0001L), bad_lexical_cast);

    BOOST_CHECK(lexical_cast<T>("+1") == static_cast<T>(1) );
    BOOST_CHECK(lexical_cast<T>("+9") == static_cast<T>(9) );
    BOOST_CHECK(lexical_cast<T>("+10") == static_cast<T>(10) );
    BOOST_CHECK(lexical_cast<T>("+90") == static_cast<T>(90) );
    BOOST_CHECK_THROW(lexical_cast<T>("++1"), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>("-+9"), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>("--1"), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<T>("+-9"), bad_lexical_cast);
    // test_conversion_from_to_integral_for_locale

    // Overflow test case from David W. Birdsall
    std::string must_owerflow_str =             (sizeof(T) < 16 ?  "160000000000000000000" :  "1600000000000000000000000000000000000000");
    std::string must_owerflow_negative_str =    (sizeof(T) < 16 ? "-160000000000000000000" : "-1600000000000000000000000000000000000000");
    for (int i = 0; i < 15; ++i) {
        BOOST_CHECK_THROW(lexical_cast<T>(must_owerflow_str), bad_lexical_cast);
        BOOST_CHECK_THROW(lexical_cast<T>(must_owerflow_negative_str), bad_lexical_cast);

        must_owerflow_str += '0';
        must_owerflow_negative_str += '0';
    }
}

template<class T>
void test_conversion_from_to_integral()
{
    test_conversion_from_to_integral_minimal<T>();
    typedef std::numpunct<char> numpunct;

    restore_oldloc guard;
    std::locale const& oldloc = guard.oldloc;

    std::string grouping1 = BOOST_USE_FACET(numpunct, oldloc).grouping();
    std::string grouping2(grouping1);

    test_conversion_from_to_integral_for_locale<T>();

    try
    {
        std::locale newloc("");
        std::locale::global(newloc);

        grouping2 = BOOST_USE_FACET(numpunct, newloc).grouping();
    }
    catch(std::exception const& ex)
    {
        std::string msg("Failed to set system locale: ");
        msg += ex.what();
        BOOST_TEST_MESSAGE(msg);
    }

    if(grouping1 != grouping2)
        test_conversion_from_to_integral_for_locale<T>();

    if(grouping1.empty() && grouping2.empty())
        BOOST_TEST_MESSAGE("Formatting with thousands_sep has not been tested");
}

void test_conversion_from_to_short()
{
    test_conversion_from_to_integral<short>();
}

void test_conversion_from_to_ushort()
{
    test_conversion_from_to_integral<unsigned short>();
}

void test_conversion_from_to_int()
{
    test_conversion_from_to_integral<int>();
}

void test_conversion_from_to_uint()
{
    test_conversion_from_to_integral<unsigned int>();
}

void test_conversion_from_to_long()
{
    test_conversion_from_to_integral<long>();
}

void test_conversion_from_to_ulong()
{
    test_conversion_from_to_integral<unsigned long>();
}

void test_conversion_from_to_intmax_t()
{
    test_conversion_from_to_integral<boost::intmax_t>();
}

void test_conversion_from_to_uintmax_t()
{
    test_conversion_from_to_integral<boost::uintmax_t>();
}

#if defined(BOOST_HAS_LONG_LONG)

void test_conversion_from_to_longlong()
{
    test_conversion_from_to_integral<boost::long_long_type>();
}

void test_conversion_from_to_ulonglong()
{
    test_conversion_from_to_integral<boost::ulong_long_type>();
}

#elif defined(BOOST_HAS_MS_INT64)

void test_conversion_from_to_longlong()
{
    test_conversion_from_to_integral<__int64>();
}

void test_conversion_from_to_ulonglong()
{
    test_conversion_from_to_integral<unsigned __int64>();
}

#endif

#ifdef BOOST_HAS_INT128

template <bool Specialized, class T>
struct test_if_specialized {
    static void test() {}
};

template <class T>
struct test_if_specialized<true, T> {
    static void test() {
        test_conversion_from_to_integral_minimal<T>();
    }
};

void test_conversion_from_to_int128()
{
    test_if_specialized<
        std::numeric_limits<boost::int128_type>::is_specialized,
        boost::int128_type
    >::test();
}

void test_conversion_from_to_uint128()
{
    test_if_specialized<
        std::numeric_limits<boost::int128_type>::is_specialized,
        boost::uint128_type
    >::test();
}
#endif

template <typename SignedT>
void test_integral_conversions_on_min_max_impl()
{
    typedef SignedT signed_t;
    typedef BOOST_DEDUCED_TYPENAME boost::make_unsigned<signed_t>::type unsigned_t;

    typedef std::numeric_limits<signed_t> s_limits;
    typedef std::numeric_limits<unsigned_t> uns_limits;

    BOOST_CHECK_EQUAL(lexical_cast<unsigned_t>((uns_limits::max)()), (uns_limits::max)());
    BOOST_CHECK_EQUAL(lexical_cast<unsigned_t>((uns_limits::min)()), (uns_limits::min)());

    BOOST_CHECK_EQUAL(lexical_cast<signed_t>((s_limits::max)()), (s_limits::max)());
    BOOST_CHECK_EQUAL(lexical_cast<signed_t>((uns_limits::min)()), static_cast<signed_t>((uns_limits::min)()));

    BOOST_CHECK_EQUAL(lexical_cast<unsigned_t>((s_limits::max)()), static_cast<unsigned_t>((s_limits::max)()));
    BOOST_CHECK_EQUAL(lexical_cast<unsigned_t>((s_limits::min)()), static_cast<unsigned_t>((s_limits::min)()));
}

void test_integral_conversions_on_min_max()
{
    test_integral_conversions_on_min_max_impl<int>();
    test_integral_conversions_on_min_max_impl<short>();

#ifdef _MSC_VER
    test_integral_conversions_on_min_max_impl<long int>();

#if defined(BOOST_HAS_LONG_LONG)
    test_integral_conversions_on_min_max_impl<boost::long_long_type>();
#elif defined(BOOST_HAS_MS_INT64)
    test_integral_conversions_on_min_max_impl<__int64>();
#endif

#ifdef BOOST_HAS_INT128
    test_integral_conversions_on_min_max_impl<boost::int128_type>();
#endif
#endif

}