<commit_before>/*************************************************************************
 *
 *  $RCSfile: scmod.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: vg $ $Date: 2003-05-27 15:07:24 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_SCMOD_HXX
#define SC_SCMOD_HXX

#ifndef SC_SCDLL_HXX
#include "scdll.hxx"
#endif

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif

#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"       // ScInputMode
#endif

#ifndef SC_MARKDATA_HXX     //@05.01.98
#include "markdata.hxx"     //ScMarkData
#endif

#ifndef SC_SHELLIDS_HXX
#include "shellids.hxx"
#endif

class KeyEvent;
class SdrModel;
class SdrView;
class EditView;
class SfxErrorHandler;
class SvxErrorHandler;
class SvtAccessibilityOptions;
class SvtCTLOptions;

namespace svtools { class ColorConfig; }

class ScRange;
class ScDocument;
class ScViewCfg;
class ScDocCfg;
class ScAppCfg;
class ScInputCfg;
class ScPrintCfg;
class ScViewOptions;
class ScDocOptions;
class ScAppOptions;
class ScInputOptions;
class ScPrintOptions;
class ScInputHandler;
class ScInputWindow;
class ScTabViewShell;
class ScFunctionDlg;
class ScArgDlgBase;
class ScTeamDlg;
class ScEditFunctionDlg;
class ScMessagePool;
class EditFieldInfo;
class ScNavipiCfg;
class ScFormEditData;
class ScTransferObj;
class ScDrawTransferObj;
class ScSelectionTransferObj;

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

//      for internal Drag&Drop:

#define SC_DROP_NAVIGATOR       1
#define SC_DROP_TABLE           2

struct ScDragData
{
    ScTransferObj*      pCellTransfer;
    ScDrawTransferObj*  pDrawTransfer;

    String              aLinkDoc;
    String              aLinkTable;
    String              aLinkArea;
    ScDocument*         pJumpLocalDoc;
    String              aJumpTarget;
    String              aJumpText;
};

struct ScClipData
{
    ScTransferObj*      pCellClipboard;
    ScDrawTransferObj*  pDrawClipboard;
};

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

class ScModule: public ScModuleDummy, public SfxListener
{
    Timer               aIdleTimer;
    Timer               aSpellTimer;
    ScDragData          aDragData;
    ScClipData          aClipData;
    ScSelectionTransferObj* pSelTransfer;
    ScMessagePool*      pMessagePool;
    //  globalen InputHandler gibt's nicht mehr, jede View hat einen
    ScInputHandler*     pRefInputHandler;
    ScTeamDlg*          pTeamDlg;
    ScViewCfg*          pViewCfg;
    ScDocCfg*           pDocCfg;
    ScAppCfg*           pAppCfg;
    ScInputCfg*         pInputCfg;
    ScPrintCfg*         pPrintCfg;
    ScNavipiCfg*        pNavipiCfg;
    svtools::ColorConfig*   pColorConfig;
    SvtAccessibilityOptions* pAccessOptions;
    SvtCTLOptions*      pCTLOptions;
    SfxErrorHandler*    pErrorHdl;
    SvxErrorHandler*    pSvxErrorHdl;
    ScFormEditData*     pFormEditData;
    USHORT              nCurRefDlgId;
    BOOL                bIsWaterCan;
    BOOL                bIsInEditCommand;

public:
                    SFX_DECL_INTERFACE(SCID_APP);

                    ScModule( SfxObjectFactory* pFact );
    virtual         ~ScModule();

    virtual SfxModule*  Load();
    virtual void        FillStatusBar(StatusBar &rBar);

    virtual void        Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    void                DeleteCfg();
    void                CloseDialogs();

                        // von der Applikation verschoben:

    DECL_LINK( IdleHandler,     Timer* );   // Timer statt idle
    DECL_LINK( SpellTimerHdl,   Timer* );
    DECL_LINK( CalcFieldValueHdl, EditFieldInfo* );

    void                Execute( SfxRequest& rReq );
    void                GetState( SfxItemSet& rSet );

    void                AnythingChanged();

    //  Drag & Drop:
    const ScDragData&   GetDragData() const     { return aDragData; }
    void                SetDragObject( ScTransferObj* pCellObj, ScDrawTransferObj* pDrawObj );
    void                ResetDragObject();
    void                SetDragLink( const String& rDoc, const String& rTab, const String& rArea );
    void                SetDragJump( ScDocument* pLocalDoc,
                                    const String& rTarget, const String& rText );

    //  clipboard:
    const ScClipData&   GetClipData() const     { return aClipData; }
    void                SetClipObject( ScTransferObj* pCellObj, ScDrawTransferObj* pDrawObj );

    ScDocument*         GetClipDoc();       // called from document - should be removed later

    //  X selection:
    ScSelectionTransferObj* GetSelectionTransfer() const    { return pSelTransfer; }
    void                SetSelectionTransfer( ScSelectionTransferObj* pNew );

    void                SetWaterCan( BOOL bNew )    { bIsWaterCan = bNew; }
    BOOL                GetIsWaterCan() const       { return bIsWaterCan; }

    void                SetInEditCommand( BOOL bNew )   { bIsInEditCommand = bNew; }
    BOOL                IsInEditCommand() const         { return bIsInEditCommand; }

    // Options:
    const ScViewOptions&    GetViewOptions  ();
    const ScDocOptions&     GetDocOptions   ();
    const ScAppOptions&     GetAppOptions   ();
    const ScInputOptions&   GetInputOptions ();
    const ScPrintOptions&   GetPrintOptions ();
    void                    SetViewOptions  ( const ScViewOptions& rOpt );
    void                    SetDocOptions   ( const ScDocOptions& rOpt );
    void                    SetAppOptions   ( const ScAppOptions& rOpt );
    void                    SetInputOptions ( const ScInputOptions& rOpt );
    void                    SetPrintOptions ( const ScPrintOptions& rOpt );
    void                    InsertEntryToLRUList(USHORT nFIndex);
    void                    RecentFunctionsChanged();

    static void         GetSpellSettings( USHORT& rDefLang, USHORT& rCjkLang, USHORT& rCtlLang,
                                        BOOL& rAutoSpell, BOOL& rHideAuto );
    static void         SetAutoSpellProperty( BOOL bSet );
    static void         SetHideAutoProperty( BOOL bSet );
    static BOOL         HasThesaurusLanguage( USHORT nLang );

    USHORT              GetOptDigitLanguage();      // from CTL options

    ScNavipiCfg&        GetNavipiCfg();
    svtools::ColorConfig&   GetColorConfig();
    SvtAccessibilityOptions& GetAccessOptions();
    SvtCTLOptions&      GetCTLOptions();

    void                ModifyOptions( const SfxItemSet& rOptSet );

    //  InputHandler:
    BOOL                IsEditMode();   // nicht bei SC_INPUT_TYPE
    BOOL                IsInputMode();  // auch bei SC_INPUT_TYPE
    void                SetInputMode( ScInputMode eMode );
    BOOL                InputKeyEvent( const KeyEvent& rKEvt, BOOL bStartEdit = FALSE );
    void                InputEnterHandler( BYTE nBlockMode = 0 );
    void                InputCancelHandler();
    void                InputSelection( EditView* pView );
    void                InputChanged( EditView* pView );
    ScInputHandler*     GetInputHdl( ScTabViewShell* pViewSh = NULL, BOOL bUseRef = TRUE );

    void                SetRefInputHdl( ScInputHandler* pNew );
    ScInputHandler*     GetRefInputHdl();

    void                SetInputWindow( ScInputWindow* pWin );
    void                ViewShellGone(ScTabViewShell* pViewSh);
    void                ViewShellChanged();
    // Kommunikation mit Funktionsautopilot
    void                InputGetSelection( xub_StrLen& rStart, xub_StrLen& rEnd );
    void                InputSetSelection( xub_StrLen nStart, xub_StrLen nEnd );
    void                InputReplaceSelection( const String& rStr );
    String              InputGetFormulaStr();
    void                ActivateInputWindow( const String* pStr = NULL,
                                                BOOL bMatrix = FALSE );

    void                InitFormEditData();
    void                ClearFormEditData();
    ScFormEditData*     GetFormEditData()       { return pFormEditData; }

    //  Referenzeingabe:
    void                SetRefDialog( USHORT nId, BOOL bVis, SfxViewFrame* pViewFrm = NULL );
    BOOL                IsModalMode(SfxObjectShell* pDocSh = NULL);
    BOOL                IsFormulaMode();
    BOOL                IsRefDialogOpen();
    BOOL                IsTableLocked();
    void                OpenTeamDlg();
    void                SetTeamDlg( ScTeamDlg* pDlg )           { pTeamDlg = pDlg; }
    ScTeamDlg*          GetTeamDlg() const                      { return pTeamDlg; }
    void                SetReference( const ScRange& rRef, ScDocument* pDoc,
                                        const ScMarkData* pMarkData = NULL );
    void                AddRefEntry();
    void                EndReference();
    USHORT              GetCurRefDlgId() const                  { return nCurRefDlgId; }

    //virtuelle Methoden fuer den Optionendialog
    virtual SfxItemSet*  CreateItemSet( USHORT nId );
    virtual void         ApplyItemSet( USHORT nId, const SfxItemSet& rSet );
    virtual SfxTabPage*  CreateTabPage( USHORT nId, Window* pParent, const SfxItemSet& rSet );
};

#define SC_MOD() ( *(ScModule**) GetAppData(SHL_CALC) )

#endif

<commit_msg>INTEGRATION: CWS fwkq1 (1.12.24); FILE MERGED 2003/07/14 16:27:51 mba 1.12.24.1: #110843#: get rid of factories<commit_after>/*************************************************************************
 *
 *  $RCSfile: scmod.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2003-09-19 08:20:57 $
 *
 *  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_SCMOD_HXX
#define SC_SCMOD_HXX

#ifndef SC_SCDLL_HXX
#include "scdll.hxx"
#endif

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif

#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"       // ScInputMode
#endif

#ifndef SC_MARKDATA_HXX     //@05.01.98
#include "markdata.hxx"     //ScMarkData
#endif

#ifndef SC_SHELLIDS_HXX
#include "shellids.hxx"
#endif

class KeyEvent;
class SdrModel;
class SdrView;
class EditView;
class SfxErrorHandler;
class SvxErrorHandler;
class SvtAccessibilityOptions;
class SvtCTLOptions;

namespace svtools { class ColorConfig; }

class ScRange;
class ScDocument;
class ScViewCfg;
class ScDocCfg;
class ScAppCfg;
class ScInputCfg;
class ScPrintCfg;
class ScViewOptions;
class ScDocOptions;
class ScAppOptions;
class ScInputOptions;
class ScPrintOptions;
class ScInputHandler;
class ScInputWindow;
class ScTabViewShell;
class ScFunctionDlg;
class ScArgDlgBase;
class ScTeamDlg;
class ScEditFunctionDlg;
class ScMessagePool;
class EditFieldInfo;
class ScNavipiCfg;
class ScFormEditData;
class ScTransferObj;
class ScDrawTransferObj;
class ScSelectionTransferObj;

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

//      for internal Drag&Drop:

#define SC_DROP_NAVIGATOR       1
#define SC_DROP_TABLE           2

struct ScDragData
{
    ScTransferObj*      pCellTransfer;
    ScDrawTransferObj*  pDrawTransfer;

    String              aLinkDoc;
    String              aLinkTable;
    String              aLinkArea;
    ScDocument*         pJumpLocalDoc;
    String              aJumpTarget;
    String              aJumpText;
};

struct ScClipData
{
    ScTransferObj*      pCellClipboard;
    ScDrawTransferObj*  pDrawClipboard;
};

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

class ScModule: public SfxModule, public SfxListener
{
    Timer               aIdleTimer;
    Timer               aSpellTimer;
    ScDragData          aDragData;
    ScClipData          aClipData;
    ScSelectionTransferObj* pSelTransfer;
    ScMessagePool*      pMessagePool;
    //  globalen InputHandler gibt's nicht mehr, jede View hat einen
    ScInputHandler*     pRefInputHandler;
    ScTeamDlg*          pTeamDlg;
    ScViewCfg*          pViewCfg;
    ScDocCfg*           pDocCfg;
    ScAppCfg*           pAppCfg;
    ScInputCfg*         pInputCfg;
    ScPrintCfg*         pPrintCfg;
    ScNavipiCfg*        pNavipiCfg;
    svtools::ColorConfig*   pColorConfig;
    SvtAccessibilityOptions* pAccessOptions;
    SvtCTLOptions*      pCTLOptions;
    SfxErrorHandler*    pErrorHdl;
    SvxErrorHandler*    pSvxErrorHdl;
    ScFormEditData*     pFormEditData;
    USHORT              nCurRefDlgId;
    BOOL                bIsWaterCan;
    BOOL                bIsInEditCommand;

public:
                    SFX_DECL_INTERFACE(SCID_APP);

                    ScModule( SfxObjectFactory* pFact );
    virtual         ~ScModule();

    virtual void        FillStatusBar(StatusBar &rBar);
    virtual void        Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
    void                DeleteCfg();
    void                CloseDialogs();

                        // von der Applikation verschoben:

    DECL_LINK( IdleHandler,     Timer* );   // Timer statt idle
    DECL_LINK( SpellTimerHdl,   Timer* );
    DECL_LINK( CalcFieldValueHdl, EditFieldInfo* );

    void                Execute( SfxRequest& rReq );
    void                GetState( SfxItemSet& rSet );

    void                AnythingChanged();

    //  Drag & Drop:
    const ScDragData&   GetDragData() const     { return aDragData; }
    void                SetDragObject( ScTransferObj* pCellObj, ScDrawTransferObj* pDrawObj );
    void                ResetDragObject();
    void                SetDragLink( const String& rDoc, const String& rTab, const String& rArea );
    void                SetDragJump( ScDocument* pLocalDoc,
                                    const String& rTarget, const String& rText );

    //  clipboard:
    const ScClipData&   GetClipData() const     { return aClipData; }
    void                SetClipObject( ScTransferObj* pCellObj, ScDrawTransferObj* pDrawObj );

    ScDocument*         GetClipDoc();       // called from document - should be removed later

    //  X selection:
    ScSelectionTransferObj* GetSelectionTransfer() const    { return pSelTransfer; }
    void                SetSelectionTransfer( ScSelectionTransferObj* pNew );

    void                SetWaterCan( BOOL bNew )    { bIsWaterCan = bNew; }
    BOOL                GetIsWaterCan() const       { return bIsWaterCan; }

    void                SetInEditCommand( BOOL bNew )   { bIsInEditCommand = bNew; }
    BOOL                IsInEditCommand() const         { return bIsInEditCommand; }

    // Options:
    const ScViewOptions&    GetViewOptions  ();
    const ScDocOptions&     GetDocOptions   ();
    const ScAppOptions&     GetAppOptions   ();
    const ScInputOptions&   GetInputOptions ();
    const ScPrintOptions&   GetPrintOptions ();
    void                    SetViewOptions  ( const ScViewOptions& rOpt );
    void                    SetDocOptions   ( const ScDocOptions& rOpt );
    void                    SetAppOptions   ( const ScAppOptions& rOpt );
    void                    SetInputOptions ( const ScInputOptions& rOpt );
    void                    SetPrintOptions ( const ScPrintOptions& rOpt );
    void                    InsertEntryToLRUList(USHORT nFIndex);
    void                    RecentFunctionsChanged();

    static void         GetSpellSettings( USHORT& rDefLang, USHORT& rCjkLang, USHORT& rCtlLang,
                                        BOOL& rAutoSpell, BOOL& rHideAuto );
    static void         SetAutoSpellProperty( BOOL bSet );
    static void         SetHideAutoProperty( BOOL bSet );
    static BOOL         HasThesaurusLanguage( USHORT nLang );

    USHORT              GetOptDigitLanguage();      // from CTL options

    ScNavipiCfg&        GetNavipiCfg();
    svtools::ColorConfig&   GetColorConfig();
    SvtAccessibilityOptions& GetAccessOptions();
    SvtCTLOptions&      GetCTLOptions();

    void                ModifyOptions( const SfxItemSet& rOptSet );

    //  InputHandler:
    BOOL                IsEditMode();   // nicht bei SC_INPUT_TYPE
    BOOL                IsInputMode();  // auch bei SC_INPUT_TYPE
    void                SetInputMode( ScInputMode eMode );
    BOOL                InputKeyEvent( const KeyEvent& rKEvt, BOOL bStartEdit = FALSE );
    void                InputEnterHandler( BYTE nBlockMode = 0 );
    void                InputCancelHandler();
    void                InputSelection( EditView* pView );
    void                InputChanged( EditView* pView );
    ScInputHandler*     GetInputHdl( ScTabViewShell* pViewSh = NULL, BOOL bUseRef = TRUE );

    void                SetRefInputHdl( ScInputHandler* pNew );
    ScInputHandler*     GetRefInputHdl();

    void                SetInputWindow( ScInputWindow* pWin );
    void                ViewShellGone(ScTabViewShell* pViewSh);
    void                ViewShellChanged();
    // Kommunikation mit Funktionsautopilot
    void                InputGetSelection( xub_StrLen& rStart, xub_StrLen& rEnd );
    void                InputSetSelection( xub_StrLen nStart, xub_StrLen nEnd );
    void                InputReplaceSelection( const String& rStr );
    String              InputGetFormulaStr();
    void                ActivateInputWindow( const String* pStr = NULL,
                                                BOOL bMatrix = FALSE );

    void                InitFormEditData();
    void                ClearFormEditData();
    ScFormEditData*     GetFormEditData()       { return pFormEditData; }

    //  Referenzeingabe:
    void                SetRefDialog( USHORT nId, BOOL bVis, SfxViewFrame* pViewFrm = NULL );
    BOOL                IsModalMode(SfxObjectShell* pDocSh = NULL);
    BOOL                IsFormulaMode();
    BOOL                IsRefDialogOpen();
    BOOL                IsTableLocked();
    void                OpenTeamDlg();
    void                SetTeamDlg( ScTeamDlg* pDlg )           { pTeamDlg = pDlg; }
    ScTeamDlg*          GetTeamDlg() const                      { return pTeamDlg; }
    void                SetReference( const ScRange& rRef, ScDocument* pDoc,
                                        const ScMarkData* pMarkData = NULL );
    void                AddRefEntry();
    void                EndReference();
    USHORT              GetCurRefDlgId() const                  { return nCurRefDlgId; }

    //virtuelle Methoden fuer den Optionendialog
    virtual SfxItemSet*  CreateItemSet( USHORT nId );
    virtual void         ApplyItemSet( USHORT nId, const SfxItemSet& rSet );
    virtual SfxTabPage*  CreateTabPage( USHORT nId, Window* pParent, const SfxItemSet& rSet );
};

#define SC_MOD() ( *(ScModule**) GetAppData(SHL_CALC) )

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sddll.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 18:14:29 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SDDLL_HXX
#define _SDDLL_HXX

#ifndef _SDMOD_HXX
#include "sdmod.hxx"
#endif

#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFXDEFS_HXX //autogen
#include <sfx2/sfxdefs.hxx>
#endif

class SvFactory;
class SotFactory;
class SfxMedium;
class SfxFilter;

/*************************************************************************
|*
|* This class is a wrapper for a Load-On-Demand-DLL. One instance
|* per SfxApplication will be created for the runtime of
|* SfxApplication-subclass::Main().
|*
|* Remember: Do export this class! It is used by the application.
|*
\************************************************************************/

