<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Time.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 22:47:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _FORMS_TIME_HXX_
#include "Time.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _TOOLS_TIME_HXX
#include <tools/time.hxx>
#endif
#ifndef _COMPHELPER_DATETIME_HXX_
#include <comphelper/datetime.hxx>
#endif
#ifndef _DBHELPER_DBCONVERSION_HXX_
#include <connectivity/dbconversion.hxx>
#endif

#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif

using namespace dbtools;

//.........................................................................
namespace frm
{
//.........................................................................

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;

//==================================================================
//=
//==================================================================

//==================================================================
//= OTimeControl
//==================================================================
//------------------------------------------------------------------
OTimeControl::OTimeControl(const Reference<XMultiServiceFactory>& _rxFactory)
               :OBoundControl(_rxFactory, VCL_CONTROL_TIMEFIELD)
{
}

//------------------------------------------------------------------
InterfaceRef SAL_CALL OTimeControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new OTimeControl(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> OTimeControl::_getTypes()
{
    return OBoundControl::_getTypes();
}

//------------------------------------------------------------------------------
StringSequence SAL_CALL OTimeControl::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControl::getSupportedServiceNames();
    aSupported.realloc(aSupported.getLength() + 1);

    ::rtl::OUString*pArray = aSupported.getArray();
    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_TIMEFIELD;
    return aSupported;
}

//==================================================================
//= OTimeModel
//==================================================================
//------------------------------------------------------------------
InterfaceRef SAL_CALL OTimeModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new OTimeModel(_rxFactory));
}

// XServiceInfo
//------------------------------------------------------------------------------
StringSequence SAL_CALL OTimeModel::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();

    sal_Int32 nOldLen = aSupported.getLength();
    aSupported.realloc( nOldLen + 8 );
    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;

    *pStoreTo++ = BINDABLE_CONTROL_MODEL;
    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;

    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;

    *pStoreTo++ = FRM_SUN_COMPONENT_TIMEFIELD;
    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_TIMEFIELD;
    *pStoreTo++ = BINDABLE_DATABASE_TIME_FIELD;

    return aSupported;
}

//------------------------------------------------------------------------------
Sequence<Type> OTimeModel::_getTypes()
{
    return OBoundControlModel::_getTypes();
}

//------------------------------------------------------------------
DBG_NAME( OTimeModel )
//------------------------------------------------------------------
OTimeModel::OTimeModel(const Reference<XMultiServiceFactory>& _rxFactory)
            :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_TIMEFIELD, FRM_SUN_CONTROL_TIMEFIELD, sal_True, sal_True )
                                    // use the old control name for compytibility reasons
            ,OLimitedFormats(_rxFactory, FormComponentType::TIMEFIELD)
{
    DBG_CTOR( OTimeModel, NULL );

    m_nClassId = FormComponentType::TIMEFIELD;
    initValueProperty( PROPERTY_TIME, PROPERTY_ID_TIME );

    setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_TIMEFORMAT));
}

//------------------------------------------------------------------------------
OTimeModel::OTimeModel( const OTimeModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
    :OEditBaseModel( _pOriginal, _rxFactory )
    ,OLimitedFormats( _rxFactory, FormComponentType::TIMEFIELD )
{
    DBG_CTOR( OTimeModel, NULL );

    setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_TIMEFORMAT ) );
}

//------------------------------------------------------------------------------
OTimeModel::~OTimeModel( )
{
    setAggregateSet(Reference< XFastPropertySet >(), -1);
    DBG_DTOR( OTimeModel, NULL );
}

// XCloneable
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( OTimeModel )

//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OTimeModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)
{
    return FRM_COMPONENT_TIMEFIELD; // old (non-sun) name for compatibility !
}

// XPropertySet
//------------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL OTimeModel::getPropertySetInfo() throw( RuntimeException )
{
    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}

//------------------------------------------------------------------------------
void OTimeModel::fillProperties(
        Sequence< Property >& _rProps,
        Sequence< Property >& _rAggregateProps ) const
{
    BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel )
        DECL_PROP3(DEFAULT_TIME,            sal_Int32,              BOUND, MAYBEDEFAULT, MAYBEVOID);
        DECL_PROP1(TABINDEX,                sal_Int16,              BOUND);
        DECL_PROP1(FORMATKEY,               sal_Int32,              TRANSIENT);
        DECL_IFACE_PROP2(FORMATSSUPPLIER,   XNumberFormatsSupplier, READONLY, TRANSIENT);
    END_DESCRIBE_PROPERTIES();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OTimeModel::getInfoHelper()
{
    return *const_cast<OTimeModel*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
void SAL_CALL OTimeModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const
{
    switch (_nHandle)
    {
        case PROPERTY_ID_FORMATKEY:
            getFormatKeyPropertyValue(_rValue);
            break;
        case PROPERTY_ID_FORMATSSUPPLIER:
            _rValue <<= getFormatsSupplier();
            break;
        default:
            OEditBaseModel::getFastPropertyValue(_rValue, _nHandle);
            break;
    }
}

//------------------------------------------------------------------------------
sal_Bool SAL_CALL OTimeModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,
        sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException)
{
    if (PROPERTY_ID_FORMATKEY == _nHandle)
        return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue);
    else
        return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue );
}

//------------------------------------------------------------------------------
void SAL_CALL OTimeModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception)
{
    if (PROPERTY_ID_FORMATKEY == _nHandle)
        setFormatKeyPropertyValue(_rValue);
    else
        OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
}

// XLoadListener
//------------------------------------------------------------------------------
void OTimeModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm )
{
    OBoundControlModel::onConnectedDbColumn( _rxForm );
    Reference<XPropertySet> xField = getField();
    if (xField.is())
    {
        m_bDateTimeField = sal_False;
        try
        {
            sal_Int32 nFieldType;
            xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType;
            m_bDateTimeField = (nFieldType == DataType::TIMESTAMP);
        }
        catch(Exception&)
        {
        }
    }
}

//------------------------------------------------------------------------------
sal_Bool OTimeModel::commitControlValueToDbColumn( bool _bPostReset )
{
    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );
    if ( !compare( aControlValue, m_aSaveValue ) )
    {
        if ( !aControlValue.hasValue() )
            m_xColumnUpdate->updateNull();
        else
        {
            try
            {
                util::Time aTime;
                if ( !( aControlValue >>= aTime ) )
                {
                    sal_Int32 nAsInt(0);
                    aControlValue >>= nAsInt;
                    aTime = DBTypeConversion::toTime(nAsInt);
                }

                if (!m_bDateTimeField)
                    m_xColumnUpdate->updateTime(aTime);
                else
                {
                    starutil::DateTime aDateTime = m_xColumn->getTimestamp();
                    aDateTime.HundredthSeconds = aTime.HundredthSeconds;
                    aDateTime.Seconds = aTime.Seconds;
                    aDateTime.Minutes = aTime.Minutes;
                    aDateTime.Hours = aTime.Hours;
                    m_xColumnUpdate->updateTimestamp(aDateTime);
                }
            }
            catch(Exception&)
            {
                return sal_False;
            }
        }
        m_aSaveValue = aControlValue;
    }
    return sal_True;
}

//------------------------------------------------------------------------------
Any OTimeModel::translateControlValueToExternalValue( ) const
{
    Any aExternalValue( getControlValue() );
    if ( aExternalValue.hasValue() )
    {
        sal_Int32 nTime = 0;
        OSL_VERIFY( aExternalValue >>= nTime );
        if ( nTime == ::Time( 99, 99, 99 ).GetTime() )
            // "invalid time" in VCL is different from "invalid time" in UNO
            aExternalValue <<= util::Time( -1, -1, -1, -1 );
        else
            aExternalValue <<= DBTypeConversion::toTime( nTime );
    }
    return aExternalValue;
}

//------------------------------------------------------------------------------
Any OTimeModel::translateExternalValueToControlValue( ) const
{
    OSL_PRECOND( hasExternalValueBinding(),
        "OTimeModel::translateExternalValueToControlValue: precondition not met!" );

    Any aControlValue;
    if ( hasExternalValueBinding() )
    {
        Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Time* >( NULL ) ) );
        if ( aExternalValue.hasValue() )
        {
            util::Time aTime;
            OSL_VERIFY( aExternalValue >>= aTime );
            aControlValue <<= DBTypeConversion::toINT32( aTime );
        }
    }
    return aControlValue;
}

//------------------------------------------------------------------------------
Any OTimeModel::translateDbColumnToControlValue()
{
    util::Time aTime = m_xColumn->getTime();
    if ( m_xColumn->wasNull() )
        m_aSaveValue.clear();
    else
        // the aggregated set expects an Int32 as value ...
        m_aSaveValue <<= DBTypeConversion::toINT32( aTime );

    return m_aSaveValue;
}

//------------------------------------------------------------------------------
Any OTimeModel::getDefaultForReset() const
{
    Any aValue;
    if  (m_aDefault.getValueType().getTypeClass() == TypeClass_LONG)
        aValue = m_aDefault;
    else
    {   // aktuelles Datum einstellen
        ::Time aCurrentTime;
        aValue <<= (sal_Int32)aCurrentTime.GetTime();
    }

    return aValue;
}

//------------------------------------------------------------------------------
sal_Bool OTimeModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding )
{
    OSL_PRECOND( _rxBinding.is(), "OTimeModel::approveValueBinding: invalid binding!" );

    return  _rxBinding.is()
        &&  _rxBinding->supportsType( ::getCppuType( static_cast< util::Time* >( NULL ) ) );
}

//.........................................................................
}   // namespace frm
//.........................................................................

<commit_msg>INTEGRATION: CWS pbrwuno (1.18.14); FILE MERGED 2005/10/17 12:20:15 fs 1.18.14.1: removed some obsolete includes<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Time.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: vg $ $Date: 2006-03-14 10:58:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _FORMS_TIME_HXX_
#include "Time.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _TOOLS_TIME_HXX
#include <tools/time.hxx>
#endif
#ifndef _DBHELPER_DBCONVERSION_HXX_
#include <connectivity/dbconversion.hxx>
#endif

