<commit_before>//---------------------------------------------------------------------------//
//!
//! \file   Utility_HydrogenFormFactorDistribution.cpp
//! \author Alex Robinson
//! \brief  The Hydrogen form factor distribution class definition
//!
//---------------------------------------------------------------------------//

// Std Lib Includes
#include <limits>

// FRENSIE Includes
#include "Utility_HydrogenFormFactorDistribution.hpp"
#include "Utility_PhysicalConstants.hpp"
#include "Utility_ExceptionTestMacros.hpp"
#include "Utility_ContractException.hpp"

namespace Utility{

// Constructor
HydrogenFormFactorDistribution::HydrogenFormFactorDistribution()
{ /* ... */ }

// Evaluate the distribution
double HydrogenFormFactorDistribution::evaluate(
					   const double indep_var_value ) const
{
  // Make sure the value is valid
  testPrecondition( !ST::isnaninf( value ) );
  testPrecondition( value >= 0.0 );

  if( indep_var_value >= 0.0 )
  {
    double arg = 1.0 + PhysicalConstants::inverse_fine_structure_constant*
      PhysicalConstants::inverse_fine_structure_constant*
      indep_var_value*indep_var_value*1e-16/2.0;

    // double arg = 1.0 + PhysicalConstants::inverse_fine_structure_constant*
    //   PhysicalConstants::inverse_fine_structure_constant*
    //   indep_var_value*indep_var_value/2.0;

    return 1 - 1.0/(arg*arg*arg*arg);
  }
  else
    return 0.0;
}

// Evaluate the PDF
double HydrogenFormFactorDistribution::evaluatePDF(
					   const double indep_var_value ) const
{
  THROW_EXCEPTION( std::logic_error,
		   "Error: This function has not been implemented yet!" );

  return 0.0;
}

// Return a random sample from the distribution
double HydrogenFormFactorDistribution::sample()
{
  return (const_cast<const HydrogenFormFactorDistribution*>(this))->sample();
}

// Return a random sample from the distribution
double HydrogenFormFactorDistribution::sample() const
{
  THROW_EXCEPTION( std::logic_error,
		   "Error: This function has not been implemented yet!" );

  return 0.0;
}

// Return the sampling efficiency from the distribution
double HydrogenFormFactorDistribution::getSamplingEfficiency() const
{
  THROW_EXCEPTION( std::logic_error,
		   "Error: This function has not been implemented yet!" );

  return 1.0;
}

// Return the upper bound of the distribution independent variable
double HydrogenFormFactorDistribution::getUpperBoundOfIndepVar() const
{
  return std::numeric_limits<double>::infinity();
}

// Return the lower bound of the distribution independent variable
double HydrogenFormFactorDistribution::getLowerBoundOfIndepVar() const
{
  return 0.0;
}

// Return the distribution type
OneDDistributionType HydrogenFormFactorDistribution::getDistributionType() const
{
  return HYDROGEN_FORM_FACTOR_DISTRIBUTION;
}

} // end Utility namespace

//---------------------------------------------------------------------------//
// end Utility_HydrogenFormFactorDistribution.cpp
//---------------------------------------------------------------------------//
<commit_msg>Fixed a precondition error in the hydrogen form factor distribution.<commit_after>//---------------------------------------------------------------------------//
//!
//! \file   Utility_HydrogenFormFactorDistribution.cpp
//! \author Alex Robinson
//! \brief  The Hydrogen form factor distribution class definition
//!
//---------------------------------------------------------------------------//

// Std Lib Includes
#include <limits>

// FRENSIE Includes
#include "Utility_HydrogenFormFactorDistribution.hpp"
#include "Utility_PhysicalConstants.hpp"
#include "Utility_ExceptionTestMacros.hpp"
#include "Utility_ContractException.hpp"

namespace Utility{

// Constructor
HydrogenFormFactorDistribution::HydrogenFormFactorDistribution()
{ /* ... */ }

// Evaluate the distribution
double HydrogenFormFactorDistribution::evaluate(
					   const double indep_var_value ) const
{
  // Make sure the value is valid
  testPrecondition( !ST::isnaninf( indep_var_value ) );
  testPrecondition( indep_var_value >= 0.0 );

  if( indep_var_value >= 0.0 )
  {
    double arg = 1.0 + PhysicalConstants::inverse_fine_structure_constant*
      PhysicalConstants::inverse_fine_structure_constant*
      indep_var_value*indep_var_value*1e-16/2.0;

    // double arg = 1.0 + PhysicalConstants::inverse_fine_structure_constant*
    //   PhysicalConstants::inverse_fine_structure_constant*
    //   indep_var_value*indep_var_value/2.0;

    return 1 - 1.0/(arg*arg*arg*arg);
  }
  else
    return 0.0;
}

// Evaluate the PDF
double HydrogenFormFactorDistribution::evaluatePDF(
					   const double indep_var_value ) const
{
  THROW_EXCEPTION( std::logic_error,
		   "Error: This function has not been implemented yet!" );

  return 0.0;
}

// Return a random sample from the distribution
double HydrogenFormFactorDistribution::sample()
{
  return (const_cast<const HydrogenFormFactorDistribution*>(this))->sample();
}

// Return a random sample from the distribution
double HydrogenFormFactorDistribution::sample() const
{
  THROW_EXCEPTION( std::logic_error,
		   "Error: This function has not been implemented yet!" );

  return 0.0;
}

// Return the sampling efficiency from the distribution
double HydrogenFormFactorDistribution::getSamplingEfficiency() const
{
  THROW_EXCEPTION( std::logic_error,
		   "Error: This function has not been implemented yet!" );

  return 1.0;
}

// Return the upper bound of the distribution independent variable
double HydrogenFormFactorDistribution::getUpperBoundOfIndepVar() const
{
  return std::numeric_limits<double>::infinity();
}

// Return the lower bound of the distribution independent variable
double HydrogenFormFactorDistribution::getLowerBoundOfIndepVar() const
{
  return 0.0;
}

// Return the distribution type
OneDDistributionType HydrogenFormFactorDistribution::getDistributionType() const
{
  return HYDROGEN_FORM_FACTOR_DISTRIBUTION;
}

} // end Utility namespace

//---------------------------------------------------------------------------//
// end Utility_HydrogenFormFactorDistribution.cpp
//---------------------------------------------------------------------------//
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004, Mart Kelder (mart.kde@hccnet.nl)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "accountmanager.h"

#include "dcopdrop.h"
#include "kio.h"
#include "maildrop.h"
#include "password.h"
#include "protocol.h"
#include "protocols.h"
#include "subjectsdlg.h"

#include <kaudioplayer.h>
#include <kconfig.h>
#include <kdebug.h>

#include <qptrlist.h>

KornSubjectsDlg* AccountManager::_subjectsDlg = 0;

AccountManager::AccountManager( QObject * parent, const char * name )
	: QObject( parent, name ),
	_kioList( new QPtrList< KMailDrop > ),
	_dcopList( new QPtrList< DCOPDrop > ),
	_dropInfo( new QMap< KMailDrop*, Dropinfo* > )
{
	_kioList->setAutoDelete( true );
	_dcopList->setAutoDelete( true );
}

AccountManager::~AccountManager()
{
	delete _kioList;
	delete _dcopList;
	delete _dropInfo;
}

void AccountManager::readConfig( KConfig* config, const int index )
{
	KConfigGroup *masterGroup = new KConfigGroup( config, QString( "korn-%1" ).arg( index ) );
	QStringList dcop = masterGroup->readListEntry( "dcop", ',' );
	KConfigGroup *accountGroup;
	int counter = 0;

	while( config->hasGroup( QString( "korn-%1-%2" ).arg( index ).arg( counter ) ) )
	{
		accountGroup = new KConfigGroup( config, QString( "korn-%1-%2" ).arg( index ).arg( counter ) );

		const Protocol *proto = Protocols::getProto( accountGroup->readEntry( "protocol" ) );
		if( !proto )
		{
			kdWarning() << "Protocol werd niet gevonden" << endl;
			++counter;
			continue;
		}
		QMap< QString, QString > *configmap = proto->createConfig( accountGroup,
		                                                   KOrnPassword::readKOrnPassword( index, counter, *accountGroup ) );
		KMailDrop *kiodrop = proto->createMaildrop( accountGroup );
		const Protocol *nproto = proto->getProtocol( accountGroup );
		Dropinfo *info = new Dropinfo;

		if( !kiodrop || !configmap || !nproto )
		{
			//Error occured when reading for config
			++counter;
			continue;
		}

		//TODO: connect some stuff
		connect( kiodrop, SIGNAL( changed( int, KMailDrop* ) ), this, SLOT( slotChanged( int, KMailDrop* ) ) );
		connect( kiodrop, SIGNAL( showPassivePopup( QPtrList< KornMailSubject >*, int, bool, const QString& ) ),
			 this, SLOT( slotShowPassivePopup( QPtrList< KornMailSubject >*, int, bool, const QString& ) ) );
		connect( kiodrop, SIGNAL( showPassivePopup( const QString&, const QString& ) ),
			 this, SLOT( slotShowPassivePopup( const QString&, const QString& ) ) );
		connect( kiodrop, SIGNAL( validChanged( bool ) ), this, SLOT( slotValidChanged( bool ) ) );

		kiodrop->readGeneralConfigGroup( *masterGroup );
		if( !kiodrop->readConfigGroup( *accountGroup ) || !kiodrop->readConfigGroup( *configmap, nproto ) )
		{
			++counter;
			continue;
		}

		kiodrop->startMonitor();

		_kioList->append( kiodrop );

		info->index = counter;
		info->reset = accountGroup->readNumEntry( "reset", 0 );
		info->msgnr = info->reset;
		info->newMessages = false;

		_dropInfo->insert( kiodrop, info );

		++counter;
	}

	QStringList::Iterator it;
	for( it = dcop.begin(); it != dcop.end(); ++it )
	{
		DCOPDrop *dcopdrop = new DCOPDrop;
		Dropinfo *info = new Dropinfo;

		connect( dcopdrop, SIGNAL( changed( int, KMailDrop* ) ), this, SLOT( slotChanged( int, KMailDrop* ) ) );
		connect( dcopdrop, SIGNAL( showPassivePopup( QPtrList< KornMailSubject >*, int, bool, const QString& ) ),
			 this, SLOT( slotShowPassivePopup( QPtrList< KornMailSubject >*, int, bool, const QString& ) ) );

		dcopdrop->readConfigGroup( *masterGroup );
		dcopdrop->setDCOPName( *it );

		_dcopList->append( dcopdrop );

		info->index = 0;
		info->reset = 0;
		info->msgnr = 0;
		info->newMessages = false;

		_dropInfo->insert( dcopdrop, info );
	}

	setCount( totalMessages(), hasNewMessages() );
}

void AccountManager::writeConfig( KConfig* config, const int index )
{
	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
	{
		config->setGroup( QString( "korn-%1-%2" ).arg( index ).arg( it.data()->index ) );
		config->writeEntry( "reset", it.data()->reset );
	}
}

QString AccountManager::getTooltip() const
{
	QStringList result;
	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
		if( it.key()->valid() )
			result.append( QString( "%1: %2" ).arg( it.key()->realName() ).arg( it.data()->msgnr - it.data()->reset ));
		else
			result.append( QString( "%1: invalid" ).arg( it.key()->realName() ) );
	result.sort();
	return result.join( QChar( '\n' ) );
}

