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

#include "buffered_stream_def.hpp"

#include "basic_buffered_stream.hpp"
#include "double_buffered_stream.hpp"

#endif  // BUFFERED_STREAM_HPP_
<commit_msg>Added mutex based double buffer.  Significantly reduces overhead.<commit_after>//   Copyright 2015 Patrick Putnam
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
#ifndef BUFFERED_STREAM_HPP_
#define BUFFERED_STREAM_HPP_

#include "buffered_stream_def.hpp"

#include "basic_buffered_stream.hpp"
#include "double_buffered_stream.hpp"
#include "double_buffered_mutex_stream.hpp"

#endif  // BUFFERED_STREAM_HPP_
<|endoftext|>


<commit_before><commit_msg>No need to use += to initialize m_aFileRoot.<commit_after><|endoftext|>


<commit_before>#include <boost/python/class.hpp>
#include "HopfieldServer_wrap.h"
#include <examples/hopfield/HopfieldServer.h>

using namespace boost::python;
using namespace opencog;

void init_HopfieldServer_py()
{
    class_<HopfieldServer>("HopfieldServer")
    ;
}
<commit_msg>Based HopfieldServer from CogServer, and exposed derivedCreateInstance() method.<commit_after>#include <boost/python/class.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/manage_new_object.hpp>
#include "HopfieldServer_wrap.h"
#include <examples/hopfield/HopfieldServer.h>
#include <opencog/server/CogServer.h>

using namespace boost::python;
using namespace opencog;

void init_HopfieldServer_py()
{
    class_<HopfieldServer, bases<CogServer> >("HopfieldServer")
        .def("derivedCreateInstance",
            &HopfieldServer::derivedCreateInstance,
            return_value_policy<manage_new_object>())
        .staticmethod("derivedCreateInstance")
    ;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: client.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: ihi $ $Date: 2007-04-19 09:23:04 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

// INCLUDE ---------------------------------------------------------------

#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_NOVISUALAREASIZEEXCEPTION_HPP_
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#endif

#include <toolkit/helper/vclunohelper.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sot/sotref.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <svx/svdograf.hxx>
#include <svtools/embedhlp.hxx>

#include "client.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"

using namespace com::sun::star;

//------------------------------------------------------------------------

ScClient::ScClient( ScTabViewShell* pViewShell, Window* pDraw, SdrModel* pSdrModel, SdrOle2Obj* pObj ) :
    SfxInPlaceClient( pViewShell, pDraw, pObj->GetAspect() ),
    pModel( pSdrModel ),
    pGrafEdit( 0 )
{
    SetObject( pObj->GetObjRef() );
}

__EXPORT ScClient::~ScClient()
{
}

SdrOle2Obj* ScClient::GetDrawObj()
{
    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();
    SdrOle2Obj* pOle2Obj = NULL;
    String aName = GetViewShell()->GetObjectShell()->GetEmbeddedObjectContainer().GetEmbeddedObjectName( xObj );

    USHORT nPages = pModel->GetPageCount();
    for (USHORT nPNr=0; nPNr<nPages && !pOle2Obj; nPNr++)
    {
        SdrPage* pPage = pModel->GetPage(nPNr);
        SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
        SdrObject* pObject = aIter.Next();
        while (pObject && !pOle2Obj)
        {
            if ( pObject->GetObjIdentifier() == OBJ_OLE2 )
            {
                // name from InfoObject is PersistName
                if ( ((SdrOle2Obj*)pObject)->GetPersistName() == aName )
                    pOle2Obj = (SdrOle2Obj*)pObject;
            }
            pObject = aIter.Next();
        }
    }
    return pOle2Obj;
}

void __EXPORT ScClient::RequestNewObjectArea( Rectangle& aLogicRect )
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    Rectangle aOldRect = GetObjArea();
    SdrOle2Obj*  pDrawObj = GetDrawObj();
    if ( pDrawObj )
    {
        if ( pDrawObj->IsResizeProtect() )
            aLogicRect.SetSize( aOldRect.GetSize() );

        if ( pDrawObj->IsMoveProtect() )
            aLogicRect.SetPos( aOldRect.TopLeft() );
    }

    USHORT nTab = pViewSh->GetViewData()->GetTabNo();
    SdrPage* pPage = pModel->GetPage(static_cast<sal_uInt16>(static_cast<sal_Int16>(nTab)));
    if ( pPage && aLogicRect != aOldRect )
    {
        Point aPos;
        Size aSize = pPage->GetSize();
        if ( aSize.Width() < 0 )
        {
            aPos.X() = aSize.Width() + 1;       // negative
            aSize.Width() = -aSize.Width();     // positive
        }
        Rectangle aPageRect( aPos, aSize );

        if (aLogicRect.Right() > aPageRect.Right())
        {
            long nDiff = aLogicRect.Right() - aPageRect.Right();
            aLogicRect.Left() -= nDiff;
            aLogicRect.Right() -= nDiff;
        }
        if (aLogicRect.Bottom() > aPageRect.Bottom())
        {
            long nDiff = aLogicRect.Bottom() - aPageRect.Bottom();
            aLogicRect.Top() -= nDiff;
            aLogicRect.Bottom() -= nDiff;
        }

        if (aLogicRect.Left() < aPageRect.Left())
        {
            long nDiff = aLogicRect.Left() - aPageRect.Left();
            aLogicRect.Right() -= nDiff;
            aLogicRect.Left() -= nDiff;
        }
        if (aLogicRect.Top() < aPageRect.Top())
        {
            long nDiff = aLogicRect.Top() - aPageRect.Top();
            aLogicRect.Bottom() -= nDiff;
            aLogicRect.Top() -= nDiff;
        }
    }
}

void __EXPORT ScClient::ObjectAreaChanged()
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    //  Position und Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        pDrawObj->SetLogicRect( GetScaledObjArea() );

        //  set document modified (SdrModel::SetChanged is not used)
        // TODO/LATER: is there a reason that this code is not executed in Draw?
//        SfxViewShell* pSfxViewSh = GetViewShell();
//        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
    }

    if (pDrawObj)
        pViewSh->ScrollToObject( pDrawObj );
}

void __EXPORT ScClient::ViewChanged()
{
    if ( GetAspect() == embed::Aspects::MSOLE_ICON )
    {
        // the iconified object seems not to need such a scaling handling
        // since the replacement image and the size a completely controlled by the container
        // TODO/LATER: when the icon exchange is implemented the scaling handling might be required again here

        return;
    }

    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();

    // TODO/LEAN: working with Visual Area can switch object to running state
    awt::Size aSz;
    try {
        aSz = xObj->getVisualAreaSize( GetAspect() );
    } catch ( embed::NoVisualAreaSizeException& )
    {
        DBG_ERROR("The visual area size must be available!\n");
    }

    MapUnit aMapUnit = VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( GetAspect() ) );
    Size aVisSize = OutputDevice::LogicToLogic( Size( aSz.Width, aSz.Height ), aMapUnit, MAP_100TH_MM );

    //  Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        Rectangle aLogicRect = pDrawObj->GetLogicRect();
        Fraction aFractX = GetScaleWidth();
        Fraction aFractY = GetScaleHeight();
        aFractX *= aVisSize.Width();
        aFractY *= aVisSize.Height();
        aVisSize = Size( (long) aFractX, (long) aFractY );      // skaliert fuer Draw-Model

        //  pClientData->SetObjArea vor pDrawObj->SetLogicRect, damit keine
        //  falschen Skalierungen ausgerechnet werden:
        //Rectangle aObjArea = aLogicRect;
        //aObjArea.SetSize( aVisSize );          // Dokument-Groesse vom Server
        //SetObjArea( aObjArea );

        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if ( pViewSh )
        {
            Window* pWin = pViewSh->GetActiveWin();
            if ( pWin->LogicToPixel( aVisSize ) != pWin->LogicToPixel( aLogicRect.GetSize() ) )
            {
                aLogicRect.SetSize( aVisSize );
                pDrawObj->SetLogicRect( aLogicRect );

                //  set document modified (SdrModel::SetChanged is not used)
                pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
            }
        }
    }
}

void __EXPORT ScClient::MakeVisible()
{
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->ScrollToObject( pDrawObj );
    }
}

<commit_msg>INTEGRATION: CWS changefileheader (1.19.302); FILE MERGED 2008/04/01 12:36:38 thb 1.19.302.2: #i85898# Stripping all external header guards 2008/03/31 17:15:09 rt 1.19.302.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: client.cxx,v $
 * $Revision: 1.20 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

// INCLUDE ---------------------------------------------------------------

#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>

#include <toolkit/helper/vclunohelper.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sot/sotref.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <svx/svdograf.hxx>
#include <svtools/embedhlp.hxx>

#include "client.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"

using namespace com::sun::star;

//------------------------------------------------------------------------

ScClient::ScClient( ScTabViewShell* pViewShell, Window* pDraw, SdrModel* pSdrModel, SdrOle2Obj* pObj ) :
    SfxInPlaceClient( pViewShell, pDraw, pObj->GetAspect() ),
    pModel( pSdrModel ),
    pGrafEdit( 0 )
{
    SetObject( pObj->GetObjRef() );
}

__EXPORT ScClient::~ScClient()
{
}

SdrOle2Obj* ScClient::GetDrawObj()
{
    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();
    SdrOle2Obj* pOle2Obj = NULL;
    String aName = GetViewShell()->GetObjectShell()->GetEmbeddedObjectContainer().GetEmbeddedObjectName( xObj );

    USHORT nPages = pModel->GetPageCount();
    for (USHORT nPNr=0; nPNr<nPages && !pOle2Obj; nPNr++)
    {
        SdrPage* pPage = pModel->GetPage(nPNr);
        SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
        SdrObject* pObject = aIter.Next();
        while (pObject && !pOle2Obj)
        {
            if ( pObject->GetObjIdentifier() == OBJ_OLE2 )
            {
                // name from InfoObject is PersistName
                if ( ((SdrOle2Obj*)pObject)->GetPersistName() == aName )
                    pOle2Obj = (SdrOle2Obj*)pObject;
            }
            pObject = aIter.Next();
        }
    }
    return pOle2Obj;
}

