<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

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 FLUSSPFERD_CREATE_HPP
#define FLUSSPFERD_CREATE_HPP

#ifndef PREPROC_DEBUG
#include "object.hpp"
#include "function.hpp"
#include "native_function.hpp"
#include "local_root_scope.hpp"
#include <boost/type_traits/is_function.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/range.hpp>
#include <boost/parameter/parameters.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/parameter/name.hpp>
#include <boost/parameter/binding.hpp>
#include <boost/type_traits.hpp>
#endif
#include "detail/limit.hpp"
#include <boost/preprocessor.hpp>
#include <boost/parameter/config.hpp>

namespace flusspferd {

class native_object_base;
class function;
class native_function_base;

/**
 * @name Creating functions
 * @addtogroup create_function
 */
//@{

/**
 * Create a new native function.
 *
 * @p ptr will be deleted by Flusspferd.
 *
 * @param ptr The native function object.
 * @return The new function.
 */
function create_native_function(native_function_base *ptr);

/**
 * Create a new native function as method of an object.
 *
 * The new method of object @p o will have the name @c ptr->name().
 *
 * @param o The object to add the method to.
 * @param ptr The native function object.
 * @return The new method.
 */
function create_native_function(object const &o, native_function_base *ptr);

#ifndef IN_DOXYGEN

#define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \
  template< \
    typename T \
    BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
  > \
  object old_create_native_functor_function( \
    object const &o \
    BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \
    typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \
  ) { \
    return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \
  } \
  /* */

BOOST_PP_REPEAT(
  BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
  FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION,
  ~
)

#else

/**
 * Create a new native function of type @p F as method of an object.
 *
 * @p F must inherit from #native_function_base.
 *
 * The new method of object @p o will have the name @c ptr->name().
 *
 * @param F The functor type.
 * @param o The object to add the method to.
 * @param ... The parameters to pass to the constructor of @p F.
 * @return The new method.
 */
template<typename F>
object create_native_functor_function(object const &o, ...);

#endif

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param fn The functor to call.
 * @param arity The function arity.
 * @return The new function.
 */
inline function create_native_function(
  object const &o,
  std::string const &name,
  boost::function<void (call_context &)> const &fn,
  unsigned arity = 0)
{
  return old_create_native_functor_function<native_function<void> >(
      o, fn, arity, name);
}

/**
 * Create a new native method of an object.
 *
 * @param T The function signature to use.
 * @param o The object to add the method to.
 * @param name The function name.
 * @param fn The functor to call.
 * @return The new function.
 */
template<typename T>
function create_native_function(
  object const &o,
  std::string const &name,
  boost::function<T> const &fn)
{
  return old_create_native_functor_function<native_function<T,false> >(o, fn, name);
}

/**
 * Create a new native method of an object.
 *
 * The first parameter passed will be 'this'.
 *
 * @param T The function signature to use.
 * @param o The object to add the method to.
 * @param name The function name.
 * @param fn The functor to call.
 * @return The new function.
 */
template<typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  boost::function<T> const &fn)
{
  return old_create_native_functor_function<native_function<T,true> >(o, fn, name);
}

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param fnptr The function to call (also determines the function signature).
 * @return The new method.
 */
template<typename T>
function create_native_function(
  object const &o,
  std::string const &name,
  T *fnptr,
  typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
  return create_native_function<T>(o, name, boost::function<T>(fnptr));
}

/**
 * Create a new native method of an object.
 *
 * The first parameter passed will be 'this'.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param fnptr The function to call (also determines the function signature).
 * @return The new method.
 */
template<typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  T *fnptr,
  typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
  return create_native_method<T>(o, name, boost::function<T>(fnptr));
}

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param memfnptr The member function to call.
 * @return The new function.
 */
template<typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  void (T::*memfnptr)(call_context &),
  unsigned arity = 0)
{
  return old_create_native_functor_function<native_member_function<void, T> >(
    o, memfnptr, arity, name);
}

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param memfnptr The member function to call (also determines the function
 *                 signature).
 * @return The new function.
 */
template<typename R, typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  R T::*memfnptr)
{
  return old_create_native_functor_function<native_member_function<R, T> >(
    o, memfnptr, name);
}

//@}

namespace param {
  BOOST_PARAMETER_NAME(container)
  BOOST_PARAMETER_NAME(name)
  BOOST_PARAMETER_NAME(attributes)

  BOOST_PARAMETER_NAME(length)
  BOOST_PARAMETER_NAME(contents)
  BOOST_PARAMETER_NAME(prototype)
  BOOST_PARAMETER_NAME(parent)

  BOOST_PARAMETER_NAME(argument_names)
  BOOST_PARAMETER_NAME(source)
  BOOST_PARAMETER_NAME(file)
  BOOST_PARAMETER_NAME(line)

  BOOST_PARAMETER_NAME(arguments)
}

namespace detail {
  template<typename Class>
  struct new_functor {
    template<typename>
    struct result {
      typedef Class &type;
    };

    Class &operator()() {
      return *new Class;
    }

#define FLUSSPFERD_NEW_FUNCTOR_INVOKE(z, n, d) \
    template< \
      BOOST_PP_ENUM_PARAMS(n, typename T) \
    > \
    Class &operator()( \
      BOOST_PP_ENUM_BINARY_PARAMS(n, T, &x) \
    ) \
    { \
      return *new Class(BOOST_PP_ENUM_PARAMS(n, x)); \
    } \
    /* */

    BOOST_PP_REPEAT_FROM_TO(
      1,
      BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
      FLUSSPFERD_NEW_FUNCTOR_INVOKE,
      ~)

#undef FLUSSPFERD_NEW_FUNCTOR_INVOKE
  };

  template<typename Class, typename Cond = void>
  struct create_traits;

  typedef param::tag::container container_spec;
  typedef param::tag::name name_spec;
  typedef param::tag::attributes attributes_spec;

  template<typename Class, typename ArgPack>
  typename boost::enable_if<
    boost::is_same<
      typename boost::parameter::binding<
        ArgPack,
        param::tag::container,
        void
      >::type,
      void
    >,
    typename create_traits<Class>::result_type
  >::type
  create_helper(ArgPack const &arg) {
    return create_traits<Class>::create(arg);
  }

  template<typename Class, typename ArgPack>
  typename boost::disable_if<
    boost::is_same<
      typename boost::parameter::binding<
        ArgPack,
        param::tag::container,
        void
      >::type,
      void
    >,
    typename create_traits<Class>::result_type
  >::type
  create_helper(ArgPack const &arg) {
    typedef create_traits<Class> traits;
    local_root_scope scope;

    typename traits::result_type result = traits::create(arg);

    object container(arg[param::_container]);
    container.define_property(
      arg[param::_name],
      result,
      arg[param::_attributes | dont_enumerate]);

    return result;
  }
}

template<typename Class>
typename detail::create_traits<Class>::result_type
create()
{
  return detail::create_traits<Class>::create();
}

#define FLUSSPFERD_CREATE(z, n, d) \
  template< \
    typename Class, \
    BOOST_PP_ENUM_PARAMS(n, typename T) \
  > \
  typename detail::create_traits<Class>::result_type \
  create( \
    BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \
    typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \
  { \
    typedef detail::create_traits<Class> traits; \
    return detail::create_helper<Class>(kw(BOOST_PP_ENUM_PARAMS(n, x))); \
  } \
  /* */

BOOST_PP_REPEAT_FROM_TO(
  1,
  BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY),
  FLUSSPFERD_CREATE,
  ~)

#undef FLUSSPFERD_CREATE

}

#endif
<commit_msg>new_create: add flusspferd::param::type<T> for passing types to flusspferd::create()<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
The MIT License

