text:
#include <iostream>
#include <string.h>
#include <boost/tokenizer.hpp>
#include <vector>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <algorithm>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>

using namespace std;
using namespace boost;

class Connector
{
    public:
        Connector();
        ~Connector();
        bool run;
        int type;
        bool runNext();
        bool precedence;

};

Connector::Connector()
{
    // the semicolon connector allows the next command to be execute always
    run = true;
    type = 0; // semicolon connector set to 0
    precedence = false;
}

Connector::~Connector()
{
}
bool Connector::runNext()
{
    if (type == 1) // && connector
    {
        if (!run) // if the first command doesn't succeed  it wont run the next command
        {
            return false;
        }
    }
    else if (type == 2) // || connector
    {
        if (run) // if the first command succeed it wont run the next command
        {
            return false;
        }
    }
    return true;
}
void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag);
void commandifier(string command, string argument, Connector& connect, string flag);
void test_function(string command, string & flag, string argument, Connector& connect);
int main()
{
    string flag;
    string str;
    string command;
    string argument;
    Connector connect;
    char hostname[100];
    int position = 0;
    while (true)
    {
        printf("%s",getlogin()); // returns string containing name of user logged in
        gethostname(hostname, sizeof hostname); // returns the standard host name for the current machine
        cout << "@" << hostname << "$ ";
        getline(cin, str);
        if (str == "exit") // special command of exit
        {
            break;
        }
        vector<string> instruction; // vector of strings
        typedef tokenizer<boost::char_separator<char> > Tok;
        char_separator<char> sep; // default constructed
        Tok tok(str, sep);;
        for (Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) // parses the input into a command and argument
        {
	    instruction.push_back(*tok_iter);

	}
	if (instruction[0] != "#") // checks for user input except for comments (#)
        {
            parseinator(instruction, command, argument, position, connect, flag); // parses the input into a command and argument
            commandifier(command, argument, connect, flag); // runs a command with a given argument
            command = "";
            argument = "";
            int vector_size = instruction.size();
            for (; position < vector_size;) // run until the end of the instruction
            {
                parseinator(instruction, command, argument, position, connect, flag);
                if (connect.runNext() && command != "") // checks connector to see if the next command should be ran
	        {
                    commandifier(command, argument, connect, flag);
                }
	        else
	        {
	            while(connect.precedence && position < vector_size)
		        {
		            if(instruction[position] == ")")
		            {
		                connect.precedence = false;
		            }
		            position++;
		        }

	            command = "";
	        }
	        command = "";
                argument = "";
            }
            position = 0;
        }
    }
    return 0;
}
void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag)
{
    if (input[position] == "&") // check if string is equal to & connector
    {
        connect.type = 1; // set & connector to 1
        position += 2; // +=2 in order to take && connect
    }
    if (input[position] == "|")
    {
        connect.type = 2; // set | connector to 2
        position += 2; // +=2 in order to take || connector
    }
    if (input[position] == ";")
    {
        connect.type = 0; // set ; connector to 0
        position ++;
    }
    if (input[position] == "(")
    {
        connect.precedence = true;
        position++;
    }
    if (input[position] != "#")
    {
        command = input[position];
        position++;
    }
    if (command == "test" || command == "[")
    {
        if(input[position] == "-")
        {
            position++;
	    if (input[position] == "f")
            {
		flag = "-f";
		position++;
	    }
	    else if (input[position] == "d")
	    {
		flag = "-d";
		position++;
	    }
	    else // DEFAULT E
	    {
		flag = "-e";
		position++;
            }
        }
    }

    int input_size = input.size();
    for (; position < input_size; position++)
    {
        if (input[position] == ")")
        {
            connect.precedence = false;
            position++;
            break;
        }
        if(command == "echo" && input[position] == "\"")
        {
            position++;
            while(input[position] != "\"" && position <= input_size)
            {

                argument += input[position];
                if(!isalnum(input[position].at(0)) && !isalnum(input[position+1].at(0)))
                {

                }
                else
		{
                    argument += " ";
                }
		position++;
            }
            position++;
            break;
        }
        if (input[position] == "#")
        {
            position = input.size();
            break;
        }
        if (input[position] == "&" || input[position] == "|" || input[position] == ";")
	    {
            break;
    	}

        argument += input[position];
        int input_size1 = input.size();
        if (position+1 != input_size1 && command == "echo")
	{
	    //adds spaces when echoing
            argument += " ";
	}
    }
}
void commandifier(string command, string argument, Connector& connect, string flag)
{
    const char * const_command = command.c_str();
    char * char_command = new char[command.size()];
    const char * const_argument = argument.c_str();
    char * char_argument = new char[argument.size()];
    strcpy (char_command, const_command);
    strcpy (char_argument, const_argument);
    char * args[2]; // char pointer array that holds command, and NULL
    char * args1[3]; // char pointer array that holds command, argument, and NULL
    bool no_arg = true;
    bool failed = false;

    if(command == "test" || command == "[")
    {
	test_function(command,flag,argument,connect);
	return;
    }
    // exit command
    if(command == "exit" || argument == "exit")
    {
	exit(1);
    }

    if (argument.size() == 0) // no arguments
    {
        args[0] = char_command; // args will contain the command
        args[1] = NULL;
    }
    else
    {
	no_arg = false; // sets bool no_arg to false
	args1[0] = char_command; // args1 contains command and argument
        args1[1] = char_argument;
        args1[2] = NULL;
    }
    pid_t c_pid, pid; // data type to reporesent process ID's
    int status;
    c_pid = fork(); // create our fork

    if (c_pid < 0) // indicates the fork has fail if its less than 0
    {
        perror("fork failed");
        exit(1);
    }
    else if (c_pid == 0) // in child process
    {
 	if (no_arg) // no argument
	{
        	execvp( args[0], args); // execvp the char pointer array that holds the command only
        	if (execvp(args[0], args) == -1) // if it returns -1 it failed
                {
                    perror("execvp failed");
                    connect.run = false;
                    failed = true;
                }
		exit(3);
	}
	else // with command and argument
	{
		execvp(args1[0], args1); // execvp the char pointer array that holds the command, and argument
		if (execvp(args1[0], args1) == -1) // if it returns -1 it failed
                {
                    perror("execvp failed");
                    connect.run = false;
                    failed = true;
                }
		exit(3);
	}
    }
    else if (c_pid > 0) // parent process
    {
        if((pid = wait(&status)) < 0 )
        {
            perror("wait");
	    exit(3);

        }
        if (WIFEXITED(status))  //Evaluates to a non-zero value if status was returned for a child process that terminated normally.

        {
            if (WEXITSTATUS(status) != 0)
            {
                connect.run = false;
            }
	    else
	    {
		connect.run = true;
            }
        }
       else
        {
            connect.run = true;
        }
     }
}
void test_function(string command, string & flag, string argument, Connector& connect)
{
   char b = '[';
   char c = ']';
   argument.erase(remove(argument.begin(), argument.end(), c ), argument.end());
   argument.erase(remove(argument.begin(), argument.end(), b ), argument.end());
   const char * arg = argument.c_str();
   struct stat sb; // struct for the stat function

   if(flag == "-f")
   {
        if(stat(arg,&sb) == 0)
        {

            connect.run = true;
	    if(S_ISREG(sb.st_mode))
	    {

 		connect.run = true;

	    }
	    else
	    {

		connect.run = false;

	    }
        }
        else
        {
	    perror("stat");
            connect.run = false;
        }
   }
   else if(flag == "-d")
   {
        if(stat(arg,&sb) == 0)
        {
            connect.run = true;
            if(S_ISDIR(sb.st_mode))
            {
            	connect.run = true;

            }
            else
       	    {
             	connect.run = false;

            }
        }
        else
        {
	    perror("stat");
            connect.run = false;
        }

   }
   else
   {
	if(stat(arg,&sb) == 0)
	{
	    connect.run = true;
 	}
	else
	{
	    perror("stat");
	    connect.run = false;
	}
   }
}


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// 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)
//
// Official repository: https://github.com/cppalliance/json
//

#ifndef BOOST_JSON_IMPL_VALUE_IPP
#define BOOST_JSON_IMPL_VALUE_IPP

#include <boost/json/value.hpp>
#include <cstring>
#include <limits>
#include <new>
#include <utility>