void __EXPORT ScClient::RequestNewObjectArea( Rectangle& aLogicRect )
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    Rectangle aOldRect = GetObjArea();
    SdrOle2Obj*  pDrawObj = GetDrawObj();
    if ( pDrawObj )
    {
        if ( pDrawObj->IsResizeProtect() )
            aLogicRect.SetSize( aOldRect.GetSize() );

        if ( pDrawObj->IsMoveProtect() )
            aLogicRect.SetPos( aOldRect.TopLeft() );
    }

    USHORT nTab = pViewSh->GetViewData()->GetTabNo();
    SdrPage* pPage = pModel->GetPage(static_cast<sal_uInt16>(static_cast<sal_Int16>(nTab)));
    if ( pPage && aLogicRect != aOldRect )
    {
        Point aPos;
        Size aSize = pPage->GetSize();
        if ( aSize.Width() < 0 )
        {
            aPos.X() = aSize.Width() + 1;       // negative
            aSize.Width() = -aSize.Width();     // positive
        }
        Rectangle aPageRect( aPos, aSize );

        if (aLogicRect.Right() > aPageRect.Right())
        {
            long nDiff = aLogicRect.Right() - aPageRect.Right();
            aLogicRect.Left() -= nDiff;
            aLogicRect.Right() -= nDiff;
        }
        if (aLogicRect.Bottom() > aPageRect.Bottom())
        {
            long nDiff = aLogicRect.Bottom() - aPageRect.Bottom();
            aLogicRect.Top() -= nDiff;
            aLogicRect.Bottom() -= nDiff;
        }

        if (aLogicRect.Left() < aPageRect.Left())
        {
            long nDiff = aLogicRect.Left() - aPageRect.Left();
            aLogicRect.Right() -= nDiff;
            aLogicRect.Left() -= nDiff;
        }
        if (aLogicRect.Top() < aPageRect.Top())
        {
            long nDiff = aLogicRect.Top() - aPageRect.Top();
            aLogicRect.Bottom() -= nDiff;
            aLogicRect.Top() -= nDiff;
        }
    }
}

void __EXPORT ScClient::ObjectAreaChanged()
{
    SfxViewShell* pSfxViewSh = GetViewShell();
    ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
    if (!pViewSh)
    {
        DBG_ERROR("Wrong ViewShell");
        return;
    }

    //  Position und Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        pDrawObj->SetLogicRect( GetScaledObjArea() );

        //  set document modified (SdrModel::SetChanged is not used)
        // TODO/LATER: is there a reason that this code is not executed in Draw?
//        SfxViewShell* pSfxViewSh = GetViewShell();
//        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
    }

    if (pDrawObj)
        pViewSh->ScrollToObject( pDrawObj );
}

void __EXPORT ScClient::ViewChanged()
{
    if ( GetAspect() == embed::Aspects::MSOLE_ICON )
    {
        // the iconified object seems not to need such a scaling handling
        // since the replacement image and the size a completely controlled by the container
        // TODO/LATER: when the icon exchange is implemented the scaling handling might be required again here

        return;
    }

    uno::Reference < embed::XEmbeddedObject > xObj = GetObject();

    // TODO/LEAN: working with Visual Area can switch object to running state
    awt::Size aSz;
    try {
        aSz = xObj->getVisualAreaSize( GetAspect() );
    } catch ( embed::NoVisualAreaSizeException& )
    {
        DBG_ERROR("The visual area size must be available!\n");
    }

    MapUnit aMapUnit = VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( GetAspect() ) );
    Size aVisSize = OutputDevice::LogicToLogic( Size( aSz.Width, aSz.Height ), aMapUnit, MAP_100TH_MM );

    //  Groesse ins Dokument uebernehmen
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        Rectangle aLogicRect = pDrawObj->GetLogicRect();
        Fraction aFractX = GetScaleWidth();
        Fraction aFractY = GetScaleHeight();
        aFractX *= aVisSize.Width();
        aFractY *= aVisSize.Height();
        aVisSize = Size( (long) aFractX, (long) aFractY );      // skaliert fuer Draw-Model

        //  pClientData->SetObjArea vor pDrawObj->SetLogicRect, damit keine
        //  falschen Skalierungen ausgerechnet werden:
        //Rectangle aObjArea = aLogicRect;
        //aObjArea.SetSize( aVisSize );          // Dokument-Groesse vom Server
        //SetObjArea( aObjArea );

        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if ( pViewSh )
        {
            Window* pWin = pViewSh->GetActiveWin();
            if ( pWin->LogicToPixel( aVisSize ) != pWin->LogicToPixel( aLogicRect.GetSize() ) )
            {
                aLogicRect.SetSize( aVisSize );
                pDrawObj->SetLogicRect( aLogicRect );

                //  set document modified (SdrModel::SetChanged is not used)
                pViewSh->GetViewData()->GetDocShell()->SetDrawModified();
            }
        }
    }
}

void __EXPORT ScClient::MakeVisible()
{
    SdrOle2Obj* pDrawObj = GetDrawObj();
    if (pDrawObj)
    {
        SfxViewShell* pSfxViewSh = GetViewShell();
        ScTabViewShell* pViewSh = PTR_CAST( ScTabViewShell, pSfxViewSh );
        if (pViewSh)
            pViewSh->ScrollToObject( pDrawObj );
    }
}

<|endoftext|>


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

#ifndef SC_OUTPUT_HXX
#define SC_OUTPUT_HXX

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _FRACT_HXX //autogen
#include <tools/fract.hxx>
#endif

#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif

class Rectangle;
class Font;
class OutputDevice;
class Window;
class EditEngine;
class ScDocument;
class ScBaseCell;
class ScPatternAttr;
class SvxMarginItem;
class SdrObject;
class SdrOle2Obj;
struct RowInfo;
struct ScTableInfo;
class ScTabViewShell;
class ScPageBreakData;
class FmFormView;

// ---------------------------------------------------------------------------

#define SC_SCENARIO_HSPACE      60
#define SC_SCENARIO_VSPACE      50

// ---------------------------------------------------------------------------

#define SC_OBJECTS_NONE         0
#define SC_OBJECTS_DRAWING      1
#define SC_OBJECTS_OLE          2
#define SC_OBJECTS_CHARTS       4
#define SC_OBJECTS_ALL          ( SC_OBJECTS_DRAWING | SC_OBJECTS_OLE | SC_OBJECTS_CHARTS )

enum ScOutputType { OUTTYPE_WINDOW, OUTTYPE_PRINTER };

class ScOutputData
{
friend class ScDrawStringsVars;
private:
    OutputDevice* pDev;         // Device
    OutputDevice* pRefDevice;   // printer if used for preview
    OutputDevice* pFmtDevice;   // reference for text formatting
    ScTableInfo& mrTabInfo;
    RowInfo* pRowInfo;          // Info-Block
    SCSIZE nArrCount;           // belegte Zeilen im Info-Block
    ScDocument* pDoc;           // Dokument
    SCTAB nTab;                 // Tabelle
    long nScrX;                 // Ausgabe Startpos. (Pixel)
    long nScrY;
    long nScrW;                 // Ausgabe Groesse (Pixel)
    long nScrH;
    long nMirrorW;              // Visible output width for mirroring (default: nScrW)
    SCCOL nX1;                  // Start-/Endkoordinaten
    SCROW nY1;                  //  ( incl. versteckte )
    SCCOL nX2;
    SCROW nY2;
    SCCOL nVisX1;               // Start-/Endkoordinaten
    SCROW nVisY1;               //  ( sichtbarer Bereich )
    SCCOL nVisX2;
    SCROW nVisY2;
    ScOutputType eType;         // Bildschirm/Drucker ...
    double nPPTX;               // Pixel per Twips
    double nPPTY;
//  USHORT nZoom;               // Zoom-Faktor (Prozent) - fuer GetFont
    Fraction aZoomX;
    Fraction aZoomY;

    SdrObject* pEditObj;        // beim Painten auslassen

    ScTabViewShell* pViewShell; // zum Connecten von sichtbaren Plug-Ins

    // #114135#
    FmFormView* pDrawView;      // SdrView to paint to

    BOOL bEditMode;             // InPlace editierte Zelle - nicht ausgeben
    SCCOL nEditCol;
    SCROW nEditRow;

    BOOL bMetaFile;             // Ausgabe auf Metafile (nicht in Pixeln!)
    BOOL bSingleGrid;           // beim Gitter bChanged auswerten

    BOOL bPagebreakMode;        // Seitenumbruch-Vorschau
    BOOL bSolidBackground;      // weiss statt transparent

    BOOL bUseStyleColor;
    BOOL bForceAutoColor;

    BOOL bSyntaxMode;           // Syntax-Highlighting
    Color* pValueColor;
    Color* pTextColor;
    Color* pFormulaColor;

    Color   aGridColor;

    BOOL    bShowNullValues;
    BOOL    bShowFormulas;
    BOOL    bShowSpellErrors;   // Spell-Errors in EditObjekten anzeigen
    BOOL    bMarkClipped;

    BOOL    bSnapPixel;

    BOOL    bAnyRotated;        // intern
    BOOL    bAnyClipped;        // intern
    BOOL    bTabProtected;
    BYTE    nTabTextDirection;  // EEHorizontalTextDirection values
    BOOL    bLayoutRTL;

                            // private methods

    BOOL            GetMergeOrigin( SCCOL nX, SCROW nY, SCSIZE nArrY,
                                    SCCOL& rOverX, SCROW& rOverY, BOOL bVisRowChanged );
    BOOL            IsEmptyCellText( RowInfo* pThisRowInfo, SCCOL nX, SCROW nY );
    void            GetVisibleCell( SCCOL nCol, SCROW nRow, SCTAB nTab, ScBaseCell*& rpCell );

    BOOL            IsAvailable( SCCOL nX, SCROW nY );
    long            GetAvailableWidth( SCCOL nX, SCROW nY, long nNeeded );
    void            GetOutputArea( SCCOL nX, SCSIZE nArrY, long nPosX, long nPosY,
                                    SCCOL nCellX, SCROW nCellY, long nNeeded,
                                    const ScPatternAttr& rPattern,
                                    USHORT nHorJustify, BOOL bCellIsValue,
                                    BOOL bBreak, BOOL bOverwrite,
                                    Rectangle& rAlignRect, Rectangle& rClipRect,
                                    BOOL& rLeftClip, BOOL& rRightClip );