void AccountManager::doRecheck()
{
	KMailDrop *item;
	for( item = _kioList->first(); item; item = _kioList->next() )
		item->forceRecheck();
}

void AccountManager::doReset()
{
	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
	{
		it.data()->reset = it.data()->msgnr;
		it.data()->newMessages = false;
	}

	setCount( 0, false );
}

void AccountManager::doView()
{
	QMap< KMailDrop*, Dropinfo* >::Iterator it;

	if( !_subjectsDlg )
		_subjectsDlg = new KornSubjectsDlg();

	_subjectsDlg->clear();

	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
		_subjectsDlg->addMailBox( it.key() );

	_subjectsDlg->loadMessages();
}

void AccountManager::doStartTimer()
{
	KMailDrop *item;

	for( item = _kioList->first(); item; item = _kioList->next() )
		item->startMonitor();
}

void AccountManager::doStopTimer()
{
	KMailDrop *item;

	for( item = _kioList->first(); item; item = _kioList->next() )
		item->stopMonitor();
}

int AccountManager::totalMessages()
{
	int result = 0;

	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
		//if( it.date()->msgnr - it.date()->reset > 0 )
			result += it.data()->msgnr - it.data()->reset;

	return result;
}

bool AccountManager::hasNewMessages()
{
	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
		if( it.data()->newMessages )
			return true;

	return false;
}

void AccountManager::playSound( const QString& file )
{
	KAudioPlayer::play( file );
}

void AccountManager::slotChanged( int count, KMailDrop* mailDrop )
{
	Dropinfo *info = _dropInfo->find( mailDrop ).data();
	info->newMessages = count > info->msgnr || ( count == info->msgnr && info->newMessages );

	if( count > info->msgnr )
	{
		if( !mailDrop->soundFile().isEmpty() )
			playSound( mailDrop->soundFile() );
		if( !mailDrop->newMailCmd().isEmpty() )
			runCommand( mailDrop->newMailCmd() );
	}

	info->msgnr = count;
	if( info->msgnr - info->reset < 0 )
		info->reset = 0;

	setCount( totalMessages(), hasNewMessages() && totalMessages() > 0 );
	setTooltip( getTooltip() );
}

void AccountManager::slotValidChanged( bool )
{
	setTooltip( getTooltip() );
}

#include "accountmanager.moc"
<commit_msg>Fix memory leak.<commit_after>/*
 * Copyright (C) 2004, Mart Kelder (mart.kde@hccnet.nl)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "accountmanager.h"

#include "dcopdrop.h"
#include "kio.h"
#include "maildrop.h"
#include "password.h"
#include "protocol.h"
#include "protocols.h"
#include "subjectsdlg.h"

#include <kaudioplayer.h>
#include <kconfig.h>
#include <kdebug.h>

#include <qptrlist.h>

KornSubjectsDlg* AccountManager::_subjectsDlg = 0;

AccountManager::AccountManager( QObject * parent, const char * name )
	: QObject( parent, name ),
	_kioList( new QPtrList< KMailDrop > ),
	_dcopList( new QPtrList< DCOPDrop > ),
	_dropInfo( new QMap< KMailDrop*, Dropinfo* > )
{
	_kioList->setAutoDelete( true );
	_dcopList->setAutoDelete( true );
}

AccountManager::~AccountManager()
{
	delete _kioList;
	delete _dcopList;
	delete _dropInfo;
}

void AccountManager::readConfig( KConfig* config, const int index )
{
	KConfigGroup *masterGroup = new KConfigGroup( config, QString( "korn-%1" ).arg( index ) );
	QStringList dcop = masterGroup->readListEntry( "dcop", ',' );
	KConfigGroup *accountGroup;
	int counter = 0;

	while( config->hasGroup( QString( "korn-%1-%2" ).arg( index ).arg( counter ) ) )
	{
		accountGroup = new KConfigGroup( config, QString( "korn-%1-%2" ).arg( index ).arg( counter ) );

		const Protocol *proto = Protocols::getProto( accountGroup->readEntry( "protocol" ) );
		if( !proto )
		{
			kdWarning() << "Protocol werd niet gevonden" << endl;
			++counter;
			continue;
		}
		QMap< QString, QString > *configmap = proto->createConfig( accountGroup,
		                                                   KOrnPassword::readKOrnPassword( index, counter, *accountGroup ) );
		KMailDrop *kiodrop = proto->createMaildrop( accountGroup );
		const Protocol *nproto = proto->getProtocol( accountGroup );
		Dropinfo *info = new Dropinfo;

		if( !kiodrop || !configmap || !nproto )
		{
			//Error occured when reading for config
			++counter;
			delete info;
			continue;
		}

		//TODO: connect some stuff
		connect( kiodrop, SIGNAL( changed( int, KMailDrop* ) ), this, SLOT( slotChanged( int, KMailDrop* ) ) );
		connect( kiodrop, SIGNAL( showPassivePopup( QPtrList< KornMailSubject >*, int, bool, const QString& ) ),
			 this, SLOT( slotShowPassivePopup( QPtrList< KornMailSubject >*, int, bool, const QString& ) ) );
		connect( kiodrop, SIGNAL( showPassivePopup( const QString&, const QString& ) ),
			 this, SLOT( slotShowPassivePopup( const QString&, const QString& ) ) );
		connect( kiodrop, SIGNAL( validChanged( bool ) ), this, SLOT( slotValidChanged( bool ) ) );

		kiodrop->readGeneralConfigGroup( *masterGroup );
		if( !kiodrop->readConfigGroup( *accountGroup ) || !kiodrop->readConfigGroup( *configmap, nproto ) )
		{
			++counter;
			delete info;
			continue;
		}

		kiodrop->startMonitor();

		_kioList->append( kiodrop );

		info->index = counter;
		info->reset = accountGroup->readNumEntry( "reset", 0 );
		info->msgnr = info->reset;
		info->newMessages = false;

		_dropInfo->insert( kiodrop, info );

		++counter;
	}

	QStringList::Iterator it;
	for( it = dcop.begin(); it != dcop.end(); ++it )
	{
		DCOPDrop *dcopdrop = new DCOPDrop;
		Dropinfo *info = new Dropinfo;

		connect( dcopdrop, SIGNAL( changed( int, KMailDrop* ) ), this, SLOT( slotChanged( int, KMailDrop* ) ) );
		connect( dcopdrop, SIGNAL( showPassivePopup( QPtrList< KornMailSubject >*, int, bool, const QString& ) ),
			 this, SLOT( slotShowPassivePopup( QPtrList< KornMailSubject >*, int, bool, const QString& ) ) );

		dcopdrop->readConfigGroup( *masterGroup );
		dcopdrop->setDCOPName( *it );

		_dcopList->append( dcopdrop );

		info->index = 0;
		info->reset = 0;
		info->msgnr = 0;
		info->newMessages = false;

		_dropInfo->insert( dcopdrop, info );
	}

	setCount( totalMessages(), hasNewMessages() );
}

void AccountManager::writeConfig( KConfig* config, const int index )
{
	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
	{
		config->setGroup( QString( "korn-%1-%2" ).arg( index ).arg( it.data()->index ) );
		config->writeEntry( "reset", it.data()->reset );
	}
}

QString AccountManager::getTooltip() const
{
	QStringList result;
	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
		if( it.key()->valid() )
			result.append( QString( "%1: %2" ).arg( it.key()->realName() ).arg( it.data()->msgnr - it.data()->reset ));
		else
			result.append( QString( "%1: invalid" ).arg( it.key()->realName() ) );
	result.sort();
	return result.join( QChar( '\n' ) );
}

void AccountManager::doRecheck()
{
	KMailDrop *item;
	for( item = _kioList->first(); item; item = _kioList->next() )
		item->forceRecheck();
}

void AccountManager::doReset()
{
	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
	{
		it.data()->reset = it.data()->msgnr;
		it.data()->newMessages = false;
	}

	setCount( 0, false );
}

void AccountManager::doView()
{
	QMap< KMailDrop*, Dropinfo* >::Iterator it;

	if( !_subjectsDlg )
		_subjectsDlg = new KornSubjectsDlg();

	_subjectsDlg->clear();

	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
		_subjectsDlg->addMailBox( it.key() );

	_subjectsDlg->loadMessages();
}

void AccountManager::doStartTimer()
{
	KMailDrop *item;

	for( item = _kioList->first(); item; item = _kioList->next() )
		item->startMonitor();
}

void AccountManager::doStopTimer()
{
	KMailDrop *item;

	for( item = _kioList->first(); item; item = _kioList->next() )
		item->stopMonitor();
}

int AccountManager::totalMessages()
{
	int result = 0;

	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
		//if( it.date()->msgnr - it.date()->reset > 0 )
			result += it.data()->msgnr - it.data()->reset;

	return result;
}

bool AccountManager::hasNewMessages()
{
	QMap< KMailDrop*, Dropinfo* >::Iterator it;
	for( it = _dropInfo->begin(); it != _dropInfo->end(); ++it )
		if( it.data()->newMessages )
			return true;

	return false;
}

void AccountManager::playSound( const QString& file )
{
	KAudioPlayer::play( file );
}

void AccountManager::slotChanged( int count, KMailDrop* mailDrop )
{
	Dropinfo *info = _dropInfo->find( mailDrop ).data();
	info->newMessages = count > info->msgnr || ( count == info->msgnr && info->newMessages );

	if( count > info->msgnr )
	{
		if( !mailDrop->soundFile().isEmpty() )
			playSound( mailDrop->soundFile() );
		if( !mailDrop->newMailCmd().isEmpty() )
			runCommand( mailDrop->newMailCmd() );
	}

	info->msgnr = count;
	if( info->msgnr - info->reset < 0 )
		info->reset = 0;

	setCount( totalMessages(), hasNewMessages() && totalMessages() > 0 );
	setTooltip( getTooltip() );
}

void AccountManager::slotValidChanged( bool )
{
	setTooltip( getTooltip() );
}

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


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ExplicitCategoriesProvider.cxx,v $
 * $Revision: 1.3 $
 *
 * 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_chart2.hxx"

#include "ExplicitCategoriesProvider.hxx"
#include "DiagramHelper.hxx"
#include "CommonConverters.hxx"
#include "DataSourceHelper.hxx"
#include "ChartModelHelper.hxx"
#include "ContainerHelper.hxx"
#include "macros.hxx"

//.............................................................................
namespace chart
{
//.............................................................................

using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::std::vector;

ExplicitCategoriesProvider::ExplicitCategoriesProvider( const Reference< chart2::XCoordinateSystem >& xCooSysModel
                                                       , const uno::Reference< frame::XModel >& xChartModel )
    : m_bDirty(true)
    , m_xCooSysModel( xCooSysModel )
    , m_xOriginalCategories()
{
    try
    {
        if( xCooSysModel.is() )
        {
            uno::Reference< XAxis > xAxis( xCooSysModel->getAxisByDimension(0,0) );
            if( xAxis.is() )
                m_xOriginalCategories = xAxis->getScaleData().Categories;
        }

        if( m_xOriginalCategories.is() )
        {
            Reference< chart2::XChartDocument > xChartDoc( xChartModel, uno::UNO_QUERY );
            if( xChartDoc.is() )
            {
                uno::Reference< data::XDataProvider > xDataProvider( xChartDoc->getDataProvider() );

                if( xDataProvider.is() )
                {
                    OUString aCatgoriesRange( DataSourceHelper::getRangeFromValues( m_xOriginalCategories ) );
                    const bool bFirstCellAsLabel = false;
                    const bool bHasCategories = false;
                    const uno::Sequence< sal_Int32 > aSequenceMapping;

                    uno::Reference< data::XDataSource > xColumnCategoriesSource( xDataProvider->createDataSource(
                         DataSourceHelper::createArguments( aCatgoriesRange, aSequenceMapping, true /*bUseColumns*/
                            , bFirstCellAsLabel, bHasCategories ) ) );

                    uno::Reference< data::XDataSource > xRowCategoriesSource( xDataProvider->createDataSource(
                         DataSourceHelper::createArguments( aCatgoriesRange, aSequenceMapping, false /*bUseColumns*/
                            , bFirstCellAsLabel, bHasCategories ) ) );

                    if( xColumnCategoriesSource.is() &&  xRowCategoriesSource.is() )
                    {
                        Sequence< Reference< data::XLabeledDataSequence> > aColumns = xColumnCategoriesSource->getDataSequences();
                        Sequence< Reference< data::XLabeledDataSequence> > aRows = xRowCategoriesSource->getDataSequences();

                        sal_Int32 nColumnCount = aColumns.getLength();
                        sal_Int32 nRowCount = aRows.getLength();
                        if( nColumnCount>1 && nRowCount>1 )
                        {
                            //we have complex categories
                            //->split them in the direction of the first series
                            //detect whether the first series is a row or a column
                            bool bSeriesUsesColumns = true;
                            ::std::vector< Reference< XDataSeries > > aSeries( ChartModelHelper::getDataSeries( xChartModel ) );
                            if( !aSeries.empty() )
                            {
                                uno::Reference< data::XDataSource > xSeriesSource( aSeries.front(), uno::UNO_QUERY );
                                ::rtl::OUString aStringDummy;
                                bool bDummy;
                                uno::Sequence< sal_Int32 > aSeqDummy;
                                DataSourceHelper::readArguments( xDataProvider->detectArguments( xSeriesSource),
                                               aStringDummy, aSeqDummy, bSeriesUsesColumns, bDummy, bDummy );
                            }
                            if( bSeriesUsesColumns )
                                m_aSplitCategoriesList=aColumns;
                            else
                                m_aSplitCategoriesList=aRows;
                        }
                    }
                }
            }
            if( !m_aSplitCategoriesList.getLength() )
            {
                m_aSplitCategoriesList.realloc(1);
                m_aSplitCategoriesList[0]=m_xOriginalCategories;
            }
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