class SdDLL
{
protected:
    static void     RegisterFactorys();
    static void     RegisterInterfaces();
    static void     RegisterControllers();

public:
                    // Ctor/Dtor must be linked to the application
                    SdDLL();
                    ~SdDLL();

                    // static-init/exit-code must be linked to the application
    static void     LibInit();  // called from SfxApplication-subclass::Init()
    static void     LibExit();  // called from SfxApplication-subclass::Exit()

                    // DLL-init/exit-code must be linked to the DLL only
    static void     Init();     // called directly after loading the DLL
    static void     Exit();     // called directly befor unloading the DLL
};

#ifndef _SD_DLL                      // Das define muss im Draw gesetzt werden
#define SD_MOD() ( *(SdModule**) GetAppData(SHL_DRAW) )
#endif

#endif                               // _SDDLL_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.364); FILE MERGED 2005/09/05 13:19:59 rt 1.5.364.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sddll.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:58:45 $
 *
 *  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 _SDDLL_HXX
#define _SDDLL_HXX

#ifndef _SDMOD_HXX
#include "sdmod.hxx"
#endif

#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFXDEFS_HXX //autogen
#include <sfx2/sfxdefs.hxx>
#endif

class SvFactory;
class SotFactory;
class SfxMedium;
class SfxFilter;

