<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2016 INRIA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
/*! \file NewtonEulerFrom1DLocalFrameR.hpp

 */
#ifndef NEWTONEULERIMPACT_H
#define NEWTONEULERIMPACT_H

#include "NewtonEulerR.hpp"
#include "NewtonEulerDS.hpp"

/** NewtonEulerFrom1DLocalFrameR
 *
 * \author O. Bonnefon
 *  \version 3.0.0.
 *  \date Dec, 2010
 *
 * This class is an interface for a relation with impact.  It
 * implements the computation of the jacoboian of h from the points of
 * contacts and the normal.  Use this class consists in overloading
 * the method computeh, by setting the member pc1, pc2, nc and y.  The
 * matrix jachq is used both for the building of the OSNSP (with T)
 * and for the predictor of activation of deactivation of the Interaction.
 *
 */

class NewtonEulerFrom1DLocalFrameR : public NewtonEulerR
{
protected:
  /** serialization hooks
  */
  ACCEPT_SERIALIZATION(NewtonEulerFrom1DLocalFrameR);

  /* Current Contact Points, may be updated within Newton loop based
   * on _relPc1, _relPc2. */
  SP::SiconosVector _Pc1;
  SP::SiconosVector _Pc2;

  /* Contact Points in coordinates relative to attached DS->q.  Set
   * these if _Pc1/_Pc2 are not calculated within the Newton loop. */
  SP::SiconosVector _relPc1;
  SP::SiconosVector _relPc2;

  /* Inward Normal at the contact.
   * \todo The meaning of "Inward" has to be explained carefully.
   */
  SP::SiconosVector _Nc;

  /* _Nc must be calculated relative to q2 */
  SP::SiconosVector _relNc;

  /* Rotation matrix converting the absolute coordinate to the contact frame coordinate.
   * This matrix contains the unit vector(s)of the contact frame in row.
   */
  SP::SimpleMatrix _RotationAbsToContactFrame;

  /* Matrix converting */
  SP::SimpleMatrix _rotationMatrixAbsToBody;

  /* Cross product matrices that correspond the lever arm from
   * contact point to center of mass*/
  SP::SimpleMatrix _NPG1;
  SP::SimpleMatrix _NPG2;

  /*buffer matrices*/
  SP::SimpleMatrix _AUX1;
  SP::SimpleMatrix _AUX2;
private:
  void NIcomputeJachqTFromContacts(SP::SiconosVector q1);
  void NIcomputeJachqTFromContacts(SP::SiconosVector q1, SP::SiconosVector q2);
public:

  /** V.A. boolean _isOnCOntact ?? Why is it public members ?
  *  seems parametrize the projection algorithm
  *  the projection is done on the surface \f$y=0\f$ or on \f$y \geq 0\f$
  */
  bool _isOnContact;

  /** constructorx
  */
  NewtonEulerFrom1DLocalFrameR():
    NewtonEulerR(), _Pc1(new SiconosVector(3)), _Pc2(new SiconosVector(3)),
    _relPc1(new SiconosVector(3)), _relPc2(new SiconosVector(3)),
    _Nc(new SiconosVector(3)), _relNc(new SiconosVector(3))
  {
    /*_ds1=NULL;_ds2=NULL;*/
  }

  /** destructor
  */
  virtual ~NewtonEulerFrom1DLocalFrameR() {};

  virtual void computeJachq(double time, Interaction& inter, SP::BlockVector q0);

  virtual void initializeWorkVectorsAndMatrices(Interaction& inter, VectorOfBlockVectors& DSlink, VectorOfVectors& workV, VectorOfSMatrices& workM);

  virtual void initialize(Interaction& inter);

  /* Default implementation consists in multiplying jachq and T (see NewtonEulerR::computeJachqT)
   * but here we compute the operator from the the contact point locations
   * and the local frame at contact
   *  \param inter interaction that owns the relation
   *  \param q0  the block vector to the dynamical system position
   */
  virtual void computeJachqT(Interaction& inter, SP::BlockVector q0);

  /* Default implementation of computeh updates contact points and
   * distance for q if different than qold. */
  virtual void computeh(double time, BlockVector& q0, SiconosVector &y);

  /** Return the distance between pc1 and pc, with sign according to normal */
  double distance() const;

  inline SP::SiconosVector pc1() const
  {
    return _Pc1;
  }
  inline SP::SiconosVector pc2() const
  {
    return _Pc2;
  }
  inline SP::SiconosVector nc() const
  {
    return _Nc;
  }

  /** set the coordinates of first contact point
  * \param npc new coordinates
  */
  void setpc1(SP::SiconosVector npc)
  {
    _Pc1 = npc;
  };

  /** set the coordinates of second contact point
  * \param npc new coordinates
  */
  void setpc2(SP::SiconosVector npc)
  {
    _Pc2 = npc;
  };

  /** set the coordinates of inside normal vector at the contact point
  * \param nnc new coordinates
  */
  void setnc(SP::SiconosVector nnc)
  {
    _Nc = nnc;
  };

  // visitors hook
  ACCEPT_STD_VISITORS();

};
#endif // NEWTONEULERRIMPACT_H
<commit_msg>[kernel] getters/setters for relative contact points and contact normal<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2016 INRIA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
/*! \file NewtonEulerFrom1DLocalFrameR.hpp

 */
#ifndef NEWTONEULERIMPACT_H
#define NEWTONEULERIMPACT_H

#include "NewtonEulerR.hpp"
#include "NewtonEulerDS.hpp"

/** NewtonEulerFrom1DLocalFrameR
 *
 * \author O. Bonnefon
 *  \version 3.0.0.
 *  \date Dec, 2010
 *
 * This class is an interface for a relation with impact.  It
 * implements the computation of the jacoboian of h from the points of
 * contacts and the normal.  Use this class consists in overloading
 * the method computeh, by setting the member pc1, pc2, nc and y.  The
 * matrix jachq is used both for the building of the OSNSP (with T)
 * and for the predictor of activation of deactivation of the Interaction.
 *
 */

class NewtonEulerFrom1DLocalFrameR : public NewtonEulerR
{
protected:
  /** serialization hooks
  */
  ACCEPT_SERIALIZATION(NewtonEulerFrom1DLocalFrameR);

  /* Current Contact Points, may be updated within Newton loop based
   * on _relPc1, _relPc2. */
  SP::SiconosVector _Pc1;
  SP::SiconosVector _Pc2;

  /* Contact Points in coordinates relative to attached DS->q.  Set
   * these if _Pc1/_Pc2 are not calculated within the Newton loop. */
  SP::SiconosVector _relPc1;
  SP::SiconosVector _relPc2;

  /* Inward Normal at the contact.
   * \todo The meaning of "Inward" has to be explained carefully.
   */
  SP::SiconosVector _Nc;

  /* _Nc must be calculated relative to q2 */
  SP::SiconosVector _relNc;

  /* Rotation matrix converting the absolute coordinate to the contact frame coordinate.
   * This matrix contains the unit vector(s)of the contact frame in row.
   */
  SP::SimpleMatrix _RotationAbsToContactFrame;

  /* Matrix converting */
  SP::SimpleMatrix _rotationMatrixAbsToBody;

  /* Cross product matrices that correspond the lever arm from
   * contact point to center of mass*/
  SP::SimpleMatrix _NPG1;
  SP::SimpleMatrix _NPG2;

  /*buffer matrices*/
  SP::SimpleMatrix _AUX1;
  SP::SimpleMatrix _AUX2;
private:
  void NIcomputeJachqTFromContacts(SP::SiconosVector q1);
  void NIcomputeJachqTFromContacts(SP::SiconosVector q1, SP::SiconosVector q2);
public:

  /** V.A. boolean _isOnCOntact ?? Why is it public members ?
  *  seems parametrize the projection algorithm
  *  the projection is done on the surface \f$y=0\f$ or on \f$y \geq 0\f$
  */
  bool _isOnContact;

  /** constructorx
  */
  NewtonEulerFrom1DLocalFrameR():
    NewtonEulerR(), _Pc1(new SiconosVector(3)), _Pc2(new SiconosVector(3)),
    _relPc1(new SiconosVector(3)), _relPc2(new SiconosVector(3)),
    _Nc(new SiconosVector(3)), _relNc(new SiconosVector(3))
  {
    /*_ds1=NULL;_ds2=NULL;*/
  }

  /** destructor
  */
  virtual ~NewtonEulerFrom1DLocalFrameR() {};

  virtual void computeJachq(double time, Interaction& inter, SP::BlockVector q0);

  virtual void initializeWorkVectorsAndMatrices(Interaction& inter, VectorOfBlockVectors& DSlink, VectorOfVectors& workV, VectorOfSMatrices& workM);

  virtual void initialize(Interaction& inter);

  /* Default implementation consists in multiplying jachq and T (see NewtonEulerR::computeJachqT)
   * but here we compute the operator from the the contact point locations
   * and the local frame at contact
   *  \param inter interaction that owns the relation
   *  \param q0  the block vector to the dynamical system position
   */
  virtual void computeJachqT(Interaction& inter, SP::BlockVector q0);

  /* Default implementation of computeh updates contact points and
   * distance for q if different than qold. */
  virtual void computeh(double time, BlockVector& q0, SiconosVector &y);

  /** Return the distance between pc1 and pc, with sign according to normal */
  double distance() const;

  inline SP::SiconosVector pc1() const
  {
    return _Pc1;
  }
  inline SP::SiconosVector pc2() const
  {
    return _Pc2;
  }
  inline SP::SiconosVector nc() const
  {
    return _Nc;
  }

  inline SP::SiconosVector relPc1() const
  {
    return _relPc1;
  }
  inline SP::SiconosVector relPc2() const
  {
    return _relPc2;
  }
  inline SP::SiconosVector relNc() const
  {
    return _relNc;
  }

  /** set the coordinates of first contact point
  * \param npc new coordinates
  */
  void setpc1(SP::SiconosVector npc)
  {
    _Pc1 = npc;
  };

  /** set the coordinates of second contact point
  * \param npc new coordinates
  */
  void setpc2(SP::SiconosVector npc)
  {
    _Pc2 = npc;
  };

  /** set the coordinates of inside normal vector at the contact point
  * \param nnc new coordinates
  */
  void setnc(SP::SiconosVector nnc)
  {
    _Nc = nnc;
  };

  /** Set the coordinates of first contact point in ds1 frame.
   * It will be used to compute _Pc1 during computeh().
  * \param npc new coordinates
  */
  void setRelPc1(SP::SiconosVector npc)
  {
    _relPc1 = npc;
  };