ExplicitCategoriesProvider::~ExplicitCategoriesProvider()
{
}

const Sequence< Reference< data::XLabeledDataSequence> >& ExplicitCategoriesProvider::getSplitCategoriesList()
{
    return m_aSplitCategoriesList;
}

bool ExplicitCategoriesProvider::hasComplexCategories() const
{
    return m_aSplitCategoriesList.getLength() > 1;
}

sal_Int32 ExplicitCategoriesProvider::getCategoryLevelCount() const
{
    sal_Int32 nCount = m_aSplitCategoriesList.getLength();
    if(!nCount)
        nCount = 1;
    return nCount;
}

std::vector<sal_Int32> lcl_getLimitingBorders( const std::vector< ComplexCategory >& rComplexCategories )
{
    std::vector<sal_Int32> aLimitingBorders;
    std::vector< ComplexCategory >::const_iterator aIt( rComplexCategories.begin() );
    std::vector< ComplexCategory >::const_iterator aEnd( rComplexCategories.end() );
    sal_Int32 nBorderIndex = 0; /*border below the index*/
    for( ; aIt != aEnd; ++aIt )
    {
        ComplexCategory aComplexCategory(*aIt);
        nBorderIndex += aComplexCategory.Count;
        aLimitingBorders.push_back(nBorderIndex);
    }
    return aLimitingBorders;
}

uno::Sequence< rtl::OUString > lcl_DataToStringSequence( const uno::Reference< data::XDataSequence >& xDataSequence )
{
    uno::Sequence< rtl::OUString > aStrings;

    OSL_ASSERT( xDataSequence.is());
    if( !xDataSequence.is() )
        return aStrings;

    uno::Reference< data::XTextualDataSequence > xTextualDataSequence( xDataSequence, uno::UNO_QUERY );
    if( xTextualDataSequence.is() )
    {
        aStrings = xTextualDataSequence->getTextualData();
    }
    else
    {
        uno::Sequence< uno::Any > aValues = xDataSequence->getData();
        aStrings.realloc(aValues.getLength());

        for(sal_Int32 nN=aValues.getLength();nN--;)
            aValues[nN] >>= aStrings[nN];
    }

    return aStrings;
}

SplitCategoriesProvider::~SplitCategoriesProvider()
{
}

class SplitCategoriesProvider_ForLabeledDataSequences : public SplitCategoriesProvider
{
public:

    explicit SplitCategoriesProvider_ForLabeledDataSequences( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XLabeledDataSequence> >& rSplitCategoriesList )
        : m_rSplitCategoriesList( rSplitCategoriesList )
    {}
    virtual ~SplitCategoriesProvider_ForLabeledDataSequences()
    {}

    virtual sal_Int32 getLevelCount() const;
    virtual uno::Sequence< rtl::OUString > getStringsForLevel( sal_Int32 nIndex ) const;

private:
    const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XLabeledDataSequence> >& m_rSplitCategoriesList;
};

sal_Int32 SplitCategoriesProvider_ForLabeledDataSequences::getLevelCount() const
{
    return m_rSplitCategoriesList.getLength();
}
uno::Sequence< rtl::OUString > SplitCategoriesProvider_ForLabeledDataSequences::getStringsForLevel( sal_Int32 nLevel ) const
{
    uno::Sequence< rtl::OUString > aRet;
    Reference< data::XLabeledDataSequence > xLabeledDataSequence( m_rSplitCategoriesList[nLevel] );
    if( xLabeledDataSequence.is() )
        aRet = lcl_DataToStringSequence( xLabeledDataSequence->getValues() );
    return aRet;
}

std::vector< ComplexCategory > lcl_DataSequenceToComplexCategoryVector(
    const uno::Sequence< rtl::OUString >& rStrings
    , const std::vector<sal_Int32>& rLimitingBorders, bool bCreateSingleCategories )
{
    std::vector< ComplexCategory > aResult;

    sal_Int32 nMaxCount = rStrings.getLength();
    OUString aPrevious;
    sal_Int32 nCurrentCount=0;
    for( sal_Int32 nN=0; nN<nMaxCount; nN++ )
    {
        OUString aCurrent = rStrings[nN];
        if( bCreateSingleCategories || ::std::find( rLimitingBorders.begin(), rLimitingBorders.end(), nN ) != rLimitingBorders.end() )
        {
            aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
            nCurrentCount=1;
            aPrevious = aCurrent;
        }
        else
        {
            if( aCurrent.getLength() && aPrevious != aCurrent )
            {
                if( aPrevious.getLength() )
                {
                    aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
                    nCurrentCount=1;
                }
                else
                    nCurrentCount++;
                aPrevious = aCurrent;
            }
            else
                nCurrentCount++;
        }
    }
    if( nCurrentCount )
        aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );

    return aResult;
}

sal_Int32 lcl_getCategoryCount( std::vector< ComplexCategory >& rComplexCategories )
{
    sal_Int32 nCount = 0;
    std::vector< ComplexCategory >::iterator aIt( rComplexCategories.begin() );
    std::vector< ComplexCategory >::const_iterator aEnd( rComplexCategories.end() );
    for( ; aIt != aEnd; ++aIt )
        nCount+=aIt->Count;
    return nCount;
}

Sequence< OUString > lcl_getExplicitSimpleCategories(
    const SplitCategoriesProvider& rSplitCategoriesProvider,
    ::std::vector< ::std::vector< ComplexCategory > >& rComplexCats )
{
    Sequence< OUString > aRet;

    rComplexCats.clear();
    sal_Int32 nLCount = rSplitCategoriesProvider.getLevelCount();
    for( sal_Int32 nL = 0; nL < nLCount; nL++ )
    {
        std::vector<sal_Int32> aLimitingBorders;
        if(nL>0)
            aLimitingBorders = lcl_getLimitingBorders( rComplexCats.back() );
        rComplexCats.push_back( lcl_DataSequenceToComplexCategoryVector(
            rSplitCategoriesProvider.getStringsForLevel(nL), aLimitingBorders, nL==(nLCount-1) ) );
    }

    std::vector< std::vector< ComplexCategory > >::iterator aOuterIt( rComplexCats.begin() );
    std::vector< std::vector< ComplexCategory > >::const_iterator aOuterEnd( rComplexCats.end() );

    //ensure that the category count is the same on each level
    sal_Int32 nMaxCategoryCount = 0;
    {
        for( aOuterIt=rComplexCats.begin(); aOuterIt != aOuterEnd; ++aOuterIt )
        {
            sal_Int32 nCurrentCount = lcl_getCategoryCount( *aOuterIt );
            nMaxCategoryCount = std::max( nCurrentCount, nMaxCategoryCount );
        }
        for( aOuterIt=rComplexCats.begin(); aOuterIt != aOuterEnd; ++aOuterIt )
        {
            sal_Int32 nCurrentCount = lcl_getCategoryCount( *aOuterIt );
            if( nCurrentCount< nMaxCategoryCount )
            {
                ComplexCategory& rComplexCategory = aOuterIt->back();
                rComplexCategory.Count += (nMaxCategoryCount-nCurrentCount);
            }
        }
    }

    //create a list with an element for every index
    std::vector< std::vector< ComplexCategory > > aComplexCatsPerIndex;
    for( aOuterIt=rComplexCats.begin() ; aOuterIt != aOuterEnd; ++aOuterIt )
    {
        std::vector< ComplexCategory > aSingleLevel;
        std::vector< ComplexCategory >::iterator aIt( aOuterIt->begin() );
        std::vector< ComplexCategory >::const_iterator aEnd( aOuterIt->end() );
        for( ; aIt != aEnd; ++aIt )
        {
            ComplexCategory aComplexCategory( *aIt );
            sal_Int32 nCount = aComplexCategory.Count;
            while( nCount-- )
                aSingleLevel.push_back(aComplexCategory);
        }
        aComplexCatsPerIndex.push_back( aSingleLevel );
    }

    if(nMaxCategoryCount)
    {
        aRet.realloc(nMaxCategoryCount);
        aOuterEnd = aComplexCatsPerIndex.end();
        OUString aSpace(C2U(" "));
        for(sal_Int32 nN=0; nN<nMaxCategoryCount; nN++)
        {
            OUString aText;
            for( aOuterIt=aComplexCatsPerIndex.begin() ; aOuterIt != aOuterEnd; ++aOuterIt )
            {
                OUString aAddText = (*aOuterIt)[nN].Text;
                if( aAddText.getLength() )
                {
                    if(aText.getLength())
                        aText += aSpace;
                    aText += aAddText;
                }
            }
            aRet[nN]=aText;
        }
    }
    return aRet;
}

//static
Sequence< OUString > ExplicitCategoriesProvider::getExplicitSimpleCategories(
    const SplitCategoriesProvider& rSplitCategoriesProvider )
{
    vector< vector< ComplexCategory > > aComplexCats;
    return lcl_getExplicitSimpleCategories( rSplitCategoriesProvider, aComplexCats );
}

