text:
/*
	DICOMLIB
	Copyright 2003 Sunnybrook and Women's College Health Science Center
	Implemented by Trevor Morgan  (morgan@sten.sunnybrook.utoronto.ca)

	See the file LICENSE.txt for copyright and licensing info.
*/

/*
	VR.hpp
	This file explicitly defines the relationships between DICOM value
	representations ('VR') and c++ types.
*/

#ifndef VR_HPP_INCLUDE_GUARD_5645353874
#define VR_HPP_INCLUDE_GUARD_5645353874

#include <vector>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>
#include <boost/shared_ptr.hpp>

//is it really worth the hassle involved in using boost date time?
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include "Exceptions.hpp"
#include "UID.hpp"
#include "Tag.hpp"
#include "Types.hpp"

namespace dicom
{

	/*!
		Represents data of vr type 'AE'
		see section 5,table 6.2-1
	*/
	typedef std::string ApplicationEntity;/*eventually should be replaced with a strict checking class.*/

	//!Value Representations.
	/*!
		Defined in  Part 5, section 6.2
	*/
	enum VR {
		VR_AE = 0x4541,	//!< Application Entity
	 	VR_AS = 0x5341, //!< Age String
		VR_AT = 0x5441, //!< Attribute Tag
		VR_CS = 0x5343, //!< Code String
		VR_DA = 0x4144, //!< Date
		VR_DS = 0x5344, //!< Decimal String
		VR_DT = 0x5444, //!< Date Time
		VR_FD = 0x4446, //!< Floating point double
		VR_FL = 0x4C46, //!< Floating point single
		VR_IS = 0x5349, //!< Integer String
		VR_LO = 0x4f4c, //!< Long string
		VR_LT = 0x544c, //!< Long Text
		VR_OB = 0x424f, //!< Other Byte String
		VR_OW = 0x574f, //!< Other Word String
		VR_PN = 0x4e50, //!< Person Name
		VR_SH = 0x4853, //!< Short String
		VR_SL = 0x4C53, //!< Signed long
		VR_SQ = 0x5153, //!< Sequence
		VR_SS = 0x5353, //!< Signed Short
		VR_ST = 0x5453, //!< Short text
		VR_TM = 0x4d54, //!< Time
		VR_UI = 0x4955, //!< Unique Identifier
		VR_UL = 0x4C55, //!< Unsigned Long
		VR_UN = 0x4e55, //!< Unknown
		VR_US = 0x5355, //!< Unsigned Short
		VR_UT = 0x5455  //!< Unlimited Text
		};

	//!General VR mismatch, mistake etc.
	/*!
		straighten up this class please.
	*/
	struct BadVR:public dicom::exception
	{
		Tag tag_;
		VR vr_;
		BadVR(Tag tag): dicom::exception("Bad VR"),tag_(tag)
		{

		}
		BadVR(VR vr):dicom::exception("Bad VR"),vr_(vr){}

		virtual ~BadVR() throw(){}
	};
	//!System got passed a value that isn't a valid VR or we don't know how to handle...
	struct UnknownVR:public dicom::exception
	{
		UINT32 vr_;
		UnknownVR():dicom::exception("Unknown VR"),vr_(0)
		{
		}
		UnknownVR(UINT32 vr):dicom::exception("Unknown VR"),vr_(vr){}
	};

	//!Retrieval of c++ type from DICOM Value Representation
	/*!
		Specialisations of this structure formally state the relationship
		between Dicom Value Representations (VR) and C++ types.

		Currently there is a 1:N relationship VR:Type.  It might make life easier
		if we had a 1:1 relationship, that is, each VR had a _unique_ type associated
		with it.  (this would require the various string vrs to be specialised carefully.)

		Then the Value class could automagically deduce the VR from the type passed to it.
		I'm not at all sure that this would be a good thing.

		The default instantiation of TypeFromVR will not compile (and will hopefully produce a vaguely
		useful compile error message), which implies that you enquired about
		a VR that the library doesn't recognise/support.

		Currently we are using std::string to do a lot of duty.  In some places it
		could be beneficial to replace it with a more specialized class that performs
		more rigourous bounds checking etc, for dicom string vrs that have a maximum length.
	*/

	template <VR vr>
	struct	TypeFromVR
	{
		//you tried asking for the type associated with a VR that I
		//don't know about.
//#if (defined _MSC_VER && _MSC_VER<=1300)//MSVC for some reason always tries to instantiate this?
//#else
//		BOOST_STATIC_ASSERT(false);//to flag the error a bit more helpfully.
//#endif
	};

	//do i need this?  Is there any platform where the following is not the case?
	BOOST_STATIC_ASSERT(sizeof(double)==8);
	BOOST_STATIC_ASSERT(sizeof(float)==4);
//  BOOST_STATIC_ASSERT(sizeof(unsigned long)==4);
	BOOST_STATIC_ASSERT(sizeof(signed short)==2);

	template<> struct TypeFromVR<VR_AE>{typedef	ApplicationEntity			Type;	};
	template<> struct TypeFromVR<VR_AS>{typedef	std::string					Type;	};//please replace

	//what about VR_AT ????
	template<> struct TypeFromVR<VR_AT>{typedef Tag							Type;	};

	template<> struct TypeFromVR<VR_CS>{typedef	std::string					Type;	};
	template<> struct TypeFromVR<VR_DA>{typedef	boost::gregorian::date		Type;	};
	template<> struct TypeFromVR<VR_DS>{typedef	std::string					Type;	};//Please FIXME
	template<> struct TypeFromVR<VR_DT>{typedef	std::string					Type;	};//please replace
	template<> struct TypeFromVR<VR_FD>{typedef	double						Type;	};
	template<> struct TypeFromVR<VR_FL>{typedef	float						Type;	};
	template<> struct TypeFromVR<VR_IS>{typedef	std::string					Type;	};//please replace
	template<> struct TypeFromVR<VR_LO>{typedef	std::string					Type;	};
	template<> struct TypeFromVR<VR_LT>{typedef	std::string					Type;	};
	template<> struct TypeFromVR<VR_OB>{typedef	std::vector<BYTE>			Type;	};
	template<> struct TypeFromVR<VR_OW>{typedef	std::vector<UINT16>			Type;	};
	template<> struct TypeFromVR<VR_PN>{typedef	std::string					Type;	};
	template<> struct TypeFromVR<VR_SH>{typedef	std::string					Type;	};//please replace.
	template<> struct TypeFromVR<VR_SL>{typedef	signed long					Type;	};
	template<> struct TypeFromVR<VR_SS>{typedef	signed short				Type;	};

	class DataSet;//we need this forward declaration to make type checking work for sequences.
	//class Sequence;
	template<> struct TypeFromVR<VR_SQ>{typedef	std::vector<DataSet>		Type;	};

	template<> struct TypeFromVR<VR_ST>{typedef	std::string					Type;	};
	template<> struct TypeFromVR<VR_TM>{typedef	std::string					Type;	};//please replace.
	template<> struct TypeFromVR<VR_UI>{typedef	UID							Type;	};
	template<> struct TypeFromVR<VR_UL>{typedef UINT32			 			Type;	};
	template<> struct TypeFromVR<VR_UN>{typedef	std::vector<BYTE>			Type;	};// a string of bytes, don't know what else to do with it
	template<> struct TypeFromVR<VR_US>{typedef	UINT16						Type;	};
	template<> struct TypeFromVR<VR_UT>{typedef	std::string					Type;	};
	/*
		//are there any left?
		.
		.
		.
	*/

	//!static validation of VR <--> c++ type correspondance.
	/*!
		Will not compile if GIVEN_TYPE is not the correct c++ type for
		the provide VR.
	*/
	template <typename GIVEN_TYPE,VR vr>
	struct StaticVRCheck
	{
		typedef typename TypeFromVR<vr>::Type EXPECTED_TYPE;
		BOOST_STATIC_ASSERT((boost::is_same<EXPECTED_TYPE,typename boost::remove_const<GIVEN_TYPE>::type>::value));
	};

	//!Fails to compile if VR is one of SQ,OB,OW,or UN
	/*!
		See Part 5, Section 6.4
	*/
	template<VR vr>
	struct StaticMultiplicityCheck
	{
		BOOST_STATIC_ASSERT(vr!= VR_SQ && vr!=VR_OB && vr!=VR_OW && vr!=VR_UN && vr!=VR_UT);
	};

	//!Throws BadVR if TYPE1 is not the same as TYPE2
	template<typename TYPE1, typename TYPE2>
	void ThrowIfDifferent(VR vr)
	{
		if(!(::boost::is_same<TYPE1,TYPE2>::value))
		{
			throw BadVR(vr);
		}
	}

	//!Run time check of VR <--> C++ type correspondance
	/*!
		throws BadVR if TYPE is not the correct C++ type
		for the given Value Representation.
		It is suggested to only use this when the VR cannot be
		known at compile time (when StaticVRCheck() can be used.)

	*/
	template <typename TYPE>
	void DynamicVRCheck(VR vr) throw(BadVR)
	{
		switch (vr)
		{
		case VR_AE:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_AE>::Type>(vr);
			break;
		case VR_AS:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_AS>::Type>(vr);
			break;
		case VR_AT:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_AT>::Type>(vr);
			break;
		case VR_CS:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_CS>::Type>(vr);
			break;
		case VR_DA:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_DA>::Type>(vr);
			break;
		case VR_DS:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_DS>::Type>(vr);
			break;
		case VR_DT:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_DT>::Type>(vr);
			break;
		case VR_FD:
			ThrowIfDifferent <TYPE,TypeFromVR<VR_FD>::Type>(vr);
			break;
		case VR_FL:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_FL>::Type> (vr);
			break;
		case VR_IS:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_IS>::Type>(vr);
			break;
		case VR_LO:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_LO>::Type>(vr);
			break;
		case VR_LT:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_LT>::Type>(vr);
			break;
		case VR_OB:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_OB>::Type>(vr);
			break;
		case VR_OW:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_OW>::Type>(vr);
			break;
		case VR_PN:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_PN>::Type>(vr);
			break;
		case VR_SH:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_SH>::Type>(vr);
			break;
		case VR_SL:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_SL>::Type> (vr);
			break;

		case VR_SQ:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_SQ>::Type> (vr);
			break;
		case VR_SS:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_SS>::Type> (vr);
			break;
		case VR_ST:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_ST>::Type>(vr);
			break;
		case VR_TM:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_TM>::Type>(vr);
			break;
		case VR_UI:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_UI>::Type>(vr);
			break;
		case VR_UL:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_UL>::Type>(vr);
			break;
		case VR_UN:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_UN>::Type>(vr);
			break;
		case VR_US:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_US>::Type> (vr);
			break;
		case VR_UT:
			ThrowIfDifferent<TYPE,TypeFromVR<VR_UT>::Type>(vr);
			break;
		default:

			throw BadVR(vr);
		}
	}

/*
	NOTE
	The above PATTERN (calling switch(vr) and instantiating a template
	specialisation for each known vr) occurs at least 4 times throughout
	the codebase.  Does this imply that we can rationalise it somehow,
	(without making the code truly incomprehensible?)

*/

}//namespace DICOM

#endif //VR_HPP_INCLUDE_GUARD_5645353874

ext: hpp

max_stars_repo_name: marcosivni/dicomlib

max_issues_repo_name: marcosivni/dicomlib

max_forks_repo_name: marcosivni/dicomlib


text:
#ifndef ASYNC_SESSON_HPP
#define ASYNC_SESSON_HPP
//include beast
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
//include strand
#include <boost/asio/strand.hpp>
//include others
#include <iostream>
#include <string>

namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;

// Performs an HTTP GET and prints the response
class AsyncSession : public std::enable_shared_from_this<AsyncSession>
{
    tcp::resolver resolver_;
    beast::tcp_stream stream_;
    beast::flat_buffer buffer_;
    http::request<http::empty_body> empty_req_;
    http::request<http::string_body> loaded_req_;
    std::string req_type_;
    http::response<http::string_body> res_;
    std::function<void(std::string)> callback_;

    public:
    // Objects are constructed with a strand to
    // ensure that handlers do not execute concurrently.
    explicit
    AsyncSession(net::io_context& ioc)
        : resolver_(net::make_strand(ioc))
        , stream_(net::make_strand(ioc))
    {
    }

