<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#ifndef ROSETTASTONE_CARD_ENUMS_HPP
#define ROSETTASTONE_CARD_ENUMS_HPP

#include <string>
#include <string_view>

namespace RosettaStone
{
//! \brief An enumerator for identifying the class of the card.
enum class CardClass
{
#define X(a) a,
#include "CardClass.def"
#undef X
};

const std::string CARD_CLASS_STR[] = {
#define X(a) #a,
#include "CardClass.def"
#undef X
};

//! \brief An enumerator for identifying the set of the card.
enum class CardSet
{
#define X(a) a,
#include "CardSet.def"
#undef X
};

const std::string CARD_SET_STR[] = {
#define X(a) #a,
#include "CardSet.def"
#undef X
};

//! \brief An enumerator for identifying the type of the card.
enum class CardType
{
#define X(a) a,
#include "CardType.def"
#undef X
};

const std::string CARD_TYPE_STR[] = {
#define X(a) #a,
#include "CardType.def"
#undef X
};

//! \brief An enumerator for identifying the faction of the card.
enum class Faction
{
#define X(a) a,
#include "Faction.def"
#undef X
};

const std::string FACTION_STR[] = {
#define X(a) #a,
#include "Faction.def"
#undef X
};

//! \brief An enumerator for identifying the game tag of the card.
enum class GameTag
{
#define X(a) a,
#include "GameTag.def"
#undef X
};

const std::string GAME_TAG_STR[] = {
#define X(a) #a,
#include "GameTag.def"
#undef X
};

//! \brief An enumerator for identifying the play requirement of the card.
enum class PlayReq
{
#define X(a) a,
#include "PlayReq.def"
#undef X
};

const std::string PLAY_REQ_STR[] = {
#define X(a) #a,
#include "PlayReq.def"
#undef X
};

//! \brief An enumerator for identifying the race of the card.
enum class Race
{
#define X(a) a,
#include "Race.def"
#undef X
};

const std::string RACE_STR[] = {
#define X(a) #a,
#include "Race.def"
#undef X
};

//! \brief An enumerator for identifying the rarity of the card.
enum class Rarity
{
#define X(a) a,
#include "Rarity.def"
#undef X
};

const std::string RARITY_STR[] = {
#define X(a) #a,
#include "Rarity.def"
#undef X
};

//! \brief An enumerator for identifying the locale of the card.
enum class Locale
{
    UNKNOWN,
    enUS,
    enGB,
    frFR,
    deDE,
    koKR,
    esES,
    esMX,
    ruRU,
    zhTW,
    zhCN,
    itIT,
    ptBR,
    plPL,
    ptPT,
    jaJP,
    thTH
};

//! \brief An enumerator for identifying the mulligan state.
enum class Mulligan
{
    INVALID,
    INPUT,
    DEALING,
    WAITING,
    DONE
};

//! \brief An enumerator for identifying the choice type of the card.
enum class ChoiceType
{
    INVALID,
    MULLIGAN,
    GENERAL
};

//! \brief An enumerator for identifying the format type of the card.
enum class FormatType
{
    UNKNOWN,
    WILD,
    STANDARD
};

//! \brief An enumerator for identifying the play state.
enum class PlayState
{
    INVALID,
    PLAYING,
    WINNING,
    LOSING,
    WON,
    LOST,
    TIED,
    DISCONNECTED,
    CONCEDED
};

//! \brief An enumerator for indicating the state of the card.
enum class State
{
    INVALID,
    LOADING,
    RUNNING,
    COMPLETE
};

//! \brief An enumerator for indicating the game step.
enum class Step
{
    INVALID,
    BEGIN_FIRST,
    BEGIN_SHUFFLE,
    BEGIN_DRAW,
    BEGIN_MULLIGAN,
    MAIN_BEGIN,
    MAIN_READY,
    MAIN_RESOURCE,
    MAIN_DRAW,
    MAIN_START,
    MAIN_ACTION,
    MAIN_COMBAT,
    MAIN_END,
    MAIN_NEXT,
    FINAL_WRAPUP,
    FINAL_GAMEOVER,
    MAIN_CLEANUP,
    MAIN_START_TRIGGERS
};

template <class T>
T StrToEnum(const std::string_view&);
template <class T>
std::string_view EnumToStr(T);

#define STR2ENUM(TYPE, ARRAY)                                                \
    template <>                                                              \
    inline TYPE StrToEnum<TYPE>(const std::string_view& str)                 \
    {                                                                        \
        for (std::size_t i = 0; i < (sizeof(ARRAY) / sizeof(ARRAY[0])); ++i) \
        {                                                                    \
            if (ARRAY[i] == str)                                             \
            {                                                                \
                return TYPE(i);                                              \
            }                                                                \
        }                                                                    \
                                                                             \
        return TYPE(0);                                                      \
    }

#define ENUM2STR(TYPE, ARRAY)                       \
    template <>                                     \
    inline std::string_view EnumToStr<TYPE>(TYPE v) \
    {                                               \
        return ARRAY[static_cast<int>(v)];          \
    }

#define ENUM_AND_STR(TYPE, ARRAY) \
    STR2ENUM(TYPE, ARRAY)         \
    ENUM2STR(TYPE, ARRAY)

ENUM_AND_STR(CardClass, CARD_CLASS_STR)
ENUM_AND_STR(CardSet, CARD_SET_STR)
ENUM_AND_STR(CardType, CARD_TYPE_STR)
ENUM_AND_STR(Faction, FACTION_STR)
ENUM_AND_STR(GameTag, GAME_TAG_STR)
ENUM_AND_STR(PlayReq, PLAY_REQ_STR)
ENUM_AND_STR(Race, RACE_STR)
ENUM_AND_STR(Rarity, RARITY_STR)
}  // namespace RosettaStone

#endif  // ROSETTASTONE_CARD_ENUMS_HPP<commit_msg>refactor: Add enum 'Zone'<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#ifndef ROSETTASTONE_CARD_ENUMS_HPP
#define ROSETTASTONE_CARD_ENUMS_HPP

#include <string>
#include <string_view>

namespace RosettaStone
{
//! \brief An enumerator for identifying the class of the card.
enum class CardClass
{
#define X(a) a,
#include "CardClass.def"
#undef X
};

const std::string CARD_CLASS_STR[] = {
#define X(a) #a,
#include "CardClass.def"
#undef X
};

//! \brief An enumerator for identifying the set of the card.
enum class CardSet
{
#define X(a) a,
#include "CardSet.def"
#undef X
};

const std::string CARD_SET_STR[] = {
#define X(a) #a,
#include "CardSet.def"
#undef X
};

//! \brief An enumerator for identifying the type of the card.
enum class CardType
{
#define X(a) a,
#include "CardType.def"
#undef X
};

const std::string CARD_TYPE_STR[] = {
#define X(a) #a,
#include "CardType.def"
#undef X
};

//! \brief An enumerator for identifying the faction of the card.
enum class Faction
{
#define X(a) a,
#include "Faction.def"
#undef X
};

const std::string FACTION_STR[] = {
#define X(a) #a,
#include "Faction.def"
#undef X
};

//! \brief An enumerator for identifying the game tag of the card.
enum class GameTag
{
#define X(a) a,
#include "GameTag.def"
#undef X
};

const std::string GAME_TAG_STR[] = {
#define X(a) #a,
#include "GameTag.def"
#undef X
};

//! \brief An enumerator for identifying the play requirement of the card.
enum class PlayReq
{
#define X(a) a,
#include "PlayReq.def"
#undef X
};

const std::string PLAY_REQ_STR[] = {
#define X(a) #a,
#include "PlayReq.def"
#undef X
};

//! \brief An enumerator for identifying the race of the card.
enum class Race
{
#define X(a) a,
#include "Race.def"
#undef X
};

const std::string RACE_STR[] = {
#define X(a) #a,
#include "Race.def"
#undef X
};

//! \brief An enumerator for identifying the rarity of the card.
enum class Rarity
{
#define X(a) a,
#include "Rarity.def"
#undef X
};

const std::string RARITY_STR[] = {
#define X(a) #a,
#include "Rarity.def"
#undef X
};

//! \brief An enumerator for identifying the locale of the card.
enum class Locale
{
    UNKNOWN,
    enUS,
    enGB,
    frFR,
    deDE,
    koKR,
    esES,
    esMX,
    ruRU,
    zhTW,
    zhCN,
    itIT,
    ptBR,
    plPL,
    ptPT,
    jaJP,
    thTH
};

//! \brief An enumerator for identifying the mulligan state.
enum class Mulligan
{
    INVALID,
    INPUT,
    DEALING,
    WAITING,
    DONE
};

//! \brief An enumerator for identifying the choice type of the card.
enum class ChoiceType
{
    INVALID,
    MULLIGAN,
    GENERAL
};

//! \brief An enumerator for identifying the format type of the card.
enum class FormatType
{
    UNKNOWN,
    WILD,
    STANDARD
};

//! \brief An enumerator for identifying the play state.
enum class PlayState
{
    INVALID,
    PLAYING,
    WINNING,
    LOSING,
    WON,
    LOST,
    TIED,
    DISCONNECTED,
    CONCEDED
};

//! \brief An enumerator for indicating the state of the card.
enum class State
{
    INVALID,
    LOADING,
    RUNNING,
    COMPLETE
};

//! \brief An enumerator for indicating the game step.
enum class Step
{
    INVALID,
    BEGIN_FIRST,
    BEGIN_SHUFFLE,
    BEGIN_DRAW,
    BEGIN_MULLIGAN,
    MAIN_BEGIN,
    MAIN_READY,
    MAIN_RESOURCE,
    MAIN_DRAW,
    MAIN_START,
    MAIN_ACTION,
    MAIN_COMBAT,
    MAIN_END,
    MAIN_NEXT,
    FINAL_WRAPUP,
    FINAL_GAMEOVER,
    MAIN_CLEANUP,
    MAIN_START_TRIGGERS
};

//! \brief An enumerator for indicating the game zone.
enum class Zone
{
    INVALID,
    PLAY,
    DECK,
    HAND,
    GRAVEYARD,
    REMOVEDFROMGAME,
    SETASIDE,
    SECRET
};

template <class T>
T StrToEnum(const std::string_view&);
template <class T>
std::string_view EnumToStr(T);

#define STR2ENUM(TYPE, ARRAY)                                                \
    template <>                                                              \
    inline TYPE StrToEnum<TYPE>(const std::string_view& str)                 \
    {                                                                        \
        for (std::size_t i = 0; i < (sizeof(ARRAY) / sizeof(ARRAY[0])); ++i) \
        {                                                                    \
            if (ARRAY[i] == str)                                             \
            {                                                                \
                return TYPE(i);                                              \
            }                                                                \
        }                                                                    \
                                                                             \
        return TYPE(0);                                                      \
    }

#define ENUM2STR(TYPE, ARRAY)                       \
    template <>                                     \
    inline std::string_view EnumToStr<TYPE>(TYPE v) \
    {                                               \
        return ARRAY[static_cast<int>(v)];          \
    }

#define ENUM_AND_STR(TYPE, ARRAY) \
    STR2ENUM(TYPE, ARRAY)         \
    ENUM2STR(TYPE, ARRAY)

ENUM_AND_STR(CardClass, CARD_CLASS_STR)
ENUM_AND_STR(CardSet, CARD_SET_STR)
ENUM_AND_STR(CardType, CARD_TYPE_STR)
ENUM_AND_STR(Faction, FACTION_STR)
ENUM_AND_STR(GameTag, GAME_TAG_STR)
ENUM_AND_STR(PlayReq, PLAY_REQ_STR)
ENUM_AND_STR(Race, RACE_STR)
ENUM_AND_STR(Rarity, RARITY_STR)
}  // namespace RosettaStone