void ExplicitCategoriesProvider::init()
{
    if( m_bDirty )
    {
        m_aExplicitCategories.realloc(0);
        m_aComplexCats.clear();//not one per index

        if( m_xOriginalCategories.is() )
        {
            if( !hasComplexCategories() )
                m_aExplicitCategories = DataSequenceToStringSequence(m_xOriginalCategories->getValues());
            else
                m_aExplicitCategories = lcl_getExplicitSimpleCategories(
                    SplitCategoriesProvider_ForLabeledDataSequences( m_aSplitCategoriesList ), m_aComplexCats );
        }
        if(!m_aExplicitCategories.getLength())
            m_aExplicitCategories = DiagramHelper::generateAutomaticCategoriesFromCooSys( m_xCooSysModel );
        m_bDirty = false;
    }
}

Sequence< ::rtl::OUString > ExplicitCategoriesProvider::getSimpleCategories()
{
    init();
    return m_aExplicitCategories;
}

std::vector< ComplexCategory >  ExplicitCategoriesProvider::getCategoriesByLevel( sal_Int32 nLevel )
{
    std::vector< ComplexCategory > aRet;
    init();
    sal_Int32 nMaxIndex = m_aComplexCats.size()-1;
    if( nLevel >= 0 && nLevel <= nMaxIndex  )
        aRet = m_aComplexCats[nMaxIndex-nLevel];
    return aRet;
}

