<commit_before>/*************************************************************************
 *
 *  $RCSfile: AdabasStat.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 15:38:24 $
 *
 *  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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _DBAUI_ADASTAT_HXX_
#include "AdabasStat.hxx"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XSTATEMENT_HPP_
#include <com/sun/star/sdbc/XStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef DBAUI_ADABASSTAT_HRC
#include "AdabasStat.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _DBAUI_SQLMESSAGE_HXX_
#include "sqlmessage.hxx"
#endif

using namespace dbaui;
DBG_NAME(OAdabasStatistics);
namespace dbaui
{
    using namespace dbtools;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::lang;

OAdabasStatistics::OAdabasStatistics( Window* pParent,
                                     const ::rtl::OUString& _rUser,
                                     const Reference< ::com::sun::star::sdbc::XConnection >& _xCurrentConnection,
                                     const Reference< XMultiServiceFactory >& _xFactory)
    : ModalDialog( pParent, ModuleRes(DLG_ADABASSTAT) )
    ,m_FL_FILES(            this , ResId(FL_FILES))
    ,m_FT_SYSDEVSPACE(      this , ResId(FT_SYSDEVSPACE))
    ,m_ET_SYSDEVSPACE(      this , STR_ADABAS_HELP_SYSDEVSPACE,ResId(ET_SYSDEVSPACE))
    ,m_FT_TRANSACTIONLOG(   this , ResId(FT_TRANSACTIONLOG))
    ,m_ET_TRANSACTIONLOG(   this , STR_ADABAS_HELP_TRANSACT,ResId(ET_TRANSACTIONLOG))
    ,m_FT_DATADEVSPACE(     this , ResId(FT_DATADEVSPACE))
    ,m_LB_DATADEVS(         this , STR_ADABAS_HELP_DATADEVSPACES,ResId(LB_DATADEVS))
    ,m_FL_SIZES(            this , ResId(FL_SIZES))
    ,m_FT_SIZE(             this , ResId(FT_SIZE))
    ,m_ET_SIZE(             this , STR_ADABAS_HELP_SIZE,ResId(ET_SIZE))
    ,m_FT_FREESIZE(         this , ResId(FT_FREESIZE))
    ,m_ET_FREESIZE(         this , STR_ADABAS_HELP_FREESIZE,ResId(ET_FREESIZE))
    ,m_FT_MEMORYUSING(      this , ResId(FT_MEMORYUSING))
    ,m_ET_MEMORYUSING(      this , STR_ADABAS_HELP_MEMORYUSING,ResId(ET_MEMORYUSING))
    ,m_PB_OK(               this , ResId(PB_OK))
    ,m_xConnection(_xCurrentConnection)
    ,m_bErrorShown(sal_False)
{
    DBG_CTOR(OAdabasStatistics,NULL);

    FreeResource();

    DBG_ASSERT(m_xConnection.is(),"No connection");
    if(m_xConnection.is())
    {
        Reference<XStatement> xStmt;
        Reference<XResultSet> xRes;

        sal_Bool bCanSelect     = sal_False;
        ::rtl::OUString aStmt;
        ::rtl::OUString sSchema = _rUser.toAsciiUpperCase();

        Reference<XDatabaseMetaData> xMetaData;
        // first read the sizes
        try
        {
            xMetaData = m_xConnection->getMetaData();
            bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii("SERVERDBSTATISTICS"),sSchema);

            if(bCanSelect)
            {
                aStmt = ::rtl::OUString::createFromAscii("SELECT SERVERDBSIZE, UNUSEDPAGES FROM ");

                aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);
                aStmt += ::rtl::OUString::createFromAscii(".\"SERVERDBSTATISTICS\"");

                xStmt = m_xConnection->createStatement();
                xRes = xStmt->executeQuery(aStmt);

                Reference<XRow> xRow(xRes,UNO_QUERY);
                // first the db sizes
                if(xRes.is() && xRes->next())
                {
                    double nUsedPages = xRow->getInt(1) / 256;
                    double nFreePages = xRow->getInt(2) / 256;

                    m_ET_SIZE.SetText(::rtl::OUString::valueOf((INT32)nUsedPages));
                    m_ET_FREESIZE.SetText(::rtl::OUString::valueOf((INT32)nFreePages));
                    m_ET_MEMORYUSING.SetValue(static_cast<sal_Int32>(((nUsedPages-nFreePages)/nUsedPages)*100));
                }
                else
                    showError();

                xRow = NULL;
            }
            else
                showError();
        }
        catch(const SQLException& e)
        {
            ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);
        }
        catch(const Exception&)
        {
            OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
        }
        try
        {
            ::comphelper::disposeComponent(xStmt);
        }
        catch(const Exception&)
        {
            OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
        }

        // now fill the datadev spaces
        if(bCanSelect)
        {
            try
            {
                bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii("DATADEVSPACES"),sSchema);

                if(bCanSelect)
                {
                    // then the db files
                    aStmt = ::rtl::OUString::createFromAscii("SELECT DEVSPACENAME FROM ");
                    aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);
                    aStmt += ::rtl::OUString::createFromAscii(".\"DATADEVSPACES\"");
                    xStmt = m_xConnection->createStatement();
                    xRes = xStmt->executeQuery(aStmt);

                    Reference<XRow> xRow(xRes,UNO_QUERY);
                    while(xRes.is() && xRes->next())
                    {
                        m_LB_DATADEVS.InsertEntry(xRow->getString(1));
                    }
                    if(!m_LB_DATADEVS.GetEntryCount())
                        showError();
                }
                else
                    showError();
            }
            catch(const SQLException& e)
            {
                ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);
            }
            catch(const Exception&)
            {
                OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
            }
            try
            {
                ::comphelper::disposeComponent(xStmt);
            }
            catch(const Exception&)
            {
                OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
            }

            // now fill the sysdatadev spaces
            if(bCanSelect)
            {
                try
                {
                    bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii("CONFIGURATION"),sSchema);

                    if(bCanSelect)
                    {
                        aStmt = ::rtl::OUString::createFromAscii("SELECT * FROM ");
                        aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);
                        aStmt += ::rtl::OUString::createFromAscii(".CONFIGURATION WHERE DESCRIPTION LIKE 'SYS%DEVSPACE%NAME'");
                        xStmt = m_xConnection->createStatement();
                        xRes = xStmt->executeQuery(aStmt);
                        if(xRes.is() && xRes->next())
                        {
                            Reference<XRow> xRow(xRes,UNO_QUERY);
                            m_ET_SYSDEVSPACE.SetText(xRow->getString(2));
                        }
                        else
                            showError();

                        aStmt = ::rtl::OUString::createFromAscii("SELECT * FROM ");
                        aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);
                        aStmt += ::rtl::OUString::createFromAscii(".CONFIGURATION WHERE DESCRIPTION = 'TRANSACTION LOG NAME'");
                        xRes = xStmt->executeQuery(aStmt);
                        if(xRes.is() && xRes->next())
                        {
                            Reference<XRow> xRow(xRes,UNO_QUERY);
                            m_ET_TRANSACTIONLOG.SetText(xRow->getString(2));
                        }
                        else
                            showError();
                    }
                    else
                        showError();
                }
                catch(const SQLException& e)
                {
                    ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);
                }
                catch(const Exception&)
                {
                    OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
                }
                try
                {
                    ::comphelper::disposeComponent(xStmt);
                }
                catch(const Exception&)
                {
                    OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
                }
            }
        }
    }

    m_ET_SYSDEVSPACE.SetSpecialReadOnly(sal_True);
    m_ET_TRANSACTIONLOG.SetSpecialReadOnly(sal_True);
    m_LB_DATADEVS.SetSpecialReadOnly(sal_True);
    m_ET_SIZE.SetSpecialReadOnly(sal_True);
    m_ET_FREESIZE.SetSpecialReadOnly(sal_True);
    m_ET_MEMORYUSING.SetSpecialReadOnly(sal_True);
}
//------------------------------------------------------------------------
OAdabasStatistics::~OAdabasStatistics()
{
    DBG_DTOR(OAdabasStatistics,NULL);
}
// -----------------------------------------------------------------------------
sal_Bool OAdabasStatistics::checkSystemTable(const ::rtl::OUString& _rsSystemTable, ::rtl::OUString& _rsSchemaName )
{
    sal_Bool bCanSelect = sal_False;
    Reference<XDatabaseMetaData> xMeta = m_xConnection->getMetaData();
    if ( xMeta.is() )
    {
        Reference<XResultSet> xRes = xMeta->getTablePrivileges(Any(),::rtl::OUString::createFromAscii("%"),  _rsSystemTable);
        if(xRes.is())
        {
            Reference<XRow> xRow(xRes,UNO_QUERY);
            static const ::rtl::OUString sSelect = ::rtl::OUString::createFromAscii("SELECT");
            // first the db sizes
            while( xRow.is() && xRes->next() )
            {
                _rsSchemaName = xRow->getString(2);
                if(sSelect == xRow->getString(6) && !xRow->wasNull())
                {
                    bCanSelect = sal_True;
                    break;
                }
            }
            ::comphelper::disposeComponent(xRes);
        }
    }

    return bCanSelect;
}
// -----------------------------------------------------------------------------
void OAdabasStatistics::showError()
{
    if(!m_bErrorShown)
    {
        OSQLMessageBox aMsg(GetParent(),GetText(),String(ModuleRes(STR_ADABAS_ERROR_SYSTEMTABLES)));
        aMsg.Execute();
        m_bErrorShown = sal_True;
    }
}
// -----------------------------------------------------------------------------
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.12.204); FILE MERGED 2005/09/05 17:33:29 rt 1.12.204.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AdabasStat.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:39:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _DBAUI_ADASTAT_HXX_
#include "AdabasStat.hxx"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XSTATEMENT_HPP_
#include <com/sun/star/sdbc/XStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef DBAUI_ADABASSTAT_HRC
#include "AdabasStat.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _DBAUI_SQLMESSAGE_HXX_
#include "sqlmessage.hxx"
#endif

using namespace dbaui;
DBG_NAME(OAdabasStatistics);
namespace dbaui
{
    using namespace dbtools;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::lang;

OAdabasStatistics::OAdabasStatistics( Window* pParent,
                                     const ::rtl::OUString& _rUser,
                                     const Reference< ::com::sun::star::sdbc::XConnection >& _xCurrentConnection,
                                     const Reference< XMultiServiceFactory >& _xFactory)
    : ModalDialog( pParent, ModuleRes(DLG_ADABASSTAT) )
    ,m_FL_FILES(            this , ResId(FL_FILES))
    ,m_FT_SYSDEVSPACE(      this , ResId(FT_SYSDEVSPACE))
    ,m_ET_SYSDEVSPACE(      this , STR_ADABAS_HELP_SYSDEVSPACE,ResId(ET_SYSDEVSPACE))
    ,m_FT_TRANSACTIONLOG(   this , ResId(FT_TRANSACTIONLOG))
    ,m_ET_TRANSACTIONLOG(   this , STR_ADABAS_HELP_TRANSACT,ResId(ET_TRANSACTIONLOG))
    ,m_FT_DATADEVSPACE(     this , ResId(FT_DATADEVSPACE))
    ,m_LB_DATADEVS(         this , STR_ADABAS_HELP_DATADEVSPACES,ResId(LB_DATADEVS))
    ,m_FL_SIZES(            this , ResId(FL_SIZES))
    ,m_FT_SIZE(             this , ResId(FT_SIZE))
    ,m_ET_SIZE(             this , STR_ADABAS_HELP_SIZE,ResId(ET_SIZE))
    ,m_FT_FREESIZE(         this , ResId(FT_FREESIZE))
    ,m_ET_FREESIZE(         this , STR_ADABAS_HELP_FREESIZE,ResId(ET_FREESIZE))
    ,m_FT_MEMORYUSING(      this , ResId(FT_MEMORYUSING))
    ,m_ET_MEMORYUSING(      this , STR_ADABAS_HELP_MEMORYUSING,ResId(ET_MEMORYUSING))
    ,m_PB_OK(               this , ResId(PB_OK))
    ,m_xConnection(_xCurrentConnection)
    ,m_bErrorShown(sal_False)
{
    DBG_CTOR(OAdabasStatistics,NULL);

    FreeResource();

    DBG_ASSERT(m_xConnection.is(),"No connection");
    if(m_xConnection.is())
    {
        Reference<XStatement> xStmt;
        Reference<XResultSet> xRes;

        sal_Bool bCanSelect     = sal_False;
        ::rtl::OUString aStmt;
        ::rtl::OUString sSchema = _rUser.toAsciiUpperCase();

        Reference<XDatabaseMetaData> xMetaData;
        // first read the sizes
        try
        {
            xMetaData = m_xConnection->getMetaData();
            bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii("SERVERDBSTATISTICS"),sSchema);

            if(bCanSelect)
            {
                aStmt = ::rtl::OUString::createFromAscii("SELECT SERVERDBSIZE, UNUSEDPAGES FROM ");

                aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);
                aStmt += ::rtl::OUString::createFromAscii(".\"SERVERDBSTATISTICS\"");

                xStmt = m_xConnection->createStatement();
                xRes = xStmt->executeQuery(aStmt);

                Reference<XRow> xRow(xRes,UNO_QUERY);
                // first the db sizes
                if(xRes.is() && xRes->next())
                {
                    double nUsedPages = xRow->getInt(1) / 256;
                    double nFreePages = xRow->getInt(2) / 256;

                    m_ET_SIZE.SetText(::rtl::OUString::valueOf((INT32)nUsedPages));
                    m_ET_FREESIZE.SetText(::rtl::OUString::valueOf((INT32)nFreePages));
                    m_ET_MEMORYUSING.SetValue(static_cast<sal_Int32>(((nUsedPages-nFreePages)/nUsedPages)*100));
                }
                else
                    showError();

                xRow = NULL;
            }
            else
                showError();
        }
        catch(const SQLException& e)
        {
            ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);
        }
        catch(const Exception&)
        {
            OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
        }
        try
        {
            ::comphelper::disposeComponent(xStmt);
        }
        catch(const Exception&)
        {
            OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
        }

        // now fill the datadev spaces
        if(bCanSelect)
        {
            try
            {
                bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii("DATADEVSPACES"),sSchema);

                if(bCanSelect)
                {
                    // then the db files
                    aStmt = ::rtl::OUString::createFromAscii("SELECT DEVSPACENAME FROM ");
                    aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);
                    aStmt += ::rtl::OUString::createFromAscii(".\"DATADEVSPACES\"");
                    xStmt = m_xConnection->createStatement();
                    xRes = xStmt->executeQuery(aStmt);

                    Reference<XRow> xRow(xRes,UNO_QUERY);
                    while(xRes.is() && xRes->next())
                    {
                        m_LB_DATADEVS.InsertEntry(xRow->getString(1));
                    }
                    if(!m_LB_DATADEVS.GetEntryCount())
                        showError();
                }
                else
                    showError();
            }
            catch(const SQLException& e)
            {
                ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);
            }
            catch(const Exception&)
            {
                OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
            }
            try
            {
                ::comphelper::disposeComponent(xStmt);
            }
            catch(const Exception&)
            {
                OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
            }

            // now fill the sysdatadev spaces
            if(bCanSelect)
            {
                try
                {
                    bCanSelect = checkSystemTable(::rtl::OUString::createFromAscii("CONFIGURATION"),sSchema);

                    if(bCanSelect)
                    {
                        aStmt = ::rtl::OUString::createFromAscii("SELECT * FROM ");
                        aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);
                        aStmt += ::rtl::OUString::createFromAscii(".CONFIGURATION WHERE DESCRIPTION LIKE 'SYS%DEVSPACE%NAME'");
                        xStmt = m_xConnection->createStatement();
                        xRes = xStmt->executeQuery(aStmt);
                        if(xRes.is() && xRes->next())
                        {
                            Reference<XRow> xRow(xRes,UNO_QUERY);
                            m_ET_SYSDEVSPACE.SetText(xRow->getString(2));
                        }
                        else
                            showError();

                        aStmt = ::rtl::OUString::createFromAscii("SELECT * FROM ");
                        aStmt += ::dbtools::quoteTableName(xMetaData,sSchema,::dbtools::eInDataManipulation);
                        aStmt += ::rtl::OUString::createFromAscii(".CONFIGURATION WHERE DESCRIPTION = 'TRANSACTION LOG NAME'");
                        xRes = xStmt->executeQuery(aStmt);
                        if(xRes.is() && xRes->next())
                        {
                            Reference<XRow> xRow(xRes,UNO_QUERY);
                            m_ET_TRANSACTIONLOG.SetText(xRow->getString(2));
                        }
                        else
                            showError();
                    }
                    else
                        showError();
                }
                catch(const SQLException& e)
                {
                    ::dbaui::showError(SQLExceptionInfo(e),pParent,_xFactory);
                }
                catch(const Exception&)
                {
                    OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
                }
                try
                {
                    ::comphelper::disposeComponent(xStmt);
                }
                catch(const Exception&)
                {
                    OSL_ENSURE(sal_False, "OAdabasStatistics::OAdabasStatistics: caught an exception!");
                }
            }
        }
    }

    m_ET_SYSDEVSPACE.SetSpecialReadOnly(sal_True);
    m_ET_TRANSACTIONLOG.SetSpecialReadOnly(sal_True);
    m_LB_DATADEVS.SetSpecialReadOnly(sal_True);
    m_ET_SIZE.SetSpecialReadOnly(sal_True);
    m_ET_FREESIZE.SetSpecialReadOnly(sal_True);
    m_ET_MEMORYUSING.SetSpecialReadOnly(sal_True);
}
//------------------------------------------------------------------------
OAdabasStatistics::~OAdabasStatistics()
{
    DBG_DTOR(OAdabasStatistics,NULL);
}
// -----------------------------------------------------------------------------
sal_Bool OAdabasStatistics::checkSystemTable(const ::rtl::OUString& _rsSystemTable, ::rtl::OUString& _rsSchemaName )
{
    sal_Bool bCanSelect = sal_False;
    Reference<XDatabaseMetaData> xMeta = m_xConnection->getMetaData();
    if ( xMeta.is() )
    {
        Reference<XResultSet> xRes = xMeta->getTablePrivileges(Any(),::rtl::OUString::createFromAscii("%"),  _rsSystemTable);
        if(xRes.is())
        {
            Reference<XRow> xRow(xRes,UNO_QUERY);
            static const ::rtl::OUString sSelect = ::rtl::OUString::createFromAscii("SELECT");
            // first the db sizes
            while( xRow.is() && xRes->next() )
            {
                _rsSchemaName = xRow->getString(2);
                if(sSelect == xRow->getString(6) && !xRow->wasNull())
                {
                    bCanSelect = sal_True;
                    break;
                }
            }
            ::comphelper::disposeComponent(xRes);
        }
    }

    return bCanSelect;
}
// -----------------------------------------------------------------------------
void OAdabasStatistics::showError()
{
    if(!m_bErrorShown)
    {
        OSQLMessageBox aMsg(GetParent(),GetText(),String(ModuleRes(STR_ADABAS_ERROR_SYSTEMTABLES)));
        aMsg.Execute();
        m_bErrorShown = sal_True;
    }
}
// -----------------------------------------------------------------------------
}

<|endoftext|>


<commit_before>//=- LiveVariables.cpp - Live Variable Analysis for Source CFGs -*- C++ --*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
// details.
//
//===----------------------------------------------------------------------===//
//
// This file implements Live Variables analysis for source-level CFGs.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/Analyses/LiveVariables.h"
#include "clang/Basic/SourceManager.h"
#include "clang/AST/Expr.h"
#include "clang/AST/CFG.h"
#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
#include "clang/Analysis/FlowSensitive/DataflowSolver.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Support/Compiler.h"

#include <string.h>
#include <stdio.h>

using namespace clang;

//===----------------------------------------------------------------------===//
// Dataflow initialization logic.
//===----------------------------------------------------------------------===//

namespace {
class VISIBILITY_HIDDEN RegisterDecls
  : public CFGRecStmtDeclVisitor<RegisterDecls> {

  LiveVariables::AnalysisDataTy& AD;
public:
  RegisterDecls(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}
  void VisitVarDecl(VarDecl* VD) { AD.Register(VD); }
  CFG& getCFG() { return AD.getCFG(); }
};
} // end anonymous namespace

LiveVariables::LiveVariables(CFG& cfg, FunctionDecl& FD) {
  getAnalysisData().setCFG(&cfg);

  for (FunctionDecl::param_iterator I=FD.param_begin(), E=FD.param_end();
       I !=E; ++I)
    getAnalysisData().Register(*I);

  // Now register all the other VarDecls;
  RegisterDecls R(getAnalysisData());
  cfg.VisitBlockStmts(R);
}

//===----------------------------------------------------------------------===//
// Transfer functions.
//===----------------------------------------------------------------------===//

namespace {

static const bool Alive = true;
static const bool Dead = false;

class VISIBILITY_HIDDEN TransferFuncs : public CFGRecStmtVisitor<TransferFuncs>{
  LiveVariables::AnalysisDataTy& AD;
  LiveVariables::ValTy LiveState;
public:
  TransferFuncs(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}

  LiveVariables::ValTy& getVal() { return LiveState; }
  CFG& getCFG() { return AD.getCFG(); }

  void VisitDeclRefExpr(DeclRefExpr* DR);
  void VisitBinaryOperator(BinaryOperator* B);
  void VisitAssign(BinaryOperator* B);
  void VisitDeclStmt(DeclStmt* DS);
  void VisitUnaryOperator(UnaryOperator* U);
  void Visit(Stmt *S);
};

void TransferFuncs::Visit(Stmt *S) {
  if (AD.Observer)
    AD.Observer->ObserveStmt(S,AD,LiveState);

  if (S == getCurrentBlkStmt()) {
    if (getCFG().isBlkExpr(S)) LiveState(S,AD) = Dead;
    StmtVisitor<TransferFuncs,void>::Visit(S);
  }
  else if (!getCFG().isBlkExpr(S))
    StmtVisitor<TransferFuncs,void>::Visit(S);
  else
    // For block-level expressions, mark that they are live.
    LiveState(S,AD) = Alive;
}

void TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) {
  if (VarDecl* V = dyn_cast<VarDecl>(DR->getDecl()))
    LiveState(V,AD) = Alive;
}

void TransferFuncs::VisitBinaryOperator(BinaryOperator* B) {
  if (B->isAssignmentOp()) VisitAssign(B);
  else VisitStmt(B);
}

void TransferFuncs::VisitUnaryOperator(UnaryOperator* U) {
  Expr *E = U->getSubExpr();

  switch (U->getOpcode()) {
  case UnaryOperator::SizeOf: return;
  case UnaryOperator::PostInc:
  case UnaryOperator::PostDec:
  case UnaryOperator::PreInc:
  case UnaryOperator::PreDec:
  case UnaryOperator::AddrOf:
    // Walk through the subexpressions, blasting through ParenExprs
    // until we either find a DeclRefExpr or some non-DeclRefExpr
    // expression.
    if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()))
      if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) {
        // Treat the --/++/& operator as a kill.
        LiveState(VD, AD) = Dead;
        if (AD.Observer) { AD.Observer->ObserverKill(DR); }
        return VisitDeclRefExpr(DR);
      }

    // Fall-through.

  default:
    return Visit(E);
  }
}

void TransferFuncs::VisitAssign(BinaryOperator* B) {
  Expr* LHS = B->getLHS();

  // Assigning to a variable?
  if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParens())) {
    LiveState(DR->getDecl(),AD) = Dead;
    if (AD.Observer) { AD.Observer->ObserverKill(DR); }

    // Handle things like +=, etc., which also generate "uses"
    // of a variable.  Do this just by visiting the subexpression.
    if (B->getOpcode() != BinaryOperator::Assign)
      VisitDeclRefExpr(DR);
  }
  else // Not assigning to a variable.  Process LHS as usual.
    Visit(LHS);

  Visit(B->getRHS());
}

void TransferFuncs::VisitDeclStmt(DeclStmt* DS) {
  // Declarations effectively "kill" a variable since they cannot
  // possibly be live before they are declared.
  for (ScopedDecl* D = DS->getDecl(); D != NULL; D = D->getNextDeclarator()) {
    LiveState(D,AD) = Dead;

    if (VarDecl* VD = dyn_cast<VarDecl>(D))
      if (Expr* Init = VD->getInit())
        Visit(Init);
  }
}

} // end anonymous namespace

//===----------------------------------------------------------------------===//
// Merge operator: if something is live on any successor block, it is live
//  in the current block (a set union).
//===----------------------------------------------------------------------===//

namespace {
typedef DeclBitVector_Types::Union Merge;
typedef DataflowSolver<LiveVariables,TransferFuncs,Merge> Solver;
} // end anonymous namespace

//===----------------------------------------------------------------------===//
// External interface to run Liveness analysis.
//===----------------------------------------------------------------------===//

void LiveVariables::runOnCFG(CFG& cfg) {
  Solver S(*this);
  S.runOnCFG(cfg);
}

void LiveVariables::runOnAllBlocks(const CFG& cfg,
                                   LiveVariables::ObserverTy* Obs,
                                   bool recordStmtValues) {
  Solver S(*this);
  ObserverTy* OldObserver = getAnalysisData().Observer;
  getAnalysisData().Observer = Obs;
  S.runOnAllBlocks(cfg, recordStmtValues);
  getAnalysisData().Observer = OldObserver;
}

//===----------------------------------------------------------------------===//
// liveness queries
//

bool LiveVariables::isLive(const CFGBlock* B, const VarDecl* D) const {
  return getBlockData(B)(D,getAnalysisData());
}

bool LiveVariables::isLive(const ValTy& Live, const VarDecl* D) const {
  return Live(D,getAnalysisData());
}

bool LiveVariables::isLive(const Stmt* Loc, const Stmt* StmtVal) const {
  return getStmtData(Loc)(StmtVal,getAnalysisData());
}

bool LiveVariables::isLive(const Stmt* Loc, const VarDecl* D) const {
  return getStmtData(Loc)(D,getAnalysisData());
}

//===----------------------------------------------------------------------===//
// printing liveness state for debugging
//

void LiveVariables::dumpLiveness(const ValTy& V, SourceManager& SM) const {
  const AnalysisDataTy& AD = getAnalysisData();

  for (AnalysisDataTy::decl_iterator I = AD.begin_decl(),
                                     E = AD.end_decl(); I!=E; ++I)
    if (V.getDeclBit(I->second)) {
      SourceLocation PhysLoc = SM.getPhysicalLoc(I->first->getLocation());

      fprintf(stderr, "  %s <%s:%u:%u>\n",
              I->first->getIdentifier()->getName(),
              SM.getSourceName(PhysLoc),
              SM.getLineNumber(PhysLoc),
              SM.getColumnNumber(PhysLoc));
    }
}

void LiveVariables::dumpBlockLiveness(SourceManager& M) const {
  for (BlockDataMapTy::iterator I = getBlockDataMap().begin(),
       E = getBlockDataMap().end(); I!=E; ++I) {
    fprintf(stderr, "\n[ B%d (live variables at block exit) ]\n",
            I->first->getBlockID());

    dumpLiveness(I->second,M);
  }

  fprintf(stderr,"\n");
}
<commit_msg>Fixed horrid bug in LiveVariables analysis where we were only merging at confluence points the liveness information for variables (Decls) and NOT block-level expressions.<commit_after>//=- LiveVariables.cpp - Live Variable Analysis for Source CFGs -*- C++ --*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
// details.
//
//===----------------------------------------------------------------------===//
//
// This file implements Live Variables analysis for source-level CFGs.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/Analyses/LiveVariables.h"
#include "clang/Basic/SourceManager.h"
#include "clang/AST/Expr.h"
#include "clang/AST/CFG.h"
#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
#include "clang/Analysis/FlowSensitive/DataflowSolver.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Support/Compiler.h"

#include <string.h>
#include <stdio.h>

using namespace clang;

//===----------------------------------------------------------------------===//
// Dataflow initialization logic.
//===----------------------------------------------------------------------===//

namespace {
class VISIBILITY_HIDDEN RegisterDecls
  : public CFGRecStmtDeclVisitor<RegisterDecls> {

  LiveVariables::AnalysisDataTy& AD;
public:
  RegisterDecls(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}
  void VisitVarDecl(VarDecl* VD) { AD.Register(VD); }
  CFG& getCFG() { return AD.getCFG(); }
};
} // end anonymous namespace

LiveVariables::LiveVariables(CFG& cfg, FunctionDecl& FD) {
  getAnalysisData().setCFG(&cfg);

  for (FunctionDecl::param_iterator I=FD.param_begin(), E=FD.param_end();
       I !=E; ++I)
    getAnalysisData().Register(*I);

  // Now register all the other VarDecls;
  RegisterDecls R(getAnalysisData());
  cfg.VisitBlockStmts(R);
}

//===----------------------------------------------------------------------===//
// Transfer functions.
//===----------------------------------------------------------------------===//

namespace {

static const bool Alive = true;
static const bool Dead = false;

class VISIBILITY_HIDDEN TransferFuncs : public CFGRecStmtVisitor<TransferFuncs>{
  LiveVariables::AnalysisDataTy& AD;
  LiveVariables::ValTy LiveState;
public:
  TransferFuncs(LiveVariables::AnalysisDataTy& ad) : AD(ad) {}

  LiveVariables::ValTy& getVal() { return LiveState; }
  CFG& getCFG() { return AD.getCFG(); }

  void VisitDeclRefExpr(DeclRefExpr* DR);
  void VisitBinaryOperator(BinaryOperator* B);
  void VisitAssign(BinaryOperator* B);
  void VisitDeclStmt(DeclStmt* DS);
  void VisitUnaryOperator(UnaryOperator* U);
  void Visit(Stmt *S);
};

void TransferFuncs::Visit(Stmt *S) {
  if (AD.Observer)
    AD.Observer->ObserveStmt(S,AD,LiveState);

  if (S == getCurrentBlkStmt()) {
    if (getCFG().isBlkExpr(S)) LiveState(S,AD) = Dead;
    StmtVisitor<TransferFuncs,void>::Visit(S);
  }
  else if (!getCFG().isBlkExpr(S))
    StmtVisitor<TransferFuncs,void>::Visit(S);
  else
    // For block-level expressions, mark that they are live.
    LiveState(S,AD) = Alive;
}

void TransferFuncs::VisitDeclRefExpr(DeclRefExpr* DR) {
  if (VarDecl* V = dyn_cast<VarDecl>(DR->getDecl()))
    LiveState(V,AD) = Alive;
}

void TransferFuncs::VisitBinaryOperator(BinaryOperator* B) {
  if (B->isAssignmentOp()) VisitAssign(B);
  else VisitStmt(B);
}

void TransferFuncs::VisitUnaryOperator(UnaryOperator* U) {
  Expr *E = U->getSubExpr();

  switch (U->getOpcode()) {
  case UnaryOperator::SizeOf: return;
  case UnaryOperator::PostInc:
  case UnaryOperator::PostDec:
  case UnaryOperator::PreInc:
  case UnaryOperator::PreDec:
  case UnaryOperator::AddrOf:
    // Walk through the subexpressions, blasting through ParenExprs
    // until we either find a DeclRefExpr or some non-DeclRefExpr
    // expression.
    if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()))
      if (VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl())) {
        // Treat the --/++/& operator as a kill.
        LiveState(VD, AD) = Dead;
        if (AD.Observer) { AD.Observer->ObserverKill(DR); }
        return VisitDeclRefExpr(DR);
      }

    // Fall-through.

  default:
    return Visit(E);
  }
}

void TransferFuncs::VisitAssign(BinaryOperator* B) {
  Expr* LHS = B->getLHS();

  // Assigning to a variable?
  if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParens())) {
    LiveState(DR->getDecl(),AD) = Dead;
    if (AD.Observer) { AD.Observer->ObserverKill(DR); }

    // Handle things like +=, etc., which also generate "uses"
    // of a variable.  Do this just by visiting the subexpression.
    if (B->getOpcode() != BinaryOperator::Assign)
      VisitDeclRefExpr(DR);
  }
  else // Not assigning to a variable.  Process LHS as usual.
    Visit(LHS);

  Visit(B->getRHS());
}

void TransferFuncs::VisitDeclStmt(DeclStmt* DS) {
  // Declarations effectively "kill" a variable since they cannot
  // possibly be live before they are declared.
  for (ScopedDecl* D = DS->getDecl(); D != NULL; D = D->getNextDeclarator()) {
    LiveState(D,AD) = Dead;

    if (VarDecl* VD = dyn_cast<VarDecl>(D))
      if (Expr* Init = VD->getInit())
        Visit(Init);
  }
}

} // end anonymous namespace

//===----------------------------------------------------------------------===//
// Merge operator: if something is live on any successor block, it is live
//  in the current block (a set union).
//===----------------------------------------------------------------------===//

namespace {
typedef ExprDeclBitVector_Types::Union Merge;
typedef DataflowSolver<LiveVariables,TransferFuncs,Merge> Solver;
} // end anonymous namespace

//===----------------------------------------------------------------------===//
// External interface to run Liveness analysis.
//===----------------------------------------------------------------------===//

void LiveVariables::runOnCFG(CFG& cfg) {
  Solver S(*this);
  S.runOnCFG(cfg);
}

void LiveVariables::runOnAllBlocks(const CFG& cfg,
                                   LiveVariables::ObserverTy* Obs,
                                   bool recordStmtValues) {
  Solver S(*this);
  ObserverTy* OldObserver = getAnalysisData().Observer;
  getAnalysisData().Observer = Obs;
  S.runOnAllBlocks(cfg, recordStmtValues);
  getAnalysisData().Observer = OldObserver;
}

//===----------------------------------------------------------------------===//
// liveness queries
//

bool LiveVariables::isLive(const CFGBlock* B, const VarDecl* D) const {
  return getBlockData(B)(D,getAnalysisData());
}

bool LiveVariables::isLive(const ValTy& Live, const VarDecl* D) const {
  return Live(D,getAnalysisData());
}

bool LiveVariables::isLive(const Stmt* Loc, const Stmt* StmtVal) const {
  return getStmtData(Loc)(StmtVal,getAnalysisData());
}

bool LiveVariables::isLive(const Stmt* Loc, const VarDecl* D) const {
  return getStmtData(Loc)(D,getAnalysisData());
}

//===----------------------------------------------------------------------===//
// printing liveness state for debugging
//

void LiveVariables::dumpLiveness(const ValTy& V, SourceManager& SM) const {
  const AnalysisDataTy& AD = getAnalysisData();

  for (AnalysisDataTy::decl_iterator I = AD.begin_decl(),
                                     E = AD.end_decl(); I!=E; ++I)
    if (V.getDeclBit(I->second)) {
      SourceLocation PhysLoc = SM.getPhysicalLoc(I->first->getLocation());

      fprintf(stderr, "  %s <%s:%u:%u>\n",
              I->first->getIdentifier()->getName(),
              SM.getSourceName(PhysLoc),
              SM.getLineNumber(PhysLoc),
              SM.getColumnNumber(PhysLoc));
    }
}

void LiveVariables::dumpBlockLiveness(SourceManager& M) const {
  for (BlockDataMapTy::iterator I = getBlockDataMap().begin(),
       E = getBlockDataMap().end(); I!=E; ++I) {
    fprintf(stderr, "\n[ B%d (live variables at block exit) ]\n",
            I->first->getBlockID());

    dumpLiveness(I->second,M);
  }

  fprintf(stderr,"\n");
}
<|endoftext|>


<commit_before>// Copyright © 2017-2018 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.02.25

// main.cpp

#include <iostream>
#include "../src/thread/ThreadPool.hpp"
#include "../src/configs/Options.hpp"
#include "../src/configs/Config.hpp"
#include "../src/server/Server.hpp"
#include "../src/utils/Daemon.hpp"
#include "../src/log/LoggerManager.hpp"

int main(int argc, char *argv[])
{
	Daemon::SetProcessName();
	Daemon::StartManageSignals();

	std::shared_ptr<Options> options;
	try
	{
		options = std::make_shared<Options>(argc, argv);
	}
	catch (const std::exception& exception)
	{
		printf("Fail get opptions ← %s", exception.what());
		return EXIT_FAILURE;
	}

	std::shared_ptr<Config> configs;
	try
	{
		configs = std::make_shared<Config>(options);
	}
	catch (const std::exception& exception)
	{
		printf("Fail get configuration ← %s", exception.what());
		return EXIT_FAILURE;
	}

	try
	{
		LoggerManager::init(configs);
	}
	catch (const std::exception& exception)
	{
		printf("Fail logging initialize ← %s", exception.what());
		return EXIT_FAILURE;
	}

	P7_Set_Crash_Handler();

	Log log("Main");
	log.info("Start daemon");

	std::shared_ptr<Server> server;
	try
	{
		server = std::make_shared<Server>(configs);
	}
	catch (const std::exception& exception)
	{
		log.error("Fail init server ← %s", exception.what());
		return EXIT_FAILURE;
	}

//	Daemon::SetDaemonMode();

	server->start();

	Daemon::doAtShutdown([server](){
		server->stop();
	});

	server->wait();

	log.info("Stop daemon");

	Log::finalFlush();

	return EXIT_SUCCESS;
}
<commit_msg>Little change<commit_after>// Copyright © 2017-2018 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.02.25

// main.cpp

#include <iostream>
#include "../src/thread/ThreadPool.hpp"
#include "../src/configs/Options.hpp"
#include "../src/configs/Config.hpp"
#include "../src/server/Server.hpp"
#include "../src/utils/Daemon.hpp"
#include "../src/log/LoggerManager.hpp"

int main(int argc, char *argv[])
{
	Daemon::SetProcessName();
	Daemon::StartManageSignals();

	std::shared_ptr<Options> options;
	try
	{
		options = std::make_shared<Options>(argc, argv);
	}
	catch (const std::exception& exception)
	{
		printf("Fail get opptions ← %s\n", exception.what());
		return EXIT_FAILURE;
	}

	std::shared_ptr<Config> configs;
	try
	{
		configs = std::make_shared<Config>(options);
	}
	catch (const std::exception& exception)
	{
		printf("Fail get configuration ← %s\n", exception.what());
		return EXIT_FAILURE;
	}

	try
	{
		LoggerManager::init(configs);
	}
	catch (const std::exception& exception)
	{
		printf("Fail logging initialize ← %s\n", exception.what());
		return EXIT_FAILURE;
	}

	P7_Set_Crash_Handler();

	Log log("Main");
	log.info("Start daemon");

	std::shared_ptr<Server> server;
	try
	{
		server = std::make_shared<Server>(configs);
	}
	catch (const std::exception& exception)
	{
		log.error("Fail init server ← %s", exception.what());
		return EXIT_FAILURE;
	}

//	Daemon::SetDaemonMode();

	server->start();

	Daemon::doAtShutdown([server](){
		server->stop();
	});

	server->wait();

	log.info("Stop daemon");

	Log::finalFlush();

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>303. Range Sum Query - Immutable<commit_after><|endoftext|>


<commit_before>#include "PhysicsThread.h"
#include "PhysicsObject.h"
#include "Collision.h"
#include <cmath>
#include <vector>
#include <algorithm>
#include <iterator>
#include <QDebug>

PhysicsThread::PhysicsThread()
{
}

PhysicsThread::PhysicsThread(int minx ,int miny ,int minz ,int maxx ,int maxy ,int maxz)
{

	this->minx = minx;
	this->miny = miny;
	this->minz = minz;

	this->maxx = maxx;
	this->maxy = maxy;
	this->maxz = maxz;

}

PhysicsThread::~PhysicsThread()
{

}

void PhysicsThread::run(){
	qDebug() << "SUCCESSFULLY STARTED UP PHYSICS-SIMULATION";
	forever{
		mutex.lock();
		qDebug() << "RUNNING PHYSICS-SIMULATION";
		runSimulation(1.0/60.0);
		if(stop){
			break;
		}
		if(bPause){
			pauseManager.wait(&mutex);
		}
		mutex.unlock();
	}
}

void PhysicsThread::TogglePause()
{
	bPause = !bPause;
	if(!bPause){
		pauseManager.wakeAll();
	}
}

void PhysicsThread::pause()
{
	bPause = true;
}

void PhysicsThread::resume()
{
	bPause = false;
	pauseManager.wakeAll();
}

void PhysicsThread::quit()
{
	stop = true;
	QThread::quit();
	qDebug() << "STOPPING PHYSICS-THREAD";
}

void PhysicsThread::runSimulation(const double& delta){

	// Collision Border
	for(int i = 0 ; i < pobjectsSphere.size() ; i++) {

		PhysicsSphere* op = pobjectsSphere.at(i);
		if(op->getIsMovable()){
			// is Sphere TODO
			if(true){
				if(op->getX()-(op->getSize()) < minx ){
					if(op->getVelocityX() < 0){
						op->setVelocityX(-op->getVelocityX());
					}else{
						op->setVelocityX(op->getVelocityX());
					}
				}else if(op->getX()+(op->getSize()) > maxx) {
					if(op->getVelocityX() > 0){
						op->setVelocityX(-op->getVelocityX());
					}else{
						op->setVelocityX(op->getVelocityX());
					}
				}

				if(op->getY()-(op->getSize()) < miny){
					if(op->getVelocityY() < 0){
						op->setVelocityY(-op->getVelocityY() * op->getRemainingEnergy());
					}else{
						op->setVelocityY(op->getVelocityY());
					}
				}else{
					if(op->getY()+(op->getSize()) > maxy){
						if(op->getVelocityY() > 0){
							op->setVelocityY(-op->getVelocityY());
						}else{
							op->setVelocityY(op->getVelocityY());
						}
					}
					// Gravity
					op->setVelocityY(op->getVelocityY() + g*delta*op->getMass());
				}

				if(op->getZ()-(op->getSize()) < minz){
					if(op->getVelocityZ() < 0){
						op->setVelocityZ(-op->getVelocityZ());
					}else{
						op->setVelocityZ(op->getVelocityZ());
					}
				}else if(op->getZ()+(op->getSize()) > maxz){
					if(op->getVelocityZ() > 0){
						op->setVelocityZ(-op->getVelocityZ());
					}else{
						op->setVelocityZ(op->getVelocityZ());
					}
				}
			}
		}
	}

	// Collision Sphere on Sphere
	for(int i = 0 ; i < pobjectsSphere.size() ; i++) {
		PhysicsSphere* op1 = pobjectsSphere.at(i);
		for(int j = i ; j < pobjectsSphere.size() ; j++) {
			PhysicsSphere* op2 = pobjectsSphere.at(j);

			// bool Collision::SphereVersusSphere(const int& x1 , const int& y1 , const int& z1 , const int& size1 , const int& x2 , const int& y2 , const int& z2 , const int& size2)
			// Sphere on Sphere
			// SIZE
			if(i != j && Collision::SphereVersusSphere(op1->getX() ,op1->getY() ,op1->getZ() ,op1->getSize() ,op2->getX() ,op2->getY() ,op2->getZ() ,op2->getSize())){

				double tempX (op1->getX() - op2->getX());
				double tempY (op1->getY() - op2->getY());
				double tempZ (op1->getZ() - op2->getZ());

				double norm = sqrt(tempX*tempX + tempY*tempY + tempZ*tempZ);

				tempX = tempX / norm;
				tempY = tempY / norm;
				tempZ = tempZ / norm;

				double a1 = (op1->getVelocityX() * tempX) + (op1->getVelocityY() * tempY) + (op1->getVelocityZ() * tempZ);
				double a2 = (op2->getVelocityX() * tempX) + (op2->getVelocityY() * tempY) + (op2->getVelocityZ() * tempZ);

				// double optimizedP = (2.0D * (a1 - a2)) / (e1.getWhight() + e2.getWhight());

				double optimizedP = (2.0 * (a1 - a2)) / (op1->getMass() + op2->getMass());

				// fix
				optimizedP = std::abs(optimizedP);

				qDebug() << optimizedP;

				// 0.9 Verlusst
				if(op1->getIsMovable()){
					op1->setVelocityX( op1->getVelocityX() + (optimizedP * op2->getMass() * tempX) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
					op1->setVelocityY( op1->getVelocityY() + (optimizedP * op2->getMass() * tempY) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
					op1->setVelocityZ( op1->getVelocityZ() + (optimizedP * op2->getMass() * tempZ) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
				}

				if(op2->getIsMovable()){
					op2->setVelocityX( op2->getVelocityX() - (optimizedP * op1->getMass() * tempX) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
					op2->setVelocityY( op2->getVelocityY() - (optimizedP * op1->getMass() * tempY) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
					op2->setVelocityZ( op2->getVelocityZ() - (optimizedP * op1->getMass() * tempZ) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
				}

				// TODO
				qDebug() << op1->getPosition() << "BEFORE";
				op1->setX(op1->getX() + op1->getVelocityX() * delta);
				op1->setY(op1->getY() + op1->getVelocityY() * delta);
				op1->setZ(op1->getZ() + op1->getVelocityZ() * delta);

				op2->setX(op2->getX() + op2->getVelocityX() * delta);
				op2->setY(op2->getY() + op2->getVelocityY() * delta);
				op2->setZ(op2->getZ() + op2->getVelocityZ() * delta);
				qDebug() << op1->getPosition() << "AFTER";
			}
		}
	}

//	// Collision Shere on Box
//	// bool Collision::SphereVersusBox
//	//(const int& sphereX ,const int& sphereY ,const int& sphereZ ,const int& sphereSize
//	// ,const int& boxMinX ,const int& boxMinY ,const int& boxMinZ ,const int& boxMaxX ,const int& boxMaxY ,const int& boxMaxZ)

    for(int i = 0 ; i < pobjectsSphere.size() ; i++) {
        PhysicsSphere* op1 = pobjectsSphere.at(i);
        for(int j = 0 ; j < pobjectsBox.size() ; j++) {
            PhysicsBox* op2 = pobjectsBox.at(j);

            if(Collision::SphereVersusBox( op1->getX() ,op1->getY() ,op1->getZ() ,op1->getSize() ,op2->getMinX()+op2->getX() ,op2->getMinY()+op2->getY() ,op2->getMinZ()+op2->getZ() ,op2->getMaxX()+op2->getX() ,op2->getMaxY()+op2->getY() ,op2->getMaxZ()+op2->getZ())){

                qDebug() << "Test";

                if((op1->getX()+op1->getSize()) > op2->getMinX() && op1->getX() < op2->getMinX()+op2->getX()){

                    if(op1->getVelocityX() > 0){
                        op1->setVelocityX(-op1->getVelocityX());
                    }
                }
                if((op1->getX()-op1->getSize()) < op2->getMaxX() && op1->getX() > op2->getMaxX()+op2->getX()){
                    if(op1->getVelocityX() < 0){
                        op1->setVelocityX(-op1->getVelocityX());
                    }
                }

                if((op1->getY()+op1->getSize()) > op2->getMinY() && op1->getY() < op2->getMinY()+op2->getY()){
                    if(op1->getVelocityY() > 0){
                        op1->setVelocityY(-op1->getVelocityY());
                    }
                }
                if((op1->getY()-op1->getSize()) < op2->getMaxY() && op1->getY() > op2->getMaxY()+op2->getY()){

                    if(op1->getVelocityY() < 0){
                        op1->setVelocityY(-op1->getVelocityY());
                    }
                }

                if((op1->getZ()+op1->getSize()) > op2->getMinZ() && op1->getZ() < op2->getMinZ()+op2->getZ()){
                    if(op1->getVelocityZ() > 0){
                        op1->setVelocityZ(-op1->getVelocityZ());
                    }
                }
                if((op1->getZ()-op1->getSize()) < op2->getMaxZ() && op1->getZ() > op2->getMaxZ()+op2->getZ()){
                    if(op1->getVelocityZ() < 0){
                        op1->setVelocityZ(-op1->getVelocityZ());
                    }
                }

                /*
                if(closeDistance > std::abs( op1->getX() - op2->getMinX()) && op1->getX() > op2->getMaxX()){
                    closeDistance = std::abs( op1->getX() - op2->getMaxX());
                    point = 0;

                }

                if(closeDistance > std::abs( op1->getX() - op2->getMinX()) && op1->getX() < op2->getMinX()){
                    closeDistance = std::abs( op1->getX() - op2->getMinX());
                    point = 1;
                }

                if(closeDistance > std::abs( op1->getY() - op2->getMaxY()) && op1->getY() > op2->getMaxY()){
                    closeDistance = std::abs( op1->getY() - op2->getMaxY());
                    point = 2;
                }

                if(closeDistance > std::abs( op1->getY() - op2->getMinY()) && op1->getY() < op2->getMinY()){
                    closeDistance = std::abs( op1->getY() - op2->getMinY());
                    point = 3;
                }

                if(closeDistance > std::abs( op1->getZ() - op2->getMaxZ()) && op1->getZ() > op2->getMaxZ()){
                    closeDistance = std::abs( op1->getZ() - op2->getMaxZ());
                    point = 4;
                }

                if(closeDistance > std::abs( op1->getZ() - op2->getMinZ()) && op1->getZ() < op2->getMinZ()){
                    closeDistance = std::abs( op1->getZ() - op2->getMinZ());
                    point = 5;
                }

                qDebug() << point << " p ";

                if(point == 0){
                    // maxX
                    if(op1->getVelocityX() < 0){
                        op1->setVelocityX(-op1->getVelocityX());
                    }
                }else if(point == 1){
                    // minX
                    if(op1->getVelocityX() > 0){
                        op1->setVelocityX(-op1->getVelocityX());
                    }
                }else if(point == 2){
                    // maxY
                    if(op1->getVelocityY() < 0){
                        op1->setVelocityY(-op1->getVelocityY());
                    }
                }else if(point == 3){
                    // minY
                    if(op1->getVelocityY() > 0){
                        op1->setVelocityY(-op1->getVelocityY());
                    }
                }else if(point == 4){
                    // maxZ
                    if(op1->getVelocityZ() < 0){
                        op1->setVelocityZ(-op1->getVelocityZ());
                    }
                }else if(point == 5){
                    // minZ
                    if(op1->getVelocityZ() > 0){
                        op1->setVelocityZ(-op1->getVelocityZ());
                    }
                }
                */
            }
        }
    }

	// Move
	for(int i = 0 ; i < pobjectsSphere.size() ; i++) {
		PhysicsSphere* op = pobjectsSphere.at(i);
		op->setX(op->getX() + op->getVelocityX()*delta);
		op->setY(op->getY() + op->getVelocityY()*delta);
		op->setZ(op->getZ() + op->getVelocityZ()*delta);
		//qDebug() << op->getVelocity();

	}
	this->msleep(pauseTickTime);
}