    void            ShrinkEditEngine( EditEngine& rEngine, const Rectangle& rAlignRect,
                                    long nLeftM, long nTopM, long nRightM, long nBottomM,
                                    BOOL bWidth, USHORT nOrient, long nAttrRotate, BOOL bPixelToLogic,
                                    long& rEngineWidth, long& rEngineHeight, long& rNeededPixel,
                                    BOOL& rLeftClip, BOOL& rRightClip );

    void            SetSyntaxColor( Font* pFont, ScBaseCell* pCell );
    void            SetEditSyntaxColor( EditEngine& rEngine, ScBaseCell* pCell );

    void            ConnectObject( const com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject >& rRef, SdrOle2Obj* pOleObj );

    double          GetStretch();

    void            DrawRotatedFrame( const Color* pForceColor );       // pixel

public:
                    ScOutputData( OutputDevice* pNewDev, ScOutputType eNewType,
                                    ScTableInfo& rTabInfo, ScDocument* pNewDoc,
                                    SCTAB nNewTab, long nNewScrX, long nNewScrY,
                                    SCCOL nNewX1, SCROW nNewY1, SCCOL nNewX2, SCROW nNewY2,
                                    double nPixelPerTwipsX, double nPixelPerTwipsY,
                                    const Fraction* pZoomX = NULL,
                                    const Fraction* pZoomY = NULL );

                    ~ScOutputData();

    void    SetRefDevice( OutputDevice* pRDev ) { pRefDevice = pFmtDevice = pRDev; }
    void    SetFmtDevice( OutputDevice* pRDev ) { pFmtDevice = pRDev; }
    void    SetEditObject( SdrObject* pObj )    { pEditObj = pObj; }
    void    SetViewShell( ScTabViewShell* pSh ) { pViewShell = pSh; }

    // #114135#
    void    SetDrawView( FmFormView* pNew )     { pDrawView = pNew; }

    void    SetSolidBackground( BOOL bSet )     { bSolidBackground = bSet; }
    void    SetUseStyleColor( BOOL bSet )       { bUseStyleColor = bSet; }

    void    SetEditCell( SCCOL nCol, SCROW nRow );
    void    SetSyntaxMode( BOOL bNewMode );
    void    SetMetaFileMode( BOOL bNewMode );
    void    SetSingleGrid( BOOL bNewMode );
    void    SetGridColor( const Color& rColor );
    void    SetMarkClipped( BOOL bSet );
    void    SetShowNullValues ( BOOL bSet = TRUE );
    void    SetShowFormulas   ( BOOL bSet = TRUE );
    void    SetShowSpellErrors( BOOL bSet = TRUE );
    void    SetMirrorWidth( long nNew );
    long    GetScrW() const     { return nScrW; }
    long    GetScrH() const     { return nScrH; }

    void    SetSnapPixel( BOOL bSet = TRUE );

    void    DrawGrid( BOOL bGrid, BOOL bPage );
    void    DrawStrings( BOOL bPixelToLogic = FALSE );
    void    DrawBackground();
    void    DrawShadow();
    void    DrawExtraShadow(BOOL bLeft, BOOL bTop, BOOL bRight, BOOL bBottom);
    void    DrawFrame();

                    // with logic MapMode set!
    void    DrawEdit(BOOL bPixelToLogic);

    void    FindRotated();
    void    DrawRotated(BOOL bPixelToLogic);        // logisch

    void    DrawClear();
    void    DrawPageBorder( SCCOL nStartX, SCROW nStartY, SCCOL nEndX, SCROW nEndY );

    // #109985#
    //void  DrawingLayer( USHORT nLayer, USHORT nObjectFlags, long nLogStX, long nLogStY );
    void    DrawingLayer(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode, long nLogStX, long nLogStY );

                                                    // nur Bildschirm:

    // #109985#
    //void  DrawingSingle( USHORT nLayer, USHORT nObjectFlags, USHORT nDummyFlags );
    void    DrawingSingle(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode);

    // #109985#
    //void  DrawSelectiveObjects( USHORT nLayer, const Rectangle& rRect, USHORT nObjectFlags, USHORT nDummyFlags = 0 );
    void    DrawSelectiveObjects(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode);

    BOOL    SetChangedClip();       // FALSE = nix

    void    FindChanged();
    void    SetPagebreakMode( ScPageBreakData* pPageData );
    void    DrawMark( Window* pWin );
    void    DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY,
                         SCCOL nRefEndX, SCROW nRefEndY,
                         const Color& rColor, BOOL bHandle );
    void    DrawOneChange( SCCOL nRefStartX, SCROW nRefStartY,
                            SCCOL nRefEndX, SCROW nRefEndY,
                            const Color& rColor, USHORT nType );
    void    DrawChangeTrack();
    void    DrawClipMarks();

    void    DrawNoteMarks();
    void    AddPDFNotes();
    void    PrintNoteMarks( const List& rPosList );     // List of ScAddress
};

#endif

<commit_msg>INTEGRATION: CWS aw039 (1.17.36); FILE MERGED 2006/12/20 16:16:44 aw 1.17.36.1: #i72502# reorganizing DrawingLayer Layer printing for SC<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: output.hxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: obo $ $Date: 2007-01-22 15:07:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_OUTPUT_HXX
#define SC_OUTPUT_HXX

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _FRACT_HXX //autogen
#include <tools/fract.hxx>
#endif

#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif

class Rectangle;
class Font;
class OutputDevice;
class Window;
class EditEngine;
class ScDocument;
class ScBaseCell;
class ScPatternAttr;
class SvxMarginItem;
class SdrObject;
class SdrOle2Obj;
struct RowInfo;
struct ScTableInfo;
class ScTabViewShell;
class ScPageBreakData;
class FmFormView;

// ---------------------------------------------------------------------------

#define SC_SCENARIO_HSPACE      60
#define SC_SCENARIO_VSPACE      50

// ---------------------------------------------------------------------------

#define SC_OBJECTS_NONE         0
#define SC_OBJECTS_DRAWING      1
#define SC_OBJECTS_OLE          2
#define SC_OBJECTS_CHARTS       4
#define SC_OBJECTS_ALL          ( SC_OBJECTS_DRAWING | SC_OBJECTS_OLE | SC_OBJECTS_CHARTS )

enum ScOutputType { OUTTYPE_WINDOW, OUTTYPE_PRINTER };

class ScOutputData
{
friend class ScDrawStringsVars;
private:
    OutputDevice* pDev;         // Device
    OutputDevice* pRefDevice;   // printer if used for preview
    OutputDevice* pFmtDevice;   // reference for text formatting
    ScTableInfo& mrTabInfo;
    RowInfo* pRowInfo;          // Info-Block
    SCSIZE nArrCount;           // belegte Zeilen im Info-Block
    ScDocument* pDoc;           // Dokument
    SCTAB nTab;                 // Tabelle
    long nScrX;                 // Ausgabe Startpos. (Pixel)
    long nScrY;
    long nScrW;                 // Ausgabe Groesse (Pixel)
    long nScrH;
    long nMirrorW;              // Visible output width for mirroring (default: nScrW)
    SCCOL nX1;                  // Start-/Endkoordinaten
    SCROW nY1;                  //  ( incl. versteckte )
    SCCOL nX2;
    SCROW nY2;
    SCCOL nVisX1;               // Start-/Endkoordinaten
    SCROW nVisY1;               //  ( sichtbarer Bereich )
    SCCOL nVisX2;
    SCROW nVisY2;
    ScOutputType eType;         // Bildschirm/Drucker ...
    double nPPTX;               // Pixel per Twips
    double nPPTY;
//  USHORT nZoom;               // Zoom-Faktor (Prozent) - fuer GetFont
    Fraction aZoomX;
    Fraction aZoomY;

    SdrObject* pEditObj;        // beim Painten auslassen

    ScTabViewShell* pViewShell; // zum Connecten von sichtbaren Plug-Ins

    // #114135#
    FmFormView* pDrawView;      // SdrView to paint to

    BOOL bEditMode;             // InPlace editierte Zelle - nicht ausgeben
    SCCOL nEditCol;
    SCROW nEditRow;

    BOOL bMetaFile;             // Ausgabe auf Metafile (nicht in Pixeln!)
    BOOL bSingleGrid;           // beim Gitter bChanged auswerten

    BOOL bPagebreakMode;        // Seitenumbruch-Vorschau
    BOOL bSolidBackground;      // weiss statt transparent

    BOOL bUseStyleColor;
    BOOL bForceAutoColor;

    BOOL bSyntaxMode;           // Syntax-Highlighting
    Color* pValueColor;
    Color* pTextColor;
    Color* pFormulaColor;

    Color   aGridColor;

    BOOL    bShowNullValues;
    BOOL    bShowFormulas;
    BOOL    bShowSpellErrors;   // Spell-Errors in EditObjekten anzeigen
    BOOL    bMarkClipped;

    BOOL    bSnapPixel;

    BOOL    bAnyRotated;        // intern
    BOOL    bAnyClipped;        // intern
    BOOL    bTabProtected;
    BYTE    nTabTextDirection;  // EEHorizontalTextDirection values
    BOOL    bLayoutRTL;

                            // private methods

    BOOL            GetMergeOrigin( SCCOL nX, SCROW nY, SCSIZE nArrY,
                                    SCCOL& rOverX, SCROW& rOverY, BOOL bVisRowChanged );
    BOOL            IsEmptyCellText( RowInfo* pThisRowInfo, SCCOL nX, SCROW nY );
    void            GetVisibleCell( SCCOL nCol, SCROW nRow, SCTAB nTab, ScBaseCell*& rpCell );

    BOOL            IsAvailable( SCCOL nX, SCROW nY );
    long            GetAvailableWidth( SCCOL nX, SCROW nY, long nNeeded );
    void            GetOutputArea( SCCOL nX, SCSIZE nArrY, long nPosX, long nPosY,
                                    SCCOL nCellX, SCROW nCellY, long nNeeded,
                                    const ScPatternAttr& rPattern,
                                    USHORT nHorJustify, BOOL bCellIsValue,
                                    BOOL bBreak, BOOL bOverwrite,
                                    Rectangle& rAlignRect, Rectangle& rClipRect,
                                    BOOL& rLeftClip, BOOL& rRightClip );