namespace boost {
namespace json {

value::
~value()
{
    switch(kind())
    {
    case json::kind::object:
        obj_.~object();
        break;

    case json::kind::array:
        arr_.~array();
        break;

    case json::kind::string:
        str_.~string();
        break;

    case json::kind::int64:
        i64_.~int64_k();
        break;

    case json::kind::uint64:
        u64_.~uint64_k();
        break;

    case json::kind::double_:
        dub_.~double_k();
        break;

    case json::kind::bool_:
        bln_.~bool_k();
        break;

    case json::kind::null:
        nul_.~null_k();
        break;
    }
}

value::
value(pilfered<value> p) noexcept
{
    relocate(this, p.get());
    ::new(&p.get().nul_) null_k;
}

value::
value(
    value const& other,
    storage_ptr sp)
{
    switch(other.kind())
    {
    case json::kind::object:
        ::new(&obj_) object(
            other.obj_,
            detail::move(sp));
        break;

    case json::kind::array:
        ::new(&arr_) array(
            other.arr_,
            detail::move(sp));
        break;

    case json::kind::string:
        ::new(&str_) string(
            other.str_,
            detail::move(sp));
        break;

    case json::kind::int64:
        ::new(&i64_) int64_k(
            other.i64_.i,
            detail::move(sp));
        break;

    case json::kind::uint64:
        ::new(&u64_) uint64_k(
            other.u64_.u,
            detail::move(sp));
        break;

    case json::kind::double_:
        ::new(&dub_) double_k(
            other.dub_.d,
            detail::move(sp));
        break;

    case json::kind::bool_:
        ::new(&bln_) bool_k(
            other.bln_.b,
            detail::move(sp));
        break;

    case json::kind::null:
        ::new(&nul_) null_k(
            detail::move(sp));
        break;
    }
}

value::
value(value&& other) noexcept
{
    relocate(this, other);
    ::new(&other.nul_) null_k(sp_);
}

value::
value(
    value&& other,
    storage_ptr sp)
{
    switch(other.kind())
    {
    case json::kind::object:
        ::new(&obj_) object(
            detail::move(other.obj_),
            detail::move(sp));
        break;

    case json::kind::array:
        ::new(&arr_) array(
            detail::move(other.arr_),
            detail::move(sp));
        break;

    case json::kind::string:
        ::new(&str_) string(
            detail::move(other.str_),
            detail::move(sp));
        break;

    case json::kind::int64:
        ::new(&i64_) int64_k(
            other.i64_.i, detail::move(sp));
        break;

    case json::kind::uint64:
        ::new(&u64_) uint64_k(
            other.u64_.u, detail::move(sp));
        break;

    case json::kind::double_:
        ::new(&dub_) double_k(
            other.dub_.d, detail::move(sp));
        break;

    case json::kind::bool_:
        ::new(&bln_) bool_k(
            other.bln_.b, detail::move(sp));
        break;

    case json::kind::null:
        ::new(&nul_) null_k(
            detail::move(sp));
        break;
    }
}

value&
value::
operator=(value&& other)
{
    undo u(this);
    ::new(this) value(
        detail::move(other),
        u.saved.storage());
    u.commit();
    return *this;
}

value&
value::
operator=(value const& other)
{
    if(this == &other)
        return *this;

    undo u(this);
    ::new(this) value(other,
        u.saved.storage());
    u.commit();
    return *this;
}

//----------------------------------------------------------
//
// Conversion
//
//----------------------------------------------------------

value::
value(
    std::initializer_list<value_ref> init,
    storage_ptr sp)
{
    if(value_ref::maybe_object(init))
        ::new(&obj_) object(
            value_ref::make_object(
                init, std::move(sp)));
    else
        ::new(&arr_) array(
            value_ref::make_array(
                init, std::move(sp)));
}

//----------------------------------------------------------
//
// Modifiers
//
//----------------------------------------------------------

object&
value::
emplace_object() noexcept
{
    return *::new(&obj_) object(destroy());
}

array&
value::
emplace_array() noexcept
{
    return *::new(&arr_) array(destroy());
}

string&
value::
emplace_string() noexcept
{
    return *::new(&str_) string(destroy());
}

std::int64_t&
value::
emplace_int64() noexcept
{
    ::new(&i64_) int64_k(destroy());
    return i64_.i;
}

std::uint64_t&
value::
emplace_uint64() noexcept
{
    ::new(&u64_) uint64_k(destroy());
    return u64_.u;
}

double&
value::
emplace_double() noexcept
{
    ::new(&dub_) double_k(destroy());
    return dub_.d;
}

bool&
value::
emplace_bool() noexcept
{
    ::new(&bln_) bool_k(destroy());
    return bln_.b;
}

void
value::
emplace_null() noexcept
{
    ::new(&nul_) null_k(destroy());
}

void
value::
swap(value& other)
{
    if(*storage() != *other.storage())
    {
        // copy
        value temp1(
            detail::move(*this),
            other.storage());
        value temp2(
            detail::move(other),
            this->storage());
        other.~value();
        ::new(&other) value(pilfer(temp1));
        this->~value();
        ::new(this) value(pilfer(temp2));
        return;
    }

    union U
    {
        value tmp;
        U(){}
        ~U(){}
    };
    U u;
    relocate(&u.tmp, *this);
    relocate(this, other);
    relocate(&other, u.tmp);
}

//----------------------------------------------------------
//
// Accessors
//
//----------------------------------------------------------

storage_ptr
value::
destroy() noexcept
{
    switch(kind())
    {
    case json::kind::object:
    {
        auto sp = obj_.storage();
        obj_.~object();
        return sp;
    }
    case json::kind::array:
    {
        auto sp = arr_.storage();
        arr_.~array();
        return sp;
    }
    case json::kind::string:
    {
        auto sp = str_.storage();
        str_.~string();
        return sp;
    }
    case json::kind::int64:
    case json::kind::uint64:
    case json::kind::double_:
    case json::kind::bool_:
    case json::kind::null:
        break;
    }
    return std::move(sp_);
}

//----------------------------------------------------------

key_value_pair::
~key_value_pair()
{
    auto const& sp = value_.storage();
    if(sp.is_not_counted_and_deallocate_is_null())
        return;
    sp->deallocate(key_, len_ + 1, 1);
}

key_value_pair::
key_value_pair(
    key_value_pair const& other)
    : value_(other.value_)
    , key_(
        [&]
        {
            auto s = reinterpret_cast<
                char*>(value_.storage()->
                    allocate(other.len_ + 1));
            std::memcpy(s, other.key_, other.len_);
            s[other.len_] = 0;
            return s;
        }())
    , len_(other.len_)
{
}

key_value_pair::
key_value_pair::
key_value_pair(
    key_value_pair const& other,
    storage_ptr sp)
    : value_(other.value_, detail::move(sp))
    , key_(
        [&]
        {
            auto s = reinterpret_cast<
                char*>(value_.storage()->
                    allocate(other.len_ + 1));
            std::memcpy(s, other.key_, other.len_);
            s[other.len_] = 0;
            return s;
        }())
    , len_(other.len_)
{
}

//----------------------------------------------------------

} // json
} // boost

#endif

ext: ipp

max_stars_repo_name: rtobar/json

max_issues_repo_name: rtobar/json

max_forks_repo_name: rtobar/json


text:
//
// Implements iLQR (on a traditional chain) for nonlinear dynamics and cost.
//
// Arun Venkatraman (arunvenk@cs.cmu.edu)
// December 2016
//

#pragma once

#include <templated/taylor_expansion.hh>
#include <utils/debug_utils.hh>

#include <Eigen/Dense>

#include <functional>
#include <vector>

namespace ilqr
{

// Defined in templated/taylor_expansion.hh
//template<int _rows, int _cols>
//using Matrix = Eigen::Matrix<double, _rows, _cols>;
//
//template<int _rows>
//using Vector = Eigen::Matrix<double, _rows, 1>;

template<int xdim, int udim>
class iLQRSolver
{
    static_assert(xdim > 0, "State dimension should be greater than 0");
    static_assert(udim > 0, "Control dimension should be greater than 0");
public:
    using Dynamics = std::function<Vector<xdim>(const Vector<xdim> &x, const Vector<udim> &u)>;
    using Cost = std::function<double(const Vector<xdim> &x, const Vector<udim> &u, const int t)>;
    using FinalCost = std::function<double(const Vector<xdim> &x)>;

    iLQRSolver(const Dynamics &dynamics,
         const FinalCost &final_cost,
         const Cost &cost
         )
    {
        this->dynamics_ = dynamics;
        this->cost_ = cost;
        this->final_cost_ = final_cost;
    }

    // Computes the control at timestep t at xt.
    // :param alpha - Backtracking line search parameter. Setting to 1 gives regular forward pass.
    inline Vector<udim> compute_control_stepsize(const Vector<xdim> &xt,
            const int t, const double alpha) const;

    // Computes the locally-optimal iLQR solution.
    // :param x_init - Initial state from which to start the system from.
    // :param u_nominal - Initial control used for the whole sequence during
    //      the first forward pass.
    // :param mu - Levenberg-Marquardt parameter for damping the least-squares.
    //      Setting it to 0 gets the default behavior. The damping makes the
    //      state-space steps smaller over iterations.
    // :param start_alpha - The initial step size to use when solving.
    // :param cost_conv_ratio - When the cost over iterations changes by less than
    //      this ratio, then the optimization is stopped.
    // :param warm_start - Warm start the solver using the previous solution stored
    //      in the object from the last call to solve.
    // :param t_offset - The warm start time offset. The input argument T to this call
    //      of solve should be T_{last_call} - t_offset.
    //      For example, if 1, then the first timestep of the previous solution
    //      is removed.
    inline void solve(const int T, const Vector<xdim> &x_init,
            const Vector<udim> u_nominal, const double mu,
            const int max_iters = 1000, bool verbose = false,
            const double cost_convg_ratio = 1e-4, const double start_alpha = 1.0,
            const bool warm_start = false, const int t_offset = 0
            );

    // :param alpha - Backtracking line search parameter. Setting to 1 gives regular forward pass.
    inline double forward_pass(const Vector<xdim> x_init,
            std::vector<Vector<xdim>> &states, std::vector<Vector<udim>> &controls,
            const double alpha ) const;

    // Returns how many timesteps we have computed control policies for.
    inline int timesteps() const;

private:
    Dynamics dynamics_;
    Cost cost_;
    FinalCost final_cost_;

    // Feedback control gains.
    std::vector<Matrix<udim, xdim>> Ks_;
    std::vector<Vector<udim>> ks_;

    // Linearization points.
    std::vector<Vector<xdim>> xhat_;
    std::vector<Vector<udim>> uhat_;

    // Performs one timestep of the bellman backup.
    // :param t - passed to the cost runction
    // :param mu - Levenberg-Marquardt parameter
    void bellman_backup(const int t, const double mu,
        const Matrix<xdim,xdim> &Vt1, const Matrix<1,xdim> &Gt1,
        Matrix<xdim,xdim> &Vt, Matrix<1,xdim> &Gt,
        Matrix<udim,xdim> &Kt, Vector<udim> &kt);

};

} // namespace lqr

#include <templated/iLQR_impl.hh>

ext: hh


text:
#pragma once
#include <boost/asio/async_result.hpp>
#include <boost/asio/handler_type.hpp>
#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
#include <future>
#include <memory>

/**
 * This is almost a 1:1 copy of Boost's use_std_future, with std::future switched out for boost::future.
 */

namespace cmakeserver {

	/// Class used to specify that an asynchronous operation should return a future.
	/**
	 * The use_boost_future_t class is used to indicate that an asynchronous operation
	 * should return a boost::future object. A use_boost_future_t object may be passed as a
	 * handler to an asynchronous operation, typically using the special value @c
	 * use_boost_future. For example:
	 *
	 * @code boost::future<std::size_t> my_future
	 *   = my_socket.async_read_some(my_buffer, boost::asio::use_boost_future); @endcode
	 *
	 * The initiating function (async_read_some in the above example) returns a
	 * future that will receive the result of the operation. If the operation
	 * completes with an error_code indicating failure, it is converted into a
	 * system_error and passed back to the caller via the future.
	 */
	template <typename Allocator = std::allocator<void>>
	class use_boost_future_t {
		public:
		/// The allocator type. The allocator is used when constructing the
		/// @c std::promise object for a given asynchronous operation.
		using allocator_type = Allocator;

		/// Construct using default-constructed allocator.
		constexpr use_boost_future_t() = default;

		/// Construct using specified allocator.
		explicit use_boost_future_t(Allocator const &allocator)
		    : allocator_(allocator) {
		}

		/// Specify an alternate allocator.
		template <typename OtherAllocator>
		use_boost_future_t<OtherAllocator> operator[](OtherAllocator const &allocator) const {
			return use_boost_future_t<OtherAllocator>(allocator);
		}