  /** Set the coordinates of second contact point in ds2 frame
   * It will be used to compute _Pc2 during computeh().
  * \param npc new coordinates
  */
  void setRelPc2(SP::SiconosVector npc)
  {
    _relPc2 = npc;
  };

  /** Set the coordinates of inside normal vector at the contact point in ds2 frame.
   * It will be used to compute _Nc during computeh().
  * \param nnc new coordinates
  */
  void setRelNc(SP::SiconosVector nnc)
  {
    _relNc = nnc;
  };

  // visitors hook
  ACCEPT_STD_VISITORS();

};
#endif // NEWTONEULERRIMPACT_H
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: UITools.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: fs $ $Date: 2001-04-03 14:15:03 $
 *
 *  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 DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMPLETEDCONNECTION_HPP_
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XKeysSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_
#include <toolkit/awt/vclxwindow.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif

// .........................................................................
namespace dbaui
{
// .........................................................................
using namespace ::dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::ui;

// -----------------------------------------------------------------------------
void composeTableName(  const Reference< XDatabaseMetaData >& _rxMetaData,
                        const Reference< XPropertySet >& _rxTable,
                        ::rtl::OUString& _rComposedName,
                        sal_Bool _bQuote)
{
    OSL_ENSURE(_rxTable.is(),"Table can not be null!");
    if(_rxTable.is())
    {
        Reference< XPropertySetInfo > xInfo = _rxTable->getPropertySetInfo();
        if(xInfo->hasPropertyByName(PROPERTY_CATALOGNAME) && xInfo->hasPropertyByName(PROPERTY_SCHEMANAME) && xInfo->hasPropertyByName(PROPERTY_NAME))
        {
            ::rtl::OUString aCatalog,aSchema,aTable;
            _rxTable->getPropertyValue(PROPERTY_CATALOGNAME)>>= aCatalog;
            _rxTable->getPropertyValue(PROPERTY_SCHEMANAME) >>= aSchema;
            _rxTable->getPropertyValue(PROPERTY_NAME)       >>= aTable;

            ::dbtools::composeTableName(_rxMetaData,aCatalog,aSchema,aTable,_rComposedName,_bQuote);
        }
    }
}
// -----------------------------------------------------------------------------

SQLExceptionInfo createConnection(  const ::rtl::OUString& _rsDataSourceName,
                                     const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xDatabaseContext,
                                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rMF,
                                    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener>& _rEvtLst,
                                    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rOUTConnection )
{
    Any aValue;
    try
    {
        aValue = _xDatabaseContext->getByName(_rsDataSourceName);
    }
    catch(Exception&)
    {
    }
    SQLExceptionInfo aInfo;
    Reference<XPropertySet> xProp;
    aValue >>= xProp;
    if (!xProp.is())
    {
        OSL_ENSURE(0,"createConnection: coult not retrieve the data source!");
        return aInfo;
    }

    ::rtl::OUString sPwd, sUser;
    sal_Bool bPwdReq = sal_False;
    try
    {
        xProp->getPropertyValue(PROPERTY_PASSWORD) >>= sPwd;
        bPwdReq = ::cppu::any2bool(xProp->getPropertyValue(PROPERTY_ISPASSWORDREQUIRED));
        xProp->getPropertyValue(PROPERTY_USER) >>= sUser;
    }
    catch(Exception&)
    {
        OSL_ENSURE(0,"createConnection: error while retrieving data source properties!");
    }

    try
    {
        if(bPwdReq && !sPwd.getLength())
        {   // password required, but empty -> connect using an interaction handler
            Reference<XCompletedConnection> xConnectionCompletion(xProp, UNO_QUERY);
            if (!xConnectionCompletion.is())
            {
                OSL_ENSURE(0,"createConnection: missing an interface ... need an error message here!");
            }
            else
            {   // instantiate the default SDB interaction handler
                Reference< XInteractionHandler > xHandler(_rMF->createInstance(SERVICE_SDB_INTERACTION_HANDLER), UNO_QUERY);
                if (!xHandler.is())
                {
                    OSL_ENSURE(sal_False, "createConnection: could not instantiate an interaction handler!");
                    // ShowServiceNotAvailableError(NULL, String(SERVICE_SDB_INTERACTION_HANDLER), sal_True);
                        // TODO: a real parent!
                }
                else
                    _rOUTConnection = xConnectionCompletion->connectWithCompletion(xHandler);
            }
        }
        else
        {
            Reference<XDataSource> xDataSource(xProp,UNO_QUERY);
            _rOUTConnection = xDataSource->getConnection(sUser, sPwd);
        }
        // be notified when connection is in disposing
        Reference< XComponent >  xComponent(_rOUTConnection, UNO_QUERY);
        if (xComponent.is() && _rEvtLst.is())
            xComponent->addEventListener(_rEvtLst);
    }
    catch(SQLContext& e) { aInfo = SQLExceptionInfo(e); }
    catch(SQLWarning& e) { aInfo = SQLExceptionInfo(e); }
    catch(SQLException& e) { aInfo = SQLExceptionInfo(e); }
    catch(Exception&) { OSL_ENSURE(0,"SbaTableQueryBrowser::OnExpandEntry: could not connect - unknown exception!"); }

    //  showError(aInfo);

    return aInfo;
}
// -----------------------------------------------------------------------------
void showError(const SQLExceptionInfo& _rInfo,Window* _pParent,const Reference< XMultiServiceFactory >& _xFactory)
{
    ::dbtools::showError(_rInfo,VCLUnoHelper::GetInterface(_pParent),_xFactory);
}
// -----------------------------------------------------------------------------
::std::vector< Reference<XNameAccess> > getKeyColumns(const Reference<XPropertySet >& _rxTable,
                                                      sal_Int32 _nKeyType)
{
    // use keys and indexes for excat postioning
    // first the keys
    Reference<XKeysSupplier> xKeySup(_rxTable,UNO_QUERY);
    Reference<XIndexAccess> xKeys;
    if(xKeySup.is())
        xKeys = xKeySup->getKeys();

    ::std::vector< Reference<XNameAccess> > vRet;

    if(xKeys.is())
    {
        Reference<XPropertySet> xProp;
        for(sal_Int32 i=0;i< xKeys->getCount();++i)
        {
            xKeys->getByIndex(i) >>= xProp;
            sal_Int32 nKeyType = 0;
            xProp->getPropertyValue(PROPERTY_TYPE) >>= nKeyType;
            if(_nKeyType == nKeyType)
            {
                Reference<XColumnsSupplier> xKeyColsSup(xProp,UNO_QUERY);
                OSL_ENSURE(xKeyColsSup.is(),"Columnsupplier is null!");
                vRet.push_back(xKeyColsSup->getColumns());
            }
        }
    }

    return vRet;
}
// -----------------------------------------------------------------------------

// .........................................................................
}
// .........................................................................
<commit_msg>assert when parent window is null by showError<commit_after>/*************************************************************************
 *
 *  $RCSfile: UITools.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: oj $ $Date: 2001-04-24 08:41:46 $
 *
 *  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 DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMPLETEDCONNECTION_HPP_
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XKEYSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XKeysSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCOLUMNSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_
#include <toolkit/awt/vclxwindow.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif

// .........................................................................
namespace dbaui
{
// .........................................................................
using namespace ::dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::ui;

// -----------------------------------------------------------------------------
void composeTableName(  const Reference< XDatabaseMetaData >& _rxMetaData,
                        const Reference< XPropertySet >& _rxTable,
                        ::rtl::OUString& _rComposedName,
                        sal_Bool _bQuote)
{
    OSL_ENSURE(_rxTable.is(),"Table can not be null!");
    if(_rxTable.is())
    {
        Reference< XPropertySetInfo > xInfo = _rxTable->getPropertySetInfo();
        if(xInfo->hasPropertyByName(PROPERTY_CATALOGNAME) && xInfo->hasPropertyByName(PROPERTY_SCHEMANAME) && xInfo->hasPropertyByName(PROPERTY_NAME))
        {
            ::rtl::OUString aCatalog,aSchema,aTable;
            _rxTable->getPropertyValue(PROPERTY_CATALOGNAME)>>= aCatalog;
            _rxTable->getPropertyValue(PROPERTY_SCHEMANAME) >>= aSchema;
            _rxTable->getPropertyValue(PROPERTY_NAME)       >>= aTable;

            ::dbtools::composeTableName(_rxMetaData,aCatalog,aSchema,aTable,_rComposedName,_bQuote);
        }
    }
}
// -----------------------------------------------------------------------------

SQLExceptionInfo createConnection(  const ::rtl::OUString& _rsDataSourceName,
                                     const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xDatabaseContext,
                                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rMF,
                                    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener>& _rEvtLst,
                                    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _rOUTConnection )
{
    Any aValue;
    try
    {
        aValue = _xDatabaseContext->getByName(_rsDataSourceName);
    }
    catch(Exception&)
    {
    }
    SQLExceptionInfo aInfo;
    Reference<XPropertySet> xProp;
    aValue >>= xProp;
    if (!xProp.is())
    {
        OSL_ENSURE(0,"createConnection: coult not retrieve the data source!");
        return aInfo;
    }

    ::rtl::OUString sPwd, sUser;
    sal_Bool bPwdReq = sal_False;
    try
    {
        xProp->getPropertyValue(PROPERTY_PASSWORD) >>= sPwd;
        bPwdReq = ::cppu::any2bool(xProp->getPropertyValue(PROPERTY_ISPASSWORDREQUIRED));
        xProp->getPropertyValue(PROPERTY_USER) >>= sUser;
    }
    catch(Exception&)
    {
        OSL_ENSURE(0,"createConnection: error while retrieving data source properties!");
    }

    try
    {
        if(bPwdReq && !sPwd.getLength())
        {   // password required, but empty -> connect using an interaction handler
            Reference<XCompletedConnection> xConnectionCompletion(xProp, UNO_QUERY);
            if (!xConnectionCompletion.is())
            {
                OSL_ENSURE(0,"createConnection: missing an interface ... need an error message here!");
            }
            else
            {   // instantiate the default SDB interaction handler
                Reference< XInteractionHandler > xHandler(_rMF->createInstance(SERVICE_SDB_INTERACTION_HANDLER), UNO_QUERY);
                if (!xHandler.is())
                {
                    OSL_ENSURE(sal_False, "createConnection: could not instantiate an interaction handler!");
                    // ShowServiceNotAvailableError(NULL, String(SERVICE_SDB_INTERACTION_HANDLER), sal_True);
                        // TODO: a real parent!
                }
                else
                    _rOUTConnection = xConnectionCompletion->connectWithCompletion(xHandler);
            }
        }
        else
        {
            Reference<XDataSource> xDataSource(xProp,UNO_QUERY);
            _rOUTConnection = xDataSource->getConnection(sUser, sPwd);
        }
        // be notified when connection is in disposing
        Reference< XComponent >  xComponent(_rOUTConnection, UNO_QUERY);
        if (xComponent.is() && _rEvtLst.is())
            xComponent->addEventListener(_rEvtLst);
    }
    catch(SQLContext& e) { aInfo = SQLExceptionInfo(e); }
    catch(SQLWarning& e) { aInfo = SQLExceptionInfo(e); }
    catch(SQLException& e) { aInfo = SQLExceptionInfo(e); }
    catch(Exception&) { OSL_ENSURE(0,"SbaTableQueryBrowser::OnExpandEntry: could not connect - unknown exception!"); }

    //  showError(aInfo);

    return aInfo;
}
// -----------------------------------------------------------------------------
void showError(const SQLExceptionInfo& _rInfo,Window* _pParent,const Reference< XMultiServiceFactory >& _xFactory)
{
    OSL_ENSURE(_pParent,"showError: Parent window must be NOT NULL!");
    ::dbtools::showError(_rInfo,VCLUnoHelper::GetInterface(_pParent),_xFactory);
}
// -----------------------------------------------------------------------------
::std::vector< Reference<XNameAccess> > getKeyColumns(const Reference<XPropertySet >& _rxTable,
                                                      sal_Int32 _nKeyType)
{
    // use keys and indexes for excat postioning
    // first the keys
    Reference<XKeysSupplier> xKeySup(_rxTable,UNO_QUERY);
    Reference<XIndexAccess> xKeys;
    if(xKeySup.is())
        xKeys = xKeySup->getKeys();

    ::std::vector< Reference<XNameAccess> > vRet;

    if(xKeys.is())
    {
        Reference<XPropertySet> xProp;
        for(sal_Int32 i=0;i< xKeys->getCount();++i)
        {
            xKeys->getByIndex(i) >>= xProp;
            sal_Int32 nKeyType = 0;
            xProp->getPropertyValue(PROPERTY_TYPE) >>= nKeyType;
            if(_nKeyType == nKeyType)
            {
                Reference<XColumnsSupplier> xKeyColsSup(xProp,UNO_QUERY);
                OSL_ENSURE(xKeyColsSup.is(),"Columnsupplier is null!");
                vRet.push_back(xKeyColsSup->getColumns());
            }
        }
    }

    return vRet;
}
// -----------------------------------------------------------------------------

// .........................................................................
}
// .........................................................................
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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.
**
****************************************************************************/