int PhysicsThread::getMiny() const
{
	return miny;
}

void PhysicsThread::setMiny(const int value)
{
	miny = value;
}

int PhysicsThread::getMinz() const
{
	return minz;
}

void PhysicsThread::setMinz(const int value)
{
	minz = value;
}

int PhysicsThread::getMaxx() const
{
	return maxx;
}

void PhysicsThread::setMaxx(const int value)
{
	maxx = value;
}

int PhysicsThread::getMaxy() const
{
	return maxy;
}

void PhysicsThread::setMaxy(const int value)
{
	maxy = value;
}

int PhysicsThread::getMaxz() const
{
	return maxz;
}

void PhysicsThread::setMaxz(const int value)
{
	maxz = value;
}

int PhysicsThread::getMinx() const
{
	return minx;
}

void PhysicsThread::setMinx(const int value)
{
	minx = value;
}

void PhysicsThread::registerPhysicsSphere(PhysicsSphere* physicsObject)
{
	pobjectsSphere.push_back(physicsObject);
}

void PhysicsThread::deregisterPhysicsSphere(PhysicsSphere* physicsObject)
{
	pobjectsSphere.erase(std::remove(pobjectsSphere.begin(), pobjectsSphere.end(),physicsObject), pobjectsSphere.end());
}

