<commit_before>#include "walletmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "ui_interface.h"
#include "wallet.h"
#include "walletdb.h" // for BackupWallet

#include <QSet>

WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0),
    transactionTableModel(0),
    cachedBalance(0), cachedUnconfirmedBalance(0), cachedNumTransactions(0),
    cachedEncryptionStatus(Unencrypted)
{
    addressTableModel = new AddressTableModel(wallet, this);
    transactionTableModel = new TransactionTableModel(wallet, this);
}

qint64 WalletModel::getBalance() const
{
    return wallet->GetBalance();
}

qint64 WalletModel::getUnconfirmedBalance() const
{
    return wallet->GetUnconfirmedBalance();
}

int WalletModel::getNumTransactions() const
{
    int numTransactions = 0;
    {
        LOCK(wallet->cs_wallet);
        numTransactions = wallet->mapWallet.size();
    }
    return numTransactions;
}

void WalletModel::update()
{
    qint64 newBalance = getBalance();
    qint64 newUnconfirmedBalance = getUnconfirmedBalance();
    int newNumTransactions = getNumTransactions();
    EncryptionStatus newEncryptionStatus = getEncryptionStatus();

    if(cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance)
        emit balanceChanged(newBalance, newUnconfirmedBalance);

    if(cachedNumTransactions != newNumTransactions)
        emit numTransactionsChanged(newNumTransactions);

    if(cachedEncryptionStatus != newEncryptionStatus)
        emit encryptionStatusChanged(newEncryptionStatus);

    cachedBalance = newBalance;
    cachedUnconfirmedBalance = newUnconfirmedBalance;
    cachedNumTransactions = newNumTransactions;

    addressTableModel->update();
}

void WalletModel::updateAddressList()
{
    addressTableModel->update();
}

bool WalletModel::validateAddress(const QString &address)
{
    CBitcoinAddress addressParsed(address.toStdString());
    return addressParsed.IsValid();
}

WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients)
{
    qint64 total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    if(total > getBalance())
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > getBalance())
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        // Sendmany
        std::vector<std::pair<CScript, int64> > vecSend;
        foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetBitcoinAddress(rcp.address.toStdString());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        int64 nFeeRequired = 0;
        bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);

        if(!fCreated)
        {
            if((total + nFeeRequired) > wallet->GetBalance())
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }
        if(!ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
    }

    // Add addresses that we've sent to to the address book
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        std::string strAddress = rcp.address.toStdString();
        {
            LOCK(wallet->cs_wallet);
            if (!wallet->mapAddressBook.count(strAddress))
                wallet->SetAddressBookName(strAddress, rcp.label.toStdString());
        }
    }

    return SendCoinsReturn(OK, 0, hex);
}

OptionsModel *WalletModel::getOptionsModel()
{
    return optionsModel;
}

AddressTableModel *WalletModel::getAddressTableModel()
{
    return addressTableModel;
}

TransactionTableModel *WalletModel::getTransactionTableModel()
{
    return transactionTableModel;
}

WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
{
    if(!wallet->IsCrypted())
    {
        return Unencrypted;
    }
    else if(wallet->IsLocked())
    {
        return Locked;
    }
    else
    {
        return Unlocked;
    }
}

bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
{
    if(encrypted)
    {
        // Encrypt
        return wallet->EncryptWallet(passphrase);
    }
    else
    {
        // Decrypt -- TODO; not supported yet
        return false;
    }
}

bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
{
    if(locked)
    {
        // Lock
        return wallet->Lock();
    }
    else
    {
        // Unlock
        return wallet->Unlock(passPhrase);
    }
}

bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
{
    bool retval;
    {
        LOCK(wallet->cs_wallet);
        wallet->Lock(); // Make sure wallet is locked before attempting pass change
        retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
    }
    return retval;
}

bool WalletModel::backupWallet(const QString &filename)
{
    return BackupWallet(*wallet, filename.toLocal8Bit().data());
}

// WalletModel::UnlockContext implementation
WalletModel::UnlockContext WalletModel::requestUnlock()
{
    bool was_locked = getEncryptionStatus() == Locked;
    if(was_locked)
    {
        // Request UI to unlock wallet
        emit requireUnlock();
    }
    // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
    bool valid = getEncryptionStatus() != Locked;

    return UnlockContext(this, valid, was_locked);
}

WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
        wallet(wallet),
        valid(valid),
        relock(relock)
{
}

WalletModel::UnlockContext::~UnlockContext()
{
    if(valid && relock)
    {
        wallet->setWalletLocked(true);
    }
}

void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
{
    // Transfer context; old object no longer relocks wallet
    *this = rhs;
    rhs.relock = false;
}
<commit_msg>Fix critical UI performance issue (#1154)<commit_after>#include "walletmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"

#include "ui_interface.h"
#include "wallet.h"
#include "walletdb.h" // for BackupWallet

#include <QSet>

WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) :
    QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0),
    transactionTableModel(0),
    cachedBalance(0), cachedUnconfirmedBalance(0), cachedNumTransactions(0),
    cachedEncryptionStatus(Unencrypted)
{
    addressTableModel = new AddressTableModel(wallet, this);
    transactionTableModel = new TransactionTableModel(wallet, this);
}

qint64 WalletModel::getBalance() const
{
    return wallet->GetBalance();
}

qint64 WalletModel::getUnconfirmedBalance() const
{
    return wallet->GetUnconfirmedBalance();
}

int WalletModel::getNumTransactions() const
{
    int numTransactions = 0;
    {
        LOCK(wallet->cs_wallet);
        numTransactions = wallet->mapWallet.size();
    }
    return numTransactions;
}

void WalletModel::update()
{
    qint64 newBalance = getBalance();
    qint64 newUnconfirmedBalance = getUnconfirmedBalance();
    int newNumTransactions = getNumTransactions();
    EncryptionStatus newEncryptionStatus = getEncryptionStatus();

    if(cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance)
        emit balanceChanged(newBalance, newUnconfirmedBalance);

    if(cachedNumTransactions != newNumTransactions)
        emit numTransactionsChanged(newNumTransactions);

    if(cachedEncryptionStatus != newEncryptionStatus)
        emit encryptionStatusChanged(newEncryptionStatus);

    cachedBalance = newBalance;
    cachedUnconfirmedBalance = newUnconfirmedBalance;
    cachedNumTransactions = newNumTransactions;
}

void WalletModel::updateAddressList()
{
    addressTableModel->update();
}

bool WalletModel::validateAddress(const QString &address)
{
    CBitcoinAddress addressParsed(address.toStdString());
    return addressParsed.IsValid();
}

WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients)
{
    qint64 total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    if(total > getBalance())
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > getBalance())
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        // Sendmany
        std::vector<std::pair<CScript, int64> > vecSend;
        foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetBitcoinAddress(rcp.address.toStdString());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        int64 nFeeRequired = 0;
        bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);

        if(!fCreated)
        {
            if((total + nFeeRequired) > wallet->GetBalance())
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }
        if(!ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
    }

    // Add addresses that we've sent to to the address book
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        std::string strAddress = rcp.address.toStdString();
        {
            LOCK(wallet->cs_wallet);
            if (!wallet->mapAddressBook.count(strAddress))
                wallet->SetAddressBookName(strAddress, rcp.label.toStdString());
        }
    }

    return SendCoinsReturn(OK, 0, hex);
}

OptionsModel *WalletModel::getOptionsModel()
{
    return optionsModel;
}

AddressTableModel *WalletModel::getAddressTableModel()
{
    return addressTableModel;
}

TransactionTableModel *WalletModel::getTransactionTableModel()
{
    return transactionTableModel;
}

WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
{
    if(!wallet->IsCrypted())
    {
        return Unencrypted;
    }
    else if(wallet->IsLocked())
    {
        return Locked;
    }
    else
    {
        return Unlocked;
    }
}

bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
{
    if(encrypted)
    {
        // Encrypt
        return wallet->EncryptWallet(passphrase);
    }
    else
    {
        // Decrypt -- TODO; not supported yet
        return false;
    }
}

bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
{
    if(locked)
    {
        // Lock
        return wallet->Lock();
    }
    else
    {
        // Unlock
        return wallet->Unlock(passPhrase);
    }
}

bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
{
    bool retval;
    {
        LOCK(wallet->cs_wallet);
        wallet->Lock(); // Make sure wallet is locked before attempting pass change
        retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
    }
    return retval;
}

bool WalletModel::backupWallet(const QString &filename)
{
    return BackupWallet(*wallet, filename.toLocal8Bit().data());
}

// WalletModel::UnlockContext implementation
WalletModel::UnlockContext WalletModel::requestUnlock()
{
    bool was_locked = getEncryptionStatus() == Locked;
    if(was_locked)
    {
        // Request UI to unlock wallet
        emit requireUnlock();
    }
    // If wallet is still locked, unlock was failed or cancelled, mark context as invalid
    bool valid = getEncryptionStatus() != Locked;

    return UnlockContext(this, valid, was_locked);
}

WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
        wallet(wallet),
        valid(valid),
        relock(relock)
{
}

WalletModel::UnlockContext::~UnlockContext()
{
    if(valid && relock)
    {
        wallet->setWalletLocked(true);
    }
}

void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
{
    // Transfer context; old object no longer relocks wallet
    *this = rhs;
    rhs.relock = false;
}
<|endoftext|>


<commit_before><commit_msg>fix uninitialized variable<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "CRowSetDataColumn.hxx"
#include "dbastrings.hrc"
#include "apitools.hxx"
#include <comphelper/types.hxx>
#include <cppuhelper/typeprovider.hxx>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <tools/debug.hxx>

using namespace dbaccess;
using namespace comphelper;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace cppu;
using namespace osl;

DBG_NAME(ORowSetDataColumn)