    // Start the asynchronous operation
    void
    run(
        char const* host,
        char const* port,
        const http::request<http::empty_body>& request,
        std::function<void(std::string)> callback
    ){
        empty_req_ = request;
        callback_ = callback;
        req_type_ = "empty";

        // Look up the domain name
        resolver_.async_resolve(
            host,
            port,
            beast::bind_front_handler(
                &AsyncSession::on_resolve,
                shared_from_this()
            )
        );
    }

    void
    run(
        char const* host,
        char const* port,
        const http::request<http::string_body>& request,
        std::function<void(std::string)> callback
    ){
        loaded_req_ = request;
        callback_ = callback;
        req_type_ = "loaded";

        // Look up the domain name
        resolver_.async_resolve(
            host,
            port,
            beast::bind_front_handler(
                &AsyncSession::on_resolve,
                shared_from_this()
            )
        );
    }

    void
    on_resolve(
        beast::error_code ec,
        tcp::resolver::results_type results)
    {
        if(ec)
            return fail(ec, "resolve");

        // Set a timeout on the operation
        stream_.expires_after(std::chrono::seconds(30));

        // Make the connection on the IP address we get from a lookup
        stream_.async_connect(
            results,
            beast::bind_front_handler(
                &AsyncSession::on_connect,
                shared_from_this()
            )
        );
    }

    void
    on_connect(beast::error_code ec, tcp::resolver::results_type::endpoint_type)
    {
        if(ec)
            return fail(ec, "connect");

        // Set a timeout on the operation
        stream_.expires_after(std::chrono::seconds(30));

        if(req_type_ == "empty"){
            // Send the HTTP request to the remote host
            http::async_write(stream_, empty_req_,
                beast::bind_front_handler(
                    &AsyncSession::on_write,
                    shared_from_this()
                )
            );
        }

        if(req_type_ == "loaded"){
            // Send the HTTP request to the remote host
            http::async_write(stream_, loaded_req_,
                beast::bind_front_handler(
                    &AsyncSession::on_write,
                    shared_from_this()
                )
            );
        }
    }

    void
    on_write(
        beast::error_code ec,
        std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        if(ec)
            return fail(ec, "write");

        // Receive the HTTP response
        http::async_read(stream_, buffer_, res_,
            beast::bind_front_handler(
                &AsyncSession::on_read,
                shared_from_this()
            )
        );
    }

    void
    on_read(
        beast::error_code ec,
        std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        if(ec)
            return fail(ec, "read");

        //check for the error
        if(res_.result() != http::status::ok){
            std::cout << "HTTP ERROR: " << res_.result() << "\n";
            std::cout << "Status Code: " << res_.result_int() << "\n";
            std::cout << "Response Body: " << res_.body() << "\n";
        }

        //Send the message to the callback
        callback_(res_.body());

        // Gracefully close the socket
        stream_.socket().shutdown(tcp::socket::shutdown_both, ec);

        // not_connected happens sometimes so don't bother reporting it.
        if(ec && ec != beast::errc::not_connected)
            return fail(ec, "shutdown");
    }
};

#endif // ASYNC_SESSON_HPP

max_stars_repo_name: akildemir/cpp-http-client

max_issues_repo_name: akildemir/cpp-http-client

max_forks_repo_name: akildemir/cpp-http-client


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

#ifndef SVTOOLS_INC_TABLE_TABLEMODEL_HXX
#define SVTOOLS_INC_TABLE_TABLEMODEL_HXX

#include "svtools/svtdllapi.h"
#include "svtools/table/tabletypes.hxx"
#include "svtools/table/tablerenderer.hxx"
#include "svtools/table/tableinputhandler.hxx"
#include "svtools/table/tablesort.hxx"

#include <com/sun/star/util/Color.hpp>
#include <com/sun/star/style/VerticalAlignment.hpp>
#include <com/sun/star/style/HorizontalAlignment.hpp>

#include <rtl/ref.hxx>
#include <sal/types.h>

#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <boost/enable_shared_from_this.hpp>

//........................................................................
namespace svt { namespace table
{
//........................................................................

	//====================================================================
	//= ScrollbarVisibility
	//====================================================================
    enum ScrollbarVisibility
    {
        /** enumeration value denoting that a scrollbar should never be visible, even
            if needed normally
        */
        ScrollbarShowNever,
        /** enumeration value denoting that a scrollbar should be visible when needed only
        */
        ScrollbarShowSmart,
        /** enumeration value denoting that a scrollbar should always be visible, even
            if not needed normally
        */
        ScrollbarShowAlways
    };

	//====================================================================
	//= ITableModelListener
	//====================================================================
    typedef sal_Int32   ColumnAttributeGroup;
    #define COL_ATTRS_NONE          (0x00000000)
    /// denotes column attributes related to the width of the column
    #define COL_ATTRS_WIDTH         (0x00000001)
    /// denotes column attributes related to the appearance of the column, i.e. those relevant for rendering
    #define COL_ATTRS_APPEARANCE    (0x00000002)
    /// denotes the entirety of column attributes
    #define COL_ATTRS_ALL           (0x7FFFFFFF)

	//====================================================================
	//= ITableModelListener
	//====================================================================
    /** declares an interface to be implemented by components interested in
        changes in an ->ITableModel
    */
    class SAL_NO_VTABLE ITableModelListener : public ::boost::enable_shared_from_this< ITableModelListener >
    {
    public:
        /** notifies the listener that one or more rows have been inserted into
            the table

            @param first
                the index of the first newly inserted row
            @param last
                the index of the last newly inserted row. Must not be smaller
                than ->first
        */
        virtual void    rowsInserted( RowPos first, RowPos last ) = 0;

        /** notifies the listener that one or more rows have been removed from
            the table

            @param first
                the old index of the first removed row. If this is -1, then all
                rows have been removed from the model.
            @param last
                the old index of the last removed row. Must not be smaller
                than ->first
        */
        virtual void    rowsRemoved( RowPos first, RowPos last ) = 0;

        /** notifies the listener that one or more columns have been inserted into
            the table

            @param first
                the index of the first newly inserted row
            @param last
                the index of the last newly inserted row. Must not be smaller
                than ->first
        */
        virtual void    columnInserted( ColPos const i_colIndex ) = 0;

        /** notifies the listener that one or more columns have been removed from
            the table

            @param i_colIndex
                the old index of the removed column
        */
        virtual void    columnRemoved( ColPos const i_colIndex ) = 0;

        /** notifies the listener that all columns have been removed form the model
        */
        virtual void    allColumnsRemoved() = 0;

        /** notifies the listener that a rectangular cell range in the table
            has been updated

            Listeners are required to discard any possibly cached information
            they have about the cells in question, in particular any possibly
            cached cell values.
        */
        virtual void    cellsUpdated( ColPos const i_firstCol, ColPos i_lastCol, RowPos const i_firstRow, RowPos const i_lastRow ) = 0;

        /** notifies the listener that attributes of a given column changed

            @param i_column
                the position of the column whose attributes changed
            @param i_attributeGroup
                a combination of one or more COL_ATTRS_* flags, denoting the attribute group(s)
                in which changes occurred.
        */
        virtual void    columnChanged( ColPos const i_column, ColumnAttributeGroup const i_attributeGroup ) = 0;

        /** notifies the listener that the metrics of the table changed.

            Metrics here include the column header height, the row header width, the row height, and the presence
            of both the row and column header.
        */
        virtual void    tableMetricsChanged() = 0;

        /// deletes the listener instance
		virtual ~ITableModelListener(){};
    };
    typedef ::boost::shared_ptr< ITableModelListener > PTableModelListener;

    //====================================================================
	//= IColumnModel
	//====================================================================
    /** interface to be implemented by table column models
    */
    class SAL_NO_VTABLE IColumnModel
    {
    public:
        /** retrieves the ID of the column

            The semantics of a column id is not defined. It's up to the
            implementor of the ->IColumnModel, respectively the ->ITableModel
            which provides the column models, to define such a semantics.

            @return
                the ID of the column. May be 0 if the table which the column
                belongs to does not need and support column ids.

            @see setID
        */
        virtual ::com::sun::star::uno::Any
                            getID() const = 0;

        /** sets a new column ID

            @return
                <TRUE/> if setting the new ID was successful. A possible error
                conditions is if you try to set an ID which is already used
                by another column within the same table.

            @see getID
        */
        virtual void        setID( const ::com::sun::star::uno::Any& _nID ) = 0;

        /** returns the name of the column

            Column names should be human-readable, but not necessarily unique
            within a given table.

            @see setName
        */
        virtual String      getName() const = 0;

        /** sets a new name for the column

            @see getName
        */
        virtual void        setName( const String& _rName ) = 0;

        /** retrieves the help text to be displayed for the column.
        */
        virtual String      getHelpText() const = 0;

        /** sets a new the help text to be displayed for the column.
        */
        virtual void        setHelpText( const String& i_helpText ) = 0;

        /** determines whether the column can be interactively resized

            @see getMinWidth
            @see getMaxWidth
            @see getWidth
        */
        virtual bool        isResizable() const = 0;

        /** declares the column as resizable or fixed in width

            @see getMinWidth
            @see getMaxWidth
            @see getWidth
        */
        virtual void        setResizable( bool _bResizable ) = 0;

        /** denotes the relative flexibility of the column

            This flexibility is taken into account when a table control auto-resizes its columns, because the available
            space changed. In this case, the columns grow or shrink according to their flexibility.

            A value of 0 means the column is not auto-resized at all.
        */
        virtual sal_Int32   getFlexibility() const = 0;

        /** sets a new flexibility value for the column

            @see getFlexibility
        */
        virtual void        setFlexibility( sal_Int32 const i_flexibility ) = 0;

        /** returns the width of the column, in app-font unitss

            The returned value must be a positive ->TableMetrics value.

            @see setWidth
            @see getMinWidth
            @see getMaxWidth
        */
        virtual TableMetrics    getWidth() const = 0;

        /** sets a new width for the column

            @param _nWidth
                the new width, app-font units

            @see getWidth
        */
        virtual void            setWidth( TableMetrics _nWidth ) = 0;

        /** returns the minimum width of the column, in app-font units, or 0 if the column
            does not have a minimal width

            @see setMinWidth
            @see getMaxWidth
            @see getWidth
        */
        virtual TableMetrics    getMinWidth() const = 0;

        /** sets the minimum width of the column, in app-font units

            @see getMinWidth
            @see setMaxWidth
            @see setWidth
        */
        virtual void            setMinWidth( TableMetrics _nMinWidth ) = 0;

        /** returns the maximum width of the column, in app-font units, or 0 if the column
            does not have a minimal width

            @see setMaxWidth
            @see getMinWidth
            @see getWidth
        */
        virtual TableMetrics    getMaxWidth() const = 0;

        /** sets the maximum width of the column, in app-font units

            @see getMaxWidth
            @see setMinWidth
            @see setWidth
        */
        virtual void            setMaxWidth( TableMetrics _nMaxWidth ) = 0;

        /** retrieves the horizontal alignment to be used for content in this cell
        */
		virtual ::com::sun::star::style::HorizontalAlignment getHorizontalAlign() = 0;

        /** sets a new the horizontal alignment to be used for content in this cell
        */
		virtual void setHorizontalAlign(::com::sun::star::style::HorizontalAlignment _xAlign) = 0;

        /// deletes the column model instance
        virtual ~IColumnModel() { }
    };
    typedef ::boost::shared_ptr< IColumnModel > PColumnModel;

    //====================================================================
	//= ITableModel
	//====================================================================
    /** declares the interface to implement by an abtract table model
    */
	class SAL_NO_VTABLE SVT_DLLPUBLIC ITableModel
	{
    public:
        /** returns the number of columns in the table
        */
        virtual TableSize   getColumnCount() const = 0;

        /** returns the number of rows in the table
        */
        virtual TableSize   getRowCount() const = 0;

        /** determines whether the table has column headers

            If this method returns <TRUE/>, the renderer returned by
            ->getRenderer must be able to render column headers.

            @see IColumnRenderer
        */
        virtual bool        hasColumnHeaders() const = 0;

        /** determines whether the table has row headers

            If this method returns <TRUE/>, the renderer returned by
            ->getRenderer must be able to render row headers.

            @see IColumnRenderer
        */
        virtual bool        hasRowHeaders() const = 0;

        /** determines whether the given cell is editable

            @see ICellEditor
            @todo
        */
        virtual bool        isCellEditable( ColPos col, RowPos row ) const = 0;