		/// Obtain allocator.
		allocator_type get_allocator() const {
			return allocator_;
		}

		private:
		Allocator allocator_;
	};

/// A special value, similar to std::nothrow.
/**
 * See the documentation for boost::asio::use_future_t for a usage example.
 */
#ifdef _MSC_VER
	__declspec(selectany) use_boost_future_t<> use_boost_future;
#else
	constexpr use_boost_future_t<> use_boost_future;
#endif

	namespace detail {
		// Completion handler to adapt a promise as a completion handler.
		template <typename T>
		class promise_handler {
			public:
			// Construct from use_future special value.
			template <typename Alloc>
			promise_handler(use_boost_future_t<Alloc> uf)
			    : promise_(std::allocate_shared<boost::promise<T>>(
			          typename std::allocator_traits<Alloc>::template rebind_alloc<char>(uf.get_allocator()),
			          std::allocator_arg,
			          typename std::allocator_traits<Alloc>::template rebind_alloc<char>(uf.get_allocator()))) {
			}

			void operator()(T t) {
				promise_->set_value(t);
			}

			void operator()(const boost::system::error_code &ec, T t) {
				if(ec) {
					promise_->set_exception(std::make_exception_ptr(boost::system::system_error(ec)));
				} else {
					promise_->set_value(t);
				}
			}

			// private:
			std::shared_ptr<boost::promise<T>> promise_;
		};

		// Completion handler to adapt a void promise as a completion handler.
		template <>
		class promise_handler<void> {
			public:
			// Construct from use_future special value. Used during rebinding.
			template <typename Alloc>
			promise_handler(use_boost_future_t<Alloc> uf)
			    : promise_(std::allocate_shared<boost::promise<void>>(
			          typename std::allocator_traits<Alloc>::template rebind_alloc<char>(uf.get_allocator()),
			          std::allocator_arg,
			          typename std::allocator_traits<Alloc>::template rebind_alloc<char>(uf.get_allocator()))) {
			}

			void operator()() {
				promise_->set_value();
			}

			void operator()(const boost::system::error_code &ec) {
				if(ec) {
					promise_->set_exception(std::make_exception_ptr(boost::system::system_error(ec)));
				} else {
					promise_->set_value();
				}
			}

			// private:
			std::shared_ptr<boost::promise<void>> promise_;
		};

		// Ensure any exceptions thrown from the handler are propagated back to the
		// caller via the future.
		template <typename Function, typename T>
		void asio_handler_invoke(Function f, promise_handler<T> *h) {
			std::shared_ptr<boost::promise<T>> p(h->promise_);
			try {
				f();
			} catch(...) { p->set_exception(std::current_exception()); }
		}

	}    // namespace detail
}    // namespace cmakeserver

namespace boost::asio {
	// Handler traits specialization for promise_handler.
	template <typename T>
	class async_result<cmakeserver::detail::promise_handler<T>> {
		public:
		// The initiating function will return a future.
		using type = boost::future<T>;

		// Constructor creates a new promise for the async operation, and obtains the
		// corresponding future.
		explicit async_result(cmakeserver::detail::promise_handler<T> &h) {
			value_ = h.promise_->get_future();
		}

		// Obtain the future to be returned from the initiating function.
		type get() {
			return std::move(value_);
		}

		private:
		type value_;
	};

	// Handler type specialisation for use_future.
	template <typename Allocator, typename ReturnType>
	struct handler_type<cmakeserver::use_boost_future_t<Allocator>, ReturnType()> {
		using type = cmakeserver::detail::promise_handler<void>;
	};

	// Handler type specialisation for use_future.
	template <typename Allocator, typename ReturnType, typename Arg1>
	struct handler_type<cmakeserver::use_boost_future_t<Allocator>, ReturnType(Arg1)> {
		using type = cmakeserver::detail::promise_handler<Arg1>;
	};

	// Handler type specialisation for use_future.
	template <typename Allocator, typename ReturnType>
	struct handler_type<cmakeserver::use_boost_future_t<Allocator>, ReturnType(boost::system::error_code)> {
		using type = cmakeserver::detail::promise_handler<void>;
	};

	// Handler type specialisation for use_future.
	template <typename Allocator, typename ReturnType, typename Arg2>
	struct handler_type<cmakeserver::use_boost_future_t<Allocator>, ReturnType(boost::system::error_code, Arg2)> {
		using type = cmakeserver::detail::promise_handler<Arg2>;
	};
}    // namespace boost::asio

ext: hpp

max_stars_repo_name: mmha/libcmakeserver

max_issues_repo_name: mmha/libcmakeserver

max_forks_repo_name: mmha/libcmakeserver


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

#include <boost/hana/assert.hpp>
#include <boost/hana/config.hpp>

#include <test/cnumeric.hpp>
using namespace boost::hana;

template <int ...>
auto constant_true = test::cnumeric<bool, true>;

template <int ...>
BOOST_HANA_CONSTEXPR_LAMBDA bool constexpr_true = []{ return true; }();

template <int ...>
bool runtime_true = true;

BOOST_HANA_CONSTANT_ASSERT(constant_true<>);
BOOST_HANA_CONSTANT_ASSERT(constant_true<0, 1>);

BOOST_HANA_CONSTANT_CHECK(constant_true<>);
BOOST_HANA_CONSTANT_CHECK(constant_true<0, 1>);

int main() {
    BOOST_HANA_CONSTEXPR_ASSERT(constexpr_true<>);
    BOOST_HANA_CONSTEXPR_ASSERT(constexpr_true<0, 1>);

    BOOST_HANA_RUNTIME_ASSERT(runtime_true<>);
    BOOST_HANA_RUNTIME_ASSERT(runtime_true<0, 1>);

    BOOST_HANA_ASSERT(runtime_true<>);
    BOOST_HANA_ASSERT(runtime_true<0, 1>);
    BOOST_HANA_ASSERT(constant_true<>);
    BOOST_HANA_ASSERT(constant_true<0, 1>);

    BOOST_HANA_CONSTEXPR_CHECK(constexpr_true<>);
    BOOST_HANA_CONSTEXPR_CHECK(constexpr_true<0, 1>);

    BOOST_HANA_RUNTIME_CHECK(runtime_true<>);
    BOOST_HANA_RUNTIME_CHECK(runtime_true<0, 1>);

    BOOST_HANA_CHECK(runtime_true<>);
    BOOST_HANA_CHECK(runtime_true<0, 1>);
    BOOST_HANA_CHECK(constant_true<>);
    BOOST_HANA_CHECK(constant_true<0, 1>);

    // make sure we can put lambdas in the assertions
    {
        BOOST_HANA_CONSTANT_ASSERT([]{ return constant_true<>; }());
        BOOST_HANA_CONSTEXPR_ASSERT([]{ return constexpr_true<>; }());
        BOOST_HANA_RUNTIME_ASSERT([]{ return runtime_true<>; }());
        BOOST_HANA_ASSERT([] { return constant_true<>; }());
        BOOST_HANA_ASSERT([] { return runtime_true<>; }());

        BOOST_HANA_CONSTANT_CHECK([]{ return constant_true<>; }());
        BOOST_HANA_CONSTEXPR_CHECK([]{ return constexpr_true<>; }());
        BOOST_HANA_RUNTIME_CHECK([]{ return runtime_true<>; }());
        BOOST_HANA_CHECK([] { return constant_true<>; }());
        BOOST_HANA_CHECK([] { return runtime_true<>; }());
    }
}

ext: cpp

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
#ifndef GRAPHLAB_UTIL_HOPSCOTCH_TABLE_HPP
#define GRAPHLAB_UTIL_HOPSCOTCH_TABLE_HPP

#include <vector>
#include <utility>
#include <algorithm>
#include <functional>
#include <iterator>

#include <graphlab/parallel/pthread_tools.hpp>
#include <graphlab/parallel/atomic.hpp>

#include <boost/functional/hash.hpp>
#define _HOPSCOTCH_TABLE_DEFAULT_HASH boost::hash<T>

namespace graphlab {

/**
  * This defines a hash table where each entry stores a
  * fixed data type T. The data type T should be <b>small</b>
  * and should preferably fit in a couple of words.
  * This hash table is not resizeable. Use the hopscotch_map
  * For a more general purpose table.
  *
  * Safe access is guaranteed if you restrict to the functions suffixed with
  * _sync.
  *
  * \tparam T The data type stored in the hash table
  * \tparam Synchronized Defaults to True. If True, locking is used to ensure
  *                      safe reads and writes to the hash table.
  *                      Even under "Synchronized", the only operations
  *                      which are safe for parallel access are all functions
  *                      suffixed with "sync".
  * \tparam Hash The hash functor type. Defaults to std::hash<T> if C++11 is
  *              available. Otherwise defaults to boost::hash<T>
  * \tparam KeyEqual The functor used to identify object equality. Defaults to
  *                  std::equal_to<T>
  */
template <typename T,
         bool Synchronized = true,
         typename Hash = _HOPSCOTCH_TABLE_DEFAULT_HASH,
         typename KeyEqual = std::equal_to<T> >
class hopscotch_table {
  public:
    /// The data type stored in the table
    typedef T              value_type;
    typedef size_t                                   size_type;
    /// The type of the hasher object
    typedef Hash                                     hasher;
    /// The type of the equality tester
    typedef KeyEqual equality_function;
    /// A pointer to the data type stored in the table
    typedef value_type* pointer;
    /// A reference to the data type stored in the table
    typedef value_type& reference;
    /// A constant pointer to the data type stored in the table
    typedef const value_type* const_pointer;
    /// A constant reference to the data type stored in the table
    typedef const value_type& const_reference;

  private:
    /// The actual contents of the hash table
    struct element {
      bool hasdata: 1;      /// Whether this entry has data.
      uint32_t field: 31;   /// The hopscotch bitfield. Only 31 bits are useable
      T elem;  /// User data
      element():hasdata(false), field(0) { }
    };

    std::vector<element> data;
    std::vector<simple_spinlock> locks;

    hasher hashfun;
    equality_function equalfun;
    atomic<size_t> numel;
    size_t mask;

    /// Returns the next power of 2 of a value
    static uint64_t next_powerof2(uint64_t val) {
      --val;
      val = val | (val >> 1);
      val = val | (val >> 2);
      val = val | (val >> 4);
      val = val | (val >> 8);
      val = val | (val >> 16);
      val = val | (val >> 32);
      return val + 1;
    }