ORowSetDataColumn::ORowSetDataColumn(   const Reference < XResultSetMetaData >& _xMetaData,
                                      const Reference < XRow >& _xRow,
                                      const Reference < XRowUpdate >& _xRowUpdate,
                                      sal_Int32 _nPos,
                                      const Reference< XDatabaseMetaData >& _rxDBMeta,
                                      const ::rtl::OUString& _rDescription,
                                      const ::rtl::OUString& i_sLabel,
                                      const ORowSetCacheIterator& _rColumnValue)
    :ODataColumn(_xMetaData,_xRow,_xRowUpdate,_nPos,_rxDBMeta)
    ,m_aColumnValue(_rColumnValue)
    ,m_sLabel(i_sLabel)
    ,m_aDescription(_rDescription)
{
    DBG_CTOR(ORowSetDataColumn,NULL);
    OColumnSettings::registerProperties( *this );
    registerProperty( PROPERTY_DESCRIPTION, PROPERTY_ID_DESCRIPTION, PropertyAttribute::READONLY, &m_aDescription, ::getCppuType( &m_aDescription ) );
}

ORowSetDataColumn::~ORowSetDataColumn()
{
    DBG_DTOR(ORowSetDataColumn,NULL);
}

// comphelper::OPropertyArrayUsageHelper
::cppu::IPropertyArrayHelper* ORowSetDataColumn::createArrayHelper( ) const
{
    BEGIN_PROPERTY_SEQUENCE(21)

    DECL_PROP1( CATALOGNAME,                ::rtl::OUString,    READONLY );
    DECL_PROP1( DISPLAYSIZE,                sal_Int32,          READONLY );
    DECL_PROP1_BOOL( ISAUTOINCREMENT,                           READONLY );
    DECL_PROP1_BOOL( ISCASESENSITIVE,                           READONLY );
    DECL_PROP1_BOOL( ISCURRENCY,                                READONLY );
    DECL_PROP1_BOOL( ISDEFINITELYWRITABLE,                      READONLY );
    DECL_PROP1( ISNULLABLE,                 sal_Int32,          READONLY );
    DECL_PROP1_BOOL( ISREADONLY,                                BOUND );
    DECL_PROP1_BOOL( ISROWVERSION,                              READONLY );
    DECL_PROP1_BOOL( ISSEARCHABLE,                              READONLY );
    DECL_PROP1_BOOL( ISSIGNED,                                  READONLY );
    DECL_PROP1_BOOL( ISWRITABLE,                                READONLY );
    DECL_PROP1( LABEL,                      ::rtl::OUString,    READONLY );
    DECL_PROP1( PRECISION,                  sal_Int32,          READONLY );
    DECL_PROP1( SCALE,                      sal_Int32,          READONLY );
    DECL_PROP1( SCHEMANAME,                 ::rtl::OUString,    READONLY );
    DECL_PROP1( SERVICENAME,                ::rtl::OUString,    READONLY );
    DECL_PROP1( TABLENAME,                  ::rtl::OUString,    READONLY );
    DECL_PROP1( TYPE,                       sal_Int32,          READONLY );
    DECL_PROP1( TYPENAME,                   ::rtl::OUString,    READONLY );
    DECL_PROP1( VALUE,                      Any,                BOUND );

    END_PROPERTY_SEQUENCE()

    Sequence< Property > aRegisteredProperties;
    describeProperties( aRegisteredProperties );

    return new ::cppu::OPropertyArrayHelper( ::comphelper::concatSequences( aDescriptor, aRegisteredProperties ), sal_False );
}

// cppu::OPropertySetHelper
::cppu::IPropertyArrayHelper& ORowSetDataColumn::getInfoHelper()
{
    return *static_cast< ::comphelper::OPropertyArrayUsageHelper< ORowSetDataColumn >* >(this)->getArrayHelper();
}

void SAL_CALL ORowSetDataColumn::getFastPropertyValue( Any& rValue, sal_Int32 nHandle ) const
{
    if ( PROPERTY_ID_VALUE == nHandle )
    {
        if ( !m_aColumnValue.isNull() && m_aColumnValue->is() )
        {
            ::osl::Mutex* pMutex = m_aColumnValue.getMutex();
            ::osl::MutexGuard aGuard( *pMutex );
#if OSL_DEBUG_LEVEL > 0
            ORowSetRow aRow = *m_aColumnValue;
#endif
            OSL_ENSURE((sal_Int32)aRow->get().size() > m_nPos,"Pos is greater than size of vector");
            rValue = ((*m_aColumnValue)->get())[m_nPos].makeAny();
        }
    }
    else if ( PROPERTY_ID_LABEL == nHandle && m_sLabel.getLength() )
        rValue <<= m_sLabel;
    else
        ODataColumn::getFastPropertyValue( rValue, nHandle );
}

void SAL_CALL ORowSetDataColumn::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue )throw (Exception)
{
    switch( nHandle )
    {
        case PROPERTY_ID_VALUE:
            updateObject(rValue);
            break;
        case PROPERTY_ID_ISREADONLY:
            {
                sal_Bool bVal = sal_False;
                rValue >>= bVal;
                m_isReadOnly.reset(bVal);
            }
            break;
        default:
            ODataColumn::setFastPropertyValue_NoBroadcast( nHandle,rValue );
            break;
    }
}

sal_Bool SAL_CALL ORowSetDataColumn::convertFastPropertyValue( Any & rConvertedValue,
                                                            Any & rOldValue,
                                                            sal_Int32 nHandle,
                                                            const Any& rValue ) throw (IllegalArgumentException)
{
    sal_Bool bModified = sal_False;
    switch( nHandle )
    {
        case PROPERTY_ID_VALUE:
            {
                rConvertedValue = rValue;
                getFastPropertyValue(rOldValue, PROPERTY_ID_VALUE);
                bModified = rConvertedValue != rOldValue;
            }
            break;
        case PROPERTY_ID_ISREADONLY:
            {
                rConvertedValue = rValue;
                getFastPropertyValue(rOldValue, PROPERTY_ID_ISREADONLY);
                bModified = rConvertedValue != rOldValue;
            }
            break;
        default:
            bModified = ODataColumn::convertFastPropertyValue(rConvertedValue, rOldValue, nHandle, rValue);
            break;
    }

    return bModified;
}

Sequence< sal_Int8 > ORowSetDataColumn::getImplementationId() throw (RuntimeException)
{
    static OImplementationId * pId = 0;
    if (! pId)
    {
        MutexGuard aGuard( Mutex::getGlobalMutex() );
        if (! pId)
        {
            static OImplementationId aId;
            pId = &aId;
        }
    }
    return pId->getImplementationId();
}

void ORowSetDataColumn::fireValueChange(const ORowSetValue& _rOldValue)
{
    if ( !m_aColumnValue.isNull() && m_aColumnValue->is() && (!(((*m_aColumnValue)->get())[m_nPos] == _rOldValue)) )
    {
        sal_Int32 nHandle = PROPERTY_ID_VALUE;
        m_aOldValue = _rOldValue.makeAny();
        Any aNew = ((*m_aColumnValue)->get())[m_nPos].makeAny();

        fire(&nHandle, &aNew, &m_aOldValue, 1, sal_False );
    }
    else if ( !m_aColumnValue.isNull() && !_rOldValue.isNull() )
    {
        sal_Int32 nHandle = PROPERTY_ID_VALUE;
        m_aOldValue = _rOldValue.makeAny();
        Any aNew;

        fire(&nHandle, &aNew, &m_aOldValue, 1, sal_False );
    }
}

DBG_NAME(ORowSetDataColumns )
ORowSetDataColumns::ORowSetDataColumns(
                sal_Bool _bCase,
                const ::rtl::Reference< ::connectivity::OSQLColumns>& _rColumns,
                ::cppu::OWeakObject& _rParent,
                ::osl::Mutex& _rMutex,
                const ::std::vector< ::rtl::OUString> &_rVector
                ) : connectivity::sdbcx::OCollection(_rParent,_bCase,_rMutex,_rVector)
                ,m_aColumns(_rColumns)
{
    DBG_CTOR(ORowSetDataColumns ,NULL);
}

ORowSetDataColumns::~ORowSetDataColumns()
{
    DBG_DTOR(ORowSetDataColumns ,NULL);
}

sdbcx::ObjectType ORowSetDataColumns::createObject(const ::rtl::OUString& _rName)
{
    connectivity::sdbcx::ObjectType xNamed;

    ::comphelper::UStringMixEqual aCase(isCaseSensitive());
    ::connectivity::OSQLColumns::Vector::const_iterator first =  ::connectivity::find(m_aColumns->get().begin(),m_aColumns->get().end(),_rName,aCase);
    if(first != m_aColumns->get().end())
        xNamed.set(*first,UNO_QUERY);

    return xNamed;
}

void SAL_CALL ORowSetDataColumns::disposing(void)
{
    ORowSetDataColumns_BASE::disposing();
    m_aColumns = NULL;
}

void ORowSetDataColumns::assign(const ::rtl::Reference< ::connectivity::OSQLColumns>& _rColumns,const ::std::vector< ::rtl::OUString> &_rVector)
{
    m_aColumns = _rColumns;
    reFill(_rVector);
}