#include "switchpage.h"
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MApplicationPage>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MMessageBox>
#include <QGraphicsLinearLayout>

SwitchPage::SwitchPage() :
        TemplatePage(TemplatePage::Buttons),
    switch1(0), switch2(0),
    switch3(0), switch4(0),
    switch5(0),
    label1(0), label2(0),
    label3(0), label4(0),
    label5(0)
{
}

SwitchPage::~SwitchPage()
{
}

QString SwitchPage::timedemoTitle()
{
    return "Switch";
}

void SwitchPage::createContent()
{
    TemplatePage::createContent();

    //landscapePolicy->insertStretch(1);

    switch1 = new MButton();
    switch1->setObjectName("switch1");
    switch1->setStyleName("CommonRightSwitch");
    switch1->setViewType(MButton::switchType);
    switch1->setCheckable(true);
    switch1->setChecked(true);
    label1 = new MLabel();
    label1->setObjectName("label1");
    label1->setStyleName("CommonBodyText");
    label1->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    QGraphicsLinearLayout *l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label1);
    l->addItem(switch1);
    l->setAlignment(switch1, Qt::AlignCenter);
    //l->setAlignment(label1, Qt::AlignRight);
    containerPolicy->addItem(l);
    connect(switch1, SIGNAL(toggled(bool)), this, SLOT(switchToggled(bool)));

    switch2 = new MButton();
    switch2->setObjectName("switch2");
    switch2->setStyleName("CommonRightSwitch");
    switch2->setViewType(MButton::switchType);
    switch2->setCheckable(true);
    label2 = new MLabel();
    label2->setObjectName("label2");
    label2->setStyleName("CommonBodyText");
    label2->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label2);
    l->addItem(switch2);
    l->setAlignment(switch2, Qt::AlignCenter);
    //l->setAlignment(label2, Qt::AlignRight);
    containerPolicy->addItem(l);

    switch3 = new MButton();
    switch3->setObjectName("switch3");
    switch3->setStyleName("CommonRightSwitch");
    switch3->setViewType(MButton::switchType);
    switch3->setCheckable(true);
    label3 = new MLabel();
    label3->setObjectName("label3");
    label3->setStyleName("CommonBodyText");
    label3->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label3);
    l->addItem(switch3);
    l->setAlignment(switch3, Qt::AlignCenter);
    //l->setAlignment(label3, Qt::AlignRight);
    containerPolicy->addItem(l);

    switch4 = new MButton();
    switch4->setObjectName("switch4");
    switch4->setStyleName("CommonRightSwitch");
    switch4->setViewType(MButton::switchType);
    switch4->setCheckable(true);
    label4 = new MLabel();
    label4->setObjectName("label4");
    label4->setStyleName("CommonBodyText");
    label4->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label4);
    l->addItem(switch4);
    l->setAlignment(switch4, Qt::AlignCenter);
    //l->setAlignment(label4, Qt::AlignRight);
    containerPolicy->addItem(l);

    switch5 = new MButton();
    switch5->setObjectName("switch5");
    switch5->setStyleName("CommonRightSwitch");
    switch5->setViewType(MButton::switchType);
    switch5->setCheckable(true);
    switch5->setChecked(true);
    label5 = new MLabel();
    label5->setObjectName("label5");
    label5->setStyleName("CommonBodyText");
    label5->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label5);
    l->addItem(switch5);
    l->setAlignment(switch5, Qt::AlignCenter);
    //l->setAlignment(label5, Qt::AlignRight);
    containerPolicy->addItem(l);

    retranslateUi();
}

void SwitchPage::retranslateUi()
{
    //% "Switch"
    setTitle(qtTrId("xx_switch_page_title"));
    if (!isContentCreated())
        return;

    //% "A Switch button differs from both a push button and an "
    //% "icon button visually. It looks like a switch, "
    //% "communicating that pressing this button will not go to "
    //% "another view or will not perform any other actions except "
    //% "to toggle the state of the button.\n\n"
    //% "Switches are used to indicate e.g. settings values"
    infoLabel->setText("" + qtTrId("xx_switch_page_info_label").replace('\n', "
"));

    //% "Headlights"
    label1->setText(qtTrId("xx_switch_page_switch1"));
    //% "Autopilot"
    label2->setText(qtTrId("xx_switch_page_switch2"));
    //% "Warp Drive"
    label3->setText(qtTrId("xx_switch_page_switch3"));
    //% "Reactor Shields"
    label4->setText(qtTrId("xx_switch_page_switch4"));
    //% "Infinite Improbability Drive"
    label5->setText(qtTrId("xx_switch_page_switch5"));
}

void SwitchPage::switchToggled(bool toggle)
{
    MMessageBox *msgBox = new MMessageBox();
    msgBox->setObjectName("msgBox");

    if (toggle)
        msgBox->setText("The feature was enabled");
    else
        msgBox->setText("The feature was disabled");

    msgBox->appear(MDialog::DestroyWhenDone);
}

<commit_msg>Changes: Activate eliding on WG switch page. RevBy: Adrian Yanes<commit_after>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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.
**
****************************************************************************/

#include "switchpage.h"
#include <MLabel>
#include <MLayout>
#include <MLocale>
#include <MApplicationPage>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MMessageBox>
#include <QGraphicsLinearLayout>

SwitchPage::SwitchPage() :
        TemplatePage(TemplatePage::Buttons),
    switch1(0), switch2(0),
    switch3(0), switch4(0),
    switch5(0),
    label1(0), label2(0),
    label3(0), label4(0),
    label5(0)
{
}

SwitchPage::~SwitchPage()
{
}

QString SwitchPage::timedemoTitle()
{
    return "Switch";
}

void SwitchPage::createContent()
{
    TemplatePage::createContent();

    //landscapePolicy->insertStretch(1);

    switch1 = new MButton();
    switch1->setObjectName("switch1");
    switch1->setStyleName("CommonRightSwitch");
    switch1->setViewType(MButton::switchType);
    switch1->setCheckable(true);
    switch1->setChecked(true);
    label1 = new MLabel();
    label1->setTextElide(true);
    label1->setObjectName("label1");
    label1->setStyleName("CommonBodyText");
    label1->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    QGraphicsLinearLayout *l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label1);
    l->addItem(switch1);
    l->setAlignment(switch1, Qt::AlignCenter);
    //l->setAlignment(label1, Qt::AlignRight);
    containerPolicy->addItem(l);
    connect(switch1, SIGNAL(toggled(bool)), this, SLOT(switchToggled(bool)));

    switch2 = new MButton();
    switch2->setObjectName("switch2");
    switch2->setStyleName("CommonRightSwitch");
    switch2->setViewType(MButton::switchType);
    switch2->setCheckable(true);
    label2 = new MLabel();
    label2->setTextElide(true);
    label2->setObjectName("label2");
    label2->setStyleName("CommonBodyText");
    label2->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label2);
    l->addItem(switch2);
    l->setAlignment(switch2, Qt::AlignCenter);
    //l->setAlignment(label2, Qt::AlignRight);
    containerPolicy->addItem(l);

    switch3 = new MButton();
    switch3->setObjectName("switch3");
    switch3->setStyleName("CommonRightSwitch");
    switch3->setViewType(MButton::switchType);
    switch3->setCheckable(true);
    label3 = new MLabel();
    label3->setTextElide(true);
    label3->setObjectName("label3");
    label3->setStyleName("CommonBodyText");
    label3->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label3);
    l->addItem(switch3);
    l->setAlignment(switch3, Qt::AlignCenter);
    //l->setAlignment(label3, Qt::AlignRight);
    containerPolicy->addItem(l);

    switch4 = new MButton();
    switch4->setObjectName("switch4");
    switch4->setStyleName("CommonRightSwitch");
    switch4->setViewType(MButton::switchType);
    switch4->setCheckable(true);
    label4 = new MLabel();
    label4->setTextElide(true);
    label4->setObjectName("label4");
    label4->setStyleName("CommonBodyText");
    label4->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label4);
    l->addItem(switch4);
    l->setAlignment(switch4, Qt::AlignCenter);
    //l->setAlignment(label4, Qt::AlignRight);
    containerPolicy->addItem(l);

    switch5 = new MButton();
    switch5->setObjectName("switch5");
    switch5->setStyleName("CommonRightSwitch");
    switch5->setViewType(MButton::switchType);
    switch5->setCheckable(true);
    switch5->setChecked(true);
    label5 = new MLabel();
    label5->setTextElide(true);
    label5->setObjectName("label5");
    label5->setStyleName("CommonBodyText");
    label5->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    l = new QGraphicsLinearLayout(Qt::Horizontal);
    l->addItem(label5);
    l->addItem(switch5);
    l->setAlignment(switch5, Qt::AlignCenter);
    //l->setAlignment(label5, Qt::AlignRight);
    containerPolicy->addItem(l);

    retranslateUi();
}

