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

#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_
#include <com/sun/star/sdbc/XDriver.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDATADEFINITIONSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XDataDefinitionSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include "connectivity/CommonTools.hxx"
#endif

//........................................................................
namespace connectivity
{
//........................................................................

    class OMetaConnection;

    namespace mysql
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriverDelegator_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception );

        typedef ::cppu::WeakComponentImplHelper3<   ::com::sun::star::sdbc::XDriver
                                                ,   ::com::sun::star::sdbcx::XDataDefinitionSupplier
                                                ,   ::com::sun::star::lang::XServiceInfo
                                                >   ODriverDelegator_BASE;

        typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,OMetaConnection*> TWeakConnectionPair;
        typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,TWeakConnectionPair> TWeakPair;
        typedef ::std::vector< TWeakPair > TWeakPairVector;
        DECLARE_STL_USTRINGACCESS_MAP(::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver >,TJDBCDrivers);

        /** delegates all calls to the orignal driver and extend the existing one with the SDBCX layer.

        */
        class ODriverDelegator : public ::comphelper::OBaseMutex
                                ,public ODriverDelegator_BASE
        {
            TJDBCDrivers                                                        m_aJdbcDrivers; // all jdbc drivers
            TWeakPairVector                                                     m_aConnections; //  vector containing a list
                                                                                //  of all the Connection objects
                                                                                //  for this Driver
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver >                 m_xODBCDriver;
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >    m_xFactory;
            ::rtl::OUString     m_sOldDriverClass;
            sal_Bool            m_bUseOdbc;

            /** load the driver we want to delegate.
                The <member>m_xODBCDriver</member> or <member>m_xDBCDriver</member> may be <NULL/> if the driver could not be loaded.
                @param  url
                    The URL.
                @param  info
                    The property info contains which driver we have to delegate.
                @return
                    The driver which was currently selected.
            */
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > loadDriver( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info );

        public:
            /** creates a new delegator for a mysql driver
            */
            ODriverDelegator(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);

            // XServiceInfo
            DECLARE_SERVICE_INFO();
            static ::rtl::OUString getImplementationName_Static(  ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(  ) throw (::com::sun::star::uno::RuntimeException);

            // XDriver
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getMajorVersion(  ) throw (::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getMinorVersion(  ) throw (::com::sun::star::uno::RuntimeException);

            // XDataDefinitionSupplier
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& connection ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByURL( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        protected:
            /// dtor
            virtual ~ODriverDelegator();
            // OComponentHelper
            virtual void SAL_CALL disposing(void);
        };
    }

//........................................................................
}   // namespace connectivity
//........................................................................
#endif // CONNECTIVITY_MYSQL_DRIVER_HXX

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

#include <com/sun/star/sdbc/XDriver.hpp>
#include <com/sun/star/sdbcx/XDataDefinitionSupplier.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <cppuhelper/compbase3.hxx>
#include <comphelper/uno3.hxx>
#include <comphelper/stl_types.hxx>
#include <comphelper/broadcasthelper.hxx>
#include "connectivity/CommonTools.hxx"

//........................................................................
namespace connectivity
{
//........................................................................

    class OMetaConnection;

    namespace mysql
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriverDelegator_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception );

        typedef ::cppu::WeakComponentImplHelper3<   ::com::sun::star::sdbc::XDriver
                                                ,   ::com::sun::star::sdbcx::XDataDefinitionSupplier
                                                ,   ::com::sun::star::lang::XServiceInfo
                                                >   ODriverDelegator_BASE;

        typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,OMetaConnection*> TWeakConnectionPair;
        typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,TWeakConnectionPair> TWeakPair;
        typedef ::std::vector< TWeakPair > TWeakPairVector;
        DECLARE_STL_USTRINGACCESS_MAP(::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver >,TJDBCDrivers);

        /** delegates all calls to the orignal driver and extend the existing one with the SDBCX layer.

        */
        class ODriverDelegator : public ::comphelper::OBaseMutex
                                ,public ODriverDelegator_BASE
        {
            TJDBCDrivers                                                        m_aJdbcDrivers; // all jdbc drivers
            TWeakPairVector                                                     m_aConnections; //  vector containing a list
                                                                                //  of all the Connection objects
                                                                                //  for this Driver
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver >                 m_xODBCDriver;
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >    m_xFactory;
            ::rtl::OUString     m_sOldDriverClass;
            sal_Bool            m_bUseOdbc;

            /** load the driver we want to delegate.
                The <member>m_xODBCDriver</member> or <member>m_xDBCDriver</member> may be <NULL/> if the driver could not be loaded.
                @param  url
                    The URL.
                @param  info
                    The property info contains which driver we have to delegate.
                @return
                    The driver which was currently selected.
            */
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > loadDriver( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info );

        public:
            /** creates a new delegator for a mysql driver
            */
            ODriverDelegator(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);

            // XServiceInfo
            DECLARE_SERVICE_INFO();
            static ::rtl::OUString getImplementationName_Static(  ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(  ) throw (::com::sun::star::uno::RuntimeException);

            // XDriver
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getMajorVersion(  ) throw (::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getMinorVersion(  ) throw (::com::sun::star::uno::RuntimeException);

            // XDataDefinitionSupplier
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& connection ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByURL( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        protected:
            /// dtor
            virtual ~ODriverDelegator();
            // OComponentHelper
            virtual void SAL_CALL disposing(void);
        };
    }

//........................................................................
}   // namespace connectivity
//........................................................................
#endif // CONNECTIVITY_MYSQL_DRIVER_HXX

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// projection_sql_test.cpp
//
// Identification: test/sql/projection_sql_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <memory>

#include "sql/testing_sql_util.h"

#include "catalog/catalog.h"
#include "common/harness.h"
#include "concurrency/transaction_manager_factory.h"

namespace peloton {
namespace test {

class ProjectionSQLTests : public PelotonTest {
 public:
  ProjectionSQLTests() {
    auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
    auto *txn = txn_manager.BeginTransaction();
    catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
    txn_manager.CommitTransaction(txn);

    auto catalog = catalog::Catalog::GetInstance();
    catalog->Bootstrap();

    SetupTestTable();
  }

  ~ProjectionSQLTests() {
    auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
    auto *txn = txn_manager.BeginTransaction();
    catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
    txn_manager.CommitTransaction(txn);
  }

  void SetupTestTable() {
    TestingSQLUtil::ExecuteSQLQuery(
        "CREATE TABLE test(a TINYINT, b SMALLINT, c INT, d BIGINT, e "
        "DECIMAL);");

    // Insert tuples into table
    TestingSQLUtil::ExecuteSQLQuery(
        "INSERT INTO test VALUES (1, 2, 3, 4, 5.0);");
  }
};

TEST_F(ProjectionSQLTests, SimpleProjectionSQLTest) {
  // Test TINYINT
  std::string sql = "SELECT a+a, a-a, a*a, a/a, a+b, a+c, a+d, a+e FROM test";
  std::vector<std::string> expected = {"2|0|1|1|3|4|5|6"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  // Test SMALLINT
  sql = "SELECT b+b, b-b, b*b, b/b, b+a, b+c, b+d, b+e FROM test";
  expected = {"4|0|4|1|3|5|6|7"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  // Test INT
  sql = "SELECT c+c, c-c, c*c, c/c, c+a, c+b, c+d, c+e FROM test";
  expected = {"6|0|9|1|4|5|7|8"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  // Test BIGINT
  sql = "SELECT d+d, d-d, d*d, d/d, d+a, d+b, d+c, d+e FROM test";
  expected = {"8|0|16|1|5|6|7|9"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  // Test DECIMAL
  sql = "SELECT e+e, e-e, e*e, e/e, e+a, e+b, e+c, e+d FROM test";
  expected = {"10|0|25|1|6|7|8|9"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);
}

TEST_F(ProjectionSQLTests, ProjectionSQLTest) {
  std::string sql = "SELECT a*5+b, -1+c, 6, a from test";
  std::vector<std::string> expected = {"7|2|6|1"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  sql = "SELECT d+e*2.0, e, e+(2*c) from test";
  expected = {"14|5|11"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);
}

}  // namespace test
}  // namespace peloton
<commit_msg>Fixed projection_sql_tests<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// projection_sql_test.cpp
//
// Identification: test/sql/projection_sql_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <memory>

#include "sql/testing_sql_util.h"

#include "catalog/catalog.h"
#include "common/harness.h"
#include "concurrency/transaction_manager_factory.h"

namespace peloton {
namespace test {

class ProjectionSQLTests : public PelotonTest {
 public:
  ProjectionSQLTests() {
    auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
    auto *txn = txn_manager.BeginTransaction();
    auto catalog = catalog::Catalog::GetInstance();
    catalog->Bootstrap();
    catalog->CreateDatabase(DEFAULT_DB_NAME, txn);
    txn_manager.CommitTransaction(txn);
    SetupTestTable();
  }

  ~ProjectionSQLTests() {
    auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
    auto *txn = txn_manager.BeginTransaction();
    catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
    txn_manager.CommitTransaction(txn);
  }

  void SetupTestTable() {
    TestingSQLUtil::ExecuteSQLQuery(
        "CREATE TABLE test(a TINYINT, b SMALLINT, c INT, d BIGINT, e "
        "DECIMAL);");

    // Insert tuples into table
    TestingSQLUtil::ExecuteSQLQuery(
        "INSERT INTO test VALUES (1, 2, 3, 4, 5.0);");
  }
};

TEST_F(ProjectionSQLTests, SimpleProjectionSQLTest) {
  // Test TINYINT
  std::string sql = "SELECT a+a, a-a, a*a, a/a, a+b, a+c, a+d, a+e FROM test";
  std::vector<std::string> expected = {"2|0|1|1|3|4|5|6"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  // Test SMALLINT
  sql = "SELECT b+b, b-b, b*b, b/b, b+a, b+c, b+d, b+e FROM test";
  expected = {"4|0|4|1|3|5|6|7"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  // Test INT
  sql = "SELECT c+c, c-c, c*c, c/c, c+a, c+b, c+d, c+e FROM test";
  expected = {"6|0|9|1|4|5|7|8"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  // Test BIGINT
  sql = "SELECT d+d, d-d, d*d, d/d, d+a, d+b, d+c, d+e FROM test";
  expected = {"8|0|16|1|5|6|7|9"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  // Test DECIMAL
  sql = "SELECT e+e, e-e, e*e, e/e, e+a, e+b, e+c, e+d FROM test";
  expected = {"10|0|25|1|6|7|8|9"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);
}

TEST_F(ProjectionSQLTests, ProjectionSQLTest) {
  std::string sql = "SELECT a*5+b, -1+c, 6, a from test";
  std::vector<std::string> expected = {"7|2|6|1"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);

  sql = "SELECT d+e*2.0, e, e+(2*c) from test";
  expected = {"14|5|11"};
  TestingSQLUtil::ExecuteSQLQueryAndCheckResult(sql, expected, false);
}

}  // namespace test
}  // namespace peloton
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: PeptideBuilder_test.C,v 1.7 2004/02/13 17:00:22 anhi Exp $

#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/STRUCTURE/peptideBuilder.h>
#include <vector>

///////////////////////////

START_TEST(PeptideBuilder, "$Id: PeptideBuilder_test.C,v 1.7 2004/02/13 17:00:22 anhi Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;
using namespace BALL::Peptides;

PeptideBuilder* pbptr = 0;
CHECK(PeptideBuilder())
	pbptr = new PeptideBuilder;
	TEST_NOT_EQUAL(pbptr, 0)
RESULT

CHECK(~PeptideBuilder())
	delete pbptr;
	pbptr = 0;
RESULT

AminoAcidDescriptor* aad = 0;
CHECK(AminoAcidDescriptor())
	aad = new AminoAcidDescriptor;
	TEST_NOT_EQUAL(aad,0)
RESULT

CHECK(~AminoAcidDescriptor())
	delete aad;
  aad= 0;
RESULT

CHECK(AminoAcidDescriptor(const String& type, const Angle& phi,
													const Angle& psi, const Angle& omega))
	aad= new AminoAcidDescriptor("HIS", Angle(M_PI, true), Angle(M_PI, true));
	TEST_NOT_EQUAL(aad, 0)
	TEST_EQUAL(aad->getType(), "HIS")
	TEST_EQUAL(aad->getPhi(), Angle(M_PI, true))
	TEST_EQUAL(aad->getPsi(), Angle(M_PI, true))
RESULT

AminoAcidDescriptor* aad2=0;
CHECK(AminoAcidDescriptor(const AminoAcidDescriptor& aad))
	aad2 = new AminoAcidDescriptor(*aad);
	TEST_NOT_EQUAL(aad2, 0)
	TEST_EQUAL(aad2->getType(), "HIS")
	TEST_EQUAL(aad2->getPhi(), Angle(M_PI, true))
	TEST_EQUAL(aad2->getPsi(), Angle(M_PI, true))
RESULT

//
// Tests for the complement get and set-methods
//

CHECK(setAminoAcidType(const String& type))
  aad->setAminoAcidType("GLY");
	TEST_EQUAL(aad->getType(),"GLY")
  aad2->setAminoAcidType("V");
	TEST_EQUAL(aad2->getType(),"VAL")
RESULT

CHECK(setPhi(const Angle& phi))
  aad->setPhi(Angle(-47., false));
	TEST_EQUAL(aad->getPhi(), Angle(-47., false) )
  aad2->setPhi(Angle(-77., false));
	TEST_EQUAL(aad2->getPhi(), Angle(-77., false) )
RESULT

CHECK(setPsi(const Angle& phi))
  aad->setPsi(Angle(-58., false));
	TEST_EQUAL(aad->getPsi(), Angle(-58., false) )
  aad2->setPsi(Angle(8.15, false));
	TEST_EQUAL(aad2->getPsi(), Angle(8.15, false) )
RESULT

CHECK(setOmega(const Angle& phi))
  aad->setOmega(Angle(90., false));
	TEST_EQUAL(aad->getOmega(), Angle(90., false))
  aad2->setOmega(Angle(M_PI, true));
	TEST_EQUAL(aad2->getOmega(), Angle(180, false))
RESULT

	/*CHECK(~AminoAcidDescriptor()) used for the addAminoAcid()-Test
	delete aad ;
  aad = 0;
	RESULT*/

//
//   Tests of class PeptideBuilder
//

PeptideBuilder* pb = 0;
CHECK(PeptideBuilder())
  pb= new PeptideBuilder;
	TEST_NOT_EQUAL(pb, 0)
RESULT

//
//CHECK(PeptideBuilder(const std::vector<AminoAcidDescriptor>& sequence)) later on
//

CHECK(addAminoAcid(const String& type, const Angle& phi, const Angle& psi, const Angle& omega))
  pb->addAminoAcid("LEU");
  pb->addAminoAcid("SER",Angle(M_PI, true),Angle(M_PI, true));
	TEST_NOT_EQUAL(pb, 0)
RESULT

CHECK(addAminoAcid(const AminoAcidDescriptor& aad))
  pb->addAminoAcid(*aad);
  pb->addAminoAcid(*aad2);
	TEST_NOT_EQUAL(pb, 0)
RESULT

CHECK(setChainName(const String& name)/getChainName())
  pb->setChainName("TestChainName");
	TEST_EQUAL(pb->getChainName(),"TestChainName")
RESULT

CHECK(setProteinName(const String& name)/getProteinName())
	pb->setProteinName("TestProteinName");
	TEST_EQUAL(pb->getProteinName(),"TestProteinName")
RESULT

PeptideBuilder* pb2 = 0;
CHECK(PeptideBuilder(const PeptideBuilder& pb))
  pb2= new PeptideBuilder(*pb);
	TEST_NOT_EQUAL(pb2, 0)
	TEST_EQUAL(pb2->getChainName(),"TestChainName")
	TEST_EQUAL(pb2->getProteinName(),"TestProteinName")
RESULT

PeptideBuilder* pb3=0;
CHECK(PeptideBuilder(const std::vector<AminoAcidDescriptor>& sequence))
  std::vector<AminoAcidDescriptor> v;
  v.push_back(*aad);
	v.push_back(*aad2);
  pb3 = new PeptideBuilder(v);
  TEST_NOT_EQUAL(pb3, 0)
RESULT

CHECK(construct())
	Protein *prot=pb->construct();
	ResidueIterator resIt;
  resIt = prot->beginResidue();

	PRECISION(1e-3)
	TEST_EQUAL(resIt->getName(), "LEU")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));
  TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-58.,false));
  ++resIt;
	TEST_EQUAL(resIt->getName(), "SER")
  TEST_REAL_EQUAL(fabs(resIt->getTorsionPhi().toRadian()), M_PI)
	TEST_REAL_EQUAL(fabs(resIt->getTorsionPsi().toRadian()), M_PI)
  ++resIt;
	PRECISION(2E-2)
	TEST_EQUAL(resIt->getName(), "GLY")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-47, false))
  TEST_REAL_EQUAL(resIt->getTorsionPsi(), -1.01);
  ++resIt;
	TEST_EQUAL(resIt->getName(), "VAL")
  TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-77., false));
	TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(0, false));

	prot = pb3->construct();
  resIt = prot->beginResidue();

	TEST_EQUAL(resIt->getName(), "GLY")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));
  TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-58.,false));
  ++resIt;
	TEST_EQUAL(resIt->getName(), "VAL")
  TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-77.,false));
	TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(0,false));

	PeptideBuilder pb4;
	pb4.addAminoAcid("PRO");
	pb4.addAminoAcid("PRO", Angle(-12., false), Angle(42, false));
	pb4.addAminoAcid("PRO", Angle(28, false), Angle(33, false));

	prot = pb4.construct();

  resIt = prot->beginResidue();

	TEST_EQUAL(resIt->getName(), "PRO")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));
  TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-80.,false));
  ++resIt;
	TEST_EQUAL(resIt->getName(), "PRO")
  TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-12, false));
	TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-80, false));
  ++resIt;
	TEST_EQUAL(resIt->getName(), "PRO")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(28,false));
  TEST_EQUAL(resIt->getTorsionPsi(), 0);