Copyright (c) 2008, 2009 Flusspferd contributors (see "CONTRIBUTORS" or
                                       http://flusspferd.org/contributors.txt)

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 FLUSSPFERD_CREATE_HPP
#define FLUSSPFERD_CREATE_HPP

#ifndef PREPROC_DEBUG
#include "object.hpp"
#include "function.hpp"
#include "native_function.hpp"
#include "local_root_scope.hpp"
#include <boost/type_traits/is_function.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/range.hpp>
#include <boost/parameter/parameters.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/parameter/name.hpp>
#include <boost/parameter/binding.hpp>
#include <boost/type_traits.hpp>
#endif
#include "detail/limit.hpp"
#include <boost/preprocessor.hpp>
#include <boost/parameter/config.hpp>

namespace flusspferd {

class native_object_base;
class function;
class native_function_base;

/**
 * @name Creating functions
 * @addtogroup create_function
 */
//@{

/**
 * Create a new native function.
 *
 * @p ptr will be deleted by Flusspferd.
 *
 * @param ptr The native function object.
 * @return The new function.
 */
function create_native_function(native_function_base *ptr);

/**
 * Create a new native function as method of an object.
 *
 * The new method of object @p o will have the name @c ptr->name().
 *
 * @param o The object to add the method to.
 * @param ptr The native function object.
 * @return The new method.
 */
function create_native_function(object const &o, native_function_base *ptr);

#ifndef IN_DOXYGEN

#define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \
  template< \
    typename T \
    BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \
  > \
  object old_create_native_functor_function( \
    object const &o \
    BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \
    typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \
  ) { \
    return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \
  } \
  /* */

BOOST_PP_REPEAT(
  BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
  FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION,
  ~
)

#else

/**
 * Create a new native function of type @p F as method of an object.
 *
 * @p F must inherit from #native_function_base.
 *
 * The new method of object @p o will have the name @c ptr->name().
 *
 * @param F The functor type.
 * @param o The object to add the method to.
 * @param ... The parameters to pass to the constructor of @p F.
 * @return The new method.
 */
template<typename F>
object create_native_functor_function(object const &o, ...);

#endif

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param fn The functor to call.
 * @param arity The function arity.
 * @return The new function.
 */
inline function create_native_function(
  object const &o,
  std::string const &name,
  boost::function<void (call_context &)> const &fn,
  unsigned arity = 0)
{
  return old_create_native_functor_function<native_function<void> >(
      o, fn, arity, name);
}

/**
 * Create a new native method of an object.
 *
 * @param T The function signature to use.
 * @param o The object to add the method to.
 * @param name The function name.
 * @param fn The functor to call.
 * @return The new function.
 */
template<typename T>
function create_native_function(
  object const &o,
  std::string const &name,
  boost::function<T> const &fn)
{
  return old_create_native_functor_function<native_function<T,false> >(o, fn, name);
}

/**
 * Create a new native method of an object.
 *
 * The first parameter passed will be 'this'.
 *
 * @param T The function signature to use.
 * @param o The object to add the method to.
 * @param name The function name.
 * @param fn The functor to call.
 * @return The new function.
 */
template<typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  boost::function<T> const &fn)
{
  return old_create_native_functor_function<native_function<T,true> >(o, fn, name);
}

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param fnptr The function to call (also determines the function signature).
 * @return The new method.
 */
template<typename T>
function create_native_function(
  object const &o,
  std::string const &name,
  T *fnptr,
  typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
  return create_native_function<T>(o, name, boost::function<T>(fnptr));
}

/**
 * Create a new native method of an object.
 *
 * The first parameter passed will be 'this'.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param fnptr The function to call (also determines the function signature).
 * @return The new method.
 */
template<typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  T *fnptr,
  typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)
{
  return create_native_method<T>(o, name, boost::function<T>(fnptr));
}

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param memfnptr The member function to call.
 * @return The new function.
 */
template<typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  void (T::*memfnptr)(call_context &),
  unsigned arity = 0)
{
  return old_create_native_functor_function<native_member_function<void, T> >(
    o, memfnptr, arity, name);
}

/**
 * Create a new native method of an object.
 *
 * @param o The object to add the method to.
 * @param name The method name.
 * @param memfnptr The member function to call (also determines the function
 *                 signature).
 * @return The new function.
 */
template<typename R, typename T>
function create_native_method(
  object const &o,
  std::string const &name,
  R T::*memfnptr)
{
  return old_create_native_functor_function<native_member_function<R, T> >(
    o, memfnptr, name);
}

//@}

namespace param {
  BOOST_PARAMETER_NAME(container)
  BOOST_PARAMETER_NAME(name)
  BOOST_PARAMETER_NAME(attributes)

  BOOST_PARAMETER_NAME(length)
  BOOST_PARAMETER_NAME(contents)
  BOOST_PARAMETER_NAME(prototype)
  BOOST_PARAMETER_NAME(parent)

  BOOST_PARAMETER_NAME(argument_names)
  BOOST_PARAMETER_NAME(source)
  BOOST_PARAMETER_NAME(file)
  BOOST_PARAMETER_NAME(line)

  BOOST_PARAMETER_NAME(arguments)

  /* For passing types. Like this: _param = param::type<int>() */
  template<typename T>
  struct type {};
}

namespace detail {
  template<typename Class>
  struct new_functor {
    template<typename>
    struct result {
      typedef Class &type;
    };

    Class &operator()() {
      return *new Class;
    }

#define FLUSSPFERD_NEW_FUNCTOR_INVOKE(z, n, d) \
    template< \
      BOOST_PP_ENUM_PARAMS(n, typename T) \
    > \
    Class &operator()( \
      BOOST_PP_ENUM_BINARY_PARAMS(n, T, &x) \
    ) \
    { \
      return *new Class(BOOST_PP_ENUM_PARAMS(n, x)); \
    } \
    /* */

    BOOST_PP_REPEAT_FROM_TO(
      1,
      BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),
      FLUSSPFERD_NEW_FUNCTOR_INVOKE,
      ~)

#undef FLUSSPFERD_NEW_FUNCTOR_INVOKE
  };

  template<typename Class, typename Cond = void>
  struct create_traits;

  typedef param::tag::container container_spec;
  typedef param::tag::name name_spec;
  typedef param::tag::attributes attributes_spec;

  template<typename Class, typename ArgPack>
  typename boost::enable_if<
    boost::is_same<
      typename boost::parameter::binding<
        ArgPack,
        param::tag::container,
        void
      >::type,
      void
    >,
    typename create_traits<Class>::result_type
  >::type
  create_helper(ArgPack const &arg) {
    return create_traits<Class>::create(arg);
  }

  template<typename Class, typename ArgPack>
  typename boost::disable_if<
    boost::is_same<
      typename boost::parameter::binding<
        ArgPack,
        param::tag::container,
        void
      >::type,
      void
    >,
    typename create_traits<Class>::result_type
  >::type
  create_helper(ArgPack const &arg) {
    typedef create_traits<Class> traits;
    local_root_scope scope;

    typename traits::result_type result = traits::create(arg);

    object container(arg[param::_container]);
    container.define_property(
      arg[param::_name],
      result,
      arg[param::_attributes | dont_enumerate]);

    return result;
  }
}

template<typename Class>
typename detail::create_traits<Class>::result_type
create()
{
  return detail::create_traits<Class>::create();
}

#define FLUSSPFERD_CREATE(z, n, d) \
  template< \
    typename Class, \
    BOOST_PP_ENUM_PARAMS(n, typename T) \
  > \
  typename detail::create_traits<Class>::result_type \
  create( \
    BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \
    typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \
  { \
    typedef detail::create_traits<Class> traits; \
    return detail::create_helper<Class>(kw(BOOST_PP_ENUM_PARAMS(n, x))); \
  } \
  /* */

BOOST_PP_REPEAT_FROM_TO(
  1,
  BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY),
  FLUSSPFERD_CREATE,
  ~)

#undef FLUSSPFERD_CREATE

}

#endif
<|endoftext|>


<commit_before>#ifndef UTILS_LOG_HPP
#define UTILS_LOG_HPP

#include <iostream>

// Older versions of Visual Studio fail compiling this file.
#ifdef DISABLE_LOGGING
#   define LOG(...)
#   define LOG_WARN(...)
#   define LOG_ERROR(...)
#   define LOG_DEBUG(...)
#   define LOG_DEBUG_WARN(...)
#   define LOG_DEBUG_ERROR(...)
#   define LOG_RAW(...)
#   define LOG_DEBUG_RAW(...)
#   define NLOGDEBUG
#else

#ifdef __linux__
#   define LOG_WARNING_PREFIX "\033[1;33mWARNING: \033[0m"
#   define LOG_ERROR_PREFIX "\033[1;31mERROR: \033[0m"
// #   define LOG_DEBUG_PREFIX "\033[;35mDEBUG: \033[0m"
#else
#   define LOG_WARNING_PREFIX "WARNING: "
#   define LOG_ERROR_PREFIX "ERROR: "
// #   define LOG_DEBUG_PREFIX "DEBUG: "
#endif

#define LOG_NORMAL_PREFIX ""
#define LOG_DEBUG_PREFIX "DEBUG: "

// Use like this:
// int x = 5;
// LOG("Some log entry");
// LOG("some variable: ", x);
// LOG_WARN("Something is wrong: ", x, "!");
#define LOG(...)        logutils::logfunc_init(__VA_ARGS__)
#define LOG_WARN(...)   logutils::logfunc_init<logutils::Warning>(__VA_ARGS__)
#define LOG_ERROR(...)  logutils::logfunc_init<logutils::Error, std::cerr>(__VA_ARGS__)