    void            ShrinkEditEngine( EditEngine& rEngine, const Rectangle& rAlignRect,
                                    long nLeftM, long nTopM, long nRightM, long nBottomM,
                                    BOOL bWidth, USHORT nOrient, long nAttrRotate, BOOL bPixelToLogic,
                                    long& rEngineWidth, long& rEngineHeight, long& rNeededPixel,
                                    BOOL& rLeftClip, BOOL& rRightClip );

    void            SetSyntaxColor( Font* pFont, ScBaseCell* pCell );
    void            SetEditSyntaxColor( EditEngine& rEngine, ScBaseCell* pCell );

    void            ConnectObject( const com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject >& rRef, SdrOle2Obj* pOleObj );

    double          GetStretch();

    void            DrawRotatedFrame( const Color* pForceColor );       // pixel

public:
                    ScOutputData( OutputDevice* pNewDev, ScOutputType eNewType,
                                    ScTableInfo& rTabInfo, ScDocument* pNewDoc,
                                    SCTAB nNewTab, long nNewScrX, long nNewScrY,
                                    SCCOL nNewX1, SCROW nNewY1, SCCOL nNewX2, SCROW nNewY2,
                                    double nPixelPerTwipsX, double nPixelPerTwipsY,
                                    const Fraction* pZoomX = NULL,
                                    const Fraction* pZoomY = NULL );

                    ~ScOutputData();

    void    SetRefDevice( OutputDevice* pRDev ) { pRefDevice = pFmtDevice = pRDev; }
    void    SetFmtDevice( OutputDevice* pRDev ) { pFmtDevice = pRDev; }
    void    SetEditObject( SdrObject* pObj )    { pEditObj = pObj; }
    void    SetViewShell( ScTabViewShell* pSh ) { pViewShell = pSh; }

    // #114135#
    void    SetDrawView( FmFormView* pNew )     { pDrawView = pNew; }

    void    SetSolidBackground( BOOL bSet )     { bSolidBackground = bSet; }
    void    SetUseStyleColor( BOOL bSet )       { bUseStyleColor = bSet; }

    void    SetEditCell( SCCOL nCol, SCROW nRow );
    void    SetSyntaxMode( BOOL bNewMode );
    void    SetMetaFileMode( BOOL bNewMode );
    void    SetSingleGrid( BOOL bNewMode );
    void    SetGridColor( const Color& rColor );
    void    SetMarkClipped( BOOL bSet );
    void    SetShowNullValues ( BOOL bSet = TRUE );
    void    SetShowFormulas   ( BOOL bSet = TRUE );
    void    SetShowSpellErrors( BOOL bSet = TRUE );
    void    SetMirrorWidth( long nNew );
    long    GetScrW() const     { return nScrW; }
    long    GetScrH() const     { return nScrH; }

    void    SetSnapPixel( BOOL bSet = TRUE );

    void    DrawGrid( BOOL bGrid, BOOL bPage );
    void    DrawStrings( BOOL bPixelToLogic = FALSE );
    void    DrawBackground();
    void    DrawShadow();
    void    DrawExtraShadow(BOOL bLeft, BOOL bTop, BOOL bRight, BOOL bBottom);
    void    DrawFrame();

                    // with logic MapMode set!
    void    DrawEdit(BOOL bPixelToLogic);

    void    FindRotated();
    void    DrawRotated(BOOL bPixelToLogic);        // logisch

    void    DrawClear();
    void    DrawPageBorder( SCCOL nStartX, SCROW nStartY, SCCOL nEndX, SCROW nEndY );

    // #i72502# printer only command set
    Point PrePrintDrawingLayer(long nLogStX, long nLogStY );
    void PostPrintDrawingLayer();
    void PrintDrawingLayer(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode, const Point& rMMOffset);

    // nur Bildschirm:
    // #109985#
    //void  DrawingSingle( USHORT nLayer, USHORT nObjectFlags, USHORT nDummyFlags );
    void    DrawingSingle(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode);

    // #109985#
    //void  DrawSelectiveObjects( USHORT nLayer, const Rectangle& rRect, USHORT nObjectFlags, USHORT nDummyFlags = 0 );
    void    DrawSelectiveObjects(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode);

    BOOL    SetChangedClip();       // FALSE = nix

    void    FindChanged();
    void    SetPagebreakMode( ScPageBreakData* pPageData );
    void    DrawMark( Window* pWin );
    void    DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY,
                         SCCOL nRefEndX, SCROW nRefEndY,
                         const Color& rColor, BOOL bHandle );
    void    DrawOneChange( SCCOL nRefStartX, SCROW nRefStartY,
                            SCCOL nRefEndX, SCROW nRefEndY,
                            const Color& rColor, USHORT nType );
    void    DrawChangeTrack();
    void    DrawClipMarks();

    void    DrawNoteMarks();
    void    AddPDFNotes();
    void    PrintNoteMarks( const List& rPosList );     // List of ScAddress
};

#endif

<|endoftext|>


<commit_before>#include <Python.h>
#include <numpy/arrayobject.h>

#include <vector>
#include <iostream>

#include "best_utility.h"
#include "solver.h"

static PyObject *
find_max(PyObject *self, PyObject *args){
    double p;
    PyArrayObject *X, *y, *X_argsort_by_feature, *example_idx; //borrowed
    PyArrayObject *feature_weights = NULL;

    // Extract the argument values
    if(!PyArg_ParseTuple(args, "dO!O!O!O!|O!",
                         &p,
                         &PyArray_Type, &X,
                         &PyArray_Type, &y,
                         &PyArray_Type, &X_argsort_by_feature,
                         &PyArray_Type, &example_idx,
                         &PyArray_Type, &feature_weights)){
        return NULL;
    }

    // Check the type of the numpy arrays
    if(PyArray_TYPE(X) != PyArray_DOUBLE){
        PyErr_SetString(PyExc_TypeError,
                        "X must be numpy.ndarray type double");
        return NULL;
    }
    if(PyArray_TYPE(y) != PyArray_LONG){
        PyErr_SetString(PyExc_TypeError,
                        "y must be numpy.ndarray type int");
        return NULL;
    }
    if(PyArray_TYPE(X_argsort_by_feature) != PyArray_LONG){
        PyErr_SetString(PyExc_TypeError,
                        "X_argsort_by_feature must be numpy.ndarray type int");
        return NULL;
    }
    if(PyArray_TYPE(example_idx) != PyArray_LONG){
        PyErr_SetString(PyExc_TypeError,
                        "example_idx must be numpy.ndarray type int");
        return NULL;
    }
    if(feature_weights && PyArray_TYPE(feature_weights) != PyArray_DOUBLE){
        PyErr_SetString(PyExc_TypeError,
                        "feature_weights must be numpy.ndarray type double");
        return NULL;
    }

    // Check the number of dimensions of the numpy arrays
    if(PyArray_NDIM(X) != 2){
        PyErr_SetString(PyExc_TypeError,
                        "X must be a 2D numpy.ndarray");
        return NULL;
    }
    if(PyArray_NDIM(y) != 1){
        PyErr_SetString(PyExc_TypeError,
                        "y must be a 1D numpy.ndarray");
        return NULL;
    }
    if(PyArray_NDIM(X_argsort_by_feature) != 2){
        PyErr_SetString(PyExc_TypeError,
                        "X_argsort_by_feature must be a 2D numpy.ndarray");
        return NULL;
    }
    if(PyArray_NDIM(example_idx) != 1){
        PyErr_SetString(PyExc_TypeError,
                        "example_idx must be a 1D numpy.ndarray");
        return NULL;
    }
    if(feature_weights && PyArray_NDIM(example_idx) != 1){
        PyErr_SetString(PyExc_TypeError,
                        "feature_weights must be a 1D numpy.ndarray");
        return NULL;
    }

    // Check that the dimension sizes match
    npy_intp X_dim0 = PyArray_DIM(X, 0);
    npy_intp X_dim1 = PyArray_DIM(X, 1);
    npy_intp y_dim0 = PyArray_DIM(y, 0);
    npy_intp X_argsort_by_feature_dim0 = PyArray_DIM(X_argsort_by_feature, 0);
    npy_intp X_argsort_by_feature_dim1 = PyArray_DIM(X_argsort_by_feature, 1);
    npy_intp example_idx_dim0 = PyArray_DIM(example_idx, 0);
    npy_intp feature_weights_dim0 = 0;
    if(feature_weights){
        feature_weights_dim0 = PyArray_DIM(feature_weights, 0);
    }

    if(X_dim0 != y_dim0){
        PyErr_SetString(PyExc_TypeError,
                        "X and y must have the same number of rows");
        return NULL;
    }
    if(X_dim0 != X_argsort_by_feature_dim0){
        PyErr_SetString(PyExc_TypeError,
                        "X and X_argsort_by_feature must have the same number of rows");
        return NULL;
    }
    if(X_dim1 != X_argsort_by_feature_dim1){
        PyErr_SetString(PyExc_TypeError,
                        "X and X_argsort_by_feature must have the same number of columns");
        return NULL;
    }
    if(feature_weights && feature_weights_dim0 != X_dim1){
        PyErr_SetString(PyExc_TypeError,
                        "feature_weights must have shape X.shape[1]");
        return NULL;
    }

    // Extract the data pointer from the number arrays
    double *X_data;
    long *y_data, *X_argsort_by_feature_data, *example_idx_data;
    X_data = (double*)PyArray_DATA(PyArray_GETCONTIGUOUS(X));
    y_data = (long*)PyArray_DATA(PyArray_GETCONTIGUOUS(y));
    X_argsort_by_feature_data = (long*)PyArray_DATA(PyArray_GETCONTIGUOUS(X_argsort_by_feature));
    example_idx_data = (long*)PyArray_DATA(PyArray_GETCONTIGUOUS(example_idx));

    double *feature_weights_data;
    if(feature_weights){
        feature_weights_data = (double*)PyArray_DATA(PyArray_GETCONTIGUOUS(feature_weights));
    }
    else{
        feature_weights_data = new double[X_dim1];
        for(int i = 0; i < X_dim1; i++){
            feature_weights_data[i] = 1;
        }
    }

    BestUtility best_solution(100);
    int status = find_max(p, X_data, y_data, X_argsort_by_feature_data, example_idx_data, feature_weights_data,
                          example_idx_dim0, X_dim0, X_dim1, best_solution);

    if(status != 0){
        PyErr_SetString(PyExc_TypeError,
                        "An error occurred in the solver");
        return NULL;
    }

    // Prepare variables for return

    double opti_utility = best_solution.best_utility;

    npy_intp dims[] = {best_solution.best_n_equiv};
    PyObject *opti_feat_idx = PyArray_SimpleNew(1, dims, PyArray_LONG);
    long *opti_feat_idx_data = (long*)PyArray_DATA(opti_feat_idx);

    PyObject *opti_thresholds = PyArray_SimpleNew(1, dims, PyArray_DOUBLE);
    double *opti_thresholds_data = (double*)PyArray_DATA(opti_thresholds);

    PyObject *opti_kinds = PyArray_SimpleNew(1, dims, PyArray_LONG);
    long *opti_kinds_data = (long*)PyArray_DATA(opti_kinds);

    for(int i = 0; i < best_solution.best_n_equiv; i++){
        opti_feat_idx_data[i] = best_solution.best_feat_idx[i];
        opti_thresholds_data[i] = best_solution.best_feat_threshold[i];
        opti_kinds_data[i] = (int) best_solution.best_feat_kind[i];
    }

    if (feature_weights){
        Py_DECREF(feature_weights);
    }
    else{
        delete [] feature_weights_data;
    }

    Py_DECREF(X);
    Py_DECREF(y);
    Py_DECREF(X_argsort_by_feature);
    Py_DECREF(example_idx);

    return Py_BuildValue("d,N,N,N",
                         opti_utility,
                         opti_feat_idx,
                         opti_thresholds,
                         opti_kinds);
}