#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif

using namespace dbtools;

//.........................................................................
namespace frm
{
//.........................................................................

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;

//==================================================================
//=
//==================================================================

//==================================================================
//= OTimeControl
//==================================================================
//------------------------------------------------------------------
OTimeControl::OTimeControl(const Reference<XMultiServiceFactory>& _rxFactory)
               :OBoundControl(_rxFactory, VCL_CONTROL_TIMEFIELD)
{
}

//------------------------------------------------------------------
InterfaceRef SAL_CALL OTimeControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new OTimeControl(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> OTimeControl::_getTypes()
{
    return OBoundControl::_getTypes();
}

//------------------------------------------------------------------------------
StringSequence SAL_CALL OTimeControl::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControl::getSupportedServiceNames();
    aSupported.realloc(aSupported.getLength() + 1);

    ::rtl::OUString*pArray = aSupported.getArray();
    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_TIMEFIELD;
    return aSupported;
}

//==================================================================
//= OTimeModel
//==================================================================
//------------------------------------------------------------------
InterfaceRef SAL_CALL OTimeModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new OTimeModel(_rxFactory));
}

// XServiceInfo
//------------------------------------------------------------------------------
StringSequence SAL_CALL OTimeModel::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();

    sal_Int32 nOldLen = aSupported.getLength();
    aSupported.realloc( nOldLen + 8 );
    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;

    *pStoreTo++ = BINDABLE_CONTROL_MODEL;
    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;

    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;

    *pStoreTo++ = FRM_SUN_COMPONENT_TIMEFIELD;
    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_TIMEFIELD;
    *pStoreTo++ = BINDABLE_DATABASE_TIME_FIELD;

    return aSupported;
}

//------------------------------------------------------------------------------
Sequence<Type> OTimeModel::_getTypes()
{
    return OBoundControlModel::_getTypes();
}

//------------------------------------------------------------------
DBG_NAME( OTimeModel )
//------------------------------------------------------------------
OTimeModel::OTimeModel(const Reference<XMultiServiceFactory>& _rxFactory)
            :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_TIMEFIELD, FRM_SUN_CONTROL_TIMEFIELD, sal_True, sal_True )
                                    // use the old control name for compytibility reasons
            ,OLimitedFormats(_rxFactory, FormComponentType::TIMEFIELD)
{
    DBG_CTOR( OTimeModel, NULL );

    m_nClassId = FormComponentType::TIMEFIELD;
    initValueProperty( PROPERTY_TIME, PROPERTY_ID_TIME );

    setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_TIMEFORMAT));
}

//------------------------------------------------------------------------------
OTimeModel::OTimeModel( const OTimeModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
    :OEditBaseModel( _pOriginal, _rxFactory )
    ,OLimitedFormats( _rxFactory, FormComponentType::TIMEFIELD )
{
    DBG_CTOR( OTimeModel, NULL );

    setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_TIMEFORMAT ) );
}

//------------------------------------------------------------------------------
OTimeModel::~OTimeModel( )
{
    setAggregateSet(Reference< XFastPropertySet >(), -1);
    DBG_DTOR( OTimeModel, NULL );
}

// XCloneable
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( OTimeModel )

//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OTimeModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)
{
    return FRM_COMPONENT_TIMEFIELD; // old (non-sun) name for compatibility !
}

// XPropertySet
//------------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL OTimeModel::getPropertySetInfo() throw( RuntimeException )
{
    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}

//------------------------------------------------------------------------------
void OTimeModel::fillProperties(
        Sequence< Property >& _rProps,
        Sequence< Property >& _rAggregateProps ) const
{
    BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel )
        DECL_PROP3(DEFAULT_TIME,            sal_Int32,              BOUND, MAYBEDEFAULT, MAYBEVOID);
        DECL_PROP1(TABINDEX,                sal_Int16,              BOUND);
        DECL_PROP1(FORMATKEY,               sal_Int32,              TRANSIENT);
        DECL_IFACE_PROP2(FORMATSSUPPLIER,   XNumberFormatsSupplier, READONLY, TRANSIENT);
    END_DESCRIBE_PROPERTIES();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OTimeModel::getInfoHelper()
{
    return *const_cast<OTimeModel*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
void SAL_CALL OTimeModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const
{
    switch (_nHandle)
    {
        case PROPERTY_ID_FORMATKEY:
            getFormatKeyPropertyValue(_rValue);
            break;
        case PROPERTY_ID_FORMATSSUPPLIER:
            _rValue <<= getFormatsSupplier();
            break;
        default:
            OEditBaseModel::getFastPropertyValue(_rValue, _nHandle);
            break;
    }
}

//------------------------------------------------------------------------------
sal_Bool SAL_CALL OTimeModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,
        sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException)
{
    if (PROPERTY_ID_FORMATKEY == _nHandle)
        return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue);
    else
        return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue );
}

//------------------------------------------------------------------------------
void SAL_CALL OTimeModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception)
{
    if (PROPERTY_ID_FORMATKEY == _nHandle)
        setFormatKeyPropertyValue(_rValue);
    else
        OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
}

// XLoadListener
//------------------------------------------------------------------------------
void OTimeModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm )
{
    OBoundControlModel::onConnectedDbColumn( _rxForm );
    Reference<XPropertySet> xField = getField();
    if (xField.is())
    {
        m_bDateTimeField = sal_False;
        try
        {
            sal_Int32 nFieldType;
            xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType;
            m_bDateTimeField = (nFieldType == DataType::TIMESTAMP);
        }
        catch(Exception&)
        {
        }
    }
}

//------------------------------------------------------------------------------
sal_Bool OTimeModel::commitControlValueToDbColumn( bool _bPostReset )
{
    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );
    if ( !compare( aControlValue, m_aSaveValue ) )
    {
        if ( !aControlValue.hasValue() )
            m_xColumnUpdate->updateNull();
        else
        {
            try
            {
                util::Time aTime;
                if ( !( aControlValue >>= aTime ) )
                {
                    sal_Int32 nAsInt(0);
                    aControlValue >>= nAsInt;
                    aTime = DBTypeConversion::toTime(nAsInt);
                }

                if (!m_bDateTimeField)
                    m_xColumnUpdate->updateTime(aTime);
                else
                {
                    util::DateTime aDateTime = m_xColumn->getTimestamp();
                    aDateTime.HundredthSeconds = aTime.HundredthSeconds;
                    aDateTime.Seconds = aTime.Seconds;
                    aDateTime.Minutes = aTime.Minutes;
                    aDateTime.Hours = aTime.Hours;
                    m_xColumnUpdate->updateTimestamp(aDateTime);
                }
            }
            catch(Exception&)
            {
                return sal_False;
            }
        }
        m_aSaveValue = aControlValue;
    }
    return sal_True;
}

//------------------------------------------------------------------------------
Any OTimeModel::translateControlValueToExternalValue( ) const
{
    Any aExternalValue( getControlValue() );
    if ( aExternalValue.hasValue() )
    {
        sal_Int32 nTime = 0;
        OSL_VERIFY( aExternalValue >>= nTime );
        if ( nTime == ::Time( 99, 99, 99 ).GetTime() )
            // "invalid time" in VCL is different from "invalid time" in UNO
            aExternalValue <<= util::Time( -1, -1, -1, -1 );
        else
            aExternalValue <<= DBTypeConversion::toTime( nTime );
    }
    return aExternalValue;
}

//------------------------------------------------------------------------------
Any OTimeModel::translateExternalValueToControlValue( ) const
{
    OSL_PRECOND( hasExternalValueBinding(),
        "OTimeModel::translateExternalValueToControlValue: precondition not met!" );

    Any aControlValue;
    if ( hasExternalValueBinding() )
    {
        Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Time* >( NULL ) ) );
        if ( aExternalValue.hasValue() )
        {
            util::Time aTime;
            OSL_VERIFY( aExternalValue >>= aTime );
            aControlValue <<= DBTypeConversion::toINT32( aTime );
        }
    }
    return aControlValue;
}

//------------------------------------------------------------------------------
Any OTimeModel::translateDbColumnToControlValue()
{
    util::Time aTime = m_xColumn->getTime();
    if ( m_xColumn->wasNull() )
        m_aSaveValue.clear();
    else
        // the aggregated set expects an Int32 as value ...
        m_aSaveValue <<= DBTypeConversion::toINT32( aTime );

    return m_aSaveValue;
}

//------------------------------------------------------------------------------
Any OTimeModel::getDefaultForReset() const
{
    Any aValue;
    if  (m_aDefault.getValueType().getTypeClass() == TypeClass_LONG)
        aValue = m_aDefault;
    else
    {   // aktuelles Datum einstellen
        ::Time aCurrentTime;
        aValue <<= (sal_Int32)aCurrentTime.GetTime();
    }

    return aValue;
}

//------------------------------------------------------------------------------
sal_Bool OTimeModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding )
{
    OSL_PRECOND( _rxBinding.is(), "OTimeModel::approveValueBinding: invalid binding!" );

    return  _rxBinding.is()
        &&  _rxBinding->supportsType( ::getCppuType( static_cast< util::Time* >( NULL ) ) );
}

//.........................................................................
}   // namespace frm
//.........................................................................

<|endoftext|>


<commit_before>#ifndef CONFIG_HPP
#define CONFIG_HPP

#include "basicTrie.hpp"
#include "naive.hpp"

// Which LPM implmentation to use
using LPM=Naive;

// Fixed ring size
constexpr auto RING_SIZE = 1024;

// Maximum time to wait for ARP
constexpr auto ARP_WAIT_MILLIS = 1000;