/*************************************************************************
|*
|* This class is a wrapper for a Load-On-Demand-DLL. One instance
|* per SfxApplication will be created for the runtime of
|* SfxApplication-subclass::Main().
|*
|* Remember: Do export this class! It is used by the application.
|*
\************************************************************************/

class SdDLL
{
protected:
    static void     RegisterFactorys();
    static void     RegisterInterfaces();
    static void     RegisterControllers();

public:
                    // Ctor/Dtor must be linked to the application
                    SdDLL();
                    ~SdDLL();

                    // static-init/exit-code must be linked to the application
    static void     LibInit();  // called from SfxApplication-subclass::Init()
    static void     LibExit();  // called from SfxApplication-subclass::Exit()

                    // DLL-init/exit-code must be linked to the DLL only
    static void     Init();     // called directly after loading the DLL
    static void     Exit();     // called directly befor unloading the DLL
};

#ifndef _SD_DLL                      // Das define muss im Draw gesetzt werden
#define SD_MOD() ( *(SdModule**) GetAppData(SHL_DRAW) )
#endif

#endif                               // _SDDLL_HXX

<|endoftext|>


<commit_before>#include <algorithm>
#include <assert.h>
#include <math.h>
#include <random>
#include "search/taboo.h"
#include <iostream>
#include "easylogging++.h"

#define MAX_DOUBLE pow(2.0, 1024)

TabooSearch::TabooSearch()
{
	std::random_device rnd_dev;
	rng.seed(rnd_dev());
	PointId point_zero = PointId();
	PointStats* ps = new PointStats {
		.point_id = point_zero,
		.sample_size = 0,
		.sat_total = 0,
		.best_cutoff = 0,
		.best_incapacity = MAX_DOUBLE
	};
	checked_points_[point_zero] = ps;
	global_record_=ps;

}

TabooSearch::~TabooSearch()
{
	// Delete all points from DB
	for (auto point_pair: checked_points_)
		delete point_pair.second;
}

std::vector<PointId> TabooSearch::GetUncheckedHammingNbhd (const PointId& point)
{
	std::vector<PointId> result;
	for (int i =0; i<point.size(); ++i){
		PointId tmp = point;
		FlipBit(tmp[i]);
		//tmp[i]=0;
		if (!PointChecked(tmp))
			result.push_back(tmp);
	}
	return result;
}

void TabooSearch::AddPointResults (const PointId& point, const Results& results)
{
	// Filter SATs and sort their scans values
	std::vector <long long int> sat_scans;
	for (auto report: results)
		if (report.state==SAT)
			sat_scans.push_back(report.watch_scans);
	std::sort(sat_scans.begin(), sat_scans.end());

	// Create new point
	PointStats* ps = new PointStats {
		.point_id = point,
		.sample_size = results.size(),
		.sat_total = sat_scans.size(),
		.best_cutoff = 0,
		.best_incapacity = MAX_DOUBLE
	};

	// derive it's best incapacity
	int S = CountOnes(point);
	const double sz = pow(2.0, S);	// backdoor size multiplier
	for (int i=0; i<sat_scans.size(); ++i){
		double t = sat_scans[i];
		double p = (1+i)/ps->sample_size;	// predicted SAT probability
		double incapacity = sz * t * 3/p ;
		if (incapacity < ps->best_incapacity){
		       	ps->best_incapacity = incapacity;	// update local record
			ps->best_cutoff  = sat_scans[i];
		}
	}
	// and add it to DB and origin candidates queue.
	checked_points_[point] = ps;
	origin_queue_.push(ps);

	// Check and update global incapacity record if necessary
	if (ps->best_incapacity < global_record_->best_incapacity){
		global_record_= checked_points_[point]; // New record found !!!
		LOG(INFO) << " New record found: "
			<< CountOnes(point) << " "
			<< ps->best_incapacity << " "
			<< sat_scans.size() << " "
			<< Point2Bitstring(point) << " ccc "
			<< Point2Varstring(point) ;
	}
}

PointId TabooSearch::GenerateNewPoint()
{
	std::vector <PointId> candidates;
	for(;;){
		// Select next origin candidate from top incapacity queue
		candidates = GetUncheckedHammingNbhd(
				origin_queue_.top()->point_id);
		if (candidates.size()>0) break;
		// All origin's neighbours were already checked, so
		// we remove it from queue
		origin_queue_.pop();
		LOG(DEBUG) << " ORIGIN POP!";
	}
	// Shuffle candidate points to even their probabilities
	std::shuffle(candidates.begin(), candidates.end(), rng);

	return candidates[0];
}

PointId TabooSearch::ProcessPointResults (const PointId& point, const Results& results)
{
	AddPointResults(point, results);

	// DEBUG
	auto second_best =  *(&origin_queue_.top() + (origin_queue_.size()>1 ? 1:0)); // dirty pointer hack!!
	LOG_EVERY_N(10, DEBUG)
		<< Point2Bitstring(point)
		<< " Point incapacity: " << checked_points_[point]->best_incapacity
		<< " Point SAT units: " << checked_points_[point]->sat_total
		<< " Best incapacity: " << GetStats().best_incapacity
		<< " queue size: " <<origin_queue_.size()
		<< " queue top: " << origin_queue_.top()->best_incapacity
		<< " second top: " << second_best->best_incapacity;

	return GenerateNewPoint();
}

PointStats TabooSearch::GetStats()
{
	return *global_record_;
}
<commit_msg> * Fixed double type conversion bug<commit_after>#include <algorithm>
#include <assert.h>
#include <math.h>
#include <random>
#include "search/taboo.h"
#include <iostream>
#include "easylogging++.h"

#define MAX_DOUBLE pow(2.0, 1024)

TabooSearch::TabooSearch()
{
	std::random_device rnd_dev;
	rng.seed(rnd_dev());
	PointId point_zero = PointId();
	PointStats* ps = new PointStats {
		.point_id = point_zero,
		.sample_size = 0,
		.sat_total = 0,
		.best_cutoff = 0,
		.best_incapacity = MAX_DOUBLE
	};
	checked_points_[point_zero] = ps;
	global_record_=ps;

}

TabooSearch::~TabooSearch()
{
	// Delete all points from DB
	for (auto point_pair: checked_points_)
		delete point_pair.second;
}

std::vector<PointId> TabooSearch::GetUncheckedHammingNbhd (const PointId& point)
{
	std::vector<PointId> result;
	for (int i =0; i<point.size(); ++i){
		PointId tmp = point;
		FlipBit(tmp[i]);
		//tmp[i]=0;
		if (!PointChecked(tmp))
			result.push_back(tmp);
	}
	return result;
}

void TabooSearch::AddPointResults (const PointId& point, const Results& results)
{
	// Filter SATs and sort their scans values
	std::vector <long long int> sat_scans;
	for (auto report: results)
		if (report.state==SAT)
			sat_scans.push_back(report.watch_scans);
	std::sort(sat_scans.begin(), sat_scans.end());

	// Create new point
	PointStats* ps = new PointStats {
		.point_id = point,
		.sample_size = results.size(),
		.sat_total = sat_scans.size(),
		.best_cutoff = 0,
		.best_incapacity = MAX_DOUBLE
	};

	// derive it's best incapacity
	int S = CountOnes(point);
	const double sz = pow(2.0, S);	// backdoor size multiplier
	for (int i=0; i<sat_scans.size(); ++i){
		double t = sat_scans[i];
		double p = double(1+i)/ps->sample_size;	// predicted SAT probability
		double incapacity = sz * t * 3/p ;
		if (incapacity < ps->best_incapacity){
		       	ps->best_incapacity = incapacity;	// update local record
			ps->best_cutoff  = sat_scans[i];
		}
	}
	// and add it to DB and origin candidates queue.
	checked_points_[point] = ps;
	origin_queue_.push(ps);

	// Check and update global incapacity record if necessary
	if (ps->best_incapacity < global_record_->best_incapacity){
		global_record_= checked_points_[point]; // New record found !!!
		LOG(INFO) << " New record found: "
			<< CountOnes(point) << " "
			<< ps->best_incapacity << " "
			<< sat_scans.size() << " "
			<< Point2Bitstring(point) << " ccc "
			<< Point2Varstring(point) ;
	}
}