// static
OUString ExplicitCategoriesProvider::getCategoryByIndex(
          const Reference< XCoordinateSystem >& xCooSysModel
        , const uno::Reference< frame::XModel >& xChartModel
        , sal_Int32 nIndex )
{
    if( xCooSysModel.is())
    {
        ExplicitCategoriesProvider aExplicitCategoriesProvider( xCooSysModel, xChartModel );
        Sequence< OUString > aCategories( aExplicitCategoriesProvider.getSimpleCategories());
        if( nIndex < aCategories.getLength())
            return aCategories[ nIndex ];
    }
    return OUString();
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>chartmultiline: #i82971# complex categories (part8 - change assignment of leading empty cells)<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ExplicitCategoriesProvider.cxx,v $
 * $Revision: 1.3 $
 *
 * 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_chart2.hxx"

#include "ExplicitCategoriesProvider.hxx"
#include "DiagramHelper.hxx"
#include "CommonConverters.hxx"
#include "DataSourceHelper.hxx"
#include "ChartModelHelper.hxx"
#include "ContainerHelper.hxx"
#include "macros.hxx"

//.............................................................................
namespace chart
{
//.............................................................................

using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::std::vector;

ExplicitCategoriesProvider::ExplicitCategoriesProvider( const Reference< chart2::XCoordinateSystem >& xCooSysModel
                                                       , const uno::Reference< frame::XModel >& xChartModel )
    : m_bDirty(true)
    , m_xCooSysModel( xCooSysModel )
    , m_xOriginalCategories()
{
    try
    {
        if( xCooSysModel.is() )
        {
            uno::Reference< XAxis > xAxis( xCooSysModel->getAxisByDimension(0,0) );
            if( xAxis.is() )
                m_xOriginalCategories = xAxis->getScaleData().Categories;
        }

        if( m_xOriginalCategories.is() )
        {
            Reference< chart2::XChartDocument > xChartDoc( xChartModel, uno::UNO_QUERY );
            if( xChartDoc.is() )
            {
                uno::Reference< data::XDataProvider > xDataProvider( xChartDoc->getDataProvider() );

                if( xDataProvider.is() )
                {
                    OUString aCatgoriesRange( DataSourceHelper::getRangeFromValues( m_xOriginalCategories ) );
                    const bool bFirstCellAsLabel = false;
                    const bool bHasCategories = false;
                    const uno::Sequence< sal_Int32 > aSequenceMapping;

                    uno::Reference< data::XDataSource > xColumnCategoriesSource( xDataProvider->createDataSource(
                         DataSourceHelper::createArguments( aCatgoriesRange, aSequenceMapping, true /*bUseColumns*/
                            , bFirstCellAsLabel, bHasCategories ) ) );

                    uno::Reference< data::XDataSource > xRowCategoriesSource( xDataProvider->createDataSource(
                         DataSourceHelper::createArguments( aCatgoriesRange, aSequenceMapping, false /*bUseColumns*/
                            , bFirstCellAsLabel, bHasCategories ) ) );

                    if( xColumnCategoriesSource.is() &&  xRowCategoriesSource.is() )
                    {
                        Sequence< Reference< data::XLabeledDataSequence> > aColumns = xColumnCategoriesSource->getDataSequences();
                        Sequence< Reference< data::XLabeledDataSequence> > aRows = xRowCategoriesSource->getDataSequences();

                        sal_Int32 nColumnCount = aColumns.getLength();
                        sal_Int32 nRowCount = aRows.getLength();
                        if( nColumnCount>1 && nRowCount>1 )
                        {
                            //we have complex categories
                            //->split them in the direction of the first series
                            //detect whether the first series is a row or a column
                            bool bSeriesUsesColumns = true;
                            ::std::vector< Reference< XDataSeries > > aSeries( ChartModelHelper::getDataSeries( xChartModel ) );
                            if( !aSeries.empty() )
                            {
                                uno::Reference< data::XDataSource > xSeriesSource( aSeries.front(), uno::UNO_QUERY );
                                ::rtl::OUString aStringDummy;
                                bool bDummy;
                                uno::Sequence< sal_Int32 > aSeqDummy;
                                DataSourceHelper::readArguments( xDataProvider->detectArguments( xSeriesSource),
                                               aStringDummy, aSeqDummy, bSeriesUsesColumns, bDummy, bDummy );
                            }
                            if( bSeriesUsesColumns )
                                m_aSplitCategoriesList=aColumns;
                            else
                                m_aSplitCategoriesList=aRows;
                        }
                    }
                }
            }
            if( !m_aSplitCategoriesList.getLength() )
            {
                m_aSplitCategoriesList.realloc(1);
                m_aSplitCategoriesList[0]=m_xOriginalCategories;
            }
        }
    }
    catch( const uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

ExplicitCategoriesProvider::~ExplicitCategoriesProvider()
{
}

const Sequence< Reference< data::XLabeledDataSequence> >& ExplicitCategoriesProvider::getSplitCategoriesList()
{
    return m_aSplitCategoriesList;
}

bool ExplicitCategoriesProvider::hasComplexCategories() const
{
    return m_aSplitCategoriesList.getLength() > 1;
}

sal_Int32 ExplicitCategoriesProvider::getCategoryLevelCount() const
{
    sal_Int32 nCount = m_aSplitCategoriesList.getLength();
    if(!nCount)
        nCount = 1;
    return nCount;
}

std::vector<sal_Int32> lcl_getLimitingBorders( const std::vector< ComplexCategory >& rComplexCategories )
{
    std::vector<sal_Int32> aLimitingBorders;
    std::vector< ComplexCategory >::const_iterator aIt( rComplexCategories.begin() );
    std::vector< ComplexCategory >::const_iterator aEnd( rComplexCategories.end() );
    sal_Int32 nBorderIndex = 0; /*border below the index*/
    for( ; aIt != aEnd; ++aIt )
    {
        ComplexCategory aComplexCategory(*aIt);
        nBorderIndex += aComplexCategory.Count;
        aLimitingBorders.push_back(nBorderIndex);
    }
    return aLimitingBorders;
}

uno::Sequence< rtl::OUString > lcl_DataToStringSequence( const uno::Reference< data::XDataSequence >& xDataSequence )
{
    uno::Sequence< rtl::OUString > aStrings;

    OSL_ASSERT( xDataSequence.is());
    if( !xDataSequence.is() )
        return aStrings;

    uno::Reference< data::XTextualDataSequence > xTextualDataSequence( xDataSequence, uno::UNO_QUERY );
    if( xTextualDataSequence.is() )
    {
        aStrings = xTextualDataSequence->getTextualData();
    }
    else
    {
        uno::Sequence< uno::Any > aValues = xDataSequence->getData();
        aStrings.realloc(aValues.getLength());

        for(sal_Int32 nN=aValues.getLength();nN--;)
            aValues[nN] >>= aStrings[nN];
    }

    return aStrings;
}

SplitCategoriesProvider::~SplitCategoriesProvider()
{
}

class SplitCategoriesProvider_ForLabeledDataSequences : public SplitCategoriesProvider
{
public:

    explicit SplitCategoriesProvider_ForLabeledDataSequences( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XLabeledDataSequence> >& rSplitCategoriesList )
        : m_rSplitCategoriesList( rSplitCategoriesList )
    {}
    virtual ~SplitCategoriesProvider_ForLabeledDataSequences()
    {}

    virtual sal_Int32 getLevelCount() const;
    virtual uno::Sequence< rtl::OUString > getStringsForLevel( sal_Int32 nIndex ) const;

private:
    const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::data::XLabeledDataSequence> >& m_rSplitCategoriesList;
};

sal_Int32 SplitCategoriesProvider_ForLabeledDataSequences::getLevelCount() const
{
    return m_rSplitCategoriesList.getLength();
}
uno::Sequence< rtl::OUString > SplitCategoriesProvider_ForLabeledDataSequences::getStringsForLevel( sal_Int32 nLevel ) const
{
    uno::Sequence< rtl::OUString > aRet;
    Reference< data::XLabeledDataSequence > xLabeledDataSequence( m_rSplitCategoriesList[nLevel] );
    if( xLabeledDataSequence.is() )
        aRet = lcl_DataToStringSequence( xLabeledDataSequence->getValues() );
    return aRet;
}

std::vector< ComplexCategory > lcl_DataSequenceToComplexCategoryVector(
    const uno::Sequence< rtl::OUString >& rStrings
    , const std::vector<sal_Int32>& rLimitingBorders, bool bCreateSingleCategories )
{
    std::vector< ComplexCategory > aResult;

    sal_Int32 nMaxCount = rStrings.getLength();
    OUString aPrevious;
    sal_Int32 nCurrentCount=0;
    for( sal_Int32 nN=0; nN<nMaxCount; nN++ )
    {
        OUString aCurrent = rStrings[nN];
        if( bCreateSingleCategories || ::std::find( rLimitingBorders.begin(), rLimitingBorders.end(), nN ) != rLimitingBorders.end() )
        {
            aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
            nCurrentCount=1;
            aPrevious = aCurrent;
        }
        else
        {
            if( aCurrent.getLength() && aPrevious != aCurrent )
            {
                aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );
                nCurrentCount=1;
                aPrevious = aCurrent;
            }
            else
                nCurrentCount++;
        }
    }
    if( nCurrentCount )
        aResult.push_back( ComplexCategory(aPrevious,nCurrentCount) );

    return aResult;
}

sal_Int32 lcl_getCategoryCount( std::vector< ComplexCategory >& rComplexCategories )
{
    sal_Int32 nCount = 0;
    std::vector< ComplexCategory >::iterator aIt( rComplexCategories.begin() );
    std::vector< ComplexCategory >::const_iterator aEnd( rComplexCategories.end() );
    for( ; aIt != aEnd; ++aIt )
        nCount+=aIt->Count;
    return nCount;
}

Sequence< OUString > lcl_getExplicitSimpleCategories(
    const SplitCategoriesProvider& rSplitCategoriesProvider,
    ::std::vector< ::std::vector< ComplexCategory > >& rComplexCats )
{
    Sequence< OUString > aRet;

    rComplexCats.clear();
    sal_Int32 nLCount = rSplitCategoriesProvider.getLevelCount();
    for( sal_Int32 nL = 0; nL < nLCount; nL++ )
    {
        std::vector<sal_Int32> aLimitingBorders;
        if(nL>0)
            aLimitingBorders = lcl_getLimitingBorders( rComplexCats.back() );
        rComplexCats.push_back( lcl_DataSequenceToComplexCategoryVector(
            rSplitCategoriesProvider.getStringsForLevel(nL), aLimitingBorders, nL==(nLCount-1) ) );
    }

    std::vector< std::vector< ComplexCategory > >::iterator aOuterIt( rComplexCats.begin() );
    std::vector< std::vector< ComplexCategory > >::const_iterator aOuterEnd( rComplexCats.end() );

    //ensure that the category count is the same on each level
    sal_Int32 nMaxCategoryCount = 0;
    {
        for( aOuterIt=rComplexCats.begin(); aOuterIt != aOuterEnd; ++aOuterIt )
        {
            sal_Int32 nCurrentCount = lcl_getCategoryCount( *aOuterIt );
            nMaxCategoryCount = std::max( nCurrentCount, nMaxCategoryCount );
        }
        for( aOuterIt=rComplexCats.begin(); aOuterIt != aOuterEnd; ++aOuterIt )
        {
            sal_Int32 nCurrentCount = lcl_getCategoryCount( *aOuterIt );
            if( nCurrentCount< nMaxCategoryCount )
            {
                ComplexCategory& rComplexCategory = aOuterIt->back();
                rComplexCategory.Count += (nMaxCategoryCount-nCurrentCount);
            }
        }
    }

    //create a list with an element for every index
    std::vector< std::vector< ComplexCategory > > aComplexCatsPerIndex;
    for( aOuterIt=rComplexCats.begin() ; aOuterIt != aOuterEnd; ++aOuterIt )
    {
        std::vector< ComplexCategory > aSingleLevel;
        std::vector< ComplexCategory >::iterator aIt( aOuterIt->begin() );
        std::vector< ComplexCategory >::const_iterator aEnd( aOuterIt->end() );
        for( ; aIt != aEnd; ++aIt )
        {
            ComplexCategory aComplexCategory( *aIt );
            sal_Int32 nCount = aComplexCategory.Count;
            while( nCount-- )
                aSingleLevel.push_back(aComplexCategory);
        }
        aComplexCatsPerIndex.push_back( aSingleLevel );
    }

    if(nMaxCategoryCount)
    {
        aRet.realloc(nMaxCategoryCount);
        aOuterEnd = aComplexCatsPerIndex.end();
        OUString aSpace(C2U(" "));
        for(sal_Int32 nN=0; nN<nMaxCategoryCount; nN++)
        {
            OUString aText;
            for( aOuterIt=aComplexCatsPerIndex.begin() ; aOuterIt != aOuterEnd; ++aOuterIt )
            {
                OUString aAddText = (*aOuterIt)[nN].Text;
                if( aAddText.getLength() )
                {
                    if(aText.getLength())
                        aText += aSpace;
                    aText += aAddText;
                }
            }
            aRet[nN]=aText;
        }
    }
    return aRet;
}

//static
Sequence< OUString > ExplicitCategoriesProvider::getExplicitSimpleCategories(
    const SplitCategoriesProvider& rSplitCategoriesProvider )
{
    vector< vector< ComplexCategory > > aComplexCats;
    return lcl_getExplicitSimpleCategories( rSplitCategoriesProvider, aComplexCats );
}

void ExplicitCategoriesProvider::init()
{
    if( m_bDirty )
    {
        m_aExplicitCategories.realloc(0);
        m_aComplexCats.clear();//not one per index

        if( m_xOriginalCategories.is() )
        {
            if( !hasComplexCategories() )
                m_aExplicitCategories = DataSequenceToStringSequence(m_xOriginalCategories->getValues());
            else
                m_aExplicitCategories = lcl_getExplicitSimpleCategories(
                    SplitCategoriesProvider_ForLabeledDataSequences( m_aSplitCategoriesList ), m_aComplexCats );
        }
        if(!m_aExplicitCategories.getLength())
            m_aExplicitCategories = DiagramHelper::generateAutomaticCategoriesFromCooSys( m_xCooSysModel );
        m_bDirty = false;
    }
}

Sequence< ::rtl::OUString > ExplicitCategoriesProvider::getSimpleCategories()
{
    init();
    return m_aExplicitCategories;
}

std::vector< ComplexCategory >  ExplicitCategoriesProvider::getCategoriesByLevel( sal_Int32 nLevel )
{
    std::vector< ComplexCategory > aRet;
    init();
    sal_Int32 nMaxIndex = m_aComplexCats.size()-1;
    if( nLevel >= 0 && nLevel <= nMaxIndex  )
        aRet = m_aComplexCats[nMaxIndex-nLevel];
    return aRet;
}

// static
OUString ExplicitCategoriesProvider::getCategoryByIndex(
          const Reference< XCoordinateSystem >& xCooSysModel
        , const uno::Reference< frame::XModel >& xChartModel
        , sal_Int32 nIndex )
{
    if( xCooSysModel.is())
    {
        ExplicitCategoriesProvider aExplicitCategoriesProvider( xCooSysModel, xChartModel );
        Sequence< OUString > aCategories( aExplicitCategoriesProvider.getSimpleCategories());
        if( nIndex < aCategories.getLength())
            return aCategories[ nIndex ];
    }
    return OUString();
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>#include "PCollide.hpp"

namespace Core
{
	bool CollideObjects(const PObject& obj1, const PObject& obj2)
	{
		if(!obj1.GetAABB().Intersect(obj2.GetAABB()))
		{
			return false;
		}

		return true;

		if(obj1.GetShape()->GetType() == PShape::e_poly && obj2.GetShape()->GetType() == PShape::e_poly)
		{
			PPoly &s1 = *((PPoly*)obj1.GetShape()),
				  &s2 = *((PPoly*)obj2.GetShape());

		}

	}
}
<commit_msg>Refined collision detection for PPolys with SAT<commit_after>#include "PCollide.hpp"

namespace Core
{
	bool CollideObjects(const PObject& obj1, const PObject& obj2)
	{
		if(!obj1.GetAABB().Intersect(obj2.GetAABB()))
		{
			return false;
		}

		//return true;

		if(obj1.GetShape()->GetType() == PShape::e_poly && obj2.GetShape()->GetType() == PShape::e_poly)
		{
			PPoly s1(*(PPoly*)obj1.GetShape()),
				  s2(*(PPoly*)obj2.GetShape());

			for(int i = 0; i < s1.GetVertexCount(); i++)
			{
				const_cast<PVec2&>(s2.GetVertex(i)).Rotate(obj1.GetAngle());
				const_cast<PVec2&>(s2.GetVertex(i)) += obj1.GetPosition();
			}

			for(int i = 0; i < s2.GetVertexCount(); i++)
			{
				const_cast<PVec2&>(s2.GetVertex(i)).Rotate(obj2.GetAngle());
				const_cast<PVec2&>(s2.GetVertex(i)) += obj2.GetPosition();
			}

			PVec2 p1, p2;
			PSegm o1, o2;

			p1 = s1.GetVertex(s1.GetVertexCount() - 1);

			for(int i = 0; i < s1.GetVertexCount(); i++)
			{
				p2 = s1.GetVertex(i);
				PVec2 edge = p1 - p2;
				edge.Normalize();

				o1.Clear();
				o2.Clear();

				for(int j = 0; j < s1.GetVertexCount(); j++)
				{
					o1.AddPoint(s1.GetVertex(j).Dot(edge));
				}

				for(int j = 0; j < s2.GetVertexCount(); j++)
				{
					o2.AddPoint(s2.GetVertex(j).Dot(edge));
				}

				if(!o1.Intersect(o2))
				{
					return false;
				}

				p1 = p2;
			}

			p1 = s2.GetVertex(s2.GetVertexCount() - 1);

			for(int i = 0; i < s2.GetVertexCount(); i++)
			{
				p2 = s2.GetVertex(i);
				PVec2 edge = p1 - p2;
				edge.Normalize();

				o1.Clear();
				o2.Clear();

				for(int j = 0; j < s1.GetVertexCount(); j++)
				{
					o1.AddPoint(s1.GetVertex(j).Dot(edge));
				}

				for(int j = 0; j < s2.GetVertexCount(); j++)
				{
					o2.AddPoint(s2.GetVertex(j).Dot(edge));
				}

				if(!o1.Intersect(o2))
				{
					return false;
				}

				p1 = p2;
			}

		}

		return true;
	}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: _serviceregistration_tools.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 19:07: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
 *
 ************************************************************************/

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

#ifndef _CPPUHELPER_IMPLEMENATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif
#include "LabeledDataSequence.hxx"
#include "DataSource.hxx"
#include "ConfigColorScheme.hxx"
#include "Scaling.hxx"
#include "ErrorBar.hxx"
#include "RegressionCurveModel.hxx"

static struct ::cppu::ImplementationEntry g_entries_chart2_tools[] =
{
    {
          ::chart::LabeledDataSequence::create
        , ::chart::LabeledDataSequence::getImplementationName_Static
        , ::chart::LabeledDataSequence::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::DataSource::create
        , ::chart::DataSource::getImplementationName_Static
        , ::chart::DataSource::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::ConfigColorScheme::create
        , ::chart::ConfigColorScheme::getImplementationName_Static
        , ::chart::ConfigColorScheme::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }

    ,{
          ::chart::LogarithmicScaling::create
        , ::chart::LogarithmicScaling::getImplementationName_Static
        , ::chart::LogarithmicScaling::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::ExponentialScaling::create
        , ::chart::ExponentialScaling::getImplementationName_Static
        , ::chart::ExponentialScaling::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::LinearScaling::create
        , ::chart::LinearScaling::getImplementationName_Static
        , ::chart::LinearScaling::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::PowerScaling::create
        , ::chart::PowerScaling::getImplementationName_Static
        , ::chart::PowerScaling::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::ErrorBar::create
        , ::chart::ErrorBar::getImplementationName_Static
        , ::chart::ErrorBar::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::MeanValueRegressionCurve::create
        , ::chart::MeanValueRegressionCurve::getImplementationName_Static
        , ::chart::MeanValueRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::LinearRegressionCurve::create
        , ::chart::LinearRegressionCurve::getImplementationName_Static
        , ::chart::LinearRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::LogarithmicRegressionCurve::create
        , ::chart::LogarithmicRegressionCurve::getImplementationName_Static
        , ::chart::LogarithmicRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::ExponentialRegressionCurve::create
        , ::chart::ExponentialRegressionCurve::getImplementationName_Static
        , ::chart::ExponentialRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::PotentialRegressionCurve::create
        , ::chart::PotentialRegressionCurve::getImplementationName_Static
        , ::chart::PotentialRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{ 0, 0, 0, 0, 0, 0 }
};

// component exports
extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    return ::cppu::component_writeInfoHelper(
                pServiceManager, pRegistryKey, g_entries_chart2_tools );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    return ::cppu::component_getFactoryHelper(
        pImplName, pServiceManager, pRegistryKey , g_entries_chart2_tools );
}
}
//=========================================================================
<commit_msg>INTEGRATION: CWS chart07 (1.2.12); FILE MERGED 2007/07/04 16:48:58 bm 1.2.12.1: warnings removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: _serviceregistration_tools.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-25 09:02:37 $
 *
 *  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
 *
 ************************************************************************/

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

#ifndef _CPPUHELPER_IMPLEMENATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif
#include "LabeledDataSequence.hxx"
#include "DataSource.hxx"
#include "ConfigColorScheme.hxx"
#include "Scaling.hxx"
#include "ErrorBar.hxx"
#include "RegressionCurveModel.hxx"

static struct ::cppu::ImplementationEntry g_entries_chart2_tools[] =
{
    {
          ::chart::LabeledDataSequence::create
        , ::chart::LabeledDataSequence::getImplementationName_Static
        , ::chart::LabeledDataSequence::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::DataSource::create
        , ::chart::DataSource::getImplementationName_Static
        , ::chart::DataSource::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::ConfigColorScheme::create
        , ::chart::ConfigColorScheme::getImplementationName_Static
        , ::chart::ConfigColorScheme::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }

    ,{
          ::chart::LogarithmicScaling::create
        , ::chart::LogarithmicScaling::getImplementationName_Static
        , ::chart::LogarithmicScaling::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::ExponentialScaling::create
        , ::chart::ExponentialScaling::getImplementationName_Static
        , ::chart::ExponentialScaling::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::LinearScaling::create
        , ::chart::LinearScaling::getImplementationName_Static
        , ::chart::LinearScaling::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::PowerScaling::create
        , ::chart::PowerScaling::getImplementationName_Static
        , ::chart::PowerScaling::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::ErrorBar::create
        , ::chart::ErrorBar::getImplementationName_Static
        , ::chart::ErrorBar::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::MeanValueRegressionCurve::create
        , ::chart::MeanValueRegressionCurve::getImplementationName_Static
        , ::chart::MeanValueRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::LinearRegressionCurve::create
        , ::chart::LinearRegressionCurve::getImplementationName_Static
        , ::chart::LinearRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::LogarithmicRegressionCurve::create
        , ::chart::LogarithmicRegressionCurve::getImplementationName_Static
        , ::chart::LogarithmicRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::ExponentialRegressionCurve::create
        , ::chart::ExponentialRegressionCurve::getImplementationName_Static
        , ::chart::ExponentialRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{
          ::chart::PotentialRegressionCurve::create
        , ::chart::PotentialRegressionCurve::getImplementationName_Static
        , ::chart::PotentialRegressionCurve::getSupportedServiceNames_Static
        , ::cppu::createSingleComponentFactory
        , 0
        , 0
    }
   ,{ 0, 0, 0, 0, 0, 0 }
};

// component exports
extern "C"
{
//==================================================================================================
void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** /* ppEnv */ )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//==================================================================================================
sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    return ::cppu::component_writeInfoHelper(
                pServiceManager, pRegistryKey, g_entries_chart2_tools );
}
//==================================================================================================
void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    return ::cppu::component_getFactoryHelper(
        pImplName, pServiceManager, pRegistryKey , g_entries_chart2_tools );
}
}
//=========================================================================
<|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/MIRIAMUI/Attic/CBiologicalDescriptionsWidget.cpp,v $
//   $Revision: 1.6 $
//   $Name:  $
//   $Author: gauges $
//   $Date: 2008/06/04 14:08:36 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

#include <qlayout.h>
#include <qpushbutton.h>
#include <sstream>

#include "copasi.h"

#include "CQMiriamWidget.h"
#include "CBiologicalDescriptionsWidget.h"

#include "MIRIAM/CModelMIRIAMInfo.h"

#include "utilities/CCopasiVector.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiObject.h"
#include "report/CKeyFactory.h"
#include "UI/qtUtilities.h"
#include "UI/CQMessageBox.h"

#define COL_MARK               0
#define COL_DUMMY              1
#define COL_RELATIONSHIP       2
#define COL_RESOURCE           3
#define COL_ID                 4

/*
 *  Constructs a CBiologicalDescriptionsWidget as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 */
CBiologicalDescriptionsWidget::CBiologicalDescriptionsWidget(QWidget* parent, const char* name, WFlags f)
    : CopasiTableWidget(parent, false, name, f, false)
{
  if (!name)
    CopasiTableWidget::setName("BiologicalDescriptionsWidget");
  init();
}

/*
 *  Destroys the object and frees any allocated resources
 */
CBiologicalDescriptionsWidget::~CBiologicalDescriptionsWidget()
{
  // no need to delete child widgets, Qt does it all for us
}

std::vector<const CCopasiObject*> CBiologicalDescriptionsWidget::getObjects() const
  {
    std::vector<const CCopasiObject*> ret;

    if (dynamic_cast <CQMiriamWidget*> (parentWidget()))
      {
        const CCopasiVector<CBiologicalDescription>& tmp = dynamic_cast <CQMiriamWidget*> (parentWidget())->getMIRIAMInfo().getBiologicalDescriptions();

        C_INT32 i, imax = tmp.size();
        for (i = 0; i < imax; ++i)
          ret.push_back(tmp[i]);
      }

    return ret;
  }

void CBiologicalDescriptionsWidget::init()
{
  //flagtoAdjust = false;
  mShowNewObjectWarning = false;
  numCols = 5;
  table->setNumCols(numCols);

  //Setting table headers
  QHeader *tableHeader = table->horizontalHeader();
  tableHeader->setLabel(COL_MARK, "Status");
  tableHeader->setLabel(COL_DUMMY, "Dummy");
  tableHeader->setLabel(COL_RELATIONSHIP, "Relationship");
  tableHeader->setLabel(COL_RESOURCE, "Resource");
  tableHeader->setLabel(COL_ID, "ID");
  table->hideColumn(COL_DUMMY);

  //table->setColumnWidth(COL_ID, 200);
  // Build the list of supported predicates
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_encodes).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_hasPart).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_hasVersion).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_is).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_isEncodedBy).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_isHomologTo).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_isPartOf).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_isVersionOf).c_str()));

  // Build the list of known resources
  const CMIRIAMResource::sResource * pResource = CMIRIAMResource::getResourceList();
  for (; pResource->MiriamId != ""; ++pResource)
    mResources.push_back(FROM_UTF8(pResource->DisplayName));
}