// Maximum backlog in a worker
constexpr auto WORKER_MAX_BACKLOG = 256;

#endif /* FRAME_HPP */
<commit_msg>switch to BasicTrie<commit_after>#ifndef CONFIG_HPP
#define CONFIG_HPP

#include "basicTrie.hpp"
#include "naive.hpp"

// Which LPM implmentation to use
using LPM=BasicTrie;

// Fixed ring size
constexpr auto RING_SIZE = 1024;

// Maximum time to wait for ARP
constexpr auto ARP_WAIT_MILLIS = 1000;

// Maximum backlog in a worker
constexpr auto WORKER_MAX_BACKLOG = 256;

#endif /* CONFIG_HPP */
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "SubProblem.h"
#include "Factory.h"
#include "MooseMesh.h"
#include "Conversion.h"
#include "Function.h"
#include "MooseApp.h"

template<>
InputParameters validParams<SubProblem>()
{
  InputParameters params = validParams<Problem>();
  return params;
}

// SubProblem /////

SubProblem::SubProblem(const std::string & name, InputParameters parameters) :
    Problem(name, parameters),
    _factory(_app.getFactory()),
    _restartable_data(libMesh::n_threads())
{
  unsigned int n_threads = libMesh::n_threads();
  _real_zero.resize(n_threads, 0.);
  _zero.resize(n_threads);
  _grad_zero.resize(n_threads);
  _second_zero.resize(n_threads);
  _second_phi_zero.resize(n_threads);
  _active_elemental_moose_variables.resize(n_threads);
  _has_active_elemental_moose_variables.resize(n_threads);
}

SubProblem::~SubProblem()
{
  unsigned int n_threads = libMesh::n_threads();
  for (unsigned int i = 0; i < n_threads; i++)
  {
    _zero[i].release();
    _grad_zero[i].release();
    _second_zero[i].release();
    _second_phi_zero[i].release();
  }
}

void
SubProblem::setActiveElementalMooseVariables(const std::set<MooseVariable *> & moose_vars, THREAD_ID tid)
{
  _has_active_elemental_moose_variables[tid] = 1;
  _active_elemental_moose_variables[tid] = moose_vars;
}

const std::set<MooseVariable *> &
SubProblem::getActiveElementalMooseVariables(THREAD_ID tid)
{
  return _active_elemental_moose_variables[tid];
}

bool
SubProblem::hasActiveElementalMooseVariables(THREAD_ID tid)
{
  return _has_active_elemental_moose_variables[tid];
}

void
SubProblem::clearActiveElementalMooseVariables(THREAD_ID tid)
{
  _has_active_elemental_moose_variables[tid] = 0;
  _active_elemental_moose_variables[tid].clear();
}

std::set<SubdomainID>
SubProblem::getMaterialPropertyBlocks(const std::string & prop_name)
{
  std::set<SubdomainID> blocks;

  for (std::map<unsigned int, std::set<std::string> >::iterator it = _map_block_material_props.begin();
      it != _map_block_material_props.end();
      ++it)
  {
    std::set<std::string> & prop_names = it->second;
    std::set<std::string>::iterator name_it = prop_names.find(prop_name);
    if (name_it != prop_names.end())
      blocks.insert(it->first);
  }

  return blocks;
}

std::vector<SubdomainName>
SubProblem::getMaterialPropertyBlockNames(const std::string & prop_name)
{
  std::set<SubdomainID> blocks = getMaterialPropertyBlocks(prop_name);
  std::vector<SubdomainName> block_names;
  block_names.reserve(blocks.size());

  for (std::set<SubdomainID>::iterator it = blocks.begin(); it != blocks.end(); ++it)
  {
    std::stringstream ss;
    ss << *it;
    block_names.push_back(ss.str());
  }
  return block_names;
}

std::set<BoundaryID>
SubProblem::getMaterialPropertyBoundaryIDs(const std::string & prop_name)
{
  std::set<BoundaryID> boundaries;

  for (std::map<unsigned int, std::set<std::string> >::iterator it = _map_boundary_material_props.begin();
      it != _map_boundary_material_props.end();
      ++it)
  {
    std::set<std::string> & prop_names = it->second;
    std::set<std::string>::iterator name_it = prop_names.find(prop_name);
    if (name_it != prop_names.end())
      boundaries.insert(it->first);
  }

  return boundaries;
}

std::vector<BoundaryName>
SubProblem::getMaterialPropertyBoundaryNames(const std::string & prop_name)
{
  std::set<BoundaryID> boundaries = getMaterialPropertyBoundaryIDs(prop_name);
  std::vector<BoundaryName> boundary_names;
  boundary_names.reserve(boundaries.size());

  for (std::set<BoundaryID>::iterator it = boundaries.begin(); it != boundaries.end(); ++it)
  {
    std::stringstream ss;
    ss << *it;
    boundary_names.push_back(ss.str());
  }
  return boundary_names;
}

void
SubProblem::storeMatPropName(SubdomainID block_id, const std::string & name)
{
  _map_block_material_props[block_id].insert(name);
}

void
SubProblem::storeMatPropName(BoundaryID boundary_id, const std::string & name)
{
  _map_boundary_material_props[boundary_id].insert(name);
}

void
SubProblem::storeDelayedCheckMatProp(const std::string & requestor, SubdomainID block_id, const std::string & name)
{
  _map_block_material_props_check[block_id].insert(std::make_pair(requestor, name));
}

void
SubProblem::storeDelayedCheckMatProp(const std::string & requestor, BoundaryID boundary_id, const std::string & name)
{
  _map_boundary_material_props_check[boundary_id].insert(std::make_pair(requestor, name));
}

void
SubProblem::checkBlockMatProps()
{
  checkMatProps(_map_block_material_props, _map_block_material_props_check, "block");
}

void
SubProblem::checkBoundaryMatProps()
{
  checkMatProps(_map_boundary_material_props, _map_boundary_material_props_check, "boundary");
}

void
SubProblem::markMatPropRequested(const std::string & prop_name)
{
  _material_property_requested.insert(prop_name);
}

bool
SubProblem::isMatPropRequested(const std::string & prop_name) const
{
  return _material_property_requested.find(prop_name) != _material_property_requested.end();
}

DiracKernelInfo &
SubProblem::diracKernelInfo()
{
  return _dirac_kernel_info;
}

Real
SubProblem::finalNonlinearResidual()
{
  return 0;
}

unsigned int
SubProblem::nNonlinearIterations()
{
  return 0;
}

unsigned int
SubProblem::nLinearIterations()
{
  return 0;
}

void
SubProblem::meshChanged()
{
  mooseError("This system does not support changing the mesh");
}