PointId TabooSearch::GenerateNewPoint()
{
	std::vector <PointId> candidates;
	for(;;){
		// Select next origin candidate from top incapacity queue
		candidates = GetUncheckedHammingNbhd(
				origin_queue_.top()->point_id);
		if (candidates.size()>0) break;
		// All origin's neighbours were already checked, so
		// we remove it from queue
		origin_queue_.pop();
		LOG(DEBUG) << " ORIGIN POP!";
	}
	// Shuffle candidate points to even their probabilities
	std::shuffle(candidates.begin(), candidates.end(), rng);

	return candidates[0];
}

PointId TabooSearch::ProcessPointResults (const PointId& point, const Results& results)
{
	AddPointResults(point, results);

	// DEBUG
	auto second_best =  *(&origin_queue_.top() + (origin_queue_.size()>1 ? 1:0)); // dirty pointer hack!!
	LOG_EVERY_N(10, DEBUG)
		<< Point2Bitstring(point)
		<< " Point incapacity: " << checked_points_[point]->best_incapacity
		<< " Point SAT units: " << checked_points_[point]->sat_total
		<< " Best incapacity: " << GetStats().best_incapacity
		<< " queue size: " <<origin_queue_.size()
		<< " queue top: " << origin_queue_.top()->best_incapacity
		<< " second top: " << second_best->best_incapacity;

	return GenerateNewPoint();
}

PointStats TabooSearch::GetStats()
{
	return *global_record_;
}
<|endoftext|>


<commit_before>/**
   @file main.cpp
   @brief Sensord initiation point

   Copyright (C) 2009-2010 Nokia Corporation

   @author Semi Malinen <semi.malinen@nokia.com>
   @author Joep van Gassel <joep.van.gassel@nokia.com>
   @author Timo Rongas <ext-timo.2.rongas@nokia.com>
   @author Ustun Ergenoglu <ext-ustun.ergenoglu@nokia.com>
   @author Lihan Guo <ext-lihan.guo@nokia.com>
   @author Antti Virtanen <antti.i.virtanen@nokia.com

   This file is part of Sensord.

   Sensord 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.

   Sensord 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 Sensord.  If not, see <http://www.gnu.org/licenses/>.

 */

#include <QtCore/QCoreApplication>
#include <signal.h>
#include <iostream>
#include <errno.h>

#include "config.h"
#include "sensormanager.h"
#include "sensormanager_a.h"
#include "logging.h"
#include "calibrationhandler.h"
#include "parser.h"

void printUsage();

void signalUSR1(int param)
{
    Q_UNUSED(param);

    SensordLogger::setOutputLevel(static_cast<SensordLogLevel> ((static_cast<int>(SensordLogger::getOutputLevel()) + 1) % SensordLogN));

    std::cerr << "New debugging level: " << SensordLogger::getOutputLevel() << "\n";
}

void signalUSR2(int param)
{
    Q_UNUSED(param);

    QStringList output;

    output.append("Flushing sensord state\n");
    output.append(QString("  Logging level: %1\n").arg(SensordLogger::getOutputLevel()));
    SensorManager::instance().printStatus(output);

    foreach (const QString& line, output) {
        sensordLogW() << line.toLocal8Bit().data();
    }
}

void signalINT(int param)
{
    Q_UNUSED(param);
    QCoreApplication::exit(0);
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    SensorManager& sm = SensorManager::instance();
    Parser parser(app.arguments());
    SensordLogger::init(parser.logTarget(), parser.logFilePath());

    if (parser.printHelp())
    {
        printUsage();
        app.exit(EXIT_SUCCESS);
        return 0;

    }

    if (parser.changeLogLevel())
    {
        SensordLogger::setOutputLevel(parser.getLogLevel());
    }

    const char* CONFIG_FILE_PATH = "/etc/sensorfw/sensord.conf";
    const char* CONFIG_DIR_PATH = "/etc/sensorfw/sensord.conf.d/";

    QString defConfigFile = CONFIG_FILE_PATH;
    if(parser.configFileInput())
        defConfigFile = parser.configFilePath();
    QString defConfigDir = CONFIG_DIR_PATH;
    if(parser.configDirInput())
        defConfigDir = parser.configDirPath();
    if (Config::loadConfig(defConfigFile, defConfigDir))
        sensordLogT() << "Config file is loaded successfully.";
    else
    {
        sensordLogC() << "Config file error! Load using default paths.";
        if (!Config::loadConfig(CONFIG_FILE_PATH, CONFIG_DIR_PATH))
        {
            sensordLogC() << "Which also failed. Bailing out";
            return 1;
        }
    }

    signal(SIGUSR1, signalUSR1);
    signal(SIGUSR2, signalUSR2);
    signal(SIGINT, signalINT);

#ifdef PROVIDE_CONTEXT_INFO
    if (parser.contextInfo())
    {
        sensordLogD() << "Loading ContextSensor " << sm.loadPlugin("contextsensor");
        sensordLogD() << "Loading ALSSensor " << sm.loadPlugin("alssensor");
    }
#endif

    if (parser.createDaemon())
    {
        int pid = fork();

        if(pid < 0)
        {
            sensordLogC() << "Failed to create a daemon: " << strerror(errno);
            exit(EXIT_FAILURE);
        } else if (pid > 0) {
            sensordLogW() << "Created a daemon";
            exit(EXIT_SUCCESS);
        }
    }

    if (parser.magnetometerCalibration())
    {
        CalibrationHandler* calibrationHandler_ = new CalibrationHandler(NULL);
        calibrationHandler_->initiateSession();
        QObject::connect(&sm, SIGNAL(resumeCalibration()), calibrationHandler_, SLOT(resumeCalibration()));
        QObject::connect(&sm, SIGNAL(stopCalibration()), calibrationHandler_, SLOT(stopCalibration()));
    }

    if (!sm.registerService())
    {
        sensordLogW() << "Failed to register service on D-Bus. Aborting.";
        exit(EXIT_FAILURE);
    }

    int ret = app.exec();
    sensordLogD() << "Exitting...";
    Config::close();
    SensordLogger::close();
    return ret;
}

void printUsage()
{
    qDebug() << "Usage: sensord [OPTIONS]";
    qDebug() << " -d, --daemon                     Detach from terminal and run as daemon.\n";
    qDebug() << " -l=N, --log-level=<level>        Use given logging level. Messages are logged for";
    qDebug() << "                                  the given and higher priority levels. Level";
    qDebug() << "                                  can also be notched up by sending SIGUSR1 to";
    qDebug() << "                                  the process. Valid values for N are: 'test',";
    qDebug() << "                                  'debug', 'warning', 'critical'.\n";
    qDebug() << " --log-target=<target>            Logging target mask (1=stdout, 2=stderr, 4=file, 8=syslog and combos e.g. 3=stdout|stderr\n";
    qDebug() << " --log-file-path=<path>           Log file path\n";
    qDebug() << " -c=P, --config-file=<path>       Load configuration from given path. By default";
    qDebug() << "                                  /etc/sensorfw/sensord.conf is used.\n";
    qDebug() << " --no-context-info                Do not provide context information for context";
    qDebug() << "                                  framework.\n";
    qDebug() << " --no-magnetometer-bg-calibration Do not start calibration of magnetometer in";
    qDebug() << "                                  the background.\n";
    qDebug() << " -h, --help                       Show usage info and exit.";
}
<commit_msg>Removed unnecessary log print.<commit_after>/**
   @file main.cpp
   @brief Sensord initiation point

   Copyright (C) 2009-2010 Nokia Corporation

   @author Semi Malinen <semi.malinen@nokia.com>
   @author Joep van Gassel <joep.van.gassel@nokia.com>
   @author Timo Rongas <ext-timo.2.rongas@nokia.com>
   @author Ustun Ergenoglu <ext-ustun.ergenoglu@nokia.com>
   @author Lihan Guo <ext-lihan.guo@nokia.com>
   @author Antti Virtanen <antti.i.virtanen@nokia.com

   This file is part of Sensord.

   Sensord 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.

   Sensord 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 Sensord.  If not, see <http://www.gnu.org/licenses/>.

 */

#include <QtCore/QCoreApplication>
#include <signal.h>
#include <iostream>
#include <errno.h>

#include "config.h"
#include "sensormanager.h"
#include "sensormanager_a.h"
#include "logging.h"
#include "calibrationhandler.h"
#include "parser.h"

void printUsage();

void signalUSR1(int param)
{
    Q_UNUSED(param);

    SensordLogger::setOutputLevel(static_cast<SensordLogLevel> ((static_cast<int>(SensordLogger::getOutputLevel()) + 1) % SensordLogN));

    std::cerr << "New debugging level: " << SensordLogger::getOutputLevel() << "\n";
}

void signalUSR2(int param)
{
    Q_UNUSED(param);

    QStringList output;

    output.append("Flushing sensord state\n");
    output.append(QString("  Logging level: %1\n").arg(SensordLogger::getOutputLevel()));
    SensorManager::instance().printStatus(output);

    foreach (const QString& line, output) {
        sensordLogW() << line.toLocal8Bit().data();
    }
}