#endif  // ROSETTASTONE_CARD_ENUMS_HPP<|endoftext|>


<commit_before>/*************************************************
* SHA-160 Source File                            *
* (C) 1999-2006 The Botan Project                *
*************************************************/

#include <botan/sha160.h>
#include <botan/bit_ops.h>

namespace Botan {

namespace {

/*************************************************
* SHA-160 F1 Function                            *
*************************************************/
inline void F1(u32bit A, u32bit& B, u32bit C, u32bit D, u32bit& E, u32bit msg)
   {
   E += (D ^ (B & (C ^ D))) + msg + 0x5A827999 + rotate_left(A, 5);
   B  = rotate_left(B, 30);
   }

/*************************************************
* SHA-160 F2 Function                            *
*************************************************/
inline void F2(u32bit A, u32bit& B, u32bit C, u32bit D, u32bit& E, u32bit msg)
   {
   E += (B ^ C ^ D) + msg + 0x6ED9EBA1 + rotate_left(A, 5);
   B  = rotate_left(B, 30);
   }

/*************************************************
* SHA-160 F3 Function                            *
*************************************************/
inline void F3(u32bit A, u32bit& B, u32bit C, u32bit D, u32bit& E, u32bit msg)
   {
   E += ((B & C) | ((B | C) & D)) + msg + 0x8F1BBCDC + rotate_left(A, 5);
   B  = rotate_left(B, 30);
   }

/*************************************************
* SHA-160 F4 Function                            *
*************************************************/
inline void F4(u32bit A, u32bit& B, u32bit C, u32bit D, u32bit& E, u32bit msg)
   {
   E += (B ^ C ^ D) + msg + 0xCA62C1D6 + rotate_left(A, 5);
   B  = rotate_left(B, 30);
   }

}

extern "C" void sha160_core(u32bit[5], const byte[64], u32bit[80]);

/*************************************************
* SHA-160 Compression Function                   *
*************************************************/
void SHA_160::hash(const byte input[])
   {
   sha160_core(digest, input, W);
   }

/*************************************************
* Copy out the digest                            *
*************************************************/
void SHA_160::copy_out(byte output[])
   {
   for(u32bit j = 0; j != OUTPUT_LENGTH; ++j)
      output[j] = get_byte(j % 4, digest[j/4]);
   }

/*************************************************
* Clear memory of sensitive data                 *
*************************************************/
void SHA_160::clear() throw()
   {
   MDx_HashFunction::clear();
   digest[0] = 0x67452301;
   digest[1] = 0xEFCDAB89;
   digest[2] = 0x98BADCFE;
   digest[3] = 0x10325476;
   digest[4] = 0xC3D2E1F0;
   }

}
<commit_msg>Remove the C implementations of the round functions, no longer used<commit_after>/*************************************************
* SHA-160 Source File                            *
* (C) 1999-2006 The Botan Project                *
*************************************************/

#include <botan/sha160.h>
#include <botan/bit_ops.h>

namespace Botan {

extern "C" void sha160_core(u32bit[5], const byte[64], u32bit[80]);

/*************************************************
* SHA-160 Compression Function                   *
*************************************************/
void SHA_160::hash(const byte input[])
   {
   sha160_core(digest, input, W);
   }

/*************************************************
* Copy out the digest                            *
*************************************************/
void SHA_160::copy_out(byte output[])
   {
   for(u32bit j = 0; j != OUTPUT_LENGTH; ++j)
      output[j] = get_byte(j % 4, digest[j/4]);
   }

/*************************************************
* Clear memory of sensitive data                 *
*************************************************/
void SHA_160::clear() throw()
   {
   MDx_HashFunction::clear();
   digest[0] = 0x67452301;
   digest[1] = 0xEFCDAB89;
   digest[2] = 0x98BADCFE;
   digest[3] = 0x10325476;
   digest[4] = 0xC3D2E1F0;
   }

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: anyrefdg.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:11:36 $
 *
 *  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_ANYREFDG_HXX
#define SC_ANYREFDG_HXX

#ifndef _IMAGEBTN_HXX
#include <vcl/imagebtn.hxx>
#endif
#ifndef _EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _ACCEL_HXX
#include <vcl/accel.hxx>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif

class SfxObjectShell;
class ScRange;
class ScDocument;
class ScTabViewShell;
class ScAnyRefDlg;
class ScRefButton;
class ScFormulaCell;
class ScCompiler;

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

class ScRefEdit : public Edit
{
private:
    Timer               aTimer;
    ScAnyRefDlg*        pAnyRefDlg;         // parent dialog
    BOOL                bSilentFocus;       // for SilentGrabFocus()

    DECL_LINK( UpdateHdl, Timer* );

protected:
    virtual void        KeyInput( const KeyEvent& rKEvt );
    virtual void        GetFocus();
    virtual void        LoseFocus();

public:
                        ScRefEdit( ScAnyRefDlg* pParent, const ResId& rResId );
                        ScRefEdit( Window* pParent, const ResId& rResId );
    virtual             ~ScRefEdit();

    void                SetRefString( const XubString& rStr );
    virtual void        SetText( const XubString& rStr );
    virtual void        Modify();

    void                StartUpdateData();

    void                SilentGrabFocus();  // does not update any references

    void                SetRefDialog( ScAnyRefDlg* pDlg );
    inline ScAnyRefDlg* GetRefDialog() { return pAnyRefDlg; }
};

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

class ScRefButton : public ImageButton
{
private:
    Image               aImgRefStart;   /// Start reference input
    Image               aImgRefStartHC; /// Start reference input (high contrast)
    Image               aImgRefDone;    /// Stop reference input
    Image               aImgRefDoneHC;  /// Stop reference input (high contrast)
    ScAnyRefDlg*        pAnyRefDlg;     // parent dialog
    ScRefEdit*          pRefEdit;       // zugeordnetes Edit-Control

protected:
    virtual void        Click();
    virtual void        KeyInput( const KeyEvent& rKEvt );
    virtual void        GetFocus();
    virtual void        LoseFocus();

public:
                        ScRefButton( ScAnyRefDlg* pParent, const ResId& rResId, ScRefEdit* pEdit );
                        ScRefButton( Window* pParent, const ResId& rResId );

    void                SetReferences( ScAnyRefDlg* pDlg, ScRefEdit* pEdit );

    void                SetStartImage();
    void                SetEndImage();
    inline void         DoRef() { Click(); }
};

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

class ScAnyRefDlg : public SfxModelessDialog
{
    friend class        ScRefButton;
    friend class        ScRefEdit;

private:
    SfxBindings*        pMyBindings;
    ScRefEdit*          pRefEdit;               // aktives Eingabefeld
    ScRefButton*        pRefBtn;                // Button dazu
    String              sOldDialogText;         // Originaltitel des Dialogfensters
    Size                aOldDialogSize;         // Originalgroesse Dialogfenster
    Point               aOldEditPos;            // Originalposition des Eingabefeldes
    Size                aOldEditSize;           // Originalgroesse des Eingabefeldes
    Point               aOldButtonPos;          // Originalpositiuon des Buttons
    BOOL*               pHiddenMarks;           // Merkfeld fuer versteckte Controls
    Accelerator*        pAccel;                 // fuer Enter/Escape
    BOOL                bAccInserted;
    BOOL                bHighLightRef;
    BOOL                bEnableColorRef;
    ScFormulaCell*      pRefCell;
    ScCompiler*         pRefComp;
    Window*             pActiveWin;
    Timer               aTimer;
    String              aDocName;               // document on which the dialog was opened

    DECL_LINK( UpdateFocusHdl, Timer* );
    DECL_LINK( AccelSelectHdl, Accelerator* );

protected:
    BOOL                DoClose( USHORT nId );

    void                EnableSpreadsheets( BOOL bFlag = TRUE, BOOL bChilds = TRUE );
    void                SetDispatcherLock( BOOL bLock );

    virtual long        PreNotify( NotifyEvent& rNEvt );

    virtual void        RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL );
    virtual void        RefInputDone( BOOL bForced = FALSE );
    void                ShowSimpleReference( const XubString& rStr );
    void                ShowFormulaReference( const XubString& rStr );

public:
                        ScAnyRefDlg( SfxBindings* pB, SfxChildWindow* pCW,
                                     Window* pParent, USHORT nResId);
    virtual             ~ScAnyRefDlg();

    virtual void        SetReference( const ScRange& rRef, ScDocument* pDoc ) = 0;
    virtual void        AddRefEntry();

    virtual BOOL        IsRefInputMode() const;
    virtual BOOL        IsTableLocked() const;
    virtual BOOL        IsDocAllowed( SfxObjectShell* pDocSh ) const;