// Same as above but without appending a new line character at the end
#define LOG_RAW(...)        logutils::logfunc_init<logutils::Normal, std::cout, false>(__VA_ARGS__)

// Same as above but will only be displayed when NLOGDEBUG is NOT defined
#ifndef NLOGDEBUG
#   define LOG_DEBUG(...)           logutils::logfunc_init<logutils::Debug>(__VA_ARGS__)
#   define LOG_DEBUG_WARN(...)      logutils::logfunc_init<logutils::DebugWarning>(__VA_ARGS__)
#   define LOG_DEBUG_ERROR(...)     logutils::logfunc_init<logutils::DebugError, std::cerr>(__VA_ARGS__)
#   define LOG_DEBUG_RAW(...)       logutils::logfunc_init<logutils::Debug, std::cout, false>(__VA_ARGS__)
#else // No, no, Mr. Debug no here.
#   define LOG_DEBUG(...)
#   define LOG_DEBUG_WARN(...)
#   define LOG_DEBUG_ERROR(...)
#   define LOG_DEBUG_RAW(...)
#endif

// Use like this:
// int x = 5;
// LOG(LOG_DUMP(x));
#define LOG_DUMP(var) #var, ": ", (var)

namespace logutils
{
    enum LogLevel
    {
        Normal,
        Warning,
        Error,
        Debug,
        DebugWarning,
        DebugError
    };

    template<std::ostream& stream, bool nl>
    void logfunc_join()
    {
        if (nl)
            stream<<"\n";
        else
            stream.flush();
    }

    template<std::ostream& stream, bool nl, class T, class... Args>
    void logfunc_join(const T& arg, const Args&... rest)
    {
        stream<<arg;
        logfunc_join<stream, nl>(rest...);
    }

    template<LogLevel level = Normal, std::ostream& stream = std::cout, bool nl = true, class... Args>
    void logfunc_init(const Args&... args)
    {
        switch (level)
        {
            case DebugWarning:
            case Warning:
                stream<<LOG_WARNING_PREFIX;
                break;

            case DebugError:
            case Error:
                stream<<LOG_ERROR_PREFIX;
                break;

            case Normal:
            default:
                stream<<LOG_NORMAL_PREFIX;
                break;
        }
        if (level >= 3)
            stream<<LOG_DEBUG_PREFIX;
        logfunc_join<stream, nl>(args...);
    }
}
#endif

#endif
<commit_msg>Add macro that expands __PRETTY_FUNCTION__ depending on platform<commit_after>#ifndef UTILS_LOG_HPP
#define UTILS_LOG_HPP

#include <iostream>

// Older versions of Visual Studio fail compiling this file.
#ifdef DISABLE_LOGGING
#   define LOG(...)
#   define LOG_WARN(...)
#   define LOG_ERROR(...)
#   define LOG_DEBUG(...)
#   define LOG_DEBUG_WARN(...)
#   define LOG_DEBUG_ERROR(...)
#   define LOG_RAW(...)
#   define LOG_DEBUG_RAW(...)
#   define NLOGDEBUG
#else

#ifdef __linux__
#   define LOG_WARNING_PREFIX "\033[1;33mWARNING: \033[0m"
#   define LOG_ERROR_PREFIX "\033[1;31mERROR: \033[0m"
// #   define LOG_DEBUG_PREFIX "\033[;35mDEBUG: \033[0m"
#else
#   define LOG_WARNING_PREFIX "WARNING: "
#   define LOG_ERROR_PREFIX "ERROR: "
// #   define LOG_DEBUG_PREFIX "DEBUG: "
#endif

#define LOG_NORMAL_PREFIX ""
#define LOG_DEBUG_PREFIX "DEBUG: "

#ifdef _WIN32
#   define FUNC_STRING __FUNCSIG__
#else
#   define FUNC_STRING __PRETTY_FUNCTION__
#endif

// Use like this:
// int x = 5;
// LOG("Some log entry");
// LOG("some variable: ", x);
// LOG_WARN("Something is wrong: ", x, "!");
#define LOG(...)        logutils::logfunc_init(__VA_ARGS__)
#define LOG_WARN(...)   logutils::logfunc_init<logutils::Warning>(__VA_ARGS__)
#define LOG_ERROR(...)  logutils::logfunc_init<logutils::Error, std::cerr>(__VA_ARGS__)

// Same as above but without appending a new line character at the end
#define LOG_RAW(...)        logutils::logfunc_init<logutils::Normal, std::cout, false>(__VA_ARGS__)

// Same as above but will only be displayed when NLOGDEBUG is NOT defined
#ifndef NLOGDEBUG
#   define LOG_DEBUG(...)           logutils::logfunc_init<logutils::Debug>(__VA_ARGS__)
#   define LOG_DEBUG_WARN(...)      logutils::logfunc_init<logutils::DebugWarning>(__VA_ARGS__)
#   define LOG_DEBUG_ERROR(...)     logutils::logfunc_init<logutils::DebugError, std::cerr>(__VA_ARGS__)
#   define LOG_DEBUG_RAW(...)       logutils::logfunc_init<logutils::Debug, std::cout, false>(__VA_ARGS__)
#else // No, no, Mr. Debug no here.
#   define LOG_DEBUG(...)
#   define LOG_DEBUG_WARN(...)
#   define LOG_DEBUG_ERROR(...)
#   define LOG_DEBUG_RAW(...)
#endif

// Use like this:
// int x = 5;
// LOG(LOG_DUMP(x));
#define LOG_DUMP(var) #var, ": ", (var)

namespace logutils
{
    enum LogLevel
    {
        Normal,
        Warning,
        Error,
        Debug,
        DebugWarning,
        DebugError
    };

    template<std::ostream& stream, bool nl>
    void logfunc_join()
    {
        if (nl)
            stream<<"\n";
        else
            stream.flush();
    }

    template<std::ostream& stream, bool nl, class T, class... Args>
    void logfunc_join(const T& arg, const Args&... rest)
    {
        stream<<arg;
        logfunc_join<stream, nl>(rest...);
    }

    template<LogLevel level = Normal, std::ostream& stream = std::cout, bool nl = true, class... Args>
    void logfunc_init(const Args&... args)
    {
        switch (level)
        {
            case DebugWarning:
            case Warning:
                stream<<LOG_WARNING_PREFIX;
                break;

            case DebugError:
            case Error:
                stream<<LOG_ERROR_PREFIX;
                break;

            case Normal:
            default:
                stream<<LOG_NORMAL_PREFIX;
                break;
        }
        if (level >= 3)
            stream<<LOG_DEBUG_PREFIX;
        logfunc_join<stream, nl>(args...);
    }
}
#endif

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */
/**
 ** \file libport/select-ref.hh
 ** \brief Select between a non ref or a ref type.
 */

#ifndef LIBPORT_SELECT_REF_HH
# define LIBPORT_SELECT_REF_HH

# warn use libport/traits.hh instead.

namespace libport
{

  /*---------------.
  | ref addition.  |
  `---------------*/

  /// Return \a T&.
  template <typename T>
  struct ref_traits
  {
    typedef T& type;
  };

  // Do not form reference to references
  template <typename T>
  struct ref_traits<T&>
  {
    typedef T& type;
  };

  /*--------------.
  | ref removal.  |
  `--------------*/

  /// Return \a T without any reference.
  template <typename T>
  struct unref_traits
  {
    typedef T type;
  };

  template <typename T>
  struct unref_traits<T&>
  {
    typedef T type;
  };

} //namespace libport

#endif // !LIBPORT_SELECT_REF_HH
<commit_msg>fix cpp directive.<commit_after>/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */
/**
 ** \file libport/select-ref.hh
 ** \brief Select between a non ref or a ref type.
 */

#ifndef LIBPORT_SELECT_REF_HH
# define LIBPORT_SELECT_REF_HH

# warning "use libport/traits.hh instead."

namespace libport
{

  /*---------------.
  | ref addition.  |
  `---------------*/

  /// Return \a T&.
  template <typename T>
  struct ref_traits
  {
    typedef T& type;
  };

  // Do not form reference to references
  template <typename T>
  struct ref_traits<T&>
  {
    typedef T& type;
  };

  /*--------------.
  | ref removal.  |
  `--------------*/

  /// Return \a T without any reference.
  template <typename T>
  struct unref_traits
  {
    typedef T type;
  };

  template <typename T>
  struct unref_traits<T&>
  {
    typedef T type;
  };

} //namespace libport

#endif // !LIBPORT_SELECT_REF_HH
<|endoftext|>


<commit_before>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author 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.

*/

#ifndef TORRENT_ALLOCA

#include "libtorrent/config.hpp"

#ifdef TORRENT_WINDOWS

#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))

#else

#include <alloca.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))

#endif

#endif