RESULT

//empty sequence
CHECK(construct())
	pb->construct();
  TEST_NOT_EQUAL(pb, 0)
RESULT

PeptideBuilder* pb4=0;
CHECK(PeptideBuilder())
  pb4 = new PeptideBuilder(*pb);
	TEST_NOT_EQUAL(pb, 0)
RESULT

// Proline as first residue
CHECK(~PeptideBuilder() throw())
	delete pb;
	pb = 0;
	delete pb2;
  pb2= 0;
	delete pb3;
  pb3= 0;
	delete pb4;
  pb4= 0;
RESULT

CHECK(~AminoAcidDescriptor() throw())
	delete aad;
  aad = 0;
	delete aad2;
  aad2= 0;
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: PeptideBuilder_test.C,v 1.8 2004/05/10 13:19:22 amoll Exp $

#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/STRUCTURE/peptideBuilder.h>
#include <BALL/STRUCTURE/fragmentDB.h>
#include <vector>

///////////////////////////

START_TEST(PeptideBuilder, "$Id: PeptideBuilder_test.C,v 1.8 2004/05/10 13:19:22 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;
using namespace BALL::Peptides;

PeptideBuilder* pbptr = 0;
CHECK(PeptideBuilder())
	pbptr = new PeptideBuilder;
	TEST_NOT_EQUAL(pbptr, 0)
RESULT

CHECK(~PeptideBuilder())
	delete pbptr;
	pbptr = 0;
RESULT

AminoAcidDescriptor* aad = 0;
CHECK(AminoAcidDescriptor())
	aad = new AminoAcidDescriptor;
	TEST_NOT_EQUAL(aad,0)
RESULT

CHECK(~AminoAcidDescriptor())
	delete aad;
  aad= 0;
RESULT

CHECK(AminoAcidDescriptor(const String& type, const Angle& phi,
													const Angle& psi, const Angle& omega))
	aad= new AminoAcidDescriptor("HIS", Angle(M_PI, true), Angle(M_PI, true));
	TEST_NOT_EQUAL(aad, 0)
	TEST_EQUAL(aad->getType(), "HIS")
	TEST_EQUAL(aad->getPhi(), Angle(M_PI, true))
	TEST_EQUAL(aad->getPsi(), Angle(M_PI, true))
RESULT

AminoAcidDescriptor* aad2=0;
CHECK(AminoAcidDescriptor(const AminoAcidDescriptor& aad))
	aad2 = new AminoAcidDescriptor(*aad);
	TEST_NOT_EQUAL(aad2, 0)
	TEST_EQUAL(aad2->getType(), "HIS")
	TEST_EQUAL(aad2->getPhi(), Angle(M_PI, true))
	TEST_EQUAL(aad2->getPsi(), Angle(M_PI, true))
RESULT

//
// Tests for the complement get and set-methods
//

CHECK(setAminoAcidType(const String& type))
  aad->setAminoAcidType("GLY");
	TEST_EQUAL(aad->getType(),"GLY")
  aad2->setAminoAcidType("V");
	TEST_EQUAL(aad2->getType(),"VAL")
RESULT

CHECK(setPhi(const Angle& phi))
  aad->setPhi(Angle(-47., false));
	TEST_EQUAL(aad->getPhi(), Angle(-47., false) )
  aad2->setPhi(Angle(-77., false));
	TEST_EQUAL(aad2->getPhi(), Angle(-77., false) )
RESULT

CHECK(setPsi(const Angle& phi))
  aad->setPsi(Angle(-58., false));
	TEST_EQUAL(aad->getPsi(), Angle(-58., false) )
  aad2->setPsi(Angle(8.15, false));
	TEST_EQUAL(aad2->getPsi(), Angle(8.15, false) )
RESULT

CHECK(setOmega(const Angle& phi))
  aad->setOmega(Angle(90., false));
	TEST_EQUAL(aad->getOmega(), Angle(90., false))
  aad2->setOmega(Angle(M_PI, true));
	TEST_EQUAL(aad2->getOmega(), Angle(180, false))
RESULT

	/*CHECK(~AminoAcidDescriptor()) used for the addAminoAcid()-Test
	delete aad ;
  aad = 0;
	RESULT*/

//
//   Tests of class PeptideBuilder
//

PeptideBuilder* pb = 0;
CHECK(PeptideBuilder())
  pb= new PeptideBuilder;
	TEST_NOT_EQUAL(pb, 0)
RESULT

//
//CHECK(PeptideBuilder(const std::vector<AminoAcidDescriptor>& sequence)) later on
//

CHECK(addAminoAcid(const String& type, const Angle& phi, const Angle& psi, const Angle& omega))
  pb->addAminoAcid("LEU");
  pb->addAminoAcid("SER",Angle(M_PI, true),Angle(M_PI, true));
	TEST_NOT_EQUAL(pb, 0)
RESULT

CHECK(addAminoAcid(const AminoAcidDescriptor& aad))
  pb->addAminoAcid(*aad);
  pb->addAminoAcid(*aad2);
	TEST_NOT_EQUAL(pb, 0)
RESULT

CHECK(setChainName(const String& name)/getChainName())
  pb->setChainName("TestChainName");
	TEST_EQUAL(pb->getChainName(),"TestChainName")
RESULT

CHECK(setProteinName(const String& name)/getProteinName())
	pb->setProteinName("TestProteinName");
	TEST_EQUAL(pb->getProteinName(),"TestProteinName")
RESULT

PeptideBuilder* pb2 = 0;
CHECK(PeptideBuilder(const PeptideBuilder& pb))
  pb2= new PeptideBuilder(*pb);
	TEST_NOT_EQUAL(pb2, 0)
	TEST_EQUAL(pb2->getChainName(),"TestChainName")
	TEST_EQUAL(pb2->getProteinName(),"TestProteinName")
RESULT

PeptideBuilder* pb3=0;
CHECK(PeptideBuilder(const std::vector<AminoAcidDescriptor>& sequence))
  std::vector<AminoAcidDescriptor> v;
  v.push_back(*aad);
	v.push_back(*aad2);
  pb3 = new PeptideBuilder(v);
  TEST_NOT_EQUAL(pb3, 0)
RESULT

FragmentDB db("");
pb->setFragmentDB(&db);
pb3->setFragmentDB(&db);

CHECK(construct())
	Protein *prot=pb->construct();
	TEST_NOT_EQUAL(prot, 0)
	ResidueIterator resIt;
  resIt = prot->beginResidue();

	PRECISION(1e-3)
	TEST_EQUAL(resIt->getName(), "LEU")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));
  TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-58.,false));
  ++resIt;
	TEST_EQUAL(resIt->getName(), "SER")
  TEST_REAL_EQUAL(fabs(resIt->getTorsionPhi().toRadian()), M_PI)
	TEST_REAL_EQUAL(fabs(resIt->getTorsionPsi().toRadian()), M_PI)
  ++resIt;
	PRECISION(2E-2)
	TEST_EQUAL(resIt->getName(), "GLY")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-47, false))
  TEST_REAL_EQUAL(resIt->getTorsionPsi(), -1.01);
  ++resIt;
	TEST_EQUAL(resIt->getName(), "VAL")
  TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-77., false));
	TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(0, false));
	delete prot;

	prot = pb3->construct();
	TEST_NOT_EQUAL(prot, 0)
  resIt = prot->beginResidue();

	TEST_EQUAL(resIt->getName(), "GLY")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));
  TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-58.,false));
  ++resIt;
	TEST_EQUAL(resIt->getName(), "VAL")
  TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-77.,false));
	TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(0,false));

	PeptideBuilder pb4;
	pb4.setFragmentDB(&db);
	pb4.addAminoAcid("PRO");
	pb4.addAminoAcid("PRO", Angle(-12., false), Angle(42, false));
	pb4.addAminoAcid("PRO", Angle(28, false), Angle(33, false));

	delete prot;
	prot = pb4.construct();

  resIt = prot->beginResidue();

	TEST_EQUAL(resIt->getName(), "PRO")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(0,false));
  TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-80.,false));
  ++resIt;
	TEST_EQUAL(resIt->getName(), "PRO")
  TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(-12, false));
	TEST_REAL_EQUAL(resIt->getTorsionPsi(), Angle(-80, false));
  ++resIt;
	TEST_EQUAL(resIt->getName(), "PRO")
	TEST_REAL_EQUAL(resIt->getTorsionPhi(), Angle(28,false));
  TEST_EQUAL(resIt->getTorsionPsi(), 0);

	delete prot;