        /** returns a model for a certain column

            @param column
                the index of the column in question. Must be greater than or
                equal 0, and smaller than the return value of ->getColumnCount()

            @return
                the model of the column in question. Must not be <NULL/>
        */
        virtual PColumnModel    getColumnModel( ColPos column ) = 0;

        /** returns a renderer which is able to paint the table represented
            by this table model

            @return the renderer to use. Must not be <NULL/>
        */
        virtual PTableRenderer  getRenderer() const = 0;

        /** returns the component handling input in a view associated with the model
        */
        virtual PTableInputHandler  getInputHandler() const = 0;

        /** determines the height of rows in the table.

            @return
                the logical height of rows in the table, in app-font units. The height must be
                greater 0.
        */
        virtual TableMetrics    getRowHeight() const = 0;

        /** determines the height of the column header row

            This method is not to be called if ->hasColumnHeaders()
            returned <FALSE/>.

            @return
                the logical height of the column header row, in app-font units.
                Must be greater than 0.
        */
        virtual TableMetrics    getColumnHeaderHeight() const = 0;

        /** determines the width of the row header column

            This method is not to be called if ->hasRowHeaders()
            returned <FALSE/>.

            @return
                the logical width of the row header column, in app-font units.
                Must be greater than 0.
        */
        virtual TableMetrics    getRowHeaderWidth() const = 0;

        /** returns the visibilit mode of the vertical scrollbar
        */
        virtual ScrollbarVisibility getVerticalScrollbarVisibility() const = 0;

        /** returns the visibilit mode of the horizontal scrollbar
        */
        virtual ScrollbarVisibility getHorizontalScrollbarVisibility() const = 0;

        /** adds a listener to be notified of changes in the table model
        */
        virtual void addTableModelListener( const PTableModelListener& i_listener ) = 0;

        /** remove a listener to be notified of changes in the table model
        */
        virtual void removeTableModelListener( const PTableModelListener& i_listener ) = 0;

        /** retrieves the content of the given cell
        */
        virtual void getCellContent( ColPos const i_col, RowPos const i_row, ::com::sun::star::uno::Any& o_cellContent ) = 0;

        /** returns an object which should be displayed as tooltip for the given cell

            At the moment, only string-convertible values are supported here. In the future, one might imagine displaying
            scaled-down versions of a graphic in a cell, and a larger version of that very graphic as tooltip.

            If no tooltip object is provided, then the cell content is used, and displayed as tooltip for the cell
            if and only if it doesn't fit into the cell's space itself.

            @param i_col
                The column index of the cell in question. COL_ROW_HEADERS is a valid argument here.
            @param i_row
                The row index of the cell in question.
            @param o_cellToolTip
                takes the tooltip object upon return.
        */
        virtual void getCellToolTip( ColPos const i_col, RowPos const i_row, ::com::sun::star::uno::Any & o_cellToolTip ) = 0;

        /** retrieves title of a given row
	    */
        virtual ::com::sun::star::uno::Any      getRowHeading( RowPos const i_rowPos ) const = 0;

        /** returns the color to be used for rendering the grid lines.

            If this value is not set, a default color from the style settings will be used.
        */
        virtual ::boost::optional< ::Color >    getLineColor() const = 0;

        /** returns the color to be used for rendering the header background.

            If this value is not set, a default color from the style settings will be used.
        */
        virtual ::boost::optional< ::Color >    getHeaderBackgroundColor() const = 0;

        /** returns the color to be used for rendering the header text.

            If this value is not set, a default color from the style settings will be used.
        */
        virtual ::boost::optional< ::Color >    getHeaderTextColor() const = 0;

        /** returns the color to be used for the background of selected cells, when the control has the focus

            If this value is not set, a default color from the style settings will be used.
        */
        virtual ::boost::optional< ::Color >    getActiveSelectionBackColor() const = 0;

        /** returns the color to be used for the background of selected cells, when the control does not have the focus

            If this value is not set, a default color from the style settings will be used.
        */
        virtual ::boost::optional< ::Color >    getInactiveSelectionBackColor() const = 0;

        /** returns the color to be used for the text of selected cells, when the control has the focus

            If this value is not set, a default color from the style settings will be used.
        */
        virtual ::boost::optional< ::Color >    getActiveSelectionTextColor() const = 0;

        /** returns the color to be used for the text of selected cells, when the control does not have the focus

            If this value is not set, a default color from the style settings will be used.
        */
        virtual ::boost::optional< ::Color >    getInactiveSelectionTextColor() const = 0;

        /** returns the color to be used for rendering cell texts.

            If this value is not set, a default color from the style settings will be used.
        */
        virtual ::boost::optional< ::Color >    getTextColor() const = 0;

        /** returns the color to be used for text lines (underline, strikethrough) when rendering cell text.

            If this value is not set, a default color from the style settings will be used.
        */
        virtual ::boost::optional< ::Color >    getTextLineColor() const = 0;

        /** returns the colors to be used for the row backgrounds.

            If this value is not set, every second row will have a background color derived from the style settings's
            selection color, the other rows will not have a special background at all.

            If this value is an empty sequence, the rows will not have a special background at all, instead the
            normal background of the complete control will be used.

            If value is a non-empty sequence, then rows will have the background colors as specified in the sequence,
            in alternating order.
        */
        virtual ::boost::optional< ::std::vector< ::Color > >
                                                getRowBackgroundColors() const = 0;

        /** determines the vertical alignment of content within a cell
        */
        virtual ::com::sun::star::style::VerticalAlignment getVerticalAlign() const = 0;

        /** returns an adapter to the sorting functionality of the model

            It is legitimate to return <NULL/> here, in this case, the table model does not support sorting.
        */
        virtual ITableDataSort* getSortAdapter() = 0;

        /** returns enabled state.
        */
        virtual bool isEnabled() const = 0;

        /// destroys the table model instance
        virtual ~ITableModel() { }
	};
	typedef ::boost::shared_ptr< ITableModel > PTableModel;

//........................................................................
} } // namespace svt::table
//........................................................................

#endif // SVTOOLS_INC_TABLE_TABLEMODEL_HXX

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
 All rights reserved.

 This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
 under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
 MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/

/**
* \file     area_graph.cpp
* \author   Collin Johnson
*
* Definition of AreaGraph, AreaNode, and AreaEdge.
*/

#include <hssh/local_topological/area_detection/labeling/area_graph.h>
#include <hssh/local_topological/area_detection/labeling/loops_and_trees.h>
#include <hssh/local_topological/area_detection/gateways/gateway_utils.h>
#include <hssh/local_topological/area_detection/voronoi/voronoi_utils.h>
#include <hssh/local_topological/area_detection/local_topo_isovist_field.h>
#include <hssh/local_topological/voronoi_skeleton_grid.h>
#include <utils/algorithm_ext.h>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/make_shared.hpp>
#include <algorithm>
#include <deque>
#include <limits>
#include <set>
#include <iostream>

// #define DEBUG_EDGE
// #define DEBUG_GRAPH