void ORowSetDataColumns::impl_refresh() throw(::com::sun::star::uno::RuntimeException)
{
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>make this more readable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "CRowSetDataColumn.hxx"
#include "dbastrings.hrc"
#include "apitools.hxx"
#include <comphelper/types.hxx>
#include <cppuhelper/typeprovider.hxx>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <tools/debug.hxx>

using namespace dbaccess;
using namespace comphelper;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace cppu;
using namespace osl;

DBG_NAME(ORowSetDataColumn)

ORowSetDataColumn::ORowSetDataColumn(   const Reference < XResultSetMetaData >& _xMetaData,
                                      const Reference < XRow >& _xRow,
                                      const Reference < XRowUpdate >& _xRowUpdate,
                                      sal_Int32 _nPos,
                                      const Reference< XDatabaseMetaData >& _rxDBMeta,
                                      const ::rtl::OUString& _rDescription,
                                      const ::rtl::OUString& i_sLabel,
                                      const ORowSetCacheIterator& _rColumnValue)
    :ODataColumn(_xMetaData,_xRow,_xRowUpdate,_nPos,_rxDBMeta)
    ,m_aColumnValue(_rColumnValue)
    ,m_sLabel(i_sLabel)
    ,m_aDescription(_rDescription)
{
    DBG_CTOR(ORowSetDataColumn,NULL);
    OColumnSettings::registerProperties( *this );
    registerProperty( PROPERTY_DESCRIPTION, PROPERTY_ID_DESCRIPTION, PropertyAttribute::READONLY, &m_aDescription, ::getCppuType( &m_aDescription ) );
}

ORowSetDataColumn::~ORowSetDataColumn()
{
    DBG_DTOR(ORowSetDataColumn,NULL);
}

// comphelper::OPropertyArrayUsageHelper
::cppu::IPropertyArrayHelper* ORowSetDataColumn::createArrayHelper( ) const
{
    BEGIN_PROPERTY_SEQUENCE(21)

    DECL_PROP1( CATALOGNAME,                ::rtl::OUString,    READONLY );
    DECL_PROP1( DISPLAYSIZE,                sal_Int32,          READONLY );
    DECL_PROP1_BOOL( ISAUTOINCREMENT,                           READONLY );
    DECL_PROP1_BOOL( ISCASESENSITIVE,                           READONLY );
    DECL_PROP1_BOOL( ISCURRENCY,                                READONLY );
    DECL_PROP1_BOOL( ISDEFINITELYWRITABLE,                      READONLY );
    DECL_PROP1( ISNULLABLE,                 sal_Int32,          READONLY );
    DECL_PROP1_BOOL( ISREADONLY,                                BOUND );
    DECL_PROP1_BOOL( ISROWVERSION,                              READONLY );
    DECL_PROP1_BOOL( ISSEARCHABLE,                              READONLY );
    DECL_PROP1_BOOL( ISSIGNED,                                  READONLY );
    DECL_PROP1_BOOL( ISWRITABLE,                                READONLY );
    DECL_PROP1( LABEL,                      ::rtl::OUString,    READONLY );
    DECL_PROP1( PRECISION,                  sal_Int32,          READONLY );
    DECL_PROP1( SCALE,                      sal_Int32,          READONLY );
    DECL_PROP1( SCHEMANAME,                 ::rtl::OUString,    READONLY );
    DECL_PROP1( SERVICENAME,                ::rtl::OUString,    READONLY );
    DECL_PROP1( TABLENAME,                  ::rtl::OUString,    READONLY );
    DECL_PROP1( TYPE,                       sal_Int32,          READONLY );
    DECL_PROP1( TYPENAME,                   ::rtl::OUString,    READONLY );
    DECL_PROP1( VALUE,                      Any,                BOUND );

    END_PROPERTY_SEQUENCE()

    Sequence< Property > aRegisteredProperties;
    describeProperties( aRegisteredProperties );

    return new ::cppu::OPropertyArrayHelper( ::comphelper::concatSequences( aDescriptor, aRegisteredProperties ), sal_False );
}

// cppu::OPropertySetHelper
::cppu::IPropertyArrayHelper& ORowSetDataColumn::getInfoHelper()
{
    return *static_cast< ::comphelper::OPropertyArrayUsageHelper< ORowSetDataColumn >* >(this)->getArrayHelper();
}

void SAL_CALL ORowSetDataColumn::getFastPropertyValue( Any& rValue, sal_Int32 nHandle ) const
{
    if ( PROPERTY_ID_VALUE == nHandle )
    {
        if ( !m_aColumnValue.isNull() && m_aColumnValue->is() )
        {
            ::osl::Mutex* pMutex = m_aColumnValue.getMutex();
            ::osl::MutexGuard aGuard( *pMutex );
#if OSL_DEBUG_LEVEL > 0
            ORowSetRow aRow = *m_aColumnValue;
#endif
            OSL_ENSURE((sal_Int32)aRow->get().size() > m_nPos,"Pos is greater than size of vector");
            rValue = ((*m_aColumnValue)->get())[m_nPos].makeAny();
        }
    }
    else if ( PROPERTY_ID_LABEL == nHandle && m_sLabel.getLength() )
        rValue <<= m_sLabel;
    else
        ODataColumn::getFastPropertyValue( rValue, nHandle );
}

void SAL_CALL ORowSetDataColumn::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue )throw (Exception)
{
    switch( nHandle )
    {
        case PROPERTY_ID_VALUE:
            updateObject(rValue);
            break;
        case PROPERTY_ID_ISREADONLY:
            {
                sal_Bool bVal = sal_False;
                rValue >>= bVal;
                m_isReadOnly.reset(bVal);
            }
            break;
        default:
            ODataColumn::setFastPropertyValue_NoBroadcast( nHandle,rValue );
            break;
    }
}

sal_Bool SAL_CALL ORowSetDataColumn::convertFastPropertyValue( Any & rConvertedValue,
                                                            Any & rOldValue,
                                                            sal_Int32 nHandle,
                                                            const Any& rValue ) throw (IllegalArgumentException)
{
    sal_Bool bModified = sal_False;
    switch( nHandle )
    {
        case PROPERTY_ID_VALUE:
            {
                rConvertedValue = rValue;
                getFastPropertyValue(rOldValue, PROPERTY_ID_VALUE);
                bModified = rConvertedValue != rOldValue;
            }
            break;
        case PROPERTY_ID_ISREADONLY:
            {
                rConvertedValue = rValue;
                getFastPropertyValue(rOldValue, PROPERTY_ID_ISREADONLY);
                bModified = rConvertedValue != rOldValue;
            }
            break;
        default:
            bModified = ODataColumn::convertFastPropertyValue(rConvertedValue, rOldValue, nHandle, rValue);
            break;
    }

    return bModified;
}

Sequence< sal_Int8 > ORowSetDataColumn::getImplementationId() throw (RuntimeException)
{
    static OImplementationId * pId = 0;
    if (! pId)
    {
        MutexGuard aGuard( Mutex::getGlobalMutex() );
        if (! pId)
        {
            static OImplementationId aId;
            pId = &aId;
        }
    }
    return pId->getImplementationId();
}

void ORowSetDataColumn::fireValueChange(const ORowSetValue& _rOldValue)
{
    if ( !m_aColumnValue.isNull() && m_aColumnValue->is() && (((*m_aColumnValue)->get())[m_nPos] != _rOldValue) )
    {
        sal_Int32 nHandle = PROPERTY_ID_VALUE;
        m_aOldValue = _rOldValue.makeAny();
        Any aNew = ((*m_aColumnValue)->get())[m_nPos].makeAny();

        fire(&nHandle, &aNew, &m_aOldValue, 1, sal_False );
    }
    else if ( !m_aColumnValue.isNull() && !_rOldValue.isNull() )
    {
        sal_Int32 nHandle = PROPERTY_ID_VALUE;
        m_aOldValue = _rOldValue.makeAny();
        Any aNew;

        fire(&nHandle, &aNew, &m_aOldValue, 1, sal_False );
    }
}

DBG_NAME(ORowSetDataColumns )
ORowSetDataColumns::ORowSetDataColumns(
                sal_Bool _bCase,
                const ::rtl::Reference< ::connectivity::OSQLColumns>& _rColumns,
                ::cppu::OWeakObject& _rParent,
                ::osl::Mutex& _rMutex,
                const ::std::vector< ::rtl::OUString> &_rVector
                ) : connectivity::sdbcx::OCollection(_rParent,_bCase,_rMutex,_rVector)
                ,m_aColumns(_rColumns)
{
    DBG_CTOR(ORowSetDataColumns ,NULL);
}

ORowSetDataColumns::~ORowSetDataColumns()
{
    DBG_DTOR(ORowSetDataColumns ,NULL);
}

sdbcx::ObjectType ORowSetDataColumns::createObject(const ::rtl::OUString& _rName)
{
    connectivity::sdbcx::ObjectType xNamed;

    ::comphelper::UStringMixEqual aCase(isCaseSensitive());
    ::connectivity::OSQLColumns::Vector::const_iterator first =  ::connectivity::find(m_aColumns->get().begin(),m_aColumns->get().end(),_rName,aCase);
    if(first != m_aColumns->get().end())
        xNamed.set(*first,UNO_QUERY);

    return xNamed;
}

void SAL_CALL ORowSetDataColumns::disposing(void)
{
    ORowSetDataColumns_BASE::disposing();
    m_aColumns = NULL;
}

void ORowSetDataColumns::assign(const ::rtl::Reference< ::connectivity::OSQLColumns>& _rColumns,const ::std::vector< ::rtl::OUString> &_rVector)
{
    m_aColumns = _rColumns;
    reFill(_rVector);
}

void ORowSetDataColumns::impl_refresh() throw(::com::sun::star::uno::RuntimeException)
{
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <wtypes.h>
#include <stdio.h>
#include <string>
#include <psapi.h>
#include "Utility.h"
#include "WindowUtility.h"

using namespace std;

int main(int argc, char** argv)
{
	string cmd = argv[1];
	if (cmd == "arch") {
		string type = argv[2];
		if (type == "-file") {
			const char* fileName = argv[3];
			ExeInfo info;
			if (GetExeInfo(fileName, info)) {
				printf("%d", info.i386);
				return info.i386;
			}
			return -1;//file not exist
		}
		else if (type == "-pid") {
			const char* pid_str = argv[3];
			DWORD processId = atoi(pid_str);

			char fileName[_MAX_PATH];
			HANDLE m_process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId);
			GetModuleFileNameEx(m_process, nullptr, fileName, _MAX_PATH);

			ExeInfo info;
			if (GetExeInfo(fileName, info)) {
				printf("%d", info.i386);
				return info.i386;
			}
		}
	}
	else if (cmd == "list_processes") {
		std::vector<Process> list;
		GetProcesses(list);

		printf("<list>");
		for (int i = 0; i < list.size(); ++i)
		{
			auto& value = list[i];
			printf("<process pid=\"%d\">", value.id);
			printf("<title><![CDATA[%s]]></title>", value.title.c_str());
			printf("<path><![CDATA[%s]]></path>", value.path.c_str());
			printf("</process>");
		}
		printf("</list>\n");
	}
	return 0;
}<commit_msg>fix support for .net framework exe(can not detect right .net exe architecture)<commit_after>#include <wtypes.h>
#include <stdio.h>
#include <string>
#include <psapi.h>
#include <algorithm>
#include "Utility.h"
#include "WindowUtility.h"