RESULT

//empty sequence
CHECK(construct())
	pb->construct();
  TEST_NOT_EQUAL(pb, 0)
RESULT

PeptideBuilder* pb4=0;
CHECK(PeptideBuilder())
  pb4 = new PeptideBuilder(*pb);
	TEST_NOT_EQUAL(pb, 0)
RESULT

// Proline as first residue
CHECK(~PeptideBuilder() throw())
	delete pb;
	pb = 0;
	delete pb2;
  pb2= 0;
	delete pb3;
  pb3= 0;
	delete pb4;
  pb4= 0;
RESULT

CHECK(~AminoAcidDescriptor() throw())
	delete aad;
  aad = 0;
	delete aad2;
  aad2= 0;
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program 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 program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include "processcontrol.h"
#include "akdebug.h"

#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtDebug>

#ifdef Q_OS_UNIX
#include <sys/types.h>
#include <signal.h>
#endif

#ifdef Q_OS_WINCE
#include <windows.h>
#endif

using namespace Akonadi;

static const int s_maxCrashCount = 2;

ProcessControl::ProcessControl( QObject *parent )
  : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ),
  mRestartOnceOnExit( false )
{
  connect( &mProcess, SIGNAL(error(QProcess::ProcessError)),
           this, SLOT(slotError(QProcess::ProcessError)) );
  connect( &mProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
           this, SLOT(slotFinished(int,QProcess::ExitStatus)) );
  mProcess.setProcessChannelMode( QProcess::ForwardedChannels );
}