void
SubProblem::checkMatProps(std::map<unsigned int, std::set<std::string> > & props,
                          std::map<unsigned int, std::multimap<std::string, std::string> > & check_props,
                          const std::string & type)
{

  // Set flag for type: block/boundary
  bool block_type;
  if (type.compare("block") == 0)
    block_type = true;
  else if (type.compare("boundary") == 0)
    block_type = false;
  else
    mooseError("Unknown type argument, it must be 'block' or 'boundary'");

  // Variable for storing the value for ANY_BLOCK_ID/ANY_BOUNDARY_ID
  int any_id;

  // Variable for storing all available blocks/boundaries from the mesh
  std::set<int> all_ids;

  // Define the id variables based on the type of material checking
  if (block_type)
  {
    any_id = Moose::ANY_BLOCK_ID;
    all_ids.insert(mesh().meshSubdomains().begin(), mesh().meshSubdomains().end());
  }
  else
  {
    any_id = Moose::ANY_BOUNDARY_ID;
    all_ids.insert(mesh().getBoundaryIDs().begin(), mesh().getBoundaryIDs().end());
  }

  // Loop through the properties to check
  for (std::map<unsigned int, std::multimap<std::string, std::string> >::const_iterator check_it = check_props.begin();
       check_it != check_props.end(); ++check_it)
  {
    // The current id for the property being checked (BoundaryID || BlockID)
    int check_id = check_it->first;

    // Get the name of the block/boundary (for error reporting)
    std::string check_name;
    if (block_type)
    {
      // TODO: Put a better a interface in MOOSE
      std::map<subdomain_id_type, std::string> & name_map = mesh().getMesh().set_subdomain_name_map();
      std::map<subdomain_id_type, std::string>::const_iterator pos = name_map.find(check_id);
      if (pos != name_map.end())
        check_name = pos->second;
    }
    else
      check_name = mesh().getMesh().get_boundary_info().sideset_name(check_id);

    // Create a name if it doesn't exist
    if (check_name.empty())
    {
      std::ostringstream ss;
      ss << check_id;
      check_name = ss.str();
    }

    // In the case when the material being checked has an ID is set to ANY, then loop through all
    // the possible ids and verify that the material property is defined.
    if (check_id == any_id)
    {
      // Loop through all the block/boundary ids
      for (std::set<int>::const_iterator all_it = all_ids.begin(); all_it != all_ids.end(); ++all_it)
      {
        // Loop through all the stored properties
        for (std::multimap<std::string, std::string>::const_iterator prop_it = check_it->second.begin(); prop_it != check_it->second.end(); ++prop_it)
        {
          // Produce an error if the material is not defined on the current block/boundary and any block/boundary
          if (props[*all_it].find(prop_it->second) == props[*all_it].end() && props[any_id].find(prop_it->second) == props[any_id].end())
            mooseError("Material property '" + prop_it->second + "', requested by '" + prop_it->first + "' is not defined on " + type + " " + Moose::stringify(*all_it));
        }
      }
    }

    // If the property is contained in the map of properties, loop over the stored names for the current id and
    // check that the property is defined
    else if (props.find(check_id) != props.end())
      for (std::multimap<std::string, std::string>::const_iterator prop_it = check_it->second.begin(); prop_it != check_it->second.end(); ++prop_it)
      {
        // Check if the name is contained in the map and skip over the id if it is Moose::ANY_BLOCK_ID/ANY_BOUNDARY_ID
        if (props[check_id].find(prop_it->second) == props[check_id].end() && check_id != any_id)
          mooseError("Material property '" + prop_it->second + "', requested by '" + prop_it->first + "' is not defined on " + type + " " + check_name);
      }
    else
      mooseError("No material defined on " + type + " " + check_name);
  }
}
<commit_msg>Retrieved of block/boundary names for a meterial property returns the actual names (refs #4420)<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "SubProblem.h"
#include "Factory.h"
#include "MooseMesh.h"
#include "Conversion.h"
#include "Function.h"
#include "MooseApp.h"

template<>
InputParameters validParams<SubProblem>()
{
  InputParameters params = validParams<Problem>();
  return params;
}

// SubProblem /////

SubProblem::SubProblem(const std::string & name, InputParameters parameters) :
    Problem(name, parameters),
    _factory(_app.getFactory()),
    _restartable_data(libMesh::n_threads())
{
  unsigned int n_threads = libMesh::n_threads();
  _real_zero.resize(n_threads, 0.);
  _zero.resize(n_threads);
  _grad_zero.resize(n_threads);
  _second_zero.resize(n_threads);
  _second_phi_zero.resize(n_threads);
  _active_elemental_moose_variables.resize(n_threads);
  _has_active_elemental_moose_variables.resize(n_threads);
}

SubProblem::~SubProblem()
{
  unsigned int n_threads = libMesh::n_threads();
  for (unsigned int i = 0; i < n_threads; i++)
  {
    _zero[i].release();
    _grad_zero[i].release();
    _second_zero[i].release();
    _second_phi_zero[i].release();
  }
}

void
SubProblem::setActiveElementalMooseVariables(const std::set<MooseVariable *> & moose_vars, THREAD_ID tid)
{
  _has_active_elemental_moose_variables[tid] = 1;
  _active_elemental_moose_variables[tid] = moose_vars;
}

const std::set<MooseVariable *> &
SubProblem::getActiveElementalMooseVariables(THREAD_ID tid)
{
  return _active_elemental_moose_variables[tid];
}

bool
SubProblem::hasActiveElementalMooseVariables(THREAD_ID tid)
{
  return _has_active_elemental_moose_variables[tid];
}

void
SubProblem::clearActiveElementalMooseVariables(THREAD_ID tid)
{
  _has_active_elemental_moose_variables[tid] = 0;
  _active_elemental_moose_variables[tid].clear();
}

std::set<SubdomainID>
SubProblem::getMaterialPropertyBlocks(const std::string & prop_name)
{
  std::set<SubdomainID> blocks;

  for (std::map<unsigned int, std::set<std::string> >::iterator it = _map_block_material_props.begin();
      it != _map_block_material_props.end();
      ++it)
  {
    std::set<std::string> & prop_names = it->second;
    std::set<std::string>::iterator name_it = prop_names.find(prop_name);
    if (name_it != prop_names.end())
      blocks.insert(it->first);
  }

  return blocks;
}

std::vector<SubdomainName>
SubProblem::getMaterialPropertyBlockNames(const std::string & prop_name)
{
  std::set<SubdomainID> blocks = getMaterialPropertyBlocks(prop_name);
  std::vector<SubdomainName> block_names;
  block_names.reserve(blocks.size());
  for (std::set<SubdomainID>::iterator it = blocks.begin(); it != blocks.end(); ++it)
  {
    SubdomainName name = mesh().getMesh().subdomain_name(*it);
    if (name.empty())
    {
      std::ostringstream oss;
      oss << *it;
      name = oss.str();
    }
    block_names.push_back(name);
  }

  return block_names;
}

std::set<BoundaryID>
SubProblem::getMaterialPropertyBoundaryIDs(const std::string & prop_name)
{
  std::set<BoundaryID> boundaries;

  for (std::map<unsigned int, std::set<std::string> >::iterator it = _map_boundary_material_props.begin();
      it != _map_boundary_material_props.end();
      ++it)
  {
    std::set<std::string> & prop_names = it->second;
    std::set<std::string>::iterator name_it = prop_names.find(prop_name);
    if (name_it != prop_names.end())
      boundaries.insert(it->first);
  }

  return boundaries;
}

std::vector<BoundaryName>
SubProblem::getMaterialPropertyBoundaryNames(const std::string & prop_name)
{
  std::set<BoundaryID> boundaries = getMaterialPropertyBoundaryIDs(prop_name);
  std::vector<BoundaryName> boundary_names;
  boundary_names.reserve(boundaries.size());
  const BoundaryInfo & boundary_info = mesh().getMesh().get_boundary_info();

  for (std::set<BoundaryID>::iterator it = boundaries.begin(); it != boundaries.end(); ++it)
  {
    BoundaryName name = boundary_info.get_sideset_name(*it);
    if (name.empty())
    {
      std::ostringstream oss;
      oss << *it;
      name = oss.str();
    }
    boundary_names.push_back(name);
  }

  return boundary_names;
}

void
SubProblem::storeMatPropName(SubdomainID block_id, const std::string & name)
{
  _map_block_material_props[block_id].insert(name);
}

void
SubProblem::storeMatPropName(BoundaryID boundary_id, const std::string & name)
{
  _map_boundary_material_props[boundary_id].insert(name);
}

void
SubProblem::storeDelayedCheckMatProp(const std::string & requestor, SubdomainID block_id, const std::string & name)
{
  _map_block_material_props_check[block_id].insert(std::make_pair(requestor, name));
}

void
SubProblem::storeDelayedCheckMatProp(const std::string & requestor, BoundaryID boundary_id, const std::string & name)
{
  _map_boundary_material_props_check[boundary_id].insert(std::make_pair(requestor, name));
}

void
SubProblem::checkBlockMatProps()
{
  checkMatProps(_map_block_material_props, _map_block_material_props_check, "block");
}

void
SubProblem::checkBoundaryMatProps()
{
  checkMatProps(_map_boundary_material_props, _map_boundary_material_props_check, "boundary");
}

void
SubProblem::markMatPropRequested(const std::string & prop_name)
{
  _material_property_requested.insert(prop_name);
}

bool
SubProblem::isMatPropRequested(const std::string & prop_name) const
{
  return _material_property_requested.find(prop_name) != _material_property_requested.end();
}

DiracKernelInfo &
SubProblem::diracKernelInfo()
{
  return _dirac_kernel_info;
}

Real
SubProblem::finalNonlinearResidual()
{
  return 0;
}

unsigned int
SubProblem::nNonlinearIterations()
{
  return 0;
}

unsigned int
SubProblem::nLinearIterations()
{
  return 0;
}

void
SubProblem::meshChanged()
{
  mooseError("This system does not support changing the mesh");
}

void
SubProblem::checkMatProps(std::map<unsigned int, std::set<std::string> > & props,
                          std::map<unsigned int, std::multimap<std::string, std::string> > & check_props,
                          const std::string & type)
{

  // Set flag for type: block/boundary
  bool block_type;
  if (type.compare("block") == 0)
    block_type = true;
  else if (type.compare("boundary") == 0)
    block_type = false;
  else
    mooseError("Unknown type argument, it must be 'block' or 'boundary'");

  // Variable for storing the value for ANY_BLOCK_ID/ANY_BOUNDARY_ID
  int any_id;

  // Variable for storing all available blocks/boundaries from the mesh
  std::set<int> all_ids;

  // Define the id variables based on the type of material checking
  if (block_type)
  {
    any_id = Moose::ANY_BLOCK_ID;
    all_ids.insert(mesh().meshSubdomains().begin(), mesh().meshSubdomains().end());
  }
  else
  {
    any_id = Moose::ANY_BOUNDARY_ID;
    all_ids.insert(mesh().getBoundaryIDs().begin(), mesh().getBoundaryIDs().end());
  }

  // Loop through the properties to check
  for (std::map<unsigned int, std::multimap<std::string, std::string> >::const_iterator check_it = check_props.begin();
       check_it != check_props.end(); ++check_it)
  {
    // The current id for the property being checked (BoundaryID || BlockID)
    int check_id = check_it->first;

    // Get the name of the block/boundary (for error reporting)
    std::string check_name;
    if (block_type)
    {
      // TODO: Put a better a interface in MOOSE
      std::map<subdomain_id_type, std::string> & name_map = mesh().getMesh().set_subdomain_name_map();
      std::map<subdomain_id_type, std::string>::const_iterator pos = name_map.find(check_id);
      if (pos != name_map.end())
        check_name = pos->second;
    }
    else
      check_name = mesh().getMesh().get_boundary_info().sideset_name(check_id);

    // Create a name if it doesn't exist
    if (check_name.empty())
    {
      std::ostringstream ss;
      ss << check_id;
      check_name = ss.str();
    }

    // In the case when the material being checked has an ID is set to ANY, then loop through all
    // the possible ids and verify that the material property is defined.
    if (check_id == any_id)
    {
      // Loop through all the block/boundary ids
      for (std::set<int>::const_iterator all_it = all_ids.begin(); all_it != all_ids.end(); ++all_it)
      {
        // Loop through all the stored properties
        for (std::multimap<std::string, std::string>::const_iterator prop_it = check_it->second.begin(); prop_it != check_it->second.end(); ++prop_it)
        {
          // Produce an error if the material is not defined on the current block/boundary and any block/boundary
          if (props[*all_it].find(prop_it->second) == props[*all_it].end() && props[any_id].find(prop_it->second) == props[any_id].end())
            mooseError("Material property '" + prop_it->second + "', requested by '" + prop_it->first + "' is not defined on " + type + " " + Moose::stringify(*all_it));
        }
      }
    }

    // If the property is contained in the map of properties, loop over the stored names for the current id and
    // check that the property is defined
    else if (props.find(check_id) != props.end())
      for (std::multimap<std::string, std::string>::const_iterator prop_it = check_it->second.begin(); prop_it != check_it->second.end(); ++prop_it)
      {
        // Check if the name is contained in the map and skip over the id if it is Moose::ANY_BLOCK_ID/ANY_BOUNDARY_ID
        if (props[check_id].find(prop_it->second) == props[check_id].end() && check_id != any_id)
          mooseError("Material property '" + prop_it->second + "', requested by '" + prop_it->first + "' is not defined on " + type + " " + check_name);
      }
    else
      mooseError("No material defined on " + type + " " + check_name);
  }
}
<|endoftext|>


<commit_before>
#include "sieve_main.h"
#include "fplll.h"
//#include "LatticePoint.h"
//#include "PointList.h"
#include <thread>
#include <chrono>
#include "SieveGauss.h"
#include <iostream>
#include <fstream>

using namespace fplll;

// Z_NR can be either long, double, or mpz_t

template <class ZT>
void test_run_sieve(int dim)
{
    TerminationConditions< Z_NR<ZT> > term_cond; //sets target-legnth as Mink. bound
    ZZ_mat<ZT> B;
    B.resize(dim, dim);
    B.gen_trg(1.1);
    lll_reduction(B, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);
    Sieve<Z_NR<ZT>, false> Test_Queue (B);
    //Test_Queue.run_2_sieve(term_cond); //file-name to output the results of tests

}

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

    cout << "Hello " << endl;

    bool longflag = false; //to be read_in as input
    int dim[] = {25, 30, 35, 40, 42, 44, 46, 48, 50, 52, 54, 56};
    int length = 12;

    if (longflag)
    {
        for (int i=0; i<length; i++)
            test_run_sieve<long>(dim[i]);
    }

    else
    {
        test_run_sieve<mpz_t>(dim[0]);
    }

    //auto start = std::chrono::high_resolution_clock::now();
//    auto finish = std::chrono::high_resolution_clock::now();
//    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);
//    cout << " Time taken: " << microseconds.count()/1000000.0 << "sec" << endl;
  return 1;
}
<commit_msg>Demo for output.<commit_after>
#include "sieve_main.h"
#include "fplll.h"
//#include "LatticePoint.h"
//#include "PointList.h"
#include <thread>
#include <chrono>
#include "SieveGauss.h"
#include <iostream>
#include <fstream>

