<commit_before>/*************************************************************************
 *
 *  $RCSfile: ZConnectionWrapper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: oj $ $Date: 2002-08-23 09:57:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#include "ZConnectionWrapper.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

using namespace connectivity;
//------------------------------------------------------------------------------
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
// --------------------------------------------------------------------------------
OConnectionWeakWrapper::OConnectionWeakWrapper(Reference< XAggregation >& _xConnection)
    : OConnectionWeakWrapper_BASE(m_aMutex)
{
    setDelegation(_xConnection,m_refCount);
    OSL_ENSURE(m_xConnection.is(),"OConnectionWeakWrapper: Connection must be valid!");
}
//-----------------------------------------------------------------------------
OConnectionWeakWrapper::~OConnectionWeakWrapper()
{
}
// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OConnectionWeakWrapper, "com.sun.star.sdbc.drivers.OConnectionWeakWrapper", "com.sun.star.sdbc.Connection")

// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OConnectionWeakWrapper::createStatement(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->createStatement();
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OConnectionWeakWrapper::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->prepareStatement(sql);
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OConnectionWeakWrapper::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->prepareCall(sql);
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OConnectionWeakWrapper::nativeSQL( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->nativeSQL(sql);
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setAutoCommit( sal_Bool autoCommit ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setAutoCommit(autoCommit);
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::getAutoCommit(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getAutoCommit();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::commit(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->commit();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::rollback(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->rollback();
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::isClosed(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    return m_xConnection->isClosed();
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OConnectionWeakWrapper::getMetaData(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getMetaData();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setReadOnly( sal_Bool readOnly ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setReadOnly(readOnly);
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::isReadOnly(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->isReadOnly();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setCatalog( const ::rtl::OUString& catalog ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setCatalog(catalog);
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OConnectionWeakWrapper::getCatalog(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getCatalog();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setTransactionIsolation( sal_Int32 level ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setTransactionIsolation(level);
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL OConnectionWeakWrapper::getTransactionIsolation(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getTransactionIsolation();
}
// --------------------------------------------------------------------------------
Reference< ::com::sun::star::container::XNameAccess > SAL_CALL OConnectionWeakWrapper::getTypeMap(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getTypeMap();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setTypeMap( const Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setTypeMap(typeMap);
}
// --------------------------------------------------------------------------------
// XCloseable
void SAL_CALL OConnectionWeakWrapper::close(  ) throw(SQLException, RuntimeException)
{
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    }
    dispose();
}
//------------------------------------------------------------------------------
void OConnectionWeakWrapper::disposing()
{
    ::osl::MutexGuard aGuard(m_aMutex);

    m_xConnection = NULL;
    OConnectionWeakWrapper_BASE::disposing();
}
// -----------------------------------------------------------------------------
// com::sun::star::lang::XUnoTunnel
IMPLEMENT_FORWARD_XINTERFACE2(OConnectionWeakWrapper,OConnectionWeakWrapper_BASE,OConnectionWrapper)
IMPLEMENT_FORWARD_XTYPEPROVIDER2(OConnectionWeakWrapper,OConnectionWeakWrapper_BASE,OConnectionWrapper)

<commit_msg>INTEGRATION: CWS insight01 (1.5.94); FILE MERGED 2004/02/18 14:46:10 oj 1.5.94.1: #111075# fix rfcount problem<commit_after>/*************************************************************************
 *
 *  $RCSfile: ZConnectionWrapper.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 16:54:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#include "ZConnectionWrapper.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

using namespace connectivity;
//------------------------------------------------------------------------------
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
// --------------------------------------------------------------------------------
OConnectionWeakWrapper::OConnectionWeakWrapper(Reference< XAggregation >& _xConnection)
    : OConnectionWeakWrapper_BASE(m_aMutex)
{
    setDelegation(_xConnection,m_refCount);
    OSL_ENSURE(m_xConnection.is(),"OConnectionWeakWrapper: Connection must be valid!");
}
//-----------------------------------------------------------------------------
OConnectionWeakWrapper::~OConnectionWeakWrapper()
{
}
// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OConnectionWeakWrapper, "com.sun.star.sdbc.drivers.OConnectionWeakWrapper", "com.sun.star.sdbc.Connection")

// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OConnectionWeakWrapper::createStatement(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->createStatement();
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OConnectionWeakWrapper::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->prepareStatement(sql);
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OConnectionWeakWrapper::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->prepareCall(sql);
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OConnectionWeakWrapper::nativeSQL( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->nativeSQL(sql);
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setAutoCommit( sal_Bool autoCommit ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setAutoCommit(autoCommit);
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::getAutoCommit(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getAutoCommit();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::commit(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->commit();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::rollback(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->rollback();
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::isClosed(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    return m_xConnection->isClosed();
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OConnectionWeakWrapper::getMetaData(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getMetaData();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setReadOnly( sal_Bool readOnly ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setReadOnly(readOnly);
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::isReadOnly(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->isReadOnly();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setCatalog( const ::rtl::OUString& catalog ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setCatalog(catalog);
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OConnectionWeakWrapper::getCatalog(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getCatalog();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setTransactionIsolation( sal_Int32 level ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setTransactionIsolation(level);
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL OConnectionWeakWrapper::getTransactionIsolation(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getTransactionIsolation();
}
// --------------------------------------------------------------------------------
Reference< ::com::sun::star::container::XNameAccess > SAL_CALL OConnectionWeakWrapper::getTypeMap(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getTypeMap();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setTypeMap( const Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setTypeMap(typeMap);
}
// --------------------------------------------------------------------------------
// XCloseable
void SAL_CALL OConnectionWeakWrapper::close(  ) throw(SQLException, RuntimeException)
{
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    }
    dispose();
}
//------------------------------------------------------------------------------
void OConnectionWeakWrapper::disposing()
{
    ::osl::MutexGuard aGuard(m_aMutex);

    OConnectionWeakWrapper_BASE::disposing();
    OConnectionWrapper::disposing();
}
// -----------------------------------------------------------------------------
// com::sun::star::lang::XUnoTunnel
IMPLEMENT_FORWARD_XINTERFACE2(OConnectionWeakWrapper,OConnectionWeakWrapper_BASE,OConnectionWrapper)
IMPLEMENT_FORWARD_XTYPEPROVIDER2(OConnectionWeakWrapper,OConnectionWeakWrapper_BASE,OConnectionWrapper)

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: LResultSet.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2003-06-02 07:57:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_SDBCX_COMPAREBOOKMARK_HPP_
#include <com/sun/star/sdbcx/CompareBookmark.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_
#include <com/sun/star/sdbcx/XDeleteRows.hpp>
#endif
#ifndef _CONNECTIVITY_EVOAB_LRESULTSET_HXX_
#include "LResultSet.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif

using namespace ::comphelper;

using namespace connectivity::evoab;
using namespace connectivity::file;
using namespace ::cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
//  using namespace com::sun::star::container;
//  using namespace com::sun::star::util;
//------------------------------------------------------------------------------
OEvoabResultSet::OEvoabResultSet( OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator&   _aSQLIterator)
                : file::OResultSet(pStmt,_aSQLIterator)
                ,m_bBookmarkable(sal_True)
{
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISBOOKMARKABLE),         PROPERTY_ID_ISBOOKMARKABLE,       PropertyAttribute::READONLY,&m_bBookmarkable,                ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OEvoabResultSet::getImplementationName(  ) throw ( RuntimeException)
{
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.evoab.ResultSet");
}
// -------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OEvoabResultSet::getSupportedServiceNames(  ) throw( RuntimeException)
{
     Sequence< ::rtl::OUString > aSupported(2);
    aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.ResultSet");
    aSupported[1] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ResultSet");
    return aSupported;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabResultSet::supportsService( const ::rtl::OUString& _rServiceName ) throw( RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
Any SAL_CALL OEvoabResultSet::queryInterface( const Type & rType ) throw(RuntimeException)
{
    if(rType == ::getCppuType((const Reference<XDeleteRows>*)0) || rType == ::getCppuType((const Reference<XResultSetUpdate>*)0)
        || rType == ::getCppuType((const Reference<XRowUpdate>*)0))
        return Any();

    Any aRet = OResultSet::queryInterface(rType);
    return aRet.hasValue() ? aRet : OEvoabResultSet_BASE::queryInterface(rType);
}
// -------------------------------------------------------------------------
Sequence<  Type > SAL_CALL OEvoabResultSet::getTypes(  ) throw( RuntimeException)
{
    Sequence< Type > aTypes = OResultSet::getTypes();
    ::std::vector<Type> aOwnTypes;
    aOwnTypes.reserve(aTypes.getLength());
    const Type* pBegin = aTypes.getConstArray();
    const Type* pEnd = pBegin + aTypes.getLength();
    for(;pBegin != pEnd;++pBegin)
    {
        if(!(*pBegin == ::getCppuType((const Reference<XDeleteRows>*)0) ||
            *pBegin == ::getCppuType((const Reference<XResultSetUpdate>*)0) ||
            *pBegin == ::getCppuType((const Reference<XRowUpdate>*)0)))
        {
            aOwnTypes.push_back(*pBegin);
        }
    }
    Sequence< Type > aRet(aOwnTypes.begin(),aOwnTypes.size());
    return ::comphelper::concatSequences(aRet,OEvoabResultSet_BASE::getTypes());
}

// -------------------------------------------------------------------------
// XRowLocate
Any SAL_CALL OEvoabResultSet::getBookmark(  ) throw( SQLException,  RuntimeException)
{
     ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    return makeAny((sal_Int32)(*m_aRow)[0]);
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabResultSet::moveToBookmark( const  Any& bookmark ) throw( SQLException,  RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;

    return Move(IResultSetHelper::BOOKMARK,comphelper::getINT32(bookmark),sal_True);
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabResultSet::moveRelativeToBookmark( const  Any& bookmark, sal_Int32 rows ) throw( SQLException,  RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;

    Move(IResultSetHelper::BOOKMARK,comphelper::getINT32(bookmark),sal_False);

    return relative(rows);
}

// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OEvoabResultSet::compareBookmarks( const  Any& first, const  Any& second ) throw( SQLException,  RuntimeException)
{
    return (first == second) ? 0 : 2;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabResultSet::hasOrderedBookmarks(  ) throw( SQLException,  RuntimeException)
{
    return sal_True;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OEvoabResultSet::hashBookmark( const  Any& bookmark ) throw( SQLException,  RuntimeException)
{
    return comphelper::getINT32(bookmark);
}
// -------------------------------------------------------------------------
IPropertyArrayHelper* OEvoabResultSet::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
IPropertyArrayHelper & OEvoabResultSet::getInfoHelper()
{
    return *OEvoabResultSet_BASE3::getArrayHelper();
}
// -----------------------------------------------------------------------------
void SAL_CALL OEvoabResultSet::acquire() throw()
{
    OEvoabResultSet_BASE2::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OEvoabResultSet::release() throw()
{
    OEvoabResultSet_BASE2::release();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OEvoabResultSet::getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS oj4 (1.2.10); FILE MERGED 2003/07/07 06:24:39 oj 1.2.10.1: linux compile errors<commit_after>/*************************************************************************
 *
 *  $RCSfile: LResultSet.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2003-09-04 08:24:16 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_SDBCX_COMPAREBOOKMARK_HPP_
#include <com/sun/star/sdbcx/CompareBookmark.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_
#include <com/sun/star/sdbcx/XDeleteRows.hpp>
#endif
#ifndef _CONNECTIVITY_EVOAB_LRESULTSET_HXX_
#include "LResultSet.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif

using namespace ::comphelper;

using namespace connectivity::evoab;
using namespace connectivity::file;
using namespace ::cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
//  using namespace com::sun::star::container;
//  using namespace com::sun::star::util;
//------------------------------------------------------------------------------
OEvoabResultSet::OEvoabResultSet( OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator&   _aSQLIterator)
                : file::OResultSet(pStmt,_aSQLIterator)
                ,m_bBookmarkable(sal_True)
{
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISBOOKMARKABLE),         PROPERTY_ID_ISBOOKMARKABLE,       PropertyAttribute::READONLY,&m_bBookmarkable,                ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OEvoabResultSet::getImplementationName(  ) throw ( RuntimeException)
{
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.evoab.ResultSet");
}
// -------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OEvoabResultSet::getSupportedServiceNames(  ) throw( RuntimeException)
{
     Sequence< ::rtl::OUString > aSupported(2);
    aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.ResultSet");
    aSupported[1] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ResultSet");
    return aSupported;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabResultSet::supportsService( const ::rtl::OUString& _rServiceName ) throw( RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
Any SAL_CALL OEvoabResultSet::queryInterface( const Type & rType ) throw(RuntimeException)
{
    if(rType == ::getCppuType((const Reference<XDeleteRows>*)0) || rType == ::getCppuType((const Reference<XResultSetUpdate>*)0)
        || rType == ::getCppuType((const Reference<XRowUpdate>*)0))
        return Any();

    Any aRet = OResultSet::queryInterface(rType);
    return aRet.hasValue() ? aRet : OEvoabResultSet_BASE::queryInterface(rType);
}
// -------------------------------------------------------------------------
Sequence<  Type > SAL_CALL OEvoabResultSet::getTypes(  ) throw( RuntimeException)
{
    Sequence< Type > aTypes = OResultSet::getTypes();
    ::std::vector<Type> aOwnTypes;
    aOwnTypes.reserve(aTypes.getLength());
    const Type* pBegin = aTypes.getConstArray();
    const Type* pEnd = pBegin + aTypes.getLength();
    for(;pBegin != pEnd;++pBegin)
    {
        if(!(*pBegin == ::getCppuType((const Reference<XDeleteRows>*)0) ||
            *pBegin == ::getCppuType((const Reference<XResultSetUpdate>*)0) ||
            *pBegin == ::getCppuType((const Reference<XRowUpdate>*)0)))
        {
            aOwnTypes.push_back(*pBegin);
        }
    }
    Sequence< Type > aRet(aOwnTypes.begin(),aOwnTypes.size());
    return ::comphelper::concatSequences(aRet,OEvoabResultSet_BASE::getTypes());
}

// -------------------------------------------------------------------------
// XRowLocate
Any SAL_CALL OEvoabResultSet::getBookmark(  ) throw( SQLException,  RuntimeException)
{
     ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    return makeAny((sal_Int32)(*m_aRow)[0]->getValue());
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabResultSet::moveToBookmark( const  Any& bookmark ) throw( SQLException,  RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;

    return Move(IResultSetHelper::BOOKMARK,comphelper::getINT32(bookmark),sal_True);
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabResultSet::moveRelativeToBookmark( const  Any& bookmark, sal_Int32 rows ) throw( SQLException,  RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;

    Move(IResultSetHelper::BOOKMARK,comphelper::getINT32(bookmark),sal_False);

    return relative(rows);
}

// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OEvoabResultSet::compareBookmarks( const  Any& first, const  Any& second ) throw( SQLException,  RuntimeException)
{
    return (first == second) ? 0 : 2;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OEvoabResultSet::hasOrderedBookmarks(  ) throw( SQLException,  RuntimeException)
{
    return sal_True;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OEvoabResultSet::hashBookmark( const  Any& bookmark ) throw( SQLException,  RuntimeException)
{
    return comphelper::getINT32(bookmark);
}
// -------------------------------------------------------------------------
IPropertyArrayHelper* OEvoabResultSet::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
IPropertyArrayHelper & OEvoabResultSet::getInfoHelper()
{
    return *OEvoabResultSet_BASE3::getArrayHelper();
}
// -----------------------------------------------------------------------------
void SAL_CALL OEvoabResultSet::acquire() throw()
{
    OEvoabResultSet_BASE2::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OEvoabResultSet::release() throw()
{
    OEvoabResultSet_BASE2::release();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OEvoabResultSet::getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// own
#include "Importer.h"
// ospcommon
#include "common/FileName.h"
#include "common/sysinfo.h"
// ospray api
#include "ospray/ospray.h"

// std::
#include <iostream>
#include <stdio.h>
#include <string.h>
#ifdef __LINUX__
# include <sched.h>
#endif
#include <stdint.h>
#include <atomic>
#include <mutex>

namespace ospray {
  namespace importer {
    struct RMLoaderThreads {
    // TODO: RMLoaderThreads should use OSPRay's thread abstractions
#ifdef _WIN32
      RMLoaderThreads(Volume *, const std::string &, int)
      {
        exitOnCondition(true, "RM importer not yet supported on Windows");
      }
#else
      Volume *volume;

      std::mutex mutex;
      std::atomic<int> nextBlockID;
      std::atomic<int> nextPinID;
      int numThreads;
      int timeStep;
      pthread_t *thread;
      std::string inFilesDir;
      bool useGZip;

      struct Block {
        uint8_t voxel[256*256*128];
      };

      RMLoaderThreads(Volume *volume, const std::string &fileName, int numThreads=10)
        : volume(volume), nextBlockID(0), thread(NULL), nextPinID(0),
        numThreads(numThreads)
      {
        inFilesDir = fileName.substr(0, fileName.rfind('.'));
        std::cout << "Reading LLNL Richtmyer-Meshkov bob from " << inFilesDir
          << " with " << numThreads << " threads" << std::endl;

        useGZip = (getenv("OSPRAY_RM_NO_GZIP") == NULL);

        const char *slash = rindex(fileName.c_str(),'/');
        std::string base
          = slash != NULL
          ? std::string(slash+1)
          : fileName;

        int rc = sscanf(base.c_str(),"bob%03d.bob",&timeStep);
        if (rc != 1)
          throw std::runtime_error("could not extract time step from bob file name "+base);

        volume->voxelRange.x = +std::numeric_limits<float>::infinity();
        volume->voxelRange.y = -std::numeric_limits<float>::infinity();

        thread = new pthread_t[numThreads];
        for (int i=0;i<numThreads;i++)
          pthread_create(thread+i,NULL,(void*(*)(void*))threadFunc,this);

        void *result = NULL;
        for (int i=0;i<numThreads;i++){
          pthread_join(thread[i],&result);
        }
      };

      void loadBlock(Block &block, const std::string &fileNameBase, size_t blockID){
        char fileName[10000];
        FILE *file;
        if (useGZip) {
          sprintf(fileName,"%s/d_%04d_%04li.gz",
              fileNameBase.c_str(),timeStep,blockID);
          const std::string cmd = "gunzip -c "+std::string(fileName);
          file = popen(cmd.c_str(),"r");
          if (!file)
            throw std::runtime_error("could not open file in popen command '"+cmd+"'");
        } else {
          sprintf(fileName,"%s/d_%04d_%04li",
              fileNameBase.c_str(),timeStep,blockID);
          file = fopen(fileName,"rb");
          if (!file)
            throw std::runtime_error("could not open '"+std::string(fileName)+"'");
        }

        assert(file);
        int rc = fread(block.voxel,sizeof(uint8_t),256*256*128,file);
        if (rc != 256*256*128) {
          PRINT(rc);
          PRINT(256*256*128);
          throw std::runtime_error("could not read enough data from "+std::string(fileName));
        }

        if (useGZip)
          pclose(file);
        else
          fclose(file);
      }

      void run()
      {
        int threadID = nextPinID.fetch_add(1);

        Block *block = new Block;
        while(1) {
          int blockID = nextBlockID.fetch_add(1);
          if (blockID >= 8*8*15) break;

          // int b = K*64+J*8+I;
          int I = blockID % 8;
          int J = (blockID / 8) % 8;
          int K = (blockID / 64);

          int cpu = -1;
#ifdef __LINUX__
          cpu = sched_getcpu();
#endif
          printf("[b%i:%i,%i,%i,(%i)]",blockID,I,J,K,cpu);
          loadBlock(*block,inFilesDir,blockID);

          ospcommon::vec2f blockRange(block->voxel[0]);
          extendVoxelRange(blockRange,&block->voxel[0],256*256*128);
          ospcommon::vec3i region_lo(I*256,J*256,K*128);
          ospcommon::vec3i region_sz(256,256,128);
          {
            std::lock_guard<std::mutex> lock(mutex);
            ospSetRegion(volume->handle,block->voxel,(osp::vec3i&)region_lo,(osp::vec3i&)region_sz);

            volume->voxelRange.x = std::min(volume->voxelRange.x,blockRange.x);
            volume->voxelRange.y = std::max(volume->voxelRange.y,blockRange.y);
          }
        }
        delete block;
      }

      static void *threadFunc(void *arg)
      { ((RMLoaderThreads *)arg)->run(); return NULL; }
      ~RMLoaderThreads() { delete[] thread; };
#endif
    };

    // Just import the RM file into some larger scene, just loads the volume
    void importVolumeRM(const FileName &fileName, Volume *volume) {
      const char *scaleFactorEnv = getenv("OSPRAY_VOLUME_SCALE_FACTOR");
      if (scaleFactorEnv){
        std::cout << "#importRM: found OSPRAY_VOLUME_SCALE_FACTOR env-var\n";
        vec3f scaleFactor;
        if (sscanf(scaleFactorEnv, "%fx%fx%f", &scaleFactor.x, &scaleFactor.y, &scaleFactor.z) != 3){
          throw std::runtime_error("Could not parse OSPRAY_RM_SCALE_FACTOR env-var. Must be of format"
              "<X>x<Y>x<Z> (e.g '1.5x2x0.5')");
        }
        std::cout << "#importRM: got OSPRAY_VOLUME_SCALE_FACTOR env-var = {"
          << scaleFactor.x << ", " << scaleFactor.y << ", " << scaleFactor.z
          << "}\n";
        volume->scaleFactor = scaleFactor;
        ospSetVec3f(volume->handle, "scaleFactor", (osp::vec3f&)volume->scaleFactor);
      }

      // Update the provided dimensions of the volume for the subvolume specified.
      ospcommon::vec3i dims(2048,2048,1920);
      volume->dimensions = dims;
      if (volume->scaleFactor != vec3f(1.f)) {
        dims = vec3i(vec3f(dims) * volume->scaleFactor);
      }
      ospSetVec3i(volume->handle, "dimensions", (osp::vec3i&)dims);
      ospSetString(volume->handle,"voxelType", "uchar");

      const int numThreads = ospcommon::getNumberOfLogicalThreads();

      double t0 = ospcommon::getSysTime();

      RMLoaderThreads(volume,fileName,numThreads);
      double t1 = ospcommon::getSysTime();
      std::cout << "done loading " << fileName
        << ", needed " << (t1-t0) << " seconds" << std::endl;

      ospSet2f(volume->handle,"voxelRange",volume->voxelRange.x,volume->voxelRange.y);
      volume->dimensions = dims;
      volume->bounds = ospcommon::empty;
      volume->bounds.extend(volume->gridOrigin);
      volume->bounds.extend(volume->gridOrigin+ vec3f(volume->dimensions) * volume->gridSpacing);
    }

    // Treat a single RM file as a "scene"
    void importRM(const FileName &fileName, Group *group) {
      const char *dpFromEnv = getenv("OSPRAY_DATA_PARALLEL");
      // Same as OSPObjectFile::importVolume for creating the initial OSPVolume and importRAW
      Volume *volume = new Volume;
      if (dpFromEnv) {
        // Create the OSPRay object.
        std::cout << "#osp.loader: found OSPRAY_DATA_PARALLEL env-var, "
          << "#osp.loader: trying to use data _parallel_ mode..." << std::endl;
        osp::vec3i blockDims;
        int rc = sscanf(dpFromEnv,"%dx%dx%d",&blockDims.x,&blockDims.y,&blockDims.z);
        if (rc != 3){
          throw std::runtime_error("could not parse OSPRAY_DATA_PARALLEL env-var."
              "Must be of format <X>x<Y>x<>Z (e.g., '4x4x4'");
        }
        volume->handle = ospNewVolume("data_distributed_volume");
        if (volume->handle == NULL){
          throw std::runtime_error("#loaders.ospObjectFile: could not create volume ...");
        }
        ospSetVec3i(volume->handle,"num_dp_blocks",blockDims);
      } else {
        // Create the OSPRay object.
        std::cout << "#osp.loader: no OSPRAY_DATA_PARALLEL dimensions set, "
          << "#osp.loader: assuming data replicated mode is desired" << std::endl;
        std::cout << "#osp.loader: to use data parallel mode, set OSPRAY_DATA_PARALLEL env-var to <X>x<Y>x<Z>" << std::endl;
        std::cout << "#osp.loader: where X, Y, and Z are the desired _number_ of data parallel blocks" << std::endl;
        volume->handle = ospNewVolume("block_bricked_volume");
      }
      if (volume->handle == NULL){
        throw std::runtime_error("#loaders.ospObjectFile: could not create volume ...");
      }

      importVolumeRM(fileName, volume);

      // Add the volume to the group
      group->volume.push_back(volume);
    }
  }
}

<commit_msg>Switch to std::thread for loading the RM volumes<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// own
#include "Importer.h"
// ospcommon
#include "common/FileName.h"
#include "common/sysinfo.h"
// ospray api
#include "ospray/ospray.h"

// std::
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>

namespace ospray {
  namespace importer {
    struct RMLoaderThreads {
      Volume *volume;

      std::mutex mutex;
      std::atomic<int> nextBlockID;
      std::atomic<int> nextPinID;
      int numThreads;
      int timeStep;
      std::vector<std::thread> threads;
      std::string inFilesDir;
      bool useGZip;

      struct Block {
        uint8_t voxel[256*256*128];
      };

      RMLoaderThreads(Volume *volume, const std::string &fileName, int numThreads=10)
        : volume(volume), nextBlockID(0), nextPinID(0), numThreads(numThreads)
      {
        inFilesDir = fileName.substr(0, fileName.rfind('.'));
        std::cout << "Reading LLNL Richtmyer-Meshkov bob from " << inFilesDir
          << " with " << numThreads << " threads" << std::endl;

        useGZip = (getenv("OSPRAY_RM_NO_GZIP") == NULL);

        const size_t slash = fileName.rfind('/');
        std::string base = slash != std::string::npos ? fileName.substr(slash + 1) : fileName;

        int rc = sscanf(base.c_str(),"bob%03d.bob",&timeStep);
        if (rc != 1)
          throw std::runtime_error("could not extract time step from bob file name "+base);

        volume->voxelRange.x = +std::numeric_limits<float>::infinity();
        volume->voxelRange.y = -std::numeric_limits<float>::infinity();

        threads.reserve(numThreads);
        for (int i = 0; i < numThreads; ++i) {
          threads.push_back(std::thread([&](){ run(); }));
        }
        for (size_t i = 0; i < threads.size(); ++i) {
          threads[i].join();
        }
      };

      void loadBlock(Block &block, const std::string &fileNameBase, size_t blockID){
        char fileName[10000];
        FILE *file;
        if (useGZip) {
#ifndef _WIN32
          sprintf(fileName,"%s/d_%04d_%04li.gz",
              fileNameBase.c_str(),timeStep,blockID);
          const std::string cmd = "gunzip -c "+std::string(fileName);
          file = popen(cmd.c_str(),"r");
          if (!file)
            throw std::runtime_error("could not open file in popen command '"+cmd+"'");
#else
          throw std::runtime_error("gzipped RM bob's aren't supported on Windows!");
#endif
        } else {
          sprintf(fileName,"%s/d_%04d_%04li",
              fileNameBase.c_str(),timeStep,blockID);
          file = fopen(fileName,"rb");
          if (!file)
            throw std::runtime_error("could not open '"+std::string(fileName)+"'");
        }

        assert(file);
        int rc = fread(block.voxel,sizeof(uint8_t),256*256*128,file);
        if (rc != 256*256*128) {
          PRINT(rc);
          PRINT(256*256*128);
          throw std::runtime_error("could not read enough data from "+std::string(fileName));
        }

        if (useGZip) {
#ifndef _WIN32
          pclose(file);
#else
          throw std::runtime_error("gzipped RM bob's aren't supported on Windows!");
#endif
        } else {
          fclose(file);
        }
      }

      void run()
      {
        int threadID = nextPinID.fetch_add(1);

        Block *block = new Block;
        while(1) {
          int blockID = nextBlockID.fetch_add(1);
          if (blockID >= 8*8*15) break;

          // int b = K*64+J*8+I;
          int I = blockID % 8;
          int J = (blockID / 8) % 8;
          int K = (blockID / 64);

          printf("[b%i:%i,%i,%i,(%i)]",blockID,I,J,K,threadID);
          loadBlock(*block,inFilesDir,blockID);

          ospcommon::vec2f blockRange(block->voxel[0]);
          extendVoxelRange(blockRange,&block->voxel[0],256*256*128);
          ospcommon::vec3i region_lo(I*256,J*256,K*128);
          ospcommon::vec3i region_sz(256,256,128);
          {
            std::lock_guard<std::mutex> lock(mutex);
            ospSetRegion(volume->handle,block->voxel,(osp::vec3i&)region_lo,(osp::vec3i&)region_sz);

            volume->voxelRange.x = std::min(volume->voxelRange.x,blockRange.x);
            volume->voxelRange.y = std::max(volume->voxelRange.y,blockRange.y);
          }
        }
        delete block;
      }
    };

    // Just import the RM file into some larger scene, just loads the volume
    void importVolumeRM(const FileName &fileName, Volume *volume) {
      const char *scaleFactorEnv = getenv("OSPRAY_VOLUME_SCALE_FACTOR");
      if (scaleFactorEnv){
        std::cout << "#importRM: found OSPRAY_VOLUME_SCALE_FACTOR env-var\n";
        vec3f scaleFactor;
        if (sscanf(scaleFactorEnv, "%fx%fx%f", &scaleFactor.x, &scaleFactor.y, &scaleFactor.z) != 3){
          throw std::runtime_error("Could not parse OSPRAY_RM_SCALE_FACTOR env-var. Must be of format"
              "<X>x<Y>x<Z> (e.g '1.5x2x0.5')");
        }
        std::cout << "#importRM: got OSPRAY_VOLUME_SCALE_FACTOR env-var = {"
          << scaleFactor.x << ", " << scaleFactor.y << ", " << scaleFactor.z
          << "}\n";
        volume->scaleFactor = scaleFactor;
        ospSetVec3f(volume->handle, "scaleFactor", (osp::vec3f&)volume->scaleFactor);
      }

      // Update the provided dimensions of the volume for the subvolume specified.
      ospcommon::vec3i dims(2048,2048,1920);
      volume->dimensions = dims;
      if (volume->scaleFactor != vec3f(1.f)) {
        dims = vec3i(vec3f(dims) * volume->scaleFactor);
      }
      ospSetVec3i(volume->handle, "dimensions", (osp::vec3i&)dims);
      ospSetString(volume->handle,"voxelType", "uchar");

      const int numThreads = ospcommon::getNumberOfLogicalThreads();

      double t0 = ospcommon::getSysTime();

      RMLoaderThreads(volume,fileName,numThreads);
      double t1 = ospcommon::getSysTime();
      std::cout << "done loading " << fileName
        << ", needed " << (t1-t0) << " seconds" << std::endl;

      ospSet2f(volume->handle,"voxelRange",volume->voxelRange.x,volume->voxelRange.y);
      volume->dimensions = dims;
      volume->bounds = ospcommon::empty;
      volume->bounds.extend(volume->gridOrigin);
      volume->bounds.extend(volume->gridOrigin+ vec3f(volume->dimensions) * volume->gridSpacing);
    }

    // Treat a single RM file as a "scene"
    void importRM(const FileName &fileName, Group *group) {
      const char *dpFromEnv = getenv("OSPRAY_DATA_PARALLEL");
      // Same as OSPObjectFile::importVolume for creating the initial OSPVolume and importRAW
      Volume *volume = new Volume;
      if (dpFromEnv) {
        // Create the OSPRay object.
        std::cout << "#osp.loader: found OSPRAY_DATA_PARALLEL env-var, "
          << "#osp.loader: trying to use data _parallel_ mode..." << std::endl;
        osp::vec3i blockDims;
        int rc = sscanf(dpFromEnv,"%dx%dx%d",&blockDims.x,&blockDims.y,&blockDims.z);
        if (rc != 3){
          throw std::runtime_error("could not parse OSPRAY_DATA_PARALLEL env-var."
              "Must be of format <X>x<Y>x<>Z (e.g., '4x4x4'");
        }
        volume->handle = ospNewVolume("data_distributed_volume");
        if (volume->handle == NULL){
          throw std::runtime_error("#loaders.ospObjectFile: could not create volume ...");
        }
        ospSetVec3i(volume->handle,"num_dp_blocks",blockDims);
      } else {
        // Create the OSPRay object.
        std::cout << "#osp.loader: no OSPRAY_DATA_PARALLEL dimensions set, "
          << "#osp.loader: assuming data replicated mode is desired" << std::endl;
        std::cout << "#osp.loader: to use data parallel mode, set OSPRAY_DATA_PARALLEL env-var to <X>x<Y>x<Z>" << std::endl;
        std::cout << "#osp.loader: where X, Y, and Z are the desired _number_ of data parallel blocks" << std::endl;
        volume->handle = ospNewVolume("block_bricked_volume");
      }
      if (volume->handle == NULL){
        throw std::runtime_error("#loaders.ospObjectFile: could not create volume ...");
      }

      importVolumeRM(fileName, volume);

      // Add the volume to the group
      group->volume.push_back(volume);
    }
  }
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/android/content_startup_flags.h"

#include "base/string_number_conversions.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "cc/switches.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "ui/base/ui_base_switches.h"

namespace content {

void SetContentCommandLineFlags(int max_render_process_count) {
  // May be called multiple times, to cover all possible program entry points.
  static bool already_initialized = false;
  if (already_initialized)
    return;
  already_initialized = true;

  CommandLine* parsed_command_line = CommandLine::ForCurrentProcess();

  parsed_command_line->AppendSwitch(cc::switches::kEnableImplSidePainting);

  if (parsed_command_line->HasSwitch(switches::kRendererProcessLimit)) {
    std::string limit = parsed_command_line->GetSwitchValueASCII(
        switches::kRendererProcessLimit);
    int value;
    if (base::StringToInt(limit, &value))
      max_render_process_count = value;
  }

  if (max_render_process_count <= 0) {
    // Need to ensure the command line flag is consistent as a lot of chrome
    // internal code checks this directly, but it wouldn't normally get set when
    // we are implementing an embedded WebView.
    parsed_command_line->AppendSwitch(switches::kSingleProcess);
  } else {
    max_render_process_count =
        std::min(max_render_process_count,
                 static_cast<int>(content::kMaxRendererProcessCount));
    content::RenderProcessHost::SetMaxRendererProcessCount(
        max_render_process_count);
  }

  parsed_command_line->AppendSwitch(switches::kForceCompositingMode);
  parsed_command_line->AppendSwitch(switches::kAllowWebUICompositing);
  parsed_command_line->AppendSwitch(switches::kEnableThreadedCompositing);
  parsed_command_line->AppendSwitch(
      switches::kEnableCompositingForFixedPosition);
  parsed_command_line->AppendSwitch(switches::kEnableAcceleratedOverflowScroll);
  parsed_command_line->AppendSwitch(
      switches::kEnableAcceleratedScrollableFrames);
  parsed_command_line->AppendSwitch(
      switches::kEnableCompositedScrollingForFrames);

  parsed_command_line->AppendSwitch(switches::kEnableGestureTapHighlight);
  parsed_command_line->AppendSwitch(switches::kEnablePinch);

  // Run the GPU service as a thread in the browser instead of as a
  // standalone process.
  parsed_command_line->AppendSwitch(switches::kInProcessGPU);

  // Always use fixed layout and viewport tag.
  parsed_command_line->AppendSwitch(switches::kEnableFixedLayout);
  parsed_command_line->AppendSwitch(switches::kEnableViewport);

  // FIXME(aelias): Commented out due to flaky tests.
//  parsed_command_line->AppendSwitch(
//      cc::switches::kEnableCompositorFrameMessage);
}

}  // namespace content
<commit_msg>Enable compositor frame message.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/android/content_startup_flags.h"

#include "base/string_number_conversions.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "cc/switches.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "ui/base/ui_base_switches.h"

namespace content {

void SetContentCommandLineFlags(int max_render_process_count) {
  // May be called multiple times, to cover all possible program entry points.
  static bool already_initialized = false;
  if (already_initialized)
    return;
  already_initialized = true;

  CommandLine* parsed_command_line = CommandLine::ForCurrentProcess();

  parsed_command_line->AppendSwitch(cc::switches::kEnableImplSidePainting);

  if (parsed_command_line->HasSwitch(switches::kRendererProcessLimit)) {
    std::string limit = parsed_command_line->GetSwitchValueASCII(
        switches::kRendererProcessLimit);
    int value;
    if (base::StringToInt(limit, &value))
      max_render_process_count = value;
  }

  if (max_render_process_count <= 0) {
    // Need to ensure the command line flag is consistent as a lot of chrome
    // internal code checks this directly, but it wouldn't normally get set when
    // we are implementing an embedded WebView.
    parsed_command_line->AppendSwitch(switches::kSingleProcess);
  } else {
    max_render_process_count =
        std::min(max_render_process_count,
                 static_cast<int>(content::kMaxRendererProcessCount));
    content::RenderProcessHost::SetMaxRendererProcessCount(
        max_render_process_count);
  }

  parsed_command_line->AppendSwitch(switches::kForceCompositingMode);
  parsed_command_line->AppendSwitch(switches::kAllowWebUICompositing);
  parsed_command_line->AppendSwitch(switches::kEnableThreadedCompositing);
  parsed_command_line->AppendSwitch(
      switches::kEnableCompositingForFixedPosition);
  parsed_command_line->AppendSwitch(switches::kEnableAcceleratedOverflowScroll);
  parsed_command_line->AppendSwitch(
      switches::kEnableAcceleratedScrollableFrames);
  parsed_command_line->AppendSwitch(
      switches::kEnableCompositedScrollingForFrames);

  parsed_command_line->AppendSwitch(switches::kEnableGestureTapHighlight);
  parsed_command_line->AppendSwitch(switches::kEnablePinch);

  // Run the GPU service as a thread in the browser instead of as a
  // standalone process.
  parsed_command_line->AppendSwitch(switches::kInProcessGPU);

  // Always use fixed layout and viewport tag.
  parsed_command_line->AppendSwitch(switches::kEnableFixedLayout);
  parsed_command_line->AppendSwitch(switches::kEnableViewport);

  parsed_command_line->AppendSwitch(
      cc::switches::kEnableCompositorFrameMessage);
}

}  // namespace content
<|endoftext|>


<commit_before>#include "libnanocv/minimize.h"
#include "libnanocv/tabulator.h"
#include "libnanocv/math/abs.hpp"
#include "libnanocv/util/timer.h"
#include "libnanocv/math/math.hpp"
#include "libnanocv/util/logger.h"
#include "libnanocv/util/stats.hpp"
#include "libnanocv/math/clamp.hpp"
#include "libnanocv/util/random.hpp"
#include "libnanocv/math/epsilon.hpp"
#include "libnanocv/thread/parallel.hpp"

#include "libnanocv/functions/function_beale.h"
#include "libnanocv/functions/function_booth.h"
#include "libnanocv/functions/function_sphere.h"
#include "libnanocv/functions/function_matyas.h"
#include "libnanocv/functions/function_ellipsoid.h"
#include "libnanocv/functions/function_mccormick.h"
#include "libnanocv/functions/function_himmelblau.h"
#include "libnanocv/functions/function_rosenbrock.h"
#include "libnanocv/functions/function_3hump_camel.h"
#include "libnanocv/functions/function_goldstein_price.h"
#include "libnanocv/functions/function_rotated_ellipsoid.h"

#include <map>
#include <tuple>

using namespace ncv;

struct optimizer_stat_t
{
        stats_t<scalar_t>       m_time;
        stats_t<scalar_t>       m_fails_3;
        stats_t<scalar_t>       m_fails_6;
        stats_t<scalar_t>       m_fails_9;
        stats_t<scalar_t>       m_iterations;
        stats_t<scalar_t>       m_func_evals;
        stats_t<scalar_t>       m_grad_evals;
};

std::map<string_t, optimizer_stat_t> optimizer_stats;

//static void sort_desc(tabulator_t& table, size_t column)
//{
//        table.sort(column, [] (const string_t& value1, const string_t& value2)
//        {
//                return text::from_string<scalar_t>(value1) > text::from_string<scalar_t>(value2);
//        });
//}

static void sort_asc(tabulator_t& table, size_t column)
{
        table.sort(column, [] (const string_t& value1, const string_t& value2)
        {
                return text::from_string<scalar_t>(value1) < text::from_string<scalar_t>(value2);
        });
}

static void check_problem(
        const string_t& problem_name,
        const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
        const std::vector<std::pair<vector_t, scalar_t>>&)
{
        const size_t iterations = 4 * 1024;
        const scalar_t epsilon = math::epsilon0<scalar_t>();

        const size_t trials = 1024;

        const size_t dims = fn_size();

        // generate fixed random trials
        vectors_t x0s;
        for (size_t t = 0; t < trials; t ++)
        {
                random_t<scalar_t> rgen(-1.0, +1.0);

                vector_t x0(dims);
                rgen(x0.data(), x0.data() + x0.size());

                x0s.push_back(x0);
        }

        // optimizers to try
        const auto optimizers =
        {
//                batch_optimizer::GD,
//                batch_optimizer::CGD_CD,
//                batch_optimizer::CGD_DY,
//                batch_optimizer::CGD_FR,
//                batch_optimizer::CGD_HS,
//                batch_optimizer::CGD_LS,
//                batch_optimizer::CGD_PRP,
//                batch_optimizer::CGD_N,
//                batch_optimizer::CGD_DYCD,
//                batch_optimizer::CGD_DYHS,
                batch_optimizer::LBFGS
        };

        const auto ls_initializers =
        {
                optimize::ls_initializer::unit,
//                optimize::ls_initializer::quadratic,
//                optimize::ls_initializer::consistent
        };

        const auto ls_strategies =
        {
                optimize::ls_strategy::backtrack_armijo,
                optimize::ls_strategy::backtrack_wolfe,
                optimize::ls_strategy::backtrack_strong_wolfe,
                optimize::ls_strategy::interpolation_bisection,
                optimize::ls_strategy::interpolation_cubic,
                optimize::ls_strategy::cg_descent
        };

        tabulator_t table(text::resize(problem_name, 32));
        table.header() << "speed"
                       << "time [us]"
                       << "|grad|"
                       << "#>e-3"
                       << "#>e-6"
                       << "#>e-9"
                       << "#iters"
                       << "#funcs"
                       << "#grads";

        thread_pool_t pool;
        thread_pool_t::mutex_t mutex;

        for (batch_optimizer optimizer : optimizers)
                for (optimize::ls_initializer ls_initializer : ls_initializers)
                        for (optimize::ls_strategy ls_strategy : ls_strategies)
        {
                stats_t<scalar_t> grads;
                stats_t<scalar_t> times;
                stats_t<scalar_t> fails_3;
                stats_t<scalar_t> fails_6;
                stats_t<scalar_t> fails_9;
                stats_t<scalar_t> opti_iters;
                stats_t<scalar_t> func_evals;
                stats_t<scalar_t> grad_evals;

                thread_loopi(trials, pool, [&] (size_t t)
                {
                        const vector_t& x0 = x0s[t];

                        // optimize
                        const ncv::timer_t timer;

                        const opt_state_t state = ncv::minimize(
                                fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
                                x0, optimizer, iterations, epsilon, ls_initializer, ls_strategy);

                        const scalar_t gnorm = state.g.lpNorm<Eigen::Infinity>();
                        const scalar_t convc = state.convergence_criteria();

                        // update stats
                        const thread_pool_t::lock_t lock(mutex);

                        grads(gnorm);
                        times(timer.microseconds());
                        opti_iters(state.n_iterations());
                        func_evals(state.n_fval_calls());
                        grad_evals(state.n_grad_calls());

                        fails_3(convc > 1e-3 ? 1.0 : 0.0);
                        fails_6(convc > 1e-6 ? 1.0 : 0.0);
                        fails_9(convc > 1e-9 ? 1.0 : 0.0);
                });

                // optimization speed: convergence / #iterations
                const scalar_t speed =
                        std::max(0.0, -std::log(std::max(epsilon, grads.avg()))) /
                        (1 + func_evals.avg() + 2 * grad_evals.avg());

                // update per-problem table
                const string_t name =
                        text::to_string(optimizer) + "[" +
                        text::to_string(ls_initializer) + "][" +
                        text::to_string(ls_strategy) + "]";

                table.append(name)
                        << speed
                        << times.avg()
                        << grads.avg()
                        << static_cast<int>(fails_3.sum())
                        << static_cast<int>(fails_6.sum())
                        << static_cast<int>(fails_9.sum())
                        << opti_iters.avg()
                        << func_evals.avg()
                        << grad_evals.avg();

                // update global statistics
                optimizer_stat_t& stat = optimizer_stats[name];
                stat.m_time(times.avg());
                stat.m_fails_3(fails_3.sum());
                stat.m_fails_6(fails_6.sum());
                stat.m_fails_9(fails_9.sum());
                stat.m_iterations(opti_iters.avg());
                stat.m_func_evals(func_evals.avg());
                stat.m_grad_evals(grad_evals.avg());
        }

        // print stats
        sort_asc(table, 5);
        sort_asc(table, 4);
        sort_asc(table, 3);
        table.print(std::cout);
}

static void check_problems(const std::vector<ncv::function_t>& funcs)
{
        for (const ncv::function_t& func : funcs)
        {
                check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);
        }
}

int main(int argc, char *argv[])
{
        using namespace ncv;

//        // Sphere function
//        check_problems(ncv::make_sphere_funcs(16));

//        // Ellipsoid function
//        check_problems(ncv::make_ellipsoid_funcs(16));

        // Rotated ellipsoid function
        check_problems(ncv::make_rotated_ellipsoid_funcs(16));

        // Rosenbrock function
        check_problems(ncv::make_rosenbrock_funcs(7));

        // Beale function
        check_problems(ncv::make_beale_funcs());

        // Goldstein-Price function
        check_problems(ncv::make_goldstein_price_funcs());

        // Booth function
        check_problems(ncv::make_booth_funcs());

        // Matyas function
        check_problems(ncv::make_matyas_funcs());

        // Himmelblau function
        check_problems(ncv::make_himmelblau_funcs());

        // 3Hump camel function
        check_problems(ncv::make_3hump_camel_funcs());

        // McCormick function
        check_problems(ncv::make_mccormick_funcs());

        // show global statistics
        tabulator_t table("optimizer");
        table.header() << "time [us]"
                       << "#>e-3"
                       << "#>e-6"
                       << "#>e-9"
                       << "#iters"
                       << "#funcs"
                       << "#grads";

        for (const auto& it : optimizer_stats)
        {
                const string_t& name = it.first;
                const optimizer_stat_t& stat = it.second;

                table.append(name) << stat.m_time.sum()
                                   << static_cast<int>(stat.m_fails_3.sum())
                                   << static_cast<int>(stat.m_fails_6.sum())
                                   << static_cast<int>(stat.m_fails_9.sum())
                                   << stat.m_iterations.sum()
                                   << stat.m_func_evals.sum()
                                   << stat.m_grad_evals.sum();
        }

        sort_asc(table, 3);
        sort_asc(table, 2);
        sort_asc(table, 1);
        table.print(std::cout);

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}

<commit_msg>improve quality assement of optimizers<commit_after>#include "libnanocv/minimize.h"
#include "libnanocv/tabulator.h"
#include "libnanocv/math/abs.hpp"
#include "libnanocv/util/timer.h"
#include "libnanocv/math/math.hpp"
#include "libnanocv/util/logger.h"
#include "libnanocv/util/stats.hpp"
#include "libnanocv/math/clamp.hpp"
#include "libnanocv/util/random.hpp"
#include "libnanocv/math/epsilon.hpp"
#include "libnanocv/thread/parallel.hpp"

#include "libnanocv/functions/function_beale.h"
#include "libnanocv/functions/function_booth.h"
#include "libnanocv/functions/function_sphere.h"
#include "libnanocv/functions/function_matyas.h"
#include "libnanocv/functions/function_ellipsoid.h"
#include "libnanocv/functions/function_mccormick.h"
#include "libnanocv/functions/function_himmelblau.h"
#include "libnanocv/functions/function_rosenbrock.h"
#include "libnanocv/functions/function_3hump_camel.h"
#include "libnanocv/functions/function_goldstein_price.h"
#include "libnanocv/functions/function_rotated_ellipsoid.h"

#include <map>
#include <tuple>

using namespace ncv;

struct optimizer_stat_t
{
        stats_t<scalar_t>       m_time;
        stats_t<scalar_t>       m_crits;
        stats_t<scalar_t>       m_fails;
        stats_t<scalar_t>       m_iters;
        stats_t<scalar_t>       m_fvals;
        stats_t<scalar_t>       m_grads;
};

std::map<string_t, optimizer_stat_t> optimizer_stats;

//static void sort_desc(tabulator_t& table, size_t column)
//{
//        table.sort(column, [] (const string_t& value1, const string_t& value2)
//        {
//                return text::from_string<scalar_t>(value1) > text::from_string<scalar_t>(value2);
//        });
//}

static void sort_asc(tabulator_t& table, size_t column)
{
        table.sort(column, [] (const string_t& value1, const string_t& value2)
        {
                return text::from_string<scalar_t>(value1) < text::from_string<scalar_t>(value2);
        });
}

static void check_problem(
        const string_t& problem_name,
        const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
        const std::vector<std::pair<vector_t, scalar_t>>&)
{
        const size_t iterations = 4 * 1024;
        const scalar_t epsilon = 1e-6;

        const size_t trials = 1024;

        const size_t dims = fn_size();

        // generate fixed random trials
        vectors_t x0s;
        for (size_t t = 0; t < trials; t ++)
        {
                random_t<scalar_t> rgen(-1.0, +1.0);

                vector_t x0(dims);
                rgen(x0.data(), x0.data() + x0.size());

                x0s.push_back(x0);
        }

        // optimizers to try
        const auto optimizers =
        {
//                batch_optimizer::GD,
//                batch_optimizer::CGD_CD,
//                batch_optimizer::CGD_DY,
//                batch_optimizer::CGD_FR,
//                batch_optimizer::CGD_HS,
//                batch_optimizer::CGD_LS,
                batch_optimizer::CGD_PRP,
                batch_optimizer::CGD_N,
//                batch_optimizer::CGD_DYCD,
                batch_optimizer::CGD_DYHS,
                batch_optimizer::LBFGS
        };

        const auto ls_initializers =
        {
                optimize::ls_initializer::unit,
                optimize::ls_initializer::quadratic,
                optimize::ls_initializer::consistent
        };

        const auto ls_strategies =
        {
//                optimize::ls_strategy::backtrack_armijo,
                optimize::ls_strategy::backtrack_wolfe,
//                optimize::ls_strategy::backtrack_strong_wolfe,
//                optimize::ls_strategy::interpolation_bisection,
                optimize::ls_strategy::interpolation_cubic,
                optimize::ls_strategy::cg_descent
        };

        tabulator_t table(text::resize(problem_name, 32));
        table.header() << "cost"
                       << "time [us]"
                       << "|grad|/|fval|"
                       << "#fails"
                       << "#iters"
                       << "#fvals"
                       << "#grads";

        thread_pool_t pool;
        thread_pool_t::mutex_t mutex;

        for (batch_optimizer optimizer : optimizers)
                for (optimize::ls_initializer ls_initializer : ls_initializers)
                        for (optimize::ls_strategy ls_strategy : ls_strategies)
        {
                stats_t<scalar_t> times;
                stats_t<scalar_t> crits;
                stats_t<scalar_t> fails;
                stats_t<scalar_t> iters;
                stats_t<scalar_t> fvals;
                stats_t<scalar_t> grads;

                thread_loopi(trials, pool, [&] (size_t t)
                {
                        const vector_t& x0 = x0s[t];

                        // optimize
                        const ncv::timer_t timer;

                        const opt_state_t state = ncv::minimize(
                                fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
                                x0, optimizer, iterations, epsilon, ls_initializer, ls_strategy);

                        const scalar_t crit = state.convergence_criteria();

                        // update stats
                        const thread_pool_t::lock_t lock(mutex);

                        times(timer.microseconds());
                        crits(crit);
                        iters(state.n_iterations());
                        fvals(state.n_fval_calls());
                        grads(state.n_grad_calls());

                        fails(crit > epsilon ? 1.0 : 0.0);
                });

                // update per-problem table
                const string_t name =
                        text::to_string(optimizer) + "[" +
                        text::to_string(ls_initializer) + "][" +
                        text::to_string(ls_strategy) + "]";

                table.append(name)
                        << static_cast<int>(fvals.sum() + 2 * grads.sum()) / trials
                        << times.avg()
                        << crits.avg()
                        << static_cast<int>(fails.sum())
                        << iters.avg()
                        << fvals.avg()
                        << grads.avg();

                // update global statistics
                optimizer_stat_t& stat = optimizer_stats[name];
                stat.m_time(times.avg());
                stat.m_crits(crits.avg());
                stat.m_fails(fails.sum());
                stat.m_iters(iters.avg());
                stat.m_fvals(fvals.avg());
                stat.m_grads(grads.avg());
        }

        // print stats
        sort_asc(table, 0);
        table.print(std::cout);
}

static void check_problems(const std::vector<ncv::function_t>& funcs)
{
        for (const ncv::function_t& func : funcs)
        {
                check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);
        }
}

int main(int argc, char *argv[])
{
        using namespace ncv;

//        // Sphere function
//        check_problems(ncv::make_sphere_funcs(16));

//        // Ellipsoid function
//        check_problems(ncv::make_ellipsoid_funcs(16));

//        // Rotated ellipsoid function
//        check_problems(ncv::make_rotated_ellipsoid_funcs(1024));

        // Rosenbrock function
        check_problems(ncv::make_rosenbrock_funcs(7));

        // Beale function
        check_problems(ncv::make_beale_funcs());

        // Goldstein-Price function
        check_problems(ncv::make_goldstein_price_funcs());

        // Booth function
        check_problems(ncv::make_booth_funcs());

        // Matyas function
        check_problems(ncv::make_matyas_funcs());

        // Himmelblau function
        check_problems(ncv::make_himmelblau_funcs());

        // 3Hump camel function
        check_problems(ncv::make_3hump_camel_funcs());

        // McCormick function
        check_problems(ncv::make_mccormick_funcs());

        // show global statistics
        tabulator_t table("optimizer");
        table.header() << "time [us]"
                       << "|grad|/|fval|"
                       << "#fails"
                       << "#iters"
                       << "#fvals"
                       << "#grads";

        for (const auto& it : optimizer_stats)
        {
                const string_t& name = it.first;
                const optimizer_stat_t& stat = it.second;

                table.append(name) << stat.m_time.sum()
                                   << stat.m_crits.avg()
                                   << static_cast<int>(stat.m_fails.sum())
                                   << stat.m_iters.sum()
                                   << stat.m_fvals.sum()
                                   << stat.m_grads.sum();
        }

        sort_asc(table, 2);
        table.print(std::cout);

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include "ssl.h"

#include <dirent.h>

#include <cstdlib>
#include <string>
#include <vector>

#include "duplex_curl.h"
#include "platform.h"
#include "util/posix.h"
#include "util/string.h"

namespace {

bool HasCertificates(const std::string &directory) {
  DIR *dirp = opendir(directory.c_str());
  if (!dirp) return false;

  platform_dirent64 *dirent;
  while ((dirent = platform_readdir(dirp))) {
    const std::string filename(directory + "/" + std::string(dirent->d_name));

    platform_stat64 stat;
    if (platform_stat(filename.c_str(), &stat) != 0) continue;
    if (!(S_ISREG(stat.st_mode) || S_ISLNK(stat.st_mode))) continue;

    if (HasSuffix(filename, ".pem", /* ignore case = */ false) ||
        HasSuffix(filename, ".crt", /* ignore case = */ false)) {
      closedir(dirp);
      return true;
    }
  }

  closedir(dirp);
  return false;
}

}  // namespace