    /** Computes the hash of the data. And perturbs it
      * using either CRC32 or Jenkin's 32-bit mix
      */
    size_t compute_hash(const value_type& d) const {
      size_t state = hashfun(d);
#ifdef HAS_BUILTIN_CRC32
      return __builtin_ia32_crc32di(0, state);
#else
    /*
     * Bob Jenkin's 32 bit integer mix function from
     * http://home.comcast.net/~bretm/hash/3.html
     */
      state += (state << 12);
      state ^= (state >> 22);
      state += (state << 4);
      state ^= (state >> 9);
      state += (state << 10);
      state ^= (state >> 2);
      state += (state << 7);
      state ^= (state >> 12);
      return state;
#endif
    }

    /// Returns the lock ID associated with a given array index
    static size_t associated_lock_id(size_t idx) {
      return idx / 32;
    }

  public:
    /**
     * Constructs a hopscotch table of a given length.
     *
     * \param len This rounded up to the next power of 2 will be used as
     *            the length of the table. This table is not resizeable.
     * \param hashfun The hasher functor. Defaults to Hash()
     * \param equalfun A functor used to test for equality. Defaults to KeyEqual()
     */
    hopscotch_table(size_t len,
                    Hash hashfun = Hash(),
                    KeyEqual equalfun = KeyEqual()):
                                              data(next_powerof2(len) + 32),
                                              locks(Synchronized ? data.size() / 32 + 1 : 0),
                                              hashfun(hashfun),
                                              equalfun(equalfun),
                                              numel(0),
                                              mask(data.size() - 32 - 1) {
    }

    /// Returns the hash function used by the hash table
    hasher hash_function() const {
      return hashfun;
    }

    /// Returns the equality function used by the hash table
    equality_function key_eq() const {
      return equalfun;
    }

    /**
      * A const iterator which allows iteration over the hash table
      * entries. Insertions may disrupt the iterator order. Deletions
      * invalidate the iterator.
      */
    struct const_iterator {
      typedef std::forward_iterator_tag iterator_category;
      typedef const typename hopscotch_table::value_type value_type;
      typedef size_t difference_type;
      typedef value_type* pointer;
      typedef value_type& reference;

      friend class hopscotch_table;

      const hopscotch_table* ptr;
      typename std::vector<element>::const_iterator iter;

      const_iterator():ptr(NULL) {}

      const_iterator operator++() {
        ++iter;
        while(iter != ptr->data.end() && !iter->hasdata) {
          ++iter;
        }
        return *this;
      }

      const_iterator operator++(int) {
        iterator cur = *this;
        ++(*this);
        return cur;
      }

      reference operator*() {
        return iter->elem;
      }

      pointer operator->() {
        return &(iter->elem);
      }

      bool operator==(const const_iterator it) const {
        return ptr == it.ptr && iter == it.iter;
      }

      bool operator!=(const const_iterator iter) const {
        return !((*this) == iter);
      }

    private:
      const_iterator(const hopscotch_table* table,
          typename std::vector<element>::const_iterator iter):
        ptr(table), iter(iter) { }
    };

    /**
      * A const iterator which allows iteration over the hash table
      * entries. Insertions may disrupt the iterator order. Deletions
      * invalidate the iterator.
      */
    struct iterator {
      typedef std::forward_iterator_tag iterator_category;
      typedef typename hopscotch_table::value_type value_type;
      typedef size_t difference_type;
      typedef value_type* pointer;
      typedef value_type& reference;

      friend class hopscotch_table;

      hopscotch_table* ptr;
      typename std::vector<element>::iterator iter;

      iterator():ptr(NULL) {}

      operator const_iterator() const {
        const_iterator it(ptr, iter);
        return it;
      }

      iterator operator++() {
        ++iter;
        while(iter != ptr->data.end() && !iter->hasdata) {
          ++iter;
        }
        return *this;
      }

      iterator operator++(int) {
        iterator cur = *this;
        ++(*this);
        return cur;
      }

      reference operator*() {
        return iter->elem;
      }

      pointer operator->() {
        return &(iter->elem);
      }

      bool operator==(const iterator it) const {
        return ptr == it.ptr && iter == it.iter;
      }

      bool operator!=(const iterator iter) const {
        return !((*this) == iter);
      }

    private:
      iterator(hopscotch_table* table,
          typename std::vector<element>::iterator iter):
        ptr(table), iter(iter) { }
    };

    /** Standard insert iterator. Writing into this iterator
     *  will cause insertions to occur. It is however, recommended
     *  that the insert() operation be used instead of the insert_iterator
     *  since the insert_iterator silently fails on insert failure.
     */
    struct insert_iterator{
      hopscotch_table* cmap;
      typedef std::forward_iterator_tag iterator_category;
      typedef typename hopscotch_table::value_type value_type;

      insert_iterator(hopscotch_table* c):cmap(c) {}

      insert_iterator operator++() {
        return (*this);
      }
      insert_iterator operator++(int) {
        return (*this);
      }

      insert_iterator& operator*() {
        return *this;
      }
      insert_iterator& operator=(const insert_iterator& i) {
        cmap = i.cmap;
        return *this;
      }

      insert_iterator& operator=(const value_type& v) {
        cmap->insert(v);
        return *this;
      }
    };

  private:
    /**
     *  Searches for a target entry and overwrites if it exists
     */
    template <bool IsSynchronized>
    iterator try_find_and_overwrite(const value_type& newdata,
                                    size_t target,
                                    bool overwrite) {
       // find the next empty entry
      size_t lockid = associated_lock_id(target);

      if (IsSynchronized) {
        locks[lockid + 1].lock();
        locks[lockid].lock();
      }
      iterator iter = find_impl(newdata, target);
      if (iter != end() && overwrite) {
        iter.iter->elem = newdata;
      }
      if (IsSynchronized) {
        locks[lockid].unlock();
        locks[lockid + 1].unlock();
      }
      return iter;
    }

    /** Insert logic. If IsSynchronized is set, locks are used
     *  If overwrite is set, it will additionally check for existance
     *  of the entry and overwrite if it exists.
     * Iterator is not going to be necessarily valid under parallel access.
     */
    template <bool IsSynchronized>
    iterator insert_impl(const value_type& newdata, bool overwrite = true) {
      // find the next empty entry
      size_t target = compute_hash(newdata) & mask;

      iterator ret = try_find_and_overwrite<IsSynchronized>(newdata,
                                                            target,
                                                            overwrite);
      if (ret != end()) return ret;

      // search for a place to stick it into
      bool found = false;
      size_t shift_target = target;
      // let max range is 31 * 20
      size_t limit = std::min(data.size(), target + 31 * 20);
      size_t lockid = 0;
      for (;shift_target < limit; shift_target++) {
        if (data[shift_target].hasdata == false) {
          lockid = associated_lock_id(shift_target);
          if (IsSynchronized) locks[lockid].lock();
          // double check
          if (data[shift_target].hasdata == false) {
            // yup still true.
            // we got an empty value.
            // quit the search
            found = true;
            break;
          } else {
            // nope. not empty anymore
            // unlock and continue
            if (IsSynchronized) locks[lockid].unlock();
          }
        }
      }

      if (!found) {
        // failed to find a place to put this value.
        return iterator(this, data.end());
      }

      // while the shift target is out of range
      while(shift_target - target >= 31) {
        // search backwards
        // we would like to jump as far as possible
        // find an hash entry whose field placed something
        // between here and the shift target
        // and move it to the shift target.
        // for i = 31 to 1
        found = false;
        // lock one before the current lockid if available
        if (IsSynchronized && lockid > 0) locks[lockid - 1].lock();

        for (size_t i = 30; i >= 1; --i) {
          size_t r;
          if (data[shift_target - i].field) {
            r = __builtin_ctz(data[shift_target - i].field);
            if (r <= i) {
              // shift
              size_t new_shift_target = shift_target - i + r;
              assert(data[new_shift_target].hasdata);
              data[shift_target].elem = data[new_shift_target].elem;
              data[shift_target].hasdata = true;
              data[new_shift_target].hasdata = false;
              data[new_shift_target].elem = T();

              // unset the bit for r and set the bit for i
              data[shift_target - i].field =
                (data[shift_target - i].field & ~((uint32_t)1 << r))
                 | ((uint32_t)1 << i);
              shift_target = new_shift_target;
              found = true;
              break;
            }
          }
        }

        if (!found) {
          // release all the locks acquired
          if (IsSynchronized) {
            locks[lockid].unlock();
            if (lockid > 0) locks[lockid - 1].unlock();
          }
          return iterator(this, data.end());
        }
        else {

          if (IsSynchronized) {
            // ok. depending on how far we went. we need to
            // unlock one of lockid or lockid - 1
            size_t newlockid = associated_lock_id(shift_target);
            assert(newlockid == lockid || newlockid == lockid - 1);
            if (newlockid == lockid) {
              if (lockid > 0) locks[lockid - 1].unlock();
            }
            else if (newlockid == lockid - 1) {
              locks[lockid].unlock();
            }
            lockid = newlockid;
          }
        }
      }
      // insert and return
      // we need to lock ID - 1 so as to ensure intersection with the hash target
      if (IsSynchronized && lockid > 0) locks[lockid - 1].lock();
      data[shift_target].elem = newdata;
      data[target].field |= (1 << (shift_target - target));
      data[shift_target].hasdata = true;
      if (IsSynchronized) {
        ++numel;
        if (lockid > 0) locks[lockid - 1].unlock();
        locks[lockid].unlock();
      }
      else {
        ++numel.value;
      }
      return iterator(this, data.begin() + shift_target);
    }

    /**
      * Searches for an entry and returns an iterator to the entry.
      * The hash entry of the key is provided.
      * KeyEqual will be used to identify if an entry matches the request.
      * return end() on failure.
      */
    const_iterator find_impl(const value_type& key, size_t target) const {
      uint32_t field = data[target].field;
      while (field > 0) {
        int r = __builtin_ctz(field);
        if (data[target + r].hasdata &&
            key_eq()(data[target + r].elem, key)) {
          return const_iterator(this, data.begin() + target + r);
        }
        else {
          // mask out the current bit and try again.
          field &= ~(((uint32_t)1 << r));
        }
      }
      return const_iterator(this, data.end());
    }

    iterator find_impl(const value_type& key, size_t target) {
      const_iterator iter = ((const hopscotch_table*)(this))->find_impl(key, target);
      return iterator(this, data.begin() + (iter.iter - data.begin()));
    }

  public:
    /**
      * Inserts an entry into the array.
      * Returns an iterator to the just inserted data on success.
      * If the entry already exists, it will be overwritten.
      * Returns end() on failure.
      */
    iterator insert(const value_type& newdata) {
      return insert_impl<false>(newdata);
    }