using namespace fplll;

// Z_NR can be either long, double, or mpz_t

template <class ZT>
void test_run_sieve(int dim)
{
    TerminationConditions< Z_NR<ZT> > term_cond; //sets target-legnth as Mink. bound
    ZZ_mat<ZT> B;
    B.resize(dim, dim);
    B.gen_trg(1.1);
    lll_reduction(B, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);
    Sieve<Z_NR<ZT>, false> Test_Queue (B);
    //Test_Queue.run_2_sieve(term_cond); //file-name to output the results of tests
    {
    std::ofstream ofs("FILENAME");
    Test_Queue.print_status(-1,ofs);
    }
}

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

    cout << "Hello " << endl;

    bool longflag = false; //to be read_in as input
    int dim[] = {25, 30, 35, 40, 42, 44, 46, 48, 50, 52, 54, 56};
    int length = 12;

    if (longflag)
    {
        for (int i=0; i<length; i++)
            test_run_sieve<long>(dim[i]);
    }

    else
    {
        test_run_sieve<mpz_t>(dim[0]);
    }

    //auto start = std::chrono::high_resolution_clock::now();
//    auto finish = std::chrono::high_resolution_clock::now();
//    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);
//    cout << " Time taken: " << microseconds.count()/1000000.0 << "sec" << endl;
  return 1;
}
<|endoftext|>


<commit_before>#define USE_REGULAR_QUEUE //comment out if you use priority-queue

#include "sieve_main.h"
#include "fplll.h"
#include "LatticePoint.h"
#include "PointList.h"
#include <thread>
#include <chrono>
#include "SieveGauss.h"
#include "LatticePoint2.h"
#include <iostream>
#include <fstream>
#include "Sampler.h"
#include <random>
#include "FilteredList.h"

using namespace fplll;

// Z_NR can be either long, double, or mpz_t

template <class ZT> void test_run_sieve(int dim, std::ofstream &ofs)
{
    //TerminationConditions< Z_NR<ZT> > term_cond; //sets target-legnth as Mink. bound

    //lll_reduction(B, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);
    //Sieve<Z_NR<ZT>, false> Test_Queue (B);
    //Test_Queue.run_2_sieve();

    ZZ_mat<ZT> BTest;
    BTest.resize(dim, dim);
    //BTest.gen_trg(1.1);
    srand (1);
    BTest.gen_qary_prime(1, 10*dim);

    if (dim >= 60)
        bkz_reduction(BTest, 8, BKZ_DEFAULT, FT_DEFAULT, 0);
    else
        lll_reduction(BTest, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);

    Sieve<Z_NR<ZT>, false> Test_Queue (BTest);

    ofs << "sieve is run on B[0]" << BTest[0] << endl;

    auto start = std::chrono::high_resolution_clock::now();
    Test_Queue.run();
    auto finish = std::chrono::high_resolution_clock::now();
    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);

    Test_Queue.print_status(-1,ofs);

    ofs << " Time taken: " << microseconds.count()/1000000.0 << "sec" << endl;
}

template <class Z> void sample_gaussians(int number, double s, double center, double cutoff)
{
    std::mt19937_64 engine;
    for (int i=0; i<number;++i)
    {
        cout << GaussSieve::sample_z_gaussian<Z, std::mt19937_64>(s,center,engine, cutoff) << endl;
    }
}

int main(int argc, char **argv)
{
sample_gaussians<long>(50, 10.0, 0.3, 4.0);
sample_gaussians<long>(50, 0.0000001, 0.48, 4.0); //should still be fast.

ZZ_mat<mpz_t> B,u,u_inv;
B.resize(10, 10);
Matrix<FP_NR<double > > r,mu;
Matrix<Z_NR<mpz_t> > g;
    //generates a lower-triangular matrix B; the argument determines (in a complicated way) the bit-size of entries
    //B.gen_trg(1.1);

srand (1);
    //generates GM lattice
B.gen_qary_prime(1, 15);

auto pGSO = new MatGSO<Z_NR<mpz_t>, FP_NR<double>>(B, u, u_inv, 1);

  pGSO->update_gso();
  mu = pGSO->get_mu_matrix();
  r  = pGSO->get_r_matrix();
  g  = pGSO->get_g_matrix();

cout << B << endl;
cout << mu<< endl;
cout << r << endl;
cout << g << endl;

//        //int dim[] = {52, 54, 56, 58, 60, 62, 64};
//        int dim = 62;
//        int length = 7;
//
//    	#ifdef USE_REGULAR_QUEUE
//        std::ofstream ofs("test_sieve_PQ_dim" +to_string(dim) + ".txt");
//		ofs << "WITH PRIORITY QUEUE" << endl;
//	#else
//		std::ofstream ofs("test_sieve_dim"+to_string(dim) + ".txt");
//		ofs << "WITH STANDARD QUEUE" << endl;
//	#endif
//	for (int i=0; i<length; i++) {
//
//
//		ofs << "start sieve on lattice of dim = " << dim[i] << endl;
//        	test_run_sieve<mpz_t>(dim[i], ofs);
//		ofs << "----------------------------------------" << endl;
//	}

//    for (int i=0; i<1; i++)
//    {
//        ofs << "start sieve on lattice of dim =  " << dim << endl;
//        test_run_sieve<mpz_t>(dim, ofs);
//        ofs << "----------------------------------------" << endl;
//    }
//   ofs.close();
  return 1;
}
<commit_msg>now compiles<commit_after>#define USE_REGULAR_QUEUE //comment out if you use priority-queue

#include "sieve_main.h"
#include "fplll.h"
#include "LatticePoint.h"
#include "PointList.h"
#include <thread>
#include <chrono>
#include "SieveGauss.h"
#include "LatticePoint2.h"
#include <iostream>
#include <fstream>
#include "Sampler.h"
#include <random>
//#include "FilteredList.h"

using namespace fplll;

// Z_NR can be either long, double, or mpz_t

template <class ZT> void test_run_sieve(int dim, std::ofstream &ofs)
{
    //TerminationConditions< Z_NR<ZT> > term_cond; //sets target-legnth as Mink. bound

    //lll_reduction(B, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);
    //Sieve<Z_NR<ZT>, false> Test_Queue (B);
    //Test_Queue.run_2_sieve();

    ZZ_mat<ZT> BTest;
    BTest.resize(dim, dim);
    //BTest.gen_trg(1.1);
    srand (1);
    BTest.gen_qary_prime(1, 10*dim);

    if (dim >= 60)
        bkz_reduction(BTest, 8, BKZ_DEFAULT, FT_DEFAULT, 0);
    else
        lll_reduction(BTest, LLL_DEF_DELTA, LLL_DEF_ETA, LM_WRAPPER);

    Sieve<Z_NR<ZT>, false> Test_Queue (BTest);

    ofs << "sieve is run on B[0]" << BTest[0] << endl;

    auto start = std::chrono::high_resolution_clock::now();
    Test_Queue.run();
    auto finish = std::chrono::high_resolution_clock::now();
    auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start);

    Test_Queue.print_status(-1,ofs);

    ofs << " Time taken: " << microseconds.count()/1000000.0 << "sec" << endl;
}

template <class Z> void sample_gaussians(int number, double s, double center, double cutoff)
{
    std::mt19937_64 engine;
    for (int i=0; i<number;++i)
    {
        cout << GaussSieve::sample_z_gaussian<Z, std::mt19937_64>(s,center,engine, cutoff) << endl;
    }
}