ProcessControl::~ProcessControl()
{
  stop();
}

void ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy )
{
  mFailedToStart = false;

  mApplication = application;
  mArguments = arguments;
  mPolicy = policy;

  start();
}

void ProcessControl::setCrashPolicy( CrashPolicy policy )
{
  mPolicy = policy;
}

void ProcessControl::stop()
{
  if ( mProcess.state() != QProcess::NotRunning ) {
    mProcess.waitForFinished( 10000 );
    mProcess.terminate();
  }
}

void ProcessControl::slotError( QProcess::ProcessError error )
{
  switch ( error ) {
    case QProcess::Crashed:
      mCrashCount++;
      // do nothing, we'll respawn in slotFinished
      break;
    case QProcess::FailedToStart:
    default:
        mFailedToStart = true;
      break;
  }

  qDebug( "ProcessControl: Application '%s' stopped unexpectedly (%s)",
          qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );
}

void ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus )
{
  if ( exitStatus == QProcess::CrashExit ) {
    if ( mPolicy == RestartOnCrash ) {
      // don't try to start an unstartable application
      if ( !mFailedToStart && mCrashCount <= s_maxCrashCount ) {
        qDebug( "Application '%s' crashed! %d restarts left.", qPrintable( mApplication ), s_maxCrashCount - mCrashCount );
        start();
        emit restarted();
      } else {
        if ( mFailedToStart ) {
          qDebug( "Application '%s' failed to start!", qPrintable( mApplication ) );
        } else {
          qDebug( "Application '%s' crashed too often. Giving up!", qPrintable( mApplication ) );
        }
        mPolicy = StopOnCrash;
        emit unableToStart();
        return;
      }
    } else {
      qDebug( "Application '%s' crashed. No restart!", qPrintable( mApplication ) );
    }
  } else {
    if ( exitCode != 0 ) {
      qDebug( "ProcessControl: Application '%s' returned with exit code %d (%s)",
              qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) );
#ifdef Q_OS_WINCE
	  // If Akonadi server crashed clean the registry key for the local socket.
	  // Qt insertes a regitsry key for each local socket opened and checks if a new
	  // socket is opened if some other socket is already bind, if a appication
	  // crashes the registru key is not deleted and no local socket can be opened
	  // so try to delete the key if it fails once
	  if ( mApplication == "akonadiserver" && exitCode == 1) {
	    HKEY hKey;
        long rc = RegOpenKeyEx (HKEY_CURRENT_USER, TEXT("Software\\Trolltech\\Qt\\QLocalServer"), 0, KEY_ALL_ACCESS, &hKey);
	    if(rc != ERROR_SUCCESS ) {
	      qWarning() << mApplication << "Tried to open HKCU\\Software\\Trolltech\\Qt\\QLocalServer to delete Key Akonadi";
	    } else {
	      rc =  RegDeleteValue( hKey, TEXT("Akonadi") );
          if(rc != ERROR_SUCCESS ) {
            qWarning() << mApplication << "Could not delete HKCU\\Software\\Trolltech\\Qt\\QLocalServer\\Akonadi";
		  }
	    }
	  }
#endif
      if ( mPolicy == RestartOnCrash ) {
        if ( mCrashCount > s_maxCrashCount ) {
          qWarning() << mApplication << "crashed too often and will not be restarted!";
          mPolicy = StopOnCrash;
          emit unableToStart();
          return;
        }
        ++mCrashCount;
        QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) );
        if ( !mFailedToStart ) { // don't try to start an unstartable application
          start();
          emit restarted();
        }
      }
    } else {
      if ( mRestartOnceOnExit ) {
        mRestartOnceOnExit = false;
        qDebug( "Restarting application '%s'.", qPrintable( mApplication ) );
        start();
      } else {
        qDebug( "Application '%s' exited normally...", qPrintable( mApplication ) );
      }
    }
  }
}

void ProcessControl::start()
{
#ifdef Q_OS_UNIX
  QString agentValgrind = getEnv( "AKONADI_VALGRIND" );
  if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) {

    mArguments.prepend( mApplication );
    const QString originalArguments = mArguments.join( QString::fromLocal8Bit( " " ) );
    mApplication = QString::fromLocal8Bit( "valgrind" );

    const QString valgrindSkin = getEnv( "AKONADI_VALGRIND_SKIN", QString::fromLocal8Bit( "memcheck" ) );
    mArguments.prepend( QLatin1String( "--tool=" ) + valgrindSkin );

    const QString valgrindOptions = getEnv( "AKONADI_VALGRIND_OPTIONS" );
    if ( !valgrindOptions.isEmpty() )
      mArguments = valgrindOptions.split( QLatin1Char(' '), QString::SkipEmptyParts ) << mArguments;

    qDebug();
    qDebug() << "============================================================";
    qDebug() << "ProcessControl: Valgrinding process" << originalArguments;
    if ( !valgrindSkin.isEmpty() )
      qDebug() << "ProcessControl: Valgrind skin:" << valgrindSkin;
    if ( !valgrindOptions.isEmpty() )
      qDebug() << "ProcessControl: Additional Valgrind options:" << valgrindOptions;
    qDebug() << "============================================================";
    qDebug();
  }
#endif

  mProcess.start( mApplication, mArguments );
  if ( !mProcess.waitForStarted( ) ) {
    qDebug( "ProcessControl: Unable to start application '%s' (%s)",
            qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );
    emit unableToStart();
    return;
  }

#ifdef Q_OS_UNIX
  else {
    QString agentDebug = QString::fromLocal8Bit( qgetenv( "AKONADI_DEBUG_WAIT" ) );
    pid_t pid = mProcess.pid();
    if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) {
      qDebug();
      qDebug() << "============================================================";
      qDebug() << "ProcessControl: Suspending process" << mApplication;
      qDebug() << "'gdb --pid" << pid << "' to debug";
      qDebug() << "'kill -SIGCONT" << pid << "' to continue";
      qDebug() << "============================================================";
      qDebug();
      kill( pid, SIGSTOP );
    }
  }
#endif
}

void ProcessControl::resetCrashCount()
{
  mCrashCount = 0;
}

bool ProcessControl::isRunning() const
{
  return mProcess.state() != QProcess::NotRunning;
}