SslCertificateStore::SslCertificateStore() {
  const char *ca_path_env = getenv("X509_CERT_DIR");
  if (ca_path_env && *ca_path_env)
    ca_path_ = ca_path_env;
  else
    ca_path_ = "/etc/grid-security/certificates";
  const char *ca_bundle_env = getenv("X509_CERT_BUNDLE");
  if (ca_bundle_env && *ca_bundle_env)
    ca_bundle_ = ca_bundle_env;
}

bool SslCertificateStore::ApplySslCertificatePath(CURL *handle) const {
  CURLcode res1 = curl_easy_setopt(handle, CURLOPT_CAPATH, ca_path_.c_str());
  CURLcode res2 = CURLE_OK;
  if (!ca_bundle_.empty())
    res2 = curl_easy_setopt(handle, CURLOPT_CAINFO, ca_bundle_.c_str());

  return (res1 == CURLE_OK) && (res2 == CURLE_OK);
}

void SslCertificateStore::UseSystemCertificatePath() {
  std::vector<std::string> candidates;

  candidates.push_back("/etc/ssl/certs");
  candidates.push_back("/etc/pki/tls/certs");
  candidates.push_back("/etc/ssl");
  candidates.push_back("/etc/pki/tls");
  candidates.push_back("/etc/pki/ca-trust/extracted/pem");
  candidates.push_back("/etc/ssl");

  for (unsigned i = 0; i < candidates.size(); ++i) {
    if (HasCertificates(candidates[i])) {
      const std::string bundle_candidate = candidates[i] + "/ca-bundle.crt";
      if (FileExists(bundle_candidate) || SymlinkExists(bundle_candidate)) {
        ca_bundle_ = bundle_candidate;
      }
      ca_path_ = candidates[i];
      return;
    }
  }

  // fallback
  ca_path_ = candidates[0];
}
<commit_msg>Fix certificate store handling for explicitly set bundles<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include "ssl.h"