void PhysicsThread::registerPhysicsBox(PhysicsBox* physicsObject)
{
	pobjectsBox.push_back(physicsObject);
}

void PhysicsThread::deregisterPhysicsBox(PhysicsBox* physicsObject)
{
	pobjectsBox.erase(std::remove(pobjectsBox.begin(), pobjectsBox.end(),physicsObject), pobjectsBox.end());
}

<commit_msg>fixed Collision Shere vs Static Shere<commit_after>#include "PhysicsThread.h"
#include "PhysicsObject.h"
#include "Collision.h"
#include <cmath>
#include <vector>
#include <algorithm>
#include <iterator>
#include <QDebug>

PhysicsThread::PhysicsThread()
{
}

PhysicsThread::PhysicsThread(int minx ,int miny ,int minz ,int maxx ,int maxy ,int maxz)
{

	this->minx = minx;
	this->miny = miny;
	this->minz = minz;

	this->maxx = maxx;
	this->maxy = maxy;
	this->maxz = maxz;

}

PhysicsThread::~PhysicsThread()
{

}

void PhysicsThread::run(){
	qDebug() << "SUCCESSFULLY STARTED UP PHYSICS-SIMULATION";
	forever{
		mutex.lock();
		qDebug() << "RUNNING PHYSICS-SIMULATION";
		runSimulation(1.0/60.0);
		if(stop){
			break;
		}
		if(bPause){
			pauseManager.wait(&mutex);
		}
		mutex.unlock();
	}
}