/***********************************************************************************************************************
 *                                                  MODULE DECLARATION
 **********************************************************************************************************************/
static PyMethodDef Methods[] = {
        {"find_max", find_max, METH_VARARGS,
                        "Find the split of maximum utility."},
        {NULL, NULL, 0, NULL}
};

#if PY_MAJOR_VERSION >= 3

static struct PyModuleDef _scm_utility_module = {
    PyModuleDef_HEAD_INIT,
    "_scm_utility",
    NULL,
    -1,
    Methods
};

PyMODINIT_FUNC PyInit__scm_utility() {
    import_array();
    return PyModule_Create(&_scm_utility_module);
};

#else

PyMODINIT_FUNC
init_scm_utility
        (void){
    (void)Py_InitModule("_scm_utility", Methods);
    import_array();//necessary from numpy otherwise we crash with segfault
}

#endif
<commit_msg>Deleted useless file<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: brkdlg.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 10:41:29 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "BreakDlg.hxx"

#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif

#include <svx/svdedtv.hxx>
#include <svx/svdetc.hxx>
#include <sfx2/app.hxx>
#include <vcl/msgbox.hxx>

#include "sdattr.hxx"
#include "brkdlg.hrc"
#include "sdresid.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "strings.hrc"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif

namespace sd {

/*************************************************************************
|*
|* Dialog zum aufbrechen von Metafiles
|*
\************************************************************************/

BreakDlg::BreakDlg(
    ::Window* pWindow,
    DrawView* _pDrView,
    DrawDocShell* pShell,
    ULONG nSumActionCount,
    ULONG nObjCount )
    : SfxModalDialog     ( pWindow, SdResId( DLG_BREAK ) ),
      aFtObjInfo            ( this, SdResId( FT_OBJ_INFO ) ),
      aFtActInfo            ( this, SdResId( FT_ACT_INFO ) ),
      aFtInsInfo            ( this, SdResId( FT_INS_INFO ) ),
      aFiObjInfo            ( this, SdResId( FI_OBJ_INFO ) ),
      aFiActInfo            ( this, SdResId( FI_ACT_INFO ) ),
      aFiInsInfo            ( this, SdResId( FI_INS_INFO ) ),
      aBtnCancel            ( this, SdResId( BTN_CANCEL ) ),
      aLink             ( LINK( this, BreakDlg, UpDate)),
      mpProgress            ( NULL )
{
    aBtnCancel.SetClickHdl( LINK( this, BreakDlg, CancelButtonHdl));

    mpProgress = new SfxProgress( pShell, String(SdResId(STR_BREAK_METAFILE)), nSumActionCount*3 );

    pProgrInfo = new SvdProgressInfo( &aLink );
    // jede Action wird in DoImport() 3mal bearbeitet
    pProgrInfo->Init( nSumActionCount*3, nObjCount );

    pDrView = _pDrView;
    bCancel = FALSE;

    FreeResource();
}

BreakDlg::~BreakDlg()
{
    if( mpProgress )
        delete mpProgress;

    if( pProgrInfo )
        delete pProgrInfo;
}

// Control-Handler fuer den Abbruch Button
IMPL_LINK( BreakDlg, CancelButtonHdl, void *, EMPTYARG )
{
  bCancel = TRUE;
  aBtnCancel.Disable();
  return( 0L );
}

// Die UpDate Methode muss regelmaessig von der Arbeitsfunktion
// ausgeuehrt werden.
// Beim ersten aufruf wird die gesamtanzahl der actions uebergeben.
// Jeder weitere sollte die bearbeiteten actions seit dem letzten aufruf von
// UpDate erhalten.

IMPL_LINK( BreakDlg, UpDate, void*, nInit )
{
    String aEmptyStr;

    if(pProgrInfo == NULL)
      return 1L;

    // Statuszeile updaten oder Fehlermeldung?
    if(nInit == (void*)1L)
    {
        ErrorBox aErrBox( this, WB_OK, String( SdResId( STR_BREAK_FAIL ) ) );
        aErrBox.Execute();
    }
    else
    {
        if(mpProgress)
            mpProgress->SetState( pProgrInfo->GetSumCurAction() );
    }

    // Welches Oject wird gerade angezeigt?
    String info = UniString::CreateFromInt32( pProgrInfo->GetCurObj() );
    info.Append( sal_Unicode('/') );
    info.Append( UniString::CreateFromInt32( pProgrInfo->GetObjCount() ) );
    aFiObjInfo.SetText(info);

    // Wieviele Actions sind schon aufgebrochen?
    if(pProgrInfo->GetActionCount() == 0)
    {
        aFiActInfo.SetText( aEmptyStr );
    }
    else
    {
        info = UniString::CreateFromInt32( pProgrInfo->GetCurAction() );
        info.Append( sal_Unicode('/') );
        info.Append( UniString::CreateFromInt32( pProgrInfo->GetActionCount() ) );
        aFiActInfo.SetText(info);
    }

    // Und erst eingefuegt????
    if(pProgrInfo->GetInsertCount() == 0)
    {
        aFiInsInfo.SetText( aEmptyStr );
    }
    else
    {
        info = UniString::CreateFromInt32( pProgrInfo->GetCurInsert() );
        info.Append( sal_Unicode('/') );
        info.Append( UniString::CreateFromInt32( pProgrInfo->GetInsertCount() ) );
        aFiInsInfo.SetText(info);
    }

    Application::Reschedule();
    return( bCancel?0L:1L );
}

// Oeffnet den Modalen Dialog und startet einen Timer der die Arbeitsfunktion
// nach oeffnen des Dialogs ausfuehrt
short BreakDlg::Execute()
{
  aTimer.SetTimeout( 10 );
  aTimer.SetTimeoutHdl( LINK( this, BreakDlg, InitialUpdate ) );
  aTimer.Start();

  return SfxModalDialog::Execute();
}

// Linkmethode welche die Arbeitsfunktion startet
IMPL_LINK( BreakDlg, InitialUpdate, Timer*, pTimer )
{
    pDrView->DoImportMarkedMtf(pProgrInfo);
    EndDialog(TRUE);
    return 0L;
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS tune03 (1.2.186); FILE MERGED 2004/08/08 12:54:00 mhu 1.2.186.1: #i29979# Added SD_DLLPUBLIC/PRIVATE (see sddllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
 *
 *  $RCSfile: brkdlg.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 08:14:11 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif

#include "BreakDlg.hxx"

#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif

#include <svx/svdedtv.hxx>
#include <svx/svdetc.hxx>
#include <sfx2/app.hxx>
#include <vcl/msgbox.hxx>

#include "sdattr.hxx"
#include "brkdlg.hrc"
#include "sdresid.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "strings.hrc"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif

namespace sd {

/*************************************************************************
|*
|* Dialog zum aufbrechen von Metafiles
|*
\************************************************************************/

BreakDlg::BreakDlg(
    ::Window* pWindow,
    DrawView* _pDrView,
    DrawDocShell* pShell,
    ULONG nSumActionCount,
    ULONG nObjCount )
    : SfxModalDialog     ( pWindow, SdResId( DLG_BREAK ) ),
      aFtObjInfo            ( this, SdResId( FT_OBJ_INFO ) ),
      aFtActInfo            ( this, SdResId( FT_ACT_INFO ) ),
      aFtInsInfo            ( this, SdResId( FT_INS_INFO ) ),
      aFiObjInfo            ( this, SdResId( FI_OBJ_INFO ) ),
      aFiActInfo            ( this, SdResId( FI_ACT_INFO ) ),
      aFiInsInfo            ( this, SdResId( FI_INS_INFO ) ),
      aBtnCancel            ( this, SdResId( BTN_CANCEL ) ),
      aLink             ( LINK( this, BreakDlg, UpDate)),
      mpProgress            ( NULL )
{
    aBtnCancel.SetClickHdl( LINK( this, BreakDlg, CancelButtonHdl));

    mpProgress = new SfxProgress( pShell, String(SdResId(STR_BREAK_METAFILE)), nSumActionCount*3 );

    pProgrInfo = new SvdProgressInfo( &aLink );
    // jede Action wird in DoImport() 3mal bearbeitet
    pProgrInfo->Init( nSumActionCount*3, nObjCount );

    pDrView = _pDrView;
    bCancel = FALSE;

    FreeResource();
}

BreakDlg::~BreakDlg()
{
    if( mpProgress )
        delete mpProgress;

    if( pProgrInfo )
        delete pProgrInfo;
}

// Control-Handler fuer den Abbruch Button
IMPL_LINK( BreakDlg, CancelButtonHdl, void *, EMPTYARG )
{
  bCancel = TRUE;
  aBtnCancel.Disable();
  return( 0L );
}

// Die UpDate Methode muss regelmaessig von der Arbeitsfunktion
// ausgeuehrt werden.
// Beim ersten aufruf wird die gesamtanzahl der actions uebergeben.
// Jeder weitere sollte die bearbeiteten actions seit dem letzten aufruf von
// UpDate erhalten.

IMPL_LINK( BreakDlg, UpDate, void*, nInit )
{
    String aEmptyStr;

    if(pProgrInfo == NULL)
      return 1L;

    // Statuszeile updaten oder Fehlermeldung?
    if(nInit == (void*)1L)
    {
        ErrorBox aErrBox( this, WB_OK, String( SdResId( STR_BREAK_FAIL ) ) );
        aErrBox.Execute();
    }
    else
    {
        if(mpProgress)
            mpProgress->SetState( pProgrInfo->GetSumCurAction() );
    }

    // Welches Oject wird gerade angezeigt?
    String info = UniString::CreateFromInt32( pProgrInfo->GetCurObj() );
    info.Append( sal_Unicode('/') );
    info.Append( UniString::CreateFromInt32( pProgrInfo->GetObjCount() ) );
    aFiObjInfo.SetText(info);

    // Wieviele Actions sind schon aufgebrochen?
    if(pProgrInfo->GetActionCount() == 0)
    {
        aFiActInfo.SetText( aEmptyStr );
    }
    else
    {
        info = UniString::CreateFromInt32( pProgrInfo->GetCurAction() );
        info.Append( sal_Unicode('/') );
        info.Append( UniString::CreateFromInt32( pProgrInfo->GetActionCount() ) );
        aFiActInfo.SetText(info);
    }

    // Und erst eingefuegt????
    if(pProgrInfo->GetInsertCount() == 0)
    {
        aFiInsInfo.SetText( aEmptyStr );
    }
    else
    {
        info = UniString::CreateFromInt32( pProgrInfo->GetCurInsert() );
        info.Append( sal_Unicode('/') );
        info.Append( UniString::CreateFromInt32( pProgrInfo->GetInsertCount() ) );
        aFiInsInfo.SetText(info);
    }

    Application::Reschedule();
    return( bCancel?0L:1L );
}

// Oeffnet den Modalen Dialog und startet einen Timer der die Arbeitsfunktion
// nach oeffnen des Dialogs ausfuehrt
short BreakDlg::Execute()
{
  aTimer.SetTimeout( 10 );
  aTimer.SetTimeoutHdl( LINK( this, BreakDlg, InitialUpdate ) );
  aTimer.Start();

  return SfxModalDialog::Execute();
}

// Linkmethode welche die Arbeitsfunktion startet
IMPL_LINK( BreakDlg, InitialUpdate, Timer*, pTimer )
{
    pDrView->DoImportMarkedMtf(pProgrInfo);
    EndDialog(TRUE);
    return 0L;
}

} // end of namespace sd
<|endoftext|>


<commit_before>#pragma once

#include <nlohmann/json.hpp>
#include <depthai-shared/pb/common/optional.hpp>

namespace dai {

    /**
     * Specify NeuralNetwork options such as blob path, ...
     */
    struct NeuralNetworkProperties {
        /**
         * Blob binary size in bytes
         */
        tl::optional<int64_t> blobSize;
        /**
         * Uri which points to blob
         */
        std::string blobUri;
        /**
         * Number of available output tensors in pool
         */
        tl::optional<int32_t> numFrames;
    };

    NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(NeuralNetworkProperties, blobSize, blobUri, numFrames)

}
<commit_msg>Updated NN properties<commit_after>#pragma once

#include <nlohmann/json.hpp>
#include <depthai-shared/pb/common/optional.hpp>

namespace dai {

    /**
     * Specify NeuralNetwork options such as blob path, ...
     */
    struct NeuralNetworkProperties {
        /**
         * Blob binary size in bytes
         */
        tl::optional<uint32_t> blobSize;
        /**
         * Uri which points to blob
         */
        std::string blobUri;
        /**
         * Number of available output tensors in pool
         */
        std::uint32_t numFrames = 8;
    };

    NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(NeuralNetworkProperties, blobSize, blobUri, numFrames)

}
<|endoftext|>


<commit_before><commit_msg>add natural merge sort<commit_after><|endoftext|>


<commit_before><commit_msg>Use std::make_reverse_iterator directly<commit_after><|endoftext|>


<commit_before>#include "catch.hpp"

#include "./shunting-yard.h"

TokenMap_t vars, tmap, key3, emap;

void PREPARE_ENVIRONMENT() {
  vars["pi"] = 3.14;
  vars["b1"] = 0.0;
  vars["b2"] = 0.86;
  vars["str1"] = "foo";
  vars["str2"] = "bar";
  vars["str3"] = "foobar";
  vars["str4"] = "foo10";
  vars["str5"] = "10bar";

  vars["map"] = &tmap;
  tmap["key"] = "mapped value";
  tmap["key1"] = "second mapped value";
  tmap["key2"] = 10;
  tmap["key3"] = &key3;
  tmap["key3"]["map1"] = "inception1";
  tmap["key3"]["map2"] = "inception2";

  emap["a"] = 10;
  emap["b"] = 20;
}

TEST_CASE("Static calculate::calculate()") {
  REQUIRE(calculator::calculate("-pi + 1", &vars).asDouble() == Approx(-2.14));
  REQUIRE(calculator::calculate("-pi + 1 * b1", &vars).asDouble() == Approx(-3.14));
  REQUIRE(calculator::calculate("(20+10)*3/2-3", &vars).asDouble() == Approx(42.0));
  REQUIRE(calculator::calculate("1 << 4", &vars).asDouble() == Approx(16.0));
  REQUIRE(calculator::calculate("1+(-2*3)", &vars).asDouble() == Approx(-5));
}

TEST_CASE("calculate::compile() and calculate::eval()") {
  calculator c1;
  c1.compile("-pi+1", &vars);
  REQUIRE(c1.eval().asDouble() == Approx(-2.14));

  calculator c2("pi+4", &vars);
  REQUIRE(c2.eval().asDouble() == Approx(7.14));
  REQUIRE(c2.eval().asDouble() == Approx(7.14));

  calculator c3("pi+b1+b2", &vars);
  REQUIRE(c3.eval(&vars).asDouble() == Approx(4.0));
}

TEST_CASE("Boolean expressions") {
  REQUIRE_FALSE(calculator::calculate("3 < 3").asBool());
  REQUIRE(calculator::calculate("3 <= 3").asBool());
  REQUIRE_FALSE(calculator::calculate("3 > 3").asBool());
  REQUIRE(calculator::calculate("3 >= 3").asBool());
  REQUIRE(calculator::calculate("3 == 3").asBool());
  REQUIRE_FALSE(calculator::calculate("3 != 3").asBool());

  REQUIRE(calculator::calculate("(3 && true) == true").asBool());
  REQUIRE_FALSE(calculator::calculate("(3 && 0) == true").asBool());
  REQUIRE(calculator::calculate("(3 || 0) == true").asBool());
  REQUIRE_FALSE(calculator::calculate("(false || 0) == true").asBool());
}

TEST_CASE("String expressions") {
  REQUIRE(calculator::calculate("str1 + str2 == str3", &vars).asBool());
  REQUIRE_FALSE(calculator::calculate("str1 + str2 != str3", &vars).asBool());
  REQUIRE(calculator::calculate("str1 + 10 == str4", &vars).asBool());
  REQUIRE(calculator::calculate("10 + str2 == str5", &vars).asBool());

  REQUIRE(calculator::calculate("'foo' + \"bar\" == str3", &vars).asBool());
  REQUIRE(calculator::calculate("'foo' + \"bar\" != 'foobar\"'", &vars).asBool());
  REQUIRE(calculator::calculate("'foo' + \"bar\\\"\" == 'foobar\"'", &vars).asBool());
}

TEST_CASE("Map access expressions") {
  REQUIRE(calculator::calculate("map[\"key\"]", &vars).asString() == "mapped value");
  REQUIRE(calculator::calculate("map[\"key\"+1]", &vars).asString() ==
          "second mapped value");
  REQUIRE(calculator::calculate("map[\"key\"+2] + 3 == 13", &vars).asBool() == true);
  REQUIRE(calculator::calculate("map.key1", &vars).asString() == "second mapped value");

  REQUIRE(calculator::calculate("map.key3.map1", &vars).asString() == "inception1");
  REQUIRE(calculator::calculate("map.key3['map2']", &vars).asString() == "inception2");
  REQUIRE_THROWS(calculator::calculate("map[\"no_key\"]", &vars));
}

TEST_CASE("Function usage expressions") {
  TokenMap_t vars;
  vars["pi"] = 3.141592653589793;
  vars["a"] = -4;

  REQUIRE(calculator::calculate("sqrt(4)", &vars).asDouble() == 2);
  REQUIRE(calculator::calculate("sin(pi)", &vars).asDouble() == Approx(0));
  REQUIRE(calculator::calculate("cos(pi/2)", &vars).asDouble() == Approx(0));
  REQUIRE(calculator::calculate("tan(pi)", &vars).asDouble() == Approx(0));
  calculator c("a + sqrt(4) * 2");
  REQUIRE(c.eval(&vars).asDouble() == 0);
  REQUIRE(calculator::calculate("sqrt(4-a*3) * 2", &vars).asDouble() == 8);
  REQUIRE(calculator::calculate("abs(42)", &vars).asDouble() == 42);
  REQUIRE(calculator::calculate("abs(-42)", &vars).asDouble() == 42);

  // With more than one argument:
  REQUIRE(calculator::calculate("pow(2,2)", &vars).asDouble() == 4);
  REQUIRE(calculator::calculate("pow(2,3)", &vars).asDouble() == 8);
  REQUIRE(calculator::calculate("pow(2,a)", &vars).asDouble() == Approx(1./16));
  REQUIRE(calculator::calculate("pow(2,a+4)", &vars).asDouble() == 1);

  REQUIRE_THROWS(calculator::calculate("foo(10)"));
  REQUIRE_THROWS(calculator::calculate("foo(10),"));
  REQUIRE_THROWS(calculator::calculate("foo,(10)"));

  // The test bellow will fail, TODO fix it:
  // REQUIRE_NOTHROW(calculator::calculate("print()"));
}

TEST_CASE("Scope management") {
  calculator c("pi+b1+b2");
  Scope scope;

  // Add vars to scope:
  scope.push(&vars);
  REQUIRE(c.eval(scope).asDouble() == Approx(4));

  tmap["b2"] = 1.0;
  scope.push(&tmap);
  REQUIRE(c.eval(scope).asDouble() == Approx(4.14));

  Scope scope_bkp = scope;

  // Remove vars from scope:
  scope.pop();
  scope.pop();

  scope.pop(); // Final pop for default functions.

  // Test what happens when you try to drop more namespaces than possible:
  REQUIRE_THROWS(scope.pop());

  // Load Saved Scope
  scope = scope_bkp;
  REQUIRE(c.eval(scope).asDouble() == Approx(4.14));

  // Testing with 3 namespaces:
  TokenMap_t vmap;
  vmap["b1"] = -1.14;
  scope.push(&vmap);
  REQUIRE(c.eval(scope).asDouble() == Approx(3.0));

  scope_bkp = scope;
  calculator c2("pi+b1+b2", scope_bkp);
  REQUIRE(c2.eval().asDouble() == Approx(3.0));
  REQUIRE(calculator::calculate("pi+b1+b2", scope_bkp).asDouble() == Approx(3.0));

  scope.clean();
}

TEST_CASE("Resource management") {
  calculator C1, C2("1 + 1");

  // These are likely to cause seg fault if
  // RPN copy is not handled:

  // Copy:
  REQUIRE_NOTHROW(calculator C3(C2));
  // Assignment:
  REQUIRE_NOTHROW(C1 = C2);
}

TEST_CASE("Exception management") {
  calculator ecalc;
  ecalc.compile("a+b+del", &emap);
  emap["del"] = 30;

  REQUIRE_THROWS(ecalc.eval());
  REQUIRE_NOTHROW(ecalc.eval(&emap));

  emap.erase("del");
  REQUIRE_THROWS(ecalc.eval(&emap));

  emap["del"] = 0;
  emap.erase("a");
  REQUIRE_NOTHROW(ecalc.eval(&emap));

  REQUIRE_THROWS(calculator c5("10 + - - 10"));
  REQUIRE_THROWS(calculator c5("10 + +"));
  REQUIRE_NOTHROW(calculator c5("10 + -10"));
  REQUIRE_THROWS(calculator c5("c.[10]"));

  TokenMap_t v1, v2;
  v1["map"] = &v2;
  // Mismatched types, no supported operators.
  REQUIRE_THROWS(calculator("map == 0").eval(&v1));
}
<commit_msg>Formatting.<commit_after>#include "catch.hpp"

#include "./shunting-yard.h"

TokenMap_t vars, tmap, key3, emap;

void PREPARE_ENVIRONMENT() {
  vars["pi"] = 3.14;
  vars["b1"] = 0.0;
  vars["b2"] = 0.86;
  vars["str1"] = "foo";
  vars["str2"] = "bar";
  vars["str3"] = "foobar";
  vars["str4"] = "foo10";
  vars["str5"] = "10bar";

  vars["map"] = &tmap;
  tmap["key"] = "mapped value";
  tmap["key1"] = "second mapped value";
  tmap["key2"] = 10;
  tmap["key3"] = &key3;
  tmap["key3"]["map1"] = "inception1";
  tmap["key3"]["map2"] = "inception2";

  emap["a"] = 10;
  emap["b"] = 20;
}

TEST_CASE("Static calculate::calculate()") {
  REQUIRE(calculator::calculate("-pi + 1", &vars).asDouble() == Approx(-2.14));
  REQUIRE(calculator::calculate("-pi + 1 * b1", &vars).asDouble() == Approx(-3.14));
  REQUIRE(calculator::calculate("(20+10)*3/2-3", &vars).asDouble() == Approx(42.0));
  REQUIRE(calculator::calculate("1 << 4", &vars).asDouble() == Approx(16.0));
  REQUIRE(calculator::calculate("1+(-2*3)", &vars).asDouble() == Approx(-5));
}

TEST_CASE("calculate::compile() and calculate::eval()") {
  calculator c1;
  c1.compile("-pi+1", &vars);
  REQUIRE(c1.eval().asDouble() == Approx(-2.14));

  calculator c2("pi+4", &vars);
  REQUIRE(c2.eval().asDouble() == Approx(7.14));
  REQUIRE(c2.eval().asDouble() == Approx(7.14));

  calculator c3("pi+b1+b2", &vars);
  REQUIRE(c3.eval(&vars).asDouble() == Approx(4.0));
}

TEST_CASE("Boolean expressions") {
  REQUIRE_FALSE(calculator::calculate("3 < 3").asBool());
  REQUIRE(calculator::calculate("3 <= 3").asBool());
  REQUIRE_FALSE(calculator::calculate("3 > 3").asBool());
  REQUIRE(calculator::calculate("3 >= 3").asBool());
  REQUIRE(calculator::calculate("3 == 3").asBool());
  REQUIRE_FALSE(calculator::calculate("3 != 3").asBool());

  REQUIRE(calculator::calculate("(3 && true) == true").asBool());
  REQUIRE_FALSE(calculator::calculate("(3 && 0) == true").asBool());
  REQUIRE(calculator::calculate("(3 || 0) == true").asBool());
  REQUIRE_FALSE(calculator::calculate("(false || 0) == true").asBool());
}

TEST_CASE("String expressions") {
  REQUIRE(calculator::calculate("str1 + str2 == str3", &vars).asBool());
  REQUIRE_FALSE(calculator::calculate("str1 + str2 != str3", &vars).asBool());
  REQUIRE(calculator::calculate("str1 + 10 == str4", &vars).asBool());
  REQUIRE(calculator::calculate("10 + str2 == str5", &vars).asBool());

  REQUIRE(calculator::calculate("'foo' + \"bar\" == str3", &vars).asBool());
  REQUIRE(calculator::calculate("'foo' + \"bar\" != 'foobar\"'", &vars).asBool());
  REQUIRE(calculator::calculate("'foo' + \"bar\\\"\" == 'foobar\"'", &vars).asBool());
}

TEST_CASE("Map access expressions") {
  REQUIRE(calculator::calculate("map[\"key\"]", &vars).asString() == "mapped value");
  REQUIRE(calculator::calculate("map[\"key\"+1]", &vars).asString() ==
          "second mapped value");
  REQUIRE(calculator::calculate("map[\"key\"+2] + 3 == 13", &vars).asBool() == true);
  REQUIRE(calculator::calculate("map.key1", &vars).asString() == "second mapped value");

  REQUIRE(calculator::calculate("map.key3.map1", &vars).asString() == "inception1");
  REQUIRE(calculator::calculate("map.key3['map2']", &vars).asString() == "inception2");
  REQUIRE_THROWS(calculator::calculate("map[\"no_key\"]", &vars));
}

TEST_CASE("Function usage expressions") {
  TokenMap_t vars;
  vars["pi"] = 3.141592653589793;
  vars["a"] = -4;

  REQUIRE(calculator::calculate("sqrt(4)", &vars).asDouble() == 2);
  REQUIRE(calculator::calculate("sin(pi)", &vars).asDouble() == Approx(0));
  REQUIRE(calculator::calculate("cos(pi/2)", &vars).asDouble() == Approx(0));
  REQUIRE(calculator::calculate("tan(pi)", &vars).asDouble() == Approx(0));
  calculator c("a + sqrt(4) * 2");
  REQUIRE(c.eval(&vars).asDouble() == 0);
  REQUIRE(calculator::calculate("sqrt(4-a*3) * 2", &vars).asDouble() == 8);
  REQUIRE(calculator::calculate("abs(42)", &vars).asDouble() == 42);
  REQUIRE(calculator::calculate("abs(-42)", &vars).asDouble() == 42);

  // With more than one argument:
  REQUIRE(calculator::calculate("pow(2,2)", &vars).asDouble() == 4);
  REQUIRE(calculator::calculate("pow(2,3)", &vars).asDouble() == 8);
  REQUIRE(calculator::calculate("pow(2,a)", &vars).asDouble() == Approx(1./16));
  REQUIRE(calculator::calculate("pow(2,a+4)", &vars).asDouble() == 1);

  REQUIRE_THROWS(calculator::calculate("foo(10)"));
  REQUIRE_THROWS(calculator::calculate("foo(10),"));
  REQUIRE_THROWS(calculator::calculate("foo,(10)"));

  // The test bellow will fail, TODO fix it:
  // REQUIRE_NOTHROW(calculator::calculate("print()"));
}

TEST_CASE("Scope management") {
  calculator c("pi+b1+b2");
  Scope scope;

  // Add vars to scope:
  scope.push(&vars);
  REQUIRE(c.eval(scope).asDouble() == Approx(4));

  tmap["b2"] = 1.0;
  scope.push(&tmap);
  REQUIRE(c.eval(scope).asDouble() == Approx(4.14));

  Scope scope_bkp = scope;

  // Remove vars from scope:
  scope.pop();
  scope.pop();

  scope.pop();  // Final pop for default functions.

  // Test what happens when you try to drop more namespaces than possible:
  REQUIRE_THROWS(scope.pop());

  // Load Saved Scope
  scope = scope_bkp;
  REQUIRE(c.eval(scope).asDouble() == Approx(4.14));

  // Testing with 3 namespaces:
  TokenMap_t vmap;
  vmap["b1"] = -1.14;
  scope.push(&vmap);
  REQUIRE(c.eval(scope).asDouble() == Approx(3.0));

  scope_bkp = scope;
  calculator c2("pi+b1+b2", scope_bkp);
  REQUIRE(c2.eval().asDouble() == Approx(3.0));
  REQUIRE(calculator::calculate("pi+b1+b2", scope_bkp).asDouble() == Approx(3.0));

  scope.clean();
}

TEST_CASE("Resource management") {
  calculator C1, C2("1 + 1");

  // These are likely to cause seg fault if
  // RPN copy is not handled:

  // Copy:
  REQUIRE_NOTHROW(calculator C3(C2));
  // Assignment:
  REQUIRE_NOTHROW(C1 = C2);
}

TEST_CASE("Exception management") {
  calculator ecalc;
  ecalc.compile("a+b+del", &emap);
  emap["del"] = 30;

  REQUIRE_THROWS(ecalc.eval());
  REQUIRE_NOTHROW(ecalc.eval(&emap));

  emap.erase("del");
  REQUIRE_THROWS(ecalc.eval(&emap));

  emap["del"] = 0;
  emap.erase("a");
  REQUIRE_NOTHROW(ecalc.eval(&emap));

  REQUIRE_THROWS(calculator c5("10 + - - 10"));
  REQUIRE_THROWS(calculator c5("10 + +"));
  REQUIRE_NOTHROW(calculator c5("10 + -10"));
  REQUIRE_THROWS(calculator c5("c.[10]"));

  TokenMap_t v1, v2;
  v1["map"] = &v2;
  // Mismatched types, no supported operators.
  REQUIRE_THROWS(calculator("map == 0").eval(&v1));
}
<|endoftext|>


<commit_before>// RUN: grep -Ev "// *[A-Z-]+:" %s | clang-format -style=LLVM -cursor=6 \
// RUN:   | FileCheck -strict-whitespace %s
// CHECK: {{^\{ "Cursor": 4, }}
// CHECK: {{^int\ \i;$}}
 int    i;
<commit_msg>Fix clang-format test. I believe that the new behavior is better.<commit_after>// RUN: grep -Ev "// *[A-Z-]+:" %s | clang-format -style=LLVM -cursor=6 \
// RUN:   | FileCheck -strict-whitespace %s
// CHECK: {{^\{ "Cursor": 3, }}
// CHECK: {{^int\ \i;$}}
 int    i;
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include <iostream>

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

#include <vector>

#include <util/PlatformUtils.hpp>

#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

#include <XMLFileReporter.hpp>
#include <FileUtility.hpp>

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::endl;
#endif

// This is here for memory leak testing.
#if defined(_DEBUG)
#include <crtdbg.h>
#endif

static const char* const	excludeStylesheets[] =
{
//	"impincl16.xml",
	0
};

inline bool
checkForExclusion(XalanDOMString currentFile)
{
	for (int i = 0; excludeStylesheets[i] != 0; ++i)
	{
		if (equals(currentFile, XalanDOMString(excludeStylesheets[i])))
		{
			return true;
		}
	}

	return false;
}

bool
getParams(int			argc,
		  const char*	/* argv */[])
{
	// This needs additional work.
	if (argc != 1)
	{
		cerr << "Usage: Stressmem" << endl;

		return false;
	}
	else
	{
		return true;
	}
}

#if defined(XALAN_NO_NAMESPACES)
typedef vector<XalanDOMString>		FileNameVectorType;
#else
typedef std::vector<XalanDOMString>	FileNameVectorType;
#endif

int
main(
	 int			argc,
	 const char*	argv[])
{

#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	if (getParams(argc, argv) == true)
	{
		// Defined root for performance directory. Based on PD's machine.
		const XalanDOMString	confDir(XALAN_STATIC_UCODE_STRING("\\xsl-test\\conf\\"));
		const XalanDOMString	outDir(XALAN_STATIC_UCODE_STRING("\\xsl-test\\cplus-mem\\"));

		FileUtility			f;

		// Get the list of Directories that are below perf
		const FileNameVectorType	dirs = f.getDirectoryNames(confDir);

		//XMLFileReporter	logFile("cpp.xml");
		//logFile.logTestFileInit("Memory Testing - Memory leaks detected during ConformanceTests. ");

		try
		{
			// Call the static initializers...
			XMLPlatformUtils::Initialize();

			XalanTransformer::initialize();

			{
				XalanTransformer		transformEngine;

				const XalanDOMString	theXSLSuffix(XALAN_STATIC_UCODE_STRING(".xsl"));
				const XalanDOMString	theXMLSuffix(XALAN_STATIC_UCODE_STRING(".xml"));
				const XalanDOMString	pathSep(XALAN_STATIC_UCODE_STRING("\\"));

				for(FileNameVectorType::size_type	j = 0; j < dirs.size(); ++j)
				{
					const FileNameVectorType	files = f.getTestFileNames(confDir, dirs[j]);

					for(FileNameVectorType::size_type i = 0; i < files.size(); ++i)
					{
						if (checkForExclusion(files[i]) == false)
						{
							// Output file name to result log.
							//logFile.logTestCaseInit(files[i]);
							cout << files[i] << endl;

							const XalanDOMString	theXMLFile= confDir + dirs[j] + pathSep + files[i];
							const XalanDOMString	outFile = outDir + dirs[j] + pathSep + files[i];
							const XalanDOMString	theXSLFile = f.GenerateFileName(theXMLFile,"xsl");
							const XalanDOMString	theOutputFile = f.GenerateFileName(outFile, "out");

							// Do a total end to end transform with no pre parsing of either xsl or xml files.
							XSLTResultTarget		theResultTarget(theOutputFile);

							const XSLTInputSource	xslInputSource(c_wstr(theXSLFile));
							const XSLTInputSource	xmlInputSource(c_wstr(theXMLFile));

							int		theResult =
								transformEngine.transform(xmlInputSource, xslInputSource, theResultTarget);

							if(theResult != 0)
							{
								cerr << "XalanError: \n" << transformEngine.getLastError();
							}
						}
					}
				}
			}

			XalanTransformer::terminate();

			XMLPlatformUtils::Terminate();
		}
		catch(...)
		{
			cerr << "Exception caught!!!" << endl << endl;
		}
	}

	return 0;
}
<commit_msg>Updated to work with new FileUtility<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include <iostream>

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

#include <vector>

#include <util/PlatformUtils.hpp>

#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

#include <XMLFileReporter.hpp>
#include <FileUtility.hpp>

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::endl;
#endif

// This is here for memory leak testing.
#if defined(_DEBUG)
#include <crtdbg.h>
#endif

static const char* const	excludeStylesheets[] =
{
//	"impincl16.xml",
	0
};

inline bool
checkForExclusion(XalanDOMString currentFile)
{
	for (int i = 0; excludeStylesheets[i] != 0; ++i)
	{
		if (equals(currentFile, XalanDOMString(excludeStylesheets[i])))
		{
			return true;
		}
	}

	return false;
}

bool
getParams(int			argc,
		  const char*	/* argv */[])
{
	// This needs additional work.
	if (argc != 1)
	{
		cerr << "Usage: Stressmem" << endl;

		return false;
	}
	else
	{
		return true;
	}
}

#if defined(XALAN_NO_NAMESPACES)
typedef vector<XalanDOMString>		FileNameVectorType;
#else
typedef std::vector<XalanDOMString>	FileNameVectorType;
#endif

int
main(
	 int			argc,
	 const char*	argv[])
{

#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	if (getParams(argc, argv) == true)
	{
		// Defined root for performance directory. Based on PD's machine.
		const XalanDOMString	confDir(XALAN_STATIC_UCODE_STRING("d:\\xslt\\xsl-test\\conf\\"));
		const XalanDOMString	outDir(XALAN_STATIC_UCODE_STRING("d:\\xslt\\xsl-test\\cplus-mem\\"));

		FileUtility			f;

		// Get the list of Directories that are below perf
		const FileNameVectorType	dirs = f.getDirectoryNames(confDir);

		//XMLFileReporter	logFile("cpp.xml");
		//logFile.logTestFileInit("Memory Testing - Memory leaks detected during ConformanceTests. ");

		try
		{
			// Call the static initializers...
			XMLPlatformUtils::Initialize();

			XalanTransformer::initialize();

			{
				XalanTransformer		transformEngine;

				const XalanDOMString	theXSLSuffix(XALAN_STATIC_UCODE_STRING(".xsl"));
				const XalanDOMString	theXMLSuffix(XALAN_STATIC_UCODE_STRING(".xml"));
				const XalanDOMString	pathSep(XALAN_STATIC_UCODE_STRING("\\"));

				for(FileNameVectorType::size_type	j = 0; j < dirs.size(); ++j)
				{
					const FileNameVectorType	files = f.getTestFileNames(confDir, dirs[j]);

					for(FileNameVectorType::size_type i = 0; i < files.size(); ++i)
					{
						if (checkForExclusion(files[i]) == false)
						{
							// Output file name to result log.
							//logFile.logTestCaseInit(files[i]);
							cout << files[i] << endl;

					//		const XalanDOMString	theXMLFile= confDir + dirs[j] + pathSep + files[i];
					//		const XalanDOMString	outFile = outDir + dirs[j] + pathSep + files[i];
					//		const XalanDOMString	theXSLFile = f.GenerateFileName(theXMLFile,"xsl");
					//		const XalanDOMString	theOutputFile = f.GenerateFileName(outFile, "out");

							const XalanDOMString  theXSLFile= confDir + dirs[j] + pathSep + files[i];
							const XalanDOMString  theXMLFile = f.GenerateFileName(theXSLFile,"xml");
							const XalanDOMString  theOutput =  outDir + dirs[j] + pathSep + files[i];
							const XalanDOMString  theOutputFile = f.GenerateFileName(theOutput, "out");

							// Do a total end to end transform with no pre parsing of either xsl or xml files.
							XSLTResultTarget		theResultTarget(theOutputFile);

							const XSLTInputSource	xslInputSource(c_wstr(theXSLFile));
							const XSLTInputSource	xmlInputSource(c_wstr(theXMLFile));

							int	theResult =
								transformEngine.transform(xmlInputSource, xslInputSource, theResultTarget);

							if(theResult != 0)
							{
								cerr << "XalanError: \n" << transformEngine.getLastError();
							}
						}
					}
				}
			}

			XalanTransformer::terminate();

			XMLPlatformUtils::Terminate();
		}
		catch(...)
		{
			cerr << "Exception caught!!!" << endl << endl;
		}
	}

	return 0;
}
<|endoftext|>