    void                ShowReference( const XubString& rStr );
    void                HideReference( BOOL bDoneRefMode = TRUE );

    void                ToggleCollapsed( ScRefEdit* pEdit, ScRefButton* pButton = NULL );
    void                ReleaseFocus( ScRefEdit* pEdit, ScRefButton* pButton = NULL );

    void                ViewShellChanged( ScTabViewShell* pScViewShell );
    void                SwitchToDocument();
    SfxBindings&        GetBindings();

    virtual void        SetActive() = 0;
//  virtual BOOL        Close();
    virtual void        StateChanged( StateChangedType nStateChange );
};

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

#endif // SC_ANYREFDG_HXX

<commit_msg>INTEGRATION: CWS calcwarnings (1.8.324); FILE MERGED 2006/12/01 08:53:31 nn 1.8.324.1: #i69284# warning-free: ui, wntmsci10<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: anyrefdg.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: vg $ $Date: 2007-02-27 13:19:30 $
 *
 *  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_ANYREFDG_HXX
#define SC_ANYREFDG_HXX

#ifndef _IMAGEBTN_HXX
#include <vcl/imagebtn.hxx>
#endif
#ifndef _EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _ACCEL_HXX
#include <vcl/accel.hxx>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif

class SfxObjectShell;
class ScRange;
class ScDocument;
class ScTabViewShell;
class ScAnyRefDlg;
class ScRefButton;
class ScFormulaCell;
class ScCompiler;

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

class ScRefEdit : public Edit
{
private:
    Timer               aTimer;
    ScAnyRefDlg*        pAnyRefDlg;         // parent dialog
    BOOL                bSilentFocus;       // for SilentGrabFocus()

    DECL_LINK( UpdateHdl, Timer* );

protected:
    virtual void        KeyInput( const KeyEvent& rKEvt );
    virtual void        GetFocus();
    virtual void        LoseFocus();

public:
                        ScRefEdit( ScAnyRefDlg* pParent, const ResId& rResId );
                        ScRefEdit( Window* pParent, const ResId& rResId );
    virtual             ~ScRefEdit();

    void                SetRefString( const XubString& rStr );
    using Edit::SetText;
    virtual void        SetText( const XubString& rStr );
    virtual void        Modify();

    void                StartUpdateData();

    void                SilentGrabFocus();  // does not update any references

    void                SetRefDialog( ScAnyRefDlg* pDlg );
    inline ScAnyRefDlg* GetRefDialog() { return pAnyRefDlg; }
};

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

class ScRefButton : public ImageButton
{
private:
    Image               aImgRefStart;   /// Start reference input
    Image               aImgRefStartHC; /// Start reference input (high contrast)
    Image               aImgRefDone;    /// Stop reference input
    Image               aImgRefDoneHC;  /// Stop reference input (high contrast)
    ScAnyRefDlg*        pAnyRefDlg;     // parent dialog
    ScRefEdit*          pRefEdit;       // zugeordnetes Edit-Control

protected:
    virtual void        Click();
    virtual void        KeyInput( const KeyEvent& rKEvt );
    virtual void        GetFocus();
    virtual void        LoseFocus();

public:
                        ScRefButton( ScAnyRefDlg* pParent, const ResId& rResId, ScRefEdit* pEdit );
                        ScRefButton( Window* pParent, const ResId& rResId );

    void                SetReferences( ScAnyRefDlg* pDlg, ScRefEdit* pEdit );

    void                SetStartImage();
    void                SetEndImage();
    inline void         DoRef() { Click(); }
};

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

class ScAnyRefDlg : public SfxModelessDialog
{
    friend class        ScRefButton;
    friend class        ScRefEdit;

private:
    SfxBindings*        pMyBindings;
    ScRefEdit*          pRefEdit;               // aktives Eingabefeld
    ScRefButton*        pRefBtn;                // Button dazu
    String              sOldDialogText;         // Originaltitel des Dialogfensters
    Size                aOldDialogSize;         // Originalgroesse Dialogfenster
    Point               aOldEditPos;            // Originalposition des Eingabefeldes
    Size                aOldEditSize;           // Originalgroesse des Eingabefeldes
    Point               aOldButtonPos;          // Originalpositiuon des Buttons
    BOOL*               pHiddenMarks;           // Merkfeld fuer versteckte Controls
    Accelerator*        pAccel;                 // fuer Enter/Escape
    BOOL                bAccInserted;
    BOOL                bHighLightRef;
    BOOL                bEnableColorRef;
    ScFormulaCell*      pRefCell;
    ScCompiler*         pRefComp;
    Window*             pActiveWin;
    Timer               aTimer;
    String              aDocName;               // document on which the dialog was opened

    DECL_LINK( UpdateFocusHdl, Timer* );
    DECL_LINK( AccelSelectHdl, Accelerator* );

protected:
    BOOL                DoClose( USHORT nId );

    void                EnableSpreadsheets( BOOL bFlag = TRUE, BOOL bChilds = TRUE );
    void                SetDispatcherLock( BOOL bLock );

    virtual long        PreNotify( NotifyEvent& rNEvt );

    virtual void        RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL );
    virtual void        RefInputDone( BOOL bForced = FALSE );
    void                ShowSimpleReference( const XubString& rStr );
    void                ShowFormulaReference( const XubString& rStr );

public:
                        ScAnyRefDlg( SfxBindings* pB, SfxChildWindow* pCW,
                                     Window* pParent, USHORT nResId);
    virtual             ~ScAnyRefDlg();

    virtual void        SetReference( const ScRange& rRef, ScDocument* pDoc ) = 0;
    virtual void        AddRefEntry();

    virtual BOOL        IsRefInputMode() const;
    virtual BOOL        IsTableLocked() const;
    virtual BOOL        IsDocAllowed( SfxObjectShell* pDocSh ) const;

    void                ShowReference( const XubString& rStr );
    void                HideReference( BOOL bDoneRefMode = TRUE );

    void                ToggleCollapsed( ScRefEdit* pEdit, ScRefButton* pButton = NULL );
    void                ReleaseFocus( ScRefEdit* pEdit, ScRefButton* pButton = NULL );

    void                ViewShellChanged( ScTabViewShell* pScViewShell );
    void                SwitchToDocument();
    SfxBindings&        GetBindings();

    virtual void        SetActive() = 0;
//  virtual BOOL        Close();
    virtual void        StateChanged( StateChangedType nStateChange );
};

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

#endif // SC_ANYREFDG_HXX

<|endoftext|>


<commit_before>#include "gvki/Logger.h"
#include "gvki/PathSeperator.h"
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <errno.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include "string.h"
#include "gvki/Debug.h"

#include <sys/stat.h>

#ifndef _WIN32

#include <dirent.h>
#include <unistd.h>
#define MKDIR_FAILS(d)     (mkdir(d, 0770) != 0)
#define DIR_ALREADY_EXISTS (errno == EEXIST)

static void checkDirectoryExists(const char* dirName) {
    DIR* dh = opendir(dirName);
    if (dh != NULL)
    {
        closedir(dh);
        return;
    }
    ERROR_MSG(strerror(errno) << ". Directory was :" << dirName);
    exit(1);
}

#else

#include <inttypes.h>
#include <Windows.h>
#define MKDIR_FAILS(d)     (CreateDirectory(ss.str().c_str(), NULL) == 0)
#define DIR_ALREADY_EXISTS (GetLastError() == ERROR_ALREADY_EXISTS)

static void checkDirectoryExists(const char* dirName) {
    DWORD ftyp = GetFileAttributesA(dirName);
    if ((ftyp != INVALID_FILE_ATTRIBUTES) && ftyp & FILE_ATTRIBUTE_DIRECTORY)
        return;
    ERROR_MSG(strerror(errno) << ". Directory was :" << dirName);
    exit(1);
}

#endif

using namespace std;
using namespace gvki;

// Maximum number of files or directories
// that can be created
static const int maxFiles = 10000;

Logger& Logger::Singleton()
{
    static Logger l;
    return l;
}

Logger::Logger()
{
    int count = 0;
    bool success= false;

    // FIXME: Reading from the environment probably doesn't belong in here
    // but it makes implementing the singleton a lot easier
    std::string directoryPrefix;

    const char* envTemp = getenv("GVKI_ROOT");
    if (envTemp)
    {
        DEBUG_MSG("Using GVKI_ROOT value as destination for directories");

        checkDirectoryExists(envTemp);

        directoryPrefix = envTemp;

    }
    else
    {
        // Use the current working directory
        DEBUG_MSG("Using current working directory as destination for directories");

        // FIXME: Hard-coding this size is gross
        #define MAX_DIR_LENGTH 1024

#ifndef _WIN32
        char cwdArray[MAX_DIR_LENGTH];
        char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)/sizeof(char));
        if (!cwdResult)
#else
        char cwdResult[MAX_DIR_LENGTH];
        if (GetCurrentDirectory(MAX_DIR_LENGTH, cwdResult) == 0)
#endif
        {
            ERROR_MSG(strerror(errno) << ". Could not read the current working directory");
            exit(1);
        }
        else
            directoryPrefix = cwdResult;
    }
    directoryPrefix += PATH_SEP "gvki";
    DEBUG_MSG("Directory prefix is \"" << directoryPrefix << "\"");

    // Keep trying a directoryPrefix name with a number as suffix
    // until we find an available one or we exhaust the maximum
    // allowed number
    while (count < maxFiles)
    {
        stringstream ss;
        ss <<  directoryPrefix << "-" << count;
        ++count;

        // Make the directoryPrefix
        if (MKDIR_FAILS(ss.str().c_str()))
        {
            if (!DIR_ALREADY_EXISTS)
            {
                ERROR_MSG(strerror(errno) << ". Directory was :" << directoryPrefix);
                exit(1);
            }

            // It already exists, try again
            continue;
        }

        this->directory = ss.str();
        success = true;
        break;
    }

    if (!success)
    {
        ERROR_MSG("Exhausted available directory names or couldn't create any");
        exit(1);
    }

    DEBUG_MSG("Directory used for logging is \"" << this->directory << "\"");

    openLog();
}