void PhysicsThread::TogglePause()
{
	bPause = !bPause;
	if(!bPause){
		pauseManager.wakeAll();
	}
}

void PhysicsThread::pause()
{
	bPause = true;
}

void PhysicsThread::resume()
{
	bPause = false;
	pauseManager.wakeAll();
}

void PhysicsThread::quit()
{
	stop = true;
	QThread::quit();
	qDebug() << "STOPPING PHYSICS-THREAD";
}

void PhysicsThread::runSimulation(const double& delta){

	// Collision Border
	for(int i = 0 ; i < pobjectsSphere.size() ; i++) {

		PhysicsSphere* op = pobjectsSphere.at(i);
		if(op->getIsMovable()){
			// is Sphere TODO
			if(true){
				if(op->getX()-(op->getSize()) < minx ){
					if(op->getVelocityX() < 0){
						op->setVelocityX(-op->getVelocityX());
					}else{
						op->setVelocityX(op->getVelocityX());
					}
				}else if(op->getX()+(op->getSize()) > maxx) {
					if(op->getVelocityX() > 0){
						op->setVelocityX(-op->getVelocityX());
					}else{
						op->setVelocityX(op->getVelocityX());
					}
				}

				if(op->getY()-(op->getSize()) < miny){
					if(op->getVelocityY() < 0){
						op->setVelocityY(-op->getVelocityY() * op->getRemainingEnergy());
					}else{
						op->setVelocityY(op->getVelocityY());
					}
				}else{
					if(op->getY()+(op->getSize()) > maxy){
						if(op->getVelocityY() > 0){
							op->setVelocityY(-op->getVelocityY());
						}else{
							op->setVelocityY(op->getVelocityY());
						}
					}
					// Gravity
					op->setVelocityY(op->getVelocityY() + g*delta*op->getMass());
				}

				if(op->getZ()-(op->getSize()) < minz){
					if(op->getVelocityZ() < 0){
						op->setVelocityZ(-op->getVelocityZ());
					}else{
						op->setVelocityZ(op->getVelocityZ());
					}
				}else if(op->getZ()+(op->getSize()) > maxz){
					if(op->getVelocityZ() > 0){
						op->setVelocityZ(-op->getVelocityZ());
					}else{
						op->setVelocityZ(op->getVelocityZ());
					}
				}
			}
		}
	}

	// Collision Sphere on Sphere
	for(int i = 0 ; i < pobjectsSphere.size() ; i++) {
		PhysicsSphere* op1 = pobjectsSphere.at(i);
		for(int j = i ; j < pobjectsSphere.size() ; j++) {
			PhysicsSphere* op2 = pobjectsSphere.at(j);

			// bool Collision::SphereVersusSphere(const int& x1 , const int& y1 , const int& z1 , const int& size1 , const int& x2 , const int& y2 , const int& z2 , const int& size2)
			// Sphere on Sphere
			// SIZE
			if(i != j && Collision::SphereVersusSphere(op1->getX() ,op1->getY() ,op1->getZ() ,op1->getSize() ,op2->getX() ,op2->getY() ,op2->getZ() ,op2->getSize())){

				double tempX (op1->getX() - op2->getX());
				double tempY (op1->getY() - op2->getY());
				double tempZ (op1->getZ() - op2->getZ());

				double norm = sqrt(tempX*tempX + tempY*tempY + tempZ*tempZ);

				tempX = tempX / norm;
				tempY = tempY / norm;
				tempZ = tempZ / norm;

				double a1 = (op1->getVelocityX() * tempX) + (op1->getVelocityY() * tempY) + (op1->getVelocityZ() * tempZ);
				double a2 = (op2->getVelocityX() * tempX) + (op2->getVelocityY() * tempY) + (op2->getVelocityZ() * tempZ);

				// double optimizedP = (2.0D * (a1 - a2)) / (e1.getWhight() + e2.getWhight());

				double optimizedP = (2.0 * (a1 - a2)) / (op1->getMass() + op2->getMass());

				// fix
				optimizedP = std::abs(optimizedP);

				qDebug() << optimizedP;

				// 0.9 Verlusst
				if(op1->getIsMovable()){
					op1->setVelocityX( op1->getVelocityX() + (optimizedP * op2->getMass() * tempX) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
					op1->setVelocityY( op1->getVelocityY() + (optimizedP * op2->getMass() * tempY) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
					op1->setVelocityZ( op1->getVelocityZ() + (optimizedP * op2->getMass() * tempZ) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
				}

				if(op2->getIsMovable()){
					op2->setVelocityX( op2->getVelocityX() - (optimizedP * op1->getMass() * tempX) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
					op2->setVelocityY( op2->getVelocityY() - (optimizedP * op1->getMass() * tempY) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
					op2->setVelocityZ( op2->getVelocityZ() - (optimizedP * op1->getMass() * tempZ) * (op1->getRemainingEnergy()*op2->getRemainingEnergy()));
				}

				// TODO
				qDebug() << op1->getPosition() << "BEFORE";
                if(!op1->getIsMovable() && op2->getIsMovable){
                    op2->setX(op2->getX() - op1->getVelocityX() * delta);
                    op2->setY(op2->getY() - op1->getVelocityY() * delta);
                    op2->setZ(op2->getZ() - op1->getVelocityZ() * delta);

                    op1->setVelocityX(0.0);
                    op1->setVelocityY(0.0);
                    op1->setVelocityZ(0.0);

                }else if(op1->getIsMovable() && !op2->getIsMovable){
                    op1->setX(op1->getX() - op2->getVelocityX() * delta);
                    op1->setY(op1->getY() - op2->getVelocityY() * delta);
                    op1->setZ(op1->getZ() - op2->getVelocityZ() * delta);

                    op2->setVelocityX(0.0);
                    op2->setVelocityY(0.0);
                    op2->setVelocityZ(0.0);
                }

				op1->setX(op1->getX() + op1->getVelocityX() * delta);
				op1->setY(op1->getY() + op1->getVelocityY() * delta);
				op1->setZ(op1->getZ() + op1->getVelocityZ() * delta);

				op2->setX(op2->getX() + op2->getVelocityX() * delta);
				op2->setY(op2->getY() + op2->getVelocityY() * delta);
				op2->setZ(op2->getZ() + op2->getVelocityZ() * delta);
				qDebug() << op1->getPosition() << "AFTER";
			}
		}
	}

//	// Collision Shere on Box
//	// bool Collision::SphereVersusBox
//	//(const int& sphereX ,const int& sphereY ,const int& sphereZ ,const int& sphereSize
//	// ,const int& boxMinX ,const int& boxMinY ,const int& boxMinZ ,const int& boxMaxX ,const int& boxMaxY ,const int& boxMaxZ)

    for(int i = 0 ; i < pobjectsSphere.size() ; i++) {
        PhysicsSphere* op1 = pobjectsSphere.at(i);
        for(int j = 0 ; j < pobjectsBox.size() ; j++) {
            PhysicsBox* op2 = pobjectsBox.at(j);

            if(Collision::SphereVersusBox( op1->getX() ,op1->getY() ,op1->getZ() ,op1->getSize() ,op2->getMinX()+op2->getX() ,op2->getMinY()+op2->getY() ,op2->getMinZ()+op2->getZ() ,op2->getMaxX()+op2->getX() ,op2->getMaxY()+op2->getY() ,op2->getMaxZ()+op2->getZ())){

                qDebug() << "Test";

                if((op1->getX()+op1->getSize()) > op2->getMinX() && op1->getX() < op2->getMinX()+op2->getX()){

                    if(op1->getVelocityX() > 0){
                        op1->setVelocityX(-op1->getVelocityX());
                    }
                }
                if((op1->getX()-op1->getSize()) < op2->getMaxX() && op1->getX() > op2->getMaxX()+op2->getX()){
                    if(op1->getVelocityX() < 0){
                        op1->setVelocityX(-op1->getVelocityX());
                    }
                }

                if((op1->getY()+op1->getSize()) > op2->getMinY() && op1->getY() < op2->getMinY()+op2->getY()){
                    if(op1->getVelocityY() > 0){
                        op1->setVelocityY(-op1->getVelocityY());
                    }
                }
                if((op1->getY()-op1->getSize()) < op2->getMaxY() && op1->getY() > op2->getMaxY()+op2->getY()){

                    if(op1->getVelocityY() < 0){
                        op1->setVelocityY(-op1->getVelocityY());
                    }
                }

                if((op1->getZ()+op1->getSize()) > op2->getMinZ() && op1->getZ() < op2->getMinZ()+op2->getZ()){
                    if(op1->getVelocityZ() > 0){
                        op1->setVelocityZ(-op1->getVelocityZ());
                    }
                }
                if((op1->getZ()-op1->getSize()) < op2->getMaxZ() && op1->getZ() > op2->getMaxZ()+op2->getZ()){
                    if(op1->getVelocityZ() < 0){
                        op1->setVelocityZ(-op1->getVelocityZ());
                    }
                }
            }
        }
    }

	// Move
	for(int i = 0 ; i < pobjectsSphere.size() ; i++) {
		PhysicsSphere* op = pobjectsSphere.at(i);
		op->setX(op->getX() + op->getVelocityX()*delta);
		op->setY(op->getY() + op->getVelocityY()*delta);
		op->setZ(op->getZ() + op->getVelocityZ()*delta);
		//qDebug() << op->getVelocity();

	}
	this->msleep(pauseTickTime);
}

int PhysicsThread::getMiny() const
{
	return miny;
}

void PhysicsThread::setMiny(const int value)
{
	miny = value;
}

int PhysicsThread::getMinz() const
{
	return minz;
}

void PhysicsThread::setMinz(const int value)
{
	minz = value;
}

int PhysicsThread::getMaxx() const
{
	return maxx;
}

void PhysicsThread::setMaxx(const int value)
{
	maxx = value;
}

int PhysicsThread::getMaxy() const
{
	return maxy;
}

void PhysicsThread::setMaxy(const int value)
{
	maxy = value;
}

int PhysicsThread::getMaxz() const
{
	return maxz;
}

void PhysicsThread::setMaxz(const int value)
{
	maxz = value;
}

int PhysicsThread::getMinx() const
{
	return minx;
}

void PhysicsThread::setMinx(const int value)
{
	minx = value;
}

void PhysicsThread::registerPhysicsSphere(PhysicsSphere* physicsObject)
{
	pobjectsSphere.push_back(physicsObject);
}

void PhysicsThread::deregisterPhysicsSphere(PhysicsSphere* physicsObject)
{
	pobjectsSphere.erase(std::remove(pobjectsSphere.begin(), pobjectsSphere.end(),physicsObject), pobjectsSphere.end());
}

void PhysicsThread::registerPhysicsBox(PhysicsBox* physicsObject)
{
	pobjectsBox.push_back(physicsObject);
}

void PhysicsThread::deregisterPhysicsBox(PhysicsBox* physicsObject)
{
	pobjectsBox.erase(std::remove(pobjectsBox.begin(), pobjectsBox.end(),physicsObject), pobjectsBox.end());
}

<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"

#include <Eigen/CXX11/Tensor>

using Eigen::Tensor;
using Eigen::TensorMap;

static void test_assign()
{
  std::string data1[6];
  TensorMap<Tensor<std::string, 2>> mat1(data1, 2, 3);
  std::string data2[6];
  const TensorMap<Tensor<const std::string, 2>> mat2(data2, 2, 3);

  for (int i = 0; i < 6; ++i) {
    std::ostringstream s1;
    s1 << "abc" << i*3;
    data1[i] = s1.str();
    std::ostringstream s2;
    s2 << "def" << i*5;
    data2[i] = s2.str();
  }

  Tensor<std::string, 2> rslt1;
  rslt1 = mat1;
  Tensor<std::string, 2> rslt2;
  rslt2 = mat2;

  Tensor<std::string, 2> rslt3 = mat1;
  Tensor<std::string, 2> rslt4 = mat2;

  Tensor<std::string, 2> rslt5(mat1);
  Tensor<std::string, 2> rslt6(mat2);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      VERIFY_IS_EQUAL(rslt1(i,j), data1[i+2*j]);
      VERIFY_IS_EQUAL(rslt2(i,j), data2[i+2*j]);
      VERIFY_IS_EQUAL(rslt3(i,j), data1[i+2*j]);
      VERIFY_IS_EQUAL(rslt4(i,j), data2[i+2*j]);
      VERIFY_IS_EQUAL(rslt5(i,j), data1[i+2*j]);
      VERIFY_IS_EQUAL(rslt6(i,j), data2[i+2*j]);
    }
  }
}

static void test_concat()
{
  Tensor<std::string, 2> t1(2, 3);
  Tensor<std::string, 2> t2(2, 3);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      std::ostringstream s1;
      s1 << "abc" << i + j*2;
      t1(i, j) = s1.str();
      std::ostringstream s2;
      s2 << "def" << i*5 + j*32;
      t2(i, j) = s2.str();
    }
  }

  Tensor<std::string, 2> result = t1.concatenate(t2, 1);
  VERIFY_IS_EQUAL(result.dimension(0), 2);
  VERIFY_IS_EQUAL(result.dimension(1), 6);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      VERIFY_IS_EQUAL(result(i, j),   t1(i, j));
      VERIFY_IS_EQUAL(result(i, j+3), t2(i, j));
    }
  }
}

