text:
// @formatter:off
//
// Balau core C++ library
//
// Copyright (C) 2017 Bora Software (contact@borasoftware.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#ifndef COM_BORA_SOFTWARE__BALAU_NETWORK_HTTP_SERVER__NETWORK_TYPES
#define COM_BORA_SOFTWARE__BALAU_NETWORK_HTTP_SERVER__NETWORK_TYPES

///
/// @file NetworkTypes.hpp
///
/// Low level types used in networking code.
///

#include <Balau/Type/ToString.hpp>
#include <Balau/Type/FromString.hpp>
#include <Balau/Util/Enums.hpp>

#include <Balau/ThirdParty/Boost/Beast/Http/BasicFileBody.hpp>

#include <boost/asio/bind_executor.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/asio/strand.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/config.hpp>

namespace boost {

namespace asio::ip {

///
/// Print the IP address as a UTF-8 string.
///
/// @return a UTF-8 string representing the IP address
///
template <typename AllocatorT>
inline Balau::U8String<AllocatorT> toString(const address & a) {
	// Currently not possible to avoid std::allocator.
	return ::toString<AllocatorT>(a.to_string());
}

///
/// Print the IP address as a UTF-8 string.
///
/// @return a UTF-8 string representing the IP address
///
inline std::string toString(const address & a) {
	return a.to_string();
}

///
/// Print the endpoint as a UTF-8 string.
///
/// @return a UTF-8 string representing the endpoint
///
template <typename AllocatorT>
inline Balau::U8String<AllocatorT> toString(const tcp::endpoint & endpoint) {
	// Currently not possible to avoid std::allocator.
	return ::toString<AllocatorT>(endpoint.address().to_string(), ":", endpoint.port());
}

///
/// Print the endpoint as a UTF-8 string.
///
/// @return a UTF-8 string representing the endpoint
///
inline std::string toString(const tcp::endpoint & endpoint) {
	return ::toString(endpoint.address().to_string(), ":", endpoint.port());
}

///
/// Populate the endpoint by parsing the supplied string.
///
inline void fromString(tcp::endpoint & endpoint, std::string_view value) {
	// TODO improve implementation (ipv4 / ipv6).

	const auto v = std::string(value);
	static const std::regex numeric("[0-9]+");

	const bool isPortOnly = std::regex_match(v, numeric);

	if (isPortOnly) {
		unsigned short port;
		::fromString(port, value);
		endpoint = tcp::endpoint(make_address("127.0.0.1"), port);
		return;
	}

	auto lastColon = Balau::Util::Strings::lastIndexOf(value, ":");

	if (lastColon == std::string::npos) {
		// No port.
		endpoint = tcp::endpoint(make_address(v), 8080);
	} else {
		auto portStr = value.substr(lastColon + 1);

		if (Balau::Util::Strings::contains(portStr, "]")) {
			// No port.
			endpoint = tcp::endpoint(make_address(v), 8080);
		} else {
			auto ip = value.substr(0, lastColon);;
			unsigned short port;
			::fromString(port, portStr);
			endpoint = tcp::endpoint(make_address(std::string(ip)), port);
		}
	}
}

} // namespace asio::ip

namespace system {

///
/// Print the error code as a UTF-8 string.
///
/// @return a UTF-8 string representing the error code
///
template <typename AllocatorT>
inline Balau::U8String<AllocatorT> toString(const error_code & errorCode) {
	// Currently not possible to avoid std::allocator.
	return Balau::U8String<AllocatorT>(errorCode.message());
}

///
/// Print the error code as a UTF-8 string.
///
/// @return a UTF-8 string representing the error code
///
inline std::string toString(const error_code & errorCode) {
	return errorCode.message();
}

} // namespace system

namespace beast::http {

///
/// Print the network status as a UTF-8 string.
///
/// @return a UTF-8 string representing the network status
///
template <typename AllocatorT>
inline Balau::U8String<AllocatorT> toString(const status & s) {
	#ifdef BOOST_BEAST_NEW_API
		return Balau::U8String<AllocatorT>(obsolete_reason(s));
	#else
		auto u = Balau::Util::Enums::toUnderlying(s);
		return Balau::U8String<AllocatorT>(detail::status_to_string<>((unsigned int) u));
	#endif
}

///
/// Print the network status as a UTF-8 string.
///
/// @return a UTF-8 string representing the network status
///
inline std::string toString(const status & s) {
	#ifdef BOOST_BEAST_NEW_API
		return std::string(obsolete_reason(s));
	#else
		auto u = Balau::Util::Enums::toUnderlying(s);
		return std::string(detail::status_to_string<>((unsigned int) u));
	#endif
}

///
/// Print the network status as a UTF-8 string.
///
/// @return a UTF-8 string representing the network status
///
template <typename AllocatorT>
inline Balau::U8String<AllocatorT> toString(const verb & method) {
	return Balau::U8String<AllocatorT>(to_string(method));
}

///
/// Print the network status as a UTF-8 string.
///
/// @return a UTF-8 string representing the network status
///
inline std::string toString(const verb & method) {
	return std::string(to_string(method));
}

///
/// Print the network status as a UTF-8 string.
///
/// @return a UTF-8 string representing the network status
///
template <typename AllocatorT>
inline Balau::U8String<AllocatorT> toString(const field & f) {
	return Balau::U8String<AllocatorT>(to_string(f));
}

///
/// Print the network status as a UTF-8 string.
///
/// @return a UTF-8 string representing the network status
///
inline std::string toString(const field & f) {
	return std::string(to_string(f));
}

} // namespace beast::http

} // namespace boost

namespace Balau::Network {

///
/// An IP4 or IP6 address.
///
using Address = boost::asio::ip::address;

///
/// An IP address and port number.
///
using Endpoint = boost::asio::ip::tcp::endpoint;

///
/// A message body represented by a vector of 8 bit characters.
///
using CharVectorBody = boost::beast::http::vector_body<char>;

///
/// A message body represented by a UTF-8 string.
///
using StringBody = boost::beast::http::basic_string_body<char>;

///
/// A message body represented by a file on the filesystem.
///
using FileBody = Balau::Boost::Beast::Http::basic_file_body<boost::beast::file>;
//using FileBody = boost::beast::http::file_body;

///
/// The type of the message body represented by a file on the filesystem.
///
using FileBodyValue = FileBody::value_type;

///
/// A message body wth no content.
///
using EmptyBody = boost::beast::http::empty_body;

///
/// The request type.
///
template<class Body, class Fields = boost::beast::http::fields>
using Request = boost::beast::http::request<Body, Fields>;

///
/// A request with a string body.
///
using StringRequest = Request<StringBody>;

///
/// A request with a char vector body.
///
using CharVectorRequest = Request<CharVectorBody>;

///
/// The response type.
///
template<class Body, class Fields = boost::beast::http::fields>
using Response = boost::beast::http::response<Body, Fields>;

///
/// A response with a string body.
///
using StringResponse = Response<StringBody>;

///
/// A response with a char vector body.
///
using CharVectorResponse = Response<CharVectorBody>;

///
/// A response with an empty body.
///
using EmptyResponse = Response<EmptyBody>;

///
/// The HTTP method (GET, HEAD, POST).
///
using Method = boost::beast::http::verb;

///
/// An HTTP header field.
///
using Field = boost::beast::http::field;

///
/// A data buffer used in HTTP code.
///
using Buffer = boost::beast::flat_buffer;

///
/// Boost error codes returned from HTTP algorithms and operations.
///
using Error = boost::beast::http::error;

///
/// Boost system error.
///
using BoostSystemError = boost::system::system_error;

///
/// Boost system error codes.
///
using BoostSystemErrorCode = boost::system::error_code;

///
/// Boost HTTP file open modes.
///
using FileMode = boost::beast::file_mode;

///
/// Boost status code.
///
using Status = boost::beast::http::status;

///
/// The Boost SSL namespace.
///
namespace SSL = boost::asio::ssl;

///
/// The Boost TCP namespace.
///
using TCP = boost::asio::ip::tcp;

///
/// The Boost HTTP namespace.
///
namespace HTTP = boost::beast::http;

///
/// The Boost WebSocket namespace.
///
namespace WS = boost::beast::websocket;

///
/// WeSocket control frames.
///
using WsFrame = WS::frame_type;

///
/// Make an endpoint on the stack.
///
inline Endpoint makeEndpoint(const std::string & address, unsigned short port) {
	return Endpoint(boost::asio::ip::make_address(address), port);
}

///
/// Make an endpoint on the stack.
///
inline Endpoint makeEndpoint(const char * address, unsigned short port) {
	return Endpoint(boost::asio::ip::make_address(address), port);
}

///
/// Make an endpoint on the heap.
///
inline std::shared_ptr<Endpoint> newEndpoint(const std::string & address, unsigned short port) {
	return std::shared_ptr<Endpoint>(new Endpoint(boost::asio::ip::make_address(address), port));
}

///
/// Make an endpoint on the heap.
///
inline std::shared_ptr<Endpoint> newEndpoint(const char * address, unsigned short port) {
	return std::make_shared<Endpoint>(boost::asio::ip::make_address(address), port);
}

} // namespace Balau::Network

#endif // COM_BORA_SOFTWARE__BALAU_NETWORK_HTTP_SERVER__NETWORK_TYPES

max_stars_repo_name: borasoftware/balau

max_issues_repo_name: borasoftware/balau

max_forks_repo_name: borasoftware/balau


text:
/*==============================================================================
    Copyright (c) 2005-2010 Joel de Guzman
    Copyright (c) 2010 Thomas Heller

    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_PHOENIX_CORE_TERMINAL_HPP
#define BOOST_PHOENIX_CORE_TERMINAL_HPP

#include <boost/is_placeholder.hpp>
#include <boost/phoenix/core/actor.hpp>
#include <boost/phoenix/core/limits.hpp>
#include <boost/phoenix/core/meta_grammar.hpp>
#include <boost/phoenix/core/terminal_fwd.hpp>
#include <boost/proto/functional/fusion/at.hpp>
#include <boost/proto/matches.hpp>
#include <boost/proto/transform/lazy.hpp>
#include <boost/type_traits/remove_pointer.hpp>

#define BOOST_PHOENIX_DEFINE_CUSTOM_TERMINAL(Template, Terminal, IsNullary,    \
                                             EvalFun)                          \
  namespace boost {                                                            \
  namespace phoenix {                                                          \
  namespace result_of {                                                        \
  Template struct is_nullary<custom_terminal<Terminal>> : IsNullary {};        \
  }                                                                            \
  Template struct is_custom_terminal<Terminal> : mpl::true_ {};                \
                                                                               \
  Template struct custom_terminal<Terminal> : proto::call<EvalFun> {};         \
  }                                                                            \
  }                                                                            \
  /**/

namespace boost {
namespace phoenix {
template <typename T, typename Dummy>
struct is_custom_terminal : mpl::false_ {};

template <typename T, typename Dummy> struct custom_terminal;

namespace tag {
struct terminal /*: public proto::tag::terminal */ {};
} // namespace tag

namespace expression {
template <typename T, template <typename> class Actor = actor>
struct terminal : proto::terminal<T> {
  typedef proto::basic_expr<proto::tag::terminal
                            // tag::terminal //cannot change to use phoenix tag
                            // - breaks code.
                            ,
                            proto::term<T>, 0>
      base_type;
  typedef Actor<base_type> type;