    /**
      * Inserts an entry into the array.
      * Returns an iterator to the just inserted data on success.
      * This function check if the entry already exists, if it does,
      * do nothing
      * Returns end() on failure.
      */
    iterator insert_do_not_overwrite(const value_type& newdata) {
      return insert_impl<false>(newdata, false);
    }

    /**
      * Searches for an entry and returns an iterator to the entry.
      * KeyEqual will be used to identify if an entry matches the request.
      * return end() on failure.
      */
    const_iterator find(const value_type& key) const {
      size_t target = compute_hash(key) & mask;
      return find_impl(key, target);
    }

    /**
      * Searches for an entry and returns an iterator to the entry.
      * KeyEqual will be used to identify if an entry matches the request.
      * return end() on failure.
      */
    iterator find(const value_type& key) {
      const_iterator iter = ((const hopscotch_table*)(this))->find(key);
      return iterator(this, data.begin() + (iter.iter - data.begin()));
    }

    void clear() {
      for (size_t i = 0;i < data.size(); ++i) {
        data[i].hasdata = false;
        data[i].field = 0;
        data[i].elem = value_type();
      }
      numel = 0;
    }

   /**
    * Erases an entry pointed to by an iterator.
    */
    bool erase(iterator iter)  {
      if (iter.iter == data.end()) return false;
      assert(iter.iter->hasdata);
      size_t target = compute_hash(iter.iter->elem) & mask;
      size_t offset = iter.iter - (data.begin() + target);
      assert(offset < 31);
      --numel.value;
      iter.iter->hasdata = false;
      iter.iter->elem = value_type();
      data[target].field &=  ~((uint32_t)1 << offset);
      return true;
    }

    /// Erases a entry matching a given value.
    bool erase(const value_type& key) {
      return erase(find(key));
    }

    /// Returns an iterator to the start of the table
    iterator begin() {
      // find the first which is not empty
      typename std::vector<element>::iterator iter = data.begin();
      while (iter != data.end() && !iter->hasdata) {
        ++iter;
      }
      return iterator(this, iter);
    }

    /// Returns an iterator to the start of the table
    const_iterator begin() const {
      // find the first which is not empty
      typename std::vector<element>::iterator iter = data.begin();
      while (iter != data.end() && !iter->hasdata) {
        ++iter;
      }
      return const_iterator(this, iter);
    }

    /// Returns an iterator to the end of the table
    iterator end() {
      return iterator(this, data.end());
    }

    /// Returns an iterator to the end of the table
    const_iterator end() const {
      return const_iterator(this, data.end());
    }

    /// Returns 1 if the table contains a given element. 0 otherwise.
    size_t count(const value_type& v) const {
      return find(v) != end();
    }

    /// Returns true if the table contains a given element. false otherwise.
    bool contains(const value_type& v) const {
      return find(v) != end();
    }

    /// Returns the number of elements in the table
    size_t size() const {
      return numel;
    }

    /// Returns the capacity of the table
    size_t capacity() const {
      return data.size();
    }

    float load_factor() const {
      return float(size()) / capacity();
    }

    // now for the safe accessors

    /// Returns the size of the hash table. Safe under parallel access.
    size_t size_sync() const {
      return numel;
    }

    /// Returns the capacity of the table
    size_t capacity_sync() const {
      return data.size();
    }

    float load_factor_sync() const {
      return float(size_sync()) / capacity_sync();
    }

    hopscotch_table& operator=(const hopscotch_table& other) {
      data = other.data;
      locks.resize(other.locks.size());
      hashfun = other.hashfun;
      equalfun = other.equalfun;
      numel = other.numel;
      mask = other.mask;
      return *this;
    }

    /** Inserts an element into the hash table. Safe under parallel access.
      * if t already exists, it will be overwritten
      */
    bool put_sync(const T& t) {
      // since data is not resizeable,
      // data.end() is always valid.
      return insert_impl<Synchronized>(t).iter != data.end();
    }

    /** Inserts an element into the hash table. Safe under parallel access.
      * if t already exists, nothing will happen
      */
    bool put_do_not_overwrite_sync(const T& t) {
      // since data is not resizeable,
      // data.end() is always valid.
      return insert_impl<Synchronized>(t, false).iter != data.end();
    }

    /** If the argument is found in the hash table,
     *  return {true, V} where V is the hash table content matching the argument.
     *  Otherwise {false, T()} is returned.
     *  KeyEqual() is used to compare entries.
     *  Safe under parallel access.
     */
    std::pair<bool, T> get_sync(const T& t) const {
      // fast path. Try to get it without locking
      const_iterator iter = find(t);
      if (iter != end()) {
        // take a snapshot of the data
        element e = *(iter.iter);
        if (e.hasdata && key_eq()(e.elem, t)) {
          return std::make_pair(true, e.elem);
        }
      }

      if (!Synchronized) {
        return std::make_pair(false, T());
      }

      // slow path. lock
      size_t target = compute_hash(t) & mask;
      size_t lockid = associated_lock_id(target);
      locks[lockid + 1].lock();
      locks[lockid].lock();
      iter = find_impl(t, target);
      if (iter != end()) {
        element e = *(iter.iter);
        locks[lockid].unlock();
        locks[lockid + 1].unlock();
        assert(e.hasdata && key_eq()(e.elem, t));
        return std::make_pair(true, e.elem);
      }
      else {
        locks[lockid].unlock();
        locks[lockid + 1].unlock();
        return std::make_pair(false, T());
      }
    }

    /**
      * Returns true if the erasure was successful.
      * If false, the entry was not found in the hash table
      */
    bool erase_sync(const T& t) {
      if (!Synchronized) {
        return erase(t);
      }

      // we need to find it first
      size_t target = compute_hash(t) & mask;
      size_t lockid = associated_lock_id(target);
      // acquire locks around the target
      locks[lockid + 1].lock();
      locks[lockid].lock();
      iterator iter = find(t);
      if (iter == end()) {
        locks[lockid].unlock();
        locks[lockid + 1].unlock();
        return false;
      }
      // now lets erase it
      assert(iter.iter->hasdata);
      size_t offset = iter.iter - (data.begin() + target);
      assert(offset < 31);
      --numel;
      iter.iter->hasdata = false;
      iter.iter->elem = value_type();
      data[target].field &=  ~((uint32_t)1 << offset);
      locks[lockid + 1].unlock();
      locks[lockid].unlock();
      return true;
    }
};

} // graphlab
#endif

max_issues_repo_name: keerthanashanmugam/graphlabapi

max_forks_repo_name: keerthanashanmugam/graphlabapi


text:
// Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2007-2008 Steven Watanabe
//
// 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_UNIT_SYSTEMS_ASTRONOMICAL_LIGHT_SECOND_HPP_INCLUDED
#define BOOST_UNIT_SYSTEMS_ASTRONOMICAL_LIGHT_SECOND_HPP_INCLUDED

#include <boost/units/conversion.hpp>
#include <boost/units/base_units/si/meter.hpp>

BOOST_UNITS_DEFINE_BASE_UNIT_WITH_CONVERSIONS(astronomical, light_second, "light second", "lsc", 2.99792458e8, boost::units::si::meter_base_unit, -201);

#if BOOST_UNITS_HAS_BOOST_TYPEOF

#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

BOOST_TYPEOF_REGISTER_TYPE(boost::units::astronomical::light_second_base_unit)

#endif

#endif // BOOST_UNIT_SYSTEMS_ASTRONOMICAL_LIGHT_SECOND_HPP_INCLUDED


text:
//
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_RFC_IMPL_REASON_PHRASE_RULE_PP
#define BOOST_HTTP_PROTO_RFC_IMPL_REASON_PHRASE_RULE_PP

#include <boost/http_proto/rfc/reason_phrase_rule.hpp>

namespace boost {
namespace http_proto {

void
reason_phrase_rule::
parse(
    char const*& it,
    char const* end,
    error_code&,
    reason_phrase_rule& t) noexcept
{
    // reason-phrase   = *( HTAB / SP / VCHAR / obs-text )
    struct reason_chars_t
    {
        constexpr
        bool
        operator()(char c) const noexcept
        {
            return
                (static_cast<unsigned char>(
                    c) >= 32 &&
                 static_cast<unsigned char>(
                    c) != 128) ||
                (c == 9);
        }
    };
    static constexpr reason_chars_t cs{};
    auto const start = it;
    it = grammar::find_if_not(it, end, cs);
    t.s = string_view(start, it - start);
}

} // http_proto
} // boost

#endif


text:
// --------------------------------------------------------------------------
//                   OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2015.
//
// This software is released under a three-clause BSD license:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of any author or any participating institution
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: George Rosenberger $
// $Authors: George Rosenberger, Hannes Roest $
// --------------------------------------------------------------------------

#include <OpenMS/MATH/MISC/RANSAC.h>
#include <OpenMS/MATH/STATISTICS/LinearRegression.h>
#include <OpenMS/CONCEPT/LogStream.h> // LOG_DEBUG

#include <numeric>
#include <boost/math/special_functions/erf.hpp>
#include <algorithm>

namespace OpenMS
{
  std::pair<double, double > Math::RANSAC::llsm_fit_(std::vector<std::pair<double, double> >& pairs)
  {
    std::vector<double> x, y;

    for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)
    {
      x.push_back(it->first);
      y.push_back(it->second);
    }

    // GSL implementation
    //double c0, c1, cov00, cov01, cov11, sumsq;
    //double* xa = &x[0];
    //double* ya = &y[0];
    //gsl_fit_linear(xa, 1, ya, 1, pairs.size(), &c0, &c1, &cov00, &cov01, &cov11, &sumsq);

    // OpenMS::MATH implementation
    Math::LinearRegression lin_reg;
    lin_reg.computeRegression(0.95, x.begin(), x.end(), y.begin());
    double c0, c1;
    c0 = lin_reg.getIntercept();
    c1 = lin_reg.getSlope();