#include "processcontrol.moc"
<commit_msg>Also match the process arguments when checking for the agent to valgrind.<commit_after>/***************************************************************************
 *   Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program 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 program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include "processcontrol.h"
#include "akdebug.h"

#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtDebug>

#ifdef Q_OS_UNIX
#include <sys/types.h>
#include <signal.h>
#endif

#ifdef Q_OS_WINCE
#include <windows.h>
#endif

using namespace Akonadi;

static const int s_maxCrashCount = 2;

ProcessControl::ProcessControl( QObject *parent )
  : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ),
  mRestartOnceOnExit( false )
{
  connect( &mProcess, SIGNAL(error(QProcess::ProcessError)),
           this, SLOT(slotError(QProcess::ProcessError)) );
  connect( &mProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
           this, SLOT(slotFinished(int,QProcess::ExitStatus)) );
  mProcess.setProcessChannelMode( QProcess::ForwardedChannels );
}

ProcessControl::~ProcessControl()
{
  stop();
}

void ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy )
{
  mFailedToStart = false;

  mApplication = application;
  mArguments = arguments;
  mPolicy = policy;

  start();
}

void ProcessControl::setCrashPolicy( CrashPolicy policy )
{
  mPolicy = policy;
}

void ProcessControl::stop()
{
  if ( mProcess.state() != QProcess::NotRunning ) {
    mProcess.waitForFinished( 10000 );
    mProcess.terminate();
  }
}

void ProcessControl::slotError( QProcess::ProcessError error )
{
  switch ( error ) {
    case QProcess::Crashed:
      mCrashCount++;
      // do nothing, we'll respawn in slotFinished
      break;
    case QProcess::FailedToStart:
    default:
        mFailedToStart = true;
      break;
  }

  qDebug( "ProcessControl: Application '%s' stopped unexpectedly (%s)",
          qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );
}

void ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus )
{
  if ( exitStatus == QProcess::CrashExit ) {
    if ( mPolicy == RestartOnCrash ) {
      // don't try to start an unstartable application
      if ( !mFailedToStart && mCrashCount <= s_maxCrashCount ) {
        qDebug( "Application '%s' crashed! %d restarts left.", qPrintable( mApplication ), s_maxCrashCount - mCrashCount );
        start();
        emit restarted();
      } else {
        if ( mFailedToStart ) {
          qDebug( "Application '%s' failed to start!", qPrintable( mApplication ) );
        } else {
          qDebug( "Application '%s' crashed too often. Giving up!", qPrintable( mApplication ) );
        }
        mPolicy = StopOnCrash;
        emit unableToStart();
        return;
      }
    } else {
      qDebug( "Application '%s' crashed. No restart!", qPrintable( mApplication ) );
    }
  } else {
    if ( exitCode != 0 ) {
      qDebug( "ProcessControl: Application '%s' returned with exit code %d (%s)",
              qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) );
#ifdef Q_OS_WINCE
	  // If Akonadi server crashed clean the registry key for the local socket.
	  // Qt insertes a regitsry key for each local socket opened and checks if a new
	  // socket is opened if some other socket is already bind, if a appication
	  // crashes the registru key is not deleted and no local socket can be opened
	  // so try to delete the key if it fails once
	  if ( mApplication == "akonadiserver" && exitCode == 1) {
	    HKEY hKey;
        long rc = RegOpenKeyEx (HKEY_CURRENT_USER, TEXT("Software\\Trolltech\\Qt\\QLocalServer"), 0, KEY_ALL_ACCESS, &hKey);
	    if(rc != ERROR_SUCCESS ) {
	      qWarning() << mApplication << "Tried to open HKCU\\Software\\Trolltech\\Qt\\QLocalServer to delete Key Akonadi";
	    } else {
	      rc =  RegDeleteValue( hKey, TEXT("Akonadi") );
          if(rc != ERROR_SUCCESS ) {
            qWarning() << mApplication << "Could not delete HKCU\\Software\\Trolltech\\Qt\\QLocalServer\\Akonadi";
		  }
	    }
	  }
#endif
      if ( mPolicy == RestartOnCrash ) {
        if ( mCrashCount > s_maxCrashCount ) {
          qWarning() << mApplication << "crashed too often and will not be restarted!";
          mPolicy = StopOnCrash;
          emit unableToStart();
          return;
        }
        ++mCrashCount;
        QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) );
        if ( !mFailedToStart ) { // don't try to start an unstartable application
          start();
          emit restarted();
        }
      }
    } else {
      if ( mRestartOnceOnExit ) {
        mRestartOnceOnExit = false;
        qDebug( "Restarting application '%s'.", qPrintable( mApplication ) );
        start();
      } else {
        qDebug( "Application '%s' exited normally...", qPrintable( mApplication ) );
      }
    }
  }
}

static bool listContains( const QStringList &list, const QString &pattern )
{
  foreach ( const QString &s, list ) {
    if ( s.contains( pattern ) )
      return true;
  }
  return false;
}

void ProcessControl::start()
{
#ifdef Q_OS_UNIX
  QString agentValgrind = getEnv( "AKONADI_VALGRIND" );
  if ( !agentValgrind.isEmpty() && (mApplication.contains( agentValgrind ) || listContains( mArguments, agentValgrind )) ) {

    mArguments.prepend( mApplication );
    const QString originalArguments = mArguments.join( QString::fromLocal8Bit( " " ) );
    mApplication = QString::fromLocal8Bit( "valgrind" );

    const QString valgrindSkin = getEnv( "AKONADI_VALGRIND_SKIN", QString::fromLocal8Bit( "memcheck" ) );
    mArguments.prepend( QLatin1String( "--tool=" ) + valgrindSkin );

    const QString valgrindOptions = getEnv( "AKONADI_VALGRIND_OPTIONS" );
    if ( !valgrindOptions.isEmpty() )
      mArguments = valgrindOptions.split( QLatin1Char(' '), QString::SkipEmptyParts ) << mArguments;

    qDebug();
    qDebug() << "============================================================";
    qDebug() << "ProcessControl: Valgrinding process" << originalArguments;
    if ( !valgrindSkin.isEmpty() )
      qDebug() << "ProcessControl: Valgrind skin:" << valgrindSkin;
    if ( !valgrindOptions.isEmpty() )
      qDebug() << "ProcessControl: Additional Valgrind options:" << valgrindOptions;
    qDebug() << "============================================================";
    qDebug();
  }
#endif

  mProcess.start( mApplication, mArguments );
  if ( !mProcess.waitForStarted( ) ) {
    qDebug( "ProcessControl: Unable to start application '%s' (%s)",
            qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );
    emit unableToStart();
    return;
  }

#ifdef Q_OS_UNIX
  else {
    QString agentDebug = QString::fromLocal8Bit( qgetenv( "AKONADI_DEBUG_WAIT" ) );
    pid_t pid = mProcess.pid();
    if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) {
      qDebug();
      qDebug() << "============================================================";
      qDebug() << "ProcessControl: Suspending process" << mApplication;
      qDebug() << "'gdb --pid" << pid << "' to debug";
      qDebug() << "'kill -SIGCONT" << pid << "' to continue";
      qDebug() << "============================================================";
      qDebug();
      kill( pid, SIGSTOP );
    }
  }
#endif
}

void ProcessControl::resetCrashCount()
{
  mCrashCount = 0;
}

bool ProcessControl::isRunning() const
{
  return mProcess.state() != QProcess::NotRunning;
}

#include "processcontrol.moc"
<|endoftext|>


<commit_before>#ifndef GF2_DEPTHIO_HPP
#define GF2_DEPTHIO_HPP

#include <string>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include "Eigen/Dense"

namespace GF2 {
namespace io {

/*! \brief Load a depth image stored as a .dat file.
 *         Assumes, that first two int entries are height and width (in this order).
 * \tparam     FilePixelT The scalar format of the data file Concept: float.
 * \tparam     MatPixelT  The output format of cv::Mat. Concept: ushort.
 * \param[out] mat        Output opencv matrix.
 * \param[in]  path       File path to read from.
 * \param[in]  alpha      Multiplier to apply to each read pixel.
*/
template <typename MatPixelT, typename FilePixelT> inline int
loadDepthAsBinary( ::cv::Mat &mat, std::string path, float alpha = 1.f )
{
    FILE *fp = fopen( path.c_str(), "rb" );
    if (!fp)
    {
        printf( "loadDepthAsBinary failed, when opening %s\n", path.c_str() );
        return false;
    }

    int w,h, read_size = 0;
    read_size += fread( &h,sizeof(int),1,fp );
    read_size += fread( &w,sizeof(int),1,fp );
    if ( read_size != 2 )
    {
        std::cerr << "[" << __func__ << "]: " << "w or h not read properly: " << w << ", " << h << std::endl;
    }

    FilePixelT *p_depth = new FilePixelT[ h * w ];

    read_size = fread( p_depth, sizeof(FilePixelT), w*h, fp );
    if ( read_size != w*h )
        std::cerr << "[" << __func__ << "]: " << "read size != " << w*h << std::endl;

    mat.create( h, w, CV_16UC1 );
    int p_depth_index = 0;
    for ( unsigned y = 0; y < mat.rows; ++y  )
    {
        for ( unsigned x = 0; x < mat.cols; ++x, ++p_depth_index )
        {
            mat.at<MatPixelT>(y,x) = p_depth[ p_depth_index ] * alpha;
        }
    }

    fclose( fp );
    if ( p_depth )
        delete [] p_depth;

    return EXIT_SUCCESS;
} //...loadDepthAsBinary()

/*! \brief Loads a raw, dat or png depth map, and outputs [mm] values.
 *
 *  \param[in] depth_path File path to read depth map from.
 *  \return OpenCV 2D matrix with ushort depth values in [mm].
 */
cv::Mat
loadDepth( std::string depth_path )
{
    cv::Mat dep;
    if ( depth_path.find("raw") != std::string::npos )
    {
        loadDepthAsBinary<ushort,ushort>( dep, depth_path, 1. );
    }
    else if ( depth_path.find("dat") != std::string::npos )
    {
        // NYU, read float, and convert it to ushort
        loadDepthAsBinary<ushort,float>( dep, depth_path, 1000. );
    }
    else
    {
        dep = cv::imread( depth_path, cv::IMREAD_UNCHANGED );
    }

    return dep;
} //...loadDepth()

// Aron's kinect calibration
#define FX_D 588.486898
#define FY_D 588.729416
#define CX_D 314.509516
#define CY_D 242.997237
#define K1_D -0.094563
#define K2_D 0.387595
#define P1_D 0.000838
#define P2_D 0.001505
#define K3_D -0.494912
#define ALPHA_D -0.002096

template <typename _Scalar>
struct Intrinsics
{
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    typedef _Scalar Scalar;
    enum CALIB_ID { TIANJIAS, ARONS, /*ARONS_WDISTORTION,*/ RGBDEMOS };

    inline Intrinsics( CALIB_ID calib_id = ARONS )
    {
         switch ( calib_id )
         {
             case ARONS:
                 _intrinsics << FX_D, 0., CX_D,
                                0., FY_D, CY_D,
                                0., 0., 1.;
                 break;
             case TIANJIAS:
                 _intrinsics << 5.1930334103339817e+02, 0., 3.2850951551345941e+02,
                                0., 5.1816401430246583e+02, 2.5282555217253503e+02,
                                0., 0., 1.;
                 break;
             case RGBDEMOS:
                 _intrinsics << 5.4013644168716110e+02, 0., 320.,
                                0., 5.4013644168716110e+02, 240.,
                                0., 0., 1.;
                 break;
         }
    }