void CBiologicalDescriptionsWidget::tableLineFromObject(const CCopasiObject* obj, unsigned C_INT32 row)
{
  if (!obj) return;
  const CBiologicalDescription *pBiologicalDescription = (const CBiologicalDescription*)obj;

  table->setText(row, COL_DUMMY, QString::number(row));

  QComboTableItem * pComboBox = NULL;
  if (dynamic_cast<QComboTableItem *>(table->item(row, COL_RELATIONSHIP)))
    {
      pComboBox = static_cast<QComboTableItem *>(table->item(row, COL_RELATIONSHIP));
      pComboBox->setCurrentItem(FROM_UTF8(pBiologicalDescription->getPredicate()));
    }
  else
    {
      pComboBox = new QComboTableItem(table, mPredicates);
      pComboBox->setCurrentItem(FROM_UTF8(pBiologicalDescription->getPredicate()));
      table->setItem(row, COL_RELATIONSHIP, pComboBox);
    }

  if (dynamic_cast<QComboTableItem *>(table->item(row, COL_RESOURCE)))
    {
      pComboBox = static_cast<QComboTableItem *>(table->item(row, COL_RESOURCE));
      pComboBox->setCurrentItem(FROM_UTF8(pBiologicalDescription->getResource()));
    }
  else
    {
      pComboBox = new QComboTableItem(table, mResources);
      pComboBox->setCurrentItem(FROM_UTF8(pBiologicalDescription->getResource()));
      table->setItem(row, COL_RESOURCE, pComboBox);
    }

  table->setText(row, COL_ID, FROM_UTF8(pBiologicalDescription->getId()));
}

void CBiologicalDescriptionsWidget::tableLineToObject(unsigned C_INT32 row, CCopasiObject* obj)
{
  if (!obj) return;
  CBiologicalDescription * pBiologicalDescription = static_cast< CBiologicalDescription * >(obj);

  if (dynamic_cast<QComboTableItem *>(table->item(row, COL_RELATIONSHIP)))
    {
      const std::string relationship = (const char *) static_cast<QComboTableItem *>(table->item(row, COL_RELATIONSHIP))->currentText().utf8();
      //Don't handle this and return if relationship is changed.
      if (pBiologicalDescription->getPredicate() != relationship)
        return;
    }

  if (dynamic_cast<QComboTableItem *>(table->item(row, COL_RESOURCE)))
    {
      QString resource = static_cast<QComboTableItem *>(table->item(row, COL_RESOURCE))->currentText();
      pBiologicalDescription->setResource((const char *) resource.utf8());
    }

  QString ID = table->text(row, COL_ID);
  pBiologicalDescription->setId((const char *) ID.utf8());
}

void CBiologicalDescriptionsWidget::defaultTableLineContent(unsigned C_INT32 row, unsigned C_INT32 exc)
{
  if (exc != COL_RELATIONSHIP)
    {
      QComboTableItem * pComboBox = new QComboTableItem(table, mPredicates);
      pComboBox->setCurrentItem(0);
      table->setItem(row, COL_RELATIONSHIP, pComboBox);
    }

  if (exc != COL_RESOURCE)
    {
      QComboTableItem * pComboBox = new QComboTableItem(table, mResources);
      pComboBox->setCurrentItem(0);
      table->setItem(row, COL_RESOURCE, pComboBox);
    }

  if (exc != COL_ID)
    table->clearCell(row, COL_ID);
}

QString CBiologicalDescriptionsWidget::defaultObjectName() const
{return "";}

CCopasiObject* CBiologicalDescriptionsWidget::createNewObject(const std::string & /* name */)
{
  if (!dynamic_cast <CQMiriamWidget*> (parentWidget()))
    return NULL;

  CBiologicalDescription* pBiologicalDescription = NULL;
  pBiologicalDescription = dynamic_cast <CQMiriamWidget*> (parentWidget())->getMIRIAMInfo().createBiologicalDescription();

  return pBiologicalDescription;
}

void CBiologicalDescriptionsWidget::deleteObjects(const std::vector<std::string> & keys)
{
  if (!dynamic_cast <CQMiriamWidget*> (parentWidget()))
    return;

  QString BiologicalDescriptionList = "Are you sure you want to delete listed BIOLOGICAL DESCRIPTION(S) ?\n";
  unsigned C_INT32 i, imax = keys.size();
  for (i = 0; i < imax; i++) //all compartments
    {
      CBiologicalDescription * pBiologicalDescription =
        dynamic_cast< CBiologicalDescription *>(GlobalKeys.get(keys[i]));

      BiologicalDescriptionList.append(FROM_UTF8(pBiologicalDescription->getObjectName()));
      BiologicalDescriptionList.append(", ");
    }

  BiologicalDescriptionList.remove(BiologicalDescriptionList.length() - 2, 2);

  QString msg = BiologicalDescriptionList;

  C_INT32 choice = 0;
  choice = CQMessageBox::question(this,
                                  "CONFIRM DELETE",
                                  msg,
                                  "Continue", "Cancel", 0, 1, 1);

  switch (choice)
    {
    case 0:                                           // Yes or Enter
      {
        for (i = 0; i < imax; i++)
          {
            dynamic_cast <CQMiriamWidget*> (parentWidget())->getMIRIAMInfo().removeBiologicalDescription(keys[i]);
          }

        for (i = 0; i < imax; i++)
          protectedNotify(mOT, ListViews::DELETE, keys[i]);

        mChanged = true;
        break;
      }
    default:                                           // No or Escape
      break;
    }
}