#include <dirent.h>

#include <cstdlib>
#include <string>
#include <vector>

#include "duplex_curl.h"
#include "platform.h"
#include "util/posix.h"
#include "util/string.h"

namespace {

bool HasCertificates(const std::string &directory) {
  DIR *dirp = opendir(directory.c_str());
  if (!dirp) return false;

  platform_dirent64 *dirent;
  while ((dirent = platform_readdir(dirp))) {
    const std::string filename(directory + "/" + std::string(dirent->d_name));

    platform_stat64 stat;
    if (platform_stat(filename.c_str(), &stat) != 0) continue;
    if (!(S_ISREG(stat.st_mode) || S_ISLNK(stat.st_mode))) continue;

    if (HasSuffix(filename, ".pem", /* ignore case = */ false) ||
        HasSuffix(filename, ".crt", /* ignore case = */ false)) {
      closedir(dirp);
      return true;
    }
  }

  closedir(dirp);
  return false;
}

}  // namespace

SslCertificateStore::SslCertificateStore() {
  const char *ca_path_env = getenv("X509_CERT_DIR");
  if (ca_path_env && *ca_path_env)
    ca_path_ = ca_path_env;
  else
    ca_path_ = "/etc/grid-security/certificates";
  const char *ca_bundle_env = getenv("X509_CERT_BUNDLE");
  if (ca_bundle_env && *ca_bundle_env)
    ca_bundle_ = ca_bundle_env;
}