namespace vulcan
{
namespace hssh
{

// Check if the anchors associated with this skeleton cell are frontiers
bool is_frontier_skeleton(cell_t cell, const VoronoiSkeletonGrid& grid);

inline bool are_adjacent_cells(cell_t lhs, cell_t rhs)
{
    return (lhs.x - rhs.x >= -1) && (lhs.x - rhs.x <= 1) && (lhs.y - rhs.y >= -1) && (lhs.y - rhs.y <= 1);
}

inline bool is_cell_on_map_border(cell_t cell, const VoronoiSkeletonGrid& grid)
{
    int width  = grid.getWidthInCells();
    int height = grid.getHeightInCells();
    return (cell.x == 0) || (cell.y == 0) || (cell.x+1 == width) || (cell.y+1 == height);
}

AreaNode::AreaNode(const Point<float>& position, cell_t cell, char typeMask, bool onBoundary)
: position(position)
, cell(cell)
, type(typeMask)
, onBoundary(onBoundary)
{
    assert(!(typeMask & kGateway));
}

AreaNode::AreaNode(const Gateway& gateway, Point<float> position)
: position(position)
, cell(gateway.skeletonCell())
, type(kGateway)
, onBoundary(false)
, gateway(gateway)
{
}

void AreaNode::addEdge(AreaEdgePtr edge)
{
    if(edge)
    {
        edges.push_back(edge);
    }
}

AreaEdge::AreaEdge(const EndpointArray& endpoints, const std::vector<voronoi_cell_t>& cells, float scale, bool borderEdge)
: endpoints(endpoints)
, cells(cells)
, borderEdge(borderEdge)
{
    using namespace boost::accumulators;

    assert(endpoints[0]);
    assert(endpoints[1]);

    // The length is approximately the number of cells times the meters per cell. It isn't quite exact for curves, but is close
    length = (cells.size()+1) * scale;

    accumulator_set<double, stats<tag::mean, tag::variance, tag::max, tag::min>> statsAcc;

    // Go through and calculate the statistics on the width of the edge
    int numFrontierCells = 0;

    for(auto& cell : cells)
    {
        statsAcc(cell.distance * 2.0);

        if(cell.isFrontier)
        {
            ++numFrontierCells;
        }
    }

    frontierRatio = static_cast<float>(numFrontierCells) / cells.size();

    minWidth     = min(statsAcc);
    maxWidth     = max(statsAcc);
    averageWidth = mean(statsAcc);
    stdDevWidth  = std::sqrt(variance(statsAcc));
}

int AreaEdge::nodeIndex(const AreaNode* node) const
{
    if(endpoints[0].get() == node)
    {
        return 0;
    }
    else if(endpoints[1].get() == node)
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

int AreaEdge::isLeftOfGateway(const AreaNode& gatewayNode) const
{
    // Search in order through the cells, starting at the gateway node, until a cell is encountered that isn't on
    // the boundary.
    assert(gatewayNode.getType() & AreaNode::kGateway);
    assert((gatewayNode == *endpoints[0]) || (gatewayNode == *endpoints[1]));

    if(cells.empty())
    {
        return (gatewayNode == *endpoints[0]) ? (gatewayNode.getGateway().isPointToLeft(endpoints[1]->getPosition()) > 0) :
                                                    (gatewayNode.getGateway().isPointToLeft(endpoints[0]->getPosition()) > 0);
    }

    Gateway gateway = gatewayNode.getGateway();
    int startIndex = 0;
    int endIndex   = cells.size();
    int dir        = 1;

    // If it isn't the first cell, then switch the direction of the iterations
    if(distance_between_points(gateway.skeletonCell(), cells.front().cell) >
        distance_between_points(gateway.skeletonCell(), cells.back().cell))
    {
        startIndex = cells.size()-1;
        endIndex   = -1;
        dir        = -1;
    }

    // Search until a dominant direction is found
    int numLeft = 0;

    for(int index = startIndex; (index != endIndex) && (std::abs(numLeft) < 20); index += dir)
    {
        numLeft += gateway.isCellToLeft(cells[index].cell);
    }

    if(numLeft == 0)
    {
        for(int index = startIndex; (index != endIndex) && (std::abs(numLeft) < 20); index += dir)
        {
            numLeft += gateway.isPointToLeft(cells[index].position);
        }
    }

#ifdef DEBUG_EDGE
    // All cells were on the boundary, which is curious, so output a message indicating the unusual state, though it isn't an error
    if(numLeft == 0)
    {
        std::cerr<<"WARNING::AreaEdge: All cells were evenly split between left and right on the gateway metric boundary, which is curious. Gateway:"
            << gateway.skeletonCell() << " Edge cells:\n";
        std::transform(cells.begin(), cells.end(), std::ostream_iterator<cell_t>(std::cerr, " "), [](const voronoi_cell_t& c) {
            return c.cell;
        });
        std::cerr << '\n';
    }
#endif

    return (numLeft == 0) ? 0 : (numLeft > 0) ? 1 : -1;
}

AreaGraph::AreaGraph(const VoronoiSkeletonGrid& grid, const std::vector<Gateway>& gateways)
{
    initializeNodes(grid, gateways);

    NeighborArray neighbors;

    for(auto nodeIt = cellToNode.begin(), nodeEnd = cellToNode.end(); nodeIt != nodeEnd; ++nodeIt)
    {
        std::size_t numNeighbors = neighbor_cells_with_classification(nodeIt->first, SKELETON_CELL_REDUCED_SKELETON, grid, FOUR_THEN_EIGHT_WAY, neighbors);

        for(std::size_t n = 0; n < numNeighbors; ++n)
        {
            cell_t& neighbor = neighbors[n];

            // If two nodes are immediate neighbors, an edge still needs to be added between them!
            // All that will happen is a zero-length edge will be created
            // Only create this node, bypassing the normal check, if the node considered it less than the neighbor.
            // This ensures that the edge is only added once.
            auto neighborIt = cellToNode.find(neighbor);
            if((neighborIt != cellToNode.end()) && (nodeIt->first < neighbor))
            {
                createEdgeBetweenNeighbors(*nodeIt, *neighborIt, grid);
            }
            else if(visited.find(neighbor) == visited.end())
            {
                extractSkeletonEdge(nodeIt->second, nodeIt->first, neighbor, grid);
            }
        }
    }

    // Go through all the gateways. If there's a gateway that doesn't have more than a single reduced neighbor,
    // turn it off because the gateway doesn't lead anywhere
    for(auto& gwy : gateways)
    {
        std::size_t numNeighbors = neighbor_cells_with_classification(gwy.skeletonCell(),
                                                                      SKELETON_CELL_REDUCED_SKELETON,
                                                                      grid,
                                                                      FOUR_THEN_EIGHT_WAY, neighbors);
        // If there's only one neighbor and it is a gateway node, set the type to dead end and not gateway because
        // there's nothing on the other side of the gateway, so it isn't bounding any structure
        if(numNeighbors == 1)
        {
            auto nodeIt = cellToNode.find(gwy.skeletonCell());
            if(nodeIt != cellToNode.end())
            {
                std::cout << "Turning off gateway: " << nodeIt->first << " Not enough neighbors.\n";
                nodeIt->second->type &= ~AreaNode::kGateway;
            }
            else
            {
                std::cout << "Failed to detect gateway at " << gwy.skeletonCell() << '\n';
            }
        }
    }

    cellToNode.clear();
    visited.clear();

    LoopGraph loopGraph;
    construct_loop_graph(*this, loopGraph);
    label_loops_and_trees(loopGraph);
    compute_node_distances(*this, loopGraph);

#ifdef DEBUG_GRAPH
    std::cout << "DEBUG:AreaGraph: Final graph:\nNodes:\n";
    for(auto& n : nodes)
    {
        std::cout << '\t' << n->getPosition() << '\n';
    }
    std::cout << "Edges:\n";
    for(auto& e : edges)
    {
        std::cout << '\t' << e->getEndpoint(0)->getPosition() << "->" << e->getEndpoint(1)->getPosition() << '\n';
    }
#endif
}

AreaGraph::AreaGraph(const std::vector<AreaNodePtr>& nodes, const std::vector<AreaEdgePtr>& edges)
: nodes(nodes)
, edges(edges)
{
    LoopGraph loopGraph;
    construct_loop_graph(*this, loopGraph);
    compute_node_distances(*this, loopGraph);
}

std::vector<AreaNodePtr> AreaGraph::getNodes(char typeMask) const
{
    // Closure to check if a node matches the mask
    auto maskCheckF = [typeMask](const AreaNodePtr& node){ return node->getType() & typeMask; };

    // Create enough nodes by checking the count and then copy them over
    std::vector<AreaNodePtr> maskNodes(std::count_if(nodes.begin(), nodes.end(), maskCheckF));
    std::copy_if(nodes.begin(), nodes.end(), maskNodes.begin(), maskCheckF);

    return maskNodes;
}

bool AreaGraph::containsNode(const AreaNodePtr& node) const
{
    return std::find(nodes.begin(), nodes.end(), node) != nodes.end();
}

bool AreaGraph::containsEdge(const AreaEdgePtr& edge) const
{
    return std::find(edges.begin(), edges.end(), edge) != edges.end();
}

void AreaGraph::setNodeDistance(const AreaNode* nodeA, const AreaNode* nodeB, double distance)
{
    nodeDistances[nodeA][nodeB] = distance;
    nodeDistances[nodeB][nodeA] = distance;
}

double AreaGraph::distanceBetweenNodes(const AreaNode* from, const AreaNode* to) const
{
    auto distsIt = nodeDistances.find(from);

    if(distsIt != nodeDistances.end())
    {
        auto nodeIt = distsIt->second.find(to);
        if(nodeIt != distsIt->second.end())
        {
            return nodeIt->second;
        }
    }

    return 0.0;
}

utils::VisibilityGraph AreaGraph::toVisibilityGraph(double edgeNodeDensity,
                                                    const VoronoiSkeletonGrid& skeleton) const
{
    // Extract the cells to be included in the visibility graph
    CellSet visibilityCells;

    // For each edge, distribute the cells evenly along the edge. There will always be at least two cells for the
    // endpoints plus however many are needed in the middle to get approximately the correctly density
    for(auto& e : edges)
    {
        assert(e->sizeCells() > 0);

        visibilityCells.insert(e->frontCell().cell);
        visibilityCells.insert(e->backCell().cell);
        int numInternalCells = e->getLength() / edgeNodeDensity;

        if(numInternalCells > 0)
        {
            // An edge of length edgeNode + epsilon will have three cells. The two ends plus one right in the middle
            // Thus the density is just the minimum density
            std::size_t stepSize = e->sizeCells() / (numInternalCells + 1);

            for(std::size_t n = stepSize; n < e->sizeCells(); n += stepSize)
            {
                visibilityCells.insert(e->at(n).cell);
            }
        }
    }

    // Return the constructed visibility graph
    return utils::VisibilityGraph(visibilityCells.begin(),
                                  visibilityCells.end(),
                                  20.0 * skeleton.cellsPerMeter(),
                                  skeleton,
                                  VoronoiSkeletonTerminationFunc());
}

utils::VisibilityGraph AreaGraph::toGraph(void) const
{
    std::vector<utils::VisGraphVertex> visNodes;

    for(auto& n : nodes)
    {
        visNodes.push_back(n->getCell());
    }

    std::vector<std::pair<int, int>> visEdges;

    for(auto& e : edges)
    {
        int zeroIdx = std::distance(nodes.begin(), std::find(nodes.begin(), nodes.end(), e->getEndpoint(0)));
        int oneIdx = std::distance(nodes.begin(), std::find(nodes.begin(), nodes.end(), e->getEndpoint(1)));

        visEdges.emplace_back(zeroIdx, oneIdx);
    }

    return utils::VisibilityGraph(visNodes, visEdges);
}

void AreaGraph::initializeNodes(const VoronoiSkeletonGrid& grid, const std::vector<Gateway>& gateways)
{
    for(auto& gateway : gateways)
    {
        createGatewayNode(gateway, grid);
    }

    for(auto cell : grid.getJunctionsPoints())
    {
        createNodeForCell(cell, AreaNode::kJunction, grid);
    }

    for(auto cell : grid.getDeadEnds())
    {
        createNodeForCell(cell, AreaNode::kDeadEnd, grid);
    }

    for(auto cell : grid.getExitPoints())
    {
        createNodeForCell(cell, AreaNode::kFrontier, grid);
    }
}

void AreaGraph::createGatewayNode(const Gateway& gateway, const VoronoiSkeletonGrid& grid)
{
    // In addition to the official skeleton cell, the gateway may intersect one or more other edges of the skeleton.
    // Trace the gateway cells to see if this is the case. If so, create nodes for them as well
    CellVector gatewayCells(gateway.beginCells(), gateway.endCells());
    gatewayCells.push_back(gateway.skeletonCell());

    // Only want to add the skeleton cells as gateway nodes
    utils::erase_remove_if(gatewayCells, [&grid](cell_t c) {
        return ~grid.getClassification(c.x, c.y) & SKELETON_CELL_REDUCED_SKELETON;
    });

    // creating the node via the gateway form, so need to do the creation in here rather than createNodeForCell
    auto nodePtr = std::make_shared<AreaNode>(gateway, gateway.center()); //utils::grid_point_to_global_point(gateway.skeletonCell(), grid));
    nodes.push_back(nodePtr);

    for(auto cell : gatewayCells)
    {
        cellToNode[cell] = nodePtr;
        visited.insert(cell);                 // add the node to the visited queue of cells
    }
}

void AreaGraph::createNodeForCell(cell_t cell, char type, const VoronoiSkeletonGrid& grid)
{
    // If a node already exists for this cell, then concatenate the types and create a new
    // node with the joint type

    if(cellToNode.find(cell) != cellToNode.end())
    {
        cellToNode[cell]->type |= type;
        cellToNode[cell]->onBoundary |= is_cell_on_map_border(cell, grid);
    }
    else // There was no node yet for this cell, so create one
    {
        auto nodePtr = std::make_shared<AreaNode>(utils::grid_point_to_global_point(cell, grid),
                                                  cell,
                                                  type,
                                                  is_cell_on_map_border(cell, grid));
        nodes.push_back(nodePtr);
        cellToNode[cell] = nodePtr;
        visited.insert(cell);                   // add the node to the visited queue of cells
    }
}

void AreaGraph::createEdgeBetweenNeighbors(CellNodePair node, CellNodePair neighbor, const VoronoiSkeletonGrid& grid)
{
    auto endpoints = AreaEdge::EndpointArray{{node.second, neighbor.second}};
    std::vector<voronoi_cell_t> cells;
    cells.push_back(
        {node.first,
        utils::grid_point_to_global_point(node.first, grid),
        grid.getMetricDistance(node.first.x, node.first.y)}
    );

    cells.push_back({
        neighbor.first,
        utils::grid_point_to_global_point(neighbor.first, grid),
        grid.getMetricDistance(neighbor.first.x, neighbor.first.y)}
    );

    addEdge(endpoints, cells, grid.metersPerCell(), node.second->isOnBoundary() | neighbor.second->isOnBoundary());
}

void AreaGraph::extractSkeletonEdge(AreaNodePtr startNode, cell_t nodeCell, cell_t cell, const VoronoiSkeletonGrid& grid)
{
    std::deque<cell_t>          cellQueue;
    std::vector<voronoi_cell_t> edgeCells;
    bool                        isBorderEdge = startNode->isOnBoundary();
    NeighborArray               neighbors;

    edgeCells.push_back({nodeCell, utils::grid_point_to_global_point(nodeCell, grid), grid.getMetricDistance(nodeCell.x, nodeCell.y), is_frontier_skeleton(nodeCell, grid)});

    cellQueue.push_back(cell);

    while(!cellQueue.empty())
    {
        int    numAdded = 0;
        cell_t current  = cellQueue.front();

        edgeCells.push_back({current, utils::grid_point_to_global_point(current, grid), grid.getMetricDistance(current.x, current.y), is_frontier_skeleton(current, grid)});

        isBorderEdge |= is_cell_on_map_border(current, grid);

        std::size_t numNeighbors = neighbor_cells_with_classification(current, SKELETON_CELL_REDUCED_SKELETON, grid, FOUR_THEN_EIGHT_WAY, neighbors);

        for(std::size_t n = 0; n < numNeighbors; ++n)
        {
            cell_t& neighbor = neighbors[n];

            // Once another node has been reached, create the edge and add it to both of the nodes
            if((cellToNode.find(neighbor) != cellToNode.end()) && (cellToNode[neighbor] != startNode))
            {
#ifdef DEBUG_EDGE
                std::cout<< "DEBUG: AreaGraph: Queue size when edge created: " << cellQueue.size() << '\n';
#endif
                auto otherNode  = cellToNode[neighbor];
                isBorderEdge    |= otherNode->isOnBoundary();
                auto endpoints  = AreaEdge::EndpointArray{{startNode, otherNode}};
                edgeCells.push_back({neighbor, utils::grid_point_to_global_point(neighbor, grid), grid.getMetricDistance(neighbor.x, neighbor.y), is_frontier_skeleton(neighbor, grid)});
                addEdge(endpoints, edgeCells, grid.metersPerCell(), isBorderEdge);
                break;
            }
            // There should only be two neighbors and one should be visited because it was the parent. If that's
            // not the case, then display an appropriate warning
            else if(visited.find(neighbor) == visited.end())
            {
                cellQueue.push_back(neighbor);
                ++numAdded;
            }

            if(numAdded > 1)
            {
                std::cerr << "WARNING:AreaGraph:Edge had more than one neighbor added, but wasn't a junction!\n";
            }
        }

        visited.insert(current);
        cellQueue.pop_front();
    }
}

void AreaGraph::addEdge(const AreaEdge::EndpointArray& endpoints,
                        const std::vector<voronoi_cell_t>& cells,
                        float scale,
                        bool borderEdge)
{
    // Don't add any self-edges
    if(endpoints[0] != endpoints[1])
    {
        auto edgePtr = std::make_shared<AreaEdge>(endpoints,
                                                cells,
                                                scale,
                                                borderEdge);
        endpoints[0]->addEdge(edgePtr);
        endpoints[1]->addEdge(edgePtr);
        edges.push_back(edgePtr);

#ifdef DEBUG_EDGE
        std::cout << "DEBUG: AreaGraph: Adding edge between " << endpoints[0]->getCell() << " -> "
            << endpoints[1]->getCell() << " :: ";
        for(auto& c : cells)
        {
            std::cout << c.cell << ' ';
        }
        std::cout << '\n';
#endif
    }
}

bool is_frontier_skeleton(cell_t cell, const VoronoiSkeletonGrid& grid)
{
    return std::find_if(grid.beginSourceCells(cell),
                        grid.endSourceCells(cell),
                        [&grid](cell_t source) { return grid.getClassification(source.x, source.y) & SKELETON_CELL_FRONTIER; }) != grid.endSourceCells(cell);

}

} // namespace hssh
} // namespace vulcan

ext: cpp


text:
/** @file
    @brief Implementation

    @date 2014

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>

*/

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

#ifndef __ANDROID__
#define OSVR_DEV_VERBOSE_DISABLE
#endif

// Internal Includes
#include <osvr/PluginHost/RegistrationContext.h>

#include "PluginSpecificRegistrationContextImpl.h"
#include <osvr/PluginHost/PathConfig.h>
#include <osvr/PluginHost/SearchPath.h>
#include <osvr/Util/Log.h>
#include <osvr/Util/Verbosity.h>

// Library/third-party includes
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/noncopyable.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <libfunctionality/LoadPlugin.h>

// Standard includes
#include <algorithm>
#include <iterator>

namespace osvr {
namespace pluginhost {
    static const auto PLUGIN_HOST_LOGGER_NAME = "PluginHost";
#ifdef _MSC_VER
    static const auto PLUGIN_HOST_DEBUG_SUFFIX = ".debug";
#endif
    namespace fs = boost::filesystem;