    return(std::make_pair(c0,c1));
  }

  double Math::RANSAC::llsm_rsq(std::vector<std::pair<double, double> >& pairs)
  {
    std::vector<double> x, y;

    for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)
    {
      x.push_back(it->first);
      y.push_back(it->second);
    }

    // GSL implementation
    //double* xa = &x[0];
    //double* ya = &y[0];
    //double r = gsl_stats_correlation(xa, 1, ya, 1, pairs.size());
    //return(r);

    // OpenMS::MATH implementation
    Math::LinearRegression lin_reg;
    lin_reg.computeRegression(0.95, x.begin(), x.end(), y.begin());

    return lin_reg.getRSquared();
  }

  double Math::RANSAC::llsm_rss_(std::vector<std::pair<double, double> >& pairs, std::pair<double, double >& coefficients)
  {
    double rss = 0;

    for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)
    {
      rss += pow(it->second - (coefficients.first + ( coefficients.second * it->first)), 2);
    }

    return rss;
  }

  std::vector<std::pair<double, double> > Math::RANSAC::llsm_rss_inliers_(
      std::vector<std::pair<double, double> >& pairs,
      std::pair<double, double >& coefficients, double max_threshold)
  {
    std::vector<std::pair<double, double> > alsoinliers;

    for (std::vector<std::pair<double, double> >::iterator it = pairs.begin(); it != pairs.end(); ++it)
    {
      if (pow(it->second - (coefficients.first + ( coefficients.second * it->first)), 2) < max_threshold)
      {
        alsoinliers.push_back(*it);
      }
    }

    return alsoinliers;
  }

  std::vector<std::pair<double, double> > Math::RANSAC::ransac(
      std::vector<std::pair<double, double> >& pairs, size_t n, size_t k, double t, size_t d, bool test)
  {
    // implementation of the RANSAC algorithm according to http://wiki.scipy.org/Cookbook/RANSAC.

    std::vector<std::pair<double, double> > maybeinliers, test_points, alsoinliers, betterdata, bestdata;

    double besterror = std::numeric_limits<double>::max();
    double bettererror;
#ifdef DEBUG_MRMRTNORMALIZER
    std::pair<double, double > bestcoeff;
    double betterrsq = 0;
    double bestrsq = 0;
#endif

    for (size_t ransac_int=0; ransac_int<k; ransac_int++)
    {
      std::vector<std::pair<double, double> > pairs_shuffled = pairs;

      if (!test)
      { // disables random selection in test mode
        std::random_shuffle(pairs_shuffled.begin(), pairs_shuffled.end());
      }

      maybeinliers.clear();
      test_points.clear();
      std::copy( pairs_shuffled.begin(), pairs_shuffled.begin()+n, std::back_inserter(maybeinliers) );
      std::copy( pairs_shuffled.begin()+n, pairs_shuffled.end(), std::back_inserter(test_points) );

      std::pair<double, double > coeff = Math::RANSAC::llsm_fit_(maybeinliers);

      alsoinliers = Math::RANSAC::llsm_rss_inliers_(test_points,coeff,t);

      if (alsoinliers.size() > d)
      {
        betterdata = maybeinliers;
        betterdata.insert( betterdata.end(), alsoinliers.begin(), alsoinliers.end() );
        std::pair<double, double > bettercoeff = Math::RANSAC::llsm_fit_(betterdata);
        bettererror = Math::RANSAC::llsm_rss_(betterdata,bettercoeff);
#ifdef DEBUG_MRMRTNORMALIZER
        betterrsq = Math::RANSAC::llsm_rsq(betterdata);
#endif

        if (bettererror < besterror)
        {
          besterror = bettererror;
#ifdef DEBUG_MRMRTNORMALIZER
          bestcoeff = bettercoeff;
#endif
          bestdata = betterdata;

#ifdef DEBUG_MRMRTNORMALIZER
          bestrsq = betterrsq;
          std::cout << "RANSAC " << ransac_int << ": Points: " << betterdata.size() << " RSQ: " << bestrsq << " Error: " << besterror << " c0: " << bestcoeff.first << " c1: " << bestcoeff.second << std::endl;
#endif
        }
      }
    }

#ifdef DEBUG_MRMRTNORMALIZER
    std::cout << "=======STARTPOINTS=======" << std::endl;
    for (std::vector<std::pair<double, double> >::iterator it = bestdata.begin(); it != bestdata.end(); ++it)
    {
      std::cout << it->first << "\t" << it->second << std::endl;
    }
    std::cout << "=======ENDPOINTS=======" << std::endl;
#endif

    return(bestdata);
  }

}

max_stars_repo_name: tomas-pluskal/openms

max_issues_repo_name: tomas-pluskal/openms

max_forks_repo_name: tomas-pluskal/openms


text:
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <boost/lexical_cast.hpp>
using namespace std;
int main() {
    long long int n; int k; cin >> n >> k;
    for (int i = 1; i <= k; i++) {
        string x = boost::lexical_cast<string>(n);
        sort(x.begin(), x.end());
        long long int a = boost::lexical_cast<long long int>(x);
        reverse(x.begin(), x.end());
        long long int b = boost::lexical_cast<long long int>(x);
        n = b - a;
    }
    cout << n << endl;
}


text:
#include <boost/serialization/export.hpp>
#include "Convolution2D.hpp"
#include "LayerModel.hpp"

using namespace std;
using namespace snn;
using namespace internal;

BOOST_CLASS_EXPORT(Convolution2D)

Convolution2D::Convolution2D(LayerModel& model, shared_ptr<NeuralNetworkOptimizer> optimizer)
    : FilterLayer(model, optimizer)
{
}

inline
unique_ptr<BaseLayer> Convolution2D::clone(std::shared_ptr<NeuralNetworkOptimizer> optimizer) const
{
    auto layer = make_unique<Convolution2D>(*this);
    for (auto& neuron : layer->neurons)
        neuron.optimizer = optimizer;
    return layer;
}

std::vector<int> Convolution2D::getShapeOfOutput() const
{
    return {
        this->shapeOfInput[0] - (this->sizeOfFilterMatrix - 1),
        this->shapeOfInput[1] - (this->sizeOfFilterMatrix - 1),
        this->numberOfFilters
    };
}

int Convolution2D::isValid() const
{
    for (auto& neuron : neurons)
    {
        if (neuron.getNumberOfInputs() != this->sizeOfFilterMatrix * this->sizeOfFilterMatrix * this->shapeOfInput[2])
            return 203;
    }
    return this->FilterLayer::isValid();
}

inline
vector<float> Convolution2D::createInputsForNeuron(int neuronNumber, const vector<float>& inputs) const
{
    vector<float> neuronInputs;
    neuronInputs.reserve(this->neurons[neuronNumber].getNumberOfInputs());
    neuronNumber = neuronNumber % this->getNumberOfNeurons()/this->numberOfFilters;
    const int neuronPositionX = neuronNumber % this->shapeOfInput[0];
    const int neuronPositionY = neuronNumber / this->shapeOfInput[0];

    for (int i = 0; i < this->sizeOfFilterMatrix; ++i)
    {
        const int beginIndex = ((neuronPositionY + i) * this->shapeOfInput[0] * this->shapeOfInput[2]) + neuronPositionX * this->shapeOfInput[2];
        const int endIndex = ((neuronPositionY + i) * this->shapeOfInput[0] * this->shapeOfInput[2])
        + (neuronPositionX + this->sizeOfFilterMatrix) * this->shapeOfInput[2];
        for (int j = beginIndex; j < endIndex; ++j)
        {
            neuronInputs.push_back(inputs[j]);
        }
    }
    return neuronInputs;
}

void Convolution2D::insertBackOutputForNeuron(int neuronNumber, const std::vector<float>& error, std::vector<float>& errors) const
{
    neuronNumber = neuronNumber % this->getNumberOfNeurons()/this->numberOfFilters;
    const int neuronPositionX = neuronNumber % (this->shapeOfInput[0] - (this->sizeOfFilterMatrix - 1));
    const int neuronPositionY = neuronNumber / (this->shapeOfInput[0] - (this->sizeOfFilterMatrix - 1));

    for (int i = 0; i < this->sizeOfFilterMatrix; ++i)
    {
        const int beginIndex = ((neuronPositionY + i) * this->shapeOfInput[0] * this->shapeOfInput[2]) + neuronPositionX * this->shapeOfInput[2];
        for(int j = 0; j < this->sizeOfFilterMatrix; ++j)
        {
            const int indexErrors = beginIndex + j;
            const int indexMatrix = i * this->sizeOfFilterMatrix + j;
            errors[indexErrors] += error[indexMatrix];
        }
    }
}

inline
bool Convolution2D::operator==(const BaseLayer& layer) const
{
    return this->FilterLayer::operator==(layer);
}

inline
bool Convolution2D::operator!=(const BaseLayer& layer) const
{
    return !(*this == layer);
}

max_stars_repo_name: sehe/StraightforwardNeuralNetwork

max_issues_repo_name: sehe/StraightforwardNeuralNetwork

max_forks_repo_name: sehe/StraightforwardNeuralNetwork


text:
#include <bdd_model.hpp>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <chrono>

#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>

using namespace verilog::bdd;
using namespace std::chrono;

int main(int nargs, char** argv){

  BDD a("a");
  BDD b("b");

  BDD c = a & b;

  std::cout << a;
  std::cout << b;
  std::cout << c;

  return 0;
}

ext: cxx


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

  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/constant/eps.hpp>
#include <boost/simd/as.hpp>
#include <scalar_test.hpp>

STF_CASE_TPL( "Check eps behavior for integral types"
            , (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t)
              (std::int8_t)(std::int16_t)(std::int32_t)(std::int64_t)
            )
{
  using boost::simd::as;
  using boost::simd::detail::eps;
  using boost::simd::Eps;

  STF_TYPE_IS(decltype(Eps<T>()), T);
  STF_EQUAL(Eps<T>(), T(1));
  STF_EQUAL(eps( as(T{}) ),T(1));
}

STF_CASE_TPL( "Check eps behavior for double type"
            , (double)
            )
{
  using boost::simd::as;
  using boost::simd::detail::eps;
  using boost::simd::Eps;

  STF_TYPE_IS(decltype(Eps<T>()), T);
  STF_IEEE_EQUAL(Eps<T>(), 2.220446049250313e-16);
  STF_IEEE_EQUAL(eps( as(T{}) ), 2.220446049250313e-16);
}
STF_CASE_TPL( "Check eps behavior for float type"
            , (float)
            )
{
  using boost::simd::as;
  using boost::simd::detail::eps;
  using boost::simd::Eps;

  STF_TYPE_IS(decltype(Eps<T>()), T);
  STF_IEEE_EQUAL(Eps<T>(),   T(1.192092895507843e-07));
  STF_IEEE_EQUAL(eps( as(T{}) ),   T(1.192092895507813e-07));
}


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS
  @copyright 2016 J.T.Lapreste

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

#include <boost/simd/config.hpp>
#include <boost/simd/function/definition/rem.hpp>
#include <boost/simd/detail/dispatch.hpp>

namespace boost { namespace simd
{
  namespace tag
  {
    using remfix_ = rem_;
  }

  BOOST_DISPATCH_CALLABLE_DEFINITION(tag::remfix_,remfix);
} }

#endif