void signalINT(int param)
{
    Q_UNUSED(param);
    QCoreApplication::exit(0);
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    SensorManager& sm = SensorManager::instance();
    Parser parser(app.arguments());
    SensordLogger::init(parser.logTarget(), parser.logFilePath());

    if (parser.printHelp())
    {
        printUsage();
        app.exit(EXIT_SUCCESS);
        return 0;

    }

    if (parser.changeLogLevel())
    {
        SensordLogger::setOutputLevel(parser.getLogLevel());
    }

    const char* CONFIG_FILE_PATH = "/etc/sensorfw/sensord.conf";
    const char* CONFIG_DIR_PATH = "/etc/sensorfw/sensord.conf.d/";

    QString defConfigFile = CONFIG_FILE_PATH;
    if(parser.configFileInput())
        defConfigFile = parser.configFilePath();
    QString defConfigDir = CONFIG_DIR_PATH;
    if(parser.configDirInput())
        defConfigDir = parser.configDirPath();
    if (!Config::loadConfig(defConfigFile, defConfigDir))
    {
        sensordLogC() << "Config file error! Load using default paths.";
        if (!Config::loadConfig(CONFIG_FILE_PATH, CONFIG_DIR_PATH))
        {
            sensordLogC() << "Which also failed. Bailing out";
            return 1;
        }
    }

    signal(SIGUSR1, signalUSR1);
    signal(SIGUSR2, signalUSR2);
    signal(SIGINT, signalINT);

#ifdef PROVIDE_CONTEXT_INFO
    if (parser.contextInfo())
    {
        sensordLogD() << "Loading ContextSensor " << sm.loadPlugin("contextsensor");
        sensordLogD() << "Loading ALSSensor " << sm.loadPlugin("alssensor");
    }
#endif

    if (parser.createDaemon())
    {
        int pid = fork();

        if(pid < 0)
        {
            sensordLogC() << "Failed to create a daemon: " << strerror(errno);
            exit(EXIT_FAILURE);
        } else if (pid > 0) {
            sensordLogW() << "Created a daemon";
            exit(EXIT_SUCCESS);
        }
    }

    if (parser.magnetometerCalibration())
    {
        CalibrationHandler* calibrationHandler_ = new CalibrationHandler(NULL);
        calibrationHandler_->initiateSession();
        QObject::connect(&sm, SIGNAL(resumeCalibration()), calibrationHandler_, SLOT(resumeCalibration()));
        QObject::connect(&sm, SIGNAL(stopCalibration()), calibrationHandler_, SLOT(stopCalibration()));
    }

    if (!sm.registerService())
    {
        sensordLogW() << "Failed to register service on D-Bus. Aborting.";
        exit(EXIT_FAILURE);
    }

    int ret = app.exec();
    sensordLogD() << "Exitting...";
    Config::close();
    SensordLogger::close();
    return ret;
}

void printUsage()
{
    qDebug() << "Usage: sensord [OPTIONS]";
    qDebug() << " -d, --daemon                     Detach from terminal and run as daemon.\n";
    qDebug() << " -l=N, --log-level=<level>        Use given logging level. Messages are logged for";
    qDebug() << "                                  the given and higher priority levels. Level";
    qDebug() << "                                  can also be notched up by sending SIGUSR1 to";
    qDebug() << "                                  the process. Valid values for N are: 'test',";
    qDebug() << "                                  'debug', 'warning', 'critical'.\n";
    qDebug() << " --log-target=<target>            Logging target mask (1=stdout, 2=stderr, 4=file, 8=syslog and combos e.g. 3=stdout|stderr\n";
    qDebug() << " --log-file-path=<path>           Log file path\n";
    qDebug() << " -c=P, --config-file=<path>       Load configuration from given path. By default";
    qDebug() << "                                  /etc/sensorfw/sensord.conf is used.\n";
    qDebug() << " --no-context-info                Do not provide context information for context";
    qDebug() << "                                  framework.\n";
    qDebug() << " --no-magnetometer-bg-calibration Do not start calibration of magnetometer in";
    qDebug() << "                                  the background.\n";
    qDebug() << " -h, --help                       Show usage info and exit.";
}
<|endoftext|>


<commit_before>
/**
 *
 * Copyright (C) 2014 Jolla Ltd.
 * Contact: Thomas Perl <thomas.perl@jolla.com>
 * All rights reserved.
 *
 * This file is part of libsailfishapp
 *
 * You may use this file under the terms of the GNU Lesser General
 * Public License version 2.1 as published by the Free Software Foundation
 * and appearing in the file license.lgpl included in the packaging
 * of this file.
 *
 * 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
 * and appearing in the file license.lgpl included in the packaging
 * of this file.
 *
 * 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.
 *
 **/

#include "sailfishapp.h"
#include "sailfishapp_priv.h"

#include <QCoreApplication>
#include <QStandardPaths>
#include <QSettings>
#include <QQmlEngine>
#include <QDebug>
#include <QDir>

int main(int argc, char *argv[])
{
    QGuiApplication *app = SailfishApp::application(argc, argv);

    qDebug() << "== QCoreApplication ==";
    qDebug() << "Organization:" << QCoreApplication::organizationName();
    qDebug() << "Application:" << QCoreApplication::applicationName();

    qDebug() << "== QStandardPaths ==";
    qDebug() << "Writable data:" << QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    qDebug() << "Writable cache:" << QStandardPaths::writableLocation(QStandardPaths::CacheLocation);

    // QStandardPaths::ConfigLocation only tells us the generic config
    // location; in order to get the application-specific location, we
    // append the QCoreApplication::applicationName() to it (we could
    // also use QCoreApplication::organizationName(), as both are set
    // by libsailfishapp so that Qt always uses the right paths)
    qDebug() << "== Target paths ==";
    qDebug() << "Config goes into:" << QDir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation))
        .filePath(QCoreApplication::applicationName());

    qDebug() << "== QSettings ==";
    qDebug() << "File name:" << QSettings().fileName();

    qDebug() << "== QQmlEngine ==";
    qDebug() << "Offline storage path:" << QQmlEngine().offlineStoragePath();

    return 0;
}
<commit_msg>tests: Fix warning about unused variable<commit_after>
/**
 *
 * Copyright (C) 2014 Jolla Ltd.
 * Contact: Thomas Perl <thomas.perl@jolla.com>
 * All rights reserved.
 *
 * This file is part of libsailfishapp
 *
 * You may use this file under the terms of the GNU Lesser General
 * Public License version 2.1 as published by the Free Software Foundation
 * and appearing in the file license.lgpl included in the packaging
 * of this file.
 *
 * 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
 * and appearing in the file license.lgpl included in the packaging
 * of this file.
 *
 * 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.
 *
 **/

#include "sailfishapp.h"
#include "sailfishapp_priv.h"

#include <QGuiApplication>
#include <QStandardPaths>
#include <QSettings>
#include <QQmlEngine>
#include <QDebug>
#include <QDir>

int main(int argc, char *argv[])
{
    QGuiApplication *app = SailfishApp::application(argc, argv);

    qDebug() << "== QCoreApplication ==";
    qDebug() << "Organization:" << QCoreApplication::organizationName();
    qDebug() << "Application:" << QCoreApplication::applicationName();

    qDebug() << "== QStandardPaths ==";
    qDebug() << "Writable data:" << QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    qDebug() << "Writable cache:" << QStandardPaths::writableLocation(QStandardPaths::CacheLocation);

    // QStandardPaths::ConfigLocation only tells us the generic config
    // location; in order to get the application-specific location, we
    // append the QCoreApplication::applicationName() to it (we could
    // also use QCoreApplication::organizationName(), as both are set
    // by libsailfishapp so that Qt always uses the right paths)
    qDebug() << "== Target paths ==";
    qDebug() << "Config goes into:" << QDir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation))
        .filePath(QCoreApplication::applicationName());

    qDebug() << "== QSettings ==";
    qDebug() << "File name:" << QSettings().fileName();

    qDebug() << "== QQmlEngine ==";
    qDebug() << "Offline storage path:" << QQmlEngine().offlineStoragePath();

    delete app;

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include <thrift/lib/cpp/transport/THeader.h>
#include <thrift/lib/cpp/util/THttpParser.h>

#include <boost/test/unit_test.hpp>
#include <memory>
#include <folly/io/IOBuf.h>
#include <folly/io/IOBufQueue.h>

using namespace boost;
using namespace apache::thrift;
using namespace folly;
using namespace apache::thrift::transport;

BOOST_AUTO_TEST_CASE(largetransform) {
  THeader header;
  header.setTransform(THeader::ZLIB_TRANSFORM); // ZLib flag

  size_t buf_size = 1000000;
  std::unique_ptr<IOBuf> buf(IOBuf::create(buf_size));
  buf->append(buf_size);

  std::map<std::string, std::string> persistentHeaders;
  buf = header.addHeader(std::move(buf), persistentHeaders);
  buf_size = buf->computeChainDataLength();
  std::unique_ptr<IOBufQueue> queue(new IOBufQueue);
  std::unique_ptr<IOBufQueue> queue2(new IOBufQueue);
  queue->append(std::move(buf));
  queue2->append(queue->split(buf_size/4));
  queue2->append(queue->split(buf_size/4));
  queue2->append(IOBuf::create(0)); // Empty buffer should work
  queue2->append(queue->split(buf_size/4));
  queue2->append(queue->move());

  size_t needed;

  buf = header.removeHeader(queue2.get(), needed, persistentHeaders);
}