void SwitchPage::retranslateUi()
{
    //% "Switch"
    setTitle(qtTrId("xx_switch_page_title"));
    if (!isContentCreated())
        return;

    //% "A Switch button differs from both a push button and an "
    //% "icon button visually. It looks like a switch, "
    //% "communicating that pressing this button will not go to "
    //% "another view or will not perform any other actions except "
    //% "to toggle the state of the button.\n\n"
    //% "Switches are used to indicate e.g. settings values"
    infoLabel->setText("" + qtTrId("xx_switch_page_info_label").replace('\n', "
"));

    //% "Headlights"
    label1->setText(qtTrId("xx_switch_page_switch1"));
    //% "Autopilot"
    label2->setText(qtTrId("xx_switch_page_switch2"));
    //% "Warp Drive"
    label3->setText(qtTrId("xx_switch_page_switch3"));
    //% "Reactor Shields"
    label4->setText(qtTrId("xx_switch_page_switch4"));
    //% "Infinite Improbability Drive"
    label5->setText(qtTrId("xx_switch_page_switch5"));
}

void SwitchPage::switchToggled(bool toggle)
{
    MMessageBox *msgBox = new MMessageBox();
    msgBox->setObjectName("msgBox");

    if (toggle)
        msgBox->setText("The feature was enabled");
    else
        msgBox->setText("The feature was disabled");

    msgBox->appear(MDialog::DestroyWhenDone);
}

<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2014 Luke Parry <l.parry@warwick.ac.uk>                 *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <QMessageBox>
# include <QTextStream>
# ifdef FC_OS_WIN32
#  include <windows.h>
# endif
#endif

/// Here the FreeCAD includes sorted by Base,App,Gui......
#include <Base/Console.h>
#include <Base/Parameter.h>
#include <Base/Exception.h>
#include <Base/Sequencer.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>

#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/MainWindow.h>
#include <Gui/ViewProvider.h>

#include <Mod/TechDraw/App/DrawTemplate.h>
#include <Mod/TechDraw/App/DrawSVGTemplate.h>
#include <Mod/TechDraw/App/DrawPage.h>

#include "QGITemplate.h"
#include "QGISVGTemplate.h"
#include "QGVPage.h"
#include "MDIViewPage.h"
#include "TemplateTextField.h"
#include "ViewProviderPage.h"
#include "ViewProviderTemplate.h"

using namespace TechDrawGui;

PROPERTY_SOURCE(TechDrawGui::ViewProviderTemplate, Gui::ViewProviderDocumentObject)

//**************************************************************************
// Construction/Destruction

ViewProviderTemplate::ViewProviderTemplate()
{
    sPixmap = "TechDraw_Tree_PageTemplate";

    DisplayMode.setStatus(App::Property::Hidden,true);
}

ViewProviderTemplate::~ViewProviderTemplate()
{
}

void ViewProviderTemplate::attach(App::DocumentObject *pcFeat)
{
    // call parent attach method
    ViewProviderDocumentObject::attach(pcFeat);
}

void ViewProviderTemplate::setDisplayMode(const char* ModeName)
{
    ViewProviderDocumentObject::setDisplayMode(ModeName);
}

std::vector<std::string> ViewProviderTemplate::getDisplayModes(void) const
{
    // get the modes of the father
    std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes();

    return StrList;
}

void ViewProviderTemplate::updateData(const App::Property* prop)
{
    if (getTemplate()->isDerivedFrom(TechDraw::DrawSVGTemplate::getClassTypeId())) {
        auto t = static_cast<TechDraw::DrawSVGTemplate*>(getTemplate());
        if (prop == &(t->Template)) {
            MDIViewPage* mdi = getMDIViewPage();
            if (mdi != nullptr) {
                mdi->attachTemplate(t);
                mdi->viewAll();
            }
       }
    }
    Gui::ViewProviderDocumentObject::updateData(prop);
}

void ViewProviderTemplate::onChanged(const App::Property *prop)
{
    App::DocumentObject* obj = getObject();
    if (!obj || obj->isRestoring()) {
        Gui::ViewProviderDocumentObject::onChanged(prop);
        return;
    }

    if (prop == &Visibility) {
        if (Visibility.getValue()) {
            show();
        } else {
            hide();
        }
    }

    Gui::ViewProviderDocumentObject::onChanged(prop);
}

void ViewProviderTemplate::show(void)
{
    QGITemplate* qTemplate = getQTemplate();
    if (qTemplate != nullptr) {
        qTemplate->show();
    }

    ViewProviderDocumentObject::show();
}

void ViewProviderTemplate::hide(void)
{
    QGITemplate* qTemplate = getQTemplate();
    if (qTemplate != nullptr) {
        qTemplate->hide();
    }

    ViewProviderDocumentObject::hide();
}

bool ViewProviderTemplate::isShow(void) const
{
    return Visibility.getValue();
}

QGITemplate* ViewProviderTemplate::getQTemplate(void)
{
    QGITemplate *result = nullptr;
    TechDraw::DrawTemplate* dt = getTemplate();
    if (dt) {
        MDIViewPage* mdi = getMDIViewPage();
        if (mdi != nullptr) {
            result = mdi->getQGVPage()->getTemplate();
        }
    }
    return result;
}

void ViewProviderTemplate::setMarkers(bool state)
{
//    Base::Console().Message("VPT::setMarkers(%d)\n",state);
    QGITemplate* qTemplate = getQTemplate();
    QGISVGTemplate* qSvgTemplate = dynamic_cast<QGISVGTemplate*> (qTemplate);
    if (qSvgTemplate != nullptr) {
        std::vector<TemplateTextField *> textFields = qSvgTemplate->getTextFields();
        for (auto& t:textFields) {
            if (state) {
                t->show();
            } else {
                t->hide();
            }
        }
        qSvgTemplate->updateView(true);
    }
}

bool ViewProviderTemplate::onDelete(const std::vector<std::string> &)
{
    // deleting the template will break the page view, thus warn the user

    // get the page
    auto page = getTemplate()->getParentPage();

    // generate dialog
    QString bodyMessage;
    QTextStream bodyMessageStream(&bodyMessage);
    bodyMessageStream << qApp->translate("Std_Delete",
        "The following referencing object might break:");
    bodyMessageStream << "\n\n" << QString::fromUtf8(page->Label.getValue());
    bodyMessageStream << "\n\n" << QObject::tr("Are you sure you want to continue?");

    // show and evaluate dialog
    int DialogResult = QMessageBox::warning(Gui::getMainWindow(),
        qApp->translate("Std_Delete", "Object dependencies"), bodyMessage,
        QMessageBox::Yes, QMessageBox::No);
    if (DialogResult == QMessageBox::Yes)
        return true;
    else
        return false;
}

MDIViewPage* ViewProviderTemplate::getMDIViewPage(void) const
{
    MDIViewPage* myMdi = nullptr;
    auto t = getTemplate();
    auto page = t->getParentPage();
    Gui::ViewProvider* vp = Gui::Application::Instance->getDocument(t->getDocument())->getViewProvider(page);
    TechDrawGui::ViewProviderPage* dvp = dynamic_cast<TechDrawGui::ViewProviderPage*>(vp);
    if (dvp) {
        myMdi = dvp->getMDIViewPage();
    }
    return myMdi;
}

Gui::MDIView *ViewProviderTemplate::getMDIView() const
{
    return getMDIViewPage();
}

TechDraw::DrawTemplate* ViewProviderTemplate::getTemplate() const
{
    return dynamic_cast<TechDraw::DrawTemplate*>(pcObject);
}
<commit_msg>TD: fixes #0004598: Segfault when deleting template without page<commit_after>/***************************************************************************
 *   Copyright (c) 2014 Luke Parry <l.parry@warwick.ac.uk>                 *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <QMessageBox>
# include <QTextStream>
# ifdef FC_OS_WIN32
#  include <windows.h>
# endif
#endif

/// Here the FreeCAD includes sorted by Base,App,Gui......
#include <Base/Console.h>
#include <Base/Parameter.h>
#include <Base/Exception.h>
#include <Base/Sequencer.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>

#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/MainWindow.h>
#include <Gui/ViewProvider.h>

#include <Mod/TechDraw/App/DrawTemplate.h>
#include <Mod/TechDraw/App/DrawSVGTemplate.h>
#include <Mod/TechDraw/App/DrawPage.h>

#include "QGITemplate.h"
#include "QGISVGTemplate.h"
#include "QGVPage.h"
#include "MDIViewPage.h"
#include "TemplateTextField.h"
#include "ViewProviderPage.h"
#include "ViewProviderTemplate.h"

using namespace TechDrawGui;

PROPERTY_SOURCE(TechDrawGui::ViewProviderTemplate, Gui::ViewProviderDocumentObject)

//**************************************************************************
// Construction/Destruction

ViewProviderTemplate::ViewProviderTemplate()
{
    sPixmap = "TechDraw_Tree_PageTemplate";

    DisplayMode.setStatus(App::Property::Hidden,true);
}

ViewProviderTemplate::~ViewProviderTemplate()
{
}

void ViewProviderTemplate::attach(App::DocumentObject *pcFeat)
{
    // call parent attach method
    ViewProviderDocumentObject::attach(pcFeat);
}

void ViewProviderTemplate::setDisplayMode(const char* ModeName)
{
    ViewProviderDocumentObject::setDisplayMode(ModeName);
}

std::vector<std::string> ViewProviderTemplate::getDisplayModes(void) const
{
    // get the modes of the father
    std::vector<std::string> StrList = ViewProviderDocumentObject::getDisplayModes();

    return StrList;
}

void ViewProviderTemplate::updateData(const App::Property* prop)
{
    if (getTemplate()->isDerivedFrom(TechDraw::DrawSVGTemplate::getClassTypeId())) {
        auto t = static_cast<TechDraw::DrawSVGTemplate*>(getTemplate());
        if (prop == &(t->Template)) {
            MDIViewPage* mdi = getMDIViewPage();
            if (mdi != nullptr) {
                mdi->attachTemplate(t);
                mdi->viewAll();
            }
       }
    }
    Gui::ViewProviderDocumentObject::updateData(prop);
}

void ViewProviderTemplate::onChanged(const App::Property *prop)
{
    App::DocumentObject* obj = getObject();
    if (!obj || obj->isRestoring()) {
        Gui::ViewProviderDocumentObject::onChanged(prop);
        return;
    }

    if (prop == &Visibility) {
        if (Visibility.getValue()) {
            show();
        } else {
            hide();
        }
    }

    Gui::ViewProviderDocumentObject::onChanged(prop);
}

void ViewProviderTemplate::show(void)
{
    QGITemplate* qTemplate = getQTemplate();
    if (qTemplate != nullptr) {
        qTemplate->show();
    }

    ViewProviderDocumentObject::show();
}

void ViewProviderTemplate::hide(void)
{
    QGITemplate* qTemplate = getQTemplate();
    if (qTemplate != nullptr) {
        qTemplate->hide();
    }

    ViewProviderDocumentObject::hide();
}

bool ViewProviderTemplate::isShow(void) const
{
    return Visibility.getValue();
}

QGITemplate* ViewProviderTemplate::getQTemplate(void)
{
    QGITemplate *result = nullptr;
    TechDraw::DrawTemplate* dt = getTemplate();
    if (dt) {
        MDIViewPage* mdi = getMDIViewPage();
        if (mdi != nullptr) {
            result = mdi->getQGVPage()->getTemplate();
        }
    }
    return result;
}

void ViewProviderTemplate::setMarkers(bool state)
{
//    Base::Console().Message("VPT::setMarkers(%d)\n",state);
    QGITemplate* qTemplate = getQTemplate();
    QGISVGTemplate* qSvgTemplate = dynamic_cast<QGISVGTemplate*> (qTemplate);
    if (qSvgTemplate != nullptr) {
        std::vector<TemplateTextField *> textFields = qSvgTemplate->getTextFields();
        for (auto& t:textFields) {
            if (state) {
                t->show();
            } else {
                t->hide();
            }
        }
        qSvgTemplate->updateView(true);
    }
}

bool ViewProviderTemplate::onDelete(const std::vector<std::string> &)
{
    // deleting the template will break the page view, thus warn the user

    // get the page
    auto page = getTemplate()->getParentPage();

    // If no parent page is given then just go ahead
    if (!page)
        return true;

    // generate dialog
    QString bodyMessage;
    QTextStream bodyMessageStream(&bodyMessage);
    bodyMessageStream << qApp->translate("Std_Delete",
        "The following referencing object might break:");
    bodyMessageStream << "\n\n" << QString::fromUtf8(page->Label.getValue());
    bodyMessageStream << "\n\n" << QObject::tr("Are you sure you want to continue?");

    // show and evaluate dialog
    int DialogResult = QMessageBox::warning(Gui::getMainWindow(),
        qApp->translate("Std_Delete", "Object dependencies"), bodyMessage,
        QMessageBox::Yes, QMessageBox::No);
    if (DialogResult == QMessageBox::Yes)
        return true;
    else
        return false;
}

MDIViewPage* ViewProviderTemplate::getMDIViewPage(void) const
{
    MDIViewPage* myMdi = nullptr;
    auto t = getTemplate();
    auto page = t->getParentPage();
    Gui::ViewProvider* vp = Gui::Application::Instance->getDocument(t->getDocument())->getViewProvider(page);
    TechDrawGui::ViewProviderPage* dvp = dynamic_cast<TechDrawGui::ViewProviderPage*>(vp);
    if (dvp) {
        myMdi = dvp->getMDIViewPage();
    }
    return myMdi;
}

Gui::MDIView *ViewProviderTemplate::getMDIView() const
{
    return getMDIViewPage();
}

TechDraw::DrawTemplate* ViewProviderTemplate::getTemplate() const
{
    return dynamic_cast<TechDraw::DrawTemplate*>(pcObject);
}
<|endoftext|>


<commit_before>/*
 * HypothesisColl.cpp
 *
 *  Created on: 26 Feb 2016
 *      Author: hieu
 */
#include <iostream>
#include <sstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include "HypothesisColl.h"
#include "ManagerBase.h"
#include "System.h"
#include "MemPoolAllocator.h"

using namespace std;

namespace Moses2
{

HypothesisColl::HypothesisColl(const ManagerBase &mgr)
:m_coll(MemPoolAllocator<const HypothesisBase*>(mgr.GetPool()))
,m_sortedHypos(NULL)
{
  //m_bestScore = -std::numeric_limits<float>::infinity();
  //m_minBeamScore = -std::numeric_limits<float>::infinity();
  m_worseScore = std::numeric_limits<float>::infinity();
}

const HypothesisBase *HypothesisColl::GetBestHypo() const
{
	if (GetSize() == 0) {
		return NULL;
	}
	if (m_sortedHypos) {
		return (*m_sortedHypos)[0];
	}

	SCORE bestScore = -std::numeric_limits<SCORE>::infinity();
	const HypothesisBase *bestHypo;
	BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
		if (hypo->GetFutureScore() > bestScore) {
			bestScore = hypo->GetFutureScore();
			bestHypo = hypo;
		}
	}
	return bestHypo;
}

void HypothesisColl::Add(
		const System &system,
		HypothesisBase *hypo,
		Recycler<HypothesisBase*> &hypoRecycle,
		ArcLists &arcLists)
{
  size_t stackSize = system.options.search.stack_size;
  SCORE futureScore = hypo->GetFutureScore();
  /*
  cerr << "scores:"
      << futureScore << " "
      << m_bestScore << " "
      << m_minBeamScore << " "
      << GetSize() << " "
      << endl;
  */
  if (GetSize() >= stackSize && futureScore < m_worseScore) {
    // beam threshold or really bad hypo that won't make the pruning cut
    // as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
    //cerr << "Discard, really bad score:" << hypo->Debug(system) << endl;
    hypoRecycle.Recycle(hypo);
    return;
  }
  /*
  if (futureScore < m_minBeamScore) {
      // beam threshold or really bad hypo that won't make the pruning cut
      // as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
      //cerr << "Discard, below beam:" << hypo->Debug(system) << endl;
      hypoRecycle.Recycle(hypo);
      return;
  }

  if (futureScore > m_bestScore) {
    m_bestScore = hypo->GetFutureScore();

    // this may also affect the worst score
    SCORE beamWidth = system.options.search.beam_width;
    //cerr << "beamWidth=" << beamWidth << endl;
    if ( m_bestScore + beamWidth > m_minBeamScore ) {
      m_minBeamScore = m_bestScore + beamWidth;
    }
  }
  //cerr << "OK:" << hypo->Debug(system) << endl;
  */

	StackAdd added = Add(hypo);

	size_t nbestSize = system.options.nbest.nbest_size;
	if (nbestSize) {
		arcLists.AddArc(added.added, hypo, added.other);
	}
	else {
		if (!added.added) {
			hypoRecycle.Recycle(hypo);
		}
		else if (added.other) {
			hypoRecycle.Recycle(added.other);
		}
	}

}

StackAdd HypothesisColl::Add(const HypothesisBase *hypo)
{
	std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);

	// CHECK RECOMBINATION
	if (addRet.second) {
		// equiv hypo doesn't exists
	  if (hypo->GetFutureScore() < m_worseScore) {
	    m_worseScore = hypo->GetFutureScore();
	  }

		return StackAdd(true, NULL);
	}
	else {
		HypothesisBase *hypoExisting = const_cast<HypothesisBase*>(*addRet.first);
		if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {
			// incoming hypo is better than the one we have
			const HypothesisBase * const &hypoExisting1 = *addRet.first;
			const HypothesisBase *&hypoExisting2 =
					const_cast<const HypothesisBase *&>(hypoExisting1);
			hypoExisting2 = hypo;

			return StackAdd(true, hypoExisting);
		}
		else {
			// already storing the best hypo. discard incoming hypo
			return StackAdd(false, hypoExisting);
		}
	}

	//assert(false);
}

const Hypotheses &HypothesisColl::GetSortedAndPruneHypos(
		const ManagerBase &mgr,
		ArcLists &arcLists) const
{
	if (m_sortedHypos == NULL) {
		// create sortedHypos first
		MemPool &pool = mgr.GetPool();
		m_sortedHypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool,
				m_coll.size());

		size_t ind = 0;
		BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
			(*m_sortedHypos)[ind] = hypo;
			++ind;
		}

		SortAndPruneHypos(mgr, arcLists);
	}

	return *m_sortedHypos;
}