static void test_slices()
{
  Tensor<std::string, 2> data(2, 6);
  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      std::ostringstream s1;
      s1 << "abc" << i + j*2;
      data(i, j) = s1.str();
    }
  }

  const Eigen::DSizes<ptrdiff_t, 2> half_size{{2, 3}};
  const Eigen::DSizes<ptrdiff_t, 2> first_half{{0, 0}};
  const Eigen::DSizes<ptrdiff_t, 2> second_half{{0, 3}};

  Tensor<std::string, 2> t1 = data.slice(first_half, half_size);
  Tensor<std::string, 2> t2 = data.slice(second_half, half_size);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      VERIFY_IS_EQUAL(data(i, j),   t1(i, j));
      VERIFY_IS_EQUAL(data(i, j+3), t2(i, j));
    }
  }
}

static void test_additions()
{
  Tensor<std::string, 1> data1(3);
  Tensor<std::string, 1> data2(3);
  for (int i = 0; i < 3; ++i) {
    data1(i) = "abc";
    std::ostringstream s1;
    s1 << i;
    data2(i) = s1.str();
  }

  Tensor<std::string, 1> sum = data1 + data2;
  for (int i = 0; i < 3; ++i) {
    std::ostringstream concat;
    concat << "abc" << i;
    std::string expected = concat.str();
    VERIFY_IS_EQUAL(sum(i), expected);
  }
}