void Logger::openLog()
{
    // FIXME: We should use mkstemp() or something
    std::stringstream ss;
    ss << directory << PATH_SEP << "log.json";
    output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate);

    if (! output->good())
    {
        ERROR_MSG("Failed to create file (" << ss.str() <<  ") to write log to");
        exit(1);
    }

    // Start of JSON array
    *output << "[" << std::endl;
}

void Logger::closeLog()
{
    // End of JSON array
    *output << std::endl << "]" << std::endl;
    output->close();
}

Logger::~Logger()
{
    closeLog();
    delete output;
}

void Logger::dump(cl_kernel k)
{
    // Output JSON format defined by
    // http://multicore.doc.ic.ac.uk/tools/GPUVerify/docs/json_format.html
    KernelInfo& ki = kernels[k];

    static bool isFirst = true;

    if (!isFirst)
    {
        // Emit array element seperator
        // to seperate from previous dump
        *output << "," << endl;
    }
    isFirst = false;

    *output << "{" << endl << "\"language\": \"OpenCL\"," << endl;

    std::string kernelSourceFile = dumpKernelSource(ki);

    *output << "\"kernel_file\": \"" << kernelSourceFile << "\"," << endl;

    // FIXME: Teach GPUVerify how to handle non zero global_offset
    // FIXME: Document this json attribute!
    // Only emit global_offset if its non zero
    bool hasNonZeroGlobalOffset = false;
    for (int index=0; index < ki.globalWorkOffset.size() ; ++index)
    {
        if (ki.globalWorkOffset[index] != 0)
            hasNonZeroGlobalOffset = true;
    }
    if (hasNonZeroGlobalOffset)
    {
        *output << "\"global_offset\": ";
        printJSONArray(ki.globalWorkOffset);
        *output << "," << endl;
    }

    *output << "\"global_size\": ";
    printJSONArray(ki.globalWorkSize);
    *output << "," << endl;

    *output << "\"local_size\": ";
    printJSONArray(ki.localWorkSize);
    *output << "," << endl;

    assert( (ki.globalWorkOffset.size() == ki.globalWorkSize.size()) &&
            (ki.globalWorkSize.size() == ki.localWorkSize.size()) &&
            "dimension mismatch");

    *output << "\"entry_point\": \"" << ki.entryPointName << "\"";

    // entry_point might be the last entry is there were no kernel args
    if (ki.arguments.size() == 0)
        *output << endl;
    else
    {
        *output << "," << endl << "\"kernel_arguments\": [ " << endl;
        for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex)
        {
            printJSONKernelArgumentInfo(ki.arguments[argIndex]);
            if (argIndex != (ki.arguments.size() -1))
                *output << "," << endl;
        }
        *output << endl << "]" << endl;
    }

    *output << "}";
}

void Logger::printJSONArray(std::vector<size_t>& array)
{
    *output << "[ ";
    for (int index=0; index < array.size(); ++index)
    {
        *output << array[index];

        if (index != (array.size() -1))
            *output << ", ";
    }
    *output << "]";
}

void Logger::printJSONKernelArgumentInfo(ArgInfo& ai)
{
    *output << "{";
    if (ai.argValue == NULL)
    {
        // NULL was passed to clSetKernelArg()
        // That implies its for unallocated memory
        *output << "\"type\": \"array\",";

        // If the arg is for local memory
        if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler))
        {
            // We assume this means this arguments is for local memory
            // where size actually means the sizeof the underlying buffer
            // rather than the size of the type.
            *output << "\"size\" : " << ai.argSize;
        }
        *output << "}";
        return;
    }

    // FIXME:
    // Eurgh... the spec says
    // ```
    // If the argument is a buffer object, the arg_value pointer can be NULL or
    // point to a NULL value in which case a NULL value will be used as the
    // value for the argument declared as a pointer to __global or __constant
    // memory in the kernel.  ```
    //
    // This makes it impossible (seeing as we don't know which address space
    // the arguments are in) to work out the argument type once derefencing the
    // pointer and finding it's equal zero because it could be a scalar constant
    // (of value 0) or it could be an unintialised array!

    // Hack:
    // It's hard to determine what type the argument is.
    // We can't dereference the void* to check if
    // it points to cl_mem we previously stored
    //
    // In some implementations cl_mem will be a pointer
    // which poses a risk if a scalar parameter of the same size
    // as the pointer type.
    if (ai.argSize == sizeof(cl_mem))
    {
       cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);

       // We might be reading invalid data now
       if (buffers.count(mightBecl_mem) == 1)
       {
           // We're going to assume it's cl_mem that we saw before
           *output << "\"type\": \"array\",";
           BufferInfo& bi = buffers[mightBecl_mem];

           *output << "\"size\": " << bi.size << "}";
           return;
       }

    }

    // Hack: a similar hack of the image types
    if (ai.argSize == sizeof(cl_mem))
    {
       cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);

       // We might be reading invalid data now
       if (images.count(mightBecl_mem) == 1)
       {
           // We're going to assume it's cl_mem that we saw before
           *output << "\"type\": \"image\"}";
           return;
       }

    }

    // Hack: a similar hack for the samplers
    if (ai.argSize == sizeof(cl_sampler))
    {
       cl_sampler mightBecl_sampler = *((cl_sampler*) ai.argValue);

       // We might be reading invalid data now
       if (samplers.count(mightBecl_sampler) == 1)
       {
           // We're going to assume it's cl_mem that we saw before
           *output << "\"type\": \"sampler\"}";
           return;
       }

    }

    // I guess it's scalar???
    *output << "\"type\": \"scalar\",";
    *output << " \"value\": \"0x";
    // Print the value as hex
    uint8_t* asByte = (uint8_t*) ai.argValue;
    // We assume the host is little endian so to print the values
    // we need to go through the array bytes backwards
    for (int byteIndex= ai.argSize -1; byteIndex >=0 ; --byteIndex)
    {
       *output << std::hex << std::setfill('0') << std::setw(2) << ( (unsigned) asByte[byteIndex]);
    }
    *output << "\"" << std::dec; //std::hex is sticky so switch back to decimal

    *output << "}";
    return;

}

static bool file_exists(std::string& name) {
	ifstream f(name.c_str());
	bool result = f.good();
	f.close();
	return result;
}

// Define the strict weak ordering over ProgramInfo instances
// Is this correct?
bool ProgramInfoCacheCompare::operator() (const ProgramInfo& lhs, const ProgramInfo& rhs) const
{
    // Use the fact that a strict-weak order is already defined over std::vector<>
    return lhs.sources < rhs.sources;
}

std::string Logger::dumpKernelSource(KernelInfo& ki)
{
    ProgramInfo& pi = programs[ki.program];

    // See if we can used a file that we already printed.
    // This avoid writing duplicate files.
    ProgCacheMapTy::iterator it = WrittenKernelFileCache.find(pi);
    if ( it != WrittenKernelFileCache.end() )
    {
        return it->second;
    }

    int count = 0;
    bool success = false;
    // FIXME: I really want a std::unique_ptr
    std::ofstream* kos = 0;
    std::string theKernelPath;
    while (count < maxFiles)
    {
        stringstream ss;
        ss << ki.entryPointName << "." << count << ".cl";

        ++count;

        std::string withDir = (directory + PATH_SEP) + ss.str();
        if (!file_exists(withDir))
        {
           kos = new std::ofstream(withDir.c_str());

           if (!kos->good())
           {
                kos->close();
                delete kos;
                continue;
           }

           success = true;
           theKernelPath = ss.str();
           break;
        }
    }

    if (!success)
    {
        ERROR_MSG("Failed to log kernel output");
        return std::string("FIXME");
    }

    // Write kernel source

    for (vector<string>::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b)
    {
        *kos << *b;
    }

    // Urgh this is bad, need RAII!
    kos->close();
    delete kos;

    // Store in cache
    assert(WrittenKernelFileCache.count(pi) == 0 && "ProgramInfo already in cache!");
    WrittenKernelFileCache[pi] = theKernelPath;

    return theKernelPath;
}
<commit_msg>Attempt to emit "compile_flags" key and value in JSON output. This has not been tested because the OpenCL implementation is broken on my machine. Hopefully if it is broken TravisCI will catch it.<commit_after>#include "gvki/Logger.h"
#include "gvki/PathSeperator.h"
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <errno.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include "string.h"
#include "gvki/Debug.h"

#include <sys/stat.h>

#ifndef _WIN32

#include <dirent.h>
#include <unistd.h>
#define MKDIR_FAILS(d)     (mkdir(d, 0770) != 0)
#define DIR_ALREADY_EXISTS (errno == EEXIST)

static void checkDirectoryExists(const char* dirName) {
    DIR* dh = opendir(dirName);
    if (dh != NULL)
    {
        closedir(dh);
        return;
    }
    ERROR_MSG(strerror(errno) << ". Directory was :" << dirName);
    exit(1);
}

#else

#include <inttypes.h>
#include <Windows.h>
#define MKDIR_FAILS(d)     (CreateDirectory(ss.str().c_str(), NULL) == 0)
#define DIR_ALREADY_EXISTS (GetLastError() == ERROR_ALREADY_EXISTS)

static void checkDirectoryExists(const char* dirName) {
    DWORD ftyp = GetFileAttributesA(dirName);
    if ((ftyp != INVALID_FILE_ATTRIBUTES) && ftyp & FILE_ATTRIBUTE_DIRECTORY)
        return;
    ERROR_MSG(strerror(errno) << ". Directory was :" << dirName);
    exit(1);
}

#endif

using namespace std;
using namespace gvki;

// Maximum number of files or directories
// that can be created
static const int maxFiles = 10000;

Logger& Logger::Singleton()
{
    static Logger l;
    return l;
}

Logger::Logger()
{
    int count = 0;
    bool success= false;

    // FIXME: Reading from the environment probably doesn't belong in here
    // but it makes implementing the singleton a lot easier
    std::string directoryPrefix;

    const char* envTemp = getenv("GVKI_ROOT");
    if (envTemp)
    {
        DEBUG_MSG("Using GVKI_ROOT value as destination for directories");

        checkDirectoryExists(envTemp);

        directoryPrefix = envTemp;

    }
    else
    {
        // Use the current working directory
        DEBUG_MSG("Using current working directory as destination for directories");

        // FIXME: Hard-coding this size is gross
        #define MAX_DIR_LENGTH 1024

#ifndef _WIN32
        char cwdArray[MAX_DIR_LENGTH];
        char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)/sizeof(char));
        if (!cwdResult)