const Hypotheses &HypothesisColl::GetSortedAndPrunedHypos() const
{
	UTIL_THROW_IF2(m_sortedHypos == NULL, "m_sortedHypos must be sorted beforehand");
	return *m_sortedHypos;
}

void HypothesisColl::SortAndPruneHypos(const ManagerBase &mgr,
		ArcLists &arcLists) const
{
	size_t stackSize = mgr.system.options.search.stack_size;
	Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

	/*
   cerr << "UNSORTED hypos: ";
   BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
	   cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
   }
   cerr << endl;
	 */
	Hypotheses::iterator iterMiddle;
	iterMiddle =
			(stackSize == 0 || m_sortedHypos->size() < stackSize) ?
					m_sortedHypos->end() : m_sortedHypos->begin() + stackSize;

	std::partial_sort(m_sortedHypos->begin(), iterMiddle, m_sortedHypos->end(),
			HypothesisFutureScoreOrderer());

	// prune
	if (stackSize && m_sortedHypos->size() > stackSize) {
		for (size_t i = stackSize; i < m_sortedHypos->size(); ++i) {
			HypothesisBase *hypo = const_cast<HypothesisBase*>((*m_sortedHypos)[i]);
			recycler.Recycle(hypo);

			// delete from arclist
			if (mgr.system.options.nbest.nbest_size) {
				arcLists.Delete(hypo);
			}
		}
		m_sortedHypos->resize(stackSize);
	}

	/*
   cerr << "sorted hypos: ";
   for (size_t i = 0; i < m_sortedHypos->size(); ++i) {
   const HypothesisBase *hypo = (*m_sortedHypos)[i];
   	   cerr << hypo << " ";
   }
   cerr << endl;
	 */
}

void HypothesisColl::Clear()
{
	m_sortedHypos = NULL;
	m_coll.clear();

  //m_bestScore = -std::numeric_limits<float>::infinity();
  //m_minBeamScore = -std::numeric_limits<float>::infinity();
  m_worseScore = std::numeric_limits<float>::infinity();
}