    struct RegistrationContext::Impl : private boost::noncopyable {
        /// constructor - creates and caches the plugin search path
        Impl() : pluginPaths(pluginhost::getPluginSearchPath()) {}

        const std::vector<std::string> pluginPaths;
    };

    RegistrationContext::RegistrationContext()
        : m_impl(new Impl),
          m_logger(util::log::make_logger(PLUGIN_HOST_LOGGER_NAME)) {}

    RegistrationContext::~RegistrationContext() {
        // Reset the plugins in reverse order.
        for (auto &ptr : m_regMap | boost::adaptors::map_values |
                             boost::adaptors::reversed) {
            ptr.reset();
        }
    }

    template <typename MapType>
    static inline bool isPluginLoaded(MapType const &regMap,
                                      std::string const &pluginName) {
        return (regMap.find(pluginName) != end(regMap));
    }

    /// Only called by manually-named plugins to load: the plugins that are
    /// loaded automatically don't go through this function.
    static inline bool tryLoadingPlugin(util::log::Logger &log,
                                        libfunc::PluginHandle &plugin,
                                        std::string const &name,
                                        OSVR_PluginRegContext ctx,
                                        bool shouldRethrow = false) {
#if defined(_MSC_VER) && !defined(NDEBUG)
        // Visual C++ debug runtime: we append to the plugin name.
        const std::string decoratedPluginName = name + PLUGIN_HOST_DEBUG_SUFFIX;
#else
        const std::string &decoratedPluginName = name;
#endif
        log.debug() << "Trying to load a plugin with the name "
                    << decoratedPluginName;
        try {
            plugin = libfunc::loadPluginByName(decoratedPluginName, ctx);
            return true;
        } catch (std::runtime_error const &e) {
            log.debug() << "Failed: " << e.what();
            if (shouldRethrow) {
                throw;
            }
            return false;
        } catch (...) {
            throw;
        }
    }

    void RegistrationContext::loadPlugin(std::string const &pluginName) {
        if (isPluginLoaded(m_regMap, pluginName)) {
            throw std::runtime_error("Already loaded a plugin named " +
                                     pluginName);
        }

        PluginRegPtr pluginReg(
            PluginSpecificRegistrationContext::create(pluginName));
        pluginReg->setParent(*this);

        bool success = false;
        libfunc::PluginHandle plugin;
        auto ctx = pluginReg->extractOpaquePointer();
        const std::string pluginPathName =
            pluginhost::findPlugin(m_impl->pluginPaths, pluginName);
        if (pluginPathName.empty()) {
            // was the plugin pre-loaded or statically linked? Try loading
            // it by name.
            success = tryLoadingPlugin(*m_logger, plugin, pluginName, ctx);
            if (!success) {
                throw std::runtime_error("Could not find plugin named " +
                                         pluginName);
            }
        }

        if (!success) {
            const auto pluginPathNameNoExt =
                (fs::path(pluginPathName).parent_path() /
                 fs::path(pluginPathName).stem())
                    .generic_string();

            success =
                tryLoadingPlugin(*m_logger, plugin, pluginPathName, ctx) ||
                tryLoadingPlugin(*m_logger, plugin, pluginPathNameNoExt, ctx,
                                 true);
            if (!success) {
                throw std::runtime_error(
                    "Unusual error occurred trying to load plugin named " +
                    pluginName);
            }
        }
        pluginReg->takePluginHandle(plugin);
        adoptPluginRegistrationContext(pluginReg);
    }

    void RegistrationContext::loadPlugins() {
        // Build a list of all the plugins we can find
        auto pluginPathNames = pluginhost::getAllFilesWithExt(
            m_impl->pluginPaths, OSVR_PLUGIN_EXTENSION);

        // Load all of the non-.manualload plugins
        for (const auto &plugin : pluginPathNames) {
            m_logger->debug() << "Examining plugin '" << plugin << "'...";
            const auto pluginBaseName =
                fs::path(plugin).filename().stem().generic_string();
            if (boost::iends_with(pluginBaseName, OSVR_PLUGIN_IGNORE_SUFFIX)) {
                m_logger->debug() << "Ignoring manual-load plugin: "
                                  << pluginBaseName;
                continue;
            }

#if defined(_MSC_VER)
            // Visual C++ debug runtime: we append to the plugin name. Must only
            // load debug plugins iff we're a debug server
            const auto isDebugRuntimePlugin =
                boost::iends_with(pluginBaseName, PLUGIN_HOST_DEBUG_SUFFIX);
#if defined(NDEBUG)
            /// This is a non-debug build.
            if (isDebugRuntimePlugin) {
                m_logger->debug() << "Ignoring debug-runtime plugin: "
                                  << pluginBaseName;
                continue;
            }
#else
            /// This is a debug build
            if (!isDebugRuntimePlugin) {
                m_logger->debug() << "Ignoring non-debug-runtime plugin: "
                                  << pluginBaseName;
                continue;
            }
#endif // NDEBUG
#endif // _MSC_VER

            try {
                loadPlugin(pluginBaseName);
                m_logger->debug() << "Successfully loaded plugin: "
                                  << pluginBaseName;
            } catch (const std::exception &e) {
                m_logger->warn() << "Failed to load plugin " << pluginBaseName
                                 << ": " << e.what();
            } catch (...) {
                m_logger->warn() << "Failed to load plugin " << pluginBaseName
                                 << ": Unknown error.";
            }
        }
    }

    void RegistrationContext::adoptPluginRegistrationContext(PluginRegPtr ctx) {
        /// This set parent might be a duplicate, but won't be if the plugin reg
        /// ctx is not created by loadPlugin above.
        ctx->setParent(*this);

        m_regMap.insert(std::make_pair(ctx->getName(), ctx));
    }

    void RegistrationContext::triggerHardwareDetect() {
        for (auto &pluginPtr : m_regMap | boost::adaptors::map_values) {
            pluginPtr->triggerHardwareDetectCallbacks();
        }
    }

    void
    RegistrationContext::instantiateDriver(const std::string &pluginName,
                                           const std::string &driverName,
                                           const std::string &params) const {
        auto pluginIt = m_regMap.find(pluginName);
        if (pluginIt == end(m_regMap)) {
            throw std::runtime_error("Could not find plugin named " +
                                     pluginName);
        }
        pluginIt->second->instantiateDriver(driverName, params);
    }

    util::AnyMap &RegistrationContext::data() { return m_data; }

    util::AnyMap const &RegistrationContext::data() const { return m_data; }
} // namespace pluginhost
} // namespace osvr

max_stars_repo_name: ethanpeng/OSVR-Core

max_issues_repo_name: ethanpeng/OSVR-Core

max_forks_repo_name: ethanpeng/OSVR-Core


text:
#ifndef mod_passauth_CORE_HPP_
#define mod_passauth_CORE_HPP_

#include "mod_passauth/provider.hpp" /* this must before "httpd.h" */

#include "apr_pools.h"
#include "apr_time.h"

#include "httpd.h"

#include <map>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <sstream>
#include <vector>

#include <boost/noncopyable.hpp>

#include "mod_passauth/config.hpp"
#include "mod_passauth/pool.hpp"

namespace mod_passauth {

class AUTH {
  public:
    ~AUTH() {}

    bool check_client_verify_mode(request_rec *r);
    std::tuple<std::string, std::string> get_token_from_req(request_rec *r);
    bool jump_auth_url(request_rec *r);
    bool loadAuth(std::strng usertoken) {
        return auth_rules_provider_.load(usertoken);
    }
    bool checkPermission(apr_time_t time, std::string pwdtoken) {
      return auth_rules_provider_.isAllowedToAccessAuth(time, pwdtoken);
    }

  private:
    explicit AUTH(const ModuleConfig& config)
      : auth_rules_provider_(config.auth_db_config) {
    }

    friend AUTH *make_auth(apr_pool_t *pool, const ModuleConfig& config);

    detail::AUTHRulesProvider auth_rules_provider_;
};

inline AUTH *make_auth(apr_pool_t *pool, const ModuleConfig& config) {
  AUTH *auth = new AUTH(config);
  detail::pool_register_delete(pool, auth);
  return auth;
}

} /* namespace mod_passauth */

#endif /* mod_passauth_CORE_HPP_ */


text:
/*
 *          Copyright Andrey Semashev 2007 - 2014.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   text_ostream_backend.hpp
 * \author Andrey Semashev
 * \date   22.04.2007
 *
 * The header contains implementation of a text output stream sink backend.
 */

#ifndef BOOST_LOG_SINKS_TEXT_OSTREAM_BACKEND_HPP_INCLUDED_
#define BOOST_LOG_SINKS_TEXT_OSTREAM_BACKEND_HPP_INCLUDED_

#include <ostream>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/log/detail/config.hpp>
#include <boost/log/sinks/basic_sink_backend.hpp>
#include <boost/log/sinks/frontend_requirements.hpp>
#include <boost/log/detail/header.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace sinks {

/*!
 * \brief An implementation of a text output stream logging sink backend
 *
 * The sink backend puts formatted log records to one or more text streams.
 */
template< typename CharT >
class basic_text_ostream_backend :
    public basic_formatted_sink_backend<
        CharT,
        combine_requirements< synchronized_feeding, flushing >::type
    >
{
    //! Base type
    typedef basic_formatted_sink_backend<
        CharT,
        combine_requirements< synchronized_feeding, flushing >::type
    > base_type;

public:
    //! Character type
    typedef typename base_type::char_type char_type;
    //! String type to be used as a message text holder
    typedef typename base_type::string_type string_type;
    //! Output stream type
    typedef std::basic_ostream< char_type > stream_type;

private:
    //! \cond

    struct implementation;
    implementation* m_pImpl;

    //! \endcond

public:
    /*!
     * Constructor. No streams attached to the constructed backend, auto flush feature disabled.
     */
    BOOST_LOG_API basic_text_ostream_backend();
    /*!
     * Destructor
     */
    BOOST_LOG_API ~basic_text_ostream_backend();

    /*!
     * The method adds a new stream to the sink.
     *
     * \param strm Pointer to the stream. Must not be NULL.
     */
    BOOST_LOG_API void add_stream(shared_ptr< stream_type > const& strm);
    /*!
     * The method removes a stream from the sink. If the stream is not attached to the sink,
     * the method has no effect.
     *
     * \param strm Pointer to the stream. Must not be NULL.
     */
    BOOST_LOG_API void remove_stream(shared_ptr< stream_type > const& strm);

    /*!
     * Sets the flag to automatically flush buffers of all attached streams after each log record
     */
    BOOST_LOG_API void auto_flush(bool f = true);

    /*!
     * The method writes the message to the sink
     */
    BOOST_LOG_API void consume(record_view const& rec, string_type const& formatted_message);

    /*!
     * The method flushes the associated streams
     */
    BOOST_LOG_API void flush();
};

#ifdef BOOST_LOG_USE_CHAR
typedef basic_text_ostream_backend< char > text_ostream_backend;        //!< Convenience typedef for narrow-character logging
#endif
#ifdef BOOST_LOG_USE_WCHAR_T
typedef basic_text_ostream_backend< wchar_t > wtext_ostream_backend;    //!< Convenience typedef for wide-character logging
#endif

} // namespace sinks

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>