  static const type make(T const &t) {
    // ?? Should the next line be Actor not actor which is the default?
    actor<base_type> const e = {base_type::make(t)};
    // Actor<base_type> const e = {base_type::make(t)};
    return e;
  }
};
} // namespace expression

namespace rule {
struct argument : proto::if_<boost::is_placeholder<proto::_value>()> {};

struct custom_terminal
    : proto::if_<boost::phoenix::is_custom_terminal<proto::_value>()> {};

struct terminal : proto::terminal<proto::_> {};
} // namespace rule

template <typename Dummy>
struct meta_grammar::case_<proto::tag::terminal, Dummy>
    : proto::or_<enable_rule<rule::argument, Dummy>,
                 enable_rule<rule::custom_terminal, Dummy>,
                 enable_rule<rule::terminal, Dummy>> {};

template <typename Dummy>
struct default_actions::when<rule::custom_terminal, Dummy>
    : proto::lazy<custom_terminal<proto::_value>(proto::_value, _context)> {};

namespace detail {
template <typename N> struct placeholder_idx : mpl::int_<N::value> {};
} // namespace detail

template <typename Grammar>
struct default_actions::when<rule::argument, Grammar>
    : proto::call<proto::functional::at(
          _env, proto::make<detail::placeholder_idx<
                    proto::make<boost::is_placeholder<proto::_value>()>>()>)> {
};
} // namespace phoenix
} // namespace boost

#endif

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
//
// Copyright (c) 2013-2016 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)
//

#ifndef BEAST_STREAMBUF_READSTREAM_HPP
#define BEAST_STREAMBUF_READSTREAM_HPP

#include <beast/async_completion.hpp>
#include <beast/streambuf.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/system/error_code.hpp>
#include <cstdint>
#include <utility>

namespace beast {

/** A `Stream` with attached `Streambuf` to buffer reads.

    This wraps a `Stream` implementation so that calls to write are
    passed through to the underlying stream, while calls to read will
    first consume the input sequence stored in a `Streambuf` which
    is part of the object.

    The use-case for this class is different than that of the
    `boost::asio::buffered_readstream`. It is designed to facilitate
    the use of `boost::asio::read_until`, and to allow buffers
    acquired during detection of handshakes to be made transparently
    available to callers. A hypothetical implementation of the
    buffered version of `boost::asio::ssl::stream::async_handshake`
    could make use of this wrapper.

    Uses:

    * Transparently leave untouched input acquired in calls
      to `boost::asio::read_until` behind for subsequent callers.

    * "Preload" a stream with handshake input data acquired
      from other sources.

    Example:
    @code
    // Process the next HTTP headers on the stream,
    // leaving excess bytes behind for the next call.
    //
    template<class Streambuf>
    void process_http_message(
        streambuf_readstream<Streambuf>& stream)
    {
        // Read up to and including the end of the HTTP
        // headers, leaving the sequence in the stream's
        // buffer. read_until may read past the end of the
        // headers; the return value will include only the
        // part up to the end of the delimiter.
        //
        std::size_t bytes_transferred =
            boost::asio::read_until(
                stream.next_layer(), stream.buffer(), "\r\n\r\n");

        // Use prepare_buffers() to limit the input
        // sequence to only the data up to and including
        // the trailing "\r\n\r\n".
        //
        auto header_buffers = prepare_buffers(
            bytes_transferred, stream.buffer().data());

        ...

        // Discard the portion of the input corresponding
        // to the HTTP headers.
        //
        stream.buffer().consume(bytes_transferred);

        // Everything we read from the stream
        // is part of the content-body.
    }
    @endcode

    @tparam Stream The type of stream to wrap.

    @tparam Streambuf The type of stream buffer to use.
*/
template<class Stream,
    class Streambuf = streambuf>
class streambuf_readstream
{
    using error_code = boost::system::error_code;

    template<class Buffers, class Handler>
    class read_some_op;

    Streambuf sb_;
    std::size_t size_ = 0;
    Stream next_layer_;

public:
    /// The type of the internal buffer
    using streambuf_type = Streambuf;

    /// The type of the next layer.
    using next_layer_type =
        typename std::remove_reference<Stream>::type;

    /// The type of the lowest layer.
    using lowest_layer_type =
        typename next_layer_type::lowest_layer_type;

    /// Move constructor.
    streambuf_readstream(streambuf_readstream&&) = default;

    /** Construct the wrapping stream.

        @param args Parameters forwarded to the `Stream` constructor.
    */
    template<class... Args>
    explicit
    streambuf_readstream(Args&&... args);

    /// Get a reference to the next layer.
    next_layer_type&
    next_layer()
    {
        return next_layer_;
    }

    /// Get a reference to the lowest layer.
    lowest_layer_type&
    lowest_layer()
    {
        return next_layer_.lowest_layer();
    }

    /// Get a const reference to the lowest layer.
    lowest_layer_type const&
    lowest_layer() const
    {
        return next_layer_.lowest_layer();
    }

    /// Get the io_service associated with the object.
    boost::asio::io_service&
    get_io_service()
    {
        return next_layer_.get_io_service();
    }

    /** Access the internal buffer.

        The internal buffer is returned. It is possible for the
        caller to break invariants with this function. For example,
        by causing the internal buffer size to increase beyond
        the caller defined maximum.
    */
    Streambuf&
    buffer()
    {
        return sb_;
    }

    /** Access the internal buffer.

        The internal buffer is returned. It is possible for the
        caller to break invariants with this function. For example,
        by causing the internal buffer size to increase beyond
        the caller defined maximum.
    */
    Streambuf const&
    buffer() const
    {
        return sb_;
    }

    /** Set the maximum buffer size.

        This changes the maximum size of the internal buffer used
        to hold read data. No bytes are discarded by this call. If
        the buffer size is set to zero, no more data will be buffered.

        Thread safety:
            The caller is responsible for making sure the call is
            made from the same implicit or explicit strand.

        @param size The number of bytes in the read buffer.

        @note This is a soft limit. If the new maximum size is smaller
        than the amount of data in the buffer, no bytes are discarded.
    */
    void
    reserve(std::size_t size)
    {
        size_ = size;
    }

    /// Write the given data to the stream. Returns the number of bytes written.
    /// Throws an exception on failure.
    template<class ConstBufferSequence>
    std::size_t
    write_some(ConstBufferSequence const& buffers)
    {
        return next_layer_.write_some(buffers);
    }

    /// Write the given data to the stream. Returns the number of bytes written,
    /// or 0 if an error occurred.
    template <class ConstBufferSequence>
    std::size_t
    write_some(ConstBufferSequence const& buffers,
        error_code& ec)
    {
        return next_layer_.write_some(buffers, ec);
    }

    /// Start an asynchronous write. The data being written must be valid for the
    /// lifetime of the asynchronous operation.
    template<class ConstBufferSequence, class WriteHandler>
    typename async_completion<
        WriteHandler, void(error_code)>::result_type
    async_write_some(ConstBufferSequence const& buffers,
        WriteHandler&& handler);

    /// Read some data from the stream. Returns the number of bytes read.
    /// Throws an exception on failure.
    template<class MutableBufferSequence>
    std::size_t
    read_some(MutableBufferSequence const& buffers);

    /// Read some data from the stream. Returns the number of bytes read
    /// or 0 if an error occurred.
    template<class MutableBufferSequence>
    std::size_t
    read_some(MutableBufferSequence const& buffers,
        error_code& ec);

    /// Start an asynchronous read. The buffer into which the data will be read
    /// must be valid for the lifetime of the asynchronous operation.
    template<class MutableBufferSequence, class ReadHandler>
    typename async_completion<
        ReadHandler, void(error_code)>::result_type
    async_read_some(MutableBufferSequence const& buffers,
        ReadHandler&& handler);
};

} // beast

#include <beast/impl/streambuf_readstream.ipp>

#endif


text:
// Copyright (C) 2013 Massachusetts Institute of Technology, Lincoln Laboratory
// License: Boost Software License   See LICENSE.txt for the full license.
// Authors: Davis E. King (davis@dlib.net)

#include "word_vects.h"
#include <dlib/matrix.h>
#include <dlib/statistics.h>
#include <dlib/sliding_buffer.h>
#include <map>
#include <mitie/group_tokenizer.h>
#include <mitie/unigram_tokenizer.h>

using namespace std;
using namespace dlib;
using namespace mitie;

typedef std::vector<std::pair<dlib::uint32, float> > sparse_vector_type;

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

unsigned long get_word_id (
    const std::map<std::string, unsigned long>& vocab,
    const std::string& word
)
{
    std::map<std::string, unsigned long>::const_iterator i;
    i = vocab.find(word);
    if (i != vocab.end())
        return i->second;
    else
        return vocab.size();
}

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

template <typename sparse_vector_type>
void get_left_and_right_context_vectors (
    const std::map<std::string, unsigned long>& vocab,
    const dlib::circular_buffer<std::string>& buf,
    sparse_vector_type& left_context,
    sparse_vector_type& right_context
)
{
    // get the left context vector
    left_context.clear();
    for (unsigned long i = 0; i < buf.size()/2; ++i)
    {
        left_context.push_back(make_pair(i*(vocab.size()+1) + get_word_id(vocab, buf[i]), 1));
    }
    make_sparse_vector_inplace(left_context);

    // get the right context vector
    right_context.clear();
    long k = 0;
    for (unsigned long i = buf.size()/2+1; i < buf.size(); ++i)
    {
        right_context.push_back(make_pair(k*(vocab.size()+1) + get_word_id(vocab, buf[i]), 1));
        ++k;
    }
    make_sparse_vector_inplace(right_context);
}

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

template <typename tokenizer_type>
void do_cca_on_windows (
    const std::map<std::string, unsigned long>& vocab,
    const long window_size,
    const long num_contexts,
    const long num_correlations,
    tokenizer_type& tok,
    matrix<float>& Ltrans,
    matrix<float>& Rtrans
)
{
    tok.reset();

    random_subset_selector<sparse_vector_type> left_contexts, right_contexts;
    left_contexts.set_max_size(num_contexts);
    right_contexts.set_max_size(num_contexts);

    dlib::circular_buffer<std::string> buf;
    buf.resize(window_size);

    sparse_vector_type left_vect, right_vect;
    cout << "Sample " << num_contexts << " random context vectors" << endl;

    std::string token;
    uint64 count = 0;
    while (tok(token))
    {
        buf.push_back(token);
        // skip the rest of the loop if buf isn't full yet
        ++count;
        if (count < buf.size())
        {
            continue;
        }

        if (left_contexts.next_add_accepts())
        {
            get_left_and_right_context_vectors(vocab, buf, left_vect, right_vect);
            left_contexts.add(left_vect);
            right_contexts.add(right_vect);
        }
        else
        {
            left_contexts.add();
            right_contexts.add();
        }
    }

    std::vector<sparse_vector_type> left(left_contexts.begin(), left_contexts.end());
    std::vector<sparse_vector_type> right(right_contexts.begin(), right_contexts.end());
    // free RAM
    left_contexts.set_max_size(0);
    right_contexts.set_max_size(0);

    cout << "Now do CCA (left size: " << left.size() << ", right size: " << right.size() << ")." << endl;
    cout << "correlations: "<< trans(cca(left, right, Ltrans, Rtrans, num_correlations, 40, 5));
    //print_true_correlations(left, right, Ltrans, Rtrans);
}

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