    inline Intrinsics( Scalar fx, Scalar fy, Scalar cx, Scalar cy )
        : _intrinsics( (Eigen::Matrix<Scalar,3,3>() <<
                        fx, 0., cx,
                        0., fy, cy,
                        0., 0., 1.).finished() ) {}
    operator Eigen::Matrix<_Scalar,3,3>() { return _intrinsics; }
    protected:
        Eigen::Matrix<Scalar,3,3> _intrinsics;
};

template <typename _Scalar> inline Eigen::Matrix<_Scalar,3,1>
point2To3D( Eigen::Matrix<_Scalar,2,1> const& pnt2, Eigen::Matrix<_Scalar,3,3> const& intrinsics )
{
    return (Eigen::Matrix<_Scalar,3,1>() << (pnt2(0) - intrinsics(0,2)) / intrinsics(0,0), // (x - cx) / fx
                                            (pnt2(1) - intrinsics(1,2)) / intrinsics(1,1), // (y - cy) / fy
                                            1.f ).finished();
}

/*! \brief Decides, if a depth map pixel is a valid 3D point.
 *  \return true, if depth > 20cm. (> 0.2)
 */
template <typename _Scalar>
inline bool isValidDepth( _Scalar d )
{
    if ( d > _Scalar(10.) ) std::cerr << "[" << __func__ << "]: " << "Depth values are assumed to be between 0..10, and not " << d << std::endl;

    return d > _Scalar(.2);
}

/*! \brief Merges a depth image and an optional rgb image to a point cloud.
 */
template <typename depT, typename _Scalar, typename _PclCloudT>
inline int rgbd2PointCloud( _PclCloudT                                     & pcl_cloud
                          , cv::Mat                                   const& dep
                          , cv::Mat                                   const& img
                          , _Scalar                                   const  alpha      = 1. / 1000.
                          , Eigen::Matrix<_Scalar,3,3>                const& intrinsics = Intrinsics<_Scalar>()
                          , Eigen::Transform<_Scalar,3,Eigen::Affine> const* pose       = NULL
                          )
{
    typedef Eigen::Matrix<_Scalar,3,1>            Position;
    typedef typename _PclCloudT::PointType        PclPointT;
    //typedef typename _PointContainerT::value_type PointPrimitiveT;

    // check inputs to be the same size
    if ( !img.empty() )
    {
        if ( dep.size() != img.size() )
        {
            std::cerr << "matsTo3D(): dep and rgb need the same size! "
                      << dep.rows << "x" << dep.cols << ", "
                      << img.rows << "x" << img.cols << std::endl;
            return EXIT_FAILURE;
        }
    }

    // check image dimensions
    if ( (!img.empty()) && (img.channels() != 3) )
    {
        std::cerr << "matsTo3D(): rgb should be 3 channels! " << img.channels() << std::endl;
        return EXIT_FAILURE;
    }

    // allocate ouptut
    //points = PCloud::Ptr( new PCloud );
//    pcl_cloud.clear();
//    pcl_cloud.reserve( img.cols * img.rows );

    // point to read to, and insert
    Position pnt3D;
    uint32_t rgb = 128 << 16 | 128 << 8 | 128;

    Eigen::Matrix<_Scalar,3,3> rotation;
    Eigen::Matrix<_Scalar,3,1> translation;
    if ( pose )
    {
        rotation    = pose->rotation();
        translation = pose->translation();
    }

    // copy inputs
    for ( int y = 0; y < dep.rows; ++y )
    {
        for ( int x = 0; x < dep.cols; ++x )
        {
            //  read depth
            float depth = (_Scalar)dep.at<depT>( y,x ) * alpha;
            // check validity
            bool isValid = isValidDepth( depth );
            if ( !isValid )
                continue;

            // calculate point
            pnt3D = point2To3D( (Eigen::Matrix<_Scalar,2,1>() << x,y).finished(), intrinsics ) * depth;

            // apply pose
            if ( pose )
                pnt3D = rotation * pnt3D + translation;

#if 0
            pcl_cloud.push_back( PointPrimitiveT( /* pos: */ pnt3D, /* dir: */ (Position()<<1.,1.,1.).finished()) );
#else
            // convert
            PclPointT point;
            point.x = pnt3D( 0 );
            point.y = pnt3D( 1 );
            point.z = pnt3D( 2 );

            // add colour
            if ( !img.empty() )
            {
                rgb = (static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() + 2)) << 16 |
                       static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() + 1)) << 8  |
                       static_cast<uint32_t>(img.at<uchar>(y, x * img.channels()    ))        );
            }
            point.rgb = *reinterpret_cast<float*>( &rgb );

            // add point
            pcl_cloud.push_back( point );
#endif
        }
    }

    //points->width = (int)points->points.size ();
    //points->height = 1;

    return EXIT_SUCCESS;

} // matsTo3D

} //...ns io
} //...ns GF2

#endif // GF2_DEPTHIO_HPP
<commit_msg>Fix wrong includes<commit_after>#ifndef GF2_DEPTHIO_HPP
#define GF2_DEPTHIO_HPP

#include <string>
#include <opencv2/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "Eigen/Dense"

namespace GF2 {
namespace io {

/*! \brief Load a depth image stored as a .dat file.
 *         Assumes, that first two int entries are height and width (in this order).
 * \tparam     FilePixelT The scalar format of the data file Concept: float.
 * \tparam     MatPixelT  The output format of cv::Mat. Concept: ushort.
 * \param[out] mat        Output opencv matrix.
 * \param[in]  path       File path to read from.
 * \param[in]  alpha      Multiplier to apply to each read pixel.
*/
template <typename MatPixelT, typename FilePixelT> inline int
loadDepthAsBinary( ::cv::Mat &mat, std::string path, float alpha = 1.f )
{
    FILE *fp = fopen( path.c_str(), "rb" );
    if (!fp)
    {
        printf( "loadDepthAsBinary failed, when opening %s\n", path.c_str() );
        return false;
    }

    int w,h, read_size = 0;
    read_size += fread( &h,sizeof(int),1,fp );
    read_size += fread( &w,sizeof(int),1,fp );
    if ( read_size != 2 )
    {
        std::cerr << "[" << __func__ << "]: " << "w or h not read properly: " << w << ", " << h << std::endl;
    }

    FilePixelT *p_depth = new FilePixelT[ h * w ];

    read_size = fread( p_depth, sizeof(FilePixelT), w*h, fp );
    if ( read_size != w*h )
        std::cerr << "[" << __func__ << "]: " << "read size != " << w*h << std::endl;

    mat.create( h, w, CV_16UC1 );
    int p_depth_index = 0;
    for ( unsigned y = 0; y < mat.rows; ++y  )
    {
        for ( unsigned x = 0; x < mat.cols; ++x, ++p_depth_index )
        {
            mat.at<MatPixelT>(y,x) = p_depth[ p_depth_index ] * alpha;
        }
    }

    fclose( fp );
    if ( p_depth )
        delete [] p_depth;

    return EXIT_SUCCESS;
} //...loadDepthAsBinary()

/*! \brief Loads a raw, dat or png depth map, and outputs [mm] values.
 *
 *  \param[in] depth_path File path to read depth map from.
 *  \return OpenCV 2D matrix with ushort depth values in [mm].
 */
cv::Mat
loadDepth( std::string depth_path )
{
    cv::Mat dep;
    if ( depth_path.find("raw") != std::string::npos )
    {
        loadDepthAsBinary<ushort,ushort>( dep, depth_path, 1. );
    }
    else if ( depth_path.find("dat") != std::string::npos )
    {
        // NYU, read float, and convert it to ushort
        loadDepthAsBinary<ushort,float>( dep, depth_path, 1000. );
    }
    else
    {
        dep = cv::imread( depth_path, cv::IMREAD_UNCHANGED );
    }

    return dep;
} //...loadDepth()

// Aron's kinect calibration
#define FX_D 588.486898
#define FY_D 588.729416
#define CX_D 314.509516
#define CY_D 242.997237
#define K1_D -0.094563
#define K2_D 0.387595
#define P1_D 0.000838
#define P2_D 0.001505
#define K3_D -0.494912
#define ALPHA_D -0.002096

template <typename _Scalar>
struct Intrinsics
{
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    typedef _Scalar Scalar;
    enum CALIB_ID { TIANJIAS, ARONS, /*ARONS_WDISTORTION,*/ RGBDEMOS };

    inline Intrinsics( CALIB_ID calib_id = ARONS )
    {
         switch ( calib_id )
         {
             case ARONS:
                 _intrinsics << FX_D, 0., CX_D,
                                0., FY_D, CY_D,
                                0., 0., 1.;
                 break;
             case TIANJIAS:
                 _intrinsics << 5.1930334103339817e+02, 0., 3.2850951551345941e+02,
                                0., 5.1816401430246583e+02, 2.5282555217253503e+02,
                                0., 0., 1.;
                 break;
             case RGBDEMOS:
                 _intrinsics << 5.4013644168716110e+02, 0., 320.,
                                0., 5.4013644168716110e+02, 240.,
                                0., 0., 1.;
                 break;
         }
    }