#endif // BOOST_LOG_SINKS_TEXT_OSTREAM_BACKEND_HPP_INCLUDED_


text:
#include "StdAfx.h"
#include "GV_PropertyGridCtrl.h"
#include "MainFrm.h"
#include "gv_rts_editor.h"
#include <boost/boost/pool/singleton_pool.hpp>
using namespace gv;
struct proper_info
{
	proper_info()
	{
	}
	~proper_info()
	{
		int i = 0;
	}
	proper_info(const char* _l)
	{
		location = _l;
	}
	gv_string_static_1024 location;
};

gv_string_tmp get_location(CMFCPropertyGridProperty* p)
{
	proper_info* pinfo = (proper_info*)p->GetData();
	if (!pinfo)
		return NULL;
	return *pinfo->location;
}

void set_location(CMFCPropertyGridProperty* p, const gv_string_tmp& location)
{
	proper_info* pinfo = new proper_info(location);
	p->SetData((DWORD_PTR)(pinfo));
}

void AddOneProperty(CMFCPropertyGridCtrl& list,
					CMFCPropertyGridProperty* pfather, gvi_type* ptype,
					gv_byte* pdata, const gv_string_tmp& name = "",
					gv_string_tmp location = "", BOOL allow_edited = FALSE,
					BOOL is_super = FALSE, BOOL is_file_name = FALSE,
					gv_id enum_id = gv_id(),
					gv::gv_class_info* stop_class = NULL,
					gv_string_tmp tooltip = "")
{

	//================================================================================
	switch (ptype->get_type())
	{

	case (gve_data_type_object):
	{
		gv_type_object* ptc = (gv_type_object*)ptype;
		gv_class_info* pcls = ptc->get_class();
		if (pcls == stop_class)
			break;
		if (pcls->get_super())
		{
			CMFCPropertyGridProperty* pgroup1 = new CMFCPropertyGridProperty(
				GV_TO_UNICODE(*pcls->get_super()->get_name_id()));
			pgroup1->SetDescription(GV_TO_UNICODE("parent class"));
			set_location(pgroup1, location);
			gv_type_object type;
			type.set_class(pcls->get_super());
			AddOneProperty(list, pgroup1, &type, pdata, "", location, allow_edited, 1,
						   0, gv_id(), stop_class);
			if (pfather)
			{
				pfather->AddSubItem(pgroup1);
			}
			else
			{
				list.AddProperty(pgroup1);
			}
		}

		for (int i = 0; i < (int)pcls->get_nb_var(); i++)
		{
			gv_var_info* pvar = pcls->get_nth_var(i);
			if (pvar->m_is_hide_in_editor)
				continue;
			BOOL this_allow_edited = allow_edited && !pvar->is_no_clone();
			if (pvar->get_type()->get_type() == gve_data_type_object)
			{
				CMFCPropertyGridProperty* pgroup1 = new CMFCPropertyGridProperty(
					GV_TO_UNICODE(*pvar->get_name_id().string()));
				if (!pvar->get_tooltip().is_empty_string())
				{
					pgroup1->SetDescription(GV_TO_UNICODE(*pvar->get_tooltip()));
				}
				set_location(pgroup1, location + "." + *pvar->get_name_id());
				AddOneProperty(list, pgroup1, pvar->get_type(),
							   pdata + pvar->get_offset(), *pvar->get_name_id(),
							   location + "." + *pvar->get_name_id(), this_allow_edited,
							   0, pvar->m_is_file_name, gv_id(), stop_class);
				if (pfather)
				{
					pfather->AddSubItem(pgroup1);
				}
				else
				{
					list.AddProperty(pgroup1);
				}
			}
			else
			{
				AddOneProperty(list, pfather, pvar->get_type(),
							   pdata + pvar->get_offset(), *pvar->get_name_id(),
							   location, this_allow_edited, 0, pvar->m_is_file_name,
							   pvar->get_enum_id(), stop_class, *pvar->get_tooltip());
			}
		}
	}
	break;
	//================================================================================
	case (gve_data_type_color):
	{
		gv_color* pcolor = (gv_color*)pdata;
		CMFCPropertyGridProperty* pgroup1 =
			new CMFCPropertyGridProperty(GV_TO_UNICODE(*name));
		pgroup1->SetDescription(GV_TO_UNICODE(*tooltip));
		if (name[0] != '[')
			location += ".";
		location += name;
		set_location(pgroup1, location);
		{
			CMFCPropertyGridColorProperty* pColorProp =
				new CMFCPropertyGridColorProperty(
					GV_TO_UNICODE("RGB"), RGB(pcolor->r, pcolor->g, pcolor->b), NULL);
			pColorProp->EnableOtherButton(_T("Other..."));
			pColorProp->EnableAutomaticButton(_T("Default"),
											  ::GetSysColor(COLOR_3DFACE));
			set_location(pColorProp, location + ".rgb");
			pColorProp->AllowEdit(allow_edited);
			pgroup1->AddSubItem(pColorProp);

			int a = pcolor->a;
			CMFCPropertyGridProperty* pProp =
				new CMFCPropertyGridProperty(_T("A"), (_variant_t)(a), _T("alpha "));
			set_location(pProp, location + "." + ".a");
			// pProp->EnableSpinControl(TRUE, 50, 200);
			pProp->AllowEdit(allow_edited);
			pgroup1->AddSubItem(pProp);
		}
		if (pfather)
		{
			pfather->AddSubItem(pgroup1);
		}
		else
		{
			list.AddProperty(pgroup1);
		}
	}
	break;

	//================================================================================
	case (gve_data_type_text):
	{
		if (is_file_name)
		{
			gv_text* ptext = (gv_text*)pdata;
			static TCHAR BASED_CODE szFilter[] = _T("All Files(*.*)|*.*||");
			CMFCPropertyGridFileProperty* pProp = new CMFCPropertyGridFileProperty(
				GV_TO_UNICODE(*name), TRUE, (_variant_t)(CString(*ptext)), _T("*"), 0,
				szFilter, _T("select a file"));
			pProp->SetDescription(GV_TO_UNICODE(*tooltip));
			pProp->AllowEdit(allow_edited);
			if (name[0] != '[')
				location += ".";
			location += name;
			set_location(pProp, location);
			if (pfather)
			{
				pfather->AddSubItem(pProp);
			}
			else
			{
				list.AddProperty(pProp);
			}
		}
		else
		{
			gv_text* ptext = (gv_text*)pdata;
			CMFCPropertyGridProperty* pProp = new CMFCPropertyGridProperty(
				GV_TO_UNICODE(*name), (_variant_t)(CString(*ptext)), _T(""));
			pProp->SetDescription(GV_TO_UNICODE(*tooltip));
			pProp->AllowEdit(allow_edited);
			if (name[0] != '[')
				location += ".";
			location += name;
			set_location(pProp, location);
			if (pfather)
			{
				pfather->AddSubItem(pProp);
			}
			else
			{
				list.AddProperty(pProp);
			}
		}
	}
	break;
	//================================================================================
	case (gve_data_type_array):
	{
		gv_type_array* pta = (gv_type_array*)ptype;
		gvi_type* pte = pta->get_element_type();
		CMFCPropertyGridProperty* pgroup1 =
			new CMFCPropertyGridProperty(GV_TO_UNICODE(*name));
		pgroup1->SetDescription(GV_TO_UNICODE(*tooltip));
		if (name[0] != '[')
			location += ".";
		location += name;
		set_location(pgroup1, *location);
		gv_type_int size_type;
		gv_type_int* ptsize = &(size_type);
		int size = pta->get_array_size(pdata);
		AddOneProperty(list, pgroup1, ptsize, (BYTE*)&size, "size", location,
					   allow_edited);
		gv_byte* phead = pta->get_array_data(pdata);
		for (int i = 0; i < size; i++)
		{
			gv_string_tmp idx;
			idx << "[" << i << "]";
			if (pte->get_type() == gve_data_type_object)
			{
				CMFCPropertyGridProperty* pgroup_el =
					new CMFCPropertyGridProperty(GV_TO_UNICODE(*idx));
				set_location(pgroup_el, location + idx);
				AddOneProperty(list, pgroup_el, pte, phead, *idx, location + idx,
							   allow_edited);
				pgroup1->AddSubItem(pgroup_el);
			}
			else
				AddOneProperty(list, pgroup1, pte, phead, *idx, location, allow_edited);
			phead += pte->get_size();
		}
		if (pfather)
		{
			pfather->AddSubItem(pgroup1);
		}
		else
			list.AddProperty(pgroup1);
	}
	break;
	//================================================================================
	case (gve_data_type_static_array):
	{
		gv_type_static_array* pta = (gv_type_static_array*)ptype;
		gvi_type* pte = pta->get_element_type();
		CMFCPropertyGridProperty* pgroup1 =
			new CMFCPropertyGridProperty(GV_TO_UNICODE(*name));
		pgroup1->SetDescription(GV_TO_UNICODE(*tooltip));
		if (name[0] != '[')
			location += ".";
		location += name;
		set_location(pgroup1, location);
		BYTE* phead = pdata;
		for (int i = 0; i < pta->get_array_size(); i++)
		{
			gv_string_tmp idx;
			idx << "[" << i << "]";
			if (pte->get_type() == gve_data_type_object)
			{
				CMFCPropertyGridProperty* pgroup_el =
					new CMFCPropertyGridProperty(GV_TO_UNICODE(*idx));
				set_location(pgroup_el, location + idx);
				AddOneProperty(list, pgroup_el, pte, phead, *idx, location + idx,
							   allow_edited);
				pgroup1->AddSubItem(pgroup_el);
			}
			else
				AddOneProperty(list, pgroup1, pte, phead, *idx, location, allow_edited);
			phead += pte->get_size();
		}
		if (pfather)
		{
			pfather->AddSubItem(pgroup1);
		}
		else
		{
			list.AddProperty(pgroup1);
		}
	}
	break;
	//================================================================================
	case (gve_data_type_bool):
	{
		bool* pbool = (bool*)pdata;
		CMFCPropertyGridProperty* pProp = new CMFCPropertyGridProperty(
			GV_TO_UNICODE(*name), (_variant_t)(*pbool), _T(""));
		pProp->SetDescription(GV_TO_UNICODE(*tooltip));
		// pProp->AllowEdit(allow_edited);
		if (name[0] != '[')
			location += ".";
		location += name;
		set_location(pProp, location);
		if (pfather)
		{
			pfather->AddSubItem(pProp);
		}
		else
		{
			list.AddProperty(pProp);
		}
	}
	break;
	default:
	{
		gv_string_tmp s;
		CMFCPropertyGridProperty* pProp = NULL;
		if (ptype->get_type() == gve_data_type_int && !enum_id.is_empty())
		{
			gv_enum_info* info = get_editor()->get_sandbox()->find_enum(enum_id);
			GV_ASSERT(info);
			gv_int* pint = (gv_int*)pdata;
			gv_string_tmp enum_value = *info->get_id(*pint);
			pProp = new CMFCPropertyGridProperty(GV_TO_UNICODE(*name),
												 GV_TO_UNICODE(*enum_value),
												 GV_TO_UNICODE("enum !!"));
			pProp->SetDescription(GV_TO_UNICODE(*tooltip));
			gvt_array< gv_id > a1;
			gvt_array< gv_int > a2;
			info->query_all(a1, a2);
			a1.sort();
			for (int i = 0; i < a1.size(); i++)
			{
				pProp->AddOption(GV_TO_UNICODE(*(a1[i])));
			}
			pProp->AllowEdit(FALSE);
		}
		else
		{
			ptype->export_to_xml(pdata, s);
			gv_cpp_string_to_string(s, false);
			pProp = new CMFCPropertyGridProperty(GV_TO_UNICODE(*name),
												 (_variant_t) * (s), _T(""));
			pProp->SetDescription(GV_TO_UNICODE(*tooltip));
			pProp->AllowEdit(allow_edited);
		}
		if (name[0] != '[')
			location += ".";
		location += name;
		set_location(pProp, location);
		if (pfather)
		{
			pfather->AddSubItem(pProp);
		}
		else
		{
			list.AddProperty(pProp);
		}
	}
	break;
	}
	return;
}