template <typename tokenizer_type>
void get_average_context_window_vector_per_word (
    const std::map<std::string, unsigned long>& vocab,
    const long window_size,
    tokenizer_type& tok,
    const matrix<float>& Ltrans,
    const matrix<float>& Rtrans,
    std::map<std::string, matrix<float,0,1> >& word_vectors
)
{
    tok.reset();
    word_vectors.clear();

    std::map<std::string,long> word_hits;
    dlib::circular_buffer<std::string> buf;
    buf.resize(window_size);

    sparse_vector_type left_vect, right_vect;

    std::string token;
    unsigned long count = 1;
    while (tok(token))
    {
        buf.push_back(token);
        // skip the rest of the loop if buf isn't full yet
        if (count < buf.size())
        {
            ++count;
            continue;
        }

        const std::string& center_word = buf[buf.size()/2];
        // only consider words in the vocab
        if (vocab.count(center_word) == 0)
            continue;

        get_left_and_right_context_vectors(vocab, buf, left_vect, right_vect);
        word_vectors[center_word] += join_cols(sparse_matrix_vector_multiply(trans(Ltrans), left_vect),
                                               sparse_matrix_vector_multiply(trans(Rtrans), right_vect));
        word_hits[center_word] += 1;
    }

    // Divide all the word vectors by their hits so they are mean vectors
    for (std::map<std::string,long>::iterator i = word_hits.begin(); i != word_hits.end(); ++i)
    {
        if (i->second > 1)
        {
            word_vectors[i->first] /= i->second;
        }
    }
}

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

std::map<std::string, unsigned long> make_word_to_int_mapping (
    const std::map<std::string, unsigned long>& words,
    unsigned long num
)
{
    std::vector<std::pair<unsigned long, std::string> > temp;
    temp.reserve(words.size());
    for (std::map<std::string, unsigned long>::const_iterator i = words.begin(); i != words.end(); ++i)
    {
        temp.push_back(make_pair(i->second, i->first));
    }

    std::sort(temp.rbegin(), temp.rend());

    // pick the most common words for our result set
    std::map<std::string, unsigned long> res;
    for (unsigned long i = 0; i < temp.size() && res.size() < num; ++i)
    {
        res[temp[i].second] = i;
    }
    return res;
}

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

void word_vects(const dlib::command_line_parser& parser)
{
    const long vocab_size = 200000;
    const long window_size = 9;
    const long num_contexts = 50000000;
    const long num_correlations = 90;

    ifstream fin("top_word_counts.dat", ios::binary);
    std::map<std::string, unsigned long> words;
    deserialize(words, fin);

    words = make_word_to_int_mapping(words,vocab_size);

    std::vector<dlib::file> files = get_files_in_directory_tree(directory(parser[0]), match_all());
    cout << "number of raw ASCII files found: " << files.size() << endl;
    group_tokenizer<unigram_tokenizer> tok(files);

    matrix<float> Ltrans, Rtrans;
    do_cca_on_windows(words, window_size,  num_contexts, num_correlations, tok, Ltrans, Rtrans);
    cout << "CCA done, now build up average word vectors" << endl;

    std::map<std::string, matrix<float,0,1> > word_vectors;
    get_average_context_window_vector_per_word(words, window_size, tok, Ltrans, Rtrans, word_vectors);

    std::ofstream fout("word_vects.dat", ios::binary);
    serialize(word_vectors, fout);
}

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

ext: cpp

max_stars_repo_name: maxmert/nlp-mitie

max_issues_repo_name: maxmert/nlp-mitie

max_forks_repo_name: maxmert/nlp-mitie


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

#include "textcomponent.h"

namespace py = boost::python;

void init_bindings();

int main()
{
    init_bindings();

    auto main_module = py::import("__main__");
    auto main_ns = main_module.attr("__dict__");

    try
    {
        py::exec_file("src/test.py", main_ns);
    }
    catch(py::error_already_set&)
    {
        PyErr_Print();
    }

    // according to Boost.Python docs, there is no need to Py_Finalize

    return 0;
}

ext: cc

max_stars_repo_name: Psidium/code-generator

max_issues_repo_name: pfsun/code-generator

max_forks_repo_name: pfsun/code-generator


text:
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
#include "qpid/replication/ReplicationExchange.h"
#include "qpid/replication/constants.h"
#include "qpid/Plugin.h"
#include "qpid/broker/Broker.h"
#include "qpid/broker/Queue.h"
#include "qpid/broker/QueueRegistry.h"
#include "qpid/broker/ExchangeRegistry.h"
#include "qpid/framing/reply_exceptions.h"
#include "qpid/log/Statement.h"
#include <boost/bind.hpp>

namespace qpid {
namespace replication {

using namespace qpid::broker;
using namespace qpid::framing;
using namespace qpid::replication::constants;

const std::string SEQUENCE_VALUE("qpid.replication-event.sequence");
ReplicationExchange::ReplicationExchange(const std::string& name, bool durable,
                                         const FieldTable& _args,
                                         QueueRegistry& qr,
                                         Manageable* parent, Broker* broker)
    : Exchange(name, durable, _args, parent, broker), queues(qr), sequence(args.getAsInt64(SEQUENCE_VALUE)), init(false)
{
    args.setInt64(SEQUENCE_VALUE, sequence);
    if (mgmtExchange != 0)
        mgmtExchange->set_type(typeName);
}

std::string ReplicationExchange::getType() const { return typeName; }

void ReplicationExchange::route(Deliverable& msg)
{
    const FieldTable* args = msg.getMessage().getApplicationHeaders();
    if (mgmtExchange != 0) {
        mgmtExchange->inc_msgReceives();
        mgmtExchange->inc_byteReceives(msg.contentSize());
    }
    if (args) {
        int eventType = args->getAsInt(REPLICATION_EVENT_TYPE);
        if (eventType) {
            if (isDuplicate(args)) {
                if (mgmtExchange != 0) {
                    mgmtExchange->inc_msgDrops();
                    mgmtExchange->inc_byteDrops(msg.contentSize());
                }
	        return;
	    }
            switch (eventType) {
              case ENQUEUE:
                handleEnqueueEvent(args, msg);
                return;
              case DEQUEUE:
                handleDequeueEvent(args, msg);
                return;
              default:
                throw IllegalArgumentException(QPID_MSG("Illegal value for " << REPLICATION_EVENT_TYPE << ": " << eventType));
            }
        }
    } else {
        QPID_LOG(warning, "Dropping unexpected message with no headers");
        if (mgmtExchange != 0) {
            mgmtExchange->inc_msgDrops();
            mgmtExchange->inc_byteDrops(msg.contentSize());
        }
    }
}

void ReplicationExchange::handleEnqueueEvent(const FieldTable* args, Deliverable& msg)
{
    std::string queueName = args->getAsString(REPLICATION_TARGET_QUEUE);
    Queue::shared_ptr queue = queues.find(queueName);
    if (queue) {

        SequenceNumber seqno1(args->getAsInt(QUEUE_MESSAGE_POSITION));

        // note that queue will ++ before enqueue.
        if (queue->getPosition() > --seqno1) // test queue.pos < seqnumber
        {
            QPID_LOG(error, "Cannot enqueue replicated message. Destination Queue " << queueName << " ahead of source queue");
            mgmtExchange->inc_msgDrops();
            mgmtExchange->inc_byteDrops(msg.contentSize());
        } else {
            queue->setPosition(seqno1);

            msg.getMessage().removeCustomProperty(REPLICATION_TARGET_QUEUE);
            msg.getMessage().removeCustomProperty(REPLICATION_EVENT_SEQNO);
            msg.getMessage().removeCustomProperty(REPLICATION_EVENT_TYPE);
            msg.getMessage().removeCustomProperty(QUEUE_MESSAGE_POSITION);
            msg.deliverTo(queue);
            QPID_LOG(debug, "Enqueued replicated message onto " << queueName);
            if (mgmtExchange != 0) {
                mgmtExchange->inc_msgRoutes();
                mgmtExchange->inc_byteRoutes( msg.contentSize());
            }
        }
    } else {
        QPID_LOG(error, "Cannot enqueue replicated message. Queue " << queueName << " does not exist");
        if (mgmtExchange != 0) {
            mgmtExchange->inc_msgDrops();
            mgmtExchange->inc_byteDrops(msg.contentSize());
        }
    }
}

void ReplicationExchange::handleDequeueEvent(const FieldTable* args, Deliverable& msg)
{
    std::string queueName = args->getAsString(REPLICATION_TARGET_QUEUE);
    Queue::shared_ptr queue = queues.find(queueName);
    if (queue) {
        SequenceNumber position(args->getAsInt(DEQUEUED_MESSAGE_POSITION));
        QueuedMessage dequeued;
        if (queue->acquireMessageAt(position, dequeued)) {
            queue->dequeue(0, dequeued);
            QPID_LOG(debug, "Processed replicated 'dequeue' event from " << queueName << " at position " << position);
            if (mgmtExchange != 0) {
                mgmtExchange->inc_msgRoutes();
                mgmtExchange->inc_byteRoutes(msg.contentSize());
            }
        } else {
            QPID_LOG(warning, "Could not acquire message " << position << " from " << queueName);
            if (mgmtExchange != 0) {
                mgmtExchange->inc_msgDrops();
                mgmtExchange->inc_byteDrops(msg.contentSize());
            }
        }
    } else {
        QPID_LOG(error, "Cannot process replicated 'dequeue' event. Queue " << queueName << " does not exist");
        if (mgmtExchange != 0) {
            mgmtExchange->inc_msgDrops();
            mgmtExchange->inc_byteDrops(msg.contentSize());
        }
    }
}

bool ReplicationExchange::isDuplicate(const FieldTable* args)
{
    if (!args->get(REPLICATION_EVENT_SEQNO)) return false;
    SequenceNumber seqno(args->getAsInt(REPLICATION_EVENT_SEQNO));
    if (!init) {
        init = true;
        sequence = seqno;
        return false;
    } else if (seqno > sequence) {
        if (seqno - sequence > 1) {
            QPID_LOG(error, "Gap in replication event sequence between: " << sequence << " and " << seqno);
        }
        sequence = seqno;
        return false;
    } else {
        QPID_LOG(info, "Duplicate detected: seqno=" << seqno << " (last seqno=" << sequence << ")");
        return true;
    }
}

bool ReplicationExchange::bind(Queue::shared_ptr /*queue*/, const std::string& /*routingKey*/, const FieldTable* /*args*/)
{
    throw NotImplementedException("Replication exchange does not support bind operation");
}

bool ReplicationExchange::unbind(Queue::shared_ptr /*queue*/, const std::string& /*routingKey*/, const FieldTable* /*args*/)
{
    throw NotImplementedException("Replication exchange does not support unbind operation");
}

bool ReplicationExchange::isBound(Queue::shared_ptr /*queue*/, const std::string* const /*routingKey*/, const FieldTable* const /*args*/)
{
    return false;
}

const std::string ReplicationExchange::typeName("replication");

void ReplicationExchange::encode(Buffer& buffer) const
{
    args.setInt64(std::string(SEQUENCE_VALUE), sequence);
    Exchange::encode(buffer);
}

struct ReplicationExchangePlugin : Plugin
{
    Broker* broker;