using namespace std;

int main(int argc, char** argv)
{
	string cmd = argv[1];
	if (cmd == "arch") {
		string type = argv[2];
		if (type == "-file") {
			const char* fileName = argv[3];
			ExeInfo info;
			if (GetExeInfo(fileName, info)) {
				printf("%d", info.i386);
				return info.i386;
			}
			return -1;//file not exist
		}
		else if (type == "-pid") {
			const char* pid_str = argv[3];
			DWORD processId = atoi(pid_str);

			char fileName[_MAX_PATH];
			HANDLE m_process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId);
			GetModuleFileNameEx(m_process, nullptr, fileName, _MAX_PATH);

			USHORT processMachine = 0, nativeMachine = 0;

			typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
			LPFN_ISWOW64PROCESS fnIsWow64Process = nullptr;

			typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS2) (HANDLE, USHORT*, USHORT*);
			LPFN_ISWOW64PROCESS2 fnIsWow64Process2 = nullptr;

			fnIsWow64Process2 = (LPFN_ISWOW64PROCESS2)GetProcAddress(
				GetModuleHandle(TEXT("kernel32")), "IsWow64Process2");

			fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(
				GetModuleHandle(TEXT("kernel32")), "IsWow64Process");

			////fnIsWow64Process2 = nullptr;

			ExeInfo info;
			if (GetExeInfo(fileName, info)) {
				if (!info.managed)
				{
					printf("%d", info.i386);
					return info.i386;
				}
				else
				{
					BOOL is64bit = FALSE;
					if (fnIsWow64Process2)
					{
						is64bit = fnIsWow64Process2(m_process, &processMachine, &nativeMachine);
					}
					else if (fnIsWow64Process)
					{
						is64bit = fnIsWow64Process(m_process, &is64bit);
					}

					printf("%d", !is64bit);
					return !is64bit;
				}

			}
		}
	}
	else if (cmd == "list_processes") {
		std::vector<Process> list;
		GetProcesses(list);

		printf("<list>");
		for (int i = 0; i < list.size(); ++i)
		{
			auto& value = list[i];
			printf("<process pid=\"%d\">", value.id);
			printf("<title><![CDATA[%s]]></title>", value.title.c_str());
			printf("<path><![CDATA[%s]]></path>", value.path.c_str());
			printf("</process>");
		}
		printf("</list>\n");
	}
	return 0;
}<|endoftext|>


<commit_before>// Copyright 2017 gRPC authors.
//
// 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.\n"
  "\n"
  "/* This code will be inserted into generated code for\n"
  " * google/protobuf/timestamp.proto. */\n"
  "\n"
  "/**\n"
  " * Returns a JavaScript 'Date' object corresponding to this Timestamp.\n"
  " * @return {!Date}\n"
  " */\n"
  "proto.google.protobuf.Timestamp.prototype.toDate = function() {\n"
  "  var seconds = this.getSeconds();\n"
  "  var nanos = this.getNanos();\n"
  "\n"
  "  return new Date((seconds * 1000) + (nanos / 1000000));\n"
  "};\n"
  "\n"
  "\n"
  "/**\n"
  " * Sets the value of this Timestamp object to be the given Date.\n"
  " * @param {!Date} value The value to set.\n"
  " */\n"
  "proto.google.protobuf.Timestamp.prototype.fromDate = function(value) {\n"
  "  var millis = value.getTime();\n"
  "  this.setSeconds(Math.floor(value.getTime() / 1000));\n"
  "  this.setNanos(value.getMilliseconds() * 1000000);\n"
  "};\n"
},
  {NULL, NULL}  // Terminate the list.
};
<commit_msg>fix protobuf_generated_well_known_types_embed.cc<commit_after>// Copyright 2017 gRPC authors.
//
// 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.