<commit_msg>Possibly fixed not found alloca on FreeBSD.<commit_after>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author 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.

*/

#ifndef TORRENT_ALLOCA

#include "libtorrent/config.hpp"

#ifdef TORRENT_WINDOWS

#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))

#else

#include <alloca.h>
#include <stdlib.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))

#endif

#endif

<|endoftext|>


<commit_before>/*

Copyright (c) 2005, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author 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.

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

#if defined(__GNUC__) && __GNUC__ >= 4

#define TORRENT_DEPRECATED __attribute__ ((deprecated))

# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
#  define TORRENT_EXPORT
# endif

#elif defined(__GNUC__)

# define TORRENT_EXPORT

#elif defined(BOOST_MSVC)

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# else
#  define TORRENT_EXPORT
# endif

#else
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif

#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1

// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
	&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif

#ifdef TORRENT_WINDOWS
#include <stdarg.h>
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif

#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

// determine what timer implementation we can use

#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif // TORRENT_CONFIG_HPP_INCLUDED

<commit_msg>attempt to make it build on windows<commit_after>/*

Copyright (c) 2005, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author 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.

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#include <stdlib.h> // for _TRUNCATE (windows)
#include <stdarg.h>

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

#if defined(__GNUC__) && __GNUC__ >= 4

#define TORRENT_DEPRECATED __attribute__ ((deprecated))

# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
#  define TORRENT_EXPORT
# endif

#elif defined(__GNUC__)

# define TORRENT_EXPORT

#elif defined(BOOST_MSVC)

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# else
#  define TORRENT_EXPORT
# endif

#else
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif

#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1

// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
	&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif

#ifdef TORRENT_WINDOWS
#include <stdarg.h>
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif

#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

// determine what timer implementation we can use

#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif // TORRENT_CONFIG_HPP_INCLUDED

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_IMAGE_NULL_HPP
#define MAPNIK_IMAGE_NULL_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/pixel_types.hpp>

//stl
#include <stdexcept>

namespace mapnik
{

template <>
class MAPNIK_DECL image<null_t>
{
public:
    using pixel_type = null_t::type;
    static const image_dtype dtype = null_t::id;
private:
public:
    image() {}
    image(int /*width*/,
          int /*height*/,
          bool /*initialize*/ = true,
          bool /*premultiplied*/ = false,
          bool /*painted*/ = false) {}
    image(image<null_t> const&) {}
    image(image<null_t> &&) noexcept {}
    image<null_t>& operator=(image<null_t>) { return *this; }
    image<null_t>const& operator=(image<null_t> const& rhs) const { return rhs; }
    bool operator==(image<null_t> const&) const { return true; }
    bool operator<(image<null_t> const&) const { return false; }

    std::size_t width() const { return 0; }
    std::size_t height() const { return 0; }
    std::size_t size() const { return 0; }
    std::size_t row_size() const { return 0; }
    void set(pixel_type const&) { throw std::runtime_error("Can not set values for null image"); }
    pixel_type& operator() (std::size_t, std::size_t) { throw std::runtime_error("Can not get or set values for null image"); }
    pixel_type const& operator() (std::size_t, std::size_t) const { throw std::runtime_error("Can not get or set values for null image"); }
    unsigned const char* bytes() const { return nullptr; }
    unsigned char* bytes() {return nullptr; }
    double get_offset() const { return 0.0; }
    void set_offset(double) {}
    double get_scaling() const { return 1.0; }
    void set_scaling(double) {}
    bool get_premultiplied() const { return false; }
    void set_premultiplied(bool) {}
    void painted(bool) {}
    bool painted() const { return false; }
    image_dtype get_dtype() const { return dtype; }
};

} // end ns mapnik

#endif // MAPNIK_IMAGE_NULL_HPP
<commit_msg>remove duplicate operator=<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_IMAGE_NULL_HPP
#define MAPNIK_IMAGE_NULL_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/pixel_types.hpp>

//stl
#include <stdexcept>

namespace mapnik
{

template <>
class MAPNIK_DECL image<null_t>
{
public:
    using pixel_type = null_t::type;
    static const image_dtype dtype = null_t::id;
private:
public:
    image() {}
    image(int /*width*/,
          int /*height*/,
          bool /*initialize*/ = true,
          bool /*premultiplied*/ = false,
          bool /*painted*/ = false) {}
    image(image<null_t> const&) {}
    image(image<null_t> &&) noexcept {}
    image<null_t>& operator=(image<null_t>) { return *this; }
    bool operator==(image<null_t> const&) const { return true; }
    bool operator<(image<null_t> const&) const { return false; }

    std::size_t width() const { return 0; }
    std::size_t height() const { return 0; }
    std::size_t size() const { return 0; }
    std::size_t row_size() const { return 0; }
    void set(pixel_type const&) { throw std::runtime_error("Can not set values for null image"); }
    pixel_type& operator() (std::size_t, std::size_t) { throw std::runtime_error("Can not get or set values for null image"); }
    pixel_type const& operator() (std::size_t, std::size_t) const { throw std::runtime_error("Can not get or set values for null image"); }
    unsigned const char* bytes() const { return nullptr; }
    unsigned char* bytes() {return nullptr; }
    double get_offset() const { return 0.0; }
    void set_offset(double) {}
    double get_scaling() const { return 1.0; }
    void set_scaling(double) {}
    bool get_premultiplied() const { return false; }
    void set_premultiplied(bool) {}
    void painted(bool) {}
    bool painted() const { return false; }
    image_dtype get_dtype() const { return dtype; }
};

} // end ns mapnik

#endif // MAPNIK_IMAGE_NULL_HPP
<|endoftext|>


<commit_before>#ifndef PROTOCOL_MESSAGES_HPP_
#define PROTOCOL_MESSAGES_HPP_

#include <cstdint>

namespace protocol {
namespace message {

struct heartbeat_message_t {
  enum { ID = 0x00 };

  std::uint8_t seq;
} __attribute__((packed));

struct log_message_t {
  enum { ID = 0x01 };

  uint32_t time;
  char data[100];
} __attribute__((packed));

struct attitude_message_t {
  enum { ID = 0x02 };

  uint32_t time;
  float dcm[9];
} __attribute__((packed));

struct set_arm_state_message_t {
  enum { ID = 0x03 };

  bool armed;
} __attribute__((packed));

struct set_control_mode_message_t {
  enum { ID = 0x04 };

  enum class ControlMode {
    MANUAL,
    OFFBOARD
  };

  ControlMode mode;
} __attribute__((packed));

struct offboard_attitude_control_message_t {
  enum { ID = 0x05 };

  float roll;
  float pitch;
  float yaw;
  float throttle;
  uint16_t buttons;   // Bitfield of buttons
  uint8_t mode;
} __attribute__((packed));

struct motor_throttle_message_t {
  enum { ID = 0x06 };

  uint32_t time;
  float throttles[4];
} __attribute__((packed));

struct sensor_calibration_request_message_t {
  enum { ID = 0x07 };
} __attribute__((packed));

struct sensor_calibration_response_message_t {
  enum { ID = 0x08 };

  enum class SensorType {
    ACCEL,
    GYRO,
    MAG
  };

  SensorType type;
  float offsets[3];
} __attribute__((packed));

struct location_message_t {
  enum { ID = 0x09 };

  uint32_t time;
  float lat;
  float lon;
  float alt;
} __attribute__((packed));

struct imu_message_t {
  enum { ID = 0x0a };

  uint32_t time;
  float gyro[3];
  float accel[3];
} __attribute__((packed));

struct system_message_t {
  enum { ID = 0x0b };

  uint32_t time;
  uint8_t state;
  float motorDC;   // TODO(yoos): Hack for esra test launch
} __attribute__((packed));

inline std::uint16_t length(int id) {
  // TODO(kyle): sizeof(empty struct) is 1 in C++...
  switch(id) {
    case heartbeat_message_t::ID:
      return sizeof(heartbeat_message_t);
    case log_message_t::ID:
      return sizeof(log_message_t);
    case attitude_message_t::ID:
      return sizeof(attitude_message_t);
    case set_arm_state_message_t::ID:
      return sizeof(set_arm_state_message_t);
    case set_control_mode_message_t::ID:
      return sizeof(set_control_mode_message_t);
    case offboard_attitude_control_message_t::ID:
      return sizeof(offboard_attitude_control_message_t);
    case motor_throttle_message_t::ID:
      return sizeof(motor_throttle_message_t);
    case sensor_calibration_request_message_t::ID:
      return sizeof(sensor_calibration_request_message_t);
    case sensor_calibration_response_message_t::ID:
      return sizeof(sensor_calibration_response_message_t);
    case location_message_t::ID:
      return sizeof(location_message_t);
    case imu_message_t::ID:
      return sizeof(imu_message_t);
    case system_message_t::ID:
      return sizeof(system_message_t);
  }

  return 0; // TODO(kyle): Return something more meaningful?
}

}
}

#endif // MESSAGES_HPP_

<commit_msg>Add stream messages.<commit_after>#ifndef PROTOCOL_MESSAGES_HPP_
#define PROTOCOL_MESSAGES_HPP_

#include <cstdint>

namespace protocol {
namespace message {

struct heartbeat_message_t {
  enum { ID = 0x00 };

  std::uint8_t seq;
} __attribute__((packed));

struct log_message_t {
  enum { ID = 0x01 };

  uint32_t time;
  char data[100];
} __attribute__((packed));

struct attitude_message_t {
  enum { ID = 0x02 };

  uint32_t time;
  float dcm[9];
} __attribute__((packed));

struct set_arm_state_message_t {
  enum { ID = 0x03 };

  bool armed;
} __attribute__((packed));

struct set_control_mode_message_t {
  enum { ID = 0x04 };

  enum class ControlMode {
    MANUAL,
    OFFBOARD
  };

  ControlMode mode;
} __attribute__((packed));

struct offboard_attitude_control_message_t {
  enum { ID = 0x05 };

  float roll;
  float pitch;
  float yaw;
  float throttle;
  uint16_t buttons;   // Bitfield of buttons
  uint8_t mode;
} __attribute__((packed));

struct motor_throttle_message_t {
  enum { ID = 0x06 };

  uint32_t time;
  float throttles[4];
} __attribute__((packed));

struct sensor_calibration_request_message_t {
  enum { ID = 0x07 };
} __attribute__((packed));

struct sensor_calibration_response_message_t {
  enum { ID = 0x08 };

  enum class SensorType {
    ACCEL,
    GYRO,
    MAG
  };

  SensorType type;
  float offsets[3];
} __attribute__((packed));

struct location_message_t {
  enum { ID = 0x09 };

  uint32_t time;
  float lat;
  float lon;
  float alt;
} __attribute__((packed));

struct imu_message_t {
  enum { ID = 0x0a };
  uint32_t time;
  float gyro[3];     // Gyroscope
  float accel[3];    // Accelerometer
} __attribute__((packed));

struct system_message_t {
  enum { ID = 0x0b };

  uint32_t time;
  uint8_t state;
  float motorDC;   // TODO(yoos): Hack for esra test launch
} __attribute__((packed));

struct raw_1000_message_t {
  enum { ID = 0x0c };
  uint32_t time;
  float accel[3];    // Accelerometer
  float accelH[3];   // High-g accel
  float gyro[3];     // Gyroscope
} __attribute__((packed));

struct raw_50_message_t {
  enum { ID = 0x0d };
  uint32_t time;
  float bar;   // Barometric pressure
  float temp;   // Temperature
  float mag[3];   // Magnetometer
} __attribute((packed));

struct raw_10_message_t {
  enum { ID = 0x0e };
  uint32_t time;
  float lat;
  float lon;
  float utc;   // UTC time
} __attribute((packed));

inline std::uint16_t length(int id) {
  // TODO(kyle): sizeof(empty struct) is 1 in C++...
  switch(id) {
    case heartbeat_message_t::ID:
      return sizeof(heartbeat_message_t);
    case log_message_t::ID:
      return sizeof(log_message_t);
    case attitude_message_t::ID:
      return sizeof(attitude_message_t);
    case set_arm_state_message_t::ID:
      return sizeof(set_arm_state_message_t);
    case set_control_mode_message_t::ID:
      return sizeof(set_control_mode_message_t);
    case offboard_attitude_control_message_t::ID:
      return sizeof(offboard_attitude_control_message_t);
    case motor_throttle_message_t::ID:
      return sizeof(motor_throttle_message_t);
    case sensor_calibration_request_message_t::ID:
      return sizeof(sensor_calibration_request_message_t);
    case sensor_calibration_response_message_t::ID:
      return sizeof(sensor_calibration_response_message_t);
    case location_message_t::ID:
      return sizeof(location_message_t);
    case imu_message_t::ID:
      return sizeof(imu_message_t);
    case system_message_t::ID:
      return sizeof(system_message_t);
    case raw_1000_message_t::ID:
      return sizeof(raw_1000_message_t);
    case raw_50_message_t::ID:
      return sizeof(raw_50_message_t);
    case raw_10_message_t::ID:
      return sizeof(raw_10_message_t);
  }

  return 0; // TODO(kyle): Return something more meaningful?
}

}
}

#endif // MESSAGES_HPP_

<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright 2015 Cloudius Systems
 */

#pragma once

#include <chrono>
#include <seastar/util/std-compat.hh>
#include <atomic>
#include <functional>
#include <seastar/core/future.hh>
#include <seastar/core/timer-set.hh>
#include <seastar/core/scheduling.hh>

namespace seastar {

using steady_clock_type = std::chrono::steady_clock;

template <typename Clock = steady_clock_type>
class timer {
public:
    typedef typename Clock::time_point time_point;
    typedef typename Clock::duration duration;
    typedef Clock clock;
private:
    using callback_t = noncopyable_function<void()>;
    boost::intrusive::list_member_hook<> _link;
    scheduling_group _sg;
    callback_t _callback;
    time_point _expiry;
    compat::optional<duration> _period;
    bool _armed = false;
    bool _queued = false;
    bool _expired = false;
    void readd_periodic();
    void arm_state(time_point until, compat::optional<duration> period) {
        assert(!_armed);
        _period = period;
        _armed = true;
        _expired = false;
        _expiry = until;
        _queued = true;
    }
public:
    timer() = default;
    timer(timer&& t) noexcept : _sg(t._sg), _callback(std::move(t._callback)), _expiry(std::move(t._expiry)), _period(std::move(t._period)),
            _armed(t._armed), _queued(t._queued), _expired(t._expired) {
        _link.swap_nodes(t._link);
        t._queued = false;
        t._armed = false;
    }
    timer(scheduling_group sg, callback_t&& callback) : _sg(sg), _callback{std::move(callback)} {
    }
    explicit timer(callback_t&& callback) : timer(current_scheduling_group(), std::move(callback)) {
    }
    ~timer();
    void set_callback(scheduling_group sg, callback_t&& callback) {
        _sg = sg;
        _callback = std::move(callback);
    }
    void set_callback(callback_t&& callback) {
        set_callback(current_scheduling_group(), std::move(callback));
    }
    void arm(time_point until, compat::optional<duration> period = {});
    void rearm(time_point until, compat::optional<duration> period = {}) {
        if (_armed) {
            cancel();
        }
        arm(until, period);
    }
    void arm(duration delta) {
        return arm(Clock::now() + delta);
    }
    void arm_periodic(duration delta) {
        arm(Clock::now() + delta, {delta});
    }
    bool armed() const { return _armed; }
    bool cancel();
    time_point get_timeout() {
        return _expiry;
    }
    friend class reactor;
    friend class timer_set<timer, &timer::_link>;
};

extern template class timer<steady_clock_type>;

}

<commit_msg>timer: document<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright 2015 Cloudius Systems
 */

#pragma once

#include <chrono>
#include <seastar/util/std-compat.hh>
#include <atomic>
#include <functional>
#include <seastar/core/future.hh>
#include <seastar/core/timer-set.hh>
#include <seastar/core/scheduling.hh>

/// \file

/// \defgroup timers Timers
///
/// Seastar provides timers that can be defined to run a callback at a certain
/// time point in the future; timers are provided for \ref lowres_clock (10ms
/// resolution, efficient), for std::chrono::steady_clock (accurate but less
/// efficient) and for \ref manual_clock_type (for testing purposes).
///
/// Timers are optimized for cancellation; that is, adding a timer and cancelling
/// it is very efficient. This means that attaching a timer per object for
/// a timeout that rarely happens is reasonable; one does not have to maintain
/// a single timer and a sorted list for this use case.
///
/// Timer callbacks should be short and execute quickly. If involved processing
/// is required, a timer can launch a continuation.

namespace seastar {

using steady_clock_type = std::chrono::steady_clock;

/// \addtogroup timers
/// @{

/// Timer - run a callback at a certain time point in the future.
///
/// Timer callbacks should execute quickly. If more involved computation
/// is required, the timer should launch it as a fiber (or signal an
/// existing fiber to continue execution). Fibers launched from a timer
/// callback are executed under the scheduling group that was current
/// when the timer was created (see current_scheduling_group()), or the
/// scheduling that was given explicitly by the caller when the callback
/// was specified.
///
/// Expiration of a `timer<std::chrono::steady_clock>` is independent of
/// task_quota, so it has relatively high accuracy, but as a result this
/// is a relatively expensive timer. It is recommended to use `timer<lowres_clock>`
/// instead, which has very coarse resolution (~10ms) but is quite efficient.
/// It is suitable for most user timeouts.
///
/// \tparam Clock type of clock used to denote time points; can be
///        std::chrono::steady_clock_type (default), lowres_clock (more efficient
///        but with less resolution) and manual_clock_type (fine-grained control
///        for testing.
template <typename Clock = steady_clock_type>
class timer {
public:
    typedef typename Clock::time_point time_point;
    typedef typename Clock::duration duration;
    typedef Clock clock;
private:
    using callback_t = noncopyable_function<void()>;
    boost::intrusive::list_member_hook<> _link;
    scheduling_group _sg;
    callback_t _callback;
    time_point _expiry;
    compat::optional<duration> _period;
    bool _armed = false;
    bool _queued = false;
    bool _expired = false;
    void readd_periodic();
    void arm_state(time_point until, compat::optional<duration> period) {
        assert(!_armed);
        _period = period;
        _armed = true;
        _expired = false;
        _expiry = until;
        _queued = true;
    }
public:
    /// Constructs a timer with no callback set and no expiration time.
    timer() = default;
    /// Constructs a timer from another timer that is moved from.
    ///
    /// \note care should be taken when moving a timer whose callback captures `this`,
    ///       since the object pointed to by `this` may have been moved as well.
    timer(timer&& t) noexcept : _sg(t._sg), _callback(std::move(t._callback)), _expiry(std::move(t._expiry)), _period(std::move(t._period)),
            _armed(t._armed), _queued(t._queued), _expired(t._expired) {
        _link.swap_nodes(t._link);
        t._queued = false;
        t._armed = false;
    }
    /// Constructs a timer with a callback. The timer is not armed.
    ///
    /// \param sg Scheduling group to run the callback under.
    /// \param callback function (with signature `void ()`) to execute after the timer is armed and expired.
    timer(scheduling_group sg, noncopyable_function<void ()>&& callback) : _sg(sg), _callback{std::move(callback)} {
    }
    /// Constructs a timer with a callback. The timer is not armed.
    ///
    /// \param callback function (with signature `void ()`) to execute after the timer is armed and expired.
    explicit timer(noncopyable_function<void ()>&& callback) : timer(current_scheduling_group(), std::move(callback)) {
    }
    /// Destroys the timer. The timer is cancelled if armed.
    ~timer();
    /// Sets the callback function to be called when the timer expires.
    ///
    /// \param sg the scheduling group under which the callback will be executed.
    /// \param callback the callback to be executed when the timer expires.
    void set_callback(scheduling_group sg, noncopyable_function<void ()>&& callback) {
        _sg = sg;
        _callback = std::move(callback);
    }
    /// Sets the callback function to be called when the timer expires.
    ///
    /// \param callback the callback to be executed when the timer expires.
    void set_callback(noncopyable_function<void ()>&& callback) {
        set_callback(current_scheduling_group(), std::move(callback));
    }
    /// Sets the timer expiration time.
    ///
    /// It is illegal to arm a timer that has already been armed (and
    /// not disarmed by expiration or cancel()). In the current
    /// implementation, this will result in an assertion failure. See
    /// rearm().
    ///
    /// \param until the time when the timer expires
    /// \param period optional automatic rearm duration; if given the timer
    ///        will automatically rearm itself when it expires, using the period
    ///        to calculate the next expiration time.
    void arm(time_point until, compat::optional<duration> period = {});
    /// Sets the timer expiration time. If the timer was already armed, it is
    /// canceled first.
    ///
    /// \param until the time when the timer expires
    /// \param period optional automatic rearm duration; if given the timer
    ///        will automatically rearm itself when it expires, using the period
    ///        to calculate the next expiration time.
    void rearm(time_point until, compat::optional<duration> period = {}) {
        if (_armed) {
            cancel();
        }
        arm(until, period);
    }
    /// Sets the timer expiration time.
    ///
    /// It is illegal to arm a timer that has already been armed (and
    /// not disarmed by expiration or cancel()). In the current
    /// implementation, this will result in an assertion failure. See
    /// rearm().
    ///
    /// \param delta the time when the timer expires, relative to now
    void arm(duration delta) {
        return arm(Clock::now() + delta);
    }
    /// Sets the timer expiration time, with automatic rearming
    ///
    /// \param delta the time when the timer expires, relative to now. The timer
    ///        will also rearm automatically using the same delta time.
    void arm_periodic(duration delta) {
        arm(Clock::now() + delta, {delta});
    }
    /// Returns whether the timer is armed
    ///
    /// \return `true` if the timer is armed and has not expired yet.
    bool armed() const { return _armed; }
    /// Cancels an armed timer.
    ///
    /// If the timer was armed, it is disarmed. If the timer was not
    /// armed, does nothing.
    ///
    /// \return `true` if the timer was armed before the call.
    bool cancel();
    /// Gets the expiration time of an armed timer.
    ///
    /// \return the time at which the timer is scheduled to expire (undefined if the
    ///       timer is not armed).
    time_point get_timeout() {
        return _expiry;
    }
    friend class reactor;
    friend class timer_set<timer, &timer::_link>;
};

extern template class timer<steady_clock_type>;

/// @}

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: office_connect.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-06 15:03:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Sun Microsystems, 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 <stdio.h>

#include <cppuhelper/bootstrap.hxx>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::bridge;
using namespace rtl;
using namespace cppu;

int main( )
{
    // create the initial component context
    Reference< XComponentContext > rComponentContext =
        defaultBootstrap_InitialComponentContext();

    // retrieve the servicemanager from the context
    Reference< XMultiComponentFactory > rServiceManager =
        rComponentContext->getServiceManager();

    // instantiate a sample service with the servicemanager.
    Reference< XInterface > rInstance =
        rServiceManager->createInstanceWithContext(
            OUString::createFromAscii("com.sun.star.bridge.UnoUrlResolver" ),
            rComponentContext );

    // Query for the XUnoUrlResolver interface
    Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY );

    if( ! rResolver.is() )
    {
        printf( "Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\n" );
        return 1;
    }
    try
    {
        // resolve the uno-url
        rInstance = rResolver->resolve( OUString::createFromAscii(
            "uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" ) );

        if( ! rInstance.is() )
        {
            printf( "StarOffice.ServiceManager is not exported from remote counterpart\n" );
            return 1;
        }

        // query for the simpler XMultiServiceFactory interface, sufficient for scripting
        Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY);

        if( ! rInstance.is() )
        {
            printf( "XMultiServiceFactory interface is not exported for StarOffice.ServiceManager\n" );
            return 1;
        }

        printf( "Connected sucessfully to the office\n" );
    }
    catch( Exception &e )
    {
        OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
        printf( "Error: %s\n", o.pData->buffer );
        return 1;
    }
    return 0;
}
<commit_msg>INTEGRATION: CWS jsc21 (1.6.92); FILE MERGED 2008/05/21 15:03:04 jsc 1.6.92.1: #i88797# adapted to new structure<commit_after>/*************************************************************************
 *
 *  $RCSfile: office_connect.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2008-07-11 14:24:32 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Sun Microsystems, 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 <stdio.h>

#include <cppuhelper/bootstrap.hxx>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>

using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::bridge;
using namespace rtl;
using namespace cppu;

int main( )
{
    // create the initial component context
    Reference< XComponentContext > rComponentContext =
        defaultBootstrap_InitialComponentContext();

    // retrieve the servicemanager from the context
    Reference< XMultiComponentFactory > rServiceManager =
        rComponentContext->getServiceManager();

    // instantiate a sample service with the servicemanager.
    Reference< XInterface > rInstance =
        rServiceManager->createInstanceWithContext(
            OUString::createFromAscii("com.sun.star.bridge.UnoUrlResolver" ),
            rComponentContext );

    // Query for the XUnoUrlResolver interface
    Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY );

    if( ! rResolver.is() )
    {
        printf( "Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\n" );
        return 1;
    }
    try
    {
        // resolve the uno-url
        rInstance = rResolver->resolve( OUString::createFromAscii(
            "uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" ) );

        if( ! rInstance.is() )
        {
            printf( "StarOffice.ServiceManager is not exported from remote counterpart\n" );
            return 1;
        }

        // query for the simpler XMultiServiceFactory interface, sufficient for scripting
        Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY);

        if( ! rInstance.is() )
        {
            printf( "XMultiServiceFactory interface is not exported for StarOffice.ServiceManager\n" );
            return 1;
        }

        printf( "Connected sucessfully to the office\n" );
    }
    catch( Exception &e )
    {
        OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
        printf( "Error: %s\n", o.pData->buffer );
        return 1;
    }
    return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include "zmsg_utils.hpp"
#include "zmsg_types.hpp"

namespace zmsg {

template<>
struct zmsg<mid_t::set_fs_spec> {
public:
	int32_t window_x_row;			// unit: pixel
	int32_t window_x_col;			// unit: pixel
	int32_t window_y_row;			// unit: pixel
	int32_t window_y_col;			// unit: pixel

	/*deprecated*/ uint32_t nm_per_pixel;			// unit: nm/pixel

	double zmotor_spec_nm_per_step;		// unit: nm/step

	double lz_nm_per_step;			// unit: nm/step
	double rz_nm_per_step;			// unit: nm/step

	uint16_t img_cap_delay;			// unit: ms

	double   clr_discharge_strength; 	// unit: volt
	uint32_t clr_discharge_gap;		// unit: nm
	uint16_t check_fiber_exist_time;	// unit: ms

	std::array<uint16_t, motorId_t::NUM>	motor_min_speed;
	std::array<uint16_t, motorId_t::NUM>	motor_max_speed;

	double entering_speed;
	double push1_speed;
	double push2_stage1_speed;
	double push2_stage2_speed;
	double manual_calibrate_speed;
	double motor_xy_precise_calibrate_speed;
	double tensionSpeed;

	uint32_t tensionStretchLength;

	uint16_t motor_xy_steps_per_pixel;	// unit: step/pixel

	double   fiber_outline_blacklevel;		// 0.0 ~ 1.0
	double   calibrating_xy_dist_threshold;		// unit: pixel
	double   precise_calibrating_xy_dist_threshold;	// unit: pixel
	double   z_dist_threshold;			// unit: pixel

	discharge_data_t discharge_base;
	discharge_data_t discharge_revise;

	double   dust_check_threshold0;
	double   dust_check_threshold1;
	uint16_t img_denoise_threshold;

	std::array<double, ledId_t::LED_NUM>	led_brightness;
	double   x_focal_distance;
	double   y_focal_distance;

	double   zmotor_speed_factor;
	double   zmotor_speed_pow;
	double   zmotor_speed_max;		/// 0.0 ~ 1.0

	double   xymotor_speed_factor;
	double   xymotor_speed_pow;
	double   xymotor_speed_max;		/// 0.0 ~ 1.0

	double   zmotor_forward_distance;	/// unit: nm
	double   zmotor_stroke;			/// unit: nm

	double   dbg_hangle_limit;		/// unit: degree
	double   dbg_vangle_limit;		/// unit: degree

	double   pre_cal_xy_dist_threshold_relax_ratio;

	std::array<rt_revise_data_t, to_val(fiber_t::max)> rt_revise_data;

	double	loss_factor;
public:
        ZMSG_PU(
		window_x_row,
		window_x_col,
		window_y_row,
		window_y_col,

		nm_per_pixel,
		zmotor_spec_nm_per_step,
		lz_nm_per_step,
		rz_nm_per_step,

		img_cap_delay,

		clr_discharge_strength,
		clr_discharge_gap,
		check_fiber_exist_time,

		motor_min_speed,
		motor_max_speed,

		entering_speed,
		push1_speed,
		push2_stage1_speed,
		push2_stage2_speed,
		manual_calibrate_speed,
		motor_xy_precise_calibrate_speed,
		tensionSpeed,

		tensionStretchLength,

		motor_xy_steps_per_pixel,

		fiber_outline_blacklevel,
		calibrating_xy_dist_threshold,
		precise_calibrating_xy_dist_threshold,
		z_dist_threshold,

		discharge_base,
		discharge_revise,

		dust_check_threshold0,
		dust_check_threshold1,
		img_denoise_threshold,

		led_brightness,

		x_focal_distance,
		y_focal_distance,

		zmotor_speed_factor,
		zmotor_speed_pow,
		zmotor_speed_max,

		xymotor_speed_factor,
		xymotor_speed_pow,
		xymotor_speed_max,

		zmotor_forward_distance,
		zmotor_stroke,

		dbg_hangle_limit,
		dbg_vangle_limit,

		pre_cal_xy_dist_threshold_relax_ratio,

		rt_revise_data,

		loss_factor)
};

template<>
struct zmsg<mid_t::update_led_brightness> {
public:
	ledId_t  id;
	double   brightness;
public:
        ZMSG_PU(id,
		brightness)
};

template<>
struct zmsg<mid_t::update_window_position> {
	bool is_pos_x;
	int32_t row;
	int32_t column;
public:
	ZMSG_PU(is_pos_x,row,column)
};

template<>
struct zmsg<mid_t::update_cmos_focal_distance> {
public:
	double x_focal_distance;
	double y_focal_distance;
public:
	ZMSG_PU(x_focal_distance, y_focal_distance)
};

}
<commit_msg>add comment for motor_speed_factor<commit_after>#pragma once

#include "zmsg_utils.hpp"
#include "zmsg_types.hpp"

namespace zmsg {

template<>
struct zmsg<mid_t::set_fs_spec> {
public:
	int32_t window_x_row;			// unit: pixel
	int32_t window_x_col;			// unit: pixel
	int32_t window_y_row;			// unit: pixel
	int32_t window_y_col;			// unit: pixel

	/*deprecated*/ uint32_t nm_per_pixel;			// unit: nm/pixel

	double zmotor_spec_nm_per_step;		// unit: nm/step

	double lz_nm_per_step;			// unit: nm/step
	double rz_nm_per_step;			// unit: nm/step

	uint16_t img_cap_delay;			// unit: ms

	double   clr_discharge_strength; 	// unit: volt
	uint32_t clr_discharge_gap;		// unit: nm
	uint16_t check_fiber_exist_time;	// unit: ms

	std::array<uint16_t, motorId_t::NUM>	motor_min_speed;
	std::array<uint16_t, motorId_t::NUM>	motor_max_speed;

	double entering_speed;
	double push1_speed;
	double push2_stage1_speed;
	double push2_stage2_speed;
	double manual_calibrate_speed;
	double motor_xy_precise_calibrate_speed;
	double tensionSpeed;

	uint32_t tensionStretchLength;

	uint16_t motor_xy_steps_per_pixel;	// unit: step/pixel

	double   fiber_outline_blacklevel;		// 0.0 ~ 1.0
	double   calibrating_xy_dist_threshold;		// unit: pixel
	double   precise_calibrating_xy_dist_threshold;	// unit: pixel
	double   z_dist_threshold;			// unit: pixel

	discharge_data_t discharge_base;
	discharge_data_t discharge_revise;

	double   dust_check_threshold0;
	double   dust_check_threshold1;
	uint16_t img_denoise_threshold;

	std::array<double, ledId_t::LED_NUM>	led_brightness;
	double   x_focal_distance;
	double   y_focal_distance;

	double   zmotor_speed_factor;		/// unit: um
	double   zmotor_speed_pow;
	double   zmotor_speed_max;		/// 0.0 ~ 1.0

	double   xymotor_speed_factor;		/// unit: um
	double   xymotor_speed_pow;
	double   xymotor_speed_max;		/// 0.0 ~ 1.0

	double   zmotor_forward_distance;	/// unit: nm
	double   zmotor_stroke;			/// unit: nm

	double   dbg_hangle_limit;		/// unit: degree
	double   dbg_vangle_limit;		/// unit: degree

	double   pre_cal_xy_dist_threshold_relax_ratio;

	std::array<rt_revise_data_t, to_val(fiber_t::max)> rt_revise_data;

	double	loss_factor;
public:
        ZMSG_PU(
		window_x_row,
		window_x_col,
		window_y_row,
		window_y_col,

		nm_per_pixel,
		zmotor_spec_nm_per_step,
		lz_nm_per_step,
		rz_nm_per_step,

		img_cap_delay,

		clr_discharge_strength,
		clr_discharge_gap,
		check_fiber_exist_time,

		motor_min_speed,
		motor_max_speed,

		entering_speed,
		push1_speed,
		push2_stage1_speed,
		push2_stage2_speed,
		manual_calibrate_speed,
		motor_xy_precise_calibrate_speed,
		tensionSpeed,

		tensionStretchLength,

		motor_xy_steps_per_pixel,

		fiber_outline_blacklevel,
		calibrating_xy_dist_threshold,
		precise_calibrating_xy_dist_threshold,
		z_dist_threshold,

		discharge_base,
		discharge_revise,

		dust_check_threshold0,
		dust_check_threshold1,
		img_denoise_threshold,

		led_brightness,

		x_focal_distance,
		y_focal_distance,

		zmotor_speed_factor,
		zmotor_speed_pow,
		zmotor_speed_max,

		xymotor_speed_factor,
		xymotor_speed_pow,
		xymotor_speed_max,

		zmotor_forward_distance,
		zmotor_stroke,

		dbg_hangle_limit,
		dbg_vangle_limit,

		pre_cal_xy_dist_threshold_relax_ratio,

		rt_revise_data,

		loss_factor)
};

template<>
struct zmsg<mid_t::update_led_brightness> {
public:
	ledId_t  id;
	double   brightness;
public:
        ZMSG_PU(id,
		brightness)
};

template<>
struct zmsg<mid_t::update_window_position> {
	bool is_pos_x;
	int32_t row;
	int32_t column;
public:
	ZMSG_PU(is_pos_x,row,column)
};

template<>
struct zmsg<mid_t::update_cmos_focal_distance> {
public:
	double x_focal_distance;
	double y_focal_distance;
public:
	ZMSG_PU(x_focal_distance, y_focal_distance)
};

}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.

// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.

// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.

// Grappa is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// Affero General Public License for more details.

// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagl.html.
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
/// Demonstrates using the GraphLab API to implement Pagerank
////////////////////////////////////////////////////////////////////////
#include <Grappa.hpp>
#include "graphlab.hpp"

DEFINE_bool( metrics, false, "Dump metrics");

DEFINE_int32(scale, 10, "Log2 number of vertices.");
DEFINE_int32(edgefactor, 16, "Average number of edges per vertex.");

DEFINE_string(path, "", "Path to graph source file.");
DEFINE_string(format, "bintsv4", "Format of graph source file.");

GRAPPA_DEFINE_METRIC(SimpleMetric<double>, init_time, 0);
GRAPPA_DEFINE_METRIC(SimpleMetric<double>, tuple_time, 0);
GRAPPA_DEFINE_METRIC(SimpleMetric<double>, construction_time, 0);
GRAPPA_DEFINE_METRIC(SimpleMetric<double>, total_time, 0);

const double RESET_PROB = 0.15;
DEFINE_double(tolerance, 1.0E-2, "tolerance");
#define TOLERANCE FLAGS_tolerance

struct CCData : public GraphlabVertexData<CCData> {
  uint64_t label;
};

struct MinLabel {
  uint64_t v;
  explicit MinLabel(uint64_t v): v(v) {}
  MinLabel(): v(std::numeric_limits<uint64_t>::max()) {}
  MinLabel& operator+=(const MinLabel& o) {
    v = std::min(v, o.v);
    return *this;
  }
  operator uint64_t () const { return v; }
};

using G = Graph<CCData,Empty>;

struct LabelPropagation : public GraphlabVertexProgram<G,MinLabel> {
  bool do_scatter;
  uint64_t tmp_label;

  LabelPropagation(Vertex& v): tmp_label(-1) {}

  bool gather_edges(const Vertex& v) const { return true; }

  Gather gather(const Vertex& v, Edge& e) const { return MinLabel(v->label); }

  void apply(Vertex& v, const Gather& total) {
    uint64_t min_label = static_cast<uint64_t>(total);
    if (v->label > min_label) {
      v->label = tmp_label = min_label;
      do_scatter = true;
    }
  }
  bool scatter_edges(const Vertex& v) const { return do_scatter; }
  Gather scatter(const Edge& e, Vertex& target) const {
    if (target->label > tmp_label) {
      target->activate();
      return MinLabel(tmp_label);
    }
    return MinLabel();
  }
};

Reducer<int64_t,ReducerType::Add> nc;

int main(int argc, char* argv[]) {
  init(&argc, &argv);
  run([]{

    double t;

    TupleGraph tg;

    GRAPPA_TIME_REGION(tuple_time) {
      if (FLAGS_path.empty()) {
        int64_t NE = (1L << FLAGS_scale) * FLAGS_edgefactor;
        tg = TupleGraph::Kronecker(FLAGS_scale, NE, 111, 222);
      } else {
        LOG(INFO) << "loading " << FLAGS_path;
        tg = TupleGraph::Load(FLAGS_path, FLAGS_format);
      }
    }
    LOG(INFO) << tuple_time;
    LOG(INFO) << "constructing graph";
    t = walltime();

    auto g = G::Undirected(tg);

    construction_time = walltime()-t;
    LOG(INFO) << construction_time;

    GRAPPA_TIME_REGION(total_time) {
      forall(g, [](VertexID i, G::Vertex& v){
        v->label = i;
        v->activate();
      });
      run_synchronous<LabelPropagation>(g);
    }
    LOG(INFO) << total_time;

    if (FLAGS_scale <= 8) {
      g->dump([](std::ostream& o, G::Vertex& v){
        o << "{ label:" << v->label << " }";
      });
    }

    nc = 0;
    forall(g, [](VertexID i, G::Vertex& v){ if (v->label == i) nc++; });
    LOG(INFO) << "ncomponents: " << nc;
  });
  finalize();
}
<commit_msg>graphlab cc: deactivate scatter<commit_after>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.

// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.

// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.

// Grappa is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// Affero General Public License for more details.

// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagl.html.
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
/// Demonstrates using the GraphLab API to implement Pagerank
////////////////////////////////////////////////////////////////////////
#include <Grappa.hpp>
#include "graphlab.hpp"

DEFINE_bool( metrics, false, "Dump metrics");

DEFINE_int32(scale, 10, "Log2 number of vertices.");
DEFINE_int32(edgefactor, 16, "Average number of edges per vertex.");

DEFINE_string(path, "", "Path to graph source file.");
DEFINE_string(format, "bintsv4", "Format of graph source file.");

GRAPPA_DEFINE_METRIC(SimpleMetric<double>, init_time, 0);
GRAPPA_DEFINE_METRIC(SimpleMetric<double>, tuple_time, 0);
GRAPPA_DEFINE_METRIC(SimpleMetric<double>, construction_time, 0);
GRAPPA_DEFINE_METRIC(SimpleMetric<double>, total_time, 0);

const double RESET_PROB = 0.15;
DEFINE_double(tolerance, 1.0E-2, "tolerance");
#define TOLERANCE FLAGS_tolerance

struct CCData : public GraphlabVertexData<CCData> {
  uint64_t label;
};

struct MinLabel {
  uint64_t v;
  explicit MinLabel(uint64_t v): v(v) {}
  MinLabel(): v(std::numeric_limits<uint64_t>::max()) {}
  MinLabel& operator+=(const MinLabel& o) {
    v = std::min(v, o.v);
    return *this;
  }
  operator uint64_t () const { return v; }
};

using G = Graph<CCData,Empty>;

struct LabelPropagation : public GraphlabVertexProgram<G,MinLabel> {
  bool do_scatter;
  uint64_t tmp_label;

  LabelPropagation(Vertex& v): tmp_label(-1) {}

  bool gather_edges(const Vertex& v) const { return true; }

  Gather gather(const Vertex& v, Edge& e) const { return MinLabel(v->label); }

  void apply(Vertex& v, const Gather& total) {
    uint64_t min_label = static_cast<uint64_t>(total);
    if (v->label > min_label) {
      v->label = tmp_label = min_label;
      do_scatter = true;
    } else {
      do_scatter = false;
    }
  }

  bool scatter_edges(const Vertex& v) const { return do_scatter; }

  Gather scatter(const Edge& e, Vertex& target) const {
    if (target->label > tmp_label) {
      target->activate();
      return MinLabel(tmp_label);
    }
    return MinLabel();
  }
};

Reducer<int64_t,ReducerType::Add> nc;

int main(int argc, char* argv[]) {
  init(&argc, &argv);
  run([]{

    double t;

    TupleGraph tg;

    GRAPPA_TIME_REGION(tuple_time) {
      if (FLAGS_path.empty()) {
        int64_t NE = (1L << FLAGS_scale) * FLAGS_edgefactor;
        tg = TupleGraph::Kronecker(FLAGS_scale, NE, 111, 222);
      } else {
        LOG(INFO) << "loading " << FLAGS_path;
        tg = TupleGraph::Load(FLAGS_path, FLAGS_format);
      }
    }
    LOG(INFO) << tuple_time;
    LOG(INFO) << "constructing graph";
    t = walltime();

    auto g = G::Undirected(tg);

    construction_time = walltime()-t;
    LOG(INFO) << construction_time;

    GRAPPA_TIME_REGION(total_time) {
      forall(g, [](VertexID i, G::Vertex& v){
        v->label = i;
        v->activate();
      });
      run_synchronous<LabelPropagation>(g);
    }
    LOG(INFO) << total_time;

    if (FLAGS_scale <= 8) {
      g->dump([](std::ostream& o, G::Vertex& v){
        o << "{ label:" << v->label << " }";
      });
    }

    nc = 0;
    forall(g, [](VertexID i, G::Vertex& v){ if (v->label == i) nc++; });
    LOG(INFO) << "ncomponents: " << nc;
  });
  finalize();
}
<|endoftext|>