    ReplicationExchangePlugin();
    void earlyInitialize(Plugin::Target& target);
    void initialize(Plugin::Target& target);
    Exchange::shared_ptr create(const std::string& name, bool durable,
                                const framing::FieldTable& args,
                                management::Manageable* parent,
                                qpid::broker::Broker* broker);
};

ReplicationExchangePlugin::ReplicationExchangePlugin() : broker(0) {}

Exchange::shared_ptr ReplicationExchangePlugin::create(const std::string& name, bool durable,
                                                       const framing::FieldTable& args,
                                                       management::Manageable* parent, qpid::broker::Broker* broker)
{
    Exchange::shared_ptr e(new ReplicationExchange(name, durable, args, broker->getQueues(), parent, broker));
    return e;
}

void ReplicationExchangePlugin::earlyInitialize(Plugin::Target& target)
{
    broker = dynamic_cast<broker::Broker*>(&target);
    if (broker) {
        ExchangeRegistry::FactoryFunction f = boost::bind(&ReplicationExchangePlugin::create, this, _1, _2, _3, _4, _5);
        broker->getExchanges().registerType(ReplicationExchange::typeName, f);
        QPID_LOG(info, "Registered replication exchange");
    }
}

void ReplicationExchangePlugin::initialize(Target&) {}

static ReplicationExchangePlugin exchangePlugin;

}} // namespace qpid::replication

max_stars_repo_name: gcsideal/debian-qpid-cpp

max_issues_repo_name: gcsideal/debian-qpid-cpp

max_forks_repo_name: gcsideal/debian-qpid-cpp


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

#include "assert_type.h"
#include "map_policy.h"
#include "pomdp_io.h"
#include "pretty.h"
#include "simple_feature_value.h"
#include "feature_space.h"

namespace pomdp
{

MapPolicy::MapPolicy()
{
}

MapPolicy::MapPolicy(const char* path)
{
  loadFromFile(path);
}

MapPolicy::~MapPolicy()
{
}

/**
 * Loads a policy file.
 *
 * @return True on success.
 */
bool MapPolicy::loadFromFile(const char* path)
{
  if(!action_space_)
    ROS_WARN("No action space set! Policy values will not be validated.");

  int action;
  actions_.clear();

  // Open file.
  std::ifstream policy_file;
  policy_file.open(path);
  if(!policy_file.good())
  {
    ROS_ERROR("Unable to open policy file '%s'.", path);
    return false;
  }

  // Check Policy has what it needs to read the file.
  ROS_ASSERT_MSG(state_space_, "Requires StateSpace to be initialized!");

  // Read file.
  std::string line;
  while(!policy_file.eof())
  {
    std::getline(policy_file, line);
    if(policy_file.fail())
      continue;

    line = stripComment(line);
    if(isBlank(line))
      continue;

    // Read actions.
    std::stringstream line_ss(line);
    std::string action_str;
    line_ss >> action_str;
    if(!line_ss.fail())
    {
      if(!action_space_)
      {
        std::stringstream(action_str) >> action;
        actions_.push_back(action);
      }
      else
      {
        shared_ptr<FeatureValue> action_obj = action_space_->readFeatureValue(action_str);
        action = boost::dynamic_pointer_cast<SimpleFeatureValue>(action_obj)->asInt();
        if(action_space_->isValid(SimpleFeatureValue(action)))
          actions_.push_back(action);
      }
    }
  }

  int num_states = actions_.size();

  // Fail on empty policy.
  if(num_states == 0)
  {
    ROS_ERROR("Empty policy file '%s'.", path);
    return false;
  }

  // Fail on mismatched number of states. No need to check for NULL state_space_, already checked above.
  if(num_states != state_space_->getNumValues())
  {
    ROS_ERROR_STREAM("Number of states in policy (" << num_states << ") does not match number in ");
    ROS_ERROR_STREAM(*state_space_);
    return false;
  }

  // Use filename for name
  boost::filesystem::path bpath(path);
  setName(bpath.stem().string());

  is_init_ = true;
  return true;
}

/**
 * Determines action from current state.
 *
 * @param index Current state, within [0, num_states).
 * @return Action or -1 for failure.
 */
int MapPolicy::applyPolicy(const FeatureValue& index) const
{
  if(!isInit())
    return -1;
  ROS_ASSERT_CMD(state_space_->isValid(index), return -1);

//  try
//  {
//    const FeatureVectorValue& v = dynamic_cast<const FeatureVectorValue&>(index);
//    state = boost::make_shared<State>(&state_space_->toNumericState(v));
//  }
//  catch(std::bad_cast& e){}

  ROS_ASSERT_TYPE(index, SimpleFeatureValue);
  const SimpleFeatureValue& state = dynamic_cast<const SimpleFeatureValue&>(index);
  return actions_[state.asInt()];
}

} /* namespace pomdp */


text:
#pragma once

#include <string>
#include <vector>

#include <Eigen/Core>
#include <nlohmann/json.hpp>

#include "attributes.hpp"

namespace swr {

enum class Shading { WIREFRAME, FLAT, SMOOTH };

struct Scene {
    Vector4F background_color;
    Vector3F ambient_light;
    Float line_thickness;
    Shading shading;

    Camera camera;
    std::vector<Material> materials;
    std::vector<Light> lights;

    Scene(const nlohmann::json&);
};

/// Render a mesh with vertices V, edges E, faces F, and vertex material
/// indicies C
bool render_mesh(
    const Scene& scene,
    const Eigen::MatrixXd& V,
    const Eigen::MatrixXi& E,
    const Eigen::MatrixXi& F,
    const Eigen::VectorXi& C,
    const std::string& filename);

} // namespace swr

max_stars_repo_name: zfergus/software-renderer

max_issues_repo_name: zfergus/software-renderer

max_forks_repo_name: zfergus/software-renderer


text:
/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011 2011 Willow Garage, Inc.
 *    Suat Gedikli <gedikli@willowgarage.com>
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */
#include <openni_camera/openni_driver.h>
#include <openni_camera/openni_device_kinect.h>
#include <openni_camera/openni_device_primesense.h>
#include <openni_camera/openni_device_xtion.h>
#include <openni_camera/openni_device_oni.h>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <locale>
#include <cctype>
#include <map>

#ifndef _WIN32
#include <libusb-1.0/libusb.h>
#else
#include <boost/tokenizer.hpp>
#endif

using namespace std;
using namespace boost;