text:
// This file is part of comma, a generic and flexible library
// Copyright (c) 2011 The University of Sydney
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. Neither the name of the University of Sydney nor the
//    names of its contributors may be used to endorse or promote products
//    derived from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
// GRANTED BY THIS LICENSE.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
// HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/// @author vsevolod vlaskine

#include <boost/regex.hpp>
#include "../base/exception.h"
#include "../csv/options.h"
#include "../string/split.h"
#include "../string/string.h"

namespace comma { namespace csv {

const csv::format& options::format() const { return *format_; }

csv::format& options::format() { return *format_; }

void options::format( const std::string& s ) { format_ = csv::format( s ); }

void options::format( const csv::format& f ) { format_ = f; }

bool options::binary() const { return static_cast< bool >( format_ ); }

namespace impl {

inline static void init( comma::csv::options& csv_options, const comma::command_line_options& options, const std::string& defaultFields, bool full_xpath )
{
    csv_options.full_xpath = full_xpath;
    csv_options.fields = options.value( "--fields,-f", defaultFields );
    if( options.exists( "--binary,-b" ) )
    {
        boost::optional< std::string > format = options.optional< std::string >( "--binary,-b" );
        if( format ) { csv_options.format( options.value< std::string >( "--binary,-b" ) ); }
    }
    csv_options.precision = options.value< unsigned int >( "--precision", 12 );
    csv_options.delimiter = options.exists( "--delimiter" ) ? options.value( "--delimiter", ',' ) : options.value( "-d", ',' );
    boost::optional< std::string > quote_character = options.optional< std::string >( "--quote" );
    if( quote_character )
    {
        switch( quote_character->size() )
        {
            case 0: csv_options.quote.reset(); break;
            case 1: csv_options.quote = ( *quote_character )[0]; break;
            case 2: COMMA_THROW( comma::exception, "expected a quote character, got \"" << *quote_character << "\"" );
        }
    }
    csv_options.flush = options.exists( "--flush" );
}

} // namespace impl {

options::options() : full_xpath( true ), delimiter( ',' ), precision( 12 ), quote( '"' ), flush( false ) {}

options::options( int argc, char** argv, const std::string& defaultFields, bool full_xpath ) { impl::init( *this, comma::command_line_options( argc, argv ), defaultFields, full_xpath ); }

options::options( const comma::command_line_options& options, const std::string& defaultFields, bool full_xpath ) { impl::init( *this, options, defaultFields, full_xpath ); }

std::string options::usage( const std::string& default_fields, bool verbose )
{
    std::ostringstream oss;
    if( verbose )
    {
        oss << "    --delimiter,-d <delimiter>: default: ','" << std::endl;
        oss << "    --fields,-f <names>: comma-separated field names";
        if( !default_fields.empty() ) { oss << "; default: " << default_fields; }
        oss << std::endl;
        oss << "    --precision <precision>: floating point precision; default: 12" << std::endl;
        oss << "    --quote=[<quote_character>]: quote sign to quote strings (ascii only); default: '\"'" << std::endl;
        oss << "    --flush: if present, flush output stream after each record" << std::endl;
        oss << "    --format <format>: explicitly set input format in csv mode (if not set, guess format from first line)" << std::endl;
        oss << "    --binary,-b <format>: use binary format" << std::endl;
        oss << format::usage();
    }
    else
    {
        oss << "    --binary,-b <format>: use binary format" << std::endl;
        oss << "    --delimiter,-d <delimiter>: default: ','" << std::endl;
        oss << "    --fields,-f <names>: comma-separated field names";
        if( !default_fields.empty() ) { oss << "; default: " << default_fields; }
        oss << std::endl;
        oss << "    --flush: if present, flush output stream after each record" << std::endl;
        oss << "    --precision <precision>: floating point precision; default: 12" << std::endl;
        oss << std::endl;
        oss << "    run with verbose for full csv options description..." << std::endl;
    }
    return oss.str();
}

bool options::has_field( const std::string& field ) const
{
    if( field.empty() ) { return false; }
    const std::vector< std::string >& v = split( fields, ',' );
    const std::vector< std::string >& f = split( field, ',' );
    for( unsigned int i = 0; i < f.size(); ++i ) { if( std::find( v.begin(), v.end(), f[i] ) == v.end() ) { return false; } }
    return true;
}

bool options::has_some_of_fields( const std::string& field ) const
{
    if( field.empty() ) { return false; }
    const std::vector< std::string >& v = split( fields, ',' );
    const std::vector< std::string >& f = split( field, ',' );
    for( unsigned int i = 0; i < f.size(); ++i ) { if( std::find( v.begin(), v.end(), f[i] ) != v.end() ) { return true; } }
    return false;
}

bool options::has_paths( const std::string& paths ) const
{
    if( paths.empty() ) { return false; }
    const std::vector< std::string >& v = split( fields, ',' );
    const std::vector< std::string >& p = split( paths, ',' );
    for( unsigned int i = 0; i < p.size(); ++i )
    {
        std::string regex_string = "^" + boost::regex_replace( boost::regex_replace( p[i], boost::regex( "\\[" ), "\\\\[" ), boost::regex( "\\]" ), "\\\\]" ) + "(([/\\[])(.*)){0,1}";
        boost::regex regex( regex_string, boost::regex::extended );
        bool found = false;
        for( unsigned int j = 0; j < v.size() && !found; ++j ) { if( boost::regex_match( v[j], boost::regex( regex_string, boost::regex::extended ) ) ) { found = true; } }
        if( !found ) { return false; }
    }
    return true;
}

bool options::has_some_of_paths( const std::string& paths ) const
{
    if( paths.empty() ) { return false; }
    const std::vector< std::string >& v = split( fields, ',' );
    const std::vector< std::string >& p = split( paths, ',' );
    for( unsigned int i = 0; i < p.size(); ++i )
    {
        std::string regex_string = "^" + boost::regex_replace( boost::regex_replace( p[i], boost::regex( "\\[" ), "\\\\[" ), boost::regex( "\\]" ), "\\\\]" ) + "(([/\\[])(.*)){0,1}";
        boost::regex regex( regex_string, boost::regex::extended );
        for( unsigned int j = 0; j < v.size(); ++j ) { if( boost::regex_match( v[j], regex ) ) { return true; } }
    }
    return false;
}

std::string options::valueless_options() { return "--flush"; }

} } // namespace comma { namespace csv {

max_stars_repo_name: mission-systems-pty-ltd/comma

max_issues_repo_name: mission-systems-pty-ltd/comma

max_forks_repo_name: mission-systems-pty-ltd/comma


text:
//////////////////////////////////////////////////////////////////////////////
///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI
///
///          Distributed under the Boost Software License, Version 1.0
///                 See accompanying file LICENSE.txt or copy at
///                     http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#define NT2_UNIT_MODULE "nt2 polynomials toolbox - unit/simd Mode"
#include <nt2/toolbox/polynomials/include/hermite.hpp>
#include <nt2/include/functions/random.hpp>
#include <nt2/include/functions/ulpdist.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/simd/native.hpp>
#include <nt2/sdk/memory/is_aligned.hpp>
#include <nt2/sdk/memory/aligned_type.hpp>
#include <nt2/sdk/memory/load.hpp>
#include <nt2/sdk/functor/meta/call.hpp>
#include <boost/type_traits/is_same.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <iostream>
//////////////////////////////////////////////////////////////////////////////
// Test behavior of arithmetic component hermite using NT2_TEST_CASE
//////////////////////////////////////////////////////////////////////////////
NT2_TEST_CASE_TPL(hermite, (float)(double)
                         )
{
 using nt2::hermite;
 using nt2::tag::hermite_;
 using nt2::load;
 using nt2::simd::native;
 using nt2::meta::cardinal_of;

 typedef NT2_SIMD_DEFAULT_EXTENSION  ext_t;
 typedef native<T,ext_t>             n_t;
 typedef typename nt2::meta::call<hermite_(int32_t, n_t)>::type call_type;
 typedef typename nt2::meta::as_real<T>::type rT;
 typedef native<rT,ext_t>            rn_t;

 NT2_TEST( (boost::is_same<call_type, rn_t>::value) );
 NT2_ALIGNED_TYPE(T) data[1*cardinal_of<n_t>::value];

 for(std::size_t i=0;i<1*cardinal_of<n_t>::value;++i)
   data[i] =nt2::random(-10.0, 10.0); // good value here for hermite

 n_t a0 = load<n_t>(&data[0],0);
 for(int ii = 0; ii < 10; ii++)
   {
     rn_t v  = nt2::hermite(ii, a0);
     for(std::size_t j=0;j<cardinal_of<n_t>::value;++j)
       {
       NT2_TEST_LESSER_EQUAL( nt2::ulpdist(v[j], hermite(ii, a0[j])), 1);
       }
   }

//    NT2_TEST_EQUAL(  nt2::hermite( 1,T(0) ) , nt2::hermite( 1,nt2::splat < n_t > (T(0)) )[0] );
//    NT2_TEST_EQUAL(  nt2::hermite( 2,T(1) ) , nt2::hermite( 2,nt2::splat < n_t > (T(1) ) )[0] );
//    NT2_TEST_EQUAL(  nt2::hermite( 1,T(2) ) , nt2::hermite( 1,nt2::splat < n_t > (T(2) ) )[0] );
//    NT2_TEST_EQUAL(  nt2::hermite( 2,T(8) ) , nt2::hermite( 2,nt2::splat < n_t > (T(8) ) )[0] );
//    NT2_TEST_EQUAL(  nt2::hermite( 2, T(-1)), nt2::hermite( 2,nt2::splat < n_t > (T(-1) ))[0]);

 }


text:
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_WEBSOCKET_IMPL_HANDSHAKE_IPP
#define BOOST_BEAST_WEBSOCKET_IMPL_HANDSHAKE_IPP

#include <boost/beast/websocket/detail/type_traits.hpp>
#include <boost/beast/http/empty_body.hpp>
#include <boost/beast/http/message.hpp>
#include <boost/beast/http/read.hpp>
#include <boost/beast/http/write.hpp>
#include <boost/beast/core/handler_ptr.hpp>
#include <boost/beast/core/type_traits.hpp>
#include <boost/asio/associated_allocator.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/coroutine.hpp>
#include <boost/asio/executor_work_guard.hpp>
#include <boost/asio/handler_continuation_hook.hpp>
#include <boost/asio/handler_invoke_hook.hpp>
#include <boost/assert.hpp>
#include <boost/throw_exception.hpp>
#include <memory>