GV_PropertyGridCtrl::GV_PropertyGridCtrl()
{
}
GV_PropertyGridCtrl::~GV_PropertyGridCtrl(void)
{
}

void GV_PropertyGridCtrl::OnClickButton(CPoint point)
{

	return CMFCPropertyGridCtrl::OnClickButton(point);
}

BOOL GV_PropertyGridCtrl::EndEditItem(BOOL bUpdateData)
{
	if (!m_pSel)
		return FALSE;
	return CMFCPropertyGridCtrl::EndEditItem(bUpdateData);
};

void GV_PropertyGridCtrl::OnPropertyChanged(
	CMFCPropertyGridProperty* pProp) const
{
	return CMFCPropertyGridCtrl::OnPropertyChanged(pProp);
}

BOOL GV_PropertyGridCtrl::ValidateItemData(CMFCPropertyGridProperty* pProp)
{
	// if (!pProp->IsAllowEdit()) return TRU  E;
	pProp->OnUpdateValue();
	gv_string_tmp location = get_location(pProp);
	gv_string_tmp value;
	value << "\"" << (CStringA)pProp->GetValue() << "\"";
	gv_byte* pval;
	gvi_type* ptype;
	gv_object* pobj;
	gv_string_tmp tail;
	gv_id enum_id;
	if (!get_editor()->get_sandbox()->find_global_property(location, pval, ptype,
														   pobj, tail, enum_id))
		return FALSE;
	if (!pProp->IsAllowEdit() && pProp->GetValue().vt != VT_BOOL)
	{
		return TRUE;
	}
	if (tail.size() && ptype->get_type() == gve_data_type_color)
	{
		CMFCPropertyGridProperty* parent = pProp->GetParent();
		gv_color c;
		value = (CStringA)parent->GetSubItem(0)->GetValue();
		value >> c.fixed32;
		value = (CStringA)parent->GetSubItem(1)->GetValue();
		value >> c.a;
		location = get_location(parent);
		value = "";
		ptype->export_to_xml(gvt_byte_ptr(c), value);
	}
	else if (ptype->get_type() == gve_data_type_text)
	{
		value = "";
		value << "<![CDATA[" << (CStringA)pProp->GetValue() << "]]>";
	}
	else if (ptype->get_type() == gve_data_type_bool)
	{
		value.to_lower();
		if (value == "\"0\"")
		{
			value = "\"0\"";
		}
		else
		{
			value = "\"1\"";
		}
	}
	else if (ptype->get_type() == gve_data_type_int && !enum_id.is_empty())
	{
		gv_enum_info* info = get_editor()->get_sandbox()->find_enum(enum_id);
		GV_ASSERT(info);
		gv_string_tmp s_val;
		s_val << (CStringA)pProp->GetValue();
		value = "";
		value << "\"" << info->get_int(gv_id(*s_val)) << "\"";
		pProp->AllowEdit(FALSE);
	}

	return CMainFrame::static_get()->UpdateObject(location, value);
};

BEGIN_MESSAGE_MAP(GV_PropertyGridCtrl, CMFCPropertyGridCtrl)
ON_WM_LBUTTONDBLCLK()
ON_WM_KEYDOWN()
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()

void GV_PropertyGridCtrl::OnLButtonDblClk(UINT nFlags, CPoint point)
{
	// TODO: Add your message handler code here and/or call default
	CMFCPropertyGridProperty* prop = this->HitTest(point);
	if (prop)
	{
		gv_string_tmp address = get_location(prop);
		gvi_type* type;
		gv_byte* data;
		gv_object* object;
		gv_string_tmp tail;
		gv_id enum_id;
		bool found = get_editor()->get_sandbox()->find_global_property(
			address, data, type, object, tail, enum_id);
		GVM_LOG(main, get_location(prop) << " selected!"
										 << "  value is: "
										 << (CStringA)prop->GetValue() << gv_endl);
		if (found)
		{
			GVM_LOG(main, "find in sandbox in object "
							  << object->get_location() << " as type "
							  << type->get_type_string() << gv_endl);
		}
		else
		{
			GVM_LOG(main, "[ERROR] the property is not found in sand box!!!"
							  << gv_endl);
			return;
		}
		if (type->get_type() == gve_data_type_text)
		{
			gv_text* ptext = (gv_text*)data;
			if (ptext)
			{
				gv_save_string_to_file("temp_temp.c", *ptext);
				gv_system_call("notepad temp_temp.c");
				gv_load_file_to_string("temp_temp.c", *ptext);
				prop->SetValue(CString(*ptext));
			}
		}
		else if (type->get_type() == gve_data_type_ptr)
		{
			gv_type_ptr* ptype = (gv_type_ptr*)type;
			if (ptype->get_pointed_type()->get_type() == gve_data_type_object)
			{
				gv_type_object* ptype_object =
					(gv_type_object*)ptype->get_pointed_type();
				if (ptype_object->get_class()->is_derive_from(
						gv_object::static_class()))
				{
					gvt_ptr< gv_object >* pp = (gvt_ptr< gv_object >*)data;
					if (pp->ptr())
						CMainFrame::static_get()->SelectObject(pp->ptr());
				}
			}
		}
		else if (type->get_type() == gve_data_type_ref_ptr)
		{
			gv_type_ref_ptr* ptype = (gv_type_ref_ptr*)type;
			if (ptype->get_pointed_type()->get_type() == gve_data_type_object)
			{
				gv_type_object* ptype_object =
					(gv_type_object*)ptype->get_pointed_type();
				if (ptype_object->get_class()->is_derive_from(
						gv_object::static_class()))
				{
					gvt_ref_ptr< gv_object >* pp = (gvt_ref_ptr< gv_object >*)data;
					if (pp->ptr())
						CMainFrame::static_get()->SelectObject(pp->ptr());
				}
			}
		}
	}
	CMFCPropertyGridCtrl::OnLButtonDblClk(nFlags, point);
}

void GV_PropertyGridCtrl::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	if (nChar = VK_F5)
	{
		this->FillProperties(this->m_selected_object);
	}
	return CMFCPropertyGridCtrl::OnKeyDown(nChar, nRepCnt, nFlags);
}

void GV_PropertyGridCtrl::FillProperties(gv_object* pobj,
										 gv::gv_class_info* stop_class)
{
	// this->SetFont();
	m_selected_object = pobj;
	EnableHeaderCtrl(FALSE);
	EnableDescriptionArea();
	SetVSDotNetLook();
	RemoveAll();
	if (!pobj)
		return;
	gv_class_info* pclass = pobj->get_class();
	gv_type_object type;
	type.set_class(pclass);
	gv_module* pmod = pobj->get_module();
	BOOL allow_edited = TRUE; // pmod? !(pmod->get_name_id()==gv_id_native):FALSE;
	ShowWindow(FALSE);
	AddOneProperty(*this, NULL, &type, (BYTE*)pobj, "",
				   pobj->get_location_string(), allow_edited, 0, 0, gv_id(),
				   stop_class);
	ShowWindow(TRUE);
};
class gv_object* m_selected_object;

int GV_PropertyGridCtrl::DropObject(UINT nFlags, CPoint point,
									gv::gv_object* drop_object)
{
	if (!drop_object)
		return NULL;
	CMFCPropertyGridProperty* prop = this->GetCurSel();
	if (prop)
	{
		gv_string_tmp address = get_location(prop);
		gvi_type* type;
		gv_byte* data;
		gv_object* object;
		gv_string_tmp tail;
		gv_id enum_id;
		bool found = get_editor()->get_sandbox()->find_global_property(
			address, data, type, object, tail, enum_id);
		if (found)
		{
			GVM_LOG(main, " try to drop to " << get_location(prop) << gv_endl);
			if (type->get_type() == gve_data_type_ptr)
			{
				gv_type_ptr* ptype = (gv_type_ptr*)type;
				if (ptype->get_pointed_type()->get_type() == gve_data_type_object)
				{
					gv_type_object* ptype_object =
						(gv_type_object*)ptype->get_pointed_type();
					if (drop_object->is_a(ptype_object->get_class()))
					{
						gv_string_tmp s;
						s << drop_object->get_location();
						CString mfc = GV_TO_UNICODE(*s);
						prop->SetValue(mfc);
						this->UpdateData(FALSE);
						return 1;
					}
				}
			}
			else if (type->get_type() == gve_data_type_ref_ptr)
			{
				gv_type_ref_ptr* ptype = (gv_type_ref_ptr*)type;
				if (ptype->get_pointed_type()->get_type() == gve_data_type_object)
				{
					gv_type_object* ptype_object =
						(gv_type_object*)ptype->get_pointed_type();
					if (drop_object->is_a(ptype_object->get_class()))
					{
						gv_string_tmp s;
						s << drop_object->get_location();
						CString mfc = GV_TO_UNICODE(*s);
						prop->SetValue(mfc);
						this->UpdateData(FALSE);
						return 0;
					}
				}
			}
		}
		::MessageBoxA(NULL,
					  "failed to drop the object reference!!!,maybe type mismatch",
					  "error", MB_OK);
	}
	return 0;
};
void GV_PropertyGridCtrl::OnMouseMove(UINT nFlags, CPoint point)
{
	// TODO: Add your message handler code here and/or call default
	CMFCPropertyGridCtrl::OnMouseMove(nFlags, point);
}


text:
//          Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef COMPONENTS_RELATEDNESS_COMPONENT_KINSHIPCOEFFICIENTCOMPUTATION_HPP
#define COMPONENTS_RELATEDNESS_COMPONENT_KINSHIPCOEFFICIENTCOMPUTATION_HPP

#include <stdint.h>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/signals2.hpp>
#include "Eigen/Core"
#include "genfile/VariantIdentifyingData.hpp"
#include "genfile/VariantDataReader.hpp"
#include "genfile/SNPDataSourceProcessor.hpp"
#include "genfile/SingleSNPGenotypeProbabilities.hpp"
#include "genfile/CohortIndividualSource.hpp"
#include "worker/Worker.hpp"
#include "worker/Task.hpp"
#include "appcontext/UIContext.hpp"
#include "appcontext/OptionProcessor.hpp"
#include "appcontext/FileUtil.hpp"
#include "components/RelatednessComponent/KinshipCoefficientManager.hpp"
//#include "components/RelatednessComponent/KinshipCoefficientBlockTask.hpp"

struct KinshipCoefficientComputer: public KinshipCoefficientManager, public genfile::SNPDataSourceProcessor::Callback
{
public:
	typedef std::auto_ptr< KinshipCoefficientComputer > UniquePtr ;

	struct Computation: public genfile::SNPDataSourceProcessor::Callback {
		typedef std::auto_ptr< Computation > UniquePtr ;
		typedef Eigen::MatrixXd Matrix ;
		typedef Eigen::VectorXd Vector ;
		typedef Eigen::Matrix< int, Eigen::Dynamic, Eigen::Dynamic > IntegerMatrix ;
		typedef Eigen::Matrix< int, Eigen::Dynamic, 1 > IntegerVector ;
		//typedef Eigen::MatrixXf IntegerMatrix ;
		//typedef Eigen::VectorXf IntegerVector ;
		virtual std::size_t number_of_snps_included() const = 0 ;
		virtual Matrix const& result() const = 0 ;
		virtual IntegerMatrix const& nonmissingness() const = 0 ;
		virtual std::string get_summary() const = 0 ;
	} ;
	static genfile::SNPDataSourceProcessor::Callback::UniquePtr create_computation( std::string const& spec ) ;

public:
	~KinshipCoefficientComputer() throw() {}