static void test_initialization()
{
  Tensor<std::string, 2> a(2, 3);
  a.setConstant(std::string("foo"));
  for (int i = 0; i < 2*3; ++i) {
    VERIFY_IS_EQUAL(a(i), std::string("foo"));
  }
}

void test_cxx11_tensor_of_strings()
{
  // Beware: none of this is likely to ever work on a GPU.
  CALL_SUBTEST(test_assign());
  CALL_SUBTEST(test_concat());
  CALL_SUBTEST(test_slices());
  CALL_SUBTEST(test_additions());
  CALL_SUBTEST(test_initialization());
}
<commit_msg>Fixed compilation warnings<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"

#include <Eigen/CXX11/Tensor>

using Eigen::Tensor;
using Eigen::TensorMap;

static void test_assign()
{
  std::string data1[6];
  TensorMap<Tensor<std::string, 2>> mat1(data1, 2, 3);
  std::string data2[6];
  const TensorMap<Tensor<const std::string, 2>> mat2(data2, 2, 3);

  for (int i = 0; i < 6; ++i) {
    std::ostringstream s1;
    s1 << "abc" << i*3;
    data1[i] = s1.str();
    std::ostringstream s2;
    s2 << "def" << i*5;
    data2[i] = s2.str();
  }

  Tensor<std::string, 2> rslt1;
  rslt1 = mat1;
  Tensor<std::string, 2> rslt2;
  rslt2 = mat2;

  Tensor<std::string, 2> rslt3 = mat1;
  Tensor<std::string, 2> rslt4 = mat2;

  Tensor<std::string, 2> rslt5(mat1);
  Tensor<std::string, 2> rslt6(mat2);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      VERIFY_IS_EQUAL(rslt1(i,j), data1[i+2*j]);
      VERIFY_IS_EQUAL(rslt2(i,j), data2[i+2*j]);
      VERIFY_IS_EQUAL(rslt3(i,j), data1[i+2*j]);
      VERIFY_IS_EQUAL(rslt4(i,j), data2[i+2*j]);
      VERIFY_IS_EQUAL(rslt5(i,j), data1[i+2*j]);
      VERIFY_IS_EQUAL(rslt6(i,j), data2[i+2*j]);
    }
  }
}