    inline Intrinsics( Scalar fx, Scalar fy, Scalar cx, Scalar cy )
        : _intrinsics( (Eigen::Matrix<Scalar,3,3>() <<
                        fx, 0., cx,
                        0., fy, cy,
                        0., 0., 1.).finished() ) {}
    operator Eigen::Matrix<_Scalar,3,3>() { return _intrinsics; }
    protected:
        Eigen::Matrix<Scalar,3,3> _intrinsics;
};

template <typename _Scalar> inline Eigen::Matrix<_Scalar,3,1>
point2To3D( Eigen::Matrix<_Scalar,2,1> const& pnt2, Eigen::Matrix<_Scalar,3,3> const& intrinsics )
{
    return (Eigen::Matrix<_Scalar,3,1>() << (pnt2(0) - intrinsics(0,2)) / intrinsics(0,0), // (x - cx) / fx
                                            (pnt2(1) - intrinsics(1,2)) / intrinsics(1,1), // (y - cy) / fy
                                            1.f ).finished();
}

/*! \brief Decides, if a depth map pixel is a valid 3D point.
 *  \return true, if depth > 20cm. (> 0.2)
 */
template <typename _Scalar>
inline bool isValidDepth( _Scalar d )
{
    if ( d > _Scalar(10.) ) std::cerr << "[" << __func__ << "]: " << "Depth values are assumed to be between 0..10, and not " << d << std::endl;

    return d > _Scalar(.2);
}

/*! \brief Merges a depth image and an optional rgb image to a point cloud.
 */
template <typename depT, typename _Scalar, typename _PclCloudT>
inline int rgbd2PointCloud( _PclCloudT                                     & pcl_cloud
                          , cv::Mat                                   const& dep
                          , cv::Mat                                   const& img
                          , _Scalar                                   const  alpha      = 1. / 1000.
                          , Eigen::Matrix<_Scalar,3,3>                const& intrinsics = Intrinsics<_Scalar>()
                          , Eigen::Transform<_Scalar,3,Eigen::Affine> const* pose       = NULL
                          )
{
    typedef Eigen::Matrix<_Scalar,3,1>            Position;
    typedef typename _PclCloudT::PointType        PclPointT;
    //typedef typename _PointContainerT::value_type PointPrimitiveT;

    // check inputs to be the same size
    if ( !img.empty() )
    {
        if ( dep.size() != img.size() )
        {
            std::cerr << "matsTo3D(): dep and rgb need the same size! "
                      << dep.rows << "x" << dep.cols << ", "
                      << img.rows << "x" << img.cols << std::endl;
            return EXIT_FAILURE;
        }
    }

    // check image dimensions
    if ( (!img.empty()) && (img.channels() != 3) )
    {
        std::cerr << "matsTo3D(): rgb should be 3 channels! " << img.channels() << std::endl;
        return EXIT_FAILURE;
    }

    // allocate ouptut
    //points = PCloud::Ptr( new PCloud );
//    pcl_cloud.clear();
//    pcl_cloud.reserve( img.cols * img.rows );

    // point to read to, and insert
    Position pnt3D;
    uint32_t rgb = 128 << 16 | 128 << 8 | 128;

    Eigen::Matrix<_Scalar,3,3> rotation;
    Eigen::Matrix<_Scalar,3,1> translation;
    if ( pose )
    {
        rotation    = pose->rotation();
        translation = pose->translation();
    }

    // copy inputs
    for ( int y = 0; y < dep.rows; ++y )
    {
        for ( int x = 0; x < dep.cols; ++x )
        {
            //  read depth
            float depth = (_Scalar)dep.at<depT>( y,x ) * alpha;
            // check validity
            bool isValid = isValidDepth( depth );
            if ( !isValid )
                continue;

            // calculate point
            pnt3D = point2To3D( (Eigen::Matrix<_Scalar,2,1>() << x,y).finished(), intrinsics ) * depth;

            // apply pose
            if ( pose )
                pnt3D = rotation * pnt3D + translation;

#if 0
            pcl_cloud.push_back( PointPrimitiveT( /* pos: */ pnt3D, /* dir: */ (Position()<<1.,1.,1.).finished()) );
#else
            // convert
            PclPointT point;
            point.x = pnt3D( 0 );
            point.y = pnt3D( 1 );
            point.z = pnt3D( 2 );

            // add colour
            if ( !img.empty() )
            {
                rgb = (static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() + 2)) << 16 |
                       static_cast<uint32_t>(img.at<uchar>(y, x * img.channels() + 1)) << 8  |
                       static_cast<uint32_t>(img.at<uchar>(y, x * img.channels()    ))        );
            }
            point.rgb = *reinterpret_cast<float*>( &rgb );

            // add point
            pcl_cloud.push_back( point );
#endif
        }
    }

    //points->width = (int)points->points.size ();
    //points->height = 1;

    return EXIT_SUCCESS;

} // matsTo3D

} //...ns io
} //...ns GF2

#endif // GF2_DEPTHIO_HPP
<|endoftext|>