// HACK: Embed the generated well_known_types_js.cc to make
// grpc-tools python package compilation easy.
#include <google/protobuf/compiler/js/well_known_types_embed.h>
struct FileToc well_known_types_js[] = {
{"any.js",
  "// Protocol Buffers - Google's data interchange format\n"
  "// Copyright 2008 Google Inc.  All rights reserved.\n"
  "// https://developers.google.com/protocol-buffers/\n"
  "//\n"
  "// Redistribution and use in source and binary forms, with or without\n"
  "// modification, are permitted provided that the following conditions are\n"
  "// met:\n"
  "//\n"
  "//     * Redistributions of source code must retain the above copyright\n"
  "// notice, this list of conditions and the following disclaimer.\n"
  "//     * Redistributions in binary form must reproduce the above\n"
  "// copyright notice, this list of conditions and the following disclaimer\n"
  "// in the documentation and/or other materials provided with the\n"
  "// distribution.\n"
  "//     * Neither the name of Google Inc. nor the names of its\n"
  "// contributors may be used to endorse or promote products derived from\n"
  "// this software without specific prior written permission.\n"
  "//\n"
  "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
  "// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
  "// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
  "// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
  "// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
  "// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
  "// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
  "// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
  "// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
  "// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
  "// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  "\n"
  "/* This code will be inserted into generated code for\n"
  " * google/protobuf/any.proto. */\n"
  "\n"
  "/**\n"
  " * Returns the type name contained in this instance, if any.\n"
  " * @return {string|undefined}\n"
  " */\n"
  "proto.google.protobuf.Any.prototype.getTypeName = function() {\n"
  "  return this.getTypeUrl().split('/').pop();\n"
  "};\n"
  "\n"
  "\n"
  "/**\n"
  " * Packs the given message instance into this Any.\n"
  " * @param {!Uint8Array} serialized The serialized data to pack.\n"
  " * @param {string} name The type name of this message object.\n"
  " * @param {string=} opt_typeUrlPrefix the type URL prefix.\n"
  " */\n"
  "proto.google.protobuf.Any.prototype.pack = function(serialized, name,\n"
  "                                                    opt_typeUrlPrefix) {\n"
  "  if (!opt_typeUrlPrefix) {\n"
  "    opt_typeUrlPrefix = 'type.googleapis.com/';\n"
  "  }\n"
  "\n"
  "  if (opt_typeUrlPrefix.substr(-1) != '/') {\n"
  "    this.setTypeUrl(opt_typeUrlPrefix + '/' + name);\n"
  "  } else {\n"
  "    this.setTypeUrl(opt_typeUrlPrefix + name);\n"
  "  }\n"
  "\n"
  "  this.setValue(serialized);\n"
  "};\n"
  "\n"
  "\n"
  "/**\n"
  " * @template T\n"
  " * Unpacks this Any into the given message object.\n"
  " * @param {function(Uint8Array):T} deserialize Function that will deserialize\n"
  " *     the binary data properly.\n"
  " * @param {string} name The expected type name of this message object.\n"
  " * @return {?T} If the name matched the expected name, returns the deserialized\n"
  " *     object, otherwise returns undefined.\n"
  " */\n"
  "proto.google.protobuf.Any.prototype.unpack = function(deserialize, name) {\n"
  "  if (this.getTypeName() == name) {\n"
  "    return deserialize(this.getValue_asU8());\n"
  "  } else {\n"
  "    return null;\n"
  "  }\n"
  "};\n"
},
{"struct.js",
  "// Protocol Buffers - Google's data interchange format\n"
  "// Copyright 2008 Google Inc.  All rights reserved.\n"
  "// https://developers.google.com/protocol-buffers/\n"
  "//\n"
  "// Redistribution and use in source and binary forms, with or without\n"
  "// modification, are permitted provided that the following conditions are\n"
  "// met:\n"
  "//\n"
  "//     * Redistributions of source code must retain the above copyright\n"
  "// notice, this list of conditions and the following disclaimer.\n"
  "//     * Redistributions in binary form must reproduce the above\n"
  "// copyright notice, this list of conditions and the following disclaimer\n"
  "// in the documentation and/or other materials provided with the\n"
  "// distribution.\n"
  "//     * Neither the name of Google Inc. nor the names of its\n"
  "// contributors may be used to endorse or promote products derived from\n"
  "// this software without specific prior written permission.\n"
  "//\n"
  "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
  "// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
  "// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
  "// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
  "// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
  "// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
  "// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
  "// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
  "// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
  "// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
  "// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  "\n"
  "/* This code will be inserted into generated code for\n"
  " * google/protobuf/struct.proto. */\n"
  "\n"
  "/**\n"
  " * Typedef representing plain JavaScript values that can go into a\n"
  " *     Struct.\n"
  " * @typedef {null|number|string|boolean|Array|Object}\n"
  " */\n"
  "proto.google.protobuf.JavaScriptValue;\n"
  "\n"
  "\n"
  "/**\n"
  " * Converts this Value object to a plain JavaScript value.\n"
  " * @return {?proto.google.protobuf.JavaScriptValue} a plain JavaScript\n"
  " *     value representing this Struct.\n"
  " */\n"
  "proto.google.protobuf.Value.prototype.toJavaScript = function() {\n"
  "  var kindCase = proto.google.protobuf.Value.KindCase;\n"
  "  switch (this.getKindCase()) {\n"
  "    case kindCase.NULL_VALUE:\n"
  "      return null;\n"
  "    case kindCase.NUMBER_VALUE:\n"
  "      return this.getNumberValue();\n"
  "    case kindCase.STRING_VALUE:\n"
  "      return this.getStringValue();\n"
  "    case kindCase.BOOL_VALUE:\n"
  "      return this.getBoolValue();\n"
  "    case kindCase.STRUCT_VALUE:\n"
  "      return this.getStructValue().toJavaScript();\n"
  "    case kindCase.LIST_VALUE:\n"
  "      return this.getListValue().toJavaScript();\n"
  "    default:\n"
  "      throw new Error('Unexpected struct type');\n"
  "  }\n"
  "};\n"
  "\n"
  "\n"
  "/**\n"
  " * Converts this JavaScript value to a new Value proto.\n"
  " * @param {!proto.google.protobuf.JavaScriptValue} value The value to\n"
  " *     convert.\n"
  " * @return {!proto.google.protobuf.Value} The newly constructed value.\n"
  " */\n"
  "proto.google.protobuf.Value.fromJavaScript = function(value) {\n"
  "  var ret = new proto.google.protobuf.Value();\n"
  "  switch (goog.typeOf(value)) {\n"
  "    case 'string':\n"
  "      ret.setStringValue(/** @type {string} */ (value));\n"
  "      break;\n"
  "    case 'number':\n"
  "      ret.setNumberValue(/** @type {number} */ (value));\n"
  "      break;\n"
  "    case 'boolean':\n"
  "      ret.setBoolValue(/** @type {boolean} */ (value));\n"
  "      break;\n"
  "    case 'null':\n"
  "      ret.setNullValue(proto.google.protobuf.NullValue.NULL_VALUE);\n"
  "      break;\n"
  "    case 'array':\n"
  "      ret.setListValue(proto.google.protobuf.ListValue.fromJavaScript(\n"
  "          /** @type{!Array} */ (value)));\n"
  "      break;\n"
  "    case 'object':\n"
  "      ret.setStructValue(proto.google.protobuf.Struct.fromJavaScript(\n"
  "          /** @type{!Object} */ (value)));\n"
  "      break;\n"
  "    default:\n"
  "      throw new Error('Unexpected struct type.');\n"
  "  }\n"
  "\n"
  "  return ret;\n"
  "};\n"
  "\n"
  "\n"
  "/**\n"
  " * Converts this ListValue object to a plain JavaScript array.\n"
  " * @return {!Array} a plain JavaScript array representing this List.\n"
  " */\n"
  "proto.google.protobuf.ListValue.prototype.toJavaScript = function() {\n"
  "  var ret = [];\n"
  "  var values = this.getValuesList();\n"
  "\n"
  "  for (var i = 0; i < values.length; i++) {\n"
  "    ret[i] = values[i].toJavaScript();\n"
  "  }\n"
  "\n"
  "  return ret;\n"
  "};\n"
  "\n"
  "\n"
  "/**\n"
  " * Constructs a ListValue protobuf from this plain JavaScript array.\n"
  " * @param {!Array} array a plain JavaScript array\n"
  " * @return {proto.google.protobuf.ListValue} a new ListValue object\n"
  " */\n"
  "proto.google.protobuf.ListValue.fromJavaScript = function(array) {\n"
  "  var ret = new proto.google.protobuf.ListValue();\n"
  "\n"
  "  for (var i = 0; i < array.length; i++) {\n"
  "    ret.addValues(proto.google.protobuf.Value.fromJavaScript(array[i]));\n"
  "  }\n"
  "\n"
  "  return ret;\n"
  "};\n"
  "\n"
  "\n"
  "/**\n"
  " * Converts this Struct object to a plain JavaScript object.\n"
  " * @return {!Object<string, !proto.google.protobuf.JavaScriptValue>} a plain\n"
  " *     JavaScript object representing this Struct.\n"
  " */\n"
  "proto.google.protobuf.Struct.prototype.toJavaScript = function() {\n"
  "  var ret = {};\n"
  "\n"
  "  this.getFieldsMap().forEach(function(value, key) {\n"
  "    ret[key] = value.toJavaScript();\n"
  "  });\n"
  "\n"
  "  return ret;\n"
  "};\n"
  "\n"
  "\n"
  "/**\n"
  " * Constructs a Struct protobuf from this plain JavaScript object.\n"
  " * @param {!Object} obj a plain JavaScript object\n"
  " * @return {proto.google.protobuf.Struct} a new Struct object\n"
  " */\n"
  "proto.google.protobuf.Struct.fromJavaScript = function(obj) {\n"
  "  var ret = new proto.google.protobuf.Struct();\n"
  "  var map = ret.getFieldsMap();\n"
  "\n"
  "  for (var property in obj) {\n"
  "    var val = obj[property];\n"
  "    map.set(property, proto.google.protobuf.Value.fromJavaScript(val));\n"
  "  }\n"
  "\n"
  "  return ret;\n"
  "};\n"
},
{"timestamp.js",
  "// Protocol Buffers - Google's data interchange format\n"
  "// Copyright 2008 Google Inc.  All rights reserved.\n"
  "// https://developers.google.com/protocol-buffers/\n"
  "//\n"
  "// Redistribution and use in source and binary forms, with or without\n"
  "// modification, are permitted provided that the following conditions are\n"
  "// met:\n"
  "//\n"
  "//     * Redistributions of source code must retain the above copyright\n"
  "// notice, this list of conditions and the following disclaimer.\n"
  "//     * Redistributions in binary form must reproduce the above\n"
  "// copyright notice, this list of conditions and the following disclaimer\n"
  "// in the documentation and/or other materials provided with the\n"
  "// distribution.\n"
  "//     * Neither the name of Google Inc. nor the names of its\n"
  "// contributors may be used to endorse or promote products derived from\n"
  "// this software without specific prior written permission.\n"
  "//\n"
  "// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n"
  "// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n"
  "// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n"
  "// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n"
  "// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n"
  "// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n"
  "// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
  "// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
  "// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
  "// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
  "// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  "\n"
  "/* This code will be inserted into generated code for\n"
  " * google/protobuf/timestamp.proto. */\n"
  "\n"
  "/**\n"
  " * Returns a JavaScript 'Date' object corresponding to this Timestamp.\n"
  " * @return {!Date}\n"
  " */\n"
  "proto.google.protobuf.Timestamp.prototype.toDate = function() {\n"
  "  var seconds = this.getSeconds();\n"
  "  var nanos = this.getNanos();\n"
  "\n"
  "  return new Date((seconds * 1000) + (nanos / 1000000));\n"
  "};\n"
  "\n"
  "\n"
  "/**\n"
  " * Sets the value of this Timestamp object to be the given Date.\n"
  " * @param {!Date} value The value to set.\n"
  " */\n"
  "proto.google.protobuf.Timestamp.prototype.fromDate = function(value) {\n"
  "  var millis = value.getTime();\n"
  "  this.setSeconds(Math.floor(value.getTime() / 1000));\n"
  "  this.setNanos(value.getMilliseconds() * 1000000);\n"
  "};\n"
},
  {NULL, NULL}  // Terminate the list.
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gencoll_rule.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2006-01-31 18:36:13 $
 *
 *  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
 *
 ************************************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sal/main.h>
#include <sal/types.h>
#include <rtl/ustrbuf.hxx>
#include <unicode/tblcoll.h>

using namespace ::rtl;

/* Main Procedure */

void data_write(char* file, char* name, sal_uInt8 *data, sal_Int32 len)
{
    FILE *fp = fopen(file, "wb");
    if (fp == NULL) {
        printf("Can't create the C source file.");
        return;
    }

    fprintf(fp, "/*\n");
    fprintf(fp, " * Copyright(c) 1999 - 2000, Sun Microsystems, Inc.\n");
    fprintf(fp, " * All Rights Reserved.\n");
    fprintf(fp, " */\n\n");
    fprintf(fp, "/* !!!The file is generated automatically. DONOT edit the file manually!!! */\n\n");
    fprintf(fp, "#include <sal/types.h>\n");
    fprintf(fp, "\nextern \"C\" {\n");

    // generate main dict. data array
    fprintf(fp, "\nstatic const sal_uInt8 %s[] = {", name);

    sal_Int32 count = 0;
    for (sal_Int32 i = 0; i < len; i++) {

        if (count++ % 16 == 0)
            fprintf(fp, "\n\t");

        fprintf(fp, "0x%04x, ", data[i]);
    }
    fprintf(fp, "\n};\n\n");

    fprintf(fp, "const sal_uInt8* get_%s() { return %s; }\n\n", name, name);
    fprintf (fp, "}\n");

    fclose(fp);

}

U_CAPI uint8_t* U_EXPORT2
ucol_cloneRuleData(const UCollator *coll, int32_t *length, UErrorCode *status);

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
    FILE *fp;

    if (argc < 4) exit(-1);

    fp = fopen(argv[1], "rb");  // open the source file for read;
    if (fp == NULL)
        printf("Open the rule source file failed.");

    sal_Char str[1024];
    OUStringBuffer Obuf;
    while (fgets(str, 1024, fp)) {
        // don't convert last new line character to Ostr.
        sal_Int32 len = strlen(str) - 1;
        // skip comment line
        if (len == 0 || str[0] == '#')
            continue;

        // input file is in UTF-8 encoding
        OUString Ostr = OUString((const sal_Char *)str, len, RTL_TEXTENCODING_UTF8).trim();

        len = Ostr.getLength();
        if (len == 0)
            continue; // skip empty line.

        Obuf.append(Ostr);
    }
    fclose(fp);

    UErrorCode status = U_ZERO_ERROR;
    //UParseError parseError;
    //UCollator *coll = ucol_openRules(Obuf.getStr(), Obuf.getLength(), UCOL_OFF,
    //        UCOL_DEFAULT_STRENGTH, &parseError, &status);

    RuleBasedCollator *coll = new RuleBasedCollator(Obuf.getStr(), status);

    if (U_SUCCESS(status)) {

        int32_t len = 0;
        //uint8_t *data = ucol_cloneRuleData(coll, &len, &status);
        uint8_t *data = coll->cloneRuleData(len, status);

        if (U_SUCCESS(status) && data != NULL)
            data_write(argv[2], argv[3], data, len);
        else {
            printf("Could not get rule data from collator\n");
        }
    } else {
        printf("\nRule parsering error\n");
    }

    if (coll)
        delete coll;