namespace openni_wrapper
{

OpenNIDriver::OpenNIDriver () throw (OpenNIException)
{
  // Initialize the Engine
  XnStatus status = context_.Init ();
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION ("initialization failed. Reason: %s", xnGetStatusString (status));

  updateDeviceList ();
}

unsigned OpenNIDriver::updateDeviceList () throw ()
{
  // clear current list of devices
  device_context_.clear ();
  // clear maps
  bus_map_.clear ();
  serial_map_.clear ();
  connection_string_map_.clear ();

  // enumerate all devices
  static xn::NodeInfoList node_info_list;
  XnStatus status = context_.EnumerateProductionTrees (XN_NODE_TYPE_DEVICE, NULL, node_info_list);
  if (status != XN_STATUS_OK && node_info_list.Begin () != node_info_list.End ())
    THROW_OPENNI_EXCEPTION ("enumerating devices failed. Reason: %s", xnGetStatusString (status));
  else if (node_info_list.Begin () == node_info_list.End ())
    return 0; // no exception

  for (xn::NodeInfoList::Iterator nodeIt = node_info_list.Begin (); nodeIt != node_info_list.End (); ++nodeIt)
  {
    connection_string_map_[(*nodeIt).GetCreationInfo ()] = device_context_.size();
    device_context_.push_back (DeviceContext (*nodeIt));
  }

  // enumerate depth nodes
  static xn::NodeInfoList depth_nodes;
  status = context_.EnumerateProductionTrees (XN_NODE_TYPE_DEPTH, NULL, depth_nodes, NULL);
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION ("enumerating depth generators failed. Reason: %s", xnGetStatusString (status));

  for (xn::NodeInfoList::Iterator nodeIt = depth_nodes.Begin (); nodeIt != depth_nodes.End (); ++nodeIt)
  {
    // check if to which device this node is assigned to
    for (xn::NodeInfoList::Iterator neededIt = (*nodeIt).GetNeededNodes ().Begin (); neededIt != (*nodeIt).GetNeededNodes ().End (); ++neededIt)
    {
      if ( connection_string_map_.count ((*neededIt).GetCreationInfo ()) )
      {
        unsigned device_index = connection_string_map_[(*neededIt).GetCreationInfo ()];
        device_context_[device_index].depth_node.reset (new xn::NodeInfo(*nodeIt));
      }
    }
  }

  // enumerate image nodes
  static xn::NodeInfoList image_nodes;
  static xn::EnumerationErrors enumeration_errors;
  status = context_.EnumerateProductionTrees (XN_NODE_TYPE_IMAGE, NULL, image_nodes, &enumeration_errors);
  if (status != XN_STATUS_OK)
  {
    // the asus pro doesn't produce images, so if the error is just "can't create node of the given type", then
    // we ignore it (that is what error code 65565 is). if this is some other error, for instance unable
    // to access the device due to permissions, then we throw an exception. -jbinney
    if((enumeration_errors.Begin()).Error() != 65565) {
      XnChar strError[1024];
      enumeration_errors.ToString(strError, 1024);
      THROW_OPENNI_EXCEPTION("enumerating image nodes failed. Reason: %s", strError);
    }
  }

  for (xn::NodeInfoList::Iterator nodeIt = image_nodes.Begin (); nodeIt != image_nodes.End (); ++nodeIt)
    {
      // check to which device this node is assigned to
      for (xn::NodeInfoList::Iterator neededIt = (*nodeIt).GetNeededNodes ().Begin (); neededIt != (*nodeIt).GetNeededNodes ().End (); ++neededIt)
        {
          if ( connection_string_map_.count ((*neededIt).GetCreationInfo ()) )
            {
              unsigned device_index = connection_string_map_[(*neededIt).GetCreationInfo ()];
              device_context_[device_index].image_node.reset (new xn::NodeInfo(*nodeIt));
            }
        }
    }

  // enumerate IR nodes
  static xn::NodeInfoList ir_nodes;
  status = context_.EnumerateProductionTrees (XN_NODE_TYPE_IR, NULL, ir_nodes, NULL);
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION ("enumerating IR generators failed. Reason: %s", xnGetStatusString (status));

  for (xn::NodeInfoList::Iterator nodeIt = ir_nodes.Begin (); nodeIt != ir_nodes.End (); ++nodeIt)
  {
    // check if to which device this node is assigned to
    for (xn::NodeInfoList::Iterator neededIt = (*nodeIt).GetNeededNodes ().Begin (); neededIt != (*nodeIt).GetNeededNodes ().End (); ++neededIt)
    {
      if ( connection_string_map_.count ((*neededIt).GetCreationInfo ()) )
      {
        unsigned device_index = connection_string_map_[(*neededIt).GetCreationInfo ()];
        device_context_[device_index].ir_node.reset (new xn::NodeInfo(*nodeIt));
      }
    }
  }

#ifndef _WIN32
  // add context object for each found device
  for (unsigned deviceIdx = 0; deviceIdx < device_context_.size (); ++deviceIdx)
  {
    // register bus@address to the corresponding context object
    unsigned short vendor_id;
    unsigned short product_id;
    unsigned char bus;
    unsigned char address;
    sscanf (device_context_[deviceIdx].device_node.GetCreationInfo (), "%hx/%hx@%hhu/%hhu", &vendor_id, &product_id, &bus, &address);
    bus_map_ [bus][address] = deviceIdx;
  }

  // get additional info about connected devices like serial number, vendor name and prduct name
  getDeviceInfos ();
  // build serial number -> device index map
  for (unsigned deviceIdx = 0; deviceIdx < device_context_.size (); ++deviceIdx)
  {
    std::string serial_number = getSerialNumber (deviceIdx);
    if (!serial_number.empty ())
      serial_map_[serial_number] = deviceIdx;
  }

#endif

  // redundant, but needed for Windows right now and also for Xtion
  for (unsigned deviceIdx = 0; deviceIdx < device_context_.size (); ++deviceIdx)
  {
    unsigned short product_id;
    unsigned short vendor_id;

    getDeviceType(device_context_[deviceIdx].device_node.GetCreationInfo (), vendor_id, product_id );

#if _WIN32
    if (vendor_id == 0x45e)
    {
      strcpy ((char*)device_context_[deviceIdx].device_node.GetDescription().strVendor, "Microsoft");
      strcpy ((char*)device_context_[deviceIdx].device_node.GetDescription().strName, "Xbox NUI Camera");
    }
    else
#endif
    if (vendor_id == 0x1d27 && device_context_[deviceIdx].image_node.get () == 0)
    {
      strcpy ((char*)device_context_[deviceIdx].device_node.GetDescription().strVendor, "ASUS");
      strcpy ((char*)device_context_[deviceIdx].device_node.GetDescription().strName, "Xtion Pro");
    }
  }
  return (device_context_.size ());
}

void OpenNIDriver::stopAll () throw (OpenNIException)
{
  XnStatus status = context_.StopGeneratingAll ();
  if (status != XN_STATUS_OK)
    THROW_OPENNI_EXCEPTION ("stopping all streams failed. Reason: %s", xnGetStatusString (status));
}

OpenNIDriver::~OpenNIDriver () throw ()
{
  // no exception during destuctor
  try
  {
    stopAll ();
  }
  catch (...)
  {
  }

  context_.Shutdown ();
}

boost::shared_ptr<OpenNIDevice> OpenNIDriver::createVirtualDevice (const string& path, bool repeat, bool stream) const throw (OpenNIException)
{
  return boost::shared_ptr<OpenNIDevice> (new DeviceONI (context_, path, repeat, stream));
}

void OpenNIDriver::getPrimesenseSerial(xn::NodeInfo info, char* buffer, unsigned buf_size) const throw () {

        context_.CreateProductionTree(info);
        xn::Device device;

        if(info.GetInstance(device) != XN_STATUS_OK) {
            THROW_OPENNI_EXCEPTION ("couldn't get device instance for reading serial no.");
        }

        xn::DeviceIdentificationCapability d = device.GetIdentificationCap();

        d.GetSerialNumber(buffer,buf_size);

        device.Release();
}

boost::shared_ptr<OpenNIDevice> OpenNIDriver::getDeviceByIndex (unsigned index) const throw (OpenNIException)
{
  using namespace std;

  if (index >= device_context_.size ())
    THROW_OPENNI_EXCEPTION ("device index out of range. only %d devices connected but device %d requested.", device_context_.size (), index);
  boost::shared_ptr<OpenNIDevice> device = device_context_[index].device.lock ();
  if (!device)
  {
    unsigned short vendor_id;
    unsigned short product_id;
    getDeviceType (device_context_[index].device_node.GetCreationInfo (), vendor_id, product_id );

    if (vendor_id == 0x45e)
    {
      device = boost::shared_ptr<OpenNIDevice > (new DeviceKinect (context_, device_context_[index].device_node,
                                                                   *device_context_[index].image_node, *device_context_[index].depth_node,
                                                                   *device_context_[index].ir_node));
      device_context_[index].device = device;
    }
    else if (vendor_id == 0x1d27)
    {
      if (device_context_[index].image_node.get())
        device = boost::shared_ptr<OpenNIDevice > (new DevicePrimesense (context_, device_context_[index].device_node,
                                                                         *device_context_[index].image_node, *device_context_[index].depth_node,
                                                                         *device_context_[index].ir_node));
      else
        device = boost::shared_ptr<OpenNIDevice > (new DeviceXtionPro (context_, device_context_[index].device_node,
                                                                       *device_context_[index].depth_node, *device_context_[index].ir_node));
      device_context_[index].device = device;
    }
    else
    {
      THROW_OPENNI_EXCEPTION ("vendor %s (%s) known by primesense driver, but not by ros driver. Contact maintainer of the ros driver.",
                              getVendorName (index), vendor_id);
    }
  }
  return (device);
}

#ifndef _WIN32
boost::shared_ptr<OpenNIDevice>
OpenNIDriver::getDeviceBySerialNumber (const std::string& serial_number) const throw (OpenNIException)
{
  std::map<std::string, unsigned>::const_iterator it = serial_map_.find (serial_number);

  if (it != serial_map_.end ())
  {
    return getDeviceByIndex (it->second);
  }

  THROW_OPENNI_EXCEPTION ("No device with serial number \'%s\' found", serial_number.c_str ());

  // because of warnings!!!
  return (boost::shared_ptr<OpenNIDevice > ((OpenNIDevice*)NULL));
}

boost::shared_ptr<OpenNIDevice>
OpenNIDriver::getDeviceByAddress (unsigned char bus, unsigned char address) const throw (OpenNIException)
{
  std::map<unsigned char, std::map<unsigned char, unsigned> >::const_iterator busIt = bus_map_.find (bus);
  if (busIt != bus_map_.end ())
  {
    std::map<unsigned char, unsigned>::const_iterator devIt;
    // Interpret invalid address 0 as "open an arbitrary device on this bus"
    if (address == 0)
      devIt = busIt->second.begin ();
    else
      devIt = busIt->second.find (address);

    if (devIt != busIt->second.end ())
    {
      return getDeviceByIndex (devIt->second);
    }
  }

  THROW_OPENNI_EXCEPTION ("No device on bus: %d @ %d found", (int)bus, (int)address);

  // because of warnings!!!
  return (boost::shared_ptr<OpenNIDevice > ((OpenNIDevice*)NULL));
}

void
OpenNIDriver::getDeviceInfos () throw ()
{
  libusb_context *context = NULL;
  int result;
  result = libusb_init (&context); //initialize a library session

  if (result < 0)
    return;

  libusb_device **devices;
  int count = libusb_get_device_list (context, &devices);
  if (count < 0)
    return;

  for (int devIdx = 0; devIdx < count; ++devIdx)
  {
    libusb_device* device = devices[devIdx];
    uint8_t busId = libusb_get_bus_number (device);
    std::map<unsigned char, std::map<unsigned char, unsigned> >::const_iterator busIt = bus_map_.find (busId);
    if (busIt == bus_map_.end ())
      continue;

    uint8_t address = libusb_get_device_address (device);
    std::map<unsigned char, unsigned>::const_iterator addressIt = busIt->second.find (address);
    if (addressIt == busIt->second.end ())
      continue;

    unsigned nodeIdx = addressIt->second;
    xn::NodeInfo& current_node = device_context_[nodeIdx].device_node;

    libusb_device_descriptor descriptor;
    result = libusb_get_device_descriptor (devices[devIdx], &descriptor);

    if (result < 0)
    {
      current_node.SetInstanceName ("");
    }
    else
    {
      libusb_device_handle* dev_handle;
      result = libusb_open (device, &dev_handle);
      if (result < 0)
      {
        current_node.SetInstanceName ("");
      }
      else
      {
        unsigned char buffer[1024];

        int len = libusb_get_string_descriptor_ascii (dev_handle, descriptor.iSerialNumber, buffer, 1024);
        if (len > 4)
          current_node.SetInstanceName ((char*)buffer);
        else
          current_node.SetInstanceName ("");

        libusb_close (dev_handle);
      }
    }
  }
  libusb_free_device_list (devices, 1);
  libusb_exit (context);
}
#endif

const char* OpenNIDriver::getSerialNumber (unsigned index) const throw ()
{
#ifndef _WIN32

    DeviceContext con = device_context_[index];
    const char* openni_serial = con.device_node.GetInstanceName ();

    if (strlen(openni_serial)>0 && strcmp(openni_serial, "Device1")) {
        return openni_serial;
    } else {
        char *primesense_serial = (char*)malloc(XN_MAX_NAME_LENGTH); // memleak
        getPrimesenseSerial(con.device_node, primesense_serial, XN_MAX_NAME_LENGTH);

        return primesense_serial;
    }

#else
  return "";
#endif
}

void OpenNIDriver::getDeviceType (const std::string& connectionString, unsigned short& vendorId, unsigned short& productId)
{
#if _WIN32
    // expected format: "\\?\usb#vid_[ID]&pid_[ID]#[SERIAL]#{GUID}"
    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
    boost::char_separator<char> separators("#&_");
    tokenizer tokens(connectionString, separators);

    unsigned int tokenIndex = 0;
    for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter, tokenIndex++)
    {
        std::string tokenValue = *tok_iter;

        switch(tokenIndex) {
            case 2:    // the vendor ID
                sscanf(tokenValue.c_str(), "%hx", &vendorId);
                break;
            case 4: // the product ID
                sscanf(tokenValue.c_str(), "%hx", &productId);
                break;
        }
    }
#else
    unsigned char bus;
    unsigned char address;
    sscanf (connectionString.c_str(), "%hx/%hx@%hhu/%hhu", &vendorId, &productId, &bus, &address);
#endif
}

const char* OpenNIDriver::getConnectionString (unsigned index) const throw ()
{
  return device_context_[index].device_node.GetCreationInfo ();
}

const char* OpenNIDriver::getVendorName (unsigned index) const throw ()
{
  return device_context_[index].device_node.GetDescription ().strVendor;
}