void CBiologicalDescriptionsWidget::slotDoubleClicked(int C_UNUSED(row), int C_UNUSED(col),
    int C_UNUSED(m), const QPoint & C_UNUSED(n))
{}

void CBiologicalDescriptionsWidget::slotValueChanged(int row, int col)
{
  if (col == COL_RELATIONSHIP || col == COL_RESOURCE)
    {
      int selectedItem = -1;
      if (row == table->numRows() - 1) //new Object
        {
          if (dynamic_cast<QComboTableItem *>(table->item(row, col)))
            {
              selectedItem = static_cast<QComboTableItem *>(table->item(row, col))->currentItem();
            }
        }
      CopasiTableWidget::slotValueChanged(row, col);
      if (selectedItem > -1)
      {static_cast<QComboTableItem *>(table->item(row, col))->setCurrentItem(selectedItem);}
    }
  else
  {CopasiTableWidget::slotValueChanged(row, col);}
}
<commit_msg>Implemented handling predicate changes.<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/MIRIAMUI/Attic/CBiologicalDescriptionsWidget.cpp,v $
//   $Revision: 1.7 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2008/06/11 13:56:03 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

#include <qlayout.h>
#include <qpushbutton.h>
#include <sstream>

#include "copasi.h"

#include "CQMiriamWidget.h"
#include "CBiologicalDescriptionsWidget.h"

#include "MIRIAM/CModelMIRIAMInfo.h"

#include "utilities/CCopasiVector.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiObject.h"
#include "report/CKeyFactory.h"
#include "UI/qtUtilities.h"
#include "UI/CQMessageBox.h"

#define COL_MARK               0
#define COL_DUMMY              1
#define COL_RELATIONSHIP       2
#define COL_RESOURCE           3
#define COL_ID                 4

/*
 *  Constructs a CBiologicalDescriptionsWidget as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 */
CBiologicalDescriptionsWidget::CBiologicalDescriptionsWidget(QWidget* parent, const char* name, WFlags f)
    : CopasiTableWidget(parent, false, name, f, false)
{
  if (!name)
    CopasiTableWidget::setName("BiologicalDescriptionsWidget");
  init();
}

/*
 *  Destroys the object and frees any allocated resources
 */
CBiologicalDescriptionsWidget::~CBiologicalDescriptionsWidget()
{
  // no need to delete child widgets, Qt does it all for us
}

std::vector<const CCopasiObject*> CBiologicalDescriptionsWidget::getObjects() const
  {
    std::vector<const CCopasiObject*> ret;

    if (dynamic_cast <CQMiriamWidget*> (parentWidget()))
      {
        const CCopasiVector<CBiologicalDescription>& tmp = dynamic_cast <CQMiriamWidget*> (parentWidget())->getMIRIAMInfo().getBiologicalDescriptions();

        C_INT32 i, imax = tmp.size();
        for (i = 0; i < imax; ++i)
          ret.push_back(tmp[i]);
      }

    return ret;
  }

void CBiologicalDescriptionsWidget::init()
{
  //flagtoAdjust = false;
  mShowNewObjectWarning = false;
  numCols = 5;
  table->setNumCols(numCols);

  //Setting table headers
  QHeader *tableHeader = table->horizontalHeader();
  tableHeader->setLabel(COL_MARK, "Status");
  tableHeader->setLabel(COL_DUMMY, "Dummy");
  tableHeader->setLabel(COL_RELATIONSHIP, "Relationship");
  tableHeader->setLabel(COL_RESOURCE, "Resource");
  tableHeader->setLabel(COL_ID, "ID");
  table->hideColumn(COL_DUMMY);

  //table->setColumnWidth(COL_ID, 200);
  // Build the list of supported predicates
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_encodes).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_hasPart).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_hasVersion).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_is).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_isEncodedBy).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_isHomologTo).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_isPartOf).c_str()));
  mPredicates.push_back(QString(CRDFPredicate::getDisplayName(CRDFPredicate::bqbiol_isVersionOf).c_str()));

  // Build the list of known resources
  const CMIRIAMResource::sResource * pResource = CMIRIAMResource::getResourceList();
  for (; pResource->MiriamId != ""; ++pResource)
    mResources.push_back(FROM_UTF8(pResource->DisplayName));
}

void CBiologicalDescriptionsWidget::tableLineFromObject(const CCopasiObject* obj, unsigned C_INT32 row)
{
  if (!obj) return;
  const CBiologicalDescription *pBiologicalDescription = (const CBiologicalDescription*)obj;

  table->setText(row, COL_DUMMY, QString::number(row));

  QComboTableItem * pComboBox = NULL;
  if (dynamic_cast<QComboTableItem *>(table->item(row, COL_RELATIONSHIP)))
    {
      pComboBox = static_cast<QComboTableItem *>(table->item(row, COL_RELATIONSHIP));
      pComboBox->setCurrentItem(FROM_UTF8(pBiologicalDescription->getPredicate()));
    }
  else
    {
      pComboBox = new QComboTableItem(table, mPredicates);
      pComboBox->setCurrentItem(FROM_UTF8(pBiologicalDescription->getPredicate()));
      table->setItem(row, COL_RELATIONSHIP, pComboBox);
    }

  if (dynamic_cast<QComboTableItem *>(table->item(row, COL_RESOURCE)))
    {
      pComboBox = static_cast<QComboTableItem *>(table->item(row, COL_RESOURCE));
      pComboBox->setCurrentItem(FROM_UTF8(pBiologicalDescription->getResource()));
    }
  else
    {
      pComboBox = new QComboTableItem(table, mResources);
      pComboBox->setCurrentItem(FROM_UTF8(pBiologicalDescription->getResource()));
      table->setItem(row, COL_RESOURCE, pComboBox);
    }

  table->setText(row, COL_ID, FROM_UTF8(pBiologicalDescription->getId()));
}

void CBiologicalDescriptionsWidget::tableLineToObject(unsigned C_INT32 row, CCopasiObject* obj)
{
  if (!obj) return;
  CBiologicalDescription * pBiologicalDescription = static_cast< CBiologicalDescription * >(obj);

  if (dynamic_cast<QComboTableItem *>(table->item(row, COL_RELATIONSHIP)))
    {
      const std::string relationship = (const char *) static_cast<QComboTableItem *>(table->item(row, COL_RELATIONSHIP))->currentText().utf8();
      pBiologicalDescription->setPredicate(relationship);
    }

  if (dynamic_cast<QComboTableItem *>(table->item(row, COL_RESOURCE)))
    {
      QString resource = static_cast<QComboTableItem *>(table->item(row, COL_RESOURCE))->currentText();
      pBiologicalDescription->setResource((const char *) resource.utf8());
    }

  QString ID = table->text(row, COL_ID);
  pBiologicalDescription->setId((const char *) ID.utf8());
}

void CBiologicalDescriptionsWidget::defaultTableLineContent(unsigned C_INT32 row, unsigned C_INT32 exc)
{
  if (exc != COL_RELATIONSHIP)
    {
      QComboTableItem * pComboBox = new QComboTableItem(table, mPredicates);
      pComboBox->setCurrentItem(0);
      table->setItem(row, COL_RELATIONSHIP, pComboBox);
    }

  if (exc != COL_RESOURCE)
    {
      QComboTableItem * pComboBox = new QComboTableItem(table, mResources);
      pComboBox->setCurrentItem(0);
      table->setItem(row, COL_RESOURCE, pComboBox);
    }

  if (exc != COL_ID)
    table->clearCell(row, COL_ID);
}

QString CBiologicalDescriptionsWidget::defaultObjectName() const
{return "";}

CCopasiObject* CBiologicalDescriptionsWidget::createNewObject(const std::string & /* name */)
{
  if (!dynamic_cast <CQMiriamWidget*> (parentWidget()))
    return NULL;

  CBiologicalDescription* pBiologicalDescription = NULL;
  pBiologicalDescription = dynamic_cast <CQMiriamWidget*> (parentWidget())->getMIRIAMInfo().createBiologicalDescription();

  return pBiologicalDescription;
}

void CBiologicalDescriptionsWidget::deleteObjects(const std::vector<std::string> & keys)
{
  if (!dynamic_cast <CQMiriamWidget*> (parentWidget()))
    return;

  QString BiologicalDescriptionList = "Are you sure you want to delete listed BIOLOGICAL DESCRIPTION(S) ?\n";
  unsigned C_INT32 i, imax = keys.size();
  for (i = 0; i < imax; i++) //all compartments
    {
      CBiologicalDescription * pBiologicalDescription =
        dynamic_cast< CBiologicalDescription *>(GlobalKeys.get(keys[i]));

      BiologicalDescriptionList.append(FROM_UTF8(pBiologicalDescription->getObjectName()));
      BiologicalDescriptionList.append(", ");
    }

  BiologicalDescriptionList.remove(BiologicalDescriptionList.length() - 2, 2);

  QString msg = BiologicalDescriptionList;

  C_INT32 choice = 0;
  choice = CQMessageBox::question(this,
                                  "CONFIRM DELETE",
                                  msg,
                                  "Continue", "Cancel", 0, 1, 1);

  switch (choice)
    {
    case 0:                                           // Yes or Enter
      {
        for (i = 0; i < imax; i++)
          {
            dynamic_cast <CQMiriamWidget*> (parentWidget())->getMIRIAMInfo().removeBiologicalDescription(keys[i]);
          }

        for (i = 0; i < imax; i++)
          protectedNotify(mOT, ListViews::DELETE, keys[i]);

        mChanged = true;
        break;
      }
    default:                                           // No or Escape
      break;
    }
}

void CBiologicalDescriptionsWidget::slotDoubleClicked(int C_UNUSED(row), int C_UNUSED(col),
    int C_UNUSED(m), const QPoint & C_UNUSED(n))
{}