BOOST_AUTO_TEST_CASE(http_clear_header) {
  THeader header;
  header.setClientType(THRIFT_HTTP_CLIENT_TYPE);
  auto parser = std::make_shared<apache::thrift::util::THttpClientParser>(
      "testhost", "testuri");
  header.setHttpClientParser(parser);
  header.setHeader("WriteHeader", "foo");

  size_t buf_size = 1000000;
  std::unique_ptr<IOBuf> buf(IOBuf::create(buf_size));
  std::map<std::string, std::string> persistentHeaders;
  buf = header.addHeader(std::move(buf), persistentHeaders);

  BOOST_CHECK(header.getWriteHeaders().empty());
}

boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]);

boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
  boost::unit_test::framework::master_test_suite().p_name.value =
    "THeaderTest";

  if (argc != 1) {
    fprintf(stderr, "unexpected arguments: %s\n", argv[1]);
    exit(1);
  }

  return nullptr;
}
<commit_msg>Migrate to gtest: thrift/lib/cpp/transport/test.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include <thrift/lib/cpp/transport/THeader.h>
#include <thrift/lib/cpp/util/THttpParser.h>

#include <memory>
#include <folly/io/IOBuf.h>
#include <folly/io/IOBufQueue.h>

#include <gtest/gtest.h>

using namespace apache::thrift;
using namespace folly;
using namespace apache::thrift::transport;

TEST(THeaderTest, largetransform) {
  THeader header;
  header.setTransform(THeader::ZLIB_TRANSFORM); // ZLib flag

  size_t buf_size = 1000000;
  std::unique_ptr<IOBuf> buf(IOBuf::create(buf_size));
  buf->append(buf_size);

  std::map<std::string, std::string> persistentHeaders;
  buf = header.addHeader(std::move(buf), persistentHeaders);
  buf_size = buf->computeChainDataLength();
  std::unique_ptr<IOBufQueue> queue(new IOBufQueue);
  std::unique_ptr<IOBufQueue> queue2(new IOBufQueue);
  queue->append(std::move(buf));
  queue2->append(queue->split(buf_size/4));
  queue2->append(queue->split(buf_size/4));
  queue2->append(IOBuf::create(0)); // Empty buffer should work
  queue2->append(queue->split(buf_size/4));
  queue2->append(queue->move());

  size_t needed;

  buf = header.removeHeader(queue2.get(), needed, persistentHeaders);
}

TEST(THeaderTest, http_clear_header) {
  THeader header;
  header.setClientType(THRIFT_HTTP_CLIENT_TYPE);
  auto parser = std::make_shared<apache::thrift::util::THttpClientParser>(
      "testhost", "testuri");
  header.setHttpClientParser(parser);
  header.setHeader("WriteHeader", "foo");

  size_t buf_size = 1000000;
  std::unique_ptr<IOBuf> buf(IOBuf::create(buf_size));
  std::map<std::string, std::string> persistentHeaders;
  buf = header.addHeader(std::move(buf), persistentHeaders);

  EXPECT_TRUE(header.getWriteHeaders().empty());
}
<|endoftext|>


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

#include "LayeredSideFluxAverage.h"

// libMesh
#include "libmesh/mesh_tools.h"

template<>
InputParameters validParams<TransientMultiApp>()
{
  InputParameters params = validParams<MultiApp>();
  params += validParams<TransientInterface>();

  params.addParam<bool>("sub_cycling", false, "Set to true to allow this MultiApp to take smaller timesteps than the rest of the simulation.  More than one timestep will be performed for each 'master' timestep");

  params.addParam<bool>("detect_steady_state", false, "If true then while sub_cycling a steady state check will be done.  In this mode output will only be done once the MultiApp reaches the target time or steady state is reached");

  params.addParam<Real>("steady_state_tol", 1e-8, "The relative difference between the new solution and the old solution that will be considered to be at steady state");

  params.addParam<unsigned int>("max_failures", 0, "Maximum number of solve failures tolerated while sub_cycling.");

  params.addParam<bool>("tolerate_failure", false, "If true this MultiApp won't participate in dt decisions and will always be fast-forwarded to the current time.");

  params.addParam<bool>("catch_up", false, "If true this will allow failed solves to attempt to 'catch up' using smaller timesteps.");

  return params;
}

TransientMultiApp::TransientMultiApp(const std::string & name, InputParameters parameters):
    MultiApp(name, parameters),
    _sub_cycling(getParam<bool>("sub_cycling")),
    _detect_steady_state(getParam<bool>("detect_steady_state")),
    _steady_state_tol(getParam<Real>("steady_state_tol")),
    _max_failures(getParam<unsigned int>("max_failures")),
    _tolerate_failure(getParam<bool>("tolerate_failure")),
    _failures(0),
    _catch_up(false)
{
  if(!_has_an_app)
    return;

  MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);

  if(_has_an_app)
  {
    _transient_executioners.resize(_my_num_apps);
    // Grab Transient Executioners from each app
    for(unsigned int i=0; i<_my_num_apps; i++)
    {
      MooseApp * app = _apps[i];
      Transient * ex = dynamic_cast<Transient *>(app->getExecutioner());
      if(!ex)
        mooseError("MultiApp " << name << " is not using a Transient Executioner!");
      appProblem(_first_local_app + i)->initialSetup();
      ex->preExecute();
      appProblem(_first_local_app + i)->copyOldSolutions();
      _transient_executioners[i] = ex;

      if(_detect_steady_state || _tolerate_failure)
        ex->allowOutput(false);
    }
  }

  // Swap back
  Moose::swapLibMeshComm(swapped);
}

TransientMultiApp::~TransientMultiApp()
{
  if(!_has_an_app)
    return;

  MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);

  for(unsigned int i=0; i<_my_num_apps; i++)
  {
    Transient * ex = _transient_executioners[i];

    ex->postExecute();
  }

  // Swap back
  Moose::swapLibMeshComm(swapped);
}

void
TransientMultiApp::solveStep(Real dt, Real target_time)
{
  if(!_has_an_app)
    return;

  std::cout<<"Solving MultiApp "<<_name<<std::endl;

  MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);

  int rank;
  int ierr;
  ierr = MPI_Comm_rank(_orig_comm, &rank); mooseCheckMPIErr(ierr);

  for(unsigned int i=0; i<_my_num_apps; i++)
  {
    Transient * ex = _transient_executioners[i];

    if(_sub_cycling)
    {
      ex->setTargetTime(target_time);

      unsigned int failures = 0;

      bool at_steady = false;

      // Now do all of the solves we need
      while(!at_steady && ex->getTime() + 2e-14 < target_time)
      {
        ex->takeStep();

        bool converged = ex->lastSolveConverged();

        if(!converged)
        {
          mooseWarning("While sub_cycling "<<_name<<_first_local_app+i<<" failed to converge!"<<std::endl);
          _failures++;

          if(_failures > _max_failures)
            mooseError("While sub_cycling "<<_name<<_first_local_app+i<<" REALLY failed!"<<std::endl);
        }

        Real solution_change_norm = ex->solutionChangeNorm();

        if(_detect_steady_state)
          std::cout<<"Solution change norm: "<<solution_change_norm<<std::endl;

        if(converged && _detect_steady_state && solution_change_norm < _steady_state_tol)
        {
          std::cout<<"Detected Steady State!  Fast-forwarding to "<<target_time<<std::endl;

          at_steady = true;

          // Set the time for the problem to the target time we were looking for
          ex->setTime(target_time);

          // Force it to output right now
          ex->forceOutput();

          // Clean up the end
          ex->endStep();
        }
        else
          ex->endStep();
      }

      // If we were looking for a steady state, but didn't reach one, we still need to output one more time
      if(_detect_steady_state && !at_steady)
        ex->forceOutput();
    }
    else if(_tolerate_failure)
    {
      ex->computeConstrainedDT();
      ex->takeStep(dt);
      ex->setTime(target_time);
      ex->forceOutput();
      ex->endStep();
    }
    else
    {
      ex->takeStep(dt);
      ex->endStep();

      if(!ex->lastSolveConverged())
      {
        mooseWarning(_name<<_first_local_app+i<<" failed to converge!"<<std::endl);

        if(_catch_up)
        {
          ex->allowOutput(false); // Don't output while catching up
          ex->computeConstrainedDT(); // Have to call this even though we're not using the dt it computes
          ex->takeStep(dt / 2.0); // Cut the timestep in half to try two half-step solves
          ex->endStep();

          if(!ex->lastSolveConverged())
            mooseError(_name<<_first_local_app+i<<" failed to converge during first catch up!"<<std::endl);

          ex->allowOutput(true);

          ex->computeConstrainedDT();
          ex->takeStep(dt / 2.0);
          ex->endStep();

          if(!ex->lastSolveConverged())
            mooseError(_name<<_first_local_app+i<<" failed to converge during second catch up!"<<std::endl);
        }
      }
    }
  }

  // Swap back
  Moose::swapLibMeshComm(swapped);

  std::cout<<"Finished Solving MultiApp "<<_name<<std::endl;
}

Real
TransientMultiApp::computeDT()
{
  if(_sub_cycling) // Bow out of the timestep selection dance
    return std::numeric_limits<Real>::max();

  Real smallest_dt = std::numeric_limits<Real>::max();

  if(_has_an_app)
  {
    MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);

    for(unsigned int i=0; i<_my_num_apps; i++)
    {
      Transient * ex = _transient_executioners[i];
      Real dt = ex->computeConstrainedDT();

      smallest_dt = std::min(dt, smallest_dt);
    }

    // Swap back
    Moose::swapLibMeshComm(swapped);
  }

  if(_tolerate_failure) // Bow out of the timestep selection dance, we do this down here because we need to call computeConstrainedDT at least once for these executioners...
    return std::numeric_limits<Real>::max();

  Parallel::min(smallest_dt);
  return smallest_dt;
}