int main(int argc, char **argv)
{
sample_gaussians<long>(50, 10.0, 0.3, 4.0);
sample_gaussians<long>(50, 0.0000001, 0.48, 4.0); //should still be fast.

ZZ_mat<mpz_t> B,u,u_inv;
B.resize(10, 10);
Matrix<FP_NR<double > > r,mu;
Matrix<Z_NR<mpz_t> > g;
    //generates a lower-triangular matrix B; the argument determines (in a complicated way) the bit-size of entries
    //B.gen_trg(1.1);

srand (1);
    //generates GM lattice
B.gen_qary_prime(1, 15);

auto pGSO = new MatGSO<Z_NR<mpz_t>, FP_NR<double>>(B, u, u_inv, 1);

  pGSO->update_gso();
  mu = pGSO->get_mu_matrix();
  r  = pGSO->get_r_matrix();
  g  = pGSO->get_g_matrix();

cout << B << endl;
cout << mu<< endl;
cout << r << endl;
cout << g << endl;

//        //int dim[] = {52, 54, 56, 58, 60, 62, 64};
//        int dim = 62;
//        int length = 7;
//
//    	#ifdef USE_REGULAR_QUEUE
//        std::ofstream ofs("test_sieve_PQ_dim" +to_string(dim) + ".txt");
//		ofs << "WITH PRIORITY QUEUE" << endl;
//	#else
//		std::ofstream ofs("test_sieve_dim"+to_string(dim) + ".txt");
//		ofs << "WITH STANDARD QUEUE" << endl;
//	#endif
//	for (int i=0; i<length; i++) {
//
//
//		ofs << "start sieve on lattice of dim = " << dim[i] << endl;
//        	test_run_sieve<mpz_t>(dim[i], ofs);
//		ofs << "----------------------------------------" << endl;
//	}

//    for (int i=0; i<1; i++)
//    {
//        ofs << "start sieve on lattice of dim =  " << dim << endl;
//        test_run_sieve<mpz_t>(dim, ofs);
//        ofs << "----------------------------------------" << endl;
//    }
//   ofs.close();
  return 1;
}
<|endoftext|>


<commit_before>
// g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2  ./a.out
// icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp  && OMP_NUM_THREADS=2  ./a.out

#include <iostream>
#include <Eigen/Core>
#include <bench/BenchTimer.h>

using namespace std;
using namespace Eigen;

#ifndef SCALAR
#define SCALAR std::complex<double>
// #define SCALAR double
#endif

typedef SCALAR Scalar;
typedef Matrix<Scalar,Dynamic,Dynamic> M;

#ifdef HAVE_BLAS

extern "C" {
  #include <bench/btl/libs/C_BLAS/blas.h>
}

static float fone = 1;
static float fzero = 0;
static double done = 1;
static double szero = 0;
static std::complex<float> cfone = 1;
static std::complex<float> cfzero = 0;
static std::complex<double> cdone = 1;
static std::complex<double> cdzero = 0;
static char notrans = 'N';
static char trans = 'T';
static char nonunit = 'N';
static char lower = 'L';
static char right = 'R';
static int intone = 1;

void blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c)
{
  int M = c.rows(); int N = c.cols(); int K = a.cols();
  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();

  sgemm_(&notrans,&notrans,&M,&N,&K,&fone,
         const_cast<float*>(a.data()),&lda,
         const_cast<float*>(b.data()),&ldb,&fone,
         c.data(),&ldc);
}

void blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c)
{
  int M = c.rows(); int N = c.cols(); int K = a.cols();
  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();

  cgemm_(&notrans,&notrans,&M,&N,&K,(float*)&cfone,
         const_cast<float*>((const float*)a.data()),&lda,
         const_cast<float*>((const float*)b.data()),&ldb,(float*)&cfone,
         (float*)c.data(),&ldc);
}

void blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c)
{
  int M = c.rows(); int N = c.cols(); int K = a.cols();
  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();

  zgemm_(&notrans,&notrans,&M,&N,&K,(double*)&cdone,
         const_cast<double*>((const double*)a.data()),&lda,
         const_cast<double*>((const double*)b.data()),&ldb,(double*)&cdone,
         (double*)c.data(),&ldc);
}

void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c)
{
  int M = c.rows(); int N = c.cols(); int K = a.cols();
  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();

  dgemm_(&notrans,&notrans,&M,&N,&K,&done,
         const_cast<double*>(a.data()),&lda,
         const_cast<double*>(b.data()),&ldb,&done,
         c.data(),&ldc);
}

#endif

template<typename M>
EIGEN_DONT_INLINE void gemm(const M& a, const M& b, M& c)
{
  c.noalias() += a * b;
}

int main(int argc, char ** argv)
{
  std::ptrdiff_t l1 = ei_queryL1CacheSize();
  std::ptrdiff_t l2 = ei_queryTopLevelCacheSize();
  std::cout << "L1 cache size     = " << (l1>0 ? l1/1024 : -1) << " KB\n";
  std::cout << "L2/L3 cache size  = " << (l2>0 ? l2/1024 : -1) << " KB\n";
  typedef ei_product_blocking_traits<Scalar> Blocking;
  std::cout << "Register blocking = " << Blocking::mr << " x " << Blocking::nr << "\n";

  int rep = 1;    // number of repetitions per try
  int tries = 2;  // number of tries, we keep the best

  int s = 2048;
  int cache_size = -1;

  bool need_help = false;
  for (int i=1; i<argc; ++i)
  {
    if(argv[i][0]=='s')
      s = atoi(argv[i]+1);
    else if(argv[i][0]=='c')
      cache_size = atoi(argv[i]+1);
    else if(argv[i][0]=='t')
      tries = atoi(argv[i]+1);
    else if(argv[i][0]=='p')
      rep = atoi(argv[i]+1);
    else
      need_help = true;
  }

  if(need_help)
  {
    std::cout << argv[0] << " s<matrix size> c<cache size> t<nb tries> p<nb repeats>\n";
    return 1;
  }

  if(cache_size>0)
    setCpuCacheSizes(cache_size,96*cache_size);

  int m = s;
  int n = s;
  int p = s;
  M a(m,n); a.setRandom();
  M b(n,p); b.setRandom();
  M c(m,p); c.setOnes();

  std::cout << "Matrix sizes = " << m << "x" << p << " * " << p << "x" << n << "\n";
  std::ptrdiff_t cm(m), cn(n), ck(p);
  computeProductBlockingSizes<Scalar,Scalar>(ck, cm, cn);
  std::cout << "blocking size = " << cm << " x " << ck << "\n";

  M r = c;

  // check the parallel product is correct
  #ifdef EIGEN_HAS_OPENMP
  int procs = omp_get_max_threads();
  if(procs>1)
  {
    #ifdef HAVE_BLAS
    blas_gemm(a,b,r);
    #else
    omp_set_num_threads(1);
    r.noalias() += a * b;
    omp_set_num_threads(procs);
    #endif
    c.noalias() += a * b;
    if(!r.isApprox(c)) std::cerr << "Warning, your parallel product is crap!\n\n";
  }
  #endif

  #ifdef HAVE_BLAS
  BenchTimer tblas;
  BENCH(tblas, tries, rep, blas_gemm(a,b,c));
  std::cout << "blas  cpu         " << tblas.best(CPU_TIMER)/rep  << "s  \t" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9  <<  " GFLOPS \t(" << tblas.total(CPU_TIMER)  << "s)\n";
  std::cout << "blas  real        " << tblas.best(REAL_TIMER)/rep << "s  \t" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 <<  " GFLOPS \t(" << tblas.total(REAL_TIMER) << "s)\n";
  #endif

  BenchTimer tmt;
  BENCH(tmt, tries, rep, gemm(a,b,c));
  std::cout << "eigen cpu         " << tmt.best(CPU_TIMER)/rep  << "s  \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9  <<  " GFLOPS \t(" << tmt.total(CPU_TIMER)  << "s)\n";
  std::cout << "eigen real        " << tmt.best(REAL_TIMER)/rep << "s  \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 <<  " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n";

  #ifdef EIGEN_HAS_OPENMP
  if(procs>1)
  {
    BenchTimer tmono;
    //omp_set_num_threads(1);
    Eigen::setNbThreads(1);
    BENCH(tmono, tries, rep, gemm(a,b,c));
    std::cout << "eigen mono cpu    " << tmono.best(CPU_TIMER)/rep  << "s  \t" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9  <<  " GFLOPS \t(" << tmono.total(CPU_TIMER)  << "s)\n";
    std::cout << "eigen mono real   " << tmono.best(REAL_TIMER)/rep << "s  \t" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 <<  " GFLOPS \t(" << tmono.total(REAL_TIMER) << "s)\n";
    std::cout << "mt speed up x" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER)  << " => " << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << "%\n";
  }
  #endif

  return 0;
}

<commit_msg>update to support mixin types<commit_after>
// g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2  ./a.out
// icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp  && OMP_NUM_THREADS=2  ./a.out

#include <iostream>
#include <Eigen/Core>
#include <bench/BenchTimer.h>

using namespace std;
using namespace Eigen;

#ifndef SCALAR
#define SCALAR std::complex<double>
// #define SCALAR double
#endif

typedef SCALAR Scalar;
typedef NumTraits<Scalar>::Real RealScalar;
typedef Matrix<RealScalar,Dynamic,Dynamic> A;
typedef Matrix<Scalar,Dynamic,Dynamic> B;
typedef Matrix<Scalar,Dynamic,Dynamic> C;

#ifdef HAVE_BLAS

extern "C" {
  #include <bench/btl/libs/C_BLAS/blas.h>
}

static float fone = 1;
static float fzero = 0;
static double done = 1;
static double szero = 0;
static std::complex<float> cfone = 1;
static std::complex<float> cfzero = 0;
static std::complex<double> cdone = 1;
static std::complex<double> cdzero = 0;
static char notrans = 'N';
static char trans = 'T';
static char nonunit = 'N';
static char lower = 'L';
static char right = 'R';
static int intone = 1;

void blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c)
{
  int M = c.rows(); int N = c.cols(); int K = a.cols();
  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();

  sgemm_(&notrans,&notrans,&M,&N,&K,&fone,
         const_cast<float*>(a.data()),&lda,
         const_cast<float*>(b.data()),&ldb,&fone,
         c.data(),&ldc);
}

void blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c)
{
  int M = c.rows(); int N = c.cols(); int K = a.cols();
  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();

  cgemm_(&notrans,&notrans,&M,&N,&K,(float*)&cfone,
         const_cast<float*>((const float*)a.data()),&lda,
         const_cast<float*>((const float*)b.data()),&ldb,(float*)&cfone,
         (float*)c.data(),&ldc);
}

void blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c)
{
  int M = c.rows(); int N = c.cols(); int K = a.cols();
  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();

  zgemm_(&notrans,&notrans,&M,&N,&K,(double*)&cdone,
         const_cast<double*>((const double*)a.data()),&lda,
         const_cast<double*>((const double*)b.data()),&ldb,(double*)&cdone,
         (double*)c.data(),&ldc);
}

void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c)
{
  int M = c.rows(); int N = c.cols(); int K = a.cols();
  int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows();

  dgemm_(&notrans,&notrans,&M,&N,&K,&done,
         const_cast<double*>(a.data()),&lda,
         const_cast<double*>(b.data()),&ldb,&done,
         c.data(),&ldc);
}

#endif

template<typename A, typename B, typename C>
EIGEN_DONT_INLINE void gemm(const A& a, const B& b, C& c)
{
  c.noalias() += a * b;
}

int main(int argc, char ** argv)
{
  std::ptrdiff_t l1 = ei_queryL1CacheSize();
  std::ptrdiff_t l2 = ei_queryTopLevelCacheSize();
  std::cout << "L1 cache size     = " << (l1>0 ? l1/1024 : -1) << " KB\n";
  std::cout << "L2/L3 cache size  = " << (l2>0 ? l2/1024 : -1) << " KB\n";
  typedef ei_product_blocking_traits<Scalar,Scalar> Blocking;
  std::cout << "Register blocking = " << Blocking::mr << " x " << Blocking::nr << "\n";

  int rep = 1;    // number of repetitions per try
  int tries = 2;  // number of tries, we keep the best

  int s = 2048;
  int cache_size = -1;

  bool need_help = false;
  for (int i=1; i<argc; ++i)
  {
    if(argv[i][0]=='s')
      s = atoi(argv[i]+1);
    else if(argv[i][0]=='c')
      cache_size = atoi(argv[i]+1);
    else if(argv[i][0]=='t')
      tries = atoi(argv[i]+1);
    else if(argv[i][0]=='p')
      rep = atoi(argv[i]+1);
    else
      need_help = true;
  }

  if(need_help)
  {
    std::cout << argv[0] << " s<matrix size> c<cache size> t<nb tries> p<nb repeats>\n";
    return 1;
  }

  if(cache_size>0)
    setCpuCacheSizes(cache_size,96*cache_size);

  int m = s;
  int n = s;
  int p = s;
  A a(m,n); a.setRandom();
  B b(n,p); b.setRandom();
  C c(m,p); c.setOnes();

  std::cout << "Matrix sizes = " << m << "x" << p << " * " << p << "x" << n << "\n";
  std::ptrdiff_t cm(m), cn(n), ck(p);
  computeProductBlockingSizes<Scalar,Scalar>(ck, cm, cn);
  std::cout << "blocking size = " << cm << " x " << ck << "\n";

  C r = c;

  // check the parallel product is correct
  #ifdef EIGEN_HAS_OPENMP
  int procs = omp_get_max_threads();
  if(procs>1)
  {
    #ifdef HAVE_BLAS
    blas_gemm(a,b,r);
    #else
    omp_set_num_threads(1);
    r.noalias() += a * b;
    omp_set_num_threads(procs);
    #endif
    c.noalias() += a * b;
    if(!r.isApprox(c)) std::cerr << "Warning, your parallel product is crap!\n\n";
  }
  #endif

  #ifdef HAVE_BLAS
  BenchTimer tblas;
  BENCH(tblas, tries, rep, blas_gemm(a,b,c));
  std::cout << "blas  cpu         " << tblas.best(CPU_TIMER)/rep  << "s  \t" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9  <<  " GFLOPS \t(" << tblas.total(CPU_TIMER)  << "s)\n";
  std::cout << "blas  real        " << tblas.best(REAL_TIMER)/rep << "s  \t" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 <<  " GFLOPS \t(" << tblas.total(REAL_TIMER) << "s)\n";
  #endif

  BenchTimer tmt;
  BENCH(tmt, tries, rep, gemm(a,b,c));
  std::cout << "eigen cpu         " << tmt.best(CPU_TIMER)/rep  << "s  \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9  <<  " GFLOPS \t(" << tmt.total(CPU_TIMER)  << "s)\n";
  std::cout << "eigen real        " << tmt.best(REAL_TIMER)/rep << "s  \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 <<  " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n";

  #ifdef EIGEN_HAS_OPENMP
  if(procs>1)
  {
    BenchTimer tmono;
    //omp_set_num_threads(1);
    Eigen::setNbThreads(1);
    BENCH(tmono, tries, rep, gemm(a,b,c));
    std::cout << "eigen mono cpu    " << tmono.best(CPU_TIMER)/rep  << "s  \t" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9  <<  " GFLOPS \t(" << tmono.total(CPU_TIMER)  << "s)\n";
    std::cout << "eigen mono real   " << tmono.best(REAL_TIMER)/rep << "s  \t" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 <<  " GFLOPS \t(" << tmono.total(REAL_TIMER) << "s)\n";
    std::cout << "mt speed up x" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER)  << " => " << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << "%\n";
  }
  #endif

  return 0;
}

<|endoftext|>


<commit_before>#pragma once

#include "../point2d.hpp"
#include "../region2d.hpp"

#include "../../3party/boost/boost/polygon/polygon.hpp"

#include "../../std/vector.hpp"

namespace boost { namespace polygon {

  typedef int32_t my_coord_t;

  ////////////////////////////////////////////////////////////////////////////////
  // Point concept.
  ////////////////////////////////////////////////////////////////////////////////
  typedef m2::PointI my_point_t;

  template <>
  struct geometry_concept<my_point_t>
  {
    typedef point_concept type;
  };

  template <>
  struct point_traits<my_point_t>
  {
    typedef my_point_t::value_type coordinate_type;

    static inline coordinate_type get(my_point_t const & p, orientation_2d o)
    {
      return ((o == HORIZONTAL) ? p.x : p.y);
    }
  };

  template <>
  struct point_mutable_traits<my_point_t>
  {
    typedef my_point_t::value_type CoordT;

    static inline void set(my_point_t & p, orientation_2d o, CoordT v)
    {
      if (o == HORIZONTAL)
        p.x = v;
      else
        p.y = v;
    }

    static inline my_point_t construct(CoordT x, CoordT y)
    {
      return my_point_t(x, y);
    }
  };

  ////////////////////////////////////////////////////////////////////////////////
  // Polygon concept.
  ////////////////////////////////////////////////////////////////////////////////
  typedef m2::RegionI my_region_t;

  template <>
  struct geometry_concept<my_region_t>
  {
    typedef polygon_concept type;
  };

  template <>
  struct polygon_traits<my_region_t>
  {
    typedef my_region_t::CoordT coordinate_type;
    typedef my_region_t::IteratorT iterator_type;
    typedef my_region_t::ValueT point_type;

    // Get the begin iterator
    static inline iterator_type begin_points(my_region_t const & t)
    {
      return t.Begin();
    }

    // Get the end iterator
    static inline iterator_type end_points(my_region_t const & t)
    {
      return t.End();
    }

    // Get the number of sides of the polygon
    static inline size_t size(my_region_t const & t)
    {
      return t.Size();
    }

    // Get the winding direction of the polygon
    static inline winding_direction winding(my_region_t const & /*t*/)
    {
      return unknown_winding;
    }
  };

  struct my_point_getter
  {
    my_point_t operator() (point_data<my_coord_t> const & t)
    {
      return my_point_t(t.x(), t.y());
    }
  };

  template <>
  struct polygon_mutable_traits<my_region_t>
  {
    // expects stl style iterators
    template <typename IterT>
    static inline my_region_t & set_points(my_region_t & t, IterT b, IterT e)
    {
      t.AssignEx(b, e, my_point_getter());
      return t;
    }
  };

  ////////////////////////////////////////////////////////////////////////////////
  // Polygon set concept.
  ////////////////////////////////////////////////////////////////////////////////
  typedef vector<my_region_t> my_region_set_t;

  template <>
  struct geometry_concept<my_region_set_t>
  {
    typedef polygon_set_concept type;
  };

  // next we map to the concept through traits
  template <>
  struct polygon_set_traits<my_region_set_t>
  {
    typedef my_coord_t coordinate_type;
    typedef my_region_set_t::const_iterator iterator_type;
    typedef my_region_set_t operator_arg_type;

    static inline iterator_type begin(my_region_set_t const & t)
    {
      return t.begin();
    }

    static inline iterator_type end(my_region_set_t const & t)
    {
      return t.end();
    }

    // don't worry about these, just return false from them
    static inline bool clean(my_region_set_t const & /*t*/) { return false; }
    static inline bool sorted(my_region_set_t const & /*t*/) { return false; }
  };

  template <>
  struct polygon_set_mutable_traits<my_region_set_t>
  {
    template <typename IterT>
    static inline void set(my_region_set_t & poly_set, IterT b, IterT e)
    {
      poly_set.clear();

      // this is kind of cheesy. I am copying the unknown input geometry
      // into my own polygon set and then calling get to populate the vector
      polygon_set_data<my_coord_t> ps;
      ps.insert(b, e);
      ps.get(poly_set);

      // if you had your own odd-ball polygon set you would probably have
      // to iterate through each polygon at this point and do something extra
    }
  };
}}
<commit_msg>[ios] Fixed simulator build error<commit_after>#pragma once