void CBiologicalDescriptionsWidget::slotValueChanged(int row, int col)
{
  if (col == COL_RELATIONSHIP || col == COL_RESOURCE)
    {
      int selectedItem = -1;
      if (row == table->numRows() - 1) //new Object
        {
          if (dynamic_cast<QComboTableItem *>(table->item(row, col)))
            {
              selectedItem = static_cast<QComboTableItem *>(table->item(row, col))->currentItem();
            }
        }
      CopasiTableWidget::slotValueChanged(row, col);
      if (selectedItem > -1)
      {static_cast<QComboTableItem *>(table->item(row, col))->setCurrentItem(selectedItem);}
    }
  else
  {CopasiTableWidget::slotValueChanged(row, col);}
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "blocksizecalculator.h"

using namespace BlockSizeCalculator;
using namespace std;

static std::vector<unsigned int> blocksizes;
static bool sorted = false;

unsigned int BlockSizeCalculator::ComputeBlockSize(CBlockIndex *pblockindex, unsigned int pastblocks) {

	unsigned int proposedMaxBlockSize = 0;
	unsigned int result = OLD_MAX_BLOCK_SIZE;

	LOCK(cs_main);

	proposedMaxBlockSize = ::GetMedianBlockSize(pblockindex, pastblocks);

	if (proposedMaxBlockSize > 0) {
		//Absolute max block size will be 2^32-1 bytes due to the fact that unsigned int's are 4 bytes
		result = proposedMaxBlockSize * MAX_BLOCK_SIZE_INCREASE_MULTIPLE;
		result = result < proposedMaxBlockSize ?
				std::numeric_limits<unsigned int>::max() :
				result;
		if (result < OLD_MAX_BLOCK_SIZE) {
			result = OLD_MAX_BLOCK_SIZE;
		}
	}

	return result;

}

inline unsigned int BlockSizeCalculator::GetMedianBlockSize(
		CBlockIndex *pblockindex, unsigned int pastblocks) {

	blocksizes = ::GetBlockSizes(pblockindex, pastblocks);

	if(!sorted) {
		std::sort(blocksizes.begin(), blocksizes.end());
		sorted = true;
	}

	unsigned int vsize = blocksizes.size();
	if (vsize == pastblocks) {
		double median = 0;
		if ((vsize % 2) == 0) {
			median = (blocksizes[vsize / 2] + blocksizes[(vsize / 2) - 1]) / 2.0;
		} else {
			median = blocksizes[vsize / 2];
		}
		return static_cast<unsigned int>(floor(median));
	} else {
		return 0;
	}

}

inline std::vector<unsigned int> BlockSizeCalculator::GetBlockSizes(
		CBlockIndex *pblockindex, unsigned int pastblocks) {

	if (pblockindex->nHeight < (int)pastblocks) {
		return blocksizes;
	}

	int firstBlock = pblockindex->nHeight - pastblocks;

	if (blocksizes.size() > 0) {

		int latestBlockSize = ::GetBlockSize(pblockindex);

		if (latestBlockSize != -1) {

			CBlockIndex *firstBlockIndex = FindBlockByHeight(firstBlock);
			int oldestBlockSize = ::GetBlockSize(firstBlockIndex);
			if (oldestBlockSize != -1) {
				std::vector<unsigned int>::iterator it;
				it = std::find(blocksizes.begin(), blocksizes.end(),
						oldestBlockSize);
				if (it != blocksizes.end()) {
					blocksizes.erase(it);
					it = std::lower_bound(blocksizes.begin(), blocksizes.end(),
							latestBlockSize);
					blocksizes.insert(it, latestBlockSize);
				}
			}

		}

	} else {

		while (pblockindex != NULL && pblockindex->nHeight > firstBlock) {

			int blocksize = ::GetBlockSize(pblockindex);
			if (blocksize != -1) {

				blocksizes.push_back(blocksize);
			}

			pblockindex = pblockindex->pprev;
		}

	}

	return blocksizes;

}

inline int BlockSizeCalculator::GetBlockSize(CBlockIndex *pblockindex) {

	if (pblockindex == NULL) {
		return -1;
	}

	const CDiskBlockPos& pos = pblockindex->GetBlockPos();

	CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
	FILE* blockFile = filein.release();
	long int filePos = ftell(blockFile);
	fseek(blockFile, filePos - sizeof(uint32_t), SEEK_SET);

	uint32_t size = 0;
	fread(&size, sizeof(uint32_t), 1, blockFile);
	fclose(blockFile);
	return (unsigned int) size;

}<commit_msg>Block size calculator must not be read only.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "blocksizecalculator.h"

using namespace BlockSizeCalculator;
using namespace std;

static std::vector<unsigned int> blocksizes;
static bool sorted = false;

unsigned int BlockSizeCalculator::ComputeBlockSize(CBlockIndex *pblockindex, unsigned int pastblocks) {

	unsigned int proposedMaxBlockSize = 0;
	unsigned int result = OLD_MAX_BLOCK_SIZE;

	LOCK(cs_main);

	proposedMaxBlockSize = ::GetMedianBlockSize(pblockindex, pastblocks);

	if (proposedMaxBlockSize > 0) {
		//Absolute max block size will be 2^32-1 bytes due to the fact that unsigned int's are 4 bytes
		result = proposedMaxBlockSize * MAX_BLOCK_SIZE_INCREASE_MULTIPLE;
		result = result < proposedMaxBlockSize ?
				std::numeric_limits<unsigned int>::max() :
				result;
		if (result < OLD_MAX_BLOCK_SIZE) {
			result = OLD_MAX_BLOCK_SIZE;
		}
	}

	return result;

}

inline unsigned int BlockSizeCalculator::GetMedianBlockSize(
		CBlockIndex *pblockindex, unsigned int pastblocks) {

	blocksizes = ::GetBlockSizes(pblockindex, pastblocks);

	if(!sorted) {
		std::sort(blocksizes.begin(), blocksizes.end());
		sorted = true;
	}

	unsigned int vsize = blocksizes.size();
	if (vsize == pastblocks) {
		double median = 0;
		if ((vsize % 2) == 0) {
			median = (blocksizes[vsize / 2] + blocksizes[(vsize / 2) - 1]) / 2.0;
		} else {
			median = blocksizes[vsize / 2];
		}
		return static_cast<unsigned int>(floor(median));
	} else {
		return 0;
	}

}

inline std::vector<unsigned int> BlockSizeCalculator::GetBlockSizes(
		CBlockIndex *pblockindex, unsigned int pastblocks) {

	if (pblockindex->nHeight < (int)pastblocks) {
		return blocksizes;
	}

	int firstBlock = pblockindex->nHeight - pastblocks;

	if (blocksizes.size() > 0) {

		int latestBlockSize = ::GetBlockSize(pblockindex);

		if (latestBlockSize != -1) {

			CBlockIndex *firstBlockIndex = FindBlockByHeight(firstBlock);
			int oldestBlockSize = ::GetBlockSize(firstBlockIndex);
			if (oldestBlockSize != -1) {
				std::vector<unsigned int>::iterator it;
				it = std::find(blocksizes.begin(), blocksizes.end(),
						oldestBlockSize);
				if (it != blocksizes.end()) {
					blocksizes.erase(it);
					it = std::lower_bound(blocksizes.begin(), blocksizes.end(),
							latestBlockSize);
					blocksizes.insert(it, latestBlockSize);
				}
			}

		}

	} else {

		while (pblockindex != NULL && pblockindex->nHeight > firstBlock) {

			int blocksize = ::GetBlockSize(pblockindex);
			if (blocksize != -1) {

				blocksizes.push_back(blocksize);
			}

			pblockindex = pblockindex->pprev;
		}

	}

	return blocksizes;

}

inline int BlockSizeCalculator::GetBlockSize(CBlockIndex *pblockindex) {

	if (pblockindex == NULL) {
		return -1;
	}

	const CDiskBlockPos& pos = pblockindex->GetBlockPos();

	CAutoFile filein(OpenBlockFile(pos, false), SER_DISK, CLIENT_VERSION);
	FILE* blockFile = filein.release();
	long int filePos = ftell(blockFile);
	fseek(blockFile, filePos - sizeof(uint32_t), SEEK_SET);

	uint32_t size = 0;
	fread(&size, sizeof(uint32_t), 1, blockFile);
	fclose(blockFile);
	return (unsigned int) size;

}<|endoftext|>


<commit_before>/*
 * pv.cpp
 *
 */

#include <columns/buildandrun.hpp>
#include "SoundProbe.hpp"
#include "CochlearLayer.hpp"
#include "inverseCochlearLayer.hpp"
#include "inverseNewCochlearLayer.hpp"
#include "SoundReconLayer.h"
#include "StreamReconLayer.h"

#define MAIN_USES_CUSTOMGROUPS

#ifdef MAIN_USES_CUSTOMGROUPS
void * addcustomgroup(const char * keyword, const char * groupname, HyPerCol * hc);
// customgroups is for adding objects not supported by build().
#endif // MAIN_USES_ADDCUSTOM

int main(int argc, char * argv[]) {

	int status;
#ifdef MAIN_USES_CUSTOMGROUPS
	status = buildandrun(argc, argv, NULL, NULL, &addcustomgroup);
#else
	status = buildandrun(argc, argv);
#endif // MAIN_USES_CUSTOMGROUPS
	return status==PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
}

#ifdef MAIN_USES_CUSTOMGROUPS
void * addcustomgroup(const char * keyword, const char * groupname, HyPerCol * hc) {
    void * addedGroup = NULL;
#ifdef PV_USE_SNDFILE
    if ( !strcmp(keyword, "SoundProbe") ) {
       addedGroup = new SoundProbe(groupname, hc);
    }
#endif // PV_USE_SNDFILE
    if ( !strcmp(keyword, "CochlearLayer") ) {
       addedGroup = new CochlearLayer(groupname, hc);
    }
    if ( !strcmp(keyword, "inverseCochlearLayer") ) {
       addedGroup = new inverseCochlearLayer(groupname, hc);
    }
    if ( !strcmp(keyword, "inverseNewCochlearLayer") ) {
        addedGroup = new inverseNewCochlearLayer(groupname, hc);
    }
    if ( !strcmp(keyword, "SoundReconLayer") ) {
        addedGroup = new SoundReconLayer(groupname, hc);
    }
    if ( !strcmp(keyword, "StreamReconLayer") ) {
        addedGroup = new StreamReconLayer(groupname, hc);
    }

    return addedGroup;
}
#endif // MAIN_USE_CUSTOMGROUPS
<commit_msg>main fixed to account for soundrecon<commit_after>/*
 * pv.cpp
 *
 */

#include <columns/buildandrun.hpp>
#include "SoundProbe.hpp"
#include "CochlearLayer.hpp"
#include "inverseCochlearLayer.hpp"
#include "inverseNewCochlearLayer.hpp"
#include "StreamReconLayer.h"

#define MAIN_USES_CUSTOMGROUPS

#ifdef MAIN_USES_CUSTOMGROUPS
void * addcustomgroup(const char * keyword, const char * groupname, HyPerCol * hc);
// customgroups is for adding objects not supported by build().
#endif // MAIN_USES_ADDCUSTOM

int main(int argc, char * argv[]) {

	int status;
#ifdef MAIN_USES_CUSTOMGROUPS
	status = buildandrun(argc, argv, NULL, NULL, &addcustomgroup);
#else
	status = buildandrun(argc, argv);
#endif // MAIN_USES_CUSTOMGROUPS
	return status==PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
}

#ifdef MAIN_USES_CUSTOMGROUPS
void * addcustomgroup(const char * keyword, const char * groupname, HyPerCol * hc) {
    void * addedGroup = NULL;
#ifdef PV_USE_SNDFILE
    if ( !strcmp(keyword, "SoundProbe") ) {
       addedGroup = new SoundProbe(groupname, hc);
    }
#endif // PV_USE_SNDFILE
    if ( !strcmp(keyword, "CochlearLayer") ) {
       addedGroup = new CochlearLayer(groupname, hc);
    }
    if ( !strcmp(keyword, "inverseCochlearLayer") ) {
       addedGroup = new inverseCochlearLayer(groupname, hc);
    }
    if ( !strcmp(keyword, "inverseNewCochlearLayer") ) {
        addedGroup = new inverseNewCochlearLayer(groupname, hc);
    }
    if ( !strcmp(keyword, "StreamReconLayer") ) {
        addedGroup = new StreamReconLayer(groupname, hc);
    }

    return addedGroup;
}
#endif // MAIN_USE_CUSTOMGROUPS
<|endoftext|>