#else
        char cwdResult[MAX_DIR_LENGTH];
        if (GetCurrentDirectory(MAX_DIR_LENGTH, cwdResult) == 0)
#endif
        {
            ERROR_MSG(strerror(errno) << ". Could not read the current working directory");
            exit(1);
        }
        else
            directoryPrefix = cwdResult;
    }
    directoryPrefix += PATH_SEP "gvki";
    DEBUG_MSG("Directory prefix is \"" << directoryPrefix << "\"");

    // Keep trying a directoryPrefix name with a number as suffix
    // until we find an available one or we exhaust the maximum
    // allowed number
    while (count < maxFiles)
    {
        stringstream ss;
        ss <<  directoryPrefix << "-" << count;
        ++count;

        // Make the directoryPrefix
        if (MKDIR_FAILS(ss.str().c_str()))
        {
            if (!DIR_ALREADY_EXISTS)
            {
                ERROR_MSG(strerror(errno) << ". Directory was :" << directoryPrefix);
                exit(1);
            }

            // It already exists, try again
            continue;
        }

        this->directory = ss.str();
        success = true;
        break;
    }

    if (!success)
    {
        ERROR_MSG("Exhausted available directory names or couldn't create any");
        exit(1);
    }

    DEBUG_MSG("Directory used for logging is \"" << this->directory << "\"");

    openLog();
}

void Logger::openLog()
{
    // FIXME: We should use mkstemp() or something
    std::stringstream ss;
    ss << directory << PATH_SEP << "log.json";
    output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate);

    if (! output->good())
    {
        ERROR_MSG("Failed to create file (" << ss.str() <<  ") to write log to");
        exit(1);
    }

    // Start of JSON array
    *output << "[" << std::endl;
}

void Logger::closeLog()
{
    // End of JSON array
    *output << std::endl << "]" << std::endl;
    output->close();
}

Logger::~Logger()
{
    closeLog();
    delete output;
}

void Logger::dump(cl_kernel k)
{
    // Output JSON format defined by
    // http://multicore.doc.ic.ac.uk/tools/GPUVerify/docs/json_format.html
    KernelInfo& ki = kernels[k];
    assert( programs.count(ki.program) == 1 && "cl_program missing");
    ProgramInfo& pi = programs[ki.program];

    static bool isFirst = true;

    if (!isFirst)
    {
        // Emit array element seperator
        // to seperate from previous dump
        *output << "," << endl;
    }
    isFirst = false;

    *output << "{" << endl << "\"language\": \"OpenCL\"," << endl;

    std::string kernelSourceFile = dumpKernelSource(ki);

    *output << "\"kernel_file\": \"" << kernelSourceFile << "\"," << endl;

    // FIXME: Teach GPUVerify how to handle non zero global_offset
    // FIXME: Document this json attribute!
    // Only emit global_offset if its non zero
    bool hasNonZeroGlobalOffset = false;
    for (int index=0; index < ki.globalWorkOffset.size() ; ++index)
    {
        if (ki.globalWorkOffset[index] != 0)
            hasNonZeroGlobalOffset = true;
    }
    if (hasNonZeroGlobalOffset)
    {
        *output << "\"global_offset\": ";
        printJSONArray(ki.globalWorkOffset);
        *output << "," << endl;
    }

    *output << "\"global_size\": ";
    printJSONArray(ki.globalWorkSize);
    *output << "," << endl;

    *output << "\"local_size\": ";
    printJSONArray(ki.localWorkSize);
    *output << "," << endl;

    *output << "\"compiler_flags\": \"" << pi.compileFlags << "\"," << endl;

    assert( (ki.globalWorkOffset.size() == ki.globalWorkSize.size()) &&
            (ki.globalWorkSize.size() == ki.localWorkSize.size()) &&
            "dimension mismatch");

    *output << "\"entry_point\": \"" << ki.entryPointName << "\"";

    // entry_point might be the last entry is there were no kernel args
    if (ki.arguments.size() == 0)
        *output << endl;
    else
    {
        *output << "," << endl << "\"kernel_arguments\": [ " << endl;
        for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex)
        {
            printJSONKernelArgumentInfo(ki.arguments[argIndex]);
            if (argIndex != (ki.arguments.size() -1))
                *output << "," << endl;
        }
        *output << endl << "]" << endl;
    }

    *output << "}";
}

void Logger::printJSONArray(std::vector<size_t>& array)
{
    *output << "[ ";
    for (int index=0; index < array.size(); ++index)
    {
        *output << array[index];

        if (index != (array.size() -1))
            *output << ", ";
    }
    *output << "]";
}

void Logger::printJSONKernelArgumentInfo(ArgInfo& ai)
{
    *output << "{";
    if (ai.argValue == NULL)
    {
        // NULL was passed to clSetKernelArg()
        // That implies its for unallocated memory
        *output << "\"type\": \"array\",";

        // If the arg is for local memory
        if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler))
        {
            // We assume this means this arguments is for local memory
            // where size actually means the sizeof the underlying buffer
            // rather than the size of the type.
            *output << "\"size\" : " << ai.argSize;
        }
        *output << "}";
        return;
    }

    // FIXME:
    // Eurgh... the spec says
    // ```
    // If the argument is a buffer object, the arg_value pointer can be NULL or
    // point to a NULL value in which case a NULL value will be used as the
    // value for the argument declared as a pointer to __global or __constant
    // memory in the kernel.  ```
    //
    // This makes it impossible (seeing as we don't know which address space
    // the arguments are in) to work out the argument type once derefencing the
    // pointer and finding it's equal zero because it could be a scalar constant
    // (of value 0) or it could be an unintialised array!

    // Hack:
    // It's hard to determine what type the argument is.
    // We can't dereference the void* to check if
    // it points to cl_mem we previously stored
    //
    // In some implementations cl_mem will be a pointer
    // which poses a risk if a scalar parameter of the same size
    // as the pointer type.
    if (ai.argSize == sizeof(cl_mem))
    {
       cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);

       // We might be reading invalid data now
       if (buffers.count(mightBecl_mem) == 1)
       {
           // We're going to assume it's cl_mem that we saw before
           *output << "\"type\": \"array\",";
           BufferInfo& bi = buffers[mightBecl_mem];

           *output << "\"size\": " << bi.size << "}";
           return;
       }

    }

    // Hack: a similar hack of the image types
    if (ai.argSize == sizeof(cl_mem))
    {
       cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);

       // We might be reading invalid data now
       if (images.count(mightBecl_mem) == 1)
       {
           // We're going to assume it's cl_mem that we saw before
           *output << "\"type\": \"image\"}";
           return;
       }

    }

    // Hack: a similar hack for the samplers
    if (ai.argSize == sizeof(cl_sampler))
    {
       cl_sampler mightBecl_sampler = *((cl_sampler*) ai.argValue);

       // We might be reading invalid data now
       if (samplers.count(mightBecl_sampler) == 1)
       {
           // We're going to assume it's cl_mem that we saw before
           *output << "\"type\": \"sampler\"}";
           return;
       }

    }

    // I guess it's scalar???
    *output << "\"type\": \"scalar\",";
    *output << " \"value\": \"0x";
    // Print the value as hex
    uint8_t* asByte = (uint8_t*) ai.argValue;
    // We assume the host is little endian so to print the values
    // we need to go through the array bytes backwards
    for (int byteIndex= ai.argSize -1; byteIndex >=0 ; --byteIndex)
    {
       *output << std::hex << std::setfill('0') << std::setw(2) << ( (unsigned) asByte[byteIndex]);
    }
    *output << "\"" << std::dec; //std::hex is sticky so switch back to decimal

    *output << "}";
    return;

}

static bool file_exists(std::string& name) {
	ifstream f(name.c_str());
	bool result = f.good();
	f.close();
	return result;
}

// Define the strict weak ordering over ProgramInfo instances
// Is this correct?
bool ProgramInfoCacheCompare::operator() (const ProgramInfo& lhs, const ProgramInfo& rhs) const
{
    // Use the fact that a strict-weak order is already defined over std::vector<>
    return lhs.sources < rhs.sources;
}

std::string Logger::dumpKernelSource(KernelInfo& ki)
{
    ProgramInfo& pi = programs[ki.program];

    // See if we can used a file that we already printed.
    // This avoid writing duplicate files.
    ProgCacheMapTy::iterator it = WrittenKernelFileCache.find(pi);
    if ( it != WrittenKernelFileCache.end() )
    {
        return it->second;
    }

    int count = 0;
    bool success = false;
    // FIXME: I really want a std::unique_ptr
    std::ofstream* kos = 0;
    std::string theKernelPath;
    while (count < maxFiles)
    {
        stringstream ss;
        ss << ki.entryPointName << "." << count << ".cl";

        ++count;

        std::string withDir = (directory + PATH_SEP) + ss.str();
        if (!file_exists(withDir))
        {
           kos = new std::ofstream(withDir.c_str());

           if (!kos->good())
           {
                kos->close();
                delete kos;
                continue;
           }

           success = true;
           theKernelPath = ss.str();
           break;
        }
    }

    if (!success)
    {
        ERROR_MSG("Failed to log kernel output");
        return std::string("FIXME");
    }

    // Write kernel source

    for (vector<string>::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b)
    {
        *kos << *b;
    }

    // Urgh this is bad, need RAII!
    kos->close();
    delete kos;

    // Store in cache
    assert(WrittenKernelFileCache.count(pi) == 0 && "ProgramInfo already in cache!");
    WrittenKernelFileCache[pi] = theKernelPath;

    return theKernelPath;
}
<|endoftext|>


<commit_before>#define DEFINE_GLOBALS
#include"all_defines.hpp"

#ifndef single_threaded
	bool single_threaded;
#endif

class Symbol;