const char* OpenNIDriver::getProductName (unsigned index) const throw ()
{
  return device_context_[index].device_node.GetDescription ().strName;
}

unsigned short OpenNIDriver::getVendorID (unsigned index) const throw ()
{
  unsigned short vendor_id;
  unsigned short product_id;
#ifndef _WIN32
  unsigned char bus;
  unsigned char address;
  sscanf (device_context_[index].device_node.GetCreationInfo (), "%hx/%hx@%hhu/%hhu", &vendor_id, &product_id, &bus, &address);

#else
  getDeviceType (device_context_[index].device_node.GetCreationInfo (), vendor_id, product_id);
#endif
  return vendor_id;
}

unsigned short OpenNIDriver::getProductID (unsigned index) const throw ()
{
  unsigned short vendor_id;
  unsigned short product_id;
#ifndef _WIN32
  unsigned char bus;
  unsigned char address;
  sscanf (device_context_[index].device_node.GetCreationInfo (), "%hx/%hx@%hhu/%hhu", &vendor_id, &product_id, &bus, &address);

#else
  getDeviceType (device_context_[index].device_node.GetCreationInfo (), vendor_id, product_id);
#endif
  return product_id;
}

unsigned char OpenNIDriver::getBus (unsigned index) const throw ()
{
  unsigned char bus = 0;
#ifndef _WIN32
  unsigned short vendor_id;
  unsigned short product_id;
  unsigned char address;
  sscanf (device_context_[index].device_node.GetCreationInfo (), "%hx/%hx@%hhu/%hhu", &vendor_id, &product_id, &bus, &address);
#endif
  return bus;
}

unsigned char OpenNIDriver::getAddress (unsigned index) const throw ()
{
  unsigned char address = 0;
#ifndef _WIN32
  unsigned short vendor_id;
  unsigned short product_id;
  unsigned char bus;
  sscanf (device_context_[index].device_node.GetCreationInfo (), "%hx/%hx@%hhu/%hhu", &vendor_id, &product_id, &bus, &address);
#endif
  return address;
}

OpenNIDriver::DeviceContext::DeviceContext (const xn::NodeInfo& device, xn::NodeInfo* image, xn::NodeInfo* depth, xn::NodeInfo* ir)
: device_node (device)
, image_node (image)
, depth_node (depth)
, ir_node (ir)
{
}

OpenNIDriver::DeviceContext::DeviceContext (const xn::NodeInfo& device)
: device_node (device)
, image_node ((xn::NodeInfo*)0)
, depth_node ((xn::NodeInfo*)0)
, ir_node ((xn::NodeInfo*)0)
{
}

OpenNIDriver::DeviceContext::DeviceContext (const DeviceContext& other)
: device_node (other.device_node)
, image_node (other.image_node)
, depth_node (other.depth_node)
, ir_node (other.ir_node)
, device (other.device)
{
}

} // namespace


text:
#pragma once

#include <cstdio>
#include <stdexcept>
#include <boost/dynamic_bitset.hpp>

class Neighbours {
public:

    Neighbours(uint16_t dim): dim(dim) {}

    void reset(uint8_t* screen) {
        this->screen = screen;
        size_=4;
        mask = 1;
        col = 1;
        row = 1;
    }

    size_t size() const { return size_; };

    void push_back(uint8_t) {
        size_++;
        mask <<= 1;
        if (mask==0){
            mask = 1;
            col++;
            if (col == dim-1) {
                row++;
                col = 1;
            }
        }
    };

    bool operator[](size_t pos) const {

        uint8_t pixel;

//printf("pos=%lu row=%d col=%d mask=%d\n", pos, row, col, mask);

        switch(size_ - 1 - pos) {
            case 0:
                pixel = at(row, col-1);
                break;
            case 1:
                pixel = at(row-1, col);
                break;
            case 2:
                pixel = at(row-1, col-1);
                break;
            case 3:
                pixel = at(row-1, col+1);
                break;
            default:
                throw std::logic_error("only 4 parents");
        }
        return (pixel & mask) > 0;
    };

private:

    uint8_t at(size_t r, size_t c) const {
        size_t i = r*dim+c;
        return screen[i];
    }

    uint8_t mask;
    uint16_t col;
    uint16_t row;
    uint8_t* screen;

    const uint16_t dim;
    size_t size_{4};
};


text:
//  (C) Copyright John maddock 1999.
//  (C) David Abrahams 2002.  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)
//
// use this header as a workaround for missing <limits>

//  See http://www.boost.org/libs/compatibility/index.html for documentation.

#ifndef BOOST_LIMITS
#define BOOST_LIMITS

#include <boost/config.hpp>

#ifdef BOOST_NO_LIMITS
# include <boost/detail/limits.hpp>
#else
# include <limits>
#endif

#include <boost/detail/extended_integer.hpp>  // for BOOST_HAS_XINT, etc.

#if (defined(BOOST_HAS_LONG_LONG) && defined(BOOST_NO_LONG_LONG_NUMERIC_LIMITS)) \
      || (defined(BOOST_HAS_MS_INT64) && defined(BOOST_NO_MS_INT64_NUMERIC_LIMITS))
// Add missing specializations for numeric_limits:
#if !defined(BOOST_HAS_XINT) || !(BOOST_HAS_XINT)
#error "Shouldn't have gotten here based on preceeding preprocessor statements"
#endif
#define BOOST_LLT    ::boost::detail::xint_t
#define BOOST_ULLT  ::boost::detail::uxint_t

#include <climits>  // for CHAR_BIT

namespace std
{
  template<>
  class numeric_limits< BOOST_LLT >
  {
   public:

      BOOST_STATIC_CONSTANT(bool, is_specialized = true);
      static BOOST_LLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return BOOST_XINT_MIN; }
      static BOOST_LLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return BOOST_XINT_MAX; }
      BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT -1);
      BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT) - 1) * 301L / 1000);
      BOOST_STATIC_CONSTANT(bool, is_signed = true);
      BOOST_STATIC_CONSTANT(bool, is_integer = true);
      BOOST_STATIC_CONSTANT(bool, is_exact = true);
      BOOST_STATIC_CONSTANT(int, radix = 2);
      static BOOST_LLT epsilon() throw() { return 0; };
      static BOOST_LLT round_error() throw() { return 0; };

      BOOST_STATIC_CONSTANT(int, min_exponent = 0);
      BOOST_STATIC_CONSTANT(int, min_exponent10 = 0);
      BOOST_STATIC_CONSTANT(int, max_exponent = 0);
      BOOST_STATIC_CONSTANT(int, max_exponent10 = 0);

      BOOST_STATIC_CONSTANT(bool, has_infinity = false);
      BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false);
      BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false);
      BOOST_STATIC_CONSTANT(bool, has_denorm = false);
      BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false);
      static BOOST_LLT infinity() throw() { return 0; };
      static BOOST_LLT quiet_NaN() throw() { return 0; };
      static BOOST_LLT signaling_NaN() throw() { return 0; };
      static BOOST_LLT denorm_min() throw() { return 0; };

      BOOST_STATIC_CONSTANT(bool, is_iec559 = false);
      BOOST_STATIC_CONSTANT(bool, is_bounded = true);
      BOOST_STATIC_CONSTANT(bool, is_modulo = true);

      BOOST_STATIC_CONSTANT(bool, traps = false);
      BOOST_STATIC_CONSTANT(bool, tinyness_before = false);
      BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero);

  };

  template<>
  class numeric_limits< BOOST_ULLT >
  {
   public:

      BOOST_STATIC_CONSTANT(bool, is_specialized = true);
      static BOOST_ULLT min BOOST_PREVENT_MACRO_SUBSTITUTION (){ return (BOOST_ULLT) 0u; }
      static BOOST_ULLT max BOOST_PREVENT_MACRO_SUBSTITUTION (){ return BOOST_UXINT_MAX; }
      BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT);
      BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT)) * 301L / 1000);
      BOOST_STATIC_CONSTANT(bool, is_signed = false);
      BOOST_STATIC_CONSTANT(bool, is_integer = true);
      BOOST_STATIC_CONSTANT(bool, is_exact = true);
      BOOST_STATIC_CONSTANT(int, radix = 2);
      static BOOST_ULLT epsilon() throw() { return 0; };
      static BOOST_ULLT round_error() throw() { return 0; };

      BOOST_STATIC_CONSTANT(int, min_exponent = 0);
      BOOST_STATIC_CONSTANT(int, min_exponent10 = 0);
      BOOST_STATIC_CONSTANT(int, max_exponent = 0);
      BOOST_STATIC_CONSTANT(int, max_exponent10 = 0);

      BOOST_STATIC_CONSTANT(bool, has_infinity = false);
      BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false);
      BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false);
      BOOST_STATIC_CONSTANT(bool, has_denorm = false);
      BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false);
      static BOOST_ULLT infinity() throw() { return 0; };
      static BOOST_ULLT quiet_NaN() throw() { return 0; };
      static BOOST_ULLT signaling_NaN() throw() { return 0; };
      static BOOST_ULLT denorm_min() throw() { return 0; };

      BOOST_STATIC_CONSTANT(bool, is_iec559 = false);
      BOOST_STATIC_CONSTANT(bool, is_bounded = true);
      BOOST_STATIC_CONSTANT(bool, is_modulo = true);

      BOOST_STATIC_CONSTANT(bool, traps = false);
      BOOST_STATIC_CONSTANT(bool, tinyness_before = false);
      BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero);

  };
}
#endif

#endif

max_stars_repo_name: jonstewart/boost-svn

max_issues_repo_name: jonstewart/boost-svn

max_forks_repo_name: jonstewart/boost-svn


text:
//  (C) Copyright John Maddock 2010.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include "test.hpp"
#include "check_integral_constant.hpp"
#ifdef TEST_STD
#  include <type_traits>
#else
#  include <boost/type_traits/conditional.hpp>
#endif
#include <boost/type_traits/is_same.hpp>

TT_TEST_BEGIN(conditional)

BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_same< ::tt::conditional<true, int, long>::type, int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_same< ::tt::conditional<false, int, long>::type, long>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_same< ::tt::conditional<true, int, long>::type, long>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_same< ::tt::conditional<false, int, long>::type, int>::value), false);

TT_TEST_END

max_stars_repo_name: lijgame/boost


text:
/************************************************************************/
/*                                                                      */
/*       Copyright 2009 by Ullrich Koethe and Hans Meine                */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    The VIGRA Website is                                              */
/*        http://hci.iwr.uni-heidelberg.de/vigra/                       */
/*    Please direct questions, bug reports, and contributions to        */
/*        ullrich.koethe@iwr.uni-heidelberg.de    or                    */
/*        vigra@informatik.uni-hamburg.de                               */
/*                                                                      */
/*    Permission is hereby granted, free of charge, to any person       */
/*    obtaining a copy of this software and associated documentation    */
/*    files (the "Software"), to deal in the Software without           */
/*    restriction, including without limitation the rights to use,      */
/*    copy, modify, merge, publish, distribute, sublicense, and/or      */
/*    sell copies of the Software, and to permit persons to whom the    */
/*    Software is furnished to do so, subject to the following          */
/*    conditions:                                                       */
/*                                                                      */
/*    The above copyright notice and this permission notice shall be    */
/*    included in all copies or substantial portions of the             */
/*    Software.                                                         */
/*                                                                      */
/*    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND    */
/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   */
/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          */
/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       */
/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      */
/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      */
/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     */
/*    OTHER DEALINGS IN THE SOFTWARE.                                   */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_NUMPY_ARRAY_CONVERTERS_HXX
#define VIGRA_NUMPY_ARRAY_CONVERTERS_HXX