std::string HypothesisColl::Debug(const System &system) const
{
	stringstream out;
	BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {
		out << hypo->Debug(system);
		out << std::endl << std::endl;
	}

	return out.str();
}

} /* namespace Moses2 */
<commit_msg>refine worseScore discarding<commit_after>/*
 * HypothesisColl.cpp
 *
 *  Created on: 26 Feb 2016
 *      Author: hieu
 */
#include <iostream>
#include <sstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include "HypothesisColl.h"
#include "ManagerBase.h"
#include "System.h"
#include "MemPoolAllocator.h"

using namespace std;

namespace Moses2
{

HypothesisColl::HypothesisColl(const ManagerBase &mgr)
:m_coll(MemPoolAllocator<const HypothesisBase*>(mgr.GetPool()))
,m_sortedHypos(NULL)
{
  //m_bestScore = -std::numeric_limits<float>::infinity();
  //m_minBeamScore = -std::numeric_limits<float>::infinity();
  m_worseScore = std::numeric_limits<float>::infinity();
}

const HypothesisBase *HypothesisColl::GetBestHypo() const
{
	if (GetSize() == 0) {
		return NULL;
	}
	if (m_sortedHypos) {
		return (*m_sortedHypos)[0];
	}

	SCORE bestScore = -std::numeric_limits<SCORE>::infinity();
	const HypothesisBase *bestHypo;
	BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
		if (hypo->GetFutureScore() > bestScore) {
			bestScore = hypo->GetFutureScore();
			bestHypo = hypo;
		}
	}
	return bestHypo;
}

void HypothesisColl::Add(
		const System &system,
		HypothesisBase *hypo,
		Recycler<HypothesisBase*> &hypoRecycle,
		ArcLists &arcLists)
{
  size_t maxStackSize = system.options.search.stack_size;
  //cerr << "stackSize=" << stackSize << endl;

  SCORE futureScore = hypo->GetFutureScore();
  /*
  cerr << "scores:"
      << futureScore << " "
      << m_bestScore << " "
      << m_minBeamScore << " "
      << GetSize() << " "
      << endl;
  */
  if (GetSize() >= maxStackSize && futureScore < m_worseScore) {
    // beam threshold or really bad hypo that won't make the pruning cut
    // as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
    //cerr << "Discard, really bad score:" << hypo->Debug(system) << endl;
    hypoRecycle.Recycle(hypo);
    return;
  }
  /*
  if (futureScore < m_minBeamScore) {
      // beam threshold or really bad hypo that won't make the pruning cut
      // as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
      //cerr << "Discard, below beam:" << hypo->Debug(system) << endl;
      hypoRecycle.Recycle(hypo);
      return;
  }

  if (futureScore > m_bestScore) {
    m_bestScore = hypo->GetFutureScore();

    // this may also affect the worst score
    SCORE beamWidth = system.options.search.beam_width;
    //cerr << "beamWidth=" << beamWidth << endl;
    if ( m_bestScore + beamWidth > m_minBeamScore ) {
      m_minBeamScore = m_bestScore + beamWidth;
    }
  }
  //cerr << "OK:" << hypo->Debug(system) << endl;
  */

	StackAdd added = Add(hypo);

	size_t nbestSize = system.options.nbest.nbest_size;
	if (nbestSize) {
		arcLists.AddArc(added.added, hypo, added.other);
	}
	else {
		if (!added.added) {
			hypoRecycle.Recycle(hypo);
		}
		else {
		  if (added.other) {
		    hypoRecycle.Recycle(added.other);
		  }

      if (GetSize() <= maxStackSize && hypo->GetFutureScore() < m_worseScore) {
        m_worseScore = futureScore;
      }
		}
	}

}

StackAdd HypothesisColl::Add(const HypothesisBase *hypo)
{
	std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);

	// CHECK RECOMBINATION
	if (addRet.second) {
		// equiv hypo doesn't exists
		return StackAdd(true, NULL);
	}
	else {
		HypothesisBase *hypoExisting = const_cast<HypothesisBase*>(*addRet.first);
		if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {
			// incoming hypo is better than the one we have
			const HypothesisBase * const &hypoExisting1 = *addRet.first;
			const HypothesisBase *&hypoExisting2 =
					const_cast<const HypothesisBase *&>(hypoExisting1);
			hypoExisting2 = hypo;

			return StackAdd(true, hypoExisting);
		}
		else {
			// already storing the best hypo. discard incoming hypo
			return StackAdd(false, hypoExisting);
		}
	}

	//assert(false);
}

const Hypotheses &HypothesisColl::GetSortedAndPruneHypos(
		const ManagerBase &mgr,
		ArcLists &arcLists) const
{
	if (m_sortedHypos == NULL) {
		// create sortedHypos first
		MemPool &pool = mgr.GetPool();
		m_sortedHypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool,
				m_coll.size());

		size_t ind = 0;
		BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
			(*m_sortedHypos)[ind] = hypo;
			++ind;
		}

		SortAndPruneHypos(mgr, arcLists);
	}

	return *m_sortedHypos;
}

const Hypotheses &HypothesisColl::GetSortedAndPrunedHypos() const
{
	UTIL_THROW_IF2(m_sortedHypos == NULL, "m_sortedHypos must be sorted beforehand");
	return *m_sortedHypos;
}

void HypothesisColl::SortAndPruneHypos(const ManagerBase &mgr,
		ArcLists &arcLists) const
{
	size_t stackSize = mgr.system.options.search.stack_size;
	Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

	/*
   cerr << "UNSORTED hypos: ";
   BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
	   cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
   }
   cerr << endl;
	 */
	Hypotheses::iterator iterMiddle;
	iterMiddle =
			(stackSize == 0 || m_sortedHypos->size() < stackSize) ?
					m_sortedHypos->end() : m_sortedHypos->begin() + stackSize;

	std::partial_sort(m_sortedHypos->begin(), iterMiddle, m_sortedHypos->end(),
			HypothesisFutureScoreOrderer());

	// prune
	if (stackSize && m_sortedHypos->size() > stackSize) {
		for (size_t i = stackSize; i < m_sortedHypos->size(); ++i) {
			HypothesisBase *hypo = const_cast<HypothesisBase*>((*m_sortedHypos)[i]);
			recycler.Recycle(hypo);

			// delete from arclist
			if (mgr.system.options.nbest.nbest_size) {
				arcLists.Delete(hypo);
			}
		}
		m_sortedHypos->resize(stackSize);
	}

	/*
   cerr << "sorted hypos: ";
   for (size_t i = 0; i < m_sortedHypos->size(); ++i) {
   const HypothesisBase *hypo = (*m_sortedHypos)[i];
   	   cerr << hypo << " ";
   }
   cerr << endl;
	 */
}

void HypothesisColl::Clear()
{
	m_sortedHypos = NULL;
	m_coll.clear();

  //m_bestScore = -std::numeric_limits<float>::infinity();
  //m_minBeamScore = -std::numeric_limits<float>::infinity();
  m_worseScore = std::numeric_limits<float>::infinity();
}

std::string HypothesisColl::Debug(const System &system) const
{
	stringstream out;
	BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {
		out << hypo->Debug(system);
		out << std::endl << std::endl;
	}

	return out.str();
}

} /* namespace Moses2 */
<|endoftext|>


<commit_before>/*
 * HypothesisColl.cpp
 *
 *  Created on: 26 Feb 2016
 *      Author: hieu
 */
#include <iostream>
#include <sstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include "HypothesisColl.h"
#include "ManagerBase.h"
#include "System.h"
#include "MemPoolAllocator.h"

using namespace std;

namespace Moses2
{

HypothesisColl::HypothesisColl(const ManagerBase &mgr)
:m_coll(MemPoolAllocator<const HypothesisBase*>(mgr.GetPool()))
,m_sortedHypos(NULL)
{
  //m_bestScore = -std::numeric_limits<float>::infinity();
  //m_minBeamScore = -std::numeric_limits<float>::infinity();
  m_worseScore = std::numeric_limits<float>::infinity();
}

const HypothesisBase *HypothesisColl::GetBestHypo() const
{
	if (GetSize() == 0) {
		return NULL;
	}
	if (m_sortedHypos) {
		return (*m_sortedHypos)[0];
	}

	SCORE bestScore = -std::numeric_limits<SCORE>::infinity();
	const HypothesisBase *bestHypo;
	BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
		if (hypo->GetFutureScore() > bestScore) {
			bestScore = hypo->GetFutureScore();
			bestHypo = hypo;
		}
	}
	return bestHypo;
}

void HypothesisColl::Add(
    const ManagerBase &mgr,
		HypothesisBase *hypo,
		Recycler<HypothesisBase*> &hypoRecycle,
		ArcLists &arcLists)
{
  size_t maxStackSize = mgr.system.options.search.stack_size;

  if (GetSize() > maxStackSize * 2) {
    //cerr << "maxStackSize=" << maxStackSize << " " << GetSize() << endl;
    PruneHypos(mgr, mgr.arcLists);
  }

  SCORE futureScore = hypo->GetFutureScore();
  /*
  cerr << "scores:"
      << futureScore << " "
      << m_bestScore << " "
      << m_minBeamScore << " "
      << GetSize() << " "
      << endl;
  */
  if (GetSize() >= maxStackSize && futureScore < m_worseScore) {
    // beam threshold or really bad hypo that won't make the pruning cut
    // as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
    //cerr << "Discard, really bad score:" << hypo->Debug(system) << endl;
    hypoRecycle.Recycle(hypo);
    return;
  }
  /*
  if (futureScore < m_minBeamScore) {
      // beam threshold or really bad hypo that won't make the pruning cut
      // as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
      //cerr << "Discard, below beam:" << hypo->Debug(system) << endl;
      hypoRecycle.Recycle(hypo);
      return;
  }

  if (futureScore > m_bestScore) {
    m_bestScore = hypo->GetFutureScore();

    // this may also affect the worst score
    SCORE beamWidth = system.options.search.beam_width;
    //cerr << "beamWidth=" << beamWidth << endl;
    if ( m_bestScore + beamWidth > m_minBeamScore ) {
      m_minBeamScore = m_bestScore + beamWidth;
    }
  }
  //cerr << "OK:" << hypo->Debug(system) << endl;
  */

	StackAdd added = Add(hypo);

	size_t nbestSize = mgr.system.options.nbest.nbest_size;
	if (nbestSize) {
		arcLists.AddArc(added.added, hypo, added.other);
	}
	else {
		if (!added.added) {
			hypoRecycle.Recycle(hypo);
		}
		else {
		  if (added.other) {
		    hypoRecycle.Recycle(added.other);
		  }

      if (GetSize() <= maxStackSize && hypo->GetFutureScore() < m_worseScore) {
        m_worseScore = futureScore;
      }
		}
	}

}