<commit_msg>add growth problem ref #1845<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/
#include "TransientMultiApp.h"

#include "LayeredSideFluxAverage.h"

// libMesh
#include "libmesh/mesh_tools.h"

template<>
InputParameters validParams<TransientMultiApp>()
{
  InputParameters params = validParams<MultiApp>();
  params += validParams<TransientInterface>();

  params.addParam<bool>("sub_cycling", false, "Set to true to allow this MultiApp to take smaller timesteps than the rest of the simulation.  More than one timestep will be performed for each 'master' timestep");

  params.addParam<bool>("detect_steady_state", false, "If true then while sub_cycling a steady state check will be done.  In this mode output will only be done once the MultiApp reaches the target time or steady state is reached");

  params.addParam<Real>("steady_state_tol", 1e-8, "The relative difference between the new solution and the old solution that will be considered to be at steady state");

  params.addParam<unsigned int>("max_failures", 0, "Maximum number of solve failures tolerated while sub_cycling.");

  params.addParam<bool>("tolerate_failure", false, "If true this MultiApp won't participate in dt decisions and will always be fast-forwarded to the current time.");

  params.addParam<bool>("catch_up", false, "If true this will allow failed solves to attempt to 'catch up' using smaller timesteps.");

  return params;
}

TransientMultiApp::TransientMultiApp(const std::string & name, InputParameters parameters):
    MultiApp(name, parameters),
    _sub_cycling(getParam<bool>("sub_cycling")),
    _detect_steady_state(getParam<bool>("detect_steady_state")),
    _steady_state_tol(getParam<Real>("steady_state_tol")),
    _max_failures(getParam<unsigned int>("max_failures")),
    _tolerate_failure(getParam<bool>("tolerate_failure")),
    _failures(0),
    _catch_up(false)
{
  if(!_has_an_app)
    return;

  MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);

  if(_has_an_app)
  {
    _transient_executioners.resize(_my_num_apps);
    // Grab Transient Executioners from each app
    for(unsigned int i=0; i<_my_num_apps; i++)
    {
      MooseApp * app = _apps[i];
      Transient * ex = dynamic_cast<Transient *>(app->getExecutioner());
      if(!ex)
        mooseError("MultiApp " << name << " is not using a Transient Executioner!");
      appProblem(_first_local_app + i)->initialSetup();
      ex->preExecute();
      appProblem(_first_local_app + i)->copyOldSolutions();
      _transient_executioners[i] = ex;

      if(_detect_steady_state || _tolerate_failure)
        ex->allowOutput(false);
    }
  }

  // Swap back
  Moose::swapLibMeshComm(swapped);
}

TransientMultiApp::~TransientMultiApp()
{
  if(!_has_an_app)
    return;

  MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);

  for(unsigned int i=0; i<_my_num_apps; i++)
  {
    Transient * ex = _transient_executioners[i];

    ex->postExecute();
  }

  // Swap back
  Moose::swapLibMeshComm(swapped);
}

void
TransientMultiApp::solveStep(Real dt, Real target_time)
{
  if(!_has_an_app)
    return;

  std::cout<<"Solving MultiApp "<<_name<<std::endl;

  MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);

  int rank;
  int ierr;
  ierr = MPI_Comm_rank(_orig_comm, &rank); mooseCheckMPIErr(ierr);

  for(unsigned int i=0; i<_my_num_apps; i++)
  {
    Transient * ex = _transient_executioners[i];

    if(ex->getTime() + 2e-14 >= target_time) // Maybe this MultiApp was already solved
      continue;

    if(_sub_cycling)
    {
      ex->allowOutput(false); // Don't Output
      ex->setTargetTime(target_time);

      unsigned int failures = 0;

      bool at_steady = false;

      // Now do all of the solves we need
      while(!at_steady && ex->getTime() + 2e-14 < target_time)
      {
        ex->takeStep();

        bool converged = ex->lastSolveConverged();

        if(!converged)
        {
          mooseWarning("While sub_cycling "<<_name<<_first_local_app+i<<" failed to converge!"<<std::endl);
          _failures++;

          if(_failures > _max_failures)
            mooseError("While sub_cycling "<<_name<<_first_local_app+i<<" REALLY failed!"<<std::endl);
        }

        Real solution_change_norm = ex->solutionChangeNorm();

        if(_detect_steady_state)
          std::cout<<"Solution change norm: "<<solution_change_norm<<std::endl;

        if(converged && _detect_steady_state && solution_change_norm < _steady_state_tol)
        {
          std::cout<<"Detected Steady State!  Fast-forwarding to "<<target_time<<std::endl;

          at_steady = true;

          // Set the time for the problem to the target time we were looking for
          ex->setTime(target_time);

          // Force it to output right now
          ex->forceOutput();

          // Clean up the end
          ex->endStep();
        }
        else
          ex->endStep();
      }

      // If we were looking for a steady state, but didn't reach one, we still need to output one more time
      if(!at_steady)
        ex->forceOutput();
    }
    else if(_tolerate_failure)
    {
      ex->computeConstrainedDT();
      ex->takeStep(dt);
      ex->setTime(target_time);
      ex->forceOutput();
      ex->endStep();
    }
    else
    {
      ex->takeStep(dt);
      ex->endStep();

      if(!ex->lastSolveConverged())
      {
        mooseWarning(_name<<_first_local_app+i<<" failed to converge!"<<std::endl);

        if(_catch_up)
        {
          ex->allowOutput(false); // Don't output while catching up
          ex->computeConstrainedDT(); // Have to call this even though we're not using the dt it computes
          ex->takeStep(dt / 2.0); // Cut the timestep in half to try two half-step solves
          ex->endStep();

          if(!ex->lastSolveConverged())
            mooseError(_name<<_first_local_app+i<<" failed to converge during first catch up!"<<std::endl);

          ex->allowOutput(true);

          ex->computeConstrainedDT();
          ex->takeStep(dt / 2.0);
          ex->endStep();

          if(!ex->lastSolveConverged())
            mooseError(_name<<_first_local_app+i<<" failed to converge during second catch up!"<<std::endl);
        }
      }
    }
  }

  // Swap back
  Moose::swapLibMeshComm(swapped);

  std::cout<<"Finished Solving MultiApp "<<_name<<std::endl;
}

Real
TransientMultiApp::computeDT()
{
  if(_sub_cycling) // Bow out of the timestep selection dance
    return std::numeric_limits<Real>::max();

  Real smallest_dt = std::numeric_limits<Real>::max();

  if(_has_an_app)
  {
    MPI_Comm swapped = Moose::swapLibMeshComm(_my_comm);

    for(unsigned int i=0; i<_my_num_apps; i++)
    {
      Transient * ex = _transient_executioners[i];
      Real dt = ex->computeConstrainedDT();

      smallest_dt = std::min(dt, smallest_dt);
    }

    // Swap back
    Moose::swapLibMeshComm(swapped);
  }

  if(_tolerate_failure) // Bow out of the timestep selection dance, we do this down here because we need to call computeConstrainedDT at least once for these executioners...
    return std::numeric_limits<Real>::max();

  Parallel::min(smallest_dt);
  return smallest_dt;
}

<|endoftext|>


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

#include "YAMLFormatter.h"
#include "Parser.h"

#include <sstream>
#include <vector>

YAMLFormatter::YAMLFormatter(std::ostream & out, bool dump_mode)
  :SyntaxFormatterInterface(out, dump_mode),
   first(true)
{
}

void
YAMLFormatter::preamble()
{
  //important: start and end yaml data delimiters used by python
  _out << "**START YAML DATA**\n";
  first = true;
}

void
YAMLFormatter::postscript()
{
  _out << "**END YAML DATA**\n";
}

void
YAMLFormatter::print(const std::string & name, const std::string * prev_name, std::vector<InputParameters *> & param_ptrs)
{
  std::string empty;

  if (!prev_name)
    prev_name = ∅

  std::vector<std::string> elements, prev_elements;
  Parser::tokenize(name, elements);
  std::string spacing = "";
  for (unsigned int i=0; i<elements.size(); ++i)
    spacing += "  ";
  Parser::tokenize(*prev_name, prev_elements);
  std::string prev_spacing = "";
  for (unsigned int i=0; i<prev_elements.size(); ++i)
    prev_spacing += "  ";
/*
  if (prev_name != NULL && (*prev_name != name || ))
  {
    Parser::tokenize(*prev_name, prev_elements);
    std::string prev_spacing = "";
    for (unsigned int i=0; i<prev_elements.size(); ++i)
      prev_spacing += "  ";
    _out << prev_spacing << "  subblocks: \n";
  }
*/
  if (prev_name == NULL || *prev_name != name || *prev_name == "Executioner" || prev_name->find("InitialCondition") != std::string::npos)
  {
    if (first)
      first = false;
    else
      _out << prev_spacing << "  subblocks: \n";
    printCloseAndOpen(name, prev_name);
    // If name is empty - abort or Python will freak
    if (name == "")
      return;
    _out << spacing << "- name: " << name << "\n";
    spacing += "  ";

    std::string class_desc, type_str;
    if (param_ptrs[1] != NULL)
    {
      class_desc = param_ptrs[1]->getClassDescription();
      type_str = param_ptrs[1]->get<std::string>("type");
    }

    //will print "" if there is no type or desc, which translates to None in python
    _out << spacing << "desc: !!str " << class_desc << "\n";
    _out << spacing << "type: " << type_str << "\n";

    _out << spacing << "parameters:\n";
  }
  else
  {
//    Parser::tokenize(*prev_name, prev_elements);
//    std::string prev_spacing = "";
//    for (unsigned int i=0; i<prev_elements.size(); ++i)
//      prev_spacing += "  ";
//    _out << prev_spacing << "  subblocks: \n";

    spacing += "  ";
  }

  for (unsigned int i=0; i<param_ptrs.size() && param_ptrs[i]; ++i)
  {
    for (InputParameters::iterator iter = param_ptrs[i]->begin(); iter != param_ptrs[i]->end(); ++iter)
    {
      std::string name = iter->first;
      // First make sure we want to see this parameter, also block active and type
      if (param_ptrs[i]->isPrivate(iter->first) || name == "active" || name == "type")
        continue;

      // Block params may be required and will have a doc string
      std::string required = param_ptrs[i]->isParamRequired(iter->first) ? "Yes" : "No";

      _out << spacing << "  - name: " << name << "\n";
      _out << spacing << "    required: " << required << "\n";
      _out << spacing << "    default: !!str ";

      //prints the value, which is the default value when dumping the tree
      //because it hasn't been changed
      iter->second->print(_out);

      _out << "\n" << spacing << "    description: |\n      " << spacing
                << param_ptrs[i]->getDocString(iter->first) << "\n";
    }
  }

//  out << spacing << "subblocks: \n";
}