static void test_concat()
{
  Tensor<std::string, 2> t1(2, 3);
  Tensor<std::string, 2> t2(2, 3);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      std::ostringstream s1;
      s1 << "abc" << i + j*2;
      t1(i, j) = s1.str();
      std::ostringstream s2;
      s2 << "def" << i*5 + j*32;
      t2(i, j) = s2.str();
    }
  }

  Tensor<std::string, 2> result = t1.concatenate(t2, 1);
  VERIFY_IS_EQUAL(result.dimension(0), 2);
  VERIFY_IS_EQUAL(result.dimension(1), 6);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      VERIFY_IS_EQUAL(result(i, j),   t1(i, j));
      VERIFY_IS_EQUAL(result(i, j+3), t2(i, j));
    }
  }
}

static void test_slices()
{
  Tensor<std::string, 2> data(2, 6);
  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      std::ostringstream s1;
      s1 << "abc" << i + j*2;
      data(i, j) = s1.str();
    }
  }

  const Eigen::DSizes<ptrdiff_t, 2> half_size(2, 3);
  const Eigen::DSizes<ptrdiff_t, 2> first_half(0, 0);
  const Eigen::DSizes<ptrdiff_t, 2> second_half(0, 3);

  Tensor<std::string, 2> t1 = data.slice(first_half, half_size);
  Tensor<std::string, 2> t2 = data.slice(second_half, half_size);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      VERIFY_IS_EQUAL(data(i, j),   t1(i, j));
      VERIFY_IS_EQUAL(data(i, j+3), t2(i, j));
    }
  }
}