StackAdd HypothesisColl::Add(const HypothesisBase *hypo)
{
	std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);

	// CHECK RECOMBINATION
	if (addRet.second) {
		// equiv hypo doesn't exists
		return StackAdd(true, NULL);
	}
	else {
		HypothesisBase *hypoExisting = const_cast<HypothesisBase*>(*addRet.first);
		if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {
			// incoming hypo is better than the one we have
			const HypothesisBase * const &hypoExisting1 = *addRet.first;
			const HypothesisBase *&hypoExisting2 =
					const_cast<const HypothesisBase *&>(hypoExisting1);
			hypoExisting2 = hypo;

			return StackAdd(true, hypoExisting);
		}
		else {
			// already storing the best hypo. discard incoming hypo
			return StackAdd(false, hypoExisting);
		}
	}

	//assert(false);
}

const Hypotheses &HypothesisColl::GetSortedAndPruneHypos(
		const ManagerBase &mgr,
		ArcLists &arcLists) const
{
	if (m_sortedHypos == NULL) {
		// create sortedHypos first
		MemPool &pool = mgr.GetPool();
		m_sortedHypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool,
				m_coll.size());

		size_t ind = 0;
		BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
			(*m_sortedHypos)[ind] = hypo;
			++ind;
		}

		SortAndPruneHypos(mgr, arcLists);
	}

	return *m_sortedHypos;
}

const Hypotheses &HypothesisColl::GetSortedAndPrunedHypos() const
{
	UTIL_THROW_IF2(m_sortedHypos == NULL, "m_sortedHypos must be sorted beforehand");
	return *m_sortedHypos;
}

void HypothesisColl::SortAndPruneHypos(const ManagerBase &mgr,
		ArcLists &arcLists) const
{
	size_t stackSize = mgr.system.options.search.stack_size;
	Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

	/*
   cerr << "UNSORTED hypos: ";
   BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
	   cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
   }
   cerr << endl;
	 */
	Hypotheses::iterator iterMiddle;
	iterMiddle =
			(stackSize == 0 || m_sortedHypos->size() < stackSize) ?
					m_sortedHypos->end() : m_sortedHypos->begin() + stackSize;

	std::partial_sort(m_sortedHypos->begin(), iterMiddle, m_sortedHypos->end(),
			HypothesisFutureScoreOrderer());

	// prune
	if (stackSize && m_sortedHypos->size() > stackSize) {
		for (size_t i = stackSize; i < m_sortedHypos->size(); ++i) {
			HypothesisBase *hypo = const_cast<HypothesisBase*>((*m_sortedHypos)[i]);
			recycler.Recycle(hypo);

			// delete from arclist
			if (mgr.system.options.nbest.nbest_size) {
				arcLists.Delete(hypo);
			}
		}
		m_sortedHypos->resize(stackSize);
	}

	/*
   cerr << "sorted hypos: ";
   for (size_t i = 0; i < m_sortedHypos->size(); ++i) {
   const HypothesisBase *hypo = (*m_sortedHypos)[i];
   	   cerr << hypo << " ";
   }
   cerr << endl;
	 */
}

void HypothesisColl::PruneHypos(const ManagerBase &mgr, ArcLists &arcLists)
{
  size_t maxStackSize = mgr.system.options.search.stack_size;
  Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

  /*
   cerr << "UNSORTED hypos: ";
   BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
     cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
   }
   cerr << endl;
   */
  vector<const HypothesisBase*> sortedHypos(GetSize());
  size_t ind = 0;
  BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
    sortedHypos[ind] = hypo;
    ++ind;
  }

  vector<const HypothesisBase*>::iterator iterMiddle;
  iterMiddle =
      (maxStackSize == 0 || sortedHypos.size() < maxStackSize) ?
          sortedHypos.end() : sortedHypos.begin() + maxStackSize;

  std::partial_sort(sortedHypos.begin(), iterMiddle, sortedHypos.end(),
      HypothesisFutureScoreOrderer());

  // update worse score
  m_worseScore = sortedHypos[maxStackSize]->GetFutureScore();

  // prune
  if (maxStackSize && sortedHypos.size() > maxStackSize) {
    for (size_t i = maxStackSize; i < sortedHypos.size(); ++i) {
      HypothesisBase *hypo = const_cast<HypothesisBase*>(sortedHypos[i]);

      // delete from arclist
      if (mgr.system.options.nbest.nbest_size) {
        arcLists.Delete(hypo);
      }

      // delete from collection
      Delete(hypo);

      recycler.Recycle(hypo);
    }

  }

  /*
   cerr << "sorted hypos: ";
   for (size_t i = 0; i < sortedHypos.size(); ++i) {
     const HypothesisBase *hypo = sortedHypos[i];
     cerr << hypo << " ";
   }
   cerr << endl;
   */
}

void HypothesisColl::Delete(const HypothesisBase *hypo)
{
  //cerr << "hypo=" << hypo << " " << m_coll.size() << endl;

  size_t erased = m_coll.erase(hypo);
  UTIL_THROW_IF2(erased != 1, "couldn't erase hypo " << hypo);
}

void HypothesisColl::Clear()
{
	m_sortedHypos = NULL;
	m_coll.clear();

  //m_bestScore = -std::numeric_limits<float>::infinity();
  //m_minBeamScore = -std::numeric_limits<float>::infinity();
  m_worseScore = std::numeric_limits<float>::infinity();
}

std::string HypothesisColl::Debug(const System &system) const
{
	stringstream out;
	BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {
		out << hypo->Debug(system);
		out << std::endl << std::endl;
	}

	return out.str();
}

} /* namespace Moses2 */
<commit_msg>tweak<commit_after>/*
 * HypothesisColl.cpp
 *
 *  Created on: 26 Feb 2016
 *      Author: hieu
 */
#include <iostream>
#include <sstream>
#include <algorithm>
#include <boost/foreach.hpp>
#include "HypothesisColl.h"
#include "ManagerBase.h"
#include "System.h"
#include "MemPoolAllocator.h"

using namespace std;

namespace Moses2
{

HypothesisColl::HypothesisColl(const ManagerBase &mgr)
:m_coll(MemPoolAllocator<const HypothesisBase*>(mgr.GetPool()))
,m_sortedHypos(NULL)
{
  //m_bestScore = -std::numeric_limits<float>::infinity();
  //m_minBeamScore = -std::numeric_limits<float>::infinity();
  m_worseScore = std::numeric_limits<float>::infinity();
}

const HypothesisBase *HypothesisColl::GetBestHypo() const
{
	if (GetSize() == 0) {
		return NULL;
	}
	if (m_sortedHypos) {
		return (*m_sortedHypos)[0];
	}

	SCORE bestScore = -std::numeric_limits<SCORE>::infinity();
	const HypothesisBase *bestHypo;
	BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
		if (hypo->GetFutureScore() > bestScore) {
			bestScore = hypo->GetFutureScore();
			bestHypo = hypo;
		}
	}
	return bestHypo;
}

void HypothesisColl::Add(
    const ManagerBase &mgr,
		HypothesisBase *hypo,
		Recycler<HypothesisBase*> &hypoRecycle,
		ArcLists &arcLists)
{
  size_t maxStackSize = mgr.system.options.search.stack_size;

  if (GetSize() > maxStackSize * 2) {
    //cerr << "maxStackSize=" << maxStackSize << " " << GetSize() << endl;
    PruneHypos(mgr, mgr.arcLists);
  }

  SCORE futureScore = hypo->GetFutureScore();
  /*
  cerr << "scores:"
      << futureScore << " "
      << m_bestScore << " "
      << m_minBeamScore << " "
      << GetSize() << " "
      << endl;
  */
  if (GetSize() >= maxStackSize && futureScore < m_worseScore) {
    // beam threshold or really bad hypo that won't make the pruning cut
    // as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
    //cerr << "Discard, really bad score:" << hypo->Debug(system) << endl;
    hypoRecycle.Recycle(hypo);
    return;
  }
  /*
  if (futureScore < m_minBeamScore) {
      // beam threshold or really bad hypo that won't make the pruning cut
      // as more hypos are added, the m_worseScore stat gets out of date and isn't the optimum cut-off point
      //cerr << "Discard, below beam:" << hypo->Debug(system) << endl;
      hypoRecycle.Recycle(hypo);
      return;
  }

  if (futureScore > m_bestScore) {
    m_bestScore = hypo->GetFutureScore();

    // this may also affect the worst score
    SCORE beamWidth = system.options.search.beam_width;
    //cerr << "beamWidth=" << beamWidth << endl;
    if ( m_bestScore + beamWidth > m_minBeamScore ) {
      m_minBeamScore = m_bestScore + beamWidth;
    }
  }
  //cerr << "OK:" << hypo->Debug(system) << endl;
  */

	StackAdd added = Add(hypo);

	size_t nbestSize = mgr.system.options.nbest.nbest_size;
	if (nbestSize) {
		arcLists.AddArc(added.added, hypo, added.other);
	}
	else {
		if (!added.added) {
			hypoRecycle.Recycle(hypo);
		}
		else {
		  if (added.other) {
		    hypoRecycle.Recycle(added.other);
		  }

      if (GetSize() <= maxStackSize && hypo->GetFutureScore() < m_worseScore) {
        m_worseScore = futureScore;
      }
		}
	}

}

StackAdd HypothesisColl::Add(const HypothesisBase *hypo)
{
	std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);

	// CHECK RECOMBINATION
	if (addRet.second) {
		// equiv hypo doesn't exists
		return StackAdd(true, NULL);
	}
	else {
		HypothesisBase *hypoExisting = const_cast<HypothesisBase*>(*addRet.first);
		if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {
			// incoming hypo is better than the one we have
			const HypothesisBase * const &hypoExisting1 = *addRet.first;
			const HypothesisBase *&hypoExisting2 =
					const_cast<const HypothesisBase *&>(hypoExisting1);
			hypoExisting2 = hypo;

			return StackAdd(true, hypoExisting);
		}
		else {
			// already storing the best hypo. discard incoming hypo
			return StackAdd(false, hypoExisting);
		}
	}

	//assert(false);
}

const Hypotheses &HypothesisColl::GetSortedAndPruneHypos(
		const ManagerBase &mgr,
		ArcLists &arcLists) const
{
	if (m_sortedHypos == NULL) {
		// create sortedHypos first
		MemPool &pool = mgr.GetPool();
		m_sortedHypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool,
				m_coll.size());

		size_t ind = 0;
		BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
			(*m_sortedHypos)[ind] = hypo;
			++ind;
		}

		SortAndPruneHypos(mgr, arcLists);
	}

	return *m_sortedHypos;
}