void
YAMLFormatter::printCloseAndOpen(const std::string & name, const std::string * prev_name) const
{
  std::string empty;
  std::vector<std::string> prev_elements, curr_elements;

  if (!prev_name)
    prev_name = ∅

  Parser::tokenize(*prev_name, prev_elements);
  Parser::tokenize(name, curr_elements);

  int num_to_close=0;
  int num_to_open=0;
  int same_elements=0;
  bool first_mismatch = false;
  for (unsigned int i=0; i<curr_elements.size(); ++i)
    if (i >= prev_elements.size())
      ++num_to_open;
    else if (prev_elements[i] != curr_elements[i] || first_mismatch)
    {
      ++num_to_open;
      first_mismatch = true;
    }
    else
      ++same_elements;

  // Executioner syntax is different - we'll hack it here!
  if ((name == "Executioner" && *prev_name == "Executioner") ||
      (name.find("InitialCondition") != std::string::npos && prev_name->find("InitialCondition") != std::string::npos) || name == "Executioner/Adaptivity")
  {
    num_to_open += 1;
    same_elements -= 1;
  }

  num_to_close = prev_elements.size() - same_elements;

  // Open new blocks if necessary
  std::string spacing = "";
  std::string partial_name = "";
  bool ran_once = false;
  for (unsigned int i=0; i<curr_elements.size()-num_to_open; ++i)
  {
    spacing += "  ";
    if (i)
    {

      partial_name += "/";
    }
    partial_name += curr_elements[i];
  }

  for (unsigned int i=curr_elements.size()-num_to_open; i<curr_elements.size()-1 && !curr_elements.empty(); ++i)
  {
    spacing += "  ";
    if (i)
    {

      partial_name += "/";
    }
    partial_name += curr_elements[i];

    ran_once = true;
    _out << spacing << "- name: " << partial_name << "\n";
    _out << spacing << "  desc: !!str\n";
    _out << spacing << "  type:\n";
    _out << spacing << "  parameters:\n";
    _out << spacing << "  subblocks:\n";
  }
}

<commit_msg>Fixes issue by stripping any new lines generated in the default string of YAML output. Fixes #988<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "YAMLFormatter.h"
#include "Parser.h"

#include <sstream>
#include <vector>

YAMLFormatter::YAMLFormatter(std::ostream & out, bool dump_mode)
  :SyntaxFormatterInterface(out, dump_mode),
   first(true)
{
}

void
YAMLFormatter::preamble()
{
  //important: start and end yaml data delimiters used by python
  _out << "**START YAML DATA**\n";
  first = true;
}

void
YAMLFormatter::postscript()
{
  _out << "**END YAML DATA**\n";
}

void
YAMLFormatter::print(const std::string & name, const std::string * prev_name, std::vector<InputParameters *> & param_ptrs)
{
  std::string empty;

  if (!prev_name)
    prev_name = ∅

  std::vector<std::string> elements, prev_elements;
  Parser::tokenize(name, elements);
  std::string spacing = "";
  for (unsigned int i=0; i<elements.size(); ++i)
    spacing += "  ";
  Parser::tokenize(*prev_name, prev_elements);
  std::string prev_spacing = "";
  for (unsigned int i=0; i<prev_elements.size(); ++i)
    prev_spacing += "  ";
/*
  if (prev_name != NULL && (*prev_name != name || ))
  {
    Parser::tokenize(*prev_name, prev_elements);
    std::string prev_spacing = "";
    for (unsigned int i=0; i<prev_elements.size(); ++i)
      prev_spacing += "  ";
    _out << prev_spacing << "  subblocks: \n";
  }
*/
  if (prev_name == NULL || *prev_name != name || *prev_name == "Executioner" || prev_name->find("InitialCondition") != std::string::npos)
  {
    if (first)
      first = false;
    else
      _out << prev_spacing << "  subblocks: \n";
    printCloseAndOpen(name, prev_name);
    // If name is empty - abort or Python will freak
    if (name == "")
      return;
    _out << spacing << "- name: " << name << "\n";
    spacing += "  ";

    std::string class_desc, type_str;
    if (param_ptrs[1] != NULL)
    {
      class_desc = param_ptrs[1]->getClassDescription();
      type_str = param_ptrs[1]->get<std::string>("type");
    }

    //will print "" if there is no type or desc, which translates to None in python
    _out << spacing << "desc: !!str " << class_desc << "\n";
    _out << spacing << "type: " << type_str << "\n";

    _out << spacing << "parameters:\n";
  }
  else
  {
//    Parser::tokenize(*prev_name, prev_elements);
//    std::string prev_spacing = "";
//    for (unsigned int i=0; i<prev_elements.size(); ++i)
//      prev_spacing += "  ";
//    _out << prev_spacing << "  subblocks: \n";

    spacing += "  ";
  }

  for (unsigned int i=0; i<param_ptrs.size() && param_ptrs[i]; ++i)
  {
    for (InputParameters::iterator iter = param_ptrs[i]->begin(); iter != param_ptrs[i]->end(); ++iter)
    {
      std::string name = iter->first;
      // First make sure we want to see this parameter, also block active and type
      if (param_ptrs[i]->isPrivate(iter->first) || name == "active" || name == "type")
        continue;

      // Block params may be required and will have a doc string
      std::string required = param_ptrs[i]->isParamRequired(iter->first) ? "Yes" : "No";

      _out << spacing << "  - name: " << name << "\n";
      _out << spacing << "    required: " << required << "\n";
      _out << spacing << "    default: !!str ";

      //prints the value, which is the default value when dumping the tree
      //because it hasn't been changed

      // remove additional '\n' possibly generated in output (breaks YAML parsing)
      std::ostringstream oss;
      iter->second->print(oss);
      std::string tmp_str = oss.str();
      for(std::string::iterator it=tmp_str.begin(); it!=tmp_str.end(); ++it)
      {
        if ( *it == '\n')
        {
          *it = ' ';
        }
      }
      _out << tmp_str;
      _out << "\n" << spacing << "    description: |\n      " << spacing
                << param_ptrs[i]->getDocString(iter->first) << "\n";
    }
  }

//  out << spacing << "subblocks: \n";
}

void
YAMLFormatter::printCloseAndOpen(const std::string & name, const std::string * prev_name) const
{
  std::string empty;
  std::vector<std::string> prev_elements, curr_elements;

  if (!prev_name)
    prev_name = ∅

  Parser::tokenize(*prev_name, prev_elements);
  Parser::tokenize(name, curr_elements);

  int num_to_close=0;
  int num_to_open=0;
  int same_elements=0;
  bool first_mismatch = false;
  for (unsigned int i=0; i<curr_elements.size(); ++i)
    if (i >= prev_elements.size())
      ++num_to_open;
    else if (prev_elements[i] != curr_elements[i] || first_mismatch)
    {
      ++num_to_open;
      first_mismatch = true;
    }
    else
      ++same_elements;

  // Executioner syntax is different - we'll hack it here!
  if ((name == "Executioner" && *prev_name == "Executioner") ||
      (name.find("InitialCondition") != std::string::npos && prev_name->find("InitialCondition") != std::string::npos) || name == "Executioner/Adaptivity")
  {
    num_to_open += 1;
    same_elements -= 1;
  }

  num_to_close = prev_elements.size() - same_elements;

  // Open new blocks if necessary
  std::string spacing = "";
  std::string partial_name = "";
  bool ran_once = false;
  for (unsigned int i=0; i<curr_elements.size()-num_to_open; ++i)
  {
    spacing += "  ";
    if (i)
    {

      partial_name += "/";
    }
    partial_name += curr_elements[i];
  }

  for (unsigned int i=curr_elements.size()-num_to_open; i<curr_elements.size()-1 && !curr_elements.empty(); ++i)
  {
    spacing += "  ";
    if (i)
    {

      partial_name += "/";
    }
    partial_name += curr_elements[i];

    ran_once = true;
    _out << spacing << "- name: " << partial_name << "\n";
    _out << spacing << "  desc: !!str\n";
    _out << spacing << "  type:\n";
    _out << spacing << "  parameters:\n";
    _out << spacing << "  subblocks:\n";
  }
}

<|endoftext|>