    exit(U_SUCCESS(status) ? 0 : 1);
    return 0;
}   // End of main
<commit_msg>INTEGRATION: CWS warnings01 (1.6.2); FILE MERGED 2006/04/07 21:05:13 sb 1.6.2.3: RESYNC: (1.6-1.7); FILE MERGED 2006/03/08 13:19:09 nn 1.6.2.2: #i53898# warning-free code 2005/11/10 10:15:00 pl 1.6.2.1: #i53898# removed warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gencoll_rule.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 04:44:43 $
 *
 *  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
 *
 ************************************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sal/main.h>
#include <sal/types.h>
#include <rtl/ustrbuf.hxx>

// External unicode includes (from icu) cause warning C4668 on Windows.
// We want to minimize the patches to external headers, so the warnings are
// disabled here instead of in the header file itself.
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <unicode/tblcoll.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

using namespace ::rtl;

/* Main Procedure */

void data_write(char* file, char* name, sal_uInt8 *data, sal_Int32 len)
{
    FILE *fp = fopen(file, "wb");
    if (fp == NULL) {
        printf("Can't create the C source file.");
        return;
    }

    fprintf(fp, "/*\n");
    fprintf(fp, " * Copyright(c) 1999 - 2000, Sun Microsystems, Inc.\n");
    fprintf(fp, " * All Rights Reserved.\n");
    fprintf(fp, " */\n\n");
    fprintf(fp, "/* !!!The file is generated automatically. DONOT edit the file manually!!! */\n\n");
    fprintf(fp, "#include <sal/types.h>\n");
    fprintf(fp, "\nextern \"C\" {\n");

    // generate main dict. data array
    fprintf(fp, "\nstatic const sal_uInt8 %s[] = {", name);

    sal_Int32 count = 0;
    for (sal_Int32 i = 0; i < len; i++) {

        if (count++ % 16 == 0)
            fprintf(fp, "\n\t");

        fprintf(fp, "0x%04x, ", data[i]);
    }
    fprintf(fp, "\n};\n\n");

    fprintf(fp, "const sal_uInt8* get_%s() { return %s; }\n\n", name, name);
    fprintf (fp, "}\n");

    fclose(fp);

}

U_CAPI uint8_t* U_EXPORT2
ucol_cloneRuleData(const UCollator *coll, int32_t *length, UErrorCode *status);

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
    FILE *fp;

    if (argc < 4) exit(-1);

    fp = fopen(argv[1], "rb");  // open the source file for read;
    if (fp == NULL)
        printf("Open the rule source file failed.");

    sal_Char str[1024];
    OUStringBuffer Obuf;
    while (fgets(str, 1024, fp)) {
        // don't convert last new line character to Ostr.
        sal_Int32 len = strlen(str) - 1;
        // skip comment line
        if (len == 0 || str[0] == '#')
            continue;

        // input file is in UTF-8 encoding
        OUString Ostr = OUString((const sal_Char *)str, len, RTL_TEXTENCODING_UTF8).trim();

        len = Ostr.getLength();
        if (len == 0)
            continue; // skip empty line.

        Obuf.append(Ostr);
    }
    fclose(fp);

    UErrorCode status = U_ZERO_ERROR;
    //UParseError parseError;
    //UCollator *coll = ucol_openRules(Obuf.getStr(), Obuf.getLength(), UCOL_OFF,
    //        UCOL_DEFAULT_STRENGTH, &parseError, &status);

    RuleBasedCollator *coll = new RuleBasedCollator(Obuf.getStr(), status);

    if (U_SUCCESS(status)) {

        int32_t len = 0;
        //uint8_t *data = ucol_cloneRuleData(coll, &len, &status);
        uint8_t *data = coll->cloneRuleData(len, status);

        if (U_SUCCESS(status) && data != NULL)
            data_write(argv[2], argv[3], data, len);
        else {
            printf("Could not get rule data from collator\n");
        }
    } else {
        printf("\nRule parsering error\n");
    }

    if (coll)
        delete coll;

    return U_SUCCESS(status) ? 0 : 1;
}   // End of main
<|endoftext|>


<commit_before>//===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the Evan Cheng and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the machine register scavenger. It can provide
// information such as unused register at any point in a machine basic block.
// It also provides a mechanism to make registers availbale by evicting them
// to spill slots.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "reg-scavenging"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;

RegScavenger::RegScavenger(MachineBasicBlock *mbb)
  : MBB(mbb), MBBI(mbb->begin()) {
  const MachineFunction &MF = *MBB->getParent();
  const TargetMachine &TM = MF.getTarget();
  const MRegisterInfo *RegInfo = TM.getRegisterInfo();

  NumPhysRegs = RegInfo->getNumRegs();
  RegStates.resize(NumPhysRegs, true);

  // Create reserved registers bitvector.
  ReservedRegs = RegInfo->getReservedRegs(MF);
  RegStates ^= ReservedRegs;

  // Create callee-saved registers bitvector.
  CalleeSavedRegs.resize(NumPhysRegs);
  const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
  if (CSRegs != NULL)
    for (unsigned i = 0; CSRegs[i]; ++i)
      CalleeSavedRegs.set(CSRegs[i]);

  // Live-in registers are in use.
  if (!MBB->livein_empty())
    for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
           E = MBB->livein_end(); I != E; ++I)
      setUsed(*I);
}

void RegScavenger::forward() {
  MachineInstr *MI = MBBI;
  // Process uses first.
  BitVector ChangedRegs(NumPhysRegs);
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    const MachineOperand &MO = MI->getOperand(i);
    if (!MO.isReg() || !MO.isUse())
      continue;
    unsigned Reg = MO.getReg();
    if (Reg == 0)
      continue;
    assert(isUsed(Reg));
    if (MO.isKill() && !isReserved(Reg))
      ChangedRegs.set(Reg);
  }
  // Change states of all registers after all the uses are processed to guard
  // against multiple uses.
  setUnused(ChangedRegs);

  // Process defs.
  const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    const MachineOperand &MO = MI->getOperand(i);
    if (!MO.isReg() || !MO.isDef())
      continue;
    // Skip two-address destination operand.
    if (TID->findTiedToSrcOperand(i) != -1)
      continue;
    unsigned Reg = MO.getReg();
    assert(isUnused(Reg) || isReserved(Reg));
    if (!MO.isDead())
      setUsed(Reg);
  }

  ++MBBI;
}

void RegScavenger::backward() {
  MachineInstr *MI = --MBBI;
  // Process defs first.
  const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    const MachineOperand &MO = MI->getOperand(i);
    if (!MO.isReg() || !MO.isDef())
      continue;
    // Skip two-address destination operand.
    if (TID->findTiedToSrcOperand(i) != -1)
      continue;
    unsigned Reg = MO.getReg();
    assert(isUsed(Reg));
    if (!isReserved(Reg))
      setUnused(Reg);
  }

  // Process uses.
  BitVector ChangedRegs(NumPhysRegs);
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    const MachineOperand &MO = MI->getOperand(i);
    if (!MO.isReg() || !MO.isUse())
      continue;
    unsigned Reg = MO.getReg();
    if (Reg == 0)
      continue;
    assert(isUnused(Reg) || isReserved(Reg));
    ChangedRegs.set(Reg);
  }
  setUsed(ChangedRegs);
}

/// CreateRegClassMask - Set the bits that represent the registers in the
/// TargetRegisterClass.
static void CreateRegClassMask(const TargetRegisterClass *RC, BitVector &Mask) {
  for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E;
       ++I)
    Mask.set(*I);
}

unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
                                     bool ExCalleeSaved) const {
  // Mask off the registers which are not in the TargetRegisterClass.
  BitVector RegStatesCopy(NumPhysRegs, false);
  CreateRegClassMask(RegClass, RegStatesCopy);
  RegStatesCopy &= RegStates;

  // If looking for a non-callee-saved register, mask off all the callee-saved
  // registers.
  if (ExCalleeSaved)
    RegStatesCopy &= ~CalleeSavedRegs;

  // Returns the first unused (bit is set) register, or 0 is none is found.
  int Reg = RegStatesCopy.find_first();
  return (Reg == -1) ? 0 : Reg;
}
<commit_msg>Add an assertion.<commit_after>//===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the Evan Cheng and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the machine register scavenger. It can provide
// information such as unused register at any point in a machine basic block.
// It also provides a mechanism to make registers availbale by evicting them
// to spill slots.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "reg-scavenging"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;

RegScavenger::RegScavenger(MachineBasicBlock *mbb)
  : MBB(mbb), MBBI(mbb->begin()) {
  const MachineFunction &MF = *MBB->getParent();
  const TargetMachine &TM = MF.getTarget();
  const MRegisterInfo *RegInfo = TM.getRegisterInfo();

  NumPhysRegs = RegInfo->getNumRegs();
  RegStates.resize(NumPhysRegs, true);

  // Create reserved registers bitvector.
  ReservedRegs = RegInfo->getReservedRegs(MF);
  RegStates ^= ReservedRegs;

  // Create callee-saved registers bitvector.
  CalleeSavedRegs.resize(NumPhysRegs);
  const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
  if (CSRegs != NULL)
    for (unsigned i = 0; CSRegs[i]; ++i)
      CalleeSavedRegs.set(CSRegs[i]);

  // Live-in registers are in use.
  if (!MBB->livein_empty())
    for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
           E = MBB->livein_end(); I != E; ++I)
      setUsed(*I);
}

void RegScavenger::forward() {
  MachineInstr *MI = MBBI;
  // Process uses first.
  BitVector ChangedRegs(NumPhysRegs);
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    const MachineOperand &MO = MI->getOperand(i);
    if (!MO.isReg() || !MO.isUse())
      continue;
    unsigned Reg = MO.getReg();
    if (Reg == 0)
      continue;
    assert(isUsed(Reg));
    if (MO.isKill() && !isReserved(Reg))
      ChangedRegs.set(Reg);
  }
  // Change states of all registers after all the uses are processed to guard
  // against multiple uses.
  setUnused(ChangedRegs);

  // Process defs.
  const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    const MachineOperand &MO = MI->getOperand(i);
    if (!MO.isReg() || !MO.isDef())
      continue;
    unsigned Reg = MO.getReg();
    // Skip two-address destination operand.
    if (TID->findTiedToSrcOperand(i) != -1) {
      assert(isUsed(Reg));
      continue;
    }
    assert(isUnused(Reg) || isReserved(Reg));
    if (!MO.isDead())
      setUsed(Reg);
  }

  ++MBBI;
}