namespace boost {
namespace beast {
namespace websocket {

//------------------------------------------------------------------------------

// send the upgrade request and process the response
//
template<class NextLayer, bool deflateSupported>
template<class Handler>
class stream<NextLayer, deflateSupported>::handshake_op
    : public boost::asio::coroutine
{
    struct data
    {
        stream<NextLayer, deflateSupported>& ws;
        boost::asio::executor_work_guard<decltype(std::declval<
            stream<NextLayer, deflateSupported>&>().get_executor())> wg;
        response_type* res_p;
        detail::sec_ws_key_type key;
        http::request<http::empty_body> req;
        response_type res;

        template<class Decorator>
        data(
            Handler const&,
            stream<NextLayer, deflateSupported>& ws_,
            response_type* res_p_,
            string_view host,
            string_view target,
            Decorator const& decorator)
            : ws(ws_)
            , wg(ws.get_executor())
            , res_p(res_p_)
            , req(ws.build_request(key,
                host, target, decorator))
        {
            ws.reset();
        }
    };

    handler_ptr<data, Handler> d_;

public:
    handshake_op(handshake_op&&) = default;
    handshake_op(handshake_op const&) = delete;

    template<class DeducedHandler, class... Args>
    handshake_op(DeducedHandler&& h,
            stream<NextLayer, deflateSupported>& ws, Args&&... args)
        : d_(std::forward<DeducedHandler>(h),
            ws, std::forward<Args>(args)...)
    {
    }

    using allocator_type =
        boost::asio::associated_allocator_t<Handler>;

    allocator_type
    get_allocator() const noexcept
    {
        return (boost::asio::get_associated_allocator)(d_.handler());
    }

    using executor_type = boost::asio::associated_executor_t<
        Handler, decltype(std::declval<stream<NextLayer, deflateSupported>&>().get_executor())>;

    executor_type
    get_executor() const noexcept
    {
        return (boost::asio::get_associated_executor)(
            d_.handler(), d_->ws.get_executor());
    }

    void
    operator()(
        error_code ec = {},
        std::size_t bytes_used = 0);

    friend
    bool asio_handler_is_continuation(handshake_op* op)
    {
        using boost::asio::asio_handler_is_continuation;
        return asio_handler_is_continuation(
            std::addressof(op->d_.handler()));
    }

    template<class Function>
    friend
    void asio_handler_invoke(Function&& f, handshake_op* op)
    {
        using boost::asio::asio_handler_invoke;
        asio_handler_invoke(f,
            std::addressof(op->d_.handler()));
    }
};

template<class NextLayer, bool deflateSupported>
template<class Handler>
void
stream<NextLayer, deflateSupported>::
handshake_op<Handler>::
operator()(error_code ec, std::size_t)
{
    auto& d = *d_;
    BOOST_ASIO_CORO_REENTER(*this)
    {
        // Send HTTP Upgrade
        d.ws.do_pmd_config(d.req, is_deflate_supported{});
        BOOST_ASIO_CORO_YIELD
        http::async_write(d.ws.stream_,
            d.req, std::move(*this));
        if(ec)
            goto upcall;

        // VFALCO We could pre-serialize the request to
        //        a single buffer, send that instead,
        //        and delete the buffer here. The buffer
        //        could be a variable block at the end
        //        of handler_ptr's allocation.

        // Read HTTP response
        BOOST_ASIO_CORO_YIELD
        http::async_read(d.ws.next_layer(),
            d.ws.rd_buf_, d.res,
                std::move(*this));
        if(ec)
            goto upcall;
        d.ws.on_response(d.res, d.key, ec);
        if(d.res_p)
            swap(d.res, *d.res_p);
    upcall:
        {
            auto wg = std::move(d.wg);
            d_.invoke(ec);
        }
    }
}

template<class NextLayer, bool deflateSupported>
template<class HandshakeHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(
    HandshakeHandler, void(error_code))
stream<NextLayer, deflateSupported>::
async_handshake(string_view host,
    string_view target,
        HandshakeHandler&& handler)
{
    static_assert(is_async_stream<next_layer_type>::value,
        "AsyncStream requirements not met");
    BOOST_BEAST_HANDLER_INIT(
        HandshakeHandler, void(error_code));
    handshake_op<BOOST_ASIO_HANDLER_TYPE(
        HandshakeHandler, void(error_code))>{
            std::move(init.completion_handler), *this, nullptr, host,
                target, &default_decorate_req}();
    return init.result.get();
}

template<class NextLayer, bool deflateSupported>
template<class HandshakeHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(
    HandshakeHandler, void(error_code))
stream<NextLayer, deflateSupported>::
async_handshake(response_type& res,
    string_view host,
        string_view target,
            HandshakeHandler&& handler)
{
    static_assert(is_async_stream<next_layer_type>::value,
        "AsyncStream requirements not met");
    BOOST_BEAST_HANDLER_INIT(
        HandshakeHandler, void(error_code));
    handshake_op<BOOST_ASIO_HANDLER_TYPE(
        HandshakeHandler, void(error_code))>{
            std::move(init.completion_handler), *this, &res, host,
                target, &default_decorate_req}();
    return init.result.get();
}

template<class NextLayer, bool deflateSupported>
template<class RequestDecorator, class HandshakeHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(
    HandshakeHandler, void(error_code))
stream<NextLayer, deflateSupported>::
async_handshake_ex(string_view host,
    string_view target,
        RequestDecorator const& decorator,
            HandshakeHandler&& handler)
{
    static_assert(is_async_stream<next_layer_type>::value,
        "AsyncStream requirements not met");
    static_assert(detail::is_request_decorator<
            RequestDecorator>::value,
        "RequestDecorator requirements not met");
    BOOST_BEAST_HANDLER_INIT(
        HandshakeHandler, void(error_code));
    handshake_op<BOOST_ASIO_HANDLER_TYPE(
        HandshakeHandler, void(error_code))>{
            std::move(init.completion_handler), *this, nullptr, host,
                target, decorator}();
    return init.result.get();
}

template<class NextLayer, bool deflateSupported>
template<class RequestDecorator, class HandshakeHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(
    HandshakeHandler, void(error_code))
stream<NextLayer, deflateSupported>::
async_handshake_ex(response_type& res,
    string_view host,
        string_view target,
            RequestDecorator const& decorator,
                HandshakeHandler&& handler)
{
    static_assert(is_async_stream<next_layer_type>::value,
        "AsyncStream requirements not met");
    static_assert(detail::is_request_decorator<
            RequestDecorator>::value,
        "RequestDecorator requirements not met");
    BOOST_BEAST_HANDLER_INIT(
        HandshakeHandler, void(error_code));
    handshake_op<BOOST_ASIO_HANDLER_TYPE(
        HandshakeHandler, void(error_code))>{
            std::move(init.completion_handler), *this, &res, host,
                target, decorator}();
    return init.result.get();
}

template<class NextLayer, bool deflateSupported>
void
stream<NextLayer, deflateSupported>::
handshake(string_view host,
    string_view target)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    error_code ec;
    handshake(
        host, target, ec);
    if(ec)
        BOOST_THROW_EXCEPTION(system_error{ec});
}

template<class NextLayer, bool deflateSupported>
void
stream<NextLayer, deflateSupported>::
handshake(response_type& res,
    string_view host,
        string_view target)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    error_code ec;
    handshake(res, host, target, ec);
    if(ec)
        BOOST_THROW_EXCEPTION(system_error{ec});
}

template<class NextLayer, bool deflateSupported>
template<class RequestDecorator>
void
stream<NextLayer, deflateSupported>::
handshake_ex(string_view host,
    string_view target,
        RequestDecorator const& decorator)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    static_assert(detail::is_request_decorator<
            RequestDecorator>::value,
        "RequestDecorator requirements not met");
    error_code ec;
    handshake_ex(host, target, decorator, ec);
    if(ec)
        BOOST_THROW_EXCEPTION(system_error{ec});
}

template<class NextLayer, bool deflateSupported>
template<class RequestDecorator>
void
stream<NextLayer, deflateSupported>::
handshake_ex(response_type& res,
    string_view host,
        string_view target,
            RequestDecorator const& decorator)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    static_assert(detail::is_request_decorator<
            RequestDecorator>::value,
        "RequestDecorator requirements not met");
    error_code ec;
    handshake_ex(res, host, target, decorator, ec);
    if(ec)
        BOOST_THROW_EXCEPTION(system_error{ec});
}

template<class NextLayer, bool deflateSupported>
void
stream<NextLayer, deflateSupported>::
handshake(string_view host,
    string_view target, error_code& ec)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    do_handshake(nullptr,
        host, target, &default_decorate_req, ec);
}

template<class NextLayer, bool deflateSupported>
void
stream<NextLayer, deflateSupported>::
handshake(response_type& res,
    string_view host,
        string_view target,
            error_code& ec)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    do_handshake(&res,
        host, target, &default_decorate_req, ec);
}

template<class NextLayer, bool deflateSupported>
template<class RequestDecorator>
void
stream<NextLayer, deflateSupported>::
handshake_ex(string_view host,
    string_view target,
        RequestDecorator const& decorator,
            error_code& ec)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    static_assert(detail::is_request_decorator<
            RequestDecorator>::value,
        "RequestDecorator requirements not met");
    do_handshake(nullptr,
        host, target, decorator, ec);
}

template<class NextLayer, bool deflateSupported>
template<class RequestDecorator>
void
stream<NextLayer, deflateSupported>::
handshake_ex(response_type& res,
    string_view host,
        string_view target,
            RequestDecorator const& decorator,
                error_code& ec)
{
    static_assert(is_sync_stream<next_layer_type>::value,
        "SyncStream requirements not met");
    static_assert(detail::is_request_decorator<
            RequestDecorator>::value,
        "RequestDecorator requirements not met");
    do_handshake(&res,
        host, target, decorator, ec);
}

//------------------------------------------------------------------------------

template<class NextLayer, bool deflateSupported>
template<class RequestDecorator>
void
stream<NextLayer, deflateSupported>::
do_handshake(
    response_type* res_p,
    string_view host,
    string_view target,
    RequestDecorator const& decorator,
    error_code& ec)
{
    response_type res;
    reset();
    detail::sec_ws_key_type key;
    {
        auto const req = build_request(
            key, host, target, decorator);
        do_pmd_config(req, is_deflate_supported{});
        http::write(stream_, req, ec);
    }
    if(ec)
        return;
    http::read(next_layer(), rd_buf_, res, ec);
    if(ec)
        return;
    on_response(res, key, ec);
    if(res_p)
        *res_p = std::move(res);
}

} // websocket
} // beast
} // boost

#endif

max_stars_repo_name: alexhenrie/poedit

max_issues_repo_name: alexhenrie/poedit

max_forks_repo_name: alexhenrie/poedit