<commit_before>#include<bits/stdc++.h>
using namespace std;
int main(){
	//freopen("1.in","r",stdin);
	//freopen("1.out","w",stdout);
    int n=10;//n 是人數
    while(cin>>n){
        int num[55]={1},list[55]={0};//num 是紀錄用 //list 為死亡順序 index 從一開始
		int j=0,number=0,s=0,t;//number 是死亡人數，j 為報數用
		for (int i=1;i<=n;i++)num[i]=1;//重置狀態 1 為活者
        t=n;
		while (number<n){
            for (int i=1;i<=n;i++){
                if (num[i]==1){
                    j++;
                    if (j==2){//滿足自殺報數
                        num[i]=0;
						list[++s]=i;
                        j=0;
                        number++;
                    }
                }
            }
        }
		cout<<list[t]<<endl;
    }
}
<commit_msg>Update 1004.cpp<commit_after>#include<bits/stdc++.h>
using namespace std;
int main(){
	//freopen("1.in","r",stdin);
	//freopen("1.out","w",stdout);
    int n=10;//n 是人數
    while(cin>>n){
        int num[55]={1},list[55]={0};//num 是紀錄用 //list 為死亡順序 index 從一開始
	int j=0,number=0,s=0,t;//number 是死亡人數，j 為報數用
	for (int i=1;i<=n;i++)num[i]=1;//重置狀態 1 為活者
        t=n;
	while (number<n){
            for (int i=1;i<=n;i++){
                if (num[i]==1){
                    j++;
                    if (j==2){//滿足自殺報數
                        num[i]=0;
			list[++s]=i;
                        j=0;
                        number++;
                    }
                }
            }
        }
	cout<<list[t]<<endl;
    }
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
// cmd_rescue.cc
//
//////////////////////////////////////////////////////////////////////////

#include "stdsneezy.h"

static int rescue(TBeing * caster, TBeing * victim, spellNumT skill)
{
  TBeing *tmp_ch = NULL;
  int percent = 0;

  if (caster->getCombatMode() == ATTACK_BERSERK) {
    caster->sendTo("You are berserking! You can't focus enough to rescue anyone!\n\r");
    return FALSE;
  }

  if (caster->checkPeaceful("No one should need rescuing here.\n\r"))
    return FALSE;

  if (victim == caster) {
    caster->sendTo("What about fleeing instead?\n\r");
    return FALSE;
  }
  if (dynamic_cast<TBeing *>(victim->riding)) {
    caster->sendTo("You can't rescue a mounted person!\n\r");
    return FALSE;
  }
  if (victim->riding) {
    caster->sendTo(COLOR_MOBS, fmt("You can't rescue %s off of %s!\n\r") %
         victim->getName() % victim->riding->getName());
    return FALSE;
  }
  if (!victim->isPc() && !victim->isPet(PETTYPE_PET | PETTYPE_CHARM | PETTYPE_THRALL)) {
    caster->sendTo("You can only rescue PCs or pets.\n\r");
    return FALSE;
  }

  if (caster->fight() == victim) {
    caster->sendTo("How can you rescue someone you are trying to kill?\n\r");
    return FALSE;
  }
#if 0
  if (!caster->inGroup(*victim)) {
    act("You need to be a part of $S group to rescue $N.",
             FALSE, caster, 0, victim, TO_CHAR);
    return FALSE;
  }
#endif

  TThing *t;
  for (t = victim->roomp->getStuff(); t; t = t->nextThing, tmp_ch = NULL) {
    tmp_ch = dynamic_cast<TBeing *>(t);
    if (!tmp_ch)
      continue;
    if (tmp_ch->fight() == victim)
      break;
  }

  if (!tmp_ch) {
    act("But nobody is fighting $M?", FALSE, caster, 0, victim, TO_CHAR);
    return FALSE;
  }

  // int level = caster->getSkillLevel(skill);
  int bKnown = caster->getSkillValue(skill);

  if (bSuccess(caster, bKnown + percent, skill)) {
    caster->sendTo("Banzai! To the rescue...\n\r");
    act("You are rescued by $N, you are confused!",
         FALSE, victim, 0, caster, TO_CHAR);
    act("$n heroically rescues $N.", FALSE, caster, 0, victim, TO_NOTVICT);

    if (victim->fight() == tmp_ch)
      victim->stopFighting();
    if (tmp_ch->fight())
      tmp_ch->stopFighting();
    if (caster->fight())
      caster->stopFighting();

    caster->setCharFighting(tmp_ch);
    caster->setVictFighting(tmp_ch);

    victim->addToWait(combatRound(1));

    if (tmp_ch->GetMaxLevel() >= victim->GetMaxLevel()) {
      if (caster->getFactionTarget() != victim) {
        caster->reconcileHelp(victim, discArray[skill]->alignMod);
        caster->setFactionTarget(victim);
      } else {
        // rescuing over and over, or rescuing back and forth
        // let it help some but not as much
        caster->reconcileHelp(victim, discArray[skill]->alignMod/4.0);
      }
    }
    return TRUE;
  } else {
    caster->sendTo("You fail the rescue.\n\r");
    act("$n attempts to rescue you, but fails miserably.",
       FALSE, caster, 0, victim, TO_VICT);
    act("$n attempts to rescue $N, but fails miserably.",
       FALSE, caster, 0, victim, TO_NOTVICT);

    // start them fighting at least
    if (!caster->fight())
      caster->setCharFighting(tmp_ch);
  }
  return TRUE;
}

int TBeing::doRescue(const char *argument)
{
  int rc;
  TBeing *victim;
  char name_buf[240];

  spellNumT skill = getSkillNum(SKILL_RESCUE);

  if (checkBusy())
    return FALSE;

  if (!doesKnowSkill(skill)) {
    sendTo("You know nothing about rescuing.\n\r");
    return FALSE;
  }

  // Default to the first PC group member who is currently tanking, or the first mobile group member if no PC is.
  if (isAffected(AFF_GROUP) && (!argument || !*argument) && (followers || (master && master->followers))) {
    followData * tFData    = (master ? master->followers : followers);
    TBeing     * tRescueMe = NULL,
               * tMaybeMe  = NULL;

    for (; tFData; tFData = tFData->next)
      if (tFData->follower && tFData->follower->isAffected(AFF_GROUP) && canSee(tFData->follower) && tFData->follower->fight() && (tFData->follower->fight()->fight() == tFData->follower) && (tFData->follower != this)) {
        if (tFData->follower->isPc()) {
          tRescueMe = tFData->follower;
          break;
        } else if (!tMaybeMe)
          tMaybeMe = tFData->follower;
      }

    if (!tRescueMe && tMaybeMe)
      tRescueMe = tMaybeMe;

    if (tRescueMe) {
      strcpy(name_buf, tRescueMe->name);

      while (strchr(name_buf, ' '))
        *strchr(name_buf, ' ') = '-';
    }
  } else
    strcpy(name_buf, argument);

  if (!(victim = get_char_room_vis(this, name_buf))) {
    sendTo("Whom do you want to rescue?\n\r");
    return FALSE;
  }
  if (!sameRoom(*victim)) {
    sendTo("That person isn't around.\n\r");
    return FALSE;
  }
  rc = rescue(this, victim, skill);
  if (rc)
    addSkillLag(skill, rc);
  if (IS_SET_DELETE(rc, DELETE_THIS))
    return DELETE_THIS;

  return rc;
}

<commit_msg>Modified the rescue code some more to pass the TBeing of the rescue target instead of the name of.  Also changed it slighly so it can also be used to save the 'master' of the rescuer.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
// cmd_rescue.cc
//
//////////////////////////////////////////////////////////////////////////

#include "stdsneezy.h"

static int rescue(TBeing * caster, TBeing * victim, spellNumT skill)
{
  TBeing *tmp_ch = NULL;
  int percent = 0;

  if (caster->getCombatMode() == ATTACK_BERSERK) {
    caster->sendTo("You are berserking! You can't focus enough to rescue anyone!\n\r");
    return FALSE;
  }

  if (caster->checkPeaceful("No one should need rescuing here.\n\r"))
    return FALSE;

  if (victim == caster) {
    caster->sendTo("What about fleeing instead?\n\r");
    return FALSE;
  }
  if (dynamic_cast<TBeing *>(victim->riding)) {
    caster->sendTo("You can't rescue a mounted person!\n\r");
    return FALSE;
  }
  if (victim->riding) {
    caster->sendTo(COLOR_MOBS, fmt("You can't rescue %s off of %s!\n\r") %
         victim->getName() % victim->riding->getName());
    return FALSE;
  }
  if (!victim->isPc() && !victim->isPet(PETTYPE_PET | PETTYPE_CHARM | PETTYPE_THRALL)) {
    caster->sendTo("You can only rescue PCs or pets.\n\r");
    return FALSE;
  }

  if (caster->fight() == victim) {
    caster->sendTo("How can you rescue someone you are trying to kill?\n\r");
    return FALSE;
  }
#if 0
  if (!caster->inGroup(*victim)) {
    act("You need to be a part of $S group to rescue $N.",
             FALSE, caster, 0, victim, TO_CHAR);
    return FALSE;
  }
#endif

  TThing *t;
  for (t = victim->roomp->getStuff(); t; t = t->nextThing, tmp_ch = NULL) {
    tmp_ch = dynamic_cast<TBeing *>(t);
    if (!tmp_ch)
      continue;
    if (tmp_ch->fight() == victim)
      break;
  }

  if (!tmp_ch) {
    act("But nobody is fighting $M?", FALSE, caster, 0, victim, TO_CHAR);
    return FALSE;
  }

  // int level = caster->getSkillLevel(skill);
  int bKnown = caster->getSkillValue(skill);

  if (bSuccess(caster, bKnown + percent, skill)) {
    caster->sendTo("Banzai! To the rescue...\n\r");
    act("You are rescued by $N, you are confused!",
         FALSE, victim, 0, caster, TO_CHAR);
    act("$n heroically rescues $N.", FALSE, caster, 0, victim, TO_NOTVICT);

    if (victim->fight() == tmp_ch)
      victim->stopFighting();
    if (tmp_ch->fight())
      tmp_ch->stopFighting();
    if (caster->fight())
      caster->stopFighting();

    caster->setCharFighting(tmp_ch);
    caster->setVictFighting(tmp_ch);

    victim->addToWait(combatRound(1));

    if (tmp_ch->GetMaxLevel() >= victim->GetMaxLevel()) {
      if (caster->getFactionTarget() != victim) {
        caster->reconcileHelp(victim, discArray[skill]->alignMod);
        caster->setFactionTarget(victim);
      } else {
        // rescuing over and over, or rescuing back and forth
        // let it help some but not as much
        caster->reconcileHelp(victim, discArray[skill]->alignMod/4.0);
      }
    }
    return TRUE;
  } else {
    caster->sendTo("You fail the rescue.\n\r");
    act("$n attempts to rescue you, but fails miserably.",
       FALSE, caster, 0, victim, TO_VICT);
    act("$n attempts to rescue $N, but fails miserably.",
       FALSE, caster, 0, victim, TO_NOTVICT);

    // start them fighting at least
    if (!caster->fight())
      caster->setCharFighting(tmp_ch);
  }
  return TRUE;
}

int TBeing::doRescue(const char *argument)
{
  int rc;
  TBeing *victim = NULL;
  char name_buf[240];

  spellNumT skill = getSkillNum(SKILL_RESCUE);

  if (checkBusy())
    return FALSE;

  if (!doesKnowSkill(skill)) {
    sendTo("You know nothing about rescuing.\n\r");
    return FALSE;
  }

  // Default to the first PC group member who is currently tanking, or the first mobile group member if no PC is.
  if (isAffected(AFF_GROUP) && (!argument || !*argument) && (followers || (master && master->followers))) {
    followData * tFData    = (master ? master->followers : followers);
    TBeing     * tRescueMe = NULL,
               * tMaybeMe  = NULL;

    if (master && master->isAffected(AFF_GROUP) && sameRoom(*master) && canSee(master) && master->fight() && (master->fight()->fight() == master))
      tRescueMe = master;
    else
      for (; tFData; tFData = tFData->next)
        if (tFData->follower && tFData->follower->isAffected(AFF_GROUP) && canSee(tFData->follower) && tFData->follower->fight() && (tFData->follower->fight()->fight() == tFData->follower) && (tFData->follower != this) && sameRoom(*tFData->follower)) {
          if (tFData->follower->isPc()) {
            tRescueMe = tFData->follower;
            break;
          } else if (!tMaybeMe)
            tMaybeMe = tFData->follower;
        }

    if (!tRescueMe && tMaybeMe)
      tRescueMe = tMaybeMe;

    victim = tRescueMe; // Since this is NULL'ed above we are safe doing this without a check.
  } else
    strcpy(name_buf, argument);

  if (!victim)
    if (!(victim = get_char_room_vis(this, name_buf))) {
      sendTo("Whom do you want to rescue?\n\r");
      return FALSE;
    }

  if (!sameRoom(*victim)) {
    sendTo("That person isn't around.\n\r");
    return FALSE;
  }

  rc = rescue(this, victim, skill);

  if (rc)
    addSkillLag(skill, rc);

  if (IS_SET_DELETE(rc, DELETE_THIS))
    return DELETE_THIS;

  return rc;
}

<|endoftext|>