#include "../point2d.hpp"
#include "../region2d.hpp"

#include "../../3party/boost/boost/polygon/detail/polygon_sort_adaptor.hpp"
#include "../../3party/boost/boost/polygon/polygon.hpp"

#include "../../std/vector.hpp"

namespace boost { namespace polygon {

  typedef int32_t my_coord_t;

  ////////////////////////////////////////////////////////////////////////////////
  // Point concept.
  ////////////////////////////////////////////////////////////////////////////////
  typedef m2::PointI my_point_t;

  template <>
  struct geometry_concept<my_point_t>
  {
    typedef point_concept type;
  };

  template <>
  struct point_traits<my_point_t>
  {
    typedef my_point_t::value_type coordinate_type;

    static inline coordinate_type get(my_point_t const & p, orientation_2d o)
    {
      return ((o == HORIZONTAL) ? p.x : p.y);
    }
  };

  template <>
  struct point_mutable_traits<my_point_t>
  {
    typedef my_point_t::value_type CoordT;

    static inline void set(my_point_t & p, orientation_2d o, CoordT v)
    {
      if (o == HORIZONTAL)
        p.x = v;
      else
        p.y = v;
    }

    static inline my_point_t construct(CoordT x, CoordT y)
    {
      return my_point_t(x, y);
    }
  };

  ////////////////////////////////////////////////////////////////////////////////
  // Polygon concept.
  ////////////////////////////////////////////////////////////////////////////////
  typedef m2::RegionI my_region_t;

  template <>
  struct geometry_concept<my_region_t>
  {
    typedef polygon_concept type;
  };

  template <>
  struct polygon_traits<my_region_t>
  {
    typedef my_region_t::CoordT coordinate_type;
    typedef my_region_t::IteratorT iterator_type;
    typedef my_region_t::ValueT point_type;

    // Get the begin iterator
    static inline iterator_type begin_points(my_region_t const & t)
    {
      return t.Begin();
    }

    // Get the end iterator
    static inline iterator_type end_points(my_region_t const & t)
    {
      return t.End();
    }

    // Get the number of sides of the polygon
    static inline size_t size(my_region_t const & t)
    {
      return t.Size();
    }

    // Get the winding direction of the polygon
    static inline winding_direction winding(my_region_t const & /*t*/)
    {
      return unknown_winding;
    }
  };

  struct my_point_getter
  {
    my_point_t operator() (point_data<my_coord_t> const & t)
    {
      return my_point_t(t.x(), t.y());
    }
  };

  template <>
  struct polygon_mutable_traits<my_region_t>
  {
    // expects stl style iterators
    template <typename IterT>
    static inline my_region_t & set_points(my_region_t & t, IterT b, IterT e)
    {
      t.AssignEx(b, e, my_point_getter());
      return t;
    }
  };

  ////////////////////////////////////////////////////////////////////////////////
  // Polygon set concept.
  ////////////////////////////////////////////////////////////////////////////////
  typedef vector<my_region_t> my_region_set_t;

  template <>
  struct geometry_concept<my_region_set_t>
  {
    typedef polygon_set_concept type;
  };

  // next we map to the concept through traits
  template <>
  struct polygon_set_traits<my_region_set_t>
  {
    typedef my_coord_t coordinate_type;
    typedef my_region_set_t::const_iterator iterator_type;
    typedef my_region_set_t operator_arg_type;

    static inline iterator_type begin(my_region_set_t const & t)
    {
      return t.begin();
    }

    static inline iterator_type end(my_region_set_t const & t)
    {
      return t.end();
    }

    // don't worry about these, just return false from them
    static inline bool clean(my_region_set_t const & /*t*/) { return false; }
    static inline bool sorted(my_region_set_t const & /*t*/) { return false; }
  };

  template <>
  struct polygon_set_mutable_traits<my_region_set_t>
  {
    template <typename IterT>
    static inline void set(my_region_set_t & poly_set, IterT b, IterT e)
    {
      poly_set.clear();

      // this is kind of cheesy. I am copying the unknown input geometry
      // into my own polygon set and then calling get to populate the vector
      polygon_set_data<my_coord_t> ps;
      ps.insert(b, e);
      ps.get(poly_set);

      // if you had your own odd-ball polygon set you would probably have
      // to iterate through each polygon at this point and do something extra
    }
  };
}}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	NTC サーミスタ 温度計算 クラス @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cmath>

namespace chip {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  サーミスタ型
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	enum class thermistor {
		NT103,	///< THB:4126, TR25:10K
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  NTCTH テンプレートクラス
		@param[in]	ADNUM	A/D 変換値の量子化最大値
		@param[in]	THM		サーミスタの型
		@param[in]	REFR	分圧抵抗値
		@param[in]	thup	サーミスタが VCC 側の場合「true」、GND 側の場合「false」
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint16_t ADNUM, thermistor THM, uint16_t REFR, bool thup>
	class NTCTH {

		// サーミスタの型に応じたパラメーター
		// THB:  B 定数
		// TR25: ２５度における基準抵抗値
		static void get_para_(float& THB, float& TR25)
		{
			switch(THM) {
			case thermistor::NT103:
				THB  = 4126.0f;  ///< サーミスタＢ定数
				TR25 = 10e3;     ///< R25 サーミスタ２５℃基準抵抗値
				break;
			default:
				break;
			}
		}

		// サーミスターが VCC 側
		static float thermistor_upper_(uint16_t raw)
		{
			float thr = (static_cast<float>(REFR * ADNUM) / static_cast<float>(raw)) - static_cast<float>(REFR);
			return thr;
		}

		// サーミスターが GND 側
		static float thermistor_lower_(uint16_t raw)
		{
			float thr = static_cast<float>(REFR * raw) / static_cast<float>(ADNUM - raw);
			return thr;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	() オペレーター
			@param[in]	adn		A/D 変換値
		 */
		//-----------------------------------------------------------------//
		float operator () (uint16_t adn) const
		{
			float thr;
			if(thup) {
				thr = thermistor_upper_(adn);
			} else {
				thr = thermistor_lower_(adn);
			}
			float THB;
			float TR25;
			get_para_(THB, TR25);
			static const float T0   = 298.15f;   ///< 絶対温度
			float t = 1.0f / (std::log(thr / TR25) / THB + (1.0f / T0));
			return t - 273.15f;
		}
	};
}
<commit_msg>fix integer range<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	NTC サーミスタ 温度計算 クラス @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cmath>

namespace chip {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  サーミスタ型
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	enum class thermistor {
		NT103,	///< THB:4126, TR25:10K
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  NTCTH テンプレートクラス
		@param[in]	ADNUM	A/D 変換値の量子化最大値
		@param[in]	THM		サーミスタの型
		@param[in]	REFR	分圧抵抗値
		@param[in]	thup	サーミスタが VCC 側の場合「true」、GND 側の場合「false」
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t ADNUM, thermistor THM, uint32_t REFR, bool thup>
	class NTCTH {

		// サーミスタの型に応じたパラメーター
		// THB:  B 定数
		// TR25: ２５度における基準抵抗値
		static void get_para_(float& THB, float& TR25)
		{
			switch(THM) {
			case thermistor::NT103:
				THB  = 4126.0f;  ///< サーミスタＢ定数
				TR25 = 10e3;     ///< R25 サーミスタ２５℃基準抵抗値
				break;
			default:
				break;
			}
		}

		// サーミスターが VCC 側
		static float thermistor_upper_(uint32_t raw)
		{
			float thr = (static_cast<float>(REFR * ADNUM) / static_cast<float>(raw)) - static_cast<float>(REFR);
			return thr;
		}

		// サーミスターが GND 側
		static float thermistor_lower_(uint32_t raw)
		{
			float thr = static_cast<float>(REFR * raw) / static_cast<float>(ADNUM - raw);
			return thr;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	() オペレーター
			@param[in]	adn		A/D 変換値
		 */
		//-----------------------------------------------------------------//
		float operator () (uint16_t adn) const
		{
			float thr;
			if(thup) {
				thr = thermistor_upper_(adn);
			} else {
				thr = thermistor_lower_(adn);
			}
			float THB;
			float TR25;
			get_para_(THB, TR25);
			static const float T0   = 298.15f;   ///< 絶対温度
			float t = 1.0f / (std::log(thr / TR25) / THB + (1.0f / T0));
			return t - 273.15f;
		}
	};
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 MANGLING_H
#define MANGLING_H

#include <vector>
#include <string>

#include "ast/Value.hpp"

#include "Types.hpp"
#include "FunctionTable.hpp"

namespace eddic {

std::string mangle(Type type);

std::string mangle(const std::string& functionName, const std::vector<ParameterType>& types);
std::string mangle(const std::string& functionName, const std::vector<ast::Value>& values);

} //end of eddic

#endif
<commit_msg>Document mangling<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 MANGLING_H
#define MANGLING_H

#include <vector>
#include <string>

#include "ast/Value.hpp"

#include "Types.hpp"
#include "FunctionTable.hpp"

namespace eddic {

/*!
 * \brief Return the mangled representation of the given type.
 * \param type The type to mangle.
 * \return The mangled type.
 */
std::string mangle(Type type);

/*!
 * \brief Return the mangled representation of the given function. Used for function declarations.
 * \param functionName The name of the function
 * \param types The types of parameters.
 * \return The mangled function name.
 */
std::string mangle(const std::string& functionName, const std::vector<ParameterType>& types);

/*!
 * \brief Return the mangled representation of the given function. Used for function calls.
 * \param functionName The name of the function.
 * \param values The values used for the call.
 * \return The mangled function name.
 */
std::string mangle(const std::string& functionName, const std::vector<ast::Value>& values);

} //end of eddic

#endif
<|endoftext|>