#include "numpy_array.hxx"
#include "metaprogramming.hxx"
#include <boost/python.hpp>
#include <boost/python/to_python_converter.hpp>
#include <set>

namespace vigra {

template <class Array>
PyObject * returnNumpyArray(Array const & a)
{
    PyObject * pa = a.pyObject();
    if(pa == 0)
        PyErr_SetString(PyExc_ValueError, "returnNumpyArray(): Conversion to Python failed, array has no data.");
    else
        Py_INCREF(pa);
    return pa;
}

VIGRA_EXPORT std::set<std::string> & exportedArrayKeys();

template <class ArrayType>
struct NumpyArrayConverter {};

template <unsigned int N, class T, class Stride>
struct NumpyArrayConverter<NumpyArray<N, T, Stride> >
{
    typedef NumpyArray<N, T, Stride> ArrayType;
    typedef typename ArrayType::ArrayTraits ArrayTraits;

    NumpyArrayConverter();

    static void* convertible(PyObject* obj);

    // from Python
    static void construct(PyObject* obj,
        boost::python::converter::rvalue_from_python_stage1_data* data);

    // to Python
    static PyObject* convert(ArrayType const& a)
    {
        return returnNumpyArray(a);
    }
};

template <unsigned int N, class T, class Stride>
NumpyArrayConverter<NumpyArray<N, T, Stride> >::NumpyArrayConverter()
{
    using namespace boost::python;

    converter::registration const * reg = converter::registry::query(type_id<ArrayType>());

    // register the to_python_converter only once
    // FIXME: I'm not sure if this is correct.
    if(!reg || !reg->rvalue_chain)
    {
        to_python_converter<ArrayType, NumpyArrayConverter>();
    }
    converter::registry::insert(&convertible, &construct, type_id<ArrayType>());
}

template <unsigned int N, class T, class Stride>
void * NumpyArrayConverter<NumpyArray<N, T, Stride> >::convertible(PyObject* obj)
{
    bool isCompatible = obj == Py_None || ArrayType::isStrictlyCompatible(obj);
    // std::cerr << "compatible for " << typeid(NumpyArray<N, T, Stride>).name() << ": " << isCompatible << "\n";
    return isCompatible
             ? obj
             : 0;
}

// from Python
template <unsigned int N, class T, class Stride>
void NumpyArrayConverter<NumpyArray<N, T, Stride> >::construct(PyObject* obj,
                   boost::python::converter::rvalue_from_python_stage1_data* data)
{
    void* const storage =
        ((boost::python::converter::rvalue_from_python_storage<ArrayType>* ) data)->storage.bytes;

    ArrayType * array = new (storage) ArrayType();
    if(obj != Py_None)
        array->makeReferenceUnchecked(obj);

    data->convertible = storage;
}

template <unsigned int N, class T, class Stride>
struct NumpyArrayConverter<MultiArrayView<N, T, Stride> >
: public NumpyArrayConverter<NumpyArray<N, T, Stride> >
{
    typedef NumpyArrayConverter<NumpyArray<N, T, Stride> > BaseType;
    typedef MultiArrayView<N, T, Stride> ArrayType;

    NumpyArrayConverter()
    {
        using namespace boost::python;
        converter::registry::insert(&BaseType::convertible, &BaseType::construct,
                                    type_id<ArrayType>());
    }
};

template <class Iter, class End>
struct RegisterNumpyArrayConverters
{
    static void exec()
    {
        typedef typename UnqualifiedType<typename boost::mpl::deref<Iter>::type>::type Type;
        NumpyArrayConverter<Type>();
        RegisterNumpyArrayConverters<typename boost::mpl::next<Iter>::type, End>::exec();
    }
};

template <class End>
struct RegisterNumpyArrayConverters<End, End>
{
    static void exec()
    {}
};

template <class Typelist>
void registerNumpyArrayConverters(Typelist)
{
    RegisterNumpyArrayConverters<typename boost::mpl::begin<Typelist>::type,
                                 typename boost::mpl::end<Typelist>::type >::exec();
}

template <class FN>
FN registerConverters(FN f)
{
    registerNumpyArrayConverters(boost::python::detail::get_signature(f));
    return f;
}

} // namespace vigra

namespace boost { namespace python {

#define VIGRA_PYTHON_MULTITYPE_FUNCTOR(functor_name, function) \
template <class T> \
struct functor_name##Impl \
{ \
    typedef functor_name##Impl type; \
     \
    static void def(const char * pythonName) \
    { \
        boost::python::def(pythonName, vigra::registerConverters(&function<T>)); \
    } \
     \
    template <class A1> \
    static void def(const char * pythonName, A1 const & a1) \
    { \
        boost::python::def(pythonName, vigra::registerConverters(&function<T>), a1); \
    } \
     \
    template <class A1, class A2> \
    static void def(const char * pythonName, A1 const & a1, A2 const & a2) \
    { \
        boost::python::def(pythonName, vigra::registerConverters(&function<T>), a1, a2); \
    } \
     \
    template <class A1, class A2, class A3> \
    static void def(const char * pythonName, A1 const & a1, A2 const & a2, A3 const & a3) \
    { \
        boost::python::def(pythonName, vigra::registerConverters(&function<T>), a1, a2, a3); \
    } \
}; \
 \
template <> \
struct functor_name##Impl<void> \
{ \
    typedef void type; \
}; \
 \
template <class T1, \
          class T2 = void, \
          class T3 = void, \
          class T4 = void, \
          class T5 = void, \
          class T6 = void, \
          class T7 = void, \
          class T8 = void, \
          class T9 = void, \
          class T10 = void, \
          class T11 = void, \
          class T12 = void> \
struct functor_name \
: public boost::python::TypeList<typename functor_name##Impl<T1>::type, \
         boost::python::TypeList<typename functor_name##Impl<T2>::type, \
         boost::python::TypeList<typename functor_name##Impl<T3>::type, \
         boost::python::TypeList<typename functor_name##Impl<T4>::type, \
         boost::python::TypeList<typename functor_name##Impl<T5>::type, \
         boost::python::TypeList<typename functor_name##Impl<T6>::type, \
         boost::python::TypeList<typename functor_name##Impl<T7>::type, \
         boost::python::TypeList<typename functor_name##Impl<T8>::type, \
         boost::python::TypeList<typename functor_name##Impl<T9>::type, \
         boost::python::TypeList<typename functor_name##Impl<T10>::type, \
         boost::python::TypeList<typename functor_name##Impl<T11>::type, \
         boost::python::TypeList<typename functor_name##Impl<T12>::type, \
         boost::python::TypeList<void, void> > > > > > > > > > > > > \
{};

template <class Head, class Tail>
struct TypeList
{
    typedef Head head;
    typedef Tail tail;
};

// in the sequel, the doc string is only registered with the last
// overload, so that it shows up only once
template <class Head, class Tail>
inline void multidef(char const* functor_name, TypeList<Head, Tail>)
{
    Head::def(functor_name);
    multidef(functor_name, Tail());
}

template <class Head, class Tail>
inline void multidef(char const* functor_name, TypeList<Head, Tail>, const char * help)
{
    Head::def(functor_name);
    multidef(functor_name, Tail(), help);
}

template <class Head, class Tail, class Args>
inline void multidef(char const* functor_name, TypeList<Head, Tail>, Args const& args)
{
    Head::def(functor_name, args);
    multidef(functor_name, Tail(), args);
}

template <class Head, class Tail, class Args>
inline void multidef(char const* functor_name, TypeList<Head, Tail>, Args const& args, char const * help)
{
    Head::def(functor_name, args);
    multidef(functor_name, Tail(), args, help);
}

template <class Head, class Tail>
inline void multidef(char const* functor_name, TypeList<Head, TypeList<void, Tail> >)
{
    Head::def(functor_name);
}

template <class Head, class Tail, class Args>
inline void multidef(char const* functor_name, TypeList<Head, TypeList<void, Tail> >, Args const& args)
{
    Head::def(functor_name, args);
}

template <class Head, class Tail>
inline void multidef(char const* functor_name, TypeList<Head, TypeList<void, Tail> >, const char * help)
{
    Head::def(functor_name, help);
}

template <class Head, class Tail, class Args>
inline void multidef(char const* functor_name, TypeList<Head, TypeList<void, Tail> >, Args const& args, const char * help)
{
    Head::def(functor_name, args, help);
}

}} // namespace boost::python

#endif // VIGRA_NUMPY_ARRAY_CONVERTERS_HXX

ext: hxx

max_stars_repo_name: RegiTheSter/vigra

max_issues_repo_name: RegiTheSter/vigra

max_forks_repo_name: RegiTheSter/vigra


text:
#include <smtbx/refinement/constraints/occupancy.h>

#include <boost/lambda/lambda.hpp>
#include <scitbx/array_family/tiny_algebra.h>

namespace smtbx { namespace refinement { namespace constraints {

  void
  dependent_occupancy
  ::linearise(uctbx::unit_cell const &unit_cell,
              sparse_matrix_type *jacobian_transpose)
  {
    scalar_parameter *o = reference();
    double k = multiplier/original_multiplier;
    if( as_one )
      value = k*o->value;
    else
      value = multiplier - k*o->value;

    if (!jacobian_transpose) return;
    sparse_matrix_type &jt = *jacobian_transpose;
    if( as_one )
      jt.col(index()) = k*jt.col(o->index());
    else
      jt.col(index()) = (-k)*jt.col(o->index());
  }

}}}


text:
/* -*-C++-*- */
/*
   (c) Copyright 2001-2005, Hewlett-Packard Development Company, LP

   See the file named COPYING for license details
*/

/** @file
    \brief Header file for Deque class, a double-ended queue.
*/

#ifndef LINTEL_DEQUE_HPP
#define LINTEL_DEQUE_HPP

#include <vector>

#include <boost/utility.hpp>

#include <Lintel/AssertBoost.hpp>
// don't use deque for runnable; it has horrid performance on
// HP-UX (~10us / insertion to empty deque) Instead, standard
// rules on a rotating vector, valid range is [q_front
// .. q_back -1] (wrapping), one slot is wasted, front ==
// back -> empty

/*!
    \class Deque
    \brief Double ended queue, standard array implementation
    \param T
    \par Type Requirements T
        T needs to be copy constructable
    \param Alloc
    \par Type Requirements Alloc
        An allocator, defaults to std::allocator<T>

    Deque implementation that has amortized constant-time performance,
    rather than log(n); g++ deque looks better since it does the linked list
    of multiple elements; performance comparison unclear.
*/
template <class T, class Alloc = std::allocator<T> >
class Deque : boost::noncopyable {
public:
    Deque(size_t default_size = 8)
	: q_front(0), q_back(0), q_size(default_size) {
	INVARIANT(q_size > 1, "Must have size at least 2\n");
	deque = allocator.allocate(q_size);
    }