	KinshipCoefficientComputer(
		appcontext::OptionProcessor const& options,
		genfile::CohortIndividualSource const& samples,
		appcontext::UIContext& ui_context,
		Computation::UniquePtr computation
	) ;

	void begin_processing_snps( std::size_t number_of_samples, genfile::SNPDataSource::Metadata const& ) ;
	void processed_snp( genfile::VariantIdentifyingData const& id_data, genfile::VariantDataReader::SharedPtr data_reader ) ;
	void end_processing_snps() ;

private:
	appcontext::OptionProcessor const& m_options ;
	appcontext::UIContext& m_ui_context ;
	std::size_t m_number_of_samples ;
	std::size_t m_number_of_snps ;
	std::size_t m_number_of_snps_processed ;
	genfile::CohortIndividualSource const& m_samples ;
	std::vector< Computation::Matrix > m_result ;
	std::vector< Computation::IntegerMatrix > m_non_missing_count ;
	std::vector< Computation::Vector > m_genotypes ;
	std::vector< Computation::IntegerVector > m_non_missingness ;
	Computation::UniquePtr m_computation ;
	void (*m_accumulate_xxt)( Computation::Vector*, Computation::Matrix*, int const begin_sample_i, int const end_sample_i, int const begin_sample_j, int const end_sample_j, double const ) ;
	void (*m_accumulate_xxt_integer)( Computation::IntegerVector*, Computation::IntegerMatrix*, int const begin_sample_i, int const end_sample_i, int const begin_sample_j, int const end_sample_j, double const ) ;
} ;

namespace impl {
	struct SampleBounds {
		int begin_sample_i ;
		int end_sample_i ;
		int begin_sample_j ;
		int end_sample_j ;
	} ;

	struct Dispatcher ;

	struct NTaskDispatcher {
	public:
		typedef std::auto_ptr< NTaskDispatcher > UniquePtr ;
	public:

		NTaskDispatcher(
			worker::Worker* worker
		) ;

		void set_number_of_tasks( std::size_t number_of_tasks ) ;

		std::size_t number_of_tasks() const ;

		void submit_task( std::size_t task_i, boost::function< void() > task ) ;

		void wait_until_complete() ;

	private:
			boost::ptr_vector< boost::nullable< worker::Task > > m_tasks ;
			worker::Worker* m_worker ;
	} ;

	struct NormaliseGenotypesAndComputeXXt: public KinshipCoefficientComputer::Computation {
		static UniquePtr create( worker::Worker*, std::string const& method ) ;
		NormaliseGenotypesAndComputeXXt( worker::Worker*, std::string const& method ) ;

		Computation::Matrix const& result() const ;
		Computation::IntegerMatrix const& nonmissingness() const ;
		std::string get_summary() const ;

		void begin_processing_snps( std::size_t number_of_samples, genfile::SNPDataSource::Metadata const& ) ;
		void processed_snp( genfile::VariantIdentifyingData const& id_data, genfile::VariantDataReader::SharedPtr data_reader ) ;
		void end_processing_snps() ;
		std::size_t number_of_snps_included() const ;
	private:
		double const m_call_threshhold ;
		double const m_allele_frequency_threshhold ;
		std::size_t m_number_of_snps_included ;
		Computation::Matrix m_result ;
		Computation::IntegerMatrix m_nonmissingness ;
		std::auto_ptr< Dispatcher > m_dispatcher ;
	} ;

	struct NormaliseGenotypesAndComputeXXtFast: public KinshipCoefficientComputer::Computation {
		static UniquePtr create( worker::Worker*, std::size_t const number_of_snps_per_computation ) ;

		NormaliseGenotypesAndComputeXXtFast(
			worker::Worker* worker,
			std::size_t const number_of_snps_per_computation
		) ;
		Computation::Matrix const& result() const ;
		Computation::IntegerMatrix const& nonmissingness() const ;
		std::string get_summary() const ;
		void begin_processing_snps( std::size_t number_of_samples, genfile::SNPDataSource::Metadata const& ) ;
		void processed_snp( genfile::VariantIdentifyingData const& id_data, genfile::VariantDataReader::SharedPtr data_reader ) ;
		void end_processing_snps() ;
		std::size_t number_of_snps_included() const ;
	private:
		worker::Worker* m_worker ;
		NTaskDispatcher::UniquePtr m_dispatcher ;
		double const m_call_threshhold ;
		double const m_allele_frequency_threshhold ;
		std::size_t const m_number_of_snps_per_chunk ;
		std::size_t const m_number_of_snps_per_computation ;
		std::vector< std::vector< double > > m_lookup_tables ;
		std::vector< std::vector< int > > m_nonmissingness_lookup_tables ;
		std::vector< SampleBounds > m_matrix_tiling ;
		std::vector< uint64_t > m_combined_genotypes ;
		std::vector< uint64_t > m_per_snp_genotypes ;
		std::size_t m_snp_count ;
		Computation::Matrix m_result ;
		Computation::IntegerMatrix m_nonmissingness ;
	private:
		void add_snp_to_lookup_table(
			std::size_t const lookup_snp_index,
			double const mean,
			double const sd,
			std::vector< double >* lookup_table,
			std::vector< int >* nonmissingness_lookup_table
		) ;

		void submit_tasks(
			std::vector< uint64_t > const& genotypes
		) ;

		void compute_block(
			SampleBounds const& sample_bounds,
			std::vector< uint64_t > const& genotypes
		) ;
	} ;
}

#endif

max_stars_repo_name: CreRecombinase/qctool

max_issues_repo_name: CreRecombinase/qctool

max_forks_repo_name: CreRecombinase/qctool


text:
#ifndef STAN_MATH_PRIM_FUN_CONSTANTS_HPP
#define STAN_MATH_PRIM_FUN_CONSTANTS_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/inv.hpp>
#include <boost/math/constants/constants.hpp>
#include <cmath>
#include <limits>

namespace stan {
namespace math {

// TODO(anyone) Use constexpr when moving to C++17

/**
 * Return the base of the natural logarithm.
 *
 * @return Base of natural logarithm.
 */
static constexpr double e() { return boost::math::constants::e<double>(); }

/**
 * Return the Euler's gamma constant.
 *
 * @return Euler's Gamma.
 */
static constexpr double egamma() {
  return boost::math::constants::euler<double>();
}

/**
 * Return the value of pi.
 *
 * @return Pi.
 */
static constexpr double pi() { return boost::math::constants::pi<double>(); }

/**
 * Smallest positive value.
 */
static constexpr double EPSILON = std::numeric_limits<double>::epsilon();

/**
 * Positive infinity.
 */
static constexpr double INFTY = std::numeric_limits<double>::infinity();

/**
 * Negative infinity.
 */
static constexpr double NEGATIVE_INFTY = -INFTY;

/**
 * (Quiet) not-a-number value.
 */
static constexpr double NOT_A_NUMBER = std::numeric_limits<double>::quiet_NaN();

/**
 * Twice the value of \f$ \pi \f$,
 * \f$ 2\pi \f$.
 */
static constexpr double TWO_PI = boost::math::constants::two_pi<double>();

/**
 * The natural logarithm of 0,
 * \f$ \log 0 \f$.
 */
static constexpr double LOG_ZERO = -INFTY;

/**
 * The natural logarithm of machine precision \f$ \epsilon \f$,
 * \f$ \log \epsilon \f$.
 */
const double LOG_EPSILON = std::log(EPSILON);

/**
 * The natural logarithm of \f$ \pi \f$,
 * \f$ \log \pi \f$.
 */
const double LOG_PI = std::log(pi());

/**
 * The natural logarithm of 2,
 * \f$ \log 2 \f$.
 */
static constexpr double LOG_TWO = boost::math::constants::ln_two<double>();

/**
 * The natural logarithm of 0.5,
 * \f$ \log 0.5 = \log 1 - \log 2 \f$.
 */
static constexpr double LOG_HALF = -LOG_TWO;

/**
 * The natural logarithm of 2 plus the natural logarithm of \f$ \pi \f$,
 * \f$ \log(2\pi) \f$.
 */
const double LOG_TWO_PI = LOG_TWO + LOG_PI;

/**
 * The value of one quarter the natural logarithm of \f$ \pi \f$,
 * \f$ \log(\pi) / 4 \f$.
 */
const double LOG_PI_OVER_FOUR = 0.25 * LOG_PI;

/**
 * The natural logarithm of the square root of \f$ \pi \f$,
 * \f$ \log(sqrt{\pi}) \f$.
 */
const double LOG_SQRT_PI = std::log(boost::math::constants::root_pi<double>());

/**
 * The natural logarithm of 10,
 * \f$ \log 10 \f$.
 */
static constexpr double LOG_TEN = boost::math::constants::ln_ten<double>();

/**
 * The value of the square root of 2,
 * \f$ \sqrt{2} \f$.
 */
static constexpr double SQRT_TWO = boost::math::constants::root_two<double>();

/**
 * The value of the square root of \f$ \pi \f$,
 * \f$ \sqrt{\pi} \f$.
 */
static constexpr double SQRT_PI = boost::math::constants::root_pi<double>();

/**
 * The value of the square root of \f$ 2\pi \f$,
 * \f$ \sqrt{2\pi} \f$.
 */
static constexpr double SQRT_TWO_PI
    = boost::math::constants::root_two_pi<double>();

/**
 * The square root of 2 divided by the square root of \f$ \pi \f$,
 * \f$ \sqrt{2} / \sqrt{\pi} \f$.
 */
static constexpr double SQRT_TWO_OVER_SQRT_PI = SQRT_TWO / SQRT_PI;

/**
 * The value of 1 over the square root of 2,
 * \f$ 1 / \sqrt{2} \f$.
 */
static constexpr double INV_SQRT_TWO
    = boost::math::constants::one_div_root_two<double>();

/**
 * The value of 1 over the square root of \f$ \pi \f$,
 * \f$ 1 / \sqrt{\pi} \f$.
 */
static constexpr double INV_SQRT_PI
    = boost::math::constants::one_div_root_pi<double>();

/**
 * The value of 1 over the square root of \f$ 2\pi \f$,
 * \f$ 1 / \sqrt{2\pi} \f$.
 */
static constexpr double INV_SQRT_TWO_PI
    = boost::math::constants::one_div_root_two_pi<double>();

/**
 * The value of 2 over the square root of \f$ \pi \f$,
 * \f$ 2 / \sqrt{\pi} \f$.
 */
static constexpr double TWO_OVER_SQRT_PI
    = boost::math::constants::two_div_root_pi<double>();

/**
 * The value of half the natural logarithm 2,
 * \f$ \log(2) / 2 \f$.
 */
static constexpr double HALF_LOG_TWO = 0.5 * LOG_TWO;

/**
 * The value of half the natural logarithm \f$ 2\pi \f$,
 * \f$ \log(2\pi) / 2 \f$.
 */
const double HALF_LOG_TWO_PI = 0.5 * LOG_TWO_PI;

/**
 * The value of minus the natural logarithm of the square root of \f$ 2\pi \f$,
 * \f$ -\log(\sqrt{2\pi}) \f$.
 */
const double NEG_LOG_SQRT_TWO_PI = -std::log(SQRT_TWO_PI);

/**
 * Largest rate parameter allowed in Poisson RNG
 */
const double POISSON_MAX_RATE = std::pow(2.0, 30);

/**
 * Return positive infinity.
 *
 * @return Positive infinity.
 */
static constexpr inline double positive_infinity() { return INFTY; }

/**
 * Return negative infinity.
 *
 * @return Negative infinity.
 */
static constexpr inline double negative_infinity() { return NEGATIVE_INFTY; }

/**
 * Return (quiet) not-a-number.
 *
 * @return Quiet not-a-number.
 */
static constexpr inline double not_a_number() { return NOT_A_NUMBER; }

/**
 * Returns the difference between 1.0 and the next value
 * representable.
 *
 * @return Minimum positive number.
 */
static constexpr inline double machine_precision() { return EPSILON; }

/**
 * Returns the natural logarithm of ten.
 *
 * @return Natural logarithm of ten.
 */
static constexpr inline double log10() { return LOG_TEN; }

/**
 * Returns the square root of two.
 *
 * @return Square root of two.
 */
static constexpr inline double sqrt2() { return SQRT_TWO; }

}  // namespace math
}  // namespace stan

#endif