void RegScavenger::backward() {
  MachineInstr *MI = --MBBI;
  // Process defs first.
  const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    const MachineOperand &MO = MI->getOperand(i);
    if (!MO.isReg() || !MO.isDef())
      continue;
    // Skip two-address destination operand.
    if (TID->findTiedToSrcOperand(i) != -1)
      continue;
    unsigned Reg = MO.getReg();
    assert(isUsed(Reg));
    if (!isReserved(Reg))
      setUnused(Reg);
  }

  // Process uses.
  BitVector ChangedRegs(NumPhysRegs);
  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    const MachineOperand &MO = MI->getOperand(i);
    if (!MO.isReg() || !MO.isUse())
      continue;
    unsigned Reg = MO.getReg();
    if (Reg == 0)
      continue;
    assert(isUnused(Reg) || isReserved(Reg));
    ChangedRegs.set(Reg);
  }
  setUsed(ChangedRegs);
}

/// CreateRegClassMask - Set the bits that represent the registers in the
/// TargetRegisterClass.
static void CreateRegClassMask(const TargetRegisterClass *RC, BitVector &Mask) {
  for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E;
       ++I)
    Mask.set(*I);
}

unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
                                     bool ExCalleeSaved) const {
  // Mask off the registers which are not in the TargetRegisterClass.
  BitVector RegStatesCopy(NumPhysRegs, false);
  CreateRegClassMask(RegClass, RegStatesCopy);
  RegStatesCopy &= RegStates;

  // If looking for a non-callee-saved register, mask off all the callee-saved
  // registers.
  if (ExCalleeSaved)
    RegStatesCopy &= ~CalleeSavedRegs;

  // Returns the first unused (bit is set) register, or 0 is none is found.
  int Reg = RegStatesCopy.find_first();
  return (Reg == -1) ? 0 : Reg;
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

// macros
#include "mitkTestingMacros.h"

// std includes
#include <string>
#include <sstream>

// MITK includes
#include <mitkBaseDataIOFactory.h>
#include <mitkConnectomicsStatisticsCalculator.h>

static void CalculateStatistics(std::string networkName, std::string outName, std::vector< std::vector< std::string > > /*vectorOfLabelVectors*/ )
{
  const std::string s1="", s2="";

  // load network
  std::vector<mitk::BaseData::Pointer> networkFile =
    mitk::BaseDataIO::LoadBaseDataFromFile( networkName, s1, s2, false );
  if( networkFile.empty() )
  {
    std::string errorMessage = "File at " + networkName + " could not be read. Aborting.";
    MITK_TEST_CONDITION_REQUIRED( !networkFile.empty(), errorMessage);
    return;
  }
  mitk::BaseData* networkBaseData = networkFile.at(0);
  mitk::ConnectomicsNetwork* network = dynamic_cast<mitk::ConnectomicsNetwork*>( networkBaseData );

  if( !network )
  {
    std::string errorMessage = "Read file at " + networkName + " could not be recognized as network. Aborting.";
    MITK_TEST_CONDITION_REQUIRED( network, errorMessage);
    return;
  }

  mitk::ConnectomicsStatisticsCalculator::Pointer statisticsCalculator = mitk::ConnectomicsStatisticsCalculator::New();

  statisticsCalculator->SetNetwork( network );
  statisticsCalculator->Update();

  std::stringstream headerStream;

  if( outName == "")
  {
    // test mode
    double eps( 0.0001 );
    MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNumberOfVertices(), 4 , eps, true ),  "GetNumberOfVertices" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNumberOfEdges(), 5 , eps, true ),  "GetNumberOfEdges" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAverageDegree(), 2.5 , eps, true ),  "GetAverageDegree" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetConnectionDensity(), 0.833333 , eps, true ),  "GetConnectionDensity" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNumberOfConnectedComponents(), 1 , eps, true ),  "GetNumberOfConnectedComponents" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAverageComponentSize(), 4 , eps, true ),  "GetAverageComponentSize" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetLargestComponentSize(), 4 , eps, true ),  "GetLargestComponentSize" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetRatioOfNodesInLargestComponent(), 1 , eps, true ),  "GetRatioOfNodesInLargestComponent" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetHopPlotExponent(), 0.192645 , eps, true ),  "GetHopPlotExponent" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetEffectiveHopDiameter(), 1 , eps, true ),  "GetEffectiveHopDiameter" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAverageClusteringCoefficientsC(), 0.833333 , eps, true ),  "GetAverageClusteringCoefficientsC" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAverageClusteringCoefficientsD(), 0.916667 , eps, true ),  "GetAverageClusteringCoefficientsD" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAverageClusteringCoefficientsE(), 0.833333 , eps, true ),  "GetAverageClusteringCoefficientsE" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAverageVertexBetweennessCentrality(), 0.25 , eps, true ),  "GetAverageVertexBetweennessCentrality" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAverageEdgeBetweennessCentrality(), 1.4 , eps, true ),  "GetAverageEdgeBetweennessCentrality" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNumberOfIsolatedPoints(), 0 , eps, true ),  "GetNumberOfIsolatedPoints" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetRatioOfIsolatedPoints(), 0 , eps, true ),  "GetRatioOfIsolatedPoints" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNumberOfEndPoints(), 0 , eps, true ),  "GetNumberOfEndPoints" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetRatioOfEndPoints(), 0 , eps, true ),  "GetRatioOfEndPoints" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetDiameter(), 2 , eps, true ),  "GetDiameter" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetDiameter90(), 2 , eps, true ),  "GetDiameter90" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetRadius(), 1 , eps, true ),  "GetRadius" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetRadius90(), 1 , eps, true ),  "GetRadius90" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAverageEccentricity(), 1.5 , eps, true ),  "GetAverageEccentricity" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAverageEccentricity90(), 1.5 , eps, true ),  "GetAverageEccentricity90" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAveragePathLength(), 1.16667 , eps, true ),  "GetAveragePathLength" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNumberOfCentralPoints(), 2 , eps, true ),  "GetNumberOfCentralPoints" )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetRatioOfCentralPoints(), 0.5 , eps, true ),  "GetRatioOfCentralPoints" )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetSpectralRadius(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetSecondLargestEigenValue(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAdjacencyTrace(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetAdjacencyEnergy(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetLaplacianTrace(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetLaplacianEnergy(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetLaplacianSpectralGap(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNormalizedLaplacianTrace(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNormalizedLaplacianEnergy(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNormalizedLaplacianNumberOf2s(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNormalizedLaplacianNumberOf1s(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNormalizedLaplacianNumberOf0s(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNormalizedLaplacianLowerSlope(), , eps, true ),  " " )
      // MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetNormalizedLaplacianUpperSlope(), , eps, true ),  " " )
      MITK_TEST_CONDITION_REQUIRED( mitk::Equal( statisticsCalculator->GetSmallWorldness(), 1.72908 , eps, true ),  "GetSmallWorldness" )
  }
  else
  {
    // batch mode
    headerStream  << "NumberOfVertices "
      << "NumberOfEdges "
      << "AverageDegree "
      << "ConnectionDensity "
      << "NumberOfConnectedComponents "
      << "AverageComponentSize "
      << "LargestComponentSize "
      << "RatioOfNodesInLargestComponent "
      << "HopPlotExponent "
      << "EffectiveHopDiameter "
      << "AverageClusteringCoefficientsC "
      << "AverageClusteringCoefficientsD "
      << "AverageClusteringCoefficientsE "
      << "AverageVertexBetweennessCentrality "
      << "AverageEdgeBetweennessCentrality "
      << "NumberOfIsolatedPoints "
      << "RatioOfIsolatedPoints "
      << "NumberOfEndPoints "
      << "RatioOfEndPoints "
      << "Diameter "
      << "Diameter90 "
      << "Radius "
      << "Radius90 "
      << "AverageEccentricity "
      << "AverageEccentricity90 "
      << "AveragePathLength "
      << "NumberOfCentralPoints "
      << "RatioOfCentralPoints "
      << "SpectralRadius "
      << "SecondLargestEigenValue "
      << "AdjacencyTrace "
      << "AdjacencyEnergy "
      << "LaplacianTrace "
      << "LaplacianEnergy "
      << "LaplacianSpectralGap "
      << "NormalizedLaplacianTrace "
      << "NormalizedLaplacianEnergy "
      << "NormalizedLaplacianNumberOf2s "
      << "NormalizedLaplacianNumberOf1s "
      << "NormalizedLaplacianNumberOf0s "
      << "NormalizedLaplacianLowerSlope "
      << "NormalizedLaplacianUpperSlope"
      << "SmallWorldness"
      << std::endl;

    std::stringstream dataStream;
    dataStream << statisticsCalculator->GetNumberOfVertices() << " "
      << statisticsCalculator->GetNumberOfEdges() << " "
      << statisticsCalculator->GetAverageDegree() << " "
      << statisticsCalculator->GetConnectionDensity() << " "
      << statisticsCalculator->GetNumberOfConnectedComponents() << " "
      << statisticsCalculator->GetAverageComponentSize() << " "
      << statisticsCalculator->GetLargestComponentSize() << " "
      << statisticsCalculator->GetRatioOfNodesInLargestComponent() << " "
      << statisticsCalculator->GetHopPlotExponent() << " "
      << statisticsCalculator->GetEffectiveHopDiameter() << " "
      << statisticsCalculator->GetAverageClusteringCoefficientsC() << " "
      << statisticsCalculator->GetAverageClusteringCoefficientsD() << " "
      << statisticsCalculator->GetAverageClusteringCoefficientsE() << " "
      << statisticsCalculator->GetAverageVertexBetweennessCentrality() << " "
      << statisticsCalculator->GetAverageEdgeBetweennessCentrality() << " "
      << statisticsCalculator->GetNumberOfIsolatedPoints() << " "
      << statisticsCalculator->GetRatioOfIsolatedPoints() << " "
      << statisticsCalculator->GetNumberOfEndPoints() << " "
      << statisticsCalculator->GetRatioOfEndPoints() << " "
      << statisticsCalculator->GetDiameter() << " "
      << statisticsCalculator->GetDiameter90() << " "
      << statisticsCalculator->GetRadius() << " "
      << statisticsCalculator->GetRadius90() << " "
      << statisticsCalculator->GetAverageEccentricity() << " "
      << statisticsCalculator->GetAverageEccentricity90() << " "
      << statisticsCalculator->GetAveragePathLength() << " "
      << statisticsCalculator->GetNumberOfCentralPoints() << " "
      << statisticsCalculator->GetRatioOfCentralPoints() << " "
      << statisticsCalculator->GetSpectralRadius() << " "
      << statisticsCalculator->GetSecondLargestEigenValue() << " "
      << statisticsCalculator->GetAdjacencyTrace() << " "
      << statisticsCalculator->GetAdjacencyEnergy() << " "
      << statisticsCalculator->GetLaplacianTrace() << " "
      << statisticsCalculator->GetLaplacianEnergy() << " "
      << statisticsCalculator->GetLaplacianSpectralGap() << " "
      << statisticsCalculator->GetNormalizedLaplacianTrace() << " "
      << statisticsCalculator->GetNormalizedLaplacianEnergy() << " "
      << statisticsCalculator->GetNormalizedLaplacianNumberOf2s() << " "
      << statisticsCalculator->GetNormalizedLaplacianNumberOf1s() << " "
      << statisticsCalculator->GetNormalizedLaplacianNumberOf0s() << " "
      << statisticsCalculator->GetNormalizedLaplacianLowerSlope() << " "
      << statisticsCalculator->GetNormalizedLaplacianUpperSlope() << " "
      << statisticsCalculator->GetSmallWorldness()
      << std::endl;

    std::ofstream outFile( outName.c_str(), std::ios::out );

    if( ! outFile.is_open() )
    {
      std::string errorMessage = "Could not open " + outName + " for writing.";
      MITK_TEST_CONDITION_REQUIRED( outFile.is_open(), errorMessage);
      return;
    }

    outFile << headerStream.str() << dataStream.str();
    outFile.close();
  }
}

/**
* @brief mitkConnectomicsStatisticsCalculatorTest A test of a number of network statistics
*/
int mitkConnectomicsStatisticsCalculatorTest(int argc, char* argv[])
{
  MITK_TEST_BEGIN(mitkConnectomicsStatisticsCalculatorTest);

  bool invalidNumberOfArguments( argc == 1 );

  if( invalidNumberOfArguments )
  {
    std::string errorMessage = "Wrong number of arguments.\nUsage: <network-filename> <network-out-filename> [list of local labels]";
    MITK_TEST_CONDITION_REQUIRED( invalidNumberOfArguments, errorMessage);
    return 0;
  }

  std::string networkName = argv[1];
  std::string outName = "";
  std::vector< std::vector< std::string > > vectorOfLabelVectors;

  if( argc > 2 )
  {
    outName = argv[2];
    for(int loop(3); loop < argc; loop++ )
    {
      vectorOfLabelVectors.at(0).push_back( argv[loop] );
    }
  }

  CalculateStatistics( networkName, outName, vectorOfLabelVectors );

  MITK_TEST_END();
}
<commit_msg>port statistics calulator test<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

// Tesing
#include "mitkTestingMacros.h"
#include "mitkTestFixture.h"

// std includes
#include <string>
#include <sstream>

// MITK includes
#include <mitkBaseDataIOFactory.h>
#include <mitkConnectomicsStatisticsCalculator.h>

class mitkConnectomicsStatisticsCalculatorTestSuite : public mitk::TestFixture
{
  CPPUNIT_TEST_SUITE(mitkConnectomicsStatisticsCalculatorTestSuite);
  MITK_TEST(StatisticsCalculatorUpdate);
  CPPUNIT_TEST_SUITE_END();

private:

  mitk::ConnectomicsNetwork::Pointer m_Network;
  std::string m_NetworkPath;

public:

  /**
  * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members for a new test case. (If the members are not used in a test, the method does not need to be called).
  */
  void setUp()
  {
    //load network

    m_NetworkPath = GetTestDataFilePath("/DiffusionImaging/Connectomics/reference.cnf");
    const std::string s1="", s2="";

    std::vector<mitk::BaseData::Pointer> networkFile =
      mitk::BaseDataIO::LoadBaseDataFromFile( m_NetworkPath, s1, s2, false );
    if( networkFile.empty() )
    {
      std::string errorMessage = "File at " + m_NetworkPath + " could not be read. Aborting.";
      CPPUNIT_ASSERT_MESSAGE( errorMessage, !networkFile.empty() );
      return;
    }
    mitk::BaseData* networkBaseData = networkFile.at(0);
    mitk::ConnectomicsNetwork* network = dynamic_cast<mitk::ConnectomicsNetwork*>( networkBaseData );

    if( !network )
    {
      std::string errorMessage = "Read file at " + m_NetworkPath + " could not be recognized as network. Aborting.";
      CPPUNIT_ASSERT_MESSAGE( errorMessage, network);
      return;
    }

    m_Network = network;
  }

  void tearDown()
  {
    m_Network = NULL;
  }

  void StatisticsCalculatorUpdate()
  {
    mitk::ConnectomicsStatisticsCalculator::Pointer statisticsCalculator = mitk::ConnectomicsStatisticsCalculator::New();

    statisticsCalculator->SetNetwork( m_Network );
    statisticsCalculator->Update();

    double eps( 0.0001 );

    CPPUNIT_ASSERT_MESSAGE( "GetNumberOfVertices", mitk::Equal( statisticsCalculator->GetNumberOfVertices( ), 4 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetNumberOfEdges" , mitk::Equal( statisticsCalculator->GetNumberOfEdges( ), 5 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAverageDegree", mitk::Equal( statisticsCalculator->GetAverageDegree( ), 2.5 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetConnectionDensity", mitk::Equal( statisticsCalculator->GetConnectionDensity( ), 0.833333 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetNumberOfConnectedComponents", mitk::Equal( statisticsCalculator->GetNumberOfConnectedComponents( ), 1 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAverageComponentSize", mitk::Equal( statisticsCalculator->GetAverageComponentSize( ), 4 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetLargestComponentSize", mitk::Equal( statisticsCalculator->GetLargestComponentSize( ), 4 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetRatioOfNodesInLargestComponent", mitk::Equal( statisticsCalculator->GetRatioOfNodesInLargestComponent( ), 1 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetHopPlotExponent", mitk::Equal( statisticsCalculator->GetHopPlotExponent( ), 0.192645 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetEffectiveHopDiameter", mitk::Equal( statisticsCalculator->GetEffectiveHopDiameter( ), 1 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAverageClusteringCoefficientsC", mitk::Equal( statisticsCalculator->GetAverageClusteringCoefficientsC( ), 0.833333 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAverageClusteringCoefficientsD", mitk::Equal( statisticsCalculator->GetAverageClusteringCoefficientsD( ), 0.916667 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAverageClusteringCoefficientsE", mitk::Equal( statisticsCalculator->GetAverageClusteringCoefficientsE( ), 0.833333 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAverageVertexBetweennessCentrality", mitk::Equal( statisticsCalculator->GetAverageVertexBetweennessCentrality( ), 0.25 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAverageEdgeBetweennessCentrality", mitk::Equal( statisticsCalculator->GetAverageEdgeBetweennessCentrality( ), 1.4 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetNumberOfIsolatedPoints" , mitk::Equal( statisticsCalculator->GetNumberOfIsolatedPoints( ), 0 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetRatioOfIsolatedPoints", mitk::Equal( statisticsCalculator->GetRatioOfIsolatedPoints( ), 0 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetNumberOfEndPoints", mitk::Equal( statisticsCalculator->GetNumberOfEndPoints( ), 0 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetRatioOfEndPoints", mitk::Equal( statisticsCalculator->GetRatioOfEndPoints( ), 0 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetDiameter", mitk::Equal( statisticsCalculator->GetDiameter( ), 2 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetDiameter90", mitk::Equal( statisticsCalculator->GetDiameter90( ), 2 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetRadius" , mitk::Equal( statisticsCalculator->GetRadius( ), 1 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetRadius90", mitk::Equal( statisticsCalculator->GetRadius90( ), 1 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAverageEccentricity", mitk::Equal( statisticsCalculator->GetAverageEccentricity( ), 1.5 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAverageEccentricity90", mitk::Equal( statisticsCalculator->GetAverageEccentricity90( ), 1.5 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetAveragePathLength" , mitk::Equal( statisticsCalculator->GetAveragePathLength( ), 1.16667 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetNumberOfCentralPoints" , mitk::Equal( statisticsCalculator->GetNumberOfCentralPoints( ), 2 , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetRatioOfCentralPoints", mitk::Equal( statisticsCalculator->GetRatioOfCentralPoints( ), 0.5 , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetSpectralRadius( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetSecondLargestEigenValue( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetAdjacencyTrace( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetAdjacencyEnergy( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetLaplacianTrace( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetLaplacianEnergy( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetLaplacianSpectralGap( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianTrace( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianEnergy( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianNumberOf2s( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianNumberOf1s( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianNumberOf0s( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianLowerSlope( ), , eps, true ) );
    // CPPUNIT_ASSERT_MESSAGE( " ", mitk::Equal( statisticsCalculator->GetNormalizedLaplacianUpperSlope( ), , eps, true ) );
    CPPUNIT_ASSERT_MESSAGE( "GetSmallWorldness", mitk::Equal( statisticsCalculator->GetSmallWorldness( ), 1.72908 , eps, true ) );

  }
};

MITK_TEST_SUITE_REGISTRATION(mitkConnectomicsStatisticsCalculator)
<|endoftext|>