    ~Deque() {
	allocator.deallocate(deque, q_size);
    }
    typedef Deque<T> mytype;

    T &front() {
	DEBUG_INVARIANT(!empty(), "front() on empty deque");
	return deque[q_front];
    }
    T &back() {
	DEBUG_INVARIANT(!empty(), "back() on empty dequeue");
	return deque[(q_back + q_size - 1) % q_size];
    }
    T &at(size_t pos) {
	DEBUG_INVARIANT(pos < size(), "invalid position for at()");
	return deque[(q_front + pos) % q_size];
    }
    void pop_front() {
	DEBUG_INVARIANT(!empty(), "pop_front() on empty dequeue");
	allocator.destroy(deque + q_front);
	q_front = (q_front + 1) % q_size;
    }
    void push_back(const T &val) {
	size_t back_next = (q_back + 1) % q_size;
	if (back_next != q_front) {
	    allocator.construct(deque + q_back, val);
	    q_back = back_next;
	} else {
	    push_expand(val);
	}
    }
    /// Add in an entire vector of values onto the back.
    void push_back(const std::vector<T> &vals) {
	typedef typename std::vector<T>::const_iterator vector_iterator;
	for(vector_iterator i = vals.begin();
	    i != vals.end(); ++i) {
	    push_back(*i);
	}
    }

    bool empty() const { return q_front == q_back;} ;
    size_t size() const { return (q_back + q_size - q_front) % q_size; }

    // TODO: Implement correct resize (reserve + push_back's, or pop_back's if we handle non-empty)
    void reserve(size_t new_size) {
	INVARIANT(empty(),"Lame implementation only does reserve when empty");
	INVARIANT(new_size > 0 && new_size < std::numeric_limits<size_t>::max(),
                  "Must have size at least 1, and at most size_t::max() - 1");
	new_size += 1; // for the empty entry that always exists
	q_front = q_back = 0;
	allocator.deallocate(deque, q_size);
	q_size = new_size;
	deque = allocator.allocate(q_size);
    }

    size_t capacity() const { return q_size - 1; }

    /// \brief an iterator for Deque's
    class iterator {
    public:
	typedef std::forward_iterator_tag iterator_category;

	typedef T value_type;
	typedef T &reference;
	typedef T *pointer;
	typedef ptrdiff_t difference_type;

        iterator(Deque *_mydeque, size_t pos)
	    : mydeque(_mydeque), cur_pos(pos)
	{ }
        iterator() : mydeque(NULL), cur_pos(-1)
        { }
        iterator(const iterator &it) : mydeque(it.mydeque), cur_pos(it.cur_pos)
        { }

        /// compares two iterators for equality
	bool operator==(const iterator &y) const {
	    DEBUG_SINVARIANT(mydeque == y.mydeque);
	    return cur_pos == y.cur_pos;
	}
        /// compares two iterators for inequality
	bool operator!=(const iterator &y) const {
	    DEBUG_SINVARIANT(mydeque == y.mydeque);
	    return cur_pos != y.cur_pos;
	}
        /// dereference the iterator
	T &operator *() {
	    DEBUG_INVARIANT(cur_pos < mydeque->q_size, "invalid use of iterator");
	    return mydeque->deque[cur_pos];
	}
        /// dereference the iterator
	T *operator ->() {
	    return &(operator *());
	}
        /// pre-increments the iterator
	iterator &operator++() { increment(); return *this; }
        /// post-increments the iterator
	iterator operator++(int) {
	    iterator tmp = *this;
	    increment();
	    return tmp;
	}
        /// pre-decrement the iterator
        iterator &operator--() { decrement(); return *this; }
        /// post-decrement the iterator
        iterator operator--(int) {
            iterator tmp = *this;
            decrement();
            return tmp;
        }

        // TODO: We are missing (n + a) variant of + and - operator, as defined by
        // RandomAccessIterator characteristics, where a is iterator type and n is integral type.
        /// adds diff and returns the iterator
        iterator operator+(ptrdiff_t diff) {
            DEBUG_SINVARIANT(inRangePlus(diff));
            return iterator(mydeque, static_cast<size_t>(cur_pos + diff) % mydeque->q_size);
        }
        /// subtracts diff and returns the iterator
        iterator operator-(ptrdiff_t diff) {
            DEBUG_SINVARIANT(inRangeMinus(diff));
            return iterator(mydeque, static_cast<size_t>(cur_pos + mydeque->q_size
                                                         - diff) % mydeque->q_size);
        }
        /// compares if lhs iterator is smaller than rhs iterator
        bool operator<(const iterator &rhs) {
            DEBUG_INVARIANT(mydeque == rhs.mydeque, "invalid use of iterator");
            return logicalOffset(*this) < logicalOffset(rhs);
        }
        /// compares if lhs iterator is greater than rhs iterator
        bool operator>(const iterator &rhs) {
            DEBUG_INVARIANT(mydeque == rhs.mydeque, "invalid use of iterator");
            return logicalOffset(*this) > logicalOffset(rhs);
        }
        /// compares if lhs iterator is smaller than and equal to rhs iterator
        bool operator<=(const iterator &rhs) {
            DEBUG_INVARIANT(mydeque == rhs.mydeque, "invalid use of iterator");
            return logicalOffset(*this) <= logicalOffset(rhs);
        }
        /// compares if lhs iterator is greater than and equal to rhs iterator
        bool operator>=(const iterator &rhs) {
            DEBUG_INVARIANT(mydeque == rhs.mydeque, "invalid use of iterator");
            return logicalOffset(*this) >= logicalOffset(rhs);
        }
        /// adds diff to the iterator and returns the reference
        iterator &operator+=(ptrdiff_t diff) {
            DEBUG_SINVARIANT(inRangePlus(diff));
            cur_pos = static_cast<size_t>(cur_pos + diff) % mydeque->q_size;
            return *this;
        }
        /// subtracts diff to the iterator and returns the reference
        iterator &operator-=(ptrdiff_t diff) {
            DEBUG_SINVARIANT(inRangeMinus(diff));

            cur_pos = static_cast<size_t>(cur_pos + mydeque->q_size - diff) % mydeque->q_size;
            return *this;
        }
        /// returns difference between two iterators
        ptrdiff_t operator-(const iterator &rhs) const {
            DEBUG_INVARIANT(mydeque == rhs.mydeque, "invalid use of iterator");
            return logicalOffset(*this) - logicalOffset(rhs);
        }

    private:
        bool inRangeMinus(ptrdiff_t diff) { // safer to do minus/plus than -diff because of overflow
            return logicalOffset(*this) - diff >= 0 // <= size as iterator at ::end is ok
                && static_cast<size_t>(logicalOffset(*this) - diff) <= mydeque->size();
        }
        bool inRangePlus(ptrdiff_t diff) {
            return logicalOffset(*this) + diff >= 0 // <= size as iterator at ::end is ok
                && static_cast<size_t>(logicalOffset(*this) + diff) <= mydeque->size();
        }
	void increment() {
	    DEBUG_INVARIANT(cur_pos < mydeque->q_size, "invalid use of iterator");
	    cur_pos = (cur_pos + 1) % mydeque->q_size;
	}
        void decrement() {
            DEBUG_INVARIANT(logicalOffset(*this) > 0, "invalid use of iterator");
            cur_pos = (cur_pos + mydeque->q_size - 1) % mydeque->q_size;
        }
        // The logical offset in the deque, as if the deque was a vector starting at 0.
        inline int64_t logicalOffset(const iterator &i) const {
            return (i.cur_pos - i.mydeque->q_front + i.mydeque->q_size) % i.mydeque->q_size;
        }
	Deque *mydeque;
	size_t cur_pos;
    };

    iterator begin() {
	return iterator(this, q_front);
    }

    iterator end() {
	return iterator(this, q_back);
    }

    void clear() {
	if (!empty()) {
	    size_t max = q_back > q_front ? q_back : q_size;
	    for(size_t i = q_front; i < max; ++i) {
		allocator.destroy(deque + i);
	    }
	    if (q_back < q_front) {
		for(size_t i = 0; i < q_back; ++i) {
		    allocator.destroy(deque + i);
		}
	    }
	}
	q_front = q_back = 0;
	DEBUG_SINVARIANT(empty());
    }

    size_t memoryUsage() {
	return q_size * sizeof(T) + sizeof(Deque<T>);
    }

private:
    friend class iterator;
    void push_expand(const T &val) {
	T *new_deque = allocator.allocate(q_size * 2);
	size_t i = 0;
	// copy back to 0 offset
	if (q_front == 0) {
	    // special case if it's already 0 offset
	    for(;i<q_back;i++) {
		allocator.construct(new_deque + i, deque[i]);
		allocator.destroy(deque + i);
	    }
	} else {
	    for(size_t j=q_front; j<q_size;++j) {
		allocator.construct(new_deque + i, deque[j]);
		allocator.destroy(deque + j);
		++i;
	    }
	    for(size_t j=0;j<q_back;++j) {
		allocator.construct(new_deque + i, deque[j]);
		allocator.destroy(deque + j);
		++i;
	    }
	}
	INVARIANT(i == q_size-1, boost::format("internal %u %u %u %u")
                  % i % q_size % q_front % q_back);
	q_front = 0;
	allocator.construct(new_deque + i, val);
	q_back = i + 1;
	allocator.deallocate(deque, q_size);
	q_size = q_size * 2;
	deque = new_deque;
    }
    Alloc allocator;
    T *deque;
    size_t q_front;
    size_t q_back;
    size_t q_size;
};

void DequeTest();

#endif

max_stars_repo_name: sbu-fsl/Lintel

max_issues_repo_name: sbu-fsl/Lintel

max_forks_repo_name: sbu-fsl/Lintel


text:
No push, lets try to reduce deprecated support in this.
Keep NEEDS just in case.

--- boost/system/config.hpp.orig	2016-09-21 17:33:27.000000000 +0300
+++ boost/system/config.hpp
@@ -10,6 +10,12 @@
 #ifndef BOOST_SYSTEM_CONFIG_HPP
 #define BOOST_SYSTEM_CONFIG_HPP

+#if defined(__DragonFly__) && !defined(BOOST_SYSTEM_NEEDS_DEPRECATED)
+#ifndef BOOST_SYSTEM_NO_DEPRECATED
+#define	BOOST_SYSTEM_NO_DEPRECATED
+#endif
+#endif
+
 #include <boost/config.hpp>
 #include <boost/predef/platform.h>
 #include <boost/system/api_config.hpp>  // for BOOST_POSIX_API or BOOST_WINDOWS_API

max_stars_repo_name: liweitianux/DeltaPorts

max_issues_repo_name: liweitianux/DeltaPorts

max_forks_repo_name: liweitianux/DeltaPorts