Symbol* symbol_sym;
Symbol* symbol_int;
Symbol* symbol_char;
Symbol* symbol_cons;
Symbol* symbol_pid;
Symbol* symbol_fn;
Symbol* symbol_string;
Symbol* symbol_unspecified;
Symbol* symbol_float;
Symbol* symbol_array;
Symbol* symbol_table;
Symbol* symbol_container;
Symbol* symbol_bytecode;
Symbol* symbol_iport;
Symbol* symbol_oport;
Symbol* symbol_binobj;
Symbol* symbol_call_star;

#include"symbols.hpp"

boost::scoped_ptr<SymbolsTable> symbols;

void initialize_globals(void) {
	symbols.reset(new SymbolsTable());
	symbol_sym = symbols->lookup("<hl>sym");
	symbol_sym = symbols->lookup("<hl>int");
	symbol_sym = symbols->lookup("<hl>char");
	symbol_cons = symbols->lookup("<hl>cons");
	symbol_pid = symbols->lookup("<hl>pid");
	symbol_fn = symbols->lookup("<hl>fn");
	symbol_string = symbols->lookup("<hl>string");
	symbol_unspecified = symbols->lookup("<hl>unspecified");
	symbol_float = symbols->lookup("<hl>float");
	symbol_array = symbols->lookup("<hl>array");
	symbol_table = symbols->lookup("<hl>table");
	symbol_container = symbols->lookup("<hl>container");
        symbol_bytecode = symbols->lookup("<hl>bytecode");
        symbol_iport = symbols->lookup("<hl>iport");
        symbol_oport = symbols->lookup("<hl>oport");
        symbol_binobj = symbols->lookup("<hl>binobj");
        symbol_call_star = symbols->lookup("<hl>call-star");
}

<commit_msg>src/globals.cpp: corrected name of <hl>call*<commit_after>#define DEFINE_GLOBALS
#include"all_defines.hpp"

#ifndef single_threaded
	bool single_threaded;
#endif

class Symbol;

Symbol* symbol_sym;
Symbol* symbol_int;
Symbol* symbol_char;
Symbol* symbol_cons;
Symbol* symbol_pid;
Symbol* symbol_fn;
Symbol* symbol_string;
Symbol* symbol_unspecified;
Symbol* symbol_float;
Symbol* symbol_array;
Symbol* symbol_table;
Symbol* symbol_container;
Symbol* symbol_bytecode;
Symbol* symbol_iport;
Symbol* symbol_oport;
Symbol* symbol_binobj;
Symbol* symbol_call_star;

#include"symbols.hpp"

boost::scoped_ptr<SymbolsTable> symbols;