const Hypotheses &HypothesisColl::GetSortedAndPrunedHypos() const
{
	UTIL_THROW_IF2(m_sortedHypos == NULL, "m_sortedHypos must be sorted beforehand");
	return *m_sortedHypos;
}

void HypothesisColl::SortAndPruneHypos(const ManagerBase &mgr,
		ArcLists &arcLists) const
{
	size_t stackSize = mgr.system.options.search.stack_size;
	Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

	/*
   cerr << "UNSORTED hypos: ";
   BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
	   cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
   }
   cerr << endl;
	 */
	Hypotheses::iterator iterMiddle;
	iterMiddle =
			(stackSize == 0 || m_sortedHypos->size() < stackSize) ?
					m_sortedHypos->end() : m_sortedHypos->begin() + stackSize;

	std::partial_sort(m_sortedHypos->begin(), iterMiddle, m_sortedHypos->end(),
			HypothesisFutureScoreOrderer());

	// prune
	if (stackSize && m_sortedHypos->size() > stackSize) {
		for (size_t i = stackSize; i < m_sortedHypos->size(); ++i) {
			HypothesisBase *hypo = const_cast<HypothesisBase*>((*m_sortedHypos)[i]);
			recycler.Recycle(hypo);

			// delete from arclist
			if (mgr.system.options.nbest.nbest_size) {
				arcLists.Delete(hypo);
			}
		}
		m_sortedHypos->resize(stackSize);
	}

	/*
   cerr << "sorted hypos: ";
   for (size_t i = 0; i < m_sortedHypos->size(); ++i) {
   const HypothesisBase *hypo = (*m_sortedHypos)[i];
   	   cerr << hypo << " ";
   }
   cerr << endl;
	 */
}

void HypothesisColl::PruneHypos(const ManagerBase &mgr, ArcLists &arcLists)
{
  size_t maxStackSize = mgr.system.options.search.stack_size;
  Recycler<HypothesisBase*> &recycler = mgr.GetHypoRecycle();

  /*
   cerr << "UNSORTED hypos: ";
   BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {
     cerr << hypo << "(" << hypo->GetFutureScore() << ")" << " ";
   }
   cerr << endl;
   */
  vector<const HypothesisBase*> sortedHypos(GetSize());
  size_t ind = 0;
  BOOST_FOREACH(const HypothesisBase *hypo, m_coll){
    sortedHypos[ind] = hypo;
    ++ind;
  }

  vector<const HypothesisBase*>::iterator iterMiddle;
  iterMiddle =
      (maxStackSize == 0 || sortedHypos.size() < maxStackSize) ?
          sortedHypos.end() : sortedHypos.begin() + maxStackSize;

  std::partial_sort(sortedHypos.begin(), iterMiddle, sortedHypos.end(),
      HypothesisFutureScoreOrderer());

  // update worse score
  m_worseScore = sortedHypos[maxStackSize - 1]->GetFutureScore();

  // prune
  if (maxStackSize && sortedHypos.size() > maxStackSize) {
    for (size_t i = maxStackSize; i < sortedHypos.size(); ++i) {
      HypothesisBase *hypo = const_cast<HypothesisBase*>(sortedHypos[i]);

      // delete from arclist
      if (mgr.system.options.nbest.nbest_size) {
        arcLists.Delete(hypo);
      }

      // delete from collection
      Delete(hypo);

      recycler.Recycle(hypo);
    }

  }

  /*
   cerr << "sorted hypos: ";
   for (size_t i = 0; i < sortedHypos.size(); ++i) {
     const HypothesisBase *hypo = sortedHypos[i];
     cerr << hypo << " ";
   }
   cerr << endl;
   */
}

void HypothesisColl::Delete(const HypothesisBase *hypo)
{
  //cerr << "hypo=" << hypo << " " << m_coll.size() << endl;

  size_t erased = m_coll.erase(hypo);
  UTIL_THROW_IF2(erased != 1, "couldn't erase hypo " << hypo);
}

void HypothesisColl::Clear()
{
	m_sortedHypos = NULL;
	m_coll.clear();

  //m_bestScore = -std::numeric_limits<float>::infinity();
  //m_minBeamScore = -std::numeric_limits<float>::infinity();
  m_worseScore = std::numeric_limits<float>::infinity();
}

std::string HypothesisColl::Debug(const System &system) const
{
	stringstream out;
	BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {
		out << hypo->Debug(system);
		out << std::endl << std::endl;
	}

	return out.str();
}

} /* namespace Moses2 */
<|endoftext|>


<commit_before>#ifndef ERROR_HH
#define ERROR_HH

#include <exception>
#include <cstdarg>
#include <cstdio>
#include <string>
#include <string.h>
#include <errno.h>

namespace fw {

//! captures the backtrace in the constructor
//
//! useful for coroutines because the stack is lost switching contexts
class backtrace_exception : public std::exception {
public:
    backtrace_exception();

    std::string str();
private:
    void *array[50];
    int size;
};

//! exception that sets what() based on current errno value
struct errno_error : backtrace_exception {
    char _buf[256];
    const char *_what;
    //! the value of errno when this exception was created
    int _error;

    //! \param err the error as specified by errno
    errno_error(int err = errno) : _error(err) {
        // requires GNU specific strerror_r
        // _what might be _buf or an internal static string
        _what = strerror_r(_error, _buf, sizeof(_buf));
    }

    //! \return string result from strerror_r
    const char *what() const throw() { return _what; }
};

//! construct a what() string in printf() format
struct errorx : backtrace_exception {
    char _buf[256];

    //! \param fmt printf-style format string
    errorx(const char *fmt, ...) __attribute__((format (printf, 2, 3))) {
        _buf[0] = 0;
        va_list ap;
        va_start(ap, fmt);
        vsnprintf(_buf, sizeof(_buf), fmt, ap);
        va_end(ap);
    }

    //! \return a string describing the error
    const char *what() const throw () { return _buf; }
};

//! macro to throw if exp returns -1
#define THROW_ON_ERROR(exp) \
    if ((exp) == -1) { \
        throw errno_error(); \
    }

#define THROW_ON_NULL(exp) \
    if ((exp) == NULL) { \
        throw errno_error(); \
    }

#define THROW_ON_NONZERO(exp) \
    { \
        int _rv = (exp); \
        if (_rv != 0) throw errno_error(_rv); \
    }

} // end namespace fw

#endif // ERROR_HH

<commit_msg>std::string constructor for errorx<commit_after>#ifndef ERROR_HH
#define ERROR_HH

#include <exception>
#include <cstdarg>
#include <cstdio>
#include <string>
#include <string.h>
#include <errno.h>

namespace fw {

//! captures the backtrace in the constructor
//
//! useful for coroutines because the stack is lost switching contexts
class backtrace_exception : public std::exception {
public:
    backtrace_exception();

    std::string str();
private:
    void *array[50];
    int size;
};

//! exception that sets what() based on current errno value
struct errno_error : backtrace_exception {
    char _buf[256];
    const char *_what;
    //! the value of errno when this exception was created
    int _error;

    //! \param err the error as specified by errno
    errno_error(int err = errno) : _error(err) {
        // requires GNU specific strerror_r
        // _what might be _buf or an internal static string
        _what = strerror_r(_error, _buf, sizeof(_buf));
    }

    //! \return string result from strerror_r
    const char *what() const throw() { return _what; }
};

//! construct a what() string in printf() format
struct errorx : backtrace_exception {
    char _buf[256];

    //! \param fmt printf-style format string
    errorx(const char *fmt, ...) __attribute__((format (printf, 2, 3))) {
        _buf[0] = 0;
        va_list ap;
        va_start(ap, fmt);
        vsnprintf(_buf, sizeof(_buf), fmt, ap);
        va_end(ap);
    }

    errorx(const std::string &msg) {
        strncpy(_buf, msg.data(), sizeof(_buf)-1);
        _buf[sizeof(_buf)-1] = 0;
    }

    //! \return a string describing the error
    const char *what() const throw () { return _buf; }
};

//! macro to throw if exp returns -1
#define THROW_ON_ERROR(exp) \
    if ((exp) == -1) { \
        throw errno_error(); \
    }

#define THROW_ON_NULL(exp) \
    if ((exp) == NULL) { \
        throw errno_error(); \
    }

#define THROW_ON_NONZERO(exp) \
    { \
        int _rv = (exp); \
        if (_rv != 0) throw errno_error(_rv); \
    }

} // end namespace fw

#endif // ERROR_HH

<|endoftext|>


<commit_before>// PRIME_FACTOR.CPP: Factorize a number into multiple of primes
// Educational purpose - Coded by Trinh D.D. Nguyen
// ---
// compile: type 'make' and ENTER
// ----
// usage: prime_factor [number]

#include <iostream>
#include <string>	// requires C++ 11 to compile stol()
			// if not please consider using atol() from stdlib.h

using namespace std;

int main(int argc, char * argv[])
{
	unsigned long i, n;

	if (argc < 2) // no value given from command line?
	{
		// input from keyboard
		cout << "enter a number to factorize: ";
		cin >> n;
	}
	else
	{
		// convert received from the value from command line to integer
		// no error checking performed here
		n = stol(argv[1]);
	}

	// ----
	// main algorithm, kinda naive and doesn't fit for using with big integers
	i = 2;					// start with 2, first prime
	while (n > 1)				// loop while n still greater than 1
	{
		while (n % i == 0)		// while still divisible
		{
			cout << i << " ";	// print out that divisor
			n = n / i;		// divide n by i
		}
		i++;	// next divisor
	}

	cout << endl;

	return 0;
}
<commit_msg>tabs fixed<commit_after>// PRIME_FACTOR.CPP: Factorize a number into multiple of primes
// Educational purpose - Coded by Trinh D.D. Nguyen
// ---
// compile: type 'make' and ENTER
// ----
// usage: prime_factor [number]

#include <iostream>
#include <string>	// requires C++ 11 to compile stol()
					// if not please consider using atol() from stdlib.h

using namespace std;

int main(int argc, char * argv[])
{
	unsigned long i, n;

	if (argc < 2) // no value given from command line?
	{
		// input from keyboard
		cout << "enter a number to factorize: ";
		cin >> n;
	}
	else
	{
		// convert received from the value from command line to integer
		// no error checking performed here
		n = stol(argv[1]);
	}

	// ----
	// main algorithm, kinda naive and doesn't fit for using with big integers
	i = 2;						// start with 2, first prime
	while (n > 1)				// loop while n still greater than 1
	{
		while (n % i == 0)		// while still divisible
		{
			cout << i << " ";	// print out that divisor
			n = n / i;			// divide n by i
		}
		i++;					// next divisor
	}

	cout << endl;

	return 0;
}
<|endoftext|>