static void test_additions()
{
  Tensor<std::string, 1> data1(3);
  Tensor<std::string, 1> data2(3);
  for (int i = 0; i < 3; ++i) {
    data1(i) = "abc";
    std::ostringstream s1;
    s1 << i;
    data2(i) = s1.str();
  }

  Tensor<std::string, 1> sum = data1 + data2;
  for (int i = 0; i < 3; ++i) {
    std::ostringstream concat;
    concat << "abc" << i;
    std::string expected = concat.str();
    VERIFY_IS_EQUAL(sum(i), expected);
  }
}

static void test_initialization()
{
  Tensor<std::string, 2> a(2, 3);
  a.setConstant(std::string("foo"));
  for (int i = 0; i < 2*3; ++i) {
    VERIFY_IS_EQUAL(a(i), std::string("foo"));
  }
}

void test_cxx11_tensor_of_strings()
{
  // Beware: none of this is likely to ever work on a GPU.
  CALL_SUBTEST(test_assign());
  CALL_SUBTEST(test_concat());
  CALL_SUBTEST(test_slices());
  CALL_SUBTEST(test_additions());
  CALL_SUBTEST(test_initialization());
}
<|endoftext|>


<commit_before>// @(#)root/gui:$Name:  $:$Id: TGuiBuilder.cxx,v 1.7 2006/05/26 09:16:29 brun Exp $
// Author: Valeriy Onuchin   12/08/04

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//
// TGuiBuilder
//
//
//  ************************************************
//                ROOT GUI Builder principles
//  ************************************************
//
//  With the GUI builder, we try to make the next step from WYSIWYG
//  to embedded editing concept - WYSIWYE ("what you see is what you edit").
//  The ROOT GUI Builder allows modifying real GUI objects.
//  For example, one can edit the existing GUI application $ROOTSYS/tutorials/guitest.C.
//  GUI components can be added to a design area from a widget palette,
//  or can be borrowed from another application.
//  One can drag and and drop TCanvas's menu bar into the application.
//  GUI objects can be resized and dragged, copied and pasted.
//  ROOT GUI Builder allows changing the layout, snap to grid, change object's
//  layout order via the GUI Builder toolbar, or by options in the right-click
//  context menus.
//  A final design can be immediatly tested and used, or saved as a C++ macro.
//  For example, it's possible to rearrange buttons in control bar,
//  add separators etc. and continue to use a new fancy control bar in the
//  application.
//
//  ************************************************
//
//  The following is a short description of the GUI Builder actions and key shortcuts:
//
//   o Press Ctrl-Double-Click to start/stop edit mode
//   o Press Double-Click to activate quick edit action (defined in root.mimes)
//
//                 Selection, grabbing, dropping
//       ************************************************
//    It is possible to select, drag any frame and drop it to any frame
//
//   o Click left mouse button or Ctrl-Click to select an object to edit.
//   o Press right mouse button to activate context menu
//   o Mutiple selection (grabbing):
//      - draw lasso and press Return key
//      - press Shift key and draw lasso
//   o Dropping:
//      - select frame and press Ctrl-Return key
//   o Changing layout order:
//      - select frame and use arrow keys to change layout order
//   o Alignment:
//      - draw lasso and press arrow keys (or Shift-Arrow key) to align frames
//
//                    Key shortcuts
//       ************************************************
//   o Return      - grab selected frames
//   o Ctrl-Return - drop frames
//   o Del         - delete selected frame
//   o Shift-Del   - crop action
//   o Ctrl-X      - cut action
//   o Ctrl-C      - copy action
//   o Ctrl-V      - paste action
//   o Ctrl-R      - replace action
//   o Ctrl-L      - compact layout
//   o Ctrl-B      - break layout
//   o Ctrl-H      - switch horizontal-vertical layout
//   o Ctrl-G      - switch on/off grid
//   o Ctrl-S      - save action
//   o Ctrl-O      - open and execute a ROOT macro file. GUI components created
//                   after macro execution will be emebedded to currently edited
//                   design area.
//   o Ctrl-N      - create new main frame
//
//Begin_Html
/*

*/
//End_Html

#include "TGuiBuilder.h"
#include "TVirtualDragManager.h"
#include "TPluginManager.h"
#include "TROOT.h"

ClassImp(TGuiBuilder)
ClassImp(TGuiBldAction)

TGuiBuilder *gGuiBuilder = 0;
static TPluginHandler *gHandler = 0;

//______________________________________________________________________________
TGuiBldAction::TGuiBldAction(const char *name, const char *title,
               Int_t type,  TGLayoutHints *hints) :
   TNamed(name, title), fType(type), fHints(hints)
{
   // constructor

   fPicture = 0;
   fPic = 0;
   fAct = "";
}

//______________________________________________________________________________
TGuiBldAction::~TGuiBldAction()
{
   // destructor
}

//______________________________________________________________________________
TGuiBuilder::TGuiBuilder()
{
   // constructor

   // load plugin
   if (!gGuiBuilder) {
      gHandler = gROOT->GetPluginManager()->FindHandler("TGuiBuilder");

      if (!gHandler || (gHandler->LoadPlugin() == -1)) return;

      gGuiBuilder = this;
      gHandler->ExecPlugin(0);
   } else {
      fAction      = 0;
      gGuiBuilder->Show();
   }
}

//______________________________________________________________________________
TGuiBuilder::~TGuiBuilder()
{
   // destructor
}

//______________________________________________________________________________
TGuiBuilder *TGuiBuilder::Instance()
{
   // return an instance of TGuiBuilder object

   return (gGuiBuilder? gGuiBuilder : new TGuiBuilder());
}
<commit_msg>Change comments according to the new $ROOTSYS/tutorials structure.<commit_after>// @(#)root/gui:$Name:  $:$Id: TGuiBuilder.cxx,v 1.8 2006/05/28 20:08:00 brun Exp $
// Author: Valeriy Onuchin   12/08/04

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//
// TGuiBuilder
//
//
//  ************************************************
//                ROOT GUI Builder principles
//  ************************************************
//
//  With the GUI builder, we try to make the next step from WYSIWYG
//  to embedded editing concept - WYSIWYE ("what you see is what you edit").
//  The ROOT GUI Builder allows modifying real GUI objects.
//  For example, one can edit the existing GUI application created by
//  $ROOTSYS/tutorials/gui/guitest.C.
//  GUI components can be added to a design area from a widget palette,
//  or can be borrowed from another application.
//  One can drag and and drop TCanvas's menu bar into the application.
//  GUI objects can be resized and dragged, copied and pasted.
//  ROOT GUI Builder allows changing the layout, snap to grid, change object's
//  layout order via the GUI Builder toolbar, or by options in the right-click
//  context menus.
//  A final design can be immediatly tested and used, or saved as a C++ macro.
//  For example, it's possible to rearrange buttons in control bar,
//  add separators etc. and continue to use a new fancy control bar in the
//  application.
//
//  ************************************************
//
//  The following is a short description of the GUI Builder actions and key shortcuts:
//
//   o Press Ctrl-Double-Click to start/stop edit mode
//   o Press Double-Click to activate quick edit action (defined in root.mimes)
//
//                 Selection, grabbing, dropping
//       ************************************************
//    It is possible to select, drag any frame and drop it to any frame
//
//   o Click left mouse button or Ctrl-Click to select an object to edit.
//   o Press right mouse button to activate context menu
//   o Mutiple selection (grabbing):
//      - draw lasso and press Return key
//      - press Shift key and draw lasso
//   o Dropping:
//      - select frame and press Ctrl-Return key
//   o Changing layout order:
//      - select frame and use arrow keys to change layout order
//   o Alignment:
//      - draw lasso and press arrow keys (or Shift-Arrow key) to align frames
//
//                    Key shortcuts
//       ************************************************
//   o Return      - grab selected frames
//   o Ctrl-Return - drop frames
//   o Del         - delete selected frame
//   o Shift-Del   - crop action
//   o Ctrl-X      - cut action
//   o Ctrl-C      - copy action
//   o Ctrl-V      - paste action
//   o Ctrl-R      - replace action
//   o Ctrl-L      - compact layout
//   o Ctrl-B      - break layout
//   o Ctrl-H      - switch horizontal-vertical layout
//   o Ctrl-G      - switch on/off grid
//   o Ctrl-S      - save action
//   o Ctrl-O      - open and execute a ROOT macro file. GUI components created
//                   after macro execution will be emebedded to currently edited
//                   design area.
//   o Ctrl-N      - create new main frame
//
//Begin_Html
/*

*/
//End_Html

#include "TGuiBuilder.h"
#include "TVirtualDragManager.h"
#include "TPluginManager.h"
#include "TROOT.h"

ClassImp(TGuiBuilder)
ClassImp(TGuiBldAction)

TGuiBuilder *gGuiBuilder = 0;
static TPluginHandler *gHandler = 0;

//______________________________________________________________________________
TGuiBldAction::TGuiBldAction(const char *name, const char *title,
               Int_t type,  TGLayoutHints *hints) :
   TNamed(name, title), fType(type), fHints(hints)
{
   // constructor

   fPicture = 0;
   fPic = 0;
   fAct = "";
}

//______________________________________________________________________________
TGuiBldAction::~TGuiBldAction()
{
   // destructor
}

//______________________________________________________________________________
TGuiBuilder::TGuiBuilder()
{
   // constructor

   // load plugin
   if (!gGuiBuilder) {
      gHandler = gROOT->GetPluginManager()->FindHandler("TGuiBuilder");

      if (!gHandler || (gHandler->LoadPlugin() == -1)) return;

      gGuiBuilder = this;
      gHandler->ExecPlugin(0);
   } else {
      fAction      = 0;
      gGuiBuilder->Show();
   }
}

//______________________________________________________________________________
TGuiBuilder::~TGuiBuilder()
{
   // destructor
}

//______________________________________________________________________________
TGuiBuilder *TGuiBuilder::Instance()
{
   // return an instance of TGuiBuilder object

   return (gGuiBuilder? gGuiBuilder : new TGuiBuilder());
}
<|endoftext|>