void initialize_globals(void) {
	symbols.reset(new SymbolsTable());
	symbol_sym = symbols->lookup("<hl>sym");
	symbol_sym = symbols->lookup("<hl>int");
	symbol_sym = symbols->lookup("<hl>char");
	symbol_cons = symbols->lookup("<hl>cons");
	symbol_pid = symbols->lookup("<hl>pid");
	symbol_fn = symbols->lookup("<hl>fn");
	symbol_string = symbols->lookup("<hl>string");
	symbol_unspecified = symbols->lookup("<hl>unspecified");
	symbol_float = symbols->lookup("<hl>float");
	symbol_array = symbols->lookup("<hl>array");
	symbol_table = symbols->lookup("<hl>table");
	symbol_container = symbols->lookup("<hl>container");
        symbol_bytecode = symbols->lookup("<hl>bytecode");
        symbol_iport = symbols->lookup("<hl>iport");
        symbol_oport = symbols->lookup("<hl>oport");
        symbol_binobj = symbols->lookup("<hl>binobj");
        symbol_call_star = symbols->lookup("<hl>call*");
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCorrelativeStatistics.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkToolkits.h"

#include "vtkCorrelativeStatistics.h"

#include "vtkDoubleArray.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"

#include <vtkstd/set>

// = Start Private Implementation =======================================
class vtkCorrelativeStatisticsPrivate
{
public:
  vtkCorrelativeStatisticsPrivate();
  ~vtkCorrelativeStatisticsPrivate();

  vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> > ColumnPairs;
};

vtkCorrelativeStatisticsPrivate::vtkCorrelativeStatisticsPrivate()
{
}

vtkCorrelativeStatisticsPrivate::~vtkCorrelativeStatisticsPrivate()
{
}

// = End Private Implementation =========================================

vtkCxxRevisionMacro(vtkCorrelativeStatistics, "1.4");
vtkStandardNewMacro(vtkCorrelativeStatistics);

// ----------------------------------------------------------------------
vtkCorrelativeStatistics::vtkCorrelativeStatistics()
{
  this->Internals = new vtkCorrelativeStatisticsPrivate;
}

// ----------------------------------------------------------------------
vtkCorrelativeStatistics::~vtkCorrelativeStatistics()
{
  delete this->Internals;
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::PrintSelf( ostream &os, vtkIndent indent )
{
  this->Superclass::PrintSelf( os, indent );
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::ResetColumnPairs()
{
  this->Internals->ColumnPairs.clear();
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::AddColumnPair( vtkIdType idxColX, vtkIdType idxColY )
{
  vtkstd::pair<vtkIdType,vtkIdType> idxPair( idxColX, idxColY );
  this->Internals->ColumnPairs.insert( idxPair );
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::ExecuteLearn( vtkTable* dataset,
                                             vtkTable* output,
                                             bool finalize )
{
  vtkIdType nCol = dataset->GetNumberOfColumns();
  if ( ! nCol )
    {
    vtkWarningMacro( "Dataset table does not have any columns. Doing nothing." );
    this->SampleSize = 0;
    return;
    }

  this->SampleSize = dataset->GetNumberOfRows();
  if ( ! this->SampleSize )
    {
    vtkWarningMacro( "Dataset table does not have any rows. Doing nothing." );
    return;
    }

  vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Column X" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Column Y" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  if ( finalize )
    {
    vtkDoubleArray* doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Mean X" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Mean Y" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Variance X" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Variance Y" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Covariance" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "SlopeYX" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    idTypeCol = vtkIdTypeArray::New();
    idTypeCol->SetName( "Linear Correlation" );
    output->AddColumn( idTypeCol );
    idTypeCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Intersect YX" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Slope XY" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Intersect XY" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Correlation" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();
    }
  else
    {
    vtkDoubleArray* doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum x" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum y" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum x2" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum y2" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum xy" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    idTypeCol = vtkIdTypeArray::New();
    idTypeCol->SetName( "Cardinality" );
    output->AddColumn( idTypeCol );
    idTypeCol->Delete();
    }

  for ( vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> >::iterator it = this->Internals->ColumnPairs.begin();
        it != this->Internals->ColumnPairs.end(); ++ it )
    {
    vtkIdType idX = it->first;
    if ( idX >= nCol )
      {
      vtkWarningMacro( "Dataset table does not have a column with index "<<idX<<". Ignoring this pair." );
      continue;
      }

    vtkIdType idY = it->second;
    if ( idY >= nCol )
      {
      vtkWarningMacro( "Dataset table does not have a column with index "<<idY<<". Ignoring this pair." );
      continue;
      }

    double x   = 0.;
    double y   = 0.;
    double sx  = 0.;
    double sy  = 0.;
    double sx2 = 0.;
    double sy2 = 0.;
    double sxy = 0.;
    for ( vtkIdType r = 0; r < this->SampleSize; ++ r )
      {
      x = dataset->GetValue( r, idX ).ToDouble();
      y = dataset->GetValue( r, idY ).ToDouble();

      sx  += x;
      sy  += y;
      sx2 += x * x;
      sy2 += y * y;
      sxy += x * y;
      }

    vtkVariantArray* row = vtkVariantArray::New();

    if ( finalize )
      {
      row->SetNumberOfValues( 13 );

      double correlations[5];
      int res = this->CalculateFromSums( this->SampleSize, sx, sy, sx2, sy2, sxy, correlations );

      row->SetValue( 0, idX );
      row->SetValue( 1, idY );
      row->SetValue( 2, sx );
      row->SetValue( 3, sy );
      row->SetValue( 4, sx2 );
      row->SetValue( 5, sy2 );
      row->SetValue( 6, sxy );
      row->SetValue( 7, res );
      for ( int i = 0; i < 5; ++ i )
        {
        row->SetValue( i + 8, correlations[i] );
        }
      }
    else
      {
      row->SetNumberOfValues( 8 );

      row->SetValue( 0, idX );
      row->SetValue( 1, idY );
      row->SetValue( 2, sx );
      row->SetValue( 3, sy );
      row->SetValue( 4, sx2 );
      row->SetValue( 5, sy2 );
      row->SetValue( 6, sxy );
      row->SetValue( 7, this->SampleSize );
      }

    output->InsertNextRow( row );

    row->Delete();
    }

  return;
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::ExecuteValidate( vtkTable*,
                                                vtkTable*,
                                                vtkTable* )
{
  // Not implemented for this statistical engine
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::ExecuteEvince( vtkTable* dataset,
                                              vtkTable* params,
                                              vtkTable* output)
{
  vtkIdType nColD = dataset->GetNumberOfColumns();
  if ( ! nColD )
    {
    vtkWarningMacro( "Dataset table does not have any columns. Doing nothing." );
    return;
    }

  vtkIdType nRowD = dataset->GetNumberOfRows();
  if ( ! nRowD )
    {
    vtkWarningMacro( "Dataset table does not have any rows. Doing nothing." );
    return;
    }

  vtkIdType nColP = params->GetNumberOfColumns();
  if ( nColP != 8 )
    {
    vtkWarningMacro( "Parameter table has "
                     << nColP
                     << " != 8 columns. Doing nothing." );
    return;
    }

  vtkIdType nRowP = params->GetNumberOfRows();
  if ( ! nRowP )
    {
    vtkWarningMacro( "Parameter table does not have any rows. Doing nothing." );
    return;
    }

  vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Column X" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Column Y" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Row" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  vtkDoubleArray* doubleCol = vtkDoubleArray::New();
  doubleCol->SetName( "Relative PDF" );
  output->AddColumn( doubleCol );
  doubleCol->Delete();

  vtkVariantArray* row = vtkVariantArray::New();
  row->SetNumberOfValues( 4 );

  for ( vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> >::iterator it = this->Internals->ColumnPairs.begin();
        it != this->Internals->ColumnPairs.end(); ++ it )
    {
    vtkIdType idX = it->first;
    if ( idX >= nColD )
      {
      vtkWarningMacro( "Dataset table does not have a column with index "<<idX<<". Ignoring it." );
      continue;
      }

    vtkIdType idY = it->second;
    if ( idY >= nColD )
      {
      vtkWarningMacro( "Dataset table does not have a column with index "<<idY<<". Ignoring it." );
      continue;
      }

    bool unfound = true;
    for ( int i = 0; i < nRowP; ++ i )
      {
      vtkIdType c1 = params->GetValue( i, 0 ).ToInt();
      vtkIdType c2 = params->GetValue( i, 1 ).ToInt();
      if ( ( c1 == it->first && c2 == it->second ) ||  ( c2 == it->first && c1 == it->second ) )
        {
        unfound = false;

        double varX = params->GetValue( i, 4 ).ToDouble();
        double varY = params->GetValue( i, 5 ).ToDouble();
        double covr = params->GetValue( i, 6 ).ToDouble();

        double d = varX * varY - covr * covr;
        if ( d <= 0. )
          {
          vtkWarningMacro( "Incorrect parameters for column pair ("
                           <<c1
                           <<", "
                           <<c2
                           <<"): variance/covariance matrix has non-positive determinant." );
          continue;
          }

        double nominalX = params->GetValue( i, 2 ).ToDouble();
        double nominalY = params->GetValue( i, 3 ).ToDouble();
        double thresPDF = params->GetValue( i, 7 ).ToDouble();
        double eFac = -.5 / d;
        covr *= 2.;

        if ( c2 == it->first )
          {
          vtkIdType tmp = idX;
          idX = idY;
          idY = tmp;
          }

        double x, y, rPDF;
        for ( vtkIdType r = 0; r < nRowD; ++ r )
          {
          x = dataset->GetValue( r, idX ).ToDouble() - nominalX;
          y = dataset->GetValue( r, idY ).ToDouble() - nominalY;

          rPDF = exp( eFac * ( varY * x * x - covr * x * y + varX * y * y ) );
          if ( rPDF < thresPDF )
            {
            row->SetValue( 0, idX );
            row->SetValue( 1, idY );
            row->SetValue( 2, r );
            row->SetValue( 3, rPDF );

            output->InsertNextRow( row );
            }
          }

        break;
        }
      }

    if ( unfound )
      {
      vtkWarningMacro( "Parameter table does not a row for dataset table column pair ("
                       <<it->first
                       <<", "
                       <<it->second
                       <<"). Ignoring it." );
      continue;
      }
    }
  row->Delete();

  return;
}

// ----------------------------------------------------------------------
int vtkCorrelativeStatistics::CalculateFromSums( int n,
                                                 double& sx,
                                                 double& sy,
                                                 double& sx2,
                                                 double& sy2,
                                                 double& sxy,
                                                 double* correlations )
{
  if ( n < 2 )
    {
    return -1;
    }

  double nd = static_cast<double>( n );

  // (unbiased) estimation of the means
  sx /= nd;
  sy /= nd;

  if ( n == 1 )
    {
    sx2 = sy2 = sxy = 0.;
    return 0;
    }

  // (unbiased) estimation of the variances and covariance
  double f = 1. / ( nd - 1. );
  sx2 = ( sx2 - sx * sx * nd ) * f;
  sy2 = ( sy2 - sy * sy * nd ) * f;
  sxy = ( sxy - sx * sy * nd ) * f;

  // linear regression

  if ( sx2 > 0. && sy2 > 0. )
    {
    // variable Y on variable X:
    //   slope
    correlations[0] = sxy / sx2;
    //   intersect
    correlations[1] = sy - correlations[0] * sx;

    //   variable X on variable Y:
    //   slope
    correlations[2] = sxy / sy2;
    //   intersect
    correlations[3] = sx - correlations[2] * sy;

    // correlation coefficient
    double d = sx2 * sy2;
    if ( d > 0 )
      {
      correlations[4] = sxy / sqrt( d );
      return 0;
      }
    else
      {
      correlations[4] = 0.;
      return 1;
      }
    }
  else
    {
    correlations[0] = 0.;
    correlations[1] = 0.;
    correlations[2] = 0.;
    correlations[3] = 0.;
    correlations[4] = 0.;
    return 1;
    }
}
<commit_msg>BUG: when columns of interest are changed, Modified() must be called.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCorrelativeStatistics.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/

#include "vtkToolkits.h"

#include "vtkCorrelativeStatistics.h"

#include "vtkDoubleArray.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"

#include <vtkstd/set>

// = Start Private Implementation =======================================
class vtkCorrelativeStatisticsPrivate
{
public:
  vtkCorrelativeStatisticsPrivate();
  ~vtkCorrelativeStatisticsPrivate();

  vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> > ColumnPairs;
};

vtkCorrelativeStatisticsPrivate::vtkCorrelativeStatisticsPrivate()
{
}

vtkCorrelativeStatisticsPrivate::~vtkCorrelativeStatisticsPrivate()
{
}

// = End Private Implementation =========================================

vtkCxxRevisionMacro(vtkCorrelativeStatistics, "1.5");
vtkStandardNewMacro(vtkCorrelativeStatistics);

// ----------------------------------------------------------------------
vtkCorrelativeStatistics::vtkCorrelativeStatistics()
{
  this->Internals = new vtkCorrelativeStatisticsPrivate;
}

// ----------------------------------------------------------------------
vtkCorrelativeStatistics::~vtkCorrelativeStatistics()
{
  delete this->Internals;
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::PrintSelf( ostream &os, vtkIndent indent )
{
  this->Superclass::PrintSelf( os, indent );
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::ResetColumnPairs()
{
  this->Internals->ColumnPairs.clear();
  this->Modified();
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::AddColumnPair( vtkIdType idxColX, vtkIdType idxColY )
{
  vtkstd::pair<vtkIdType,vtkIdType> idxPair( idxColX, idxColY );
  this->Internals->ColumnPairs.insert( idxPair );
  this->Modified();
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::ExecuteLearn( vtkTable* dataset,
                                             vtkTable* output,
                                             bool finalize )
{
  vtkIdType nCol = dataset->GetNumberOfColumns();
  if ( ! nCol )
    {
    vtkWarningMacro( "Dataset table does not have any columns. Doing nothing." );
    this->SampleSize = 0;
    return;
    }

  this->SampleSize = dataset->GetNumberOfRows();
  if ( ! this->SampleSize )
    {
    vtkWarningMacro( "Dataset table does not have any rows. Doing nothing." );
    return;
    }

  vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Column X" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Column Y" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  if ( finalize )
    {
    vtkDoubleArray* doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Mean X" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Mean Y" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Variance X" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Variance Y" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Covariance" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "SlopeYX" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    idTypeCol = vtkIdTypeArray::New();
    idTypeCol->SetName( "Linear Correlation" );
    output->AddColumn( idTypeCol );
    idTypeCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Intersect YX" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Slope XY" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Intersect XY" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Correlation" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();
    }
  else
    {
    vtkDoubleArray* doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum x" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum y" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum x2" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum y2" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    doubleCol = vtkDoubleArray::New();
    doubleCol->SetName( "Sum xy" );
    output->AddColumn( doubleCol );
    doubleCol->Delete();

    idTypeCol = vtkIdTypeArray::New();
    idTypeCol->SetName( "Cardinality" );
    output->AddColumn( idTypeCol );
    idTypeCol->Delete();
    }

  for ( vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> >::iterator it = this->Internals->ColumnPairs.begin();
        it != this->Internals->ColumnPairs.end(); ++ it )
    {
    vtkIdType idX = it->first;
    if ( idX >= nCol )
      {
      vtkWarningMacro( "Dataset table does not have a column with index "<<idX<<". Ignoring this pair." );
      continue;
      }

    vtkIdType idY = it->second;
    if ( idY >= nCol )
      {
      vtkWarningMacro( "Dataset table does not have a column with index "<<idY<<". Ignoring this pair." );
      continue;
      }

    double x   = 0.;
    double y   = 0.;
    double sx  = 0.;
    double sy  = 0.;
    double sx2 = 0.;
    double sy2 = 0.;
    double sxy = 0.;
    for ( vtkIdType r = 0; r < this->SampleSize; ++ r )
      {
      x = dataset->GetValue( r, idX ).ToDouble();
      y = dataset->GetValue( r, idY ).ToDouble();

      sx  += x;
      sy  += y;
      sx2 += x * x;
      sy2 += y * y;
      sxy += x * y;
      }

    vtkVariantArray* row = vtkVariantArray::New();

    if ( finalize )
      {
      row->SetNumberOfValues( 13 );

      double correlations[5];
      int res = this->CalculateFromSums( this->SampleSize, sx, sy, sx2, sy2, sxy, correlations );

      row->SetValue( 0, idX );
      row->SetValue( 1, idY );
      row->SetValue( 2, sx );
      row->SetValue( 3, sy );
      row->SetValue( 4, sx2 );
      row->SetValue( 5, sy2 );
      row->SetValue( 6, sxy );
      row->SetValue( 7, res );
      for ( int i = 0; i < 5; ++ i )
        {
        row->SetValue( i + 8, correlations[i] );
        }
      }
    else
      {
      row->SetNumberOfValues( 8 );

      row->SetValue( 0, idX );
      row->SetValue( 1, idY );
      row->SetValue( 2, sx );
      row->SetValue( 3, sy );
      row->SetValue( 4, sx2 );
      row->SetValue( 5, sy2 );
      row->SetValue( 6, sxy );
      row->SetValue( 7, this->SampleSize );
      }

    output->InsertNextRow( row );

    row->Delete();
    }

  return;
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::ExecuteValidate( vtkTable*,
                                                vtkTable*,
                                                vtkTable* )
{
  // Not implemented for this statistical engine
}

// ----------------------------------------------------------------------
void vtkCorrelativeStatistics::ExecuteEvince( vtkTable* dataset,
                                              vtkTable* params,
                                              vtkTable* output)
{
  vtkIdType nColD = dataset->GetNumberOfColumns();
  if ( ! nColD )
    {
    vtkWarningMacro( "Dataset table does not have any columns. Doing nothing." );
    return;
    }

  vtkIdType nRowD = dataset->GetNumberOfRows();
  if ( ! nRowD )
    {
    vtkWarningMacro( "Dataset table does not have any rows. Doing nothing." );
    return;
    }

  vtkIdType nColP = params->GetNumberOfColumns();
  if ( nColP != 8 )
    {
    vtkWarningMacro( "Parameter table has "
                     << nColP
                     << " != 8 columns. Doing nothing." );
    return;
    }

  vtkIdType nRowP = params->GetNumberOfRows();
  if ( ! nRowP )
    {
    vtkWarningMacro( "Parameter table does not have any rows. Doing nothing." );
    return;
    }

  vtkIdTypeArray* idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Column X" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Column Y" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  idTypeCol = vtkIdTypeArray::New();
  idTypeCol->SetName( "Row" );
  output->AddColumn( idTypeCol );
  idTypeCol->Delete();

  vtkDoubleArray* doubleCol = vtkDoubleArray::New();
  doubleCol->SetName( "Relative PDF" );
  output->AddColumn( doubleCol );
  doubleCol->Delete();

  vtkVariantArray* row = vtkVariantArray::New();
  row->SetNumberOfValues( 4 );

  for ( vtkstd::set<vtkstd::pair<vtkIdType,vtkIdType> >::iterator it = this->Internals->ColumnPairs.begin();
        it != this->Internals->ColumnPairs.end(); ++ it )
    {
    vtkIdType idX = it->first;
    if ( idX >= nColD )
      {
      vtkWarningMacro( "Dataset table does not have a column with index "<<idX<<". Ignoring it." );
      continue;
      }

    vtkIdType idY = it->second;
    if ( idY >= nColD )
      {
      vtkWarningMacro( "Dataset table does not have a column with index "<<idY<<". Ignoring it." );
      continue;
      }

    bool unfound = true;
    for ( int i = 0; i < nRowP; ++ i )
      {
      vtkIdType c1 = params->GetValue( i, 0 ).ToInt();
      vtkIdType c2 = params->GetValue( i, 1 ).ToInt();
      if ( ( c1 == it->first && c2 == it->second ) ||  ( c2 == it->first && c1 == it->second ) )
        {
        unfound = false;

        double varX = params->GetValue( i, 4 ).ToDouble();
        double varY = params->GetValue( i, 5 ).ToDouble();
        double covr = params->GetValue( i, 6 ).ToDouble();

        double d = varX * varY - covr * covr;
        if ( d <= 0. )
          {
          vtkWarningMacro( "Incorrect parameters for column pair ("
                           <<c1
                           <<", "
                           <<c2
                           <<"): variance/covariance matrix has non-positive determinant." );
          continue;
          }

        double nominalX = params->GetValue( i, 2 ).ToDouble();
        double nominalY = params->GetValue( i, 3 ).ToDouble();
        double thresPDF = params->GetValue( i, 7 ).ToDouble();
        double eFac = -.5 / d;
        covr *= 2.;

        if ( c2 == it->first )
          {
          vtkIdType tmp = idX;
          idX = idY;
          idY = tmp;
          }

        double x, y, rPDF;
        for ( vtkIdType r = 0; r < nRowD; ++ r )
          {
          x = dataset->GetValue( r, idX ).ToDouble() - nominalX;
          y = dataset->GetValue( r, idY ).ToDouble() - nominalY;

          rPDF = exp( eFac * ( varY * x * x - covr * x * y + varX * y * y ) );
          if ( rPDF < thresPDF )
            {
            row->SetValue( 0, idX );
            row->SetValue( 1, idY );
            row->SetValue( 2, r );
            row->SetValue( 3, rPDF );

            output->InsertNextRow( row );
            }
          }

        break;
        }
      }

    if ( unfound )
      {
      vtkWarningMacro( "Parameter table does not a row for dataset table column pair ("
                       <<it->first
                       <<", "
                       <<it->second
                       <<"). Ignoring it." );
      continue;
      }
    }
  row->Delete();

  return;
}

// ----------------------------------------------------------------------
int vtkCorrelativeStatistics::CalculateFromSums( int n,
                                                 double& sx,
                                                 double& sy,
                                                 double& sx2,
                                                 double& sy2,
                                                 double& sxy,
                                                 double* correlations )
{
  if ( n < 2 )
    {
    return -1;
    }

  double nd = static_cast<double>( n );

  // (unbiased) estimation of the means
  sx /= nd;
  sy /= nd;

  if ( n == 1 )
    {
    sx2 = sy2 = sxy = 0.;
    return 0;
    }

  // (unbiased) estimation of the variances and covariance
  double f = 1. / ( nd - 1. );
  sx2 = ( sx2 - sx * sx * nd ) * f;
  sy2 = ( sy2 - sy * sy * nd ) * f;
  sxy = ( sxy - sx * sy * nd ) * f;

  // linear regression

  if ( sx2 > 0. && sy2 > 0. )
    {
    // variable Y on variable X:
    //   slope
    correlations[0] = sxy / sx2;
    //   intersect
    correlations[1] = sy - correlations[0] * sx;

    //   variable X on variable Y:
    //   slope
    correlations[2] = sxy / sy2;
    //   intersect
    correlations[3] = sx - correlations[2] * sy;

    // correlation coefficient
    double d = sx2 * sy2;
    if ( d > 0 )
      {
      correlations[4] = sxy / sqrt( d );
      return 0;
      }
    else
      {
      correlations[4] = 0.;
      return 1;
      }
    }
  else
    {
    correlations[0] = 0.;
    correlations[1] = 0.;
    correlations[2] = 0.;
    correlations[3] = 0.;
    correlations[4] = 0.;
    return 1;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: areasdlg.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: dr $ $Date: 2001-05-23 15:05:18 $
 *
 *  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 SC_AREASDLG_HXX
#define SC_AREASDLG_HXX

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef SC_ANYREFDG_HXX
#include <anyrefdg.hxx>
#endif

class ScDocument;
class ScViewData;
class ScRangeUtil;
class ScRangeItem;

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

class ScPrintAreasDlg : public ScAnyRefDlg
{
public:
                    ScPrintAreasDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent );
                    ~ScPrintAreasDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pDoc );
    virtual void    AddRefEntry();

    virtual BOOL    IsTableLocked() const;

    virtual void    SetActive();
    virtual void    Deactivate();
    virtual BOOL    Close();

private:
    ListBox         aLbPrintArea;
    FixedLine       aFlPrintArea;
    ScRefEdit       aEdPrintArea;
    ScRefButton     aRbPrintArea;

    ListBox         aLbRepeatRow;
    FixedLine       aFlRepeatRow;
    ScRefEdit       aEdRepeatRow;
    ScRefButton     aRbRepeatRow;

    ListBox         aLbRepeatCol;
    FixedLine       aFlRepeatCol;
    ScRefEdit       aEdRepeatCol;
    ScRefButton     aRbRepeatCol;

    OKButton        aBtnOk;
    CancelButton    aBtnCancel;
    HelpButton      aBtnHelp;

    BOOL            bDlgLostFocus;
    ScRefEdit*      pRefInputEdit;
    ScDocument*     pDoc;
    ScViewData*     pViewData;
    USHORT          nCurTab;

#ifdef _AREASDLG_CXX
private:
    void Impl_Reset();
    BOOL Impl_CheckRefStrings();
    void Impl_FillLists();
    BOOL Impl_GetItem( Edit* pEd, SfxStringItem& rItem );

    // Handler:
    DECL_LINK( Impl_SelectHdl,      ListBox*    );
    DECL_LINK( Impl_ModifyHdl,      ScRefEdit*  );
    DECL_LINK( Impl_BtnHdl,         PushButton* );
    DECL_LINK( Impl_GetFocusHdl,    Control*    );
#endif
};

#endif

<commit_msg>INTEGRATION: CWS rowlimit (1.2.332); FILE MERGED 2004/01/13 20:04:08 er 1.2.332.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/*************************************************************************
 *
 *  $RCSfile: areasdlg.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:30:10 $
 *
 *  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 SC_AREASDLG_HXX
#define SC_AREASDLG_HXX

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

#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef SC_ANYREFDG_HXX
#include <anyrefdg.hxx>
#endif

class ScDocument;
class ScViewData;
class ScRangeUtil;
class ScRangeItem;

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

class ScPrintAreasDlg : public ScAnyRefDlg
{
public:
                    ScPrintAreasDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent );
                    ~ScPrintAreasDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pDoc );
    virtual void    AddRefEntry();

    virtual BOOL    IsTableLocked() const;

    virtual void    SetActive();
    virtual void    Deactivate();
    virtual BOOL    Close();

private:
    ListBox         aLbPrintArea;
    FixedLine       aFlPrintArea;
    ScRefEdit       aEdPrintArea;
    ScRefButton     aRbPrintArea;

    ListBox         aLbRepeatRow;
    FixedLine       aFlRepeatRow;
    ScRefEdit       aEdRepeatRow;
    ScRefButton     aRbRepeatRow;

    ListBox         aLbRepeatCol;
    FixedLine       aFlRepeatCol;
    ScRefEdit       aEdRepeatCol;
    ScRefButton     aRbRepeatCol;

    OKButton        aBtnOk;
    CancelButton    aBtnCancel;
    HelpButton      aBtnHelp;

    BOOL            bDlgLostFocus;
    ScRefEdit*      pRefInputEdit;
    ScDocument*     pDoc;
    ScViewData*     pViewData;
    SCTAB           nCurTab;

#ifdef _AREASDLG_CXX
private:
    void Impl_Reset();
    BOOL Impl_CheckRefStrings();
    void Impl_FillLists();
    BOOL Impl_GetItem( Edit* pEd, SfxStringItem& rItem );

    // Handler:
    DECL_LINK( Impl_SelectHdl,      ListBox*    );
    DECL_LINK( Impl_ModifyHdl,      ScRefEdit*  );
    DECL_LINK( Impl_BtnHdl,         PushButton* );
    DECL_LINK( Impl_GetFocusHdl,    Control*    );
#endif
};

#endif

<|endoftext|>