bool SslCertificateStore::ApplySslCertificatePath(CURL *handle) const {
  CURLcode res1 = curl_easy_setopt(handle, CURLOPT_CAPATH, ca_path_.c_str());
  CURLcode res2 = CURLE_OK;
  if (!ca_bundle_.empty())
    res2 = curl_easy_setopt(handle, CURLOPT_CAINFO, ca_bundle_.c_str());

  return (res1 == CURLE_OK) && (res2 == CURLE_OK);
}

void SslCertificateStore::UseSystemCertificatePath() {
  std::vector<std::string> candidates;

  candidates.push_back("/etc/ssl/certs");
  candidates.push_back("/etc/pki/tls/certs");
  candidates.push_back("/etc/ssl");
  candidates.push_back("/etc/pki/tls");
  candidates.push_back("/etc/pki/ca-trust/extracted/pem");
  candidates.push_back("/etc/ssl");

  for (unsigned i = 0; i < candidates.size(); ++i) {
    if (HasCertificates(candidates[i])) {
      const std::string bundle_candidate = candidates[i] + "/ca-bundle.crt";
      if (ca_bundle_.empty() &&
          (FileExists(bundle_candidate) || SymlinkExists(bundle_candidate)))
      {
        ca_bundle_ = bundle_candidate;
      }
      ca_path_ = candidates[i];
      return;
    }
  }

  // fallback
  ca_path_ = candidates[0];
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2018 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////

#include "NoResultsExecutor.h"

#include "Aql/AqlItemMatrix.h"
#include "Aql/ExecutionBlockImpl.h"
#include "Aql/OutputAqlItemRow.h"
#include "Aql/Stats.h"

using namespace arangodb;
using namespace arangodb::aql;

NoResultsExecutor::NoResultsExecutor(Fetcher&, ExecutorInfos&) {}
NoResultsExecutor::~NoResultsExecutor() = default;

auto NoResultsExecutor::produceRows(AqlItemBlockInputRange& input, OutputAqlItemRow& output) const
    noexcept -> std::tuple<ExecutorState, Stats, AqlCall> {
  return {ExecutorState::DONE, NoStats{}, AqlCall{0, false, 0, AqlCall::LimitType::HARD}};
}

auto NoResultsExecutor::skipRowsRange(AqlItemBlockInputRange& inputRange, AqlCall& call) const
    noexcept -> std::tuple<ExecutorState, Stats, size_t, AqlCall> {
  return {inputRange.upstreamState(), NoStats{}, 0,
          AqlCall{0, false, 0, AqlCall::LimitType::HARD}};
};

[[nodiscard]] auto NoResultsExecutor::expectedNumberOfRowsNew(AqlItemBlockInputRange const& input,
                                                              AqlCall const& call) const
    noexcept -> size_t {
  // Well nevermind the input, but we will always return 0 rows here.
  return 0;
}
<commit_msg>Force upstream call to be forwarded in NoResultsExecutor (#11412)<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2018 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////

#include "NoResultsExecutor.h"

#include "Aql/AqlItemMatrix.h"
#include "Aql/ExecutionBlockImpl.h"
#include "Aql/OutputAqlItemRow.h"
#include "Aql/Stats.h"

using namespace arangodb;
using namespace arangodb::aql;

NoResultsExecutor::NoResultsExecutor(Fetcher&, ExecutorInfos&) {}
NoResultsExecutor::~NoResultsExecutor() = default;

auto NoResultsExecutor::produceRows(AqlItemBlockInputRange& input, OutputAqlItemRow& output) const
    noexcept -> std::tuple<ExecutorState, Stats, AqlCall> {
  return {input.upstreamState(), NoStats{}, AqlCall{0, false, 0, AqlCall::LimitType::HARD}};
}

auto NoResultsExecutor::skipRowsRange(AqlItemBlockInputRange& inputRange, AqlCall& call) const
    noexcept -> std::tuple<ExecutorState, Stats, size_t, AqlCall> {
  return {inputRange.upstreamState(), NoStats{}, 0,
          AqlCall{0, false, 0, AqlCall::LimitType::HARD}};
};

[[nodiscard]] auto NoResultsExecutor::expectedNumberOfRowsNew(AqlItemBlockInputRange const& input,
                                                              AqlCall const& call) const
    noexcept -> size_t {
  // Well nevermind the input, but we will always return 0 rows here.
  return 0;
}
<|endoftext|>