<commit_before>#ifndef ALEPH_CONTAINERS_POINT_CLOUD_HH__
#define ALEPH_CONTAINERS_POINT_CLOUD_HH__

#include <algorithm>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include <string>

#include <cstddef>

#include <utilities/String.hh>

namespace aleph
{

template <class T> class PointCloud
{
public:

  // Exporting the type of elements stored in the point cloud. This is
  // used by other algorithms to prevent casting.
  using ElementType = T;

  PointCloud()
    : _n( 0 )
    , _d( 0 )
    , _points( nullptr )
  {
  }

  PointCloud( std::size_t n, std::size_t d )
    : _n( n )
    , _d( d )
    , _points( new T[ _n * _d ] )
  {
    // Zero-initialization. This may not be the most efficient way of
    // doing it, in particular if a client has some data to pass, but
    // it ensures consistency.
    std::fill( _points, _points + _n * _d, T() );
  }

  PointCloud( const PointCloud& other )
    : _n( other._n )
    , _d( other._d )
    , _points( new T[ _n * _d ] )
  {
    std::copy( other._points, other._points + _n * _d, _points );
  }

  PointCloud( PointCloud&& other )
  {
    swap( *this, other );
  }

  PointCloud& operator=( PointCloud other )
  {
    swap( *this, other );
    return *this;
  }

  ~PointCloud()
  {
    delete[] _points;
  }

  friend void swap( PointCloud& pc1, PointCloud& pc2 )
  {
    using std::swap;

    swap( pc1._points, pc2._points );
    swap( pc1._n,      pc2._n );
    swap( pc1._d,      pc2._d );
  }

  // Attributes --------------------------------------------------------

  std::size_t size() const noexcept
  {
    return _n;
  }

  std::size_t dimension() const noexcept
  {
    return _d;
  }

  // Point access ------------------------------------------------------

  // This is slightly evil. The function is not really "bit-wise"
  // constant because it still permits modifying the pointer that
  // is being returned.
  T* data() const noexcept
  {
    return _points;
  }

  /**
    Sets $i$th point of point cloud. Throws if the number of dimensions
    does not match the number of dimensions in the point cloud.
  */

  template <class InputIterator> void set( std::size_t i,
                                           InputIterator begin, InputIterator end )
  {
    if( i >= this->size() )
      throw std::runtime_error( "Invalid index" );

    auto distance = std::distance( begin, end );

    if( static_cast<std::size_t>( distance ) != this->dimension() )
      throw std::runtime_error( "Incorrect number of dimensions" );

    std::copy( begin, end, _points[ this->dimension() * i ]);
  }

  /**
    Gets the $i$th point of the point cloud. It will be stored via an
    output iterator. Incorrect indices will result in an exception.
  */

  template <class OutputIterator> void get( std::size_t i,
                                            OutputIterator result ) const
  {
    if( i >= this->size() )
      throw std::runtime_error( "Invalid index" );

    auto offset = i * this->dimension();

    std::copy( _points + offset, _points + offset + this->dimension(),
               result );
  }

private:
  std::size_t _n; ///< Number of points
  std::size_t _d; ///< Dimension

  T* _points;
};

/**
  Loads a new point cloud from a file. The file is supposed to be in
  ASCII format. Each row must specify one item of the data set.  The
  different attributes of each item are assumed to be separated by a
  comma or white-space characters.
*/
template<class T> PointCloud<T> load( const std::string& filename )
{
  std::ifstream in( filename );

  if( !in )
    return PointCloud<T>();

  auto lines = std::count( std::istreambuf_iterator<char>( in ),
                           std::istreambuf_iterator<char>(),
                           '\n' );

  if( lines <= 0 )
    return PointCloud<T>();

  std::size_t i = 0;
  std::size_t d = 0;
  std::size_t n = static_cast<std::size_t>( lines );

  std::string line;

  PointCloud<T> pointCloud;

  while( std::getline( in, line ) )
  {
    auto tokens = utilities::split( line, std::string( "[:;,[:space:]]+" ) );

    if( d == 0 )
    {
      d          = tokens.size();
      pointCloud = PointCloud<T>( n, d );
    }

    std::vector<T> coordinates;
    coordinates.reserve( d );

    for( auto&& token : tokens )
    {
      T coordinate = utilities::convert<T>( token );
      coordinates.push_back( coordinate );
    }

    pointCloud.set( i,
                    coordinates.begin(), coordinates.end() );

    ++i;
  }

  return pointCloud;
}

}

#endif
<commit_msg>Equality operator for point clouds<commit_after>#ifndef ALEPH_CONTAINERS_POINT_CLOUD_HH__
#define ALEPH_CONTAINERS_POINT_CLOUD_HH__

#include <algorithm>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include <string>

#include <cstddef>

#include <utilities/String.hh>

namespace aleph
{

template <class T> class PointCloud
{
public:

  // Exporting the type of elements stored in the point cloud. This is
  // used by other algorithms to prevent casting.
  using ElementType = T;

  PointCloud()
    : _n( 0 )
    , _d( 0 )
    , _points( nullptr )
  {
  }

  PointCloud( std::size_t n, std::size_t d )
    : _n( n )
    , _d( d )
    , _points( new T[ _n * _d ] )
  {
    // Zero-initialization. This may not be the most efficient way of
    // doing it, in particular if a client has some data to pass, but
    // it ensures consistency.
    std::fill( _points, _points + _n * _d, T() );
  }

  PointCloud( const PointCloud& other )
    : _n( other._n )
    , _d( other._d )
    , _points( new T[ _n * _d ] )
  {
    std::copy( other._points, other._points + _n * _d, _points );
  }

  PointCloud( PointCloud&& other )
  {
    swap( *this, other );
  }

  PointCloud& operator=( PointCloud other )
  {
    swap( *this, other );
    return *this;
  }

  ~PointCloud()
  {
    delete[] _points;
  }

  friend void swap( PointCloud& pc1, PointCloud& pc2 )
  {
    using std::swap;

    swap( pc1._points, pc2._points );
    swap( pc1._n,      pc2._n );
    swap( pc1._d,      pc2._d );
  }

  // Equality comparison -----------------------------------------------

  bool operator==( const PointCloud<T>& other ) const noexcept
  {
    return    _n == other._n
           && _d == other._d
           && std::equal( _points, _points + _n * _d, other._points );
  }

  // Attributes --------------------------------------------------------

  std::size_t size() const noexcept
  {
    return _n;
  }

  std::size_t dimension() const noexcept
  {
    return _d;
  }

  // Point access ------------------------------------------------------

  // This is slightly evil. The function is not really "bit-wise"
  // constant because it still permits modifying the pointer that
  // is being returned.
  T* data() const noexcept
  {
    return _points;
  }

  /**
    Sets $i$th point of point cloud. Throws if the number of dimensions
    does not match the number of dimensions in the point cloud.
  */

  template <class InputIterator> void set( std::size_t i,
                                           InputIterator begin, InputIterator end )
  {
    if( i >= this->size() )
      throw std::runtime_error( "Invalid index" );

    auto distance = std::distance( begin, end );

    if( static_cast<std::size_t>( distance ) != this->dimension() )
      throw std::runtime_error( "Incorrect number of dimensions" );

    std::copy( begin, end, _points[ this->dimension() * i ]);
  }

  /**
    Gets the $i$th point of the point cloud. It will be stored via an
    output iterator. Incorrect indices will result in an exception.
  */

  template <class OutputIterator> void get( std::size_t i,
                                            OutputIterator result ) const
  {
    if( i >= this->size() )
      throw std::runtime_error( "Invalid index" );

    auto offset = i * this->dimension();

    std::copy( _points + offset, _points + offset + this->dimension(),
               result );
  }

private:
  std::size_t _n; ///< Number of points
  std::size_t _d; ///< Dimension

  T* _points;
};

/**
  Loads a new point cloud from a file. The file is supposed to be in
  ASCII format. Each row must specify one item of the data set.  The
  different attributes of each item are assumed to be separated by a
  comma or white-space characters.
*/
template<class T> PointCloud<T> load( const std::string& filename )
{
  std::ifstream in( filename );

  if( !in )
    return PointCloud<T>();

  auto lines = std::count( std::istreambuf_iterator<char>( in ),
                           std::istreambuf_iterator<char>(),
                           '\n' );

  if( lines <= 0 )
    return PointCloud<T>();

  std::size_t i = 0;
  std::size_t d = 0;
  std::size_t n = static_cast<std::size_t>( lines );

  std::string line;

  PointCloud<T> pointCloud;

  while( std::getline( in, line ) )
  {
    auto tokens = utilities::split( line, std::string( "[:;,[:space:]]+" ) );

    if( d == 0 )
    {
      d          = tokens.size();
      pointCloud = PointCloud<T>( n, d );
    }

    std::vector<T> coordinates;
    coordinates.reserve( d );

    for( auto&& token : tokens )
    {
      T coordinate = utilities::convert<T>( token );
      coordinates.push_back( coordinate );
    }

    pointCloud.set( i,
                    coordinates.begin(), coordinates.end() );

    ++i;
  }

  return pointCloud;
}

}

#endif
<|endoftext|>


<commit_before>//
//  common_types.hpp
//  fibio
//
//  Created by Chen Xu on 14-3-10.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#ifndef fibio_http_common_common_types_hpp
#define fibio_http_common_common_types_hpp

#include <cstdint>
#include <string>
#include <map>
#include <chrono>
#include <fibio/http/common/content_type.hpp>

namespace fibio { namespace http { namespace common {
    enum class http_version : uint16_t {
        INVALID_VERSION=0x0000,
        HTTP_0_9=0x0009,
        HTTP_1_0=0x0100,
        HTTP_1_1=0x0101,
    };

    enum class http_method : uint16_t {
        INVALID_METHOD=0,
        DELETE=1,
        GET=2,
        HEAD=3,
        POST=4,
        PUT=5,
        /* pathological */
        CONNECT=6,
        OPTIONS=7,
        TRACE=8,
        /* webdav */
        COPY=9,
        LOCK=10,
        MKCOL=11,
        MOVE=12,
        PROPFIND=13,
        PROPPATCH=14,
        SEARCH=15,
        UNLOCK=16,
        /* subversion */
        REPORT=17,
        MKACTIVITY=18,
        CHECKOUT=19,
        MERGE=20,
        /* upnp */
        MSEARCH=21,
        NOTIFY=22,
        SUBSCRIBE=23,
        UNSUBSCRIBE=24,
        /* RFC-5789 */
        PATCH=25,
        PURGE=26,
    };

    enum class http_status_code : uint16_t {
        INVALID_STATUS                  =0,
        CONTINUE                        =100,
        SWITCHING_PROTOCOLS             =101,
        OK                              =200,
        CREATED                         =201,
        ACCEPTED                        =202,
        NON_AUTHORITATIVE_INFORMATION   =203,
        NO_CONTENT                      =204,
        RESET_CONTENT                   =205,
        PARTIAL_CONTENT                 =206,
        MULTIPLE_CHOICES                =300,
        MOVED_PERMANENTLY               =301,
        FOUND                           =302,
        SEE_OTHER                       =303,
        NOT_MODIFIED                    =304,
        USE_PROXY                       =305,
        //UNUSED                        =306,
        TEMPORARY_REDIRECT              =307,
        BAD_REQUEST                     =400,
        UNAUTHORIZED                    =401,
        PAYMENT_REQUIRED                =402,
        FORBIDDEN                       =403,
        NOT_FOUND                       =404,
        METHOD_NOT_ALLOWED              =405,
        NOT_ACCEPTABLE                  =406,
        PROXY_AUTHENTICATION_REQUIRED   =407,
        REQUEST_TIMEOUT                 =408,
        CONFLICT                        =409,
        GONE                            =410,
        LENGTH_REQUIRED                 =411,
        PRECONDITION_FAILED             =412,
        REQUEST_ENTITY_TOO_LARGE        =413,
        REQUEST_URI_TOO_LONG            =414,
        UNSUPPORTED_MEDIA_TYPE          =415,
        REQUESTED_RANGE_NOT_SATISFIABLE =416,
        EXPECTATION_FAILED              =417,
        UPGRADE_REQUIRED                =426,
        PRECONDITION_REQUIRED           =428,
        TOO_MANY_REQUESTS               =429,
        REQUEST_HEADER_FIELDS_TOO_LARGE =431,
        INTERNAL_SERVER_ERROR           =500,
        NOT_IMPLEMENTED                 =501,
        BAD_GATEWAY                     =502,
        SERVICE_UNAVAILABLE             =503,
        GATEWAY_TIMEOUT                 =504,
        HTTP_VERSION_NOT_SUPPORTED      =505,
    };

    typedef std::string header_key_type;
    typedef std::string header_value_type;

    struct iless {
        inline bool operator()(const header_key_type &lhs, const header_key_type &rhs) const
        { return strcasecmp(lhs.c_str(), rhs.c_str())<0; }
    };

    struct iequal {
        inline bool operator()(const header_key_type &lhs, const header_key_type &rhs) const
        { return strcasecmp(lhs.c_str(), rhs.c_str())==0; }
    };

    typedef std::multimap<header_key_type, header_value_type, iless> header_map;

    typedef std::chrono::steady_clock::duration timeout_type;
}}} // End of namespace fibio::http::common

namespace fibio { namespace http {
    using common::http_version;
    using common::http_method;
    using common::http_status_code;
    using common::timeout_type;
}}  // End of namespace fibio::http

#endif
<commit_msg>Method enum needs to be same as http-parser<commit_after>//
//  common_types.hpp
//  fibio
//
//  Created by Chen Xu on 14-3-10.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#ifndef fibio_http_common_common_types_hpp
#define fibio_http_common_common_types_hpp

#include <cstdint>
#include <string>
#include <map>
#include <chrono>
#include <fibio/http/common/content_type.hpp>

namespace fibio { namespace http { namespace common {
    enum class http_version : uint16_t {
        INVALID_VERSION=0x0000,
        HTTP_0_9=0x0009,
        HTTP_1_0=0x0100,
        HTTP_1_1=0x0101,
    };

    enum class http_method : uint16_t {
        DELETE=0,
        GET=1,
        HEAD=2,
        POST=3,
        PUT=4,
        /* pathological */
        CONNECT=5,
        OPTIONS=6,
        TRACE=7,
        /* webdav */
        COPY=8,
        LOCK=9,
        MKCOL=10,
        MOVE=11,
        PROPFIND=12,
        PROPPATCH=13,
        SEARCH=14,
        UNLOCK=15,
        /* subversion */
        REPORT=16,
        MKACTIVITY=17,
        CHECKOUT=18,
        MERGE=19,
        /* upnp */
        MSEARCH=20,
        NOTIFY=21,
        SUBSCRIBE=22,
        UNSUBSCRIBE=23,
        /* RFC-5789 */
        PATCH=24,
        PURGE=25,
        INVALID_METHOD=0xFFFF,
    };

    enum class http_status_code : uint16_t {
        INVALID_STATUS                  =0,
        CONTINUE                        =100,
        SWITCHING_PROTOCOLS             =101,
        OK                              =200,
        CREATED                         =201,
        ACCEPTED                        =202,
        NON_AUTHORITATIVE_INFORMATION   =203,
        NO_CONTENT                      =204,
        RESET_CONTENT                   =205,
        PARTIAL_CONTENT                 =206,
        MULTIPLE_CHOICES                =300,
        MOVED_PERMANENTLY               =301,
        FOUND                           =302,
        SEE_OTHER                       =303,
        NOT_MODIFIED                    =304,
        USE_PROXY                       =305,
        //UNUSED                        =306,
        TEMPORARY_REDIRECT              =307,
        BAD_REQUEST                     =400,
        UNAUTHORIZED                    =401,
        PAYMENT_REQUIRED                =402,
        FORBIDDEN                       =403,
        NOT_FOUND                       =404,
        METHOD_NOT_ALLOWED              =405,
        NOT_ACCEPTABLE                  =406,
        PROXY_AUTHENTICATION_REQUIRED   =407,
        REQUEST_TIMEOUT                 =408,
        CONFLICT                        =409,
        GONE                            =410,
        LENGTH_REQUIRED                 =411,
        PRECONDITION_FAILED             =412,
        REQUEST_ENTITY_TOO_LARGE        =413,
        REQUEST_URI_TOO_LONG            =414,
        UNSUPPORTED_MEDIA_TYPE          =415,
        REQUESTED_RANGE_NOT_SATISFIABLE =416,
        EXPECTATION_FAILED              =417,
        UPGRADE_REQUIRED                =426,
        PRECONDITION_REQUIRED           =428,
        TOO_MANY_REQUESTS               =429,
        REQUEST_HEADER_FIELDS_TOO_LARGE =431,
        INTERNAL_SERVER_ERROR           =500,
        NOT_IMPLEMENTED                 =501,
        BAD_GATEWAY                     =502,
        SERVICE_UNAVAILABLE             =503,
        GATEWAY_TIMEOUT                 =504,
        HTTP_VERSION_NOT_SUPPORTED      =505,
    };

    typedef std::string header_key_type;
    typedef std::string header_value_type;

    struct iless {
        inline bool operator()(const header_key_type &lhs, const header_key_type &rhs) const
        { return strcasecmp(lhs.c_str(), rhs.c_str())<0; }
    };

    struct iequal {
        inline bool operator()(const header_key_type &lhs, const header_key_type &rhs) const
        { return strcasecmp(lhs.c_str(), rhs.c_str())==0; }
    };

    typedef std::multimap<header_key_type, header_value_type, iless> header_map;

    typedef std::chrono::steady_clock::duration timeout_type;
}}} // End of namespace fibio::http::common

namespace fibio { namespace http {
    using common::http_version;
    using common::http_method;
    using common::http_status_code;
    using common::timeout_type;
}}  // End of namespace fibio::http

#endif
<|endoftext|>


<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_PATH_VALIDATION_REPORT_HH
# define HPP_CORE_PATH_VALIDATION_REPORT_HH

# include <hpp/core/validation-report.hh>

namespace hpp {
  namespace core {
    /// \addtogroup validation
    /// \{

    /// Abstraction of path validation report
    ///
    /// This class is aimed at being derived to store information relative to
    /// various PathValidation derived classes.
    struct HPP_CORE_DLLAPI PathValidationReport :
      public ValidationReport
    {
			PathValidationReport()
			: ValidationReport()
			, configurationReport() {}
      PathValidationReport (const value_type& param,
			    const ValidationReportPtr_t& report) :
	parameter (param), configurationReport (report)
      {}

      virtual std::ostream& print (std::ostream& os) const
      {
	os << "Invalid configuration at parameter " << parameter << std::endl;
	os << *configurationReport;
	return os;
      }
      /// Parameter of the path where a invalid configuration has been found
      value_type parameter;
      ValidationReportPtr_t configurationReport;
    }; // class PathValidationReport
    /// \}
  } // namespace core
} // namespace hpp

#endif // HPP_CORE_PATH_VALIDATION_REPORT_HH
<commit_msg>PathValidationReport checks if configurationReport is NULL<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_PATH_VALIDATION_REPORT_HH
# define HPP_CORE_PATH_VALIDATION_REPORT_HH

# include <hpp/core/validation-report.hh>

namespace hpp {
  namespace core {
    /// \addtogroup validation
    /// \{

    /// Abstraction of path validation report
    ///
    /// This class is aimed at being derived to store information relative to
    /// various PathValidation derived classes.
    struct HPP_CORE_DLLAPI PathValidationReport :
      public ValidationReport
    {
			PathValidationReport()
			: ValidationReport()
			, configurationReport() {}
      PathValidationReport (const value_type& param,
			    const ValidationReportPtr_t& report) :
	parameter (param), configurationReport (report)
      {}

      virtual std::ostream& print (std::ostream& os) const
      {
	os << "Invalid configuration at parameter " << parameter << std::endl;
        if (!configurationReport) os << "No ValidationReport";
        else os << *configurationReport;
	return os;
      }
      /// Parameter of the path where a invalid configuration has been found
      value_type parameter;
      ValidationReportPtr_t configurationReport;
    }; // class PathValidationReport
    /// \}
  } // namespace core
} // namespace hpp

#endif // HPP_CORE_PATH_VALIDATION_REPORT_HH
<|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_GEOMETRY_ADAPTERS_HPP
#define MAPNIK_GEOMETRY_ADAPTERS_HPP

#include <mapnik/config.hpp>

// undef B0 to workaround https://svn.boost.org/trac/boost/ticket/10467
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#undef B0
#include <boost/geometry/geometries/register/linestring.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/geometries/register/ring.hpp>
// NOTE: ideally we would not include all of boost/geometry here to save on compile time
// however we need to pull in <boost/geometry/multi/multi.hpp> for things to work
// and once we do that the compile time is == to just including boost/geometry.hpp
#include <boost/geometry.hpp>
#pragma GCC diagnostic pop

#include <mapnik/geometry.hpp>
#include <mapnik/coord.hpp>
#include <mapnik/box2d.hpp>

#include <cstdint>

// register point
BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<double>, double, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<std::int64_t>, std::int64_t, boost::geometry::cs::cartesian, x, y)
// ring
BOOST_GEOMETRY_REGISTER_RING_TEMPLATED(mapnik::geometry::linear_ring)
// needed by box2d<double>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, boost::geometry::cs::cartesian, x, y)

namespace boost {

template <typename CoordinateType>
struct range_iterator<mapnik::geometry::line_string<CoordinateType> >
{
    using type = typename mapnik::geometry::line_string<CoordinateType>::iterator;
};

template <typename CoordinateType>
struct range_const_iterator<mapnik::geometry::line_string<CoordinateType> >
{
    using type = typename mapnik::geometry::line_string<CoordinateType>::const_iterator;
};

template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::iterator
range_begin(mapnik::geometry::line_string<CoordinateType> & line) {return line.begin();}

template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::iterator
range_end(mapnik::geometry::line_string<CoordinateType> & line) {return line.end();}

template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::const_iterator
range_begin(mapnik::geometry::line_string<CoordinateType> const& line) {return line.begin();}

template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::const_iterator
range_end(mapnik::geometry::line_string<CoordinateType> const& line) {return line.end();}

namespace geometry { namespace traits {

// register mapnik::box2d<double>
template<> struct tag<mapnik::box2d<double> > { using type = box_tag; };
template<> struct point_type<mapnik::box2d<double> > { using type = mapnik::coord2d; };

template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 0>
{
    using ct = coordinate_type<mapnik::coord2d>::type;
    static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}
    static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }
};

template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 1>
{
    using ct = coordinate_type<mapnik::coord2d>::type;
    static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}
    static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }
};

template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 0>
{
    using ct = coordinate_type<mapnik::coord2d>::type;
    static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}
    static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }
};

template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 1>
{
    using ct = coordinate_type<mapnik::coord2d>::type;
    static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}
    static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }
};

// mapnik::geometry::line_string
template<typename CoordinateType>
struct tag<mapnik::geometry::line_string<CoordinateType> >
{
    using type = linestring_tag;
};

// mapnik::geometry::polygon
template<typename CoordinateType>
struct tag<mapnik::geometry::polygon<CoordinateType> >
{
    using type = polygon_tag;
};

template <typename CoordinateType>
struct point_order<mapnik::geometry::linear_ring<CoordinateType> >
{
    static const order_selector value = counterclockwise;
};

template<typename CoordinateType>
struct tag<mapnik::geometry::multi_point<CoordinateType> >
{
    using type = multi_point_tag;
};

template<typename CoordinateType>
struct tag<mapnik::geometry::multi_line_string<CoordinateType> >
{
    using type = multi_linestring_tag;
};

template<typename CoordinateType>
struct tag<mapnik::geometry::multi_polygon<CoordinateType> >
{
    using type = multi_polygon_tag;
};

// ring
template <typename CoordinateType>
struct ring_const_type<mapnik::geometry::polygon<CoordinateType> >
{
    using type = typename mapnik::geometry::linear_ring<CoordinateType> const&;
};

template <typename CoordinateType>
struct ring_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
    using type = typename mapnik::geometry::linear_ring<CoordinateType>&;
};

// interior
template <typename CoordinateType>
struct interior_const_type<mapnik::geometry::polygon<CoordinateType> >
{
    using type = typename mapnik::geometry::polygon<CoordinateType>::rings_container const&;
};

template <typename CoordinateType>
struct interior_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
    using type = typename mapnik::geometry::polygon<CoordinateType>::rings_container&;
};

// exterior
template <typename CoordinateType>
struct exterior_ring<mapnik::geometry::polygon<CoordinateType> >
{
    static mapnik::geometry::linear_ring<CoordinateType> & get(mapnik::geometry::polygon<CoordinateType> & p)
    {
        return p.exterior_ring;
    }

    static mapnik::geometry::linear_ring<CoordinateType> const& get(mapnik::geometry::polygon<CoordinateType> const& p)
    {
        return p.exterior_ring;
    }
};

template <typename CoordinateType>
struct interior_rings<mapnik::geometry::polygon<CoordinateType> >
{
    using holes_type = typename mapnik::geometry::polygon<CoordinateType>::rings_container;
    static holes_type&  get(mapnik::geometry::polygon<CoordinateType> & p)
    {
        return p.interior_rings;
    }

    static holes_type const& get(mapnik::geometry::polygon<CoordinateType> const& p)
    {
        return p.interior_rings;
    }
};

}}}

#endif //MAPNIK_GEOMETRY_ADAPTERS_HPP
<commit_msg>adapt box2d<float> to boost::geometry<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_GEOMETRY_ADAPTERS_HPP
#define MAPNIK_GEOMETRY_ADAPTERS_HPP

#include <mapnik/config.hpp>

// undef B0 to workaround https://svn.boost.org/trac/boost/ticket/10467
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#undef B0
#include <boost/geometry/geometries/register/linestring.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <boost/geometry/geometries/register/ring.hpp>
// NOTE: ideally we would not include all of boost/geometry here to save on compile time
// however we need to pull in <boost/geometry/multi/multi.hpp> for things to work
// and once we do that the compile time is == to just including boost/geometry.hpp
#include <boost/geometry.hpp>
#pragma GCC diagnostic pop

#include <mapnik/geometry.hpp>
#include <mapnik/coord.hpp>
#include <mapnik/box2d.hpp>

#include <cstdint>

// register point
BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<double>, double, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<float>, float, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<std::int64_t>, std::int64_t, boost::geometry::cs::cartesian, x, y)
// ring
BOOST_GEOMETRY_REGISTER_RING_TEMPLATED(mapnik::geometry::linear_ring)
// needed by box2d<T>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, boost::geometry::cs::cartesian, x, y)
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2f, float,  boost::geometry::cs::cartesian, x, y)

namespace boost {

template <typename CoordinateType>
struct range_iterator<mapnik::geometry::line_string<CoordinateType> >
{
    using type = typename mapnik::geometry::line_string<CoordinateType>::iterator;
};

template <typename CoordinateType>
struct range_const_iterator<mapnik::geometry::line_string<CoordinateType> >
{
    using type = typename mapnik::geometry::line_string<CoordinateType>::const_iterator;
};

template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::iterator
range_begin(mapnik::geometry::line_string<CoordinateType> & line) {return line.begin();}

template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::iterator
range_end(mapnik::geometry::line_string<CoordinateType> & line) {return line.end();}

template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::const_iterator
range_begin(mapnik::geometry::line_string<CoordinateType> const& line) {return line.begin();}

template <typename CoordinateType>
inline typename mapnik::geometry::line_string<CoordinateType>::const_iterator
range_end(mapnik::geometry::line_string<CoordinateType> const& line) {return line.end();}

namespace geometry { namespace traits {

// register mapnik::box2d<double>
template<> struct tag<mapnik::box2d<double> > { using type = box_tag; };
template<> struct point_type<mapnik::box2d<double> > { using type = mapnik::coord2d; };

template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 0>
{
    using ct = coordinate_type<mapnik::coord2d>::type;
    static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}
    static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }
};

template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 1>
{
    using ct = coordinate_type<mapnik::coord2d>::type;
    static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}
    static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }
};

template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 0>
{
    using ct = coordinate_type<mapnik::coord2d>::type;
    static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}
    static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }
};

template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 1>
{
    using ct = coordinate_type<mapnik::coord2d>::type;
    static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}
    static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }
};

// box2d<float>
template<> struct tag<mapnik::box2d<float> > { using type = box_tag; };
template<> struct point_type<mapnik::box2d<float> > { using type = mapnik::coord2f; };

template <>
struct indexed_access<mapnik::box2d<float>, min_corner, 0>
{
    using ct = coordinate_type<mapnik::coord2f>::type;
    static inline ct get(mapnik::box2d<float> const& b) { return b.minx();}
    static inline void set(mapnik::box2d<float> &b, ct const& value) { b.set_minx(value); }
};

template <>
struct indexed_access<mapnik::box2d<float>, min_corner, 1>
{
    using ct = coordinate_type<mapnik::coord2f>::type;
    static inline ct get(mapnik::box2d<float> const& b) { return b.miny();}
    static inline void set(mapnik::box2d<float> &b, ct const& value) { b.set_miny(value); }
};

template <>
struct indexed_access<mapnik::box2d<float>, max_corner, 0>
{
    using ct = coordinate_type<mapnik::coord2f>::type;
    static inline ct get(mapnik::box2d<float> const& b) { return b.maxx();}
    static inline void set(mapnik::box2d<float> &b, ct const& value) { b.set_maxx(value); }
};

template <>
struct indexed_access<mapnik::box2d<float>, max_corner, 1>
{
    using ct = coordinate_type<mapnik::coord2f>::type;
    static inline ct get(mapnik::box2d<float> const& b) { return b.maxy();}
    static inline void set(mapnik::box2d<float> &b , ct const& value) { b.set_maxy(value); }
};

// mapnik::geometry::line_string
template<typename CoordinateType>
struct tag<mapnik::geometry::line_string<CoordinateType> >
{
    using type = linestring_tag;
};

// mapnik::geometry::polygon
template<typename CoordinateType>
struct tag<mapnik::geometry::polygon<CoordinateType> >
{
    using type = polygon_tag;
};

template <typename CoordinateType>
struct point_order<mapnik::geometry::linear_ring<CoordinateType> >
{
    static const order_selector value = counterclockwise;
};

template<typename CoordinateType>
struct tag<mapnik::geometry::multi_point<CoordinateType> >
{
    using type = multi_point_tag;
};

template<typename CoordinateType>
struct tag<mapnik::geometry::multi_line_string<CoordinateType> >
{
    using type = multi_linestring_tag;
};

template<typename CoordinateType>
struct tag<mapnik::geometry::multi_polygon<CoordinateType> >
{
    using type = multi_polygon_tag;
};

// ring
template <typename CoordinateType>
struct ring_const_type<mapnik::geometry::polygon<CoordinateType> >
{
    using type = typename mapnik::geometry::linear_ring<CoordinateType> const&;
};

template <typename CoordinateType>
struct ring_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
    using type = typename mapnik::geometry::linear_ring<CoordinateType>&;
};

// interior
template <typename CoordinateType>
struct interior_const_type<mapnik::geometry::polygon<CoordinateType> >
{
    using type = typename mapnik::geometry::polygon<CoordinateType>::rings_container const&;
};

template <typename CoordinateType>
struct interior_mutable_type<mapnik::geometry::polygon<CoordinateType> >
{
    using type = typename mapnik::geometry::polygon<CoordinateType>::rings_container&;
};

// exterior
template <typename CoordinateType>
struct exterior_ring<mapnik::geometry::polygon<CoordinateType> >
{
    static mapnik::geometry::linear_ring<CoordinateType> & get(mapnik::geometry::polygon<CoordinateType> & p)
    {
        return p.exterior_ring;
    }

    static mapnik::geometry::linear_ring<CoordinateType> const& get(mapnik::geometry::polygon<CoordinateType> const& p)
    {
        return p.exterior_ring;
    }
};

template <typename CoordinateType>
struct interior_rings<mapnik::geometry::polygon<CoordinateType> >
{
    using holes_type = typename mapnik::geometry::polygon<CoordinateType>::rings_container;
    static holes_type&  get(mapnik::geometry::polygon<CoordinateType> & p)
    {
        return p.interior_rings;
    }

    static holes_type const& get(mapnik::geometry::polygon<CoordinateType> const& p)
    {
        return p.interior_rings;
    }
};

}}}

#endif //MAPNIK_GEOMETRY_ADAPTERS_HPP
<|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_SYMBOLIZER_GRAMMAR_HPP
#define MAPNIK_SYMBOLIZER_GRAMMAR_HPP

#include <mapnik/config.hpp>

// boost
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

// mapnik
#include <mapnik/util/variant.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/symbolizer_utils.hpp>
#include <mapnik/json/error_handler.hpp>
#include <mapnik/json/generic_json.hpp>

namespace mapnik { namespace json {

namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;
namespace fusion = boost::fusion;
namespace standard_wide =  boost::spirit::standard_wide;
using standard_wide::space_type;

template <typename Symbolizer>
struct json_value_visitor
{
    json_value_visitor(Symbolizer & sym, mapnik::keys key)
        : sym_(sym), key_(key) {}

    void operator() (value_bool val) const
    {
        put<value_bool>(sym_, key_, val);
    }

    void operator() (value_integer val) const
    {
        put<value_integer>(sym_, key_, val);
    }

    void operator() (value_double val) const
    {
        put<value_double>(sym_, key_, val);
    }

    void operator() (std::string const& val) const
    {
        set_property(sym_, key_, val);
    }

    template <typename T>
    void operator() (T const& val) const
    {
        std::cerr << std::get<0>(get_meta(key_)) << ":" << val <<  std::endl;
        //put<T>(sym_, key_, val);
    }

    Symbolizer & sym_;
    keys key_;
};

template <typename T>
struct put_property_visitor
{
    using value_type = T;

    put_property_visitor(mapnik::keys key, value_type const& val)
        : key_(key), val_(val) {}

    template <typename Symbolizer>
    void operator() (Symbolizer & sym) const
    {
        mapnik::util::apply_visitor(json_value_visitor<Symbolizer>(sym, key_), val_);
    }

    keys key_;
    value_type const& val_;
};

struct put_property
{
    using result_type = void;
    template <typename T0,typename T1, typename T2>
    result_type operator() (T0 & sym, T1 const& name, T2 const& val) const
    {
        try
        {
            mapnik::util::apply_visitor(put_property_visitor<T2>(get_key(name),val), sym);
        }
        catch (std::runtime_error const& err)
        {
            std::cerr <<  err.what() << std::endl;
        }
    }
};

template <typename Iterator, typename ErrorHandler = error_handler<Iterator>>
struct symbolizer_grammar : qi::grammar<Iterator, space_type, symbolizer()>
{
    using json_value_type = util::variant<value_null,value_bool,value_integer,value_double, std::string>;
    symbolizer_grammar()
        : symbolizer_grammar::base_type(sym, "symbolizer"),
          json_()
    {
        qi::lit_type lit;
        qi::double_type double_;
        qi::int_type int_;
        qi::no_skip_type no_skip;
        qi::_val_type _val;
        qi::_a_type _a;
        qi::_r1_type _r1;
        qi::_1_type _1;
        standard_wide::char_type char_;
        using phoenix::construct;

        // generic json types
        json_.value =  json_.object | json_.array | json_.string_
            | json_.number
            ;

        json_.pairs = json_.key_value % lit(',')
            ;

        json_.key_value = (json_.string_ >> lit(':') >> json_.value)
            ;

        json_.object = lit('{')
            >> *json_.pairs
            >> lit('}')
            ;

        json_.array = lit('[')
            >> json_.value >> *(lit(',') >> json_.value)
            >> lit(']')
        ;

        json_.number %= json_.strict_double
            | json_.int__
            | lit("true") [_val = true]
            | lit ("false") [_val = false]
            | lit("null")[_val = construct<value_null>()]
            ;
        json_.unesc_char.add
            ("\\\"", '\"') // quotation mark
            ("\\\\", '\\') // reverse solidus
            ("\\/", '/')   // solidus
            ("\\b", '\b')  // backspace
            ("\\f", '\f')  // formfeed
            ("\\n", '\n')  // newline
            ("\\r", '\r')  // carrige return
            ("\\t", '\t')  // tab
        ;

        json_.string_ %= lit('"') >> no_skip[*(json_.unesc_char | "\\u" >> json_.hex4 | (char_ - lit('"')))] >> lit('"')
            ;

        sym = lit('{')
            >> lit("\"type\"") >> lit(':')
            >> (lit("\"PointSymbolizer\"")[_val = construct<point_symbolizer>()]
                |
                lit("\"LineSymbolizer\"")[_val = construct<line_symbolizer>()]
                |
                lit("\"PolygonSymbolizer\"")[_val = construct<polygon_symbolizer>()]
                )
            >> lit(',')
            >> lit("\"properties\"") >> lit(':')
            >> ((lit('{') >> *property(_val) >> lit('}')) | lit("null"))
            >> lit('}')
            ;

        property = (json_.string_ [_a = _1] >> lit(':') >> property_value [put_property_(_r1,_a,_1)]) % lit(',')
            ;

        property_value %= json_.number | json_.string_  ;

    }

    // generic JSON
    generic_json<Iterator> json_;
    // symbolizer
    qi::rule<Iterator, space_type, mapnik::symbolizer()> sym;
    qi::rule<Iterator,qi::locals<std::string>, void(mapnik::symbolizer&),space_type> property;
    qi::rule<Iterator, space_type, json_value_type()> property_value;

    phoenix::function<put_property> put_property_;
    // error
    //qi::on_error<qi::fail>(sym, error_handler(_1, _2, _3, _4));
};

}}

#endif // MAPNIK_SYMBOLIZER_GRAMMAR_HPP
<commit_msg>remove unused symbolizer_grammar.hpp (ref #3343)<commit_after><|endoftext|>


<commit_before><commit_msg>Fix for last commit<commit_after><|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 (C) 2016 ScyllaDB, Ltd.
 */

#pragma once

#include <boost/intrusive/list.hpp>

#include <seastar/core/timer.hh>
#include <seastar/core/loop.hh>

namespace seastar {

/// \addtogroup fiber-module
/// @{

/// Exception thrown when a condition variable is broken by
/// \ref condition_variable::broken().
class broken_condition_variable : public std::exception {
public:
    /// Reports the exception reason.
    virtual const char* what() const noexcept;
};

/// Exception thrown when wait() operation times out
/// \ref condition_variable::wait(time_point timeout).
class condition_variable_timed_out : public std::exception {
public:
    /// Reports the exception reason.
    virtual const char* what() const noexcept;
};

/// \brief Conditional variable.
///
/// This is a standard computer science condition variable sans locking,
/// since in seastar access to variables is atomic anyway, adapted
/// for futures.  You can wait for variable to be notified.
///
/// To support exceptional conditions, a \ref broken() method
/// is provided, which causes all current waiters to stop waiting,
/// with an exceptional future returned.  This allows causing all
/// fibers that are blocked on a condition variable to continue.
/// This issimilar to POSIX's `pthread_cancel()`, with \ref wait()
/// acting as a cancellation point.

class condition_variable {
private:
    using clock = typename timer<>::clock;
    using duration = typename clock::duration;
    using time_point = typename clock::time_point;

    // the base for queue waiters. looks complicated, but this is
    // to make it transparent once we add non-promise based nodes
    struct waiter : public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::auto_unlink>> {
        virtual ~waiter() = default;
        void timeout() noexcept;

        virtual void signal() noexcept = 0;
        virtual void set_exception(std::exception_ptr) noexcept = 0;
    };

    struct promise_waiter : public waiter, public promise<> {
        void signal() noexcept override {
            set_value();
            // note: we self-delete in either case we are woken
            // up. See usage below: only the resulting future
            // state is required once we've left the wait queue
            delete this;
        }
        void set_exception(std::exception_ptr ep) noexcept override {
            promise<>::set_exception(std::move(ep));
            // see comment above
            delete this;
        }
    };

    boost::intrusive::list<waiter, boost::intrusive::constant_time_size<false>> _waiters;
    std::exception_ptr _ex; //"broken" exception
    bool _signalled = false; // set to true if signalled while no waiters

    void add_waiter(waiter&) noexcept;
    void timeout(waiter&) noexcept;
    bool wakeup_first() noexcept;
    bool check_and_consume_signal() noexcept;
public:
    /// Constructs a condition_variable object.
    /// Initialzie the semaphore with a default value of 0 to enusre
    /// the first call to wait() before signal() won't be waken up immediately.
    condition_variable() noexcept = default;
    ~condition_variable();

    /// Waits until condition variable is signaled, may wake up without condition been met
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception.
    future<> wait() noexcept {
        if (check_and_consume_signal()) {
            return make_ready_future();
        }
        auto* w = new promise_waiter;
        auto f = w->get_future();
        add_waiter(*w);
        return f;
    }

    /// Waits until condition variable is signaled or timeout is reached
    ///
    /// \param timeout time point at which wait will exit with a timeout
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception. If timepoint is reached will return \ref condition_variable_timed_out exception.
    future<> wait(time_point timeout) noexcept {
        if (check_and_consume_signal()) {
            return make_ready_future();
        }
        struct timeout_waiter : public promise_waiter, public timer<> {};
        // use a unique_ptr here, because bind/set_callback can throw
        auto w = std::make_unique<timeout_waiter>();
        auto f = w->get_future();

        w->set_callback(std::bind(&waiter::timeout, w.get()));
        w->arm(timeout);
        add_waiter(*w.release());
        return f;
    }

    /// Waits until condition variable is signaled or timeout is reached
    ///
    /// \param timeout duration after which wait will exit with a timeout
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception. If timepoint is passed will return \ref condition_variable_timed_out exception.
    future<> wait(duration timeout) noexcept {
        return wait(timer<>::clock::now() + timeout);
    }

    /// Waits until condition variable is notified and pred() == true, otherwise
    /// wait again.
    ///
    /// \param pred predicate that checks that awaited condition is true
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken(), may contain an exception.
    template<typename Pred>
    SEASTAR_CONCEPT( requires seastar::InvokeReturns<Pred, bool> )
    future<> wait(Pred&& pred) noexcept {
        return do_until(std::forward<Pred>(pred), [this] {
            return wait();
        });
    }

    /// Waits until condition variable is notified and pred() == true or timeout is reached, otherwise
    /// wait again.
    ///
    /// \param timeout time point at which wait will exit with a timeout
    /// \param pred predicate that checks that awaited condition is true
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception. If timepoint is reached will return \ref condition_variable_timed_out exception.
    template<typename Pred>
    SEASTAR_CONCEPT( requires seastar::InvokeReturns<Pred, bool> )
    future<> wait(time_point timeout, Pred&& pred) noexcept {
        return do_until(std::forward<Pred>(pred), [this, timeout] {
            return wait(timeout);
        });
    }

    /// Waits until condition variable is notified and pred() == true or timeout is reached, otherwise
    /// wait again.
    ///
    /// \param timeout duration after which wait will exit with a timeout
    /// \param pred predicate that checks that awaited condition is true
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception. If timepoint is passed will return \ref condition_variable_timed_out exception.
    template<typename Pred>
    SEASTAR_CONCEPT( requires seastar::InvokeReturns<Pred, bool> )
    future<> wait(duration timeout, Pred&& pred) noexcept {
        return wait(timer<>::clock::now() + timeout, std::forward<Pred>(pred));
    }
    /// Notify variable and wake up a waiter if there is one
    void signal() noexcept;

    /// Notify variable and wake up all waiter
    void broadcast() noexcept;

    /// Signal to waiters that an error occurred.  \ref wait() will see
    /// an exceptional future<> containing the provided exception parameter.
    /// The future is made available immediately.
    void broken() noexcept;

    void broken(std::exception_ptr) noexcept;
};

/// @}

}
<commit_msg>condition_variable: Make std::chrono timeout operations templated<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 (C) 2016 ScyllaDB, Ltd.
 */

#pragma once

#include <boost/intrusive/list.hpp>

#include <seastar/core/timer.hh>
#include <seastar/core/loop.hh>

namespace seastar {

/// \addtogroup fiber-module
/// @{

/// Exception thrown when a condition variable is broken by
/// \ref condition_variable::broken().
class broken_condition_variable : public std::exception {
public:
    /// Reports the exception reason.
    virtual const char* what() const noexcept;
};

/// Exception thrown when wait() operation times out
/// \ref condition_variable::wait(time_point timeout).
class condition_variable_timed_out : public std::exception {
public:
    /// Reports the exception reason.
    virtual const char* what() const noexcept;
};

/// \brief Conditional variable.
///
/// This is a standard computer science condition variable sans locking,
/// since in seastar access to variables is atomic anyway, adapted
/// for futures.  You can wait for variable to be notified.
///
/// To support exceptional conditions, a \ref broken() method
/// is provided, which causes all current waiters to stop waiting,
/// with an exceptional future returned.  This allows causing all
/// fibers that are blocked on a condition variable to continue.
/// This issimilar to POSIX's `pthread_cancel()`, with \ref wait()
/// acting as a cancellation point.

class condition_variable {
private:
    // the base for queue waiters. looks complicated, but this is
    // to make it transparent once we add non-promise based nodes
    struct waiter : public boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::auto_unlink>> {
        virtual ~waiter() = default;
        void timeout() noexcept;

        virtual void signal() noexcept = 0;
        virtual void set_exception(std::exception_ptr) noexcept = 0;
    };

    struct promise_waiter : public waiter, public promise<> {
        void signal() noexcept override {
            set_value();
            // note: we self-delete in either case we are woken
            // up. See usage below: only the resulting future
            // state is required once we've left the wait queue
            delete this;
        }
        void set_exception(std::exception_ptr ep) noexcept override {
            promise<>::set_exception(std::move(ep));
            // see comment above
            delete this;
        }
    };

    boost::intrusive::list<waiter, boost::intrusive::constant_time_size<false>> _waiters;
    std::exception_ptr _ex; //"broken" exception
    bool _signalled = false; // set to true if signalled while no waiters

    void add_waiter(waiter&) noexcept;
    void timeout(waiter&) noexcept;
    bool wakeup_first() noexcept;
    bool check_and_consume_signal() noexcept;
public:
    /// Constructs a condition_variable object.
    /// Initialzie the semaphore with a default value of 0 to enusre
    /// the first call to wait() before signal() won't be waken up immediately.
    condition_variable() noexcept = default;
    ~condition_variable();

    /// Waits until condition variable is signaled, may wake up without condition been met
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception.
    future<> wait() noexcept {
        if (check_and_consume_signal()) {
            return make_ready_future();
        }
        auto* w = new promise_waiter;
        auto f = w->get_future();
        add_waiter(*w);
        return f;
    }

    /// Waits until condition variable is signaled or timeout is reached
    ///
    /// \param timeout time point at which wait will exit with a timeout
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception. If timepoint is reached will return \ref condition_variable_timed_out exception.
    template<typename Clock = typename timer<>::clock, typename Duration = typename Clock::duration>
    future<> wait(std::chrono::time_point<Clock, Duration> timeout) noexcept {
        if (check_and_consume_signal()) {
            return make_ready_future();
        }
        struct timeout_waiter : public promise_waiter, public timer<Clock> {};
        auto w = std::make_unique<timeout_waiter>();
        auto f = w->get_future();

        w->set_callback(std::bind(&waiter::timeout, w.get()));
        w->arm(timeout);
        add_waiter(*w.release());
        return f;
    }

    /// Waits until condition variable is signaled or timeout is reached
    ///
    /// \param timeout duration after which wait will exit with a timeout
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception. If timepoint is passed will return \ref condition_variable_timed_out exception.
    template<typename Rep, typename Period>
    future<> wait(std::chrono::duration<Rep, Period> timeout) noexcept {
        return wait(timer<>::clock::now() + timeout);
    }

    /// Waits until condition variable is notified and pred() == true, otherwise
    /// wait again.
    ///
    /// \param pred predicate that checks that awaited condition is true
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken(), may contain an exception.
    template<typename Pred>
    SEASTAR_CONCEPT( requires seastar::InvokeReturns<Pred, bool> )
    future<> wait(Pred&& pred) noexcept {
        return do_until(std::forward<Pred>(pred), [this] {
            return wait();
        });
    }

    /// Waits until condition variable is notified and pred() == true or timeout is reached, otherwise
    /// wait again.
    ///
    /// \param timeout time point at which wait will exit with a timeout
    /// \param pred predicate that checks that awaited condition is true
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception. If timepoint is reached will return \ref condition_variable_timed_out exception.
    template<typename Clock = typename timer<>::clock, typename Duration = typename Clock::duration, typename Pred>
    SEASTAR_CONCEPT( requires seastar::InvokeReturns<Pred, bool> )
    future<> wait(std::chrono::time_point<Clock, Duration> timeout, Pred&& pred) noexcept {
        return do_until(std::forward<Pred>(pred), [this, timeout] {
            return wait(timeout);
        });
    }

    /// Waits until condition variable is notified and pred() == true or timeout is reached, otherwise
    /// wait again.
    ///
    /// \param timeout duration after which wait will exit with a timeout
    /// \param pred predicate that checks that awaited condition is true
    ///
    /// \return a future that becomes ready when \ref signal() is called
    ///         If the condition variable was \ref broken() will return \ref broken_condition_variable
    ///         exception. If timepoint is passed will return \ref condition_variable_timed_out exception.
    template<typename Rep, typename Period, typename Pred>
    SEASTAR_CONCEPT( requires seastar::InvokeReturns<Pred, bool> )
    future<> wait(std::chrono::duration<Rep, Period> timeout, Pred&& pred) noexcept {
        return wait(timer<>::clock::now() + timeout, std::forward<Pred>(pred));
    }

    /// Notify variable and wake up a waiter if there is one
    void signal() noexcept;

    /// Notify variable and wake up all waiter
    void broadcast() noexcept;

    /// Signal to waiters that an error occurred.  \ref wait() will see
    /// an exceptional future<> containing the provided exception parameter.
    /// The future is made available immediately.
    void broken() noexcept;

    void broken(std::exception_ptr) noexcept;
};

/// @}

}
<|endoftext|>


<commit_before>#include <StdAfx.h>
#include "ProjectionHelper.h"

// ***************************************************************
//		IsEmpty()
// ***************************************************************
bool ProjectionHelper::IsEmpty(IGeoProjection* gp)
{
	if (!gp) return true;
	VARIANT_BOOL isEmpty;
	gp->get_IsEmpty(&isEmpty);
	return isEmpty ? true : false;
}

// ***************************************************************
//		IsGeographic()
// ***************************************************************
bool ProjectionHelper::IsGeographic(IGeoProjection* gp)
{
	if (!gp) return false;
	VARIANT_BOOL geograhpic;
	gp->get_IsGeographic(&geograhpic);
	return geograhpic ? true : false;
}

// ***************************************************************
//		IsSame()
// ***************************************************************
bool ProjectionHelper::IsSame(IGeoProjection* gp1, IGeoProjection* gp2, IExtents* bounds, int sampleSize)
{
	if (!gp1 || !gp2 || !bounds) return false;
	VARIANT_BOOL vb;
	gp1->get_IsSameExt(gp2, bounds, sampleSize, &vb);
	return vb ? true : false;
}

// ***************************************************************
//		ToString()
// ***************************************************************
CString ProjectionHelper::ToString(IGeoProjection* gp)
{
	if (!gp) return "";

	CComBSTR str;
	if (!IsEmpty(gp)) {
		gp->ExportToProj4(&str);
	}
	else {
		str = L"";
	}

	USES_CONVERSION;
	return str.Length() > 0 ? OLE2A(str) : "<empty>";
}

// ***************************************************************
//		GetSpatialReference()
// ***************************************************************
void ProjectionHelper::GetSpatialReference(IGeoProjection* gp, OGRSpatialReference& result)
{
	if (!gp) return;

	// TODO: importFromProj4 is deprecated:
	CComBSTR bstr;
	gp->ExportToProj4(&bstr);

	USES_CONVERSION;
	CString s = OLE2A(bstr);
	result.importFromProj4(s);
}

// ***************************************************************
//		ImportFromEsri()
// ***************************************************************
OGRErr ProjectionHelper::ImportFromEsri(OGRSpatialReference* sr, CString proj)
{
	if (!sr) {
		return false;
	}

	char* apszPrj[2];
	char* s = proj.GetBuffer();
	apszPrj[0] = s;
	apszPrj[1] = nullptr;

	// Parameters: papszPrj	NULL terminated list of strings containing the definition.
	return sr->importFromESRI(apszPrj);
}

// ***************************************************************
//		ImportFromWkt()
// ***************************************************************
OGRErr ProjectionHelper::ImportFromWkt(OGRSpatialReference* sr, CString proj)
{
	if (!sr) {
		return false;
	}

	char* s = proj.GetBuffer();

	// TODO: Deprecated: GDAL 2.3. Use importFromWkt(const char**) instead.
	return sr->importFromWkt(&s);

	// TODO: Should we use Validate (https://gdal.org/api/ogrspatialref.html#_CPPv4NK19OGRSpatialReference8ValidateEv)
	// Validate CRS imported with importFromWkt()
}

// ***************************************************************
//		ExportFromWkt()
// ***************************************************************
OGRErr ProjectionHelper::ExportToWkt(OGRSpatialReference* sr, CString& proj)
{
	if (!sr) {
		return false;
	}

	char* s = nullptr;
	const OGRErr err = sr->exportToWkt(&s);

	proj = s;

	if (s) {
		CPLFree(s);
	}

	return err;
}

// ***************************************************************
//		ExportFromWktEx()
//  Starting with GDAL 3.0, the OGRSpatialReference::exportToWkt() method accepts options
// ***************************************************************
OGRErr ProjectionHelper::ExportToWktEx(OGRSpatialReference* sr, CString& proj)
{
	if (!sr) {
		return false;
	}

	char* s = nullptr;
	const char* apszOptions[3] = { "FORMAT=WKT2_2019", "MULTILINE=YES", nullptr };
	const OGRErr err = sr->exportToWkt(&s, apszOptions);

	proj = s;

	if (s) {
		CPLFree(s);
	}

	return err;
}

// ************************************************************
//		SupportsWorldWideTransform
// ************************************************************
bool ProjectionHelper::SupportsWorldWideTransform(IGeoProjection* mapProjection, IGeoProjection* wgsProjection)
{
	VARIANT_BOOL isGeograpic;
	mapProjection->get_IsGeographic(&isGeograpic);
	if (isGeograpic)
	{
		return true;
	}

	double TOLERANCE = 0.00001;
	VARIANT_BOOL vb1, vb2, vb3;
	double minLng = -180.0, maxLng = 180.0, minLat = -85.05112878, maxLat = 85.05112878;
	double x1 = minLng, x2 = maxLng, y1 = minLat, y2 = maxLat;
	double x3 = 0.0, y3 = 0.0;

	m_globalSettings.suppressGdalErrors = true;
	wgsProjection->Transform(&x1, &y1, &vb1);
	wgsProjection->Transform(&x2, &y2, &vb2);
	wgsProjection->Transform(&x3, &y3, &vb3);
	m_globalSettings.suppressGdalErrors = false;

	if ((y3 > y2 && y3 > y1) || (y3 < y2 && y3 < y1))
	{
		// this check that direction of Y axis is the same on its whole length;
		// for Lambert Conformal Conic, that's not the case
		return false;
	}

	if (vb1 && vb2 && vb3)
	{
		mapProjection->Transform(&x1, &y1, &vb1);
		mapProjection->Transform(&x2, &y2, &vb1);
		if (abs(x1 - minLng) < TOLERANCE &&
			abs(x2 - maxLng) < TOLERANCE &&
			abs(y1 - minLat) < TOLERANCE &&
			abs(y2 - maxLat) < TOLERANCE)
		{
			return true;
		}
	}

	return false;
}

<commit_msg>MWGIS-272; update ImportFromWkt for the latest GDAL library.<commit_after>#include <StdAfx.h>
#include "ProjectionHelper.h"

// ***************************************************************
//		IsEmpty()
// ***************************************************************
bool ProjectionHelper::IsEmpty(IGeoProjection* gp)
{
	if (!gp) return true;
	VARIANT_BOOL isEmpty;
	gp->get_IsEmpty(&isEmpty);
	return isEmpty ? true : false;
}

// ***************************************************************
//		IsGeographic()
// ***************************************************************
bool ProjectionHelper::IsGeographic(IGeoProjection* gp)
{
	if (!gp) return false;
	VARIANT_BOOL geograhpic;
	gp->get_IsGeographic(&geograhpic);
	return geograhpic ? true : false;
}

// ***************************************************************
//		IsSame()
// ***************************************************************
bool ProjectionHelper::IsSame(IGeoProjection* gp1, IGeoProjection* gp2, IExtents* bounds, int sampleSize)
{
	if (!gp1 || !gp2 || !bounds) return false;
	VARIANT_BOOL vb;
	gp1->get_IsSameExt(gp2, bounds, sampleSize, &vb);
	return vb ? true : false;
}

// ***************************************************************
//		ToString()
// ***************************************************************
CString ProjectionHelper::ToString(IGeoProjection* gp)
{
	if (!gp) return "";

	CComBSTR str;
	if (!IsEmpty(gp)) {
		gp->ExportToProj4(&str);
	}
	else {
		str = L"";
	}

	USES_CONVERSION;
	return str.Length() > 0 ? OLE2A(str) : "<empty>";
}

// ***************************************************************
//		GetSpatialReference()
// ***************************************************************
void ProjectionHelper::GetSpatialReference(IGeoProjection* gp, OGRSpatialReference& result)
{
	if (!gp) return;

	// TODO: importFromProj4 is deprecated:
	CComBSTR bstr;
	gp->ExportToProj4(&bstr);

	USES_CONVERSION;
	CString s = OLE2A(bstr);
	result.importFromProj4(s);
}

// ***************************************************************
//		ImportFromEsri()
// ***************************************************************
OGRErr ProjectionHelper::ImportFromEsri(OGRSpatialReference* sr, CString proj)
{
	if (!sr) {
		return false;
	}

	char* apszPrj[2];
	char* s = proj.GetBuffer();
	apszPrj[0] = s;
	apszPrj[1] = nullptr;

	// Parameters: papszPrj	NULL terminated list of strings containing the definition.
	return sr->importFromESRI(apszPrj);
}

// ***************************************************************
//		ImportFromWkt()
// ***************************************************************
OGRErr ProjectionHelper::ImportFromWkt(OGRSpatialReference* sr, CString proj)
{
	if (!sr)
	{
		return false;
	}

	const char* s = proj.GetBuffer();

	OGRErr result = OGRERR_NONE;
	// use newer method importFromWkt(const char*)
	if ((result = sr->importFromWkt(&s)) == OGRERR_NONE)
	{
		// then Validate (https://gdal.org/api/ogrspatialref.html#_CPPv4NK19OGRSpatialReference8ValidateEv)
		return sr->Validate();
	}
	else
	{
		// return error from failed import
		return result;
	}
}

// ***************************************************************
//		ExportFromWkt()
// ***************************************************************
OGRErr ProjectionHelper::ExportToWkt(OGRSpatialReference* sr, CString& proj)
{
	if (!sr) {
		return false;
	}

	char* s = nullptr;
	const OGRErr err = sr->exportToWkt(&s);

	proj = s;

	if (s) {
		CPLFree(s);
	}

	return err;
}

// ***************************************************************
//		ExportFromWktEx()
//  Starting with GDAL 3.0, the OGRSpatialReference::exportToWkt() method accepts options
// ***************************************************************
OGRErr ProjectionHelper::ExportToWktEx(OGRSpatialReference* sr, CString& proj)
{
	if (!sr) {
		return false;
	}

	char* s = nullptr;
	const char* apszOptions[3] = { "FORMAT=WKT2_2019", "MULTILINE=YES", nullptr };
	const OGRErr err = sr->exportToWkt(&s, apszOptions);

	proj = s;

	if (s) {
		CPLFree(s);
	}

	return err;
}

// ************************************************************
//		SupportsWorldWideTransform
// ************************************************************
bool ProjectionHelper::SupportsWorldWideTransform(IGeoProjection* mapProjection, IGeoProjection* wgsProjection)
{
	VARIANT_BOOL isGeograpic;
	mapProjection->get_IsGeographic(&isGeograpic);
	if (isGeograpic)
	{
		return true;
	}

	double TOLERANCE = 0.00001;
	VARIANT_BOOL vb1, vb2, vb3;
	double minLng = -180.0, maxLng = 180.0, minLat = -85.05112878, maxLat = 85.05112878;
	double x1 = minLng, x2 = maxLng, y1 = minLat, y2 = maxLat;
	double x3 = 0.0, y3 = 0.0;

	m_globalSettings.suppressGdalErrors = true;
	wgsProjection->Transform(&x1, &y1, &vb1);
	wgsProjection->Transform(&x2, &y2, &vb2);
	wgsProjection->Transform(&x3, &y3, &vb3);
	m_globalSettings.suppressGdalErrors = false;

	if ((y3 > y2 && y3 > y1) || (y3 < y2 && y3 < y1))
	{
		// this check that direction of Y axis is the same on its whole length;
		// for Lambert Conformal Conic, that's not the case
		return false;
	}

	if (vb1 && vb2 && vb3)
	{
		mapProjection->Transform(&x1, &y1, &vb1);
		mapProjection->Transform(&x2, &y2, &vb1);
		if (abs(x1 - minLng) < TOLERANCE &&
			abs(x2 - maxLng) < TOLERANCE &&
			abs(y1 - minLat) < TOLERANCE &&
			abs(y2 - maxLat) < TOLERANCE)
		{
			return true;
		}
	}

	return false;
}

<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mhome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "quicklaunchbarview.h"
#include "quicklaunchbar.h"
#include "launcher.h"
#include "mainwindow.h"

#include <QGraphicsLinearLayout>
#include <MButton>
#include <MViewCreator>

const int QuickLaunchBarView::TOGGLE_LAUNCHER_BUTTON_INDEX = 2;

QuickLaunchBarView::QuickLaunchBarView(QuickLaunchBar *controller) : MWidgetView(controller),
    launcherButtonLayout(new QGraphicsLinearLayout(Qt::Horizontal)),
    toggleLauncherButton(new MButton)
{
    QGraphicsLinearLayout *l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->setContentsMargins(0, 0, 0, 0);
    controller->setLayout(l);

    // A layout for the launcher buttons
    launcherButtonLayout->setContentsMargins(0, 0, 0, 0);

    // Create launcher button
    toggleLauncherButton->setViewType("icon");
    toggleLauncherButton->setObjectName("ToggleLauncherButton");
    toggleLauncherButton->setIconID("icon-m-quicklaunchbar-menu-open");
    connect(toggleLauncherButton, SIGNAL(clicked()), controller, SIGNAL(toggleLauncherButtonClicked()));

    // Put the stuff into a layout
    l->addStretch();
    l->addItem(launcherButtonLayout);
    l->addStretch();
    MButton *appletSpaceButton = new MButton("Applet Space");
    connect(appletSpaceButton, SIGNAL(clicked()), controller, SIGNAL(toggleAppletSpaceButtonClicked()));
    l->addItem(appletSpaceButton);
}

QuickLaunchBarView::~QuickLaunchBarView()
{
}

void QuickLaunchBarView::setupModel()
{
    MWidgetView::setupModel();
    QList<const char *> modifications;
    modifications << QuickLaunchBarModel::Widgets;
    updateData(modifications);
}

void QuickLaunchBarView::updateData(const QList<const char *>& modifications)
{
    MWidgetView::updateData(modifications);
    const char *member;
    foreach(member, modifications) {
        if (member == QuickLaunchBarModel::Widgets) {
            // Remove everything from the launcher button layout
            while (launcherButtonLayout->count() > 0) {
                launcherButtonLayout->removeAt(0);
            }

            // Add all launcher buttons to the launcher button layout
            foreach (MWidget *widget, model()->widgets()) {
                launcherButtonLayout->addItem(widget);

                if (launcherButtonLayout->count() == TOGGLE_LAUNCHER_BUTTON_INDEX) {
                    // Add a launcher button in the expected index
                    launcherButtonLayout->addItem(toggleLauncherButton);
                }
            }
        }
    }
}

M_REGISTER_VIEW_NEW(QuickLaunchBarView, QuickLaunchBar)
<commit_msg>Changes: Disabled the applet space for now<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mhome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "quicklaunchbarview.h"
#include "quicklaunchbar.h"
#include "launcher.h"
#include "mainwindow.h"

#include <QGraphicsLinearLayout>
#include <MButton>
#include <MViewCreator>

const int QuickLaunchBarView::TOGGLE_LAUNCHER_BUTTON_INDEX = 2;

QuickLaunchBarView::QuickLaunchBarView(QuickLaunchBar *controller) : MWidgetView(controller),
    launcherButtonLayout(new QGraphicsLinearLayout(Qt::Horizontal)),
    toggleLauncherButton(new MButton)
{
    QGraphicsLinearLayout *l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->setContentsMargins(0, 0, 0, 0);
    controller->setLayout(l);

    // A layout for the launcher buttons
    launcherButtonLayout->setContentsMargins(0, 0, 0, 0);

    // Create launcher button
    toggleLauncherButton->setViewType("icon");
    toggleLauncherButton->setObjectName("ToggleLauncherButton");
    toggleLauncherButton->setIconID("icon-m-quicklaunchbar-menu-open");
    connect(toggleLauncherButton, SIGNAL(clicked()), controller, SIGNAL(toggleLauncherButtonClicked()));

    // Put the stuff into a layout
    l->addStretch();
    l->addItem(launcherButtonLayout);
    l->addStretch();

    // The applet space is currently disabled
    /*
    MButton *appletSpaceButton = new MButton("Applet Space");
    connect(appletSpaceButton, SIGNAL(clicked()), controller, SIGNAL(toggleAppletSpaceButtonClicked()));
    l->addItem(appletSpaceButton);
    */
}

QuickLaunchBarView::~QuickLaunchBarView()
{
}

void QuickLaunchBarView::setupModel()
{
    MWidgetView::setupModel();
    QList<const char *> modifications;
    modifications << QuickLaunchBarModel::Widgets;
    updateData(modifications);
}

void QuickLaunchBarView::updateData(const QList<const char *>& modifications)
{
    MWidgetView::updateData(modifications);
    const char *member;
    foreach(member, modifications) {
        if (member == QuickLaunchBarModel::Widgets) {
            // Remove everything from the launcher button layout
            while (launcherButtonLayout->count() > 0) {
                launcherButtonLayout->removeAt(0);
            }

            // Add all launcher buttons to the launcher button layout
            foreach (MWidget *widget, model()->widgets()) {
                launcherButtonLayout->addItem(widget);

                if (launcherButtonLayout->count() == TOGGLE_LAUNCHER_BUTTON_INDEX) {
                    // Add a launcher button in the expected index
                    launcherButtonLayout->addItem(toggleLauncherButton);
                }
            }
        }
    }
}

M_REGISTER_VIEW_NEW(QuickLaunchBarView, QuickLaunchBar)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLChangeTrackingExportHelper.hxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: rt $ $Date: 2008-01-29 15:33:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SC_XMLCHANGETRACKINGEXPORTHELPER_HXX
#define _SC_XMLCHANGETRACKINGEXPORTHELPER_HXX

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#include <list>
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

class ScChangeAction;
class ScChangeTrack;
class ScXMLExport;
class ScBaseCell;
class ScChangeActionDel;
class ScBigRange;
class ScEditEngineTextObj;
class ScChangeActionTable;
class String;
class DateTime;

typedef std::list<ScChangeActionDel*> ScMyDeletionsList;

class ScChangeTrackingExportHelper
{
    ScXMLExport&    rExport;

    ScChangeTrack*  pChangeTrack;
    ScEditEngineTextObj* pEditTextObj;
    ScChangeActionTable* pDependings;
    rtl::OUString   sChangeIDPrefix;
    com::sun::star::uno::Reference<com::sun::star::text::XText> xText;

    rtl::OUString GetChangeID(const sal_uInt32 nActionNumber);
    void GetAcceptanceState(const ScChangeAction* pAction);

    void WriteBigRange(const ScBigRange& rBigRange, xmloff::token::XMLTokenEnum aName);
    void WriteChangeInfo(const ScChangeAction* pAction);
    void WriteGenerated(const ScChangeAction* pDependAction);
    void WriteDeleted(const ScChangeAction* pDependAction);
    void WriteDepending(const ScChangeAction* pDependAction);
    void WriteDependings(ScChangeAction* pAction);

    void WriteEmptyCell();
    void SetValueAttributes(const double& fValue, const String& sValue);
    void WriteValueCell(const ScBaseCell* pCell, const String& sValue);
    void WriteStringCell(const ScBaseCell* pCell);
    void WriteEditCell(const ScBaseCell* pCell);
    void WriteFormulaCell(const ScBaseCell* pCell, const String& sValue);
    void WriteCell(const ScBaseCell* pCell, const String& sValue);

    void WriteContentChange(ScChangeAction* pAction);
    void AddInsertionAttributes(const ScChangeAction* pAction);
    void WriteInsertion(ScChangeAction* pAction);
    void AddDeletionAttributes(const ScChangeActionDel* pAction, const ScChangeActionDel* pLastAction);
    void WriteDeletionCells(ScChangeActionDel* pAction);
    void WriteCutOffs(const ScChangeActionDel* pAction);
    void WriteDeletion(ScChangeAction* pAction);
    void WriteMovement(ScChangeAction* pAction);
    void WriteRejection(ScChangeAction* pAction);

    void CollectCellAutoStyles(const ScBaseCell* pBaseCell);
    void CollectActionAutoStyles(ScChangeAction* pAction);
    void WorkWithChangeAction(ScChangeAction* pAction);
public:
    ScChangeTrackingExportHelper(ScXMLExport& rExport);
    ~ScChangeTrackingExportHelper();

    void WriteChangeViewSettings();
    void CollectAutoStyles();
    void CollectAndWriteChanges();
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.16.88); FILE MERGED 2008/04/01 15:30:23 thb 1.16.88.3: #i85898# Stripping all external header guards 2008/04/01 12:36:29 thb 1.16.88.2: #i85898# Stripping all external header guards 2008/03/31 17:14:54 rt 1.16.88.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: XMLChangeTrackingExportHelper.hxx,v $
 * $Revision: 1.17 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SC_XMLCHANGETRACKINGEXPORTHELPER_HXX
#define _SC_XMLCHANGETRACKINGEXPORTHELPER_HXX

#include <xmloff/xmltoken.hxx>
#include <list>
#include <com/sun/star/text/XText.hpp>
#include <rtl/ustrbuf.hxx>

class ScChangeAction;
class ScChangeTrack;
class ScXMLExport;
class ScBaseCell;
class ScChangeActionDel;
class ScBigRange;
class ScEditEngineTextObj;
class ScChangeActionTable;
class String;
class DateTime;

typedef std::list<ScChangeActionDel*> ScMyDeletionsList;

class ScChangeTrackingExportHelper
{
    ScXMLExport&    rExport;

    ScChangeTrack*  pChangeTrack;
    ScEditEngineTextObj* pEditTextObj;
    ScChangeActionTable* pDependings;
    rtl::OUString   sChangeIDPrefix;
    com::sun::star::uno::Reference<com::sun::star::text::XText> xText;

    rtl::OUString GetChangeID(const sal_uInt32 nActionNumber);
    void GetAcceptanceState(const ScChangeAction* pAction);

    void WriteBigRange(const ScBigRange& rBigRange, xmloff::token::XMLTokenEnum aName);
    void WriteChangeInfo(const ScChangeAction* pAction);
    void WriteGenerated(const ScChangeAction* pDependAction);
    void WriteDeleted(const ScChangeAction* pDependAction);
    void WriteDepending(const ScChangeAction* pDependAction);
    void WriteDependings(ScChangeAction* pAction);

    void WriteEmptyCell();
    void SetValueAttributes(const double& fValue, const String& sValue);
    void WriteValueCell(const ScBaseCell* pCell, const String& sValue);
    void WriteStringCell(const ScBaseCell* pCell);
    void WriteEditCell(const ScBaseCell* pCell);
    void WriteFormulaCell(const ScBaseCell* pCell, const String& sValue);
    void WriteCell(const ScBaseCell* pCell, const String& sValue);

    void WriteContentChange(ScChangeAction* pAction);
    void AddInsertionAttributes(const ScChangeAction* pAction);
    void WriteInsertion(ScChangeAction* pAction);
    void AddDeletionAttributes(const ScChangeActionDel* pAction, const ScChangeActionDel* pLastAction);
    void WriteDeletionCells(ScChangeActionDel* pAction);
    void WriteCutOffs(const ScChangeActionDel* pAction);
    void WriteDeletion(ScChangeAction* pAction);
    void WriteMovement(ScChangeAction* pAction);
    void WriteRejection(ScChangeAction* pAction);

    void CollectCellAutoStyles(const ScBaseCell* pBaseCell);
    void CollectActionAutoStyles(ScChangeAction* pAction);
    void WorkWithChangeAction(ScChangeAction* pAction);
public:
    ScChangeTrackingExportHelper(ScXMLExport& rExport);
    ~ScChangeTrackingExportHelper();

    void WriteChangeViewSettings();
    void CollectAutoStyles();
    void CollectAndWriteChanges();
};

#endif
<|endoftext|>


<commit_before>#include "Genes/King_Confinement_Gene.h"

#include <cmath>
#include <array>
#include <memory>
#include <map>

#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"
#include "Game/Square.h"
#include "Game/Piece.h"

#include "Utility.h"

King_Confinement_Gene::King_Confinement_Gene() :
    friendly_block_score(0.0),
    enemy_block_score(0.0),
    maximum_distance(1)
{
}

std::unique_ptr<Gene> King_Confinement_Gene::duplicate() const
{
    return std::make_unique<King_Confinement_Gene>(*this);
}

std::string King_Confinement_Gene::name() const
{
    return "King Confinement Gene";
}

void King_Confinement_Gene::load_properties()
{
    Gene::load_properties();
    friendly_block_score = properties["Friendly Block Score"];
    enemy_block_score = properties["Enemy Block Score"];
    maximum_distance = int(properties["Maximum Distance"]);
}

void King_Confinement_Gene::reset_properties() const
{
    Gene::reset_properties();
    properties["Friendly Block Score"] = friendly_block_score;
    properties["Enemy Block Score"] = enemy_block_score;
    properties["Maximum Distance"] = maximum_distance;
}

void King_Confinement_Gene::gene_specific_mutation()
{
    make_priority_minimum_zero();
    auto mutation_size = Random::random_laplace(2.0);
    switch(Random::random_integer(1, 3))
    {
        case 1:
            friendly_block_score += mutation_size;
            break;
        case 2:
            enemy_block_score += mutation_size;
            break;
        case 3:
            maximum_distance += int(mutation_size);
            maximum_distance = Math::clamp(maximum_distance, 1, 63);
            break;
        default:
            throw std::logic_error("Bad random value in King Confinement Gene");
    }
}

double King_Confinement_Gene::score_board(const Board& board, const Board& opposite_board, size_t) const
{
    // A flood-fill-like algorithm to count the squares that are reachable by the
    // king from its current positions with unlimited consecutive moves. The
    // boundaries of this area area squares attacked by the other color or occupied
    // by pieces of the same color.
    //
    // The more moves it takes to reach a square, the less it adds to the score.

    std::vector<Square> square_queue;
    square_queue.reserve(64);
    auto perspective = board.whose_turn();
    const auto& king_square = board.find_king(perspective);
    square_queue.push_back(king_square);

    std::array<int, 64> distance;
    distance.fill(-1); // never-visited value
    distance[Board::square_index(king_square.file, king_square.rank)] = 0;

    auto squares_safe_for_king = opposite_board.squares_safe_for_king();

    double friendly_block_total = 0.0;
    double enemy_block_total = 0.0;
    int free_space_total = 0;

    for(size_t i = 0; i < square_queue.size(); ++i)
    {
        auto square = square_queue[i];
        auto square_index = Board::square_index(square.file, square.rank);

        auto attacked_by_other = ! squares_safe_for_king[square_index];
        auto dist = distance[square_index];

        auto piece = board.piece_on_square(square.file, square.rank);
        bool occupied_by_same = piece &&
                                piece->color() == perspective &&
                                piece->type() != KING;

        if(occupied_by_same)
        {
            friendly_block_total += friendly_block_score;
        }
        else if(attacked_by_other)
        {
            enemy_block_total += enemy_block_score;
        }
        else
        {
            ++free_space_total;
        }

        auto reachable = (square == king_square) || (! occupied_by_same && ! attacked_by_other);

        // Add surrounding squares to square_queue.
        // always check the squares surrounding the king's current positions, even if
        // it is not safe (i.e., the king is in check).
        if(reachable && dist < maximum_distance)
        {
            for(char new_file = square.file - 1; new_file <= square.file + 1; ++new_file)
            {
                if( ! board.inside_board(new_file))
                {
                    continue;
                }

                for(int new_rank = square.rank - 1; new_rank <= square.rank + 1; ++new_rank)
                {
                    if( ! board.inside_board(new_rank))
                    {
                        continue;
                    }

                    auto new_index = Board::square_index(new_file, new_rank);
                    if(distance[new_index] == -1) // never checked
                    {
                        square_queue.push_back(Square{new_file, new_rank});
                        distance[new_index] = dist + 1;
                    }
                }
            }
        }
    }

    auto normalizer = std::abs(friendly_block_score) + std::abs(enemy_block_score);
    return ((friendly_block_total + enemy_block_total)/free_space_total)/normalizer;
}
<commit_msg>Rename and unify condition to continue flood fill algorithm<commit_after>#include "Genes/King_Confinement_Gene.h"

#include <cmath>
#include <array>
#include <memory>
#include <map>

#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"
#include "Game/Square.h"
#include "Game/Piece.h"

#include "Utility.h"

King_Confinement_Gene::King_Confinement_Gene() :
    friendly_block_score(0.0),
    enemy_block_score(0.0),
    maximum_distance(1)
{
}

std::unique_ptr<Gene> King_Confinement_Gene::duplicate() const
{
    return std::make_unique<King_Confinement_Gene>(*this);
}

std::string King_Confinement_Gene::name() const
{
    return "King Confinement Gene";
}

void King_Confinement_Gene::load_properties()
{
    Gene::load_properties();
    friendly_block_score = properties["Friendly Block Score"];
    enemy_block_score = properties["Enemy Block Score"];
    maximum_distance = int(properties["Maximum Distance"]);
}

void King_Confinement_Gene::reset_properties() const
{
    Gene::reset_properties();
    properties["Friendly Block Score"] = friendly_block_score;
    properties["Enemy Block Score"] = enemy_block_score;
    properties["Maximum Distance"] = maximum_distance;
}

void King_Confinement_Gene::gene_specific_mutation()
{
    make_priority_minimum_zero();
    auto mutation_size = Random::random_laplace(2.0);
    switch(Random::random_integer(1, 3))
    {
        case 1:
            friendly_block_score += mutation_size;
            break;
        case 2:
            enemy_block_score += mutation_size;
            break;
        case 3:
            maximum_distance += int(mutation_size);
            maximum_distance = Math::clamp(maximum_distance, 1, 63);
            break;
        default:
            throw std::logic_error("Bad random value in King Confinement Gene");
    }
}

double King_Confinement_Gene::score_board(const Board& board, const Board& opposite_board, size_t) const
{
    // A flood-fill-like algorithm to count the squares that are reachable by the
    // king from its current positions with unlimited consecutive moves. The
    // boundaries of this area area squares attacked by the other color or occupied
    // by pieces of the same color.
    //
    // The more moves it takes to reach a square, the less it adds to the score.

    std::vector<Square> square_queue;
    square_queue.reserve(64);
    auto perspective = board.whose_turn();
    const auto& king_square = board.find_king(perspective);
    square_queue.push_back(king_square);

    std::array<int, 64> distance;
    distance.fill(-1); // never-visited value
    distance[Board::square_index(king_square.file, king_square.rank)] = 0;

    auto squares_safe_for_king = opposite_board.squares_safe_for_king();

    double friendly_block_total = 0.0;
    double enemy_block_total = 0.0;
    int free_space_total = 0;

    for(size_t i = 0; i < square_queue.size(); ++i)
    {
        auto square = square_queue[i];
        auto square_index = Board::square_index(square.file, square.rank);

        auto attacked_by_other = ! squares_safe_for_king[square_index];
        auto dist = distance[square_index];

        auto piece = board.piece_on_square(square.file, square.rank);
        bool occupied_by_same = piece &&
                                piece->color() == perspective &&
                                piece->type() != KING;

        if(occupied_by_same)
        {
            friendly_block_total += friendly_block_score;
        }
        else if(attacked_by_other)
        {
            enemy_block_total += enemy_block_score;
        }
        else
        {
            ++free_space_total;
        }

        auto keep_going = (square == king_square) ||
            (! occupied_by_same && ! attacked_by_other && dist < maximum_distance);

        // Add surrounding squares to square_queue.
        // always check the squares surrounding the king's current positions, even if
        // it is not safe (i.e., the king is in check).
        if(keep_going)
        {
            for(char new_file = square.file - 1; new_file <= square.file + 1; ++new_file)
            {
                if( ! board.inside_board(new_file))
                {
                    continue;
                }

                for(int new_rank = square.rank - 1; new_rank <= square.rank + 1; ++new_rank)
                {
                    if( ! board.inside_board(new_rank))
                    {
                        continue;
                    }

                    auto new_index = Board::square_index(new_file, new_rank);
                    if(distance[new_index] == -1) // never checked
                    {
                        square_queue.push_back(Square{new_file, new_rank});
                        distance[new_index] = dist + 1;
                    }
                }
            }
        }
    }

    auto normalizer = std::abs(friendly_block_score) + std::abs(enemy_block_score);
    return ((friendly_block_total + enemy_block_total)/free_space_total)/normalizer;
}
<|endoftext|>