<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmltransition.h"
#include "qmlstategroup.h"
#include "qmlstate_p.h"
#include "qmlbinding.h"
#include "qmlstateoperations.h"
#include "qmlanimation.h"
#include "qmlanimation_p.h"
#include "qmlstate.h"
#include <QtCore/qdebug.h>

QT_BEGIN_NAMESPACE

DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG);

Action::Action()
: restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), fromBinding(0), toBinding(0), event(0),
  specifiedObject(0)
{
}

Action::Action(QObject *target, const QString &propertyName,
               const QVariant &value)
: restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), toValue(value), fromBinding(0),
  toBinding(0), event(0), specifiedObject(target),
  specifiedProperty(propertyName)
{
    property = QmlMetaProperty::createProperty(target, propertyName);
    if (property.isValid())
        fromValue = property.read();
}

ActionEvent::~ActionEvent()
{
}

QString ActionEvent::typeName() const
{
    return QString();
}

void ActionEvent::execute()
{
}

bool ActionEvent::isReversable()
{
    return false;
}

void ActionEvent::reverse()
{
}

QList<Action> ActionEvent::extraActions()
{
    return QList<Action>();
}

bool ActionEvent::changesBindings()
{
    return false;
}

void ActionEvent::clearForwardBindings()
{
}

void ActionEvent::clearReverseBindings()
{
}

bool ActionEvent::override(ActionEvent *other)
{
    Q_UNUSED(other);
    return false;
}

/*!
    \internal
*/
QmlStateOperation::QmlStateOperation(QObjectPrivate &dd, QObject *parent)
    : QObject(dd, parent)
{
}

/*!
    \qmlclass State
    \brief The State element defines configurations of objects and properties.

    A state is specified as a set of batched changes from the default configuration.

    Note that setting the state of an object from within another state of the same object is
    inadvisible. Not only would this have the same effect as going directly to the second state
    it may cause the program to crash.

    \sa {states-transitions}{States and Transitions}
*/

/*!
    \internal
    \class QmlState
    \brief The QmlState class allows you to define configurations of objects and properties.

    \ingroup group_states

    QmlState allows you to specify a state as a set of batched changes from the default
    configuration.

    \sa {states-transitions}{States and Transitions}
*/

QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,State,QmlState)
QmlState::QmlState(QObject *parent)
: QObject(*(new QmlStatePrivate), parent)
{
    Q_D(QmlState);
    d->transitionManager.setState(this);
}

QmlState::~QmlState()
{
}

/*!
    \qmlproperty string State::name
    This property holds the name of the state

    Each state should have a unique name.
*/
QString QmlState::name() const
{
    Q_D(const QmlState);
    return d->name;
}

void QmlState::setName(const QString &n)
{
    Q_D(QmlState);
    d->name = n;
}

bool QmlState::isWhenKnown() const
{
    Q_D(const QmlState);
    return d->when != 0;
}

/*!
    \qmlproperty bool State::when
    This property holds when the state should be applied

    This should be set to an expression that evaluates to true when you want the state to
    be applied.
*/
QmlBinding *QmlState::when() const
{
    Q_D(const QmlState);
    return d->when;
}

void QmlState::setWhen(QmlBinding *when)
{
    Q_D(QmlState);
    d->when = when;
    if (d->group)
        d->group->updateAutoState();
}

/*!
    \qmlproperty string State::extend
    This property holds the state that this state extends

    The state being extended is treated as the base state in regards to
    the changes specified by the extending state.
*/
QString QmlState::extends() const
{
    Q_D(const QmlState);
    return d->extends;
}

void QmlState::setExtends(const QString &extends)
{
    Q_D(QmlState);
    d->extends = extends;
}

/*!
    \qmlproperty list<Change> State::changes
    This property holds the changes to apply for this state
    \default

    By default these changes are applied against the default state. If the state
    extends another state, then the changes are applied against the state being
    extended.
*/
QmlList<QmlStateOperation *> *QmlState::changes()
{
    Q_D(QmlState);
    return &d->operations;
}

QmlState &QmlState::operator<<(QmlStateOperation *op)
{
    Q_D(QmlState);
    d->operations.append(op);
    return *this;
}

void QmlStatePrivate::complete()
{
    Q_Q(QmlState);

    for (int ii = 0; ii < reverting.count(); ++ii) {
        for (int jj = 0; jj < revertList.count(); ++jj) {
            if (revertList.at(jj).property == reverting.at(ii)) {
                revertList.removeAt(jj);
                break;
            }
        }
    }
    reverting.clear();

    emit q->completed();
}

// Generate a list of actions for this state.  This includes coelescing state
// actions that this state "extends"
QmlStateOperation::ActionList
QmlStatePrivate::generateActionList(QmlStateGroup *group) const
{
    QmlStateOperation::ActionList applyList;
    if (inState)
        return applyList;

    // Prevent "extends" recursion
    inState = true;

    if (!extends.isEmpty()) {
        QList<QmlState *> states = group->states();
        for (int ii = 0; ii < states.count(); ++ii)
            if (states.at(ii)->name() == extends)
                applyList = static_cast<QmlStatePrivate*>(states.at(ii)->d_func())->generateActionList(group);
    }

    foreach(QmlStateOperation *op, operations)
        applyList << op->actions();

    inState = false;
    return applyList;
}

QmlStateGroup *QmlState::stateGroup() const
{
    Q_D(const QmlState);
    return d->group;
}

void QmlState::setStateGroup(QmlStateGroup *group)
{
    Q_D(QmlState);
    d->group = group;
}

void QmlState::cancel()
{
    Q_D(QmlState);
    d->transitionManager.cancel();
}

void Action::deleteFromBinding()
{
    if (fromBinding) {
        property.setBinding(0);
        delete fromBinding;
        fromBinding = 0;
    }
}

void QmlState::apply(QmlStateGroup *group, QmlTransition *trans, QmlState *revert)
{
    Q_D(QmlState);

    cancel();
    if (revert)
        revert->cancel();
    d->revertList.clear();
    d->reverting.clear();

    if (revert) {
        QmlStatePrivate *revertPrivate =
            static_cast<QmlStatePrivate*>(revert->d_func());
        d->revertList = revertPrivate->revertList;
        revertPrivate->revertList.clear();
    }

    // List of actions caused by this state
    QmlStateOperation::ActionList applyList = d->generateActionList(group);

    // List of actions that need to be reverted to roll back (just) this state
    QmlStatePrivate::SimpleActionList additionalReverts;
    // First add the reverse of all the applyList actions
    for (int ii = 0; ii < applyList.count(); ++ii) {
        Action &action = applyList[ii];

        bool found = false;

        int jj;
        if (action.event) {
            if (!action.event->isReversable())
                continue;
            action.event->saveOriginals();
            for (jj = 0; jj < d->revertList.count(); ++jj) {
                ActionEvent *event = d->revertList.at(jj).event;
                if (event && event->typeName() == action.event->typeName()) {
                    if (action.event->override(event)) {
                        found = true;
                        break;
                    }
                }
            }
        } else {
            action.fromBinding = action.property.binding();

            for (jj = 0; jj < d->revertList.count(); ++jj) {
                if (d->revertList.at(jj).property == action.property) {
                    found = true;
                    break;
                }
            }
        }

        if (!found) {
            if (!action.restore) {
                action.deleteFromBinding();
            } else {
                // Only need to revert the applyList action if the previous
                // state doesn't have a higher priority revert already
                SimpleAction r(action);
                additionalReverts << r;
            }
        } else if (d->revertList.at(jj).binding != action.fromBinding) {
            action.deleteFromBinding();
        }
    }

    // Any reverts from a previous state that aren't carried forth
    // into this state need to be translated into apply actions
    for (int ii = 0; ii < d->revertList.count(); ++ii) {
        bool found = false;
        if (d->revertList.at(ii).event) {
            ActionEvent *event = d->revertList.at(ii).event;
            if (!event->isReversable())
                continue;
            for (int jj = 0; !found && jj < applyList.count(); ++jj) {
                const Action &action = applyList.at(jj);
                if (action.event && action.event->typeName() == event->typeName()) {
                    if (action.event->override(event))
                        found = true;
                }
            }
        } else {
            for (int jj = 0; !found && jj < applyList.count(); ++jj) {
                const Action &action = applyList.at(jj);
                if (action.property == d->revertList.at(ii).property)
                    found = true;
            }
        }
        if (!found) {
            QVariant cur = d->revertList.at(ii).property.read();
            delete d->revertList.at(ii).property.setBinding(0);

            Action a;
            a.property = d->revertList.at(ii).property;
            a.fromValue = cur;
            a.toValue = d->revertList.at(ii).value;
            a.toBinding = d->revertList.at(ii).binding;
            a.specifiedObject = d->revertList.at(ii).specifiedObject;
            a.specifiedProperty = d->revertList.at(ii).specifiedProperty;
            a.event = d->revertList.at(ii).event;
            a.reverseEvent = d->revertList.at(ii).reverseEvent;
            applyList << a;
            // Store these special reverts in the reverting list
            d->reverting << d->revertList.at(ii).property;
        }
    }
    // All the local reverts now become part of the ongoing revertList
    d->revertList << additionalReverts;

    // Output for debugging
    if (stateChangeDebug()) {
        foreach(const Action &action, applyList) {
            qWarning() << "    Action:" << action.property.object()
                       << action.property.name() << action.toValue;
        }
    }

    d->transitionManager.transition(applyList, trans);
}

QML_DEFINE_NOCREATE_TYPE(QmlStateOperation)
QmlStateOperation::ActionList QmlStateOperation::actions()
{
    return ActionList();
}

QT_END_NAMESPACE
<commit_msg>Don't accidently override originals.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmltransition.h"
#include "qmlstategroup.h"
#include "qmlstate_p.h"
#include "qmlbinding.h"
#include "qmlstateoperations.h"
#include "qmlanimation.h"
#include "qmlanimation_p.h"
#include "qmlstate.h"
#include <QtCore/qdebug.h>

QT_BEGIN_NAMESPACE

DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG);

Action::Action()
: restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), fromBinding(0), toBinding(0), event(0),
  specifiedObject(0)
{
}

Action::Action(QObject *target, const QString &propertyName,
               const QVariant &value)
: restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), toValue(value), fromBinding(0),
  toBinding(0), event(0), specifiedObject(target),
  specifiedProperty(propertyName)
{
    property = QmlMetaProperty::createProperty(target, propertyName);
    if (property.isValid())
        fromValue = property.read();
}

ActionEvent::~ActionEvent()
{
}

QString ActionEvent::typeName() const
{
    return QString();
}

void ActionEvent::execute()
{
}

bool ActionEvent::isReversable()
{
    return false;
}

void ActionEvent::reverse()
{
}

QList<Action> ActionEvent::extraActions()
{
    return QList<Action>();
}

bool ActionEvent::changesBindings()
{
    return false;
}

void ActionEvent::clearForwardBindings()
{
}

void ActionEvent::clearReverseBindings()
{
}

bool ActionEvent::override(ActionEvent *other)
{
    Q_UNUSED(other);
    return false;
}

/*!
    \internal
*/
QmlStateOperation::QmlStateOperation(QObjectPrivate &dd, QObject *parent)
    : QObject(dd, parent)
{
}

/*!
    \qmlclass State
    \brief The State element defines configurations of objects and properties.

    A state is specified as a set of batched changes from the default configuration.

    Note that setting the state of an object from within another state of the same object is
    inadvisible. Not only would this have the same effect as going directly to the second state
    it may cause the program to crash.

    \sa {states-transitions}{States and Transitions}
*/

/*!
    \internal
    \class QmlState
    \brief The QmlState class allows you to define configurations of objects and properties.

    \ingroup group_states

    QmlState allows you to specify a state as a set of batched changes from the default
    configuration.

    \sa {states-transitions}{States and Transitions}
*/

QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,State,QmlState)
QmlState::QmlState(QObject *parent)
: QObject(*(new QmlStatePrivate), parent)
{
    Q_D(QmlState);
    d->transitionManager.setState(this);
}

QmlState::~QmlState()
{
}

/*!
    \qmlproperty string State::name
    This property holds the name of the state

    Each state should have a unique name.
*/
QString QmlState::name() const
{
    Q_D(const QmlState);
    return d->name;
}

void QmlState::setName(const QString &n)
{
    Q_D(QmlState);
    d->name = n;
}

bool QmlState::isWhenKnown() const
{
    Q_D(const QmlState);
    return d->when != 0;
}

/*!
    \qmlproperty bool State::when
    This property holds when the state should be applied

    This should be set to an expression that evaluates to true when you want the state to
    be applied.
*/
QmlBinding *QmlState::when() const
{
    Q_D(const QmlState);
    return d->when;
}

void QmlState::setWhen(QmlBinding *when)
{
    Q_D(QmlState);
    d->when = when;
    if (d->group)
        d->group->updateAutoState();
}

/*!
    \qmlproperty string State::extend
    This property holds the state that this state extends

    The state being extended is treated as the base state in regards to
    the changes specified by the extending state.
*/
QString QmlState::extends() const
{
    Q_D(const QmlState);
    return d->extends;
}

void QmlState::setExtends(const QString &extends)
{
    Q_D(QmlState);
    d->extends = extends;
}

/*!
    \qmlproperty list<Change> State::changes
    This property holds the changes to apply for this state
    \default

    By default these changes are applied against the default state. If the state
    extends another state, then the changes are applied against the state being
    extended.
*/
QmlList<QmlStateOperation *> *QmlState::changes()
{
    Q_D(QmlState);
    return &d->operations;
}

QmlState &QmlState::operator<<(QmlStateOperation *op)
{
    Q_D(QmlState);
    d->operations.append(op);
    return *this;
}

void QmlStatePrivate::complete()
{
    Q_Q(QmlState);

    for (int ii = 0; ii < reverting.count(); ++ii) {
        for (int jj = 0; jj < revertList.count(); ++jj) {
            if (revertList.at(jj).property == reverting.at(ii)) {
                revertList.removeAt(jj);
                break;
            }
        }
    }
    reverting.clear();

    emit q->completed();
}

// Generate a list of actions for this state.  This includes coelescing state
// actions that this state "extends"
QmlStateOperation::ActionList
QmlStatePrivate::generateActionList(QmlStateGroup *group) const
{
    QmlStateOperation::ActionList applyList;
    if (inState)
        return applyList;

    // Prevent "extends" recursion
    inState = true;

    if (!extends.isEmpty()) {
        QList<QmlState *> states = group->states();
        for (int ii = 0; ii < states.count(); ++ii)
            if (states.at(ii)->name() == extends)
                applyList = static_cast<QmlStatePrivate*>(states.at(ii)->d_func())->generateActionList(group);
    }

    foreach(QmlStateOperation *op, operations)
        applyList << op->actions();

    inState = false;
    return applyList;
}

QmlStateGroup *QmlState::stateGroup() const
{
    Q_D(const QmlState);
    return d->group;
}

void QmlState::setStateGroup(QmlStateGroup *group)
{
    Q_D(QmlState);
    d->group = group;
}

void QmlState::cancel()
{
    Q_D(QmlState);
    d->transitionManager.cancel();
}

void Action::deleteFromBinding()
{
    if (fromBinding) {
        property.setBinding(0);
        delete fromBinding;
        fromBinding = 0;
    }
}

void QmlState::apply(QmlStateGroup *group, QmlTransition *trans, QmlState *revert)
{
    Q_D(QmlState);

    cancel();
    if (revert)
        revert->cancel();
    d->revertList.clear();
    d->reverting.clear();

    if (revert) {
        QmlStatePrivate *revertPrivate =
            static_cast<QmlStatePrivate*>(revert->d_func());
        d->revertList = revertPrivate->revertList;
        revertPrivate->revertList.clear();
    }

    // List of actions caused by this state
    QmlStateOperation::ActionList applyList = d->generateActionList(group);

    // List of actions that need to be reverted to roll back (just) this state
    QmlStatePrivate::SimpleActionList additionalReverts;
    // First add the reverse of all the applyList actions
    for (int ii = 0; ii < applyList.count(); ++ii) {
        Action &action = applyList[ii];

        bool found = false;

        int jj;
        if (action.event) {
            if (!action.event->isReversable())
                continue;
            for (jj = 0; jj < d->revertList.count(); ++jj) {
                ActionEvent *event = d->revertList.at(jj).event;
                if (event && event->typeName() == action.event->typeName()) {
                    if (action.event->override(event)) {
                        found = true;
                        break;
                    }
                }
            }
            if (!found || action.event != d->revertList.at(jj).event)
                action.event->saveOriginals();
        } else {
            action.fromBinding = action.property.binding();

            for (jj = 0; jj < d->revertList.count(); ++jj) {
                if (d->revertList.at(jj).property == action.property) {
                    found = true;
                    break;
                }
            }
        }

        if (!found) {
            if (!action.restore) {
                action.deleteFromBinding();
            } else {
                // Only need to revert the applyList action if the previous
                // state doesn't have a higher priority revert already
                SimpleAction r(action);
                additionalReverts << r;
            }
        } else if (d->revertList.at(jj).binding != action.fromBinding) {
            action.deleteFromBinding();
        }
    }

    // Any reverts from a previous state that aren't carried forth
    // into this state need to be translated into apply actions
    for (int ii = 0; ii < d->revertList.count(); ++ii) {
        bool found = false;
        if (d->revertList.at(ii).event) {
            ActionEvent *event = d->revertList.at(ii).event;
            if (!event->isReversable())
                continue;
            for (int jj = 0; !found && jj < applyList.count(); ++jj) {
                const Action &action = applyList.at(jj);
                if (action.event && action.event->typeName() == event->typeName()) {
                    if (action.event->override(event))
                        found = true;
                }
            }
        } else {
            for (int jj = 0; !found && jj < applyList.count(); ++jj) {
                const Action &action = applyList.at(jj);
                if (action.property == d->revertList.at(ii).property)
                    found = true;
            }
        }
        if (!found) {
            QVariant cur = d->revertList.at(ii).property.read();
            delete d->revertList.at(ii).property.setBinding(0);

            Action a;
            a.property = d->revertList.at(ii).property;
            a.fromValue = cur;
            a.toValue = d->revertList.at(ii).value;
            a.toBinding = d->revertList.at(ii).binding;
            a.specifiedObject = d->revertList.at(ii).specifiedObject;
            a.specifiedProperty = d->revertList.at(ii).specifiedProperty;
            a.event = d->revertList.at(ii).event;
            a.reverseEvent = d->revertList.at(ii).reverseEvent;
            applyList << a;
            // Store these special reverts in the reverting list
            d->reverting << d->revertList.at(ii).property;
        }
    }
    // All the local reverts now become part of the ongoing revertList
    d->revertList << additionalReverts;

    // Output for debugging
    if (stateChangeDebug()) {
        foreach(const Action &action, applyList) {
            qWarning() << "    Action:" << action.property.object()
                       << action.property.name() << action.toValue;
        }
    }

    d->transitionManager.transition(applyList, trans);
}

QML_DEFINE_NOCREATE_TYPE(QmlStateOperation)
QmlStateOperation::ActionList QmlStateOperation::actions()
{
    return ActionList();
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//

#include <muduo/net/inspect/ProcessInspector.h>
#include <muduo/base/ProcessInfo.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>

using namespace muduo;
using namespace muduo::net;

string uptime()
{
  char buf[256];
  int64_t age = Timestamp::now().microSecondsSinceEpoch() - ProcessInfo::startTime().microSecondsSinceEpoch();
  int microseconds = static_cast<int>(age % Timestamp::kMicroSecondsPerSecond);
  int seconds = static_cast<int>(age / Timestamp::kMicroSecondsPerSecond);
  int days = seconds/86400;
  int hours = (seconds % 86400) / 3600;
  int minutes = (seconds % 3600) / 60;
  snprintf(buf, sizeof buf, "%d days %02d:%02d:%02d.%06d",
           days, hours, minutes, seconds % 60, microseconds);
  return buf;
}

long getLong(const string& procStatus, const char* key)
{
  long result = 0;
  size_t pos = procStatus.find(key);
  if (pos != string::npos)
  {
    result = ::atol(procStatus.c_str() + pos + strlen(key));
  }
  return result;
}

string getProcessName(const string& procStatus)
{
  string result;
  size_t pos = procStatus.find("Name:");
  if (pos != string::npos)
  {
    pos += strlen("Name:");
    while (procStatus[pos] == '\t')
      ++pos;
    size_t eol = pos;
    while (procStatus[eol] != '\n')
      ++eol;
    result = procStatus.substr(pos, eol-pos);
  }
  return result;
}

/*
long getStatField(const string& procStat, int field)
{
  // 969 (inspector_test) S
  // 19089 969 19089 34823 969 4202496 609 0 0 0 0 3 0 0
  // 20 0 2 0 162443763 95813632 463 18446744073709551615 4194304 5159121
  // 140737297994192 140737297972304 140050830496611 0 0 4096 0
  // 18446744073709551615 0 0 17 3 0 0 0 0 0
  //
  long result = -1;
  size_t pos = procStat.find(") ");
  if (pos != string::npos)
  {
    const char* start = procStat.c_str() + pos + 4;
    int f = 0;
    const char* end = &*procStat.end();
    // FIXME: Test with last field
    while (f < field && start < end)
    {
      while (start < end && *start != ' ')
        ++start;
      ++f;
      while (start < end && *start == ' ')
        ++start;
    }
    if (f == field)
    {
      result = strtol(start, NULL, 10);
    }
  }
  return result;
}
*/

int stringPrintf(string* out, const char* fmt, ...) __attribute__ ((format (printf, 2, 3)));

int stringPrintf(string* out, const char* fmt, ...)
{
  char buf[256];
  va_list args;
  va_start(args, fmt);
  int ret = vsnprintf(buf, sizeof buf, fmt, args);
  va_end(args);
  out->append(buf);
  return ret;
}

string ProcessInspector::username_ = ProcessInfo::username();

void ProcessInspector::registerCommands(Inspector* ins)
{
  ins->add("proc", "overview", ProcessInspector::overview, "print basic overview");
  ins->add("proc", "pid", ProcessInspector::pid, "print pid");
  ins->add("proc", "status", ProcessInspector::procStatus, "print /proc/self/status");
  // ins->add("proc", "opened_files", ProcessInspector::openedFiles, "count /proc/self/fd");
  ins->add("proc", "threads", ProcessInspector::threads, "list /proc/self/task");
}

string ProcessInspector::overview(HttpRequest::Method, const Inspector::ArgList&)
{
  string result;
  result.reserve(1024);
  result += "Page generated at ";
  result += Timestamp::now().toFormattedString();
  result += " (UTC)\nStarted at ";
  result += ProcessInfo::startTime().toFormattedString();
  result += " (UTC), up for ";
  result += uptime();
  result += "\n";

  string procStatus = ProcessInfo::procStatus();
  result += getProcessName(procStatus);
  result += " (";
  result += ProcessInfo::exePath();
  result += ") running as ";
  result += username_;
  result += " on ";
  result += ProcessInfo::hostname(); // cache ?
  result += "\n";

  if (ProcessInfo::isDebugBuild())
  {
    result += "WARNING: debug build!\n";
  }

  stringPrintf(&result, "pid %d, num of threads %ld\n",
               ProcessInfo::pid(), getLong(procStatus, "Threads:"));

  result += "Virtual memory: ";
  stringPrintf(&result, "%.3f MiB, ",
               static_cast<double>(getLong(procStatus, "VmSize:")) / 1024.0);

  result += "RSS memory: ";
  stringPrintf(&result, "%.3f MiB\n",
               static_cast<double>(getLong(procStatus, "VmRSS:")) / 1024.0);

  stringPrintf(&result, "Opened files: %d, limit: %d\n",
               ProcessInfo::openedFiles(), ProcessInfo::maxOpenFiles());

  // string procStat = ProcessInfo::procStat();

  /*
  stringPrintf(&result, "ppid %ld\n", getStatField(procStat, 0));
  stringPrintf(&result, "pgid %ld\n", getStatField(procStat, 1));
  */

  ProcessInfo::CpuTime t = ProcessInfo::cpuTime();
  stringPrintf(&result, "User time: %12.3fs\nSys time:  %12.3fs\n",
               t.userSeconds, t.systemSeconds);

  // FIXME: add context switches

  return result;
}

string ProcessInspector::pid(HttpRequest::Method, const Inspector::ArgList&)
{
  char buf[32];
  snprintf(buf, sizeof buf, "%d", ProcessInfo::pid());
  return buf;
}

string ProcessInspector::procStatus(HttpRequest::Method, const Inspector::ArgList&)
{
  return ProcessInfo::procStatus();
}

string ProcessInspector::openedFiles(HttpRequest::Method, const Inspector::ArgList&)
{
  char buf[32];
  snprintf(buf, sizeof buf, "%d", ProcessInfo::openedFiles());
  return buf;
}

string ProcessInspector::threads(HttpRequest::Method, const Inspector::ArgList&)
{
  std::vector<pid_t> threads = ProcessInfo::threads();
  string result;
  for (size_t i = 0; i < threads.size(); ++i)
  {
    char buf[32];
    snprintf(buf, sizeof buf, "%d\n", threads[i]);
    result += buf;
  }
  return result;
}

<commit_msg>use one 'now' in overview page.<commit_after>// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//

#include <muduo/net/inspect/ProcessInspector.h>
#include <muduo/base/ProcessInfo.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>

using namespace muduo;
using namespace muduo::net;

string uptime(Timestamp now)
{
  char buf[256];
  int64_t age = now.microSecondsSinceEpoch() - ProcessInfo::startTime().microSecondsSinceEpoch();
  int microseconds = static_cast<int>(age % Timestamp::kMicroSecondsPerSecond);
  int seconds = static_cast<int>(age / Timestamp::kMicroSecondsPerSecond);
  int days = seconds/86400;
  int hours = (seconds % 86400) / 3600;
  int minutes = (seconds % 3600) / 60;
  snprintf(buf, sizeof buf, "%d days %02d:%02d:%02d.%06d",
           days, hours, minutes, seconds % 60, microseconds);
  return buf;
}

long getLong(const string& procStatus, const char* key)
{
  long result = 0;
  size_t pos = procStatus.find(key);
  if (pos != string::npos)
  {
    result = ::atol(procStatus.c_str() + pos + strlen(key));
  }
  return result;
}

string getProcessName(const string& procStatus)
{
  string result;
  size_t pos = procStatus.find("Name:");
  if (pos != string::npos)
  {
    pos += strlen("Name:");
    while (procStatus[pos] == '\t')
      ++pos;
    size_t eol = pos;
    while (procStatus[eol] != '\n')
      ++eol;
    result = procStatus.substr(pos, eol-pos);
  }
  return result;
}

/*
long getStatField(const string& procStat, int field)
{
  // 969 (inspector_test) S
  // 19089 969 19089 34823 969 4202496 609 0 0 0 0 3 0 0
  // 20 0 2 0 162443763 95813632 463 18446744073709551615 4194304 5159121
  // 140737297994192 140737297972304 140050830496611 0 0 4096 0
  // 18446744073709551615 0 0 17 3 0 0 0 0 0
  //
  long result = -1;
  size_t pos = procStat.find(") ");
  if (pos != string::npos)
  {
    const char* start = procStat.c_str() + pos + 4;
    int f = 0;
    const char* end = &*procStat.end();
    // FIXME: Test with last field
    while (f < field && start < end)
    {
      while (start < end && *start != ' ')
        ++start;
      ++f;
      while (start < end && *start == ' ')
        ++start;
    }
    if (f == field)
    {
      result = strtol(start, NULL, 10);
    }
  }
  return result;
}
*/

int stringPrintf(string* out, const char* fmt, ...) __attribute__ ((format (printf, 2, 3)));

int stringPrintf(string* out, const char* fmt, ...)
{
  char buf[256];
  va_list args;
  va_start(args, fmt);
  int ret = vsnprintf(buf, sizeof buf, fmt, args);
  va_end(args);
  out->append(buf);
  return ret;
}

string ProcessInspector::username_ = ProcessInfo::username();

void ProcessInspector::registerCommands(Inspector* ins)
{
  ins->add("proc", "overview", ProcessInspector::overview, "print basic overview");
  ins->add("proc", "pid", ProcessInspector::pid, "print pid");
  ins->add("proc", "status", ProcessInspector::procStatus, "print /proc/self/status");
  // ins->add("proc", "opened_files", ProcessInspector::openedFiles, "count /proc/self/fd");
  ins->add("proc", "threads", ProcessInspector::threads, "list /proc/self/task");
}

string ProcessInspector::overview(HttpRequest::Method, const Inspector::ArgList&)
{
  string result;
  result.reserve(1024);
  Timestamp now = Timestamp::now();
  result += "Page generated at ";
  result += now.toFormattedString();
  result += " (UTC)\nStarted at ";
  result += ProcessInfo::startTime().toFormattedString();
  result += " (UTC), up for ";
  result += uptime(now);
  result += "\n";

  string procStatus = ProcessInfo::procStatus();
  result += getProcessName(procStatus);
  result += " (";
  result += ProcessInfo::exePath();
  result += ") running as ";
  result += username_;
  result += " on ";
  result += ProcessInfo::hostname(); // cache ?
  result += "\n";

  if (ProcessInfo::isDebugBuild())
  {
    result += "WARNING: debug build!\n";
  }

  stringPrintf(&result, "pid %d, num of threads %ld\n",
               ProcessInfo::pid(), getLong(procStatus, "Threads:"));

  result += "Virtual memory: ";
  stringPrintf(&result, "%.3f MiB, ",
               static_cast<double>(getLong(procStatus, "VmSize:")) / 1024.0);

  result += "RSS memory: ";
  stringPrintf(&result, "%.3f MiB\n",
               static_cast<double>(getLong(procStatus, "VmRSS:")) / 1024.0);

  stringPrintf(&result, "Opened files: %d, limit: %d\n",
               ProcessInfo::openedFiles(), ProcessInfo::maxOpenFiles());

  // string procStat = ProcessInfo::procStat();

  /*
  stringPrintf(&result, "ppid %ld\n", getStatField(procStat, 0));
  stringPrintf(&result, "pgid %ld\n", getStatField(procStat, 1));
  */

  ProcessInfo::CpuTime t = ProcessInfo::cpuTime();
  stringPrintf(&result, "User time: %12.3fs\nSys time:  %12.3fs\n",
               t.userSeconds, t.systemSeconds);

  // FIXME: add context switches

  return result;
}

string ProcessInspector::pid(HttpRequest::Method, const Inspector::ArgList&)
{
  char buf[32];
  snprintf(buf, sizeof buf, "%d", ProcessInfo::pid());
  return buf;
}

string ProcessInspector::procStatus(HttpRequest::Method, const Inspector::ArgList&)
{
  return ProcessInfo::procStatus();
}

string ProcessInspector::openedFiles(HttpRequest::Method, const Inspector::ArgList&)
{
  char buf[32];
  snprintf(buf, sizeof buf, "%d", ProcessInfo::openedFiles());
  return buf;
}

string ProcessInspector::threads(HttpRequest::Method, const Inspector::ArgList&)
{
  std::vector<pid_t> threads = ProcessInfo::threads();
  string result;
  for (size_t i = 0; i < threads.size(); ++i)
  {
    char buf[32];
    snprintf(buf, sizeof buf, "%d\n", threads[i]);
    result += buf;
  }
  return result;
}

<|endoftext|>


<commit_before><commit_msg>Disable a test that's been failing since around r12725.<commit_after><|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <chrono>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/Settings.h"
#include "joynr/SystemServicesSettings.h"
#include "joynr/system/ProviderReregistrationControllerProxy.h"
#include "utils/TestLibJoynrWebSocketRuntime.h"

using namespace ::testing;
using namespace joynr;

TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime)
{
    auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
    joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
    const std::string domain(systemServiceSettings.getDomain());

    auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
    runtime->init();
    runtime->start();

    auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
    auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();

    Semaphore finishedSemaphore;
    providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr);
    EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10)));

    runtime->stop();
    runtime = nullptr;
}

TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnWsRuntime)
{
    auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
    joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
    const std::string domain(systemServiceSettings.getDomain());

    auto ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
    ccRuntime->init();
    ccRuntime->start();

    auto wsRuntimeSettings = std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings");
    auto wsRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(wsRuntimeSettings), nullptr);
    ASSERT_TRUE(wsRuntime->connect(std::chrono::seconds(2)));

    auto providerReregistrationControllerProxyBuilder = wsRuntime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
    auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();

    Semaphore finishedSemaphore;
    providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, [](const joynr::exceptions::JoynrRuntimeException&) { FAIL(); });
    EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10)));

    wsRuntime = nullptr;
    ccRuntime->stop();
    ccRuntime = nullptr;
}
<commit_msg>[C++] Increase discovery timeouts in ProviderReregistrationControllerTest<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <chrono>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/Settings.h"
#include "joynr/SystemServicesSettings.h"
#include "joynr/system/ProviderReregistrationControllerProxy.h"
#include "joynr/DiscoveryQos.h"
#include "utils/TestLibJoynrWebSocketRuntime.h"

using namespace ::testing;
using namespace joynr;

TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime)
{
    auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
    joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
    const std::string domain(systemServiceSettings.getDomain());

    auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
    runtime->init();
    runtime->start();

    DiscoveryQos discoveryQos;
    discoveryQos.setDiscoveryTimeoutMs(3000);

    auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
    auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->setDiscoveryQos(discoveryQos)->build();

    Semaphore finishedSemaphore;
    providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr);
    EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10)));

    runtime->stop();
    runtime = nullptr;
}

TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnWsRuntime)
{
    auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
    joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
    const std::string domain(systemServiceSettings.getDomain());

    auto ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
    ccRuntime->init();
    ccRuntime->start();

    DiscoveryQos discoveryQos;
    discoveryQos.setDiscoveryTimeoutMs(3000);

    auto wsRuntimeSettings = std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings");
    auto wsRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(wsRuntimeSettings), nullptr);
    ASSERT_TRUE(wsRuntime->connect(std::chrono::seconds(2)));

    auto providerReregistrationControllerProxyBuilder = wsRuntime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
    auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->setDiscoveryQos(discoveryQos)->build();

    Semaphore finishedSemaphore;
    providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, [](const joynr::exceptions::JoynrRuntimeException&) { FAIL(); });
    EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10)));

    wsRuntime = nullptr;
    ccRuntime->stop();
    ccRuntime = nullptr;
}
<|endoftext|>


<commit_before>//
//  story_view.cc
//  AirHockeyFree
//
//  Created by Jonathan Sharkey on 10-05-17.
//  Copyright 2010 Sharkable. All rights reserved.
//

#include "airhockey/views/story_view.h"

#include "gameengine/game_engine.h"

StoryView::StoryView(sp<GameEngine> game_engine) : EngineView(game_engine) {
  // TODO We're loading this twice so the counter for this texture goes up. Rethink texture
  // management.
  Sprite story_button_image = Sprite(game_engine, "story");
  Sprite story_button_image_2 = Sprite(game_engine, "story");
  GameSize screen_size = game_engine->game_size();
  GamePoint button_position =
      game_point_make((screen_size.width - story_button_image.content_size().width) / 2,
                      (screen_size.height - story_button_image.content_size().height) / 2);
  double zoom = screen_size.width / story_button_image.content_size().width;
  cout << "zoom: " << zoom << endl;
  story_button_.reset(new Button());
  story_button_->set_normal_sprite(story_button_image);
  story_button_->set_pressed_sprite(story_button_image_2);
  story_button_->set_zoom(zoom);
  story_button_->set_position(button_position);
  story_button_->set_delegate(this);
  AddEntity(story_button_);

  Sprite about_button_image = Sprite(game_engine, "about");
  Sprite about_button_image_2 = Sprite(game_engine, "about");
  about_button_.reset(new Button());
  about_button_->set_normal_sprite(about_button_image);
  about_button_->set_pressed_sprite(about_button_image_2);
  about_button_->set_zoom(zoom);
  about_button_->set_position(button_position);
  about_button_->set_delegate(this);
}

// ButtonDelegate

void StoryView::ButtonPressed(Button *button) {
  if (button == story_button_.get()) {
    RemoveEntity(story_button_);
    AddEntity(about_button_);
  } else if (button == about_button_.get()) {
    game_engine()->PopView();
  }
}
<commit_msg>Remove debug output statement.<commit_after>//
//  story_view.cc
//  AirHockeyFree
//
//  Created by Jonathan Sharkey on 10-05-17.
//  Copyright 2010 Sharkable. All rights reserved.
//

#include "airhockey/views/story_view.h"

#include "gameengine/game_engine.h"

StoryView::StoryView(sp<GameEngine> game_engine) : EngineView(game_engine) {
  // TODO We're loading this twice so the counter for this texture goes up. Rethink texture
  // management.
  Sprite story_button_image = Sprite(game_engine, "story");
  Sprite story_button_image_2 = Sprite(game_engine, "story");
  GameSize screen_size = game_engine->game_size();
  GamePoint button_position =
      game_point_make((screen_size.width - story_button_image.content_size().width) / 2,
                      (screen_size.height - story_button_image.content_size().height) / 2);
  double zoom = screen_size.width / story_button_image.content_size().width;
  story_button_.reset(new Button());
  story_button_->set_normal_sprite(story_button_image);
  story_button_->set_pressed_sprite(story_button_image_2);
  story_button_->set_zoom(zoom);
  story_button_->set_position(button_position);
  story_button_->set_delegate(this);
  AddEntity(story_button_);

  Sprite about_button_image = Sprite(game_engine, "about");
  Sprite about_button_image_2 = Sprite(game_engine, "about");
  about_button_.reset(new Button());
  about_button_->set_normal_sprite(about_button_image);
  about_button_->set_pressed_sprite(about_button_image_2);
  about_button_->set_zoom(zoom);
  about_button_->set_position(button_position);
  about_button_->set_delegate(this);
}

// ButtonDelegate

void StoryView::ButtonPressed(Button *button) {
  if (button == story_button_.get()) {
    RemoveEntity(story_button_);
    AddEntity(about_button_);
  } else if (button == about_button_.get()) {
    game_engine()->PopView();
  }
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {ROI_QB_MUL_1.png}
//    OUTPUTS: {PanTexOutput.tif}, {pretty_PanTexInput.png}, {pretty_PanTexOutput.png}
//  Software Guide : EndCommandLineArgs

#include "itkExceptionObject.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"

// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{otb}{PanTexTextureImageFilter}. This texture parameter was
// first introduced in \cite{PanTex} and is very useful for urban area
// detection.
// \relatedClasses
//  \begin{itemize}
//  \item \doxygen{otb}{ContrastTextureFunctor}
//  \end{itemize}
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbPanTexTextureImageFilter.h"
// Software Guide : EndCodeSnippet

int main(int argc, char * argv[])
{
  // Parse command line parameters
  if (argc != 5)
    {
    std::cerr << "Usage: " << argv[0] << " <inputImage> ";
    std::cerr << " <outputImage> <inputRescaled> <outputRescaled> ";
    std::cerr << std::endl;
    return EXIT_FAILURE;
    }

  const char* infname   = argv[1];
  const char* outfname  = argv[2];
  const char* inprettyfname  = argv[3];
  const char* outprettyfname  = argv[4];

  typedef double PixelType;
  const int Dimension = 2;
  typedef otb::Image<PixelType, Dimension> ImageType;

  // Software Guide : BeginLatex
//
// After defining the types for the pixels and the images used in the
// example, we define the type for the PanTex filter. It is
// templated by the input and output image types.
//
// Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::PanTexTextureImageFilter<ImageType, ImageType> PanTexType;
  // Software Guide : EndCodeSnippet
  typedef otb::ImageFileReader<ImageType> ReaderType;
  typedef otb::ImageFileWriter<ImageType> WriterType;

  ReaderType::Pointer reader  = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName(infname);
  writer->SetFileName(outfname);

  // Software Guide : BeginLatex
//
// We can now instatiate the filter.
//
// Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  PanTexType::Pointer textureFilter = PanTexType::New();
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex//
// We can now plug the pipeline and trigger the execution by calling
// the \code{Update} method of the writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
  textureFilter->SetInput(reader->GetOutput());
  writer->SetInput(textureFilter->GetOutput());

  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  // Figure~\ref{fig:PANTEXFILTER} shows the result of applying
  // the PanTex computation.
  // \begin{figure}
  // \center
  // \includegraphics[width=0.40\textwidth]{pretty_PanTexInput.eps}
  // \includegraphics[width=0.40\textwidth]{pretty_PanTexOutput.eps}
  // \itkcaption[PanTex Filter]{Result of applying the
  // \doxygen{otb}{PanTexTextureImageFilter} to an image. From left to right :
  // original image, PanTex feature.}
  // \label{fig:PANTEXFILTER}
  // \end{figure}
  //
  //  Software Guide : EndLatex

  // Pretty image creation for printing

  typedef otb::Image<unsigned char,
                     Dimension>
  OutputPrettyImageType;
  typedef otb::ImageFileWriter<OutputPrettyImageType>
  WriterPrettyOutputType;
  typedef itk::RescaleIntensityImageFilter<ImageType,
                                           OutputPrettyImageType>
  RescalerOutputType;

  RescalerOutputType::Pointer     outputRescaler     = RescalerOutputType::New();
  WriterPrettyOutputType::Pointer prettyOutputWriter =
    WriterPrettyOutputType::New();
  outputRescaler->SetInput(textureFilter->GetOutput());
  outputRescaler->SetOutputMinimum(0);
  outputRescaler->SetOutputMaximum(255);
  prettyOutputWriter->SetFileName(outprettyfname);
  prettyOutputWriter->SetInput(outputRescaler->GetOutput());

  prettyOutputWriter->Update();

  outputRescaler->SetInput(reader->GetOutput());
  outputRescaler->SetOutputMinimum(0);
  outputRescaler->SetOutputMaximum(255);
  prettyOutputWriter->SetFileName(inprettyfname);
  prettyOutputWriter->SetInput(outputRescaler->GetOutput());

  prettyOutputWriter->Update();

  return EXIT_SUCCESS;
}
<commit_msg>DOC:Modify example in the software guide for the derived built-up precense index texture (PanTex)<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {ROI_QB_MUL_1.png}
//    OUTPUTS: {PanTexOutput.tif}, {pretty_PanTexInput.png}, {pretty_PanTexOutput.png}
//  Software Guide : EndCommandLineArgs

#include "itkExceptionObject.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"

// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{otb}{ScalarImageToPanTexTextureFilter}. This texture parameter was
// first introduced in \cite{PanTex} and is very useful for urban area
// detection.
// \relatedClasses
//  \begin{itemize}
//  \item \doxygen{otb}{ContrastTextureFunctor}
//  \end{itemize}
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbScalarImageToPanTexTextureFilter.h"
// Software Guide : EndCodeSnippet

int main(int argc, char * argv[])
{
  // Parse command line parameters
  if (argc != 5)
    {
    std::cerr << "Usage: " << argv[0] << " <inputImage> ";
    std::cerr << " <outputImage> <inputRescaled> <outputRescaled> ";
    std::cerr << std::endl;
    return EXIT_FAILURE;
    }

  const char* infname   = argv[1];
  const char* outfname  = argv[2];
  const char* inprettyfname  = argv[3];
  const char* outprettyfname  = argv[4];

  typedef double PixelType;
  const int Dimension = 2;
  typedef otb::Image<PixelType, Dimension> ImageType;

  // Software Guide : BeginLatex
//
// After defining the types for the pixels and the images used in the
// example, we define the type for the PanTex filter. It is
// templated by the input and output image types.
//
// Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::ScalarImageToPanTexTextureFilter<ImageType, ImageType> PanTexTextureFilterType;
  // Software Guide : EndCodeSnippet
  typedef otb::ImageFileReader<ImageType> ReaderType;
  typedef otb::ImageFileWriter<ImageType> WriterType;

  ReaderType::Pointer reader  = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName(infname);
  writer->SetFileName(outfname);

  // Software Guide : BeginLatex
//
// We can now instatiate the filter.
//
// Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  PanTexTextureFilterType::Pointer textureFilter = PanTexTextureFilterType::New();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Then, we set the parameters of the filter.The radius of
  // the neighborhood to compute the texture.
  // The number of bins per axis for histogramm generation (it is the
  // size of the co-occurrence matrix). Moreover, we have to specify
  // the Min/Max in the input image. In the example, image Min/Max is setted
  // by the user to 0 and 255. Alternatyvely you can use the class \doxygen{itk}{MinimumMaximumImageCalculator}
  // to calculate these values.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  PanTexTextureFilterType::SizeType sradius;
  sradius.Fill(4);
  textureFilter->SetNumberOfBinsPerAxis(8);
  textureFilter->SetRadius(sradius);
  textureFilter->SetInputImageMinimum(0);
  textureFilter->SetInputImageMaximum(256);
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We can now plug the pipeline and trigger the execution by calling
  // the \code{Update} method of the writer.
  //
  // Software Guide : EndLatex
  // Software Guide : BeginCodeSnippet
  textureFilter->SetInput(reader->GetOutput());
  writer->SetInput(textureFilter->GetOutput());

  writer->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  // Figure~\ref{fig:PANTEXFILTER} shows the result of applying
  // the PanTex computation.
  // \begin{figure}
  // \center
  // \includegraphics[width=0.40\textwidth]{pretty_PanTexInput.eps}
  // \includegraphics[width=0.40\textwidth]{pretty_PanTexOutput.eps}
  // \itkcaption[PanTex Filter]{Result of applying the
  // \doxygen{otb}{ScalarImageToPanTexTextureFilter} to an image. From left to right :
  // original image, PanTex feature.}
  // \label{fig:PANTEXFILTER}
  // \end{figure}
  //
  //  Software Guide : EndLatex

  // Pretty image creation for printing

  typedef otb::Image<unsigned char,
                     Dimension>
  OutputPrettyImageType;
  typedef otb::ImageFileWriter<OutputPrettyImageType>
  WriterPrettyOutputType;
  typedef itk::RescaleIntensityImageFilter<ImageType,
                                           OutputPrettyImageType>
  RescalerOutputType;

  RescalerOutputType::Pointer     outputRescaler     = RescalerOutputType::New();
  WriterPrettyOutputType::Pointer prettyOutputWriter =
    WriterPrettyOutputType::New();
  outputRescaler->SetInput(textureFilter->GetOutput());
  outputRescaler->SetOutputMinimum(0);
  outputRescaler->SetOutputMaximum(255);
  prettyOutputWriter->SetFileName(outprettyfname);
  prettyOutputWriter->SetInput(outputRescaler->GetOutput());

  prettyOutputWriter->Update();

  outputRescaler->SetInput(reader->GetOutput());
  outputRescaler->SetOutputMinimum(0);
  outputRescaler->SetOutputMaximum(255);
  prettyOutputWriter->SetFileName(inprettyfname);
  prettyOutputWriter->SetInput(outputRescaler->GetOutput());

  prettyOutputWriter->Update();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "doofit/plotting/Plot/Plot.h"

// STL
#include <string>
#include <sstream>
#include <vector>

// boost
#include <boost/regex.hpp>

// ROOT
#include "TIterator.h"

// from RooFit
#include "RooArgList.h"
#include "RooAbsRealLValue.h"
#include "RooAbsData.h"
#include "RooAbsPdf.h"
#include "RooPlot.h"
#include "RooHist.h"

// from Project
#include "doocore/io/MsgStream.h"
#include "doocore/lutils/lutils.h"
#include "doofit/plotting/Plot/PlotConfig.h"

using namespace ROOT;
using namespace RooFit;
using namespace doocore::io;

namespace doofit {
namespace plotting {

Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooArgList& pdfs, const std::string& plot_name)
: config_plot_(cfg_plot),
  dimension_(dimension),
  datasets_(),
  plot_name_(plot_name)
{
  datasets_.push_back(&dataset);
  pdf_ = dynamic_cast<RooAbsPdf*>(pdfs.first());

  if (&dimension_ == NULL) {
    serr << "Plot::Plot(): Dimension is invalid." << endmsg;
    throw 1;
  }
  if (datasets_.front() == NULL) {
    serr << "Plot::Plot(): Dataset is invalid." << endmsg;
    throw 1;
  }
  if (plot_name_ == "") {
    plot_name_ = dimension_.GetName();
  }

  for (int i=1; i<pdfs.getSize(); ++i) {
    RooAbsArg* sub_arg = pdfs.at(i);
    const RooAbsPdf* sub_pdf = dynamic_cast<RooAbsPdf*>(sub_arg);

    if (sub_pdf != NULL) {
      components_.push_back(RooArgSet(*sub_pdf));
    }
  }
}

Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooAbsPdf& pdf, const std::vector<std::string>& components, const std::string& plot_name)
: config_plot_(cfg_plot),
  dimension_(dimension),
  datasets_(),
  plot_name_(plot_name)
{
  datasets_.push_back(&dataset);
  pdf_ = &pdf;

  if (pdf_ == NULL) {
    serr << "Plot::Plot(): Main PDF is invalid." << endmsg;
    throw 1;
  }
  if (&dimension_ == NULL) {
    serr << "Plot::Plot(): Dimension is invalid." << endmsg;
    throw 1;
  }
  if (datasets_.front() == NULL) {
    serr << "Plot::Plot(): Dataset is invalid." << endmsg;
    throw 1;
  }
  if (plot_name_ == "") {
    plot_name_ = dimension_.GetName();
  }

  // iterate over sub PDFs and match supplied regular expressions
  RooArgSet nodes;
  pdf.branchNodeServerList(&nodes);

  for (std::vector<std::string>::const_iterator it = components.begin();
       it != components.end(); ++it) {
    boost::regex r(*it);
    components_.push_back(RooArgSet());

    TIterator* it_nodes = nodes.createIterator();
    RooAbsArg* node = NULL;

    while ((node = dynamic_cast<RooAbsArg*>(it_nodes->Next()))) {
      RooAbsPdf* pdf_node = dynamic_cast<RooAbsPdf*>(node);
      if (pdf_node != NULL) {
        std::string pdf_name = pdf_node->GetName();

        // exclude resolution models generated by RooFit and match the rest
        if (pdf_name.find("_conv_") == -1 && regex_match(pdf_name,r)) {
          components_.back().add(*pdf_node);
        }
      }
    }
    delete it_nodes;
  }
}

void Plot::PlotHandler(ScaleType sc_y, std::string suffix) const {
  if (suffix == "") suffix = "_log";

  std::string plot_name = plot_name_;

  std::stringstream log_plot_name_sstr;
  log_plot_name_sstr << plot_name << suffix;
  std::string log_plot_name = log_plot_name_sstr.str();

  std::stringstream pull_plot_sstr;
  pull_plot_sstr << plot_name << "_pull";
  std::string pull_plot_name = pull_plot_sstr.str();

  std::stringstream log_pull_plot_sstr;
  log_pull_plot_sstr << plot_name << "_pull" << suffix;
  std::string log_pull_plot_name = log_pull_plot_sstr.str();

  sinfo << "Plotting " << dimension_.GetName() << " into " << config_plot_.plot_directory() << plot_name << endmsg;

  doocore::lutils::setStyle("LHCb");

  RooCmdArg range_arg;

  // x range
  if (!dimension_.hasMin() && !dimension_.hasMax()) {
    double min, max;

    // ugly const_cast because RooFit is stupid (RooDataSet::getRange needs non-const RooRealVar)
    RooRealVar* dimension_non_const = const_cast<RooRealVar*>(dynamic_cast<const RooRealVar*>(&dimension_));
    datasets_.front()->getRange(*dimension_non_const, min, max);

    double min_t, max_t;
    for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin()+1;
         it != datasets_.end(); ++it) {
      (*it)->getRange(*dimension_non_const, min_t, max_t);
      if (min_t < min) min = min_t;
      if (max_t > max) max = max_t;
    }

    range_arg = Range(min, max);
  }
  RooPlot* plot_frame = dimension_.frame(range_arg);

  for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
       it != datasets_.end(); ++it) {
    (*it)->plotOn(plot_frame/*, Rescale(1.0/(*it)->sumEntries())*/);
  }

  // y range adaptively for log scale
  RooHist * data = (RooHist*) plot_frame->findObject(0,RooHist::Class());
  double x,y;
  data->GetPoint(0,x,y);
  double min_data_entry = y;
  for (unsigned int i = 1; i < data->GetN(); ++i) {
    data->GetPoint(i,x,y);
    sdebug << y << endmsg;
    if (min_data_entry > y) min_data_entry = y;
  }
  double min_plot = TMath::Power(10.0,TMath::Log10(min_data_entry)-0.7);

  sdebug << "minimum entry in histogram: " << min_data_entry << endmsg;
  sdebug << "minimum for plot range: " << min_plot << endmsg;

  TLatex label(0.65,0.85,"LHCb");

  config_plot_.OnDemandOpenPlotStack();
  if (pdf_ != NULL) {
    RooPlot* plot_frame_pull = dimension_.frame(range_arg);
    for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
         it != datasets_.end(); ++it) {
      (*it)->plotOn(plot_frame_pull);
    }

    // I feel so stupid doing this but apparently RooFit leaves me no other way...
    RooCmdArg arg1, arg2, arg3, arg4, arg5, arg6, arg7;
    if (plot_args_.size() > 0) arg1 = plot_args_[0];
    if (plot_args_.size() > 1) arg2 = plot_args_[1];
    if (plot_args_.size() > 2) arg3 = plot_args_[2];
    if (plot_args_.size() > 3) arg4 = plot_args_[3];
    if (plot_args_.size() > 4) arg5 = plot_args_[4];
    if (plot_args_.size() > 5) arg6 = plot_args_[5];
    if (plot_args_.size() > 6) arg7 = plot_args_[6];

    int i=1;
    for (std::vector<RooArgSet>::const_iterator it = components_.begin();
         it != components_.end(); ++it) {
      if (it->getSize() > 0) {
        sinfo << "Plotting component " << it->first()->GetName() << endmsg;
        pdf_->plotOn(plot_frame, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
        pdf_->plotOn(plot_frame_pull, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
        ++i;
      }
    }

    pdf_->plotOn(plot_frame, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
    pdf_->plotOn(plot_frame_pull, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);

    // =10^(ln(11)/ln(10)-0.5)
    //plot_frame_pull->SetMinimum(0.5);

    plot_frame_pull->SetMinimum(0.5);
    plot_frame_pull->SetMaximum(1.3*plot_frame_pull->GetMaximum());
    if (sc_y == kLinear || sc_y == kBoth) {
      doocore::lutils::PlotPulls(pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), false, false, true);
      doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), false, false, true, "");
    }

    plot_frame_pull->SetMinimum(min_plot);
    if (sc_y == kLogarithmic || sc_y == kBoth) {
      doocore::lutils::PlotPulls(log_pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), true, false, true);
      doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), true, false, true, "");
    }

    delete plot_frame_pull;
  }

  plot_frame->SetMinimum(0.0);
  plot_frame->SetMaximum(1.3*plot_frame->GetMaximum());
  if (sc_y == kLinear || sc_y == kBoth) {
    doocore::lutils::PlotSimple(plot_name, plot_frame, label, config_plot_.plot_directory(), false);
    doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), false);
  }

  plot_frame->SetMinimum(min_plot);
  if (sc_y == kLogarithmic || sc_y == kBoth) {
    doocore::lutils::PlotSimple(log_plot_name, plot_frame, label, config_plot_.plot_directory(), true);
    doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), true);
  }

  delete plot_frame;
}

Plot::~Plot() {}

} // namespace plotting
} // namespace doofit
<commit_msg>Plotting: fixing problems with zero bins for y range<commit_after>#include "doofit/plotting/Plot/Plot.h"

// STL
#include <string>
#include <sstream>
#include <vector>

// boost
#include <boost/regex.hpp>

// ROOT
#include "TIterator.h"

// from RooFit
#include "RooArgList.h"
#include "RooAbsRealLValue.h"
#include "RooAbsData.h"
#include "RooAbsPdf.h"
#include "RooPlot.h"
#include "RooHist.h"

// from Project
#include "doocore/io/MsgStream.h"
#include "doocore/lutils/lutils.h"
#include "doofit/plotting/Plot/PlotConfig.h"

using namespace ROOT;
using namespace RooFit;
using namespace doocore::io;

namespace doofit {
namespace plotting {

Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooArgList& pdfs, const std::string& plot_name)
: config_plot_(cfg_plot),
  dimension_(dimension),
  datasets_(),
  plot_name_(plot_name)
{
  datasets_.push_back(&dataset);
  pdf_ = dynamic_cast<RooAbsPdf*>(pdfs.first());

  if (&dimension_ == NULL) {
    serr << "Plot::Plot(): Dimension is invalid." << endmsg;
    throw 1;
  }
  if (datasets_.front() == NULL) {
    serr << "Plot::Plot(): Dataset is invalid." << endmsg;
    throw 1;
  }
  if (plot_name_ == "") {
    plot_name_ = dimension_.GetName();
  }

  for (int i=1; i<pdfs.getSize(); ++i) {
    RooAbsArg* sub_arg = pdfs.at(i);
    const RooAbsPdf* sub_pdf = dynamic_cast<RooAbsPdf*>(sub_arg);

    if (sub_pdf != NULL) {
      components_.push_back(RooArgSet(*sub_pdf));
    }
  }
}

Plot::Plot(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooAbsPdf& pdf, const std::vector<std::string>& components, const std::string& plot_name)
: config_plot_(cfg_plot),
  dimension_(dimension),
  datasets_(),
  plot_name_(plot_name)
{
  datasets_.push_back(&dataset);
  pdf_ = &pdf;

  if (pdf_ == NULL) {
    serr << "Plot::Plot(): Main PDF is invalid." << endmsg;
    throw 1;
  }
  if (&dimension_ == NULL) {
    serr << "Plot::Plot(): Dimension is invalid." << endmsg;
    throw 1;
  }
  if (datasets_.front() == NULL) {
    serr << "Plot::Plot(): Dataset is invalid." << endmsg;
    throw 1;
  }
  if (plot_name_ == "") {
    plot_name_ = dimension_.GetName();
  }

  // iterate over sub PDFs and match supplied regular expressions
  RooArgSet nodes;
  pdf.branchNodeServerList(&nodes);

  for (std::vector<std::string>::const_iterator it = components.begin();
       it != components.end(); ++it) {
    boost::regex r(*it);
    components_.push_back(RooArgSet());

    TIterator* it_nodes = nodes.createIterator();
    RooAbsArg* node = NULL;

    while ((node = dynamic_cast<RooAbsArg*>(it_nodes->Next()))) {
      RooAbsPdf* pdf_node = dynamic_cast<RooAbsPdf*>(node);
      if (pdf_node != NULL) {
        std::string pdf_name = pdf_node->GetName();

        // exclude resolution models generated by RooFit and match the rest
        if (pdf_name.find("_conv_") == -1 && regex_match(pdf_name,r)) {
          components_.back().add(*pdf_node);
        }
      }
    }
    delete it_nodes;
  }
}

void Plot::PlotHandler(ScaleType sc_y, std::string suffix) const {
  if (suffix == "") suffix = "_log";

  std::string plot_name = plot_name_;

  std::stringstream log_plot_name_sstr;
  log_plot_name_sstr << plot_name << suffix;
  std::string log_plot_name = log_plot_name_sstr.str();

  std::stringstream pull_plot_sstr;
  pull_plot_sstr << plot_name << "_pull";
  std::string pull_plot_name = pull_plot_sstr.str();

  std::stringstream log_pull_plot_sstr;
  log_pull_plot_sstr << plot_name << "_pull" << suffix;
  std::string log_pull_plot_name = log_pull_plot_sstr.str();

  sinfo << "Plotting " << dimension_.GetName() << " into " << config_plot_.plot_directory() << plot_name << endmsg;

  doocore::lutils::setStyle("LHCb");

  RooCmdArg range_arg;

  // x range
  if (!dimension_.hasMin() && !dimension_.hasMax()) {
    double min, max;

    // ugly const_cast because RooFit is stupid (RooDataSet::getRange needs non-const RooRealVar)
    RooRealVar* dimension_non_const = const_cast<RooRealVar*>(dynamic_cast<const RooRealVar*>(&dimension_));
    datasets_.front()->getRange(*dimension_non_const, min, max);

    double min_t, max_t;
    for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin()+1;
         it != datasets_.end(); ++it) {
      (*it)->getRange(*dimension_non_const, min_t, max_t);
      if (min_t < min) min = min_t;
      if (max_t > max) max = max_t;
    }

    range_arg = Range(min, max);
  }
  RooPlot* plot_frame = dimension_.frame(range_arg);

  for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
       it != datasets_.end(); ++it) {
    (*it)->plotOn(plot_frame/*, Rescale(1.0/(*it)->sumEntries())*/);
  }

  // y range adaptively for log scale
  RooHist * data = (RooHist*) plot_frame->findObject(0,RooHist::Class());
  double x,y;
  data->GetPoint(0,x,y);
  double min_data_entry = y;
  for (unsigned int i = 1; i < data->GetN(); ++i) {
    data->GetPoint(i,x,y);
    if (min_data_entry > y) min_data_entry = y;
  }
  if (min_data_entry == 0.0) min_data_entry = 1.0;
  double min_plot = TMath::Power(10.0,TMath::Log10(min_data_entry)-0.7);

//  sdebug << "minimum entry in histogram: " << min_data_entry << endmsg;
//  sdebug << "minimum for plot range: " << min_plot << endmsg;

  TLatex label(0.65,0.85,"LHCb");

  config_plot_.OnDemandOpenPlotStack();
  if (pdf_ != NULL) {
    RooPlot* plot_frame_pull = dimension_.frame(range_arg);
    for (std::vector<const RooAbsData*>::const_iterator it = datasets_.begin();
         it != datasets_.end(); ++it) {
      (*it)->plotOn(plot_frame_pull);
    }

    // I feel so stupid doing this but apparently RooFit leaves me no other way...
    RooCmdArg arg1, arg2, arg3, arg4, arg5, arg6, arg7;
    if (plot_args_.size() > 0) arg1 = plot_args_[0];
    if (plot_args_.size() > 1) arg2 = plot_args_[1];
    if (plot_args_.size() > 2) arg3 = plot_args_[2];
    if (plot_args_.size() > 3) arg4 = plot_args_[3];
    if (plot_args_.size() > 4) arg5 = plot_args_[4];
    if (plot_args_.size() > 5) arg6 = plot_args_[5];
    if (plot_args_.size() > 6) arg7 = plot_args_[6];

    int i=1;
    for (std::vector<RooArgSet>::const_iterator it = components_.begin();
         it != components_.end(); ++it) {
      if (it->getSize() > 0) {
        sinfo << "Plotting component " << it->first()->GetName() << endmsg;
        pdf_->plotOn(plot_frame, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
        pdf_->plotOn(plot_frame_pull, Components(*it), LineColor(config_plot_.GetPdfLineColor(i)), LineStyle(config_plot_.GetPdfLineStyle(i)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
        ++i;
      }
    }

    pdf_->plotOn(plot_frame, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);
    pdf_->plotOn(plot_frame_pull, LineColor(config_plot_.GetPdfLineColor(0)), LineStyle(config_plot_.GetPdfLineStyle(0)), arg1, arg2, arg3, arg4, arg5, arg6, arg7);

    // =10^(ln(11)/ln(10)-0.5)
    //plot_frame_pull->SetMinimum(0.5);

    plot_frame_pull->SetMinimum(0.5);
    plot_frame_pull->SetMaximum(1.3*plot_frame_pull->GetMaximum());
    if (sc_y == kLinear || sc_y == kBoth) {
      doocore::lutils::PlotPulls(pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), false, false, true);
      doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), false, false, true, "");
    }

    plot_frame_pull->SetMinimum(min_plot);
    if (sc_y == kLogarithmic || sc_y == kBoth) {
      doocore::lutils::PlotPulls(log_pull_plot_name, plot_frame_pull, label, config_plot_.plot_directory(), true, false, true);
      doocore::lutils::PlotPulls("AllPlots", plot_frame_pull, label, config_plot_.plot_directory(), true, false, true, "");
    }

    delete plot_frame_pull;
  }

  plot_frame->SetMinimum(0.0);
  plot_frame->SetMaximum(1.3*plot_frame->GetMaximum());
  if (sc_y == kLinear || sc_y == kBoth) {
    doocore::lutils::PlotSimple(plot_name, plot_frame, label, config_plot_.plot_directory(), false);
    doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), false);
  }

  plot_frame->SetMinimum(min_plot);
  if (sc_y == kLogarithmic || sc_y == kBoth) {
    doocore::lutils::PlotSimple(log_plot_name, plot_frame, label, config_plot_.plot_directory(), true);
    doocore::lutils::PlotSimple("AllPlots", plot_frame, label, config_plot_.plot_directory(), true);
  }

  delete plot_frame;
}

Plot::~Plot() {}

} // namespace plotting
} // namespace doofit
<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "Diff.h"

#include "GitRepository.h"

#include "../simple/Parser.h"

namespace FilePersistence {

Diff::Diff(){}

Diff::Diff(QList<GenericNode*>& nodesA, std::shared_ptr<GenericTree> treeA,
			  QList<GenericNode*>& nodesB, std::shared_ptr<GenericTree> treeB,
			  const GitRepository*)
{
	treeA_ = treeA;
	treeB_ = treeB;

	IdToGenericNodeHash nodesAHash;

	for (auto node : nodesA)
		nodesAHash.insertMulti(node->id(), node);

	IdToGenericNodeHash nodesBHash;
	for (auto node : nodesB)
		nodesBHash.insertMulti(node->id(), node);

	filterPersistenceUnits(nodesAHash);
	filterPersistenceUnits(nodesBHash);

	computeChanges(nodesAHash, nodesBHash);
	computeStructChanges();
}

IdToChangeDescriptionHash Diff::changes(ChangeType type) const
{
	IdToChangeDescriptionHash changesOfType;
	for (auto change : changeDescriptions_.values())
		if (change->type() == type)
			changesOfType.insert(change->nodeId(), change);
	return changesOfType;
}

IdToChangeDescriptionHash Diff::changes(ChangeType type, ChangeDescription::UpdateFlags flags) const
{
	IdToChangeDescriptionHash changesOfType;
	for (auto change : changeDescriptions_.values())
		if (change->type() == type && change->hasFlags(flags))
			changesOfType.insert(change->nodeId(), change);
	return changesOfType;
}

// Private methods
void Diff::computeChanges(IdToGenericNodeHash& nodesA, IdToGenericNodeHash& nodesB)
{
	QSet<Model::NodeIdType> onlyInNodesB = QSet<Model::NodeIdType>::fromList(nodesB.keys());
	IdToGenericNodeHash::iterator iter;
	for (auto nodeA : nodesA.values())
	{
		iter = nodesB.find(nodeA->id());
		if (iter == nodesB.end())
		{
			// no such id in nodesB
			auto change = std::make_shared<ChangeDescription>(nodeA, nullptr);
			changeDescriptions_.insert(nodeA->id(), change);
		}
		else
		{
			// found id in nodesB
			auto change = std::make_shared<ChangeDescription>(nodeA, iter.value());
			changeDescriptions_.insert(nodeA->id(), change);
			onlyInNodesB.remove(iter.key());
		}
	}
	/* Intermediate state 2
	 * See report for details.
	 * TODO add link to report
	 */
	for (auto id : onlyInNodesB)
	{
		iter = nodesB.find(id);
		auto change = std::make_shared<ChangeDescription>(nullptr, iter.value());
		changeDescriptions_.insert(id, change);
	}
	for (auto change : changeDescriptions_.values())
		if (change->isFake())
			changeDescriptions_.remove(change->nodeId());
}

void Diff::computeStructChanges()
{
	for (auto change : changeDescriptions_.values())
	{
		if (change->type() == ChangeType::Insertion || change->type() == ChangeType::Move)
			setStructureFlagForId(change->nodeB()->parentId(), change);
		if (change->type() == ChangeType::Deletion || change->type() == ChangeType::Move
			 || change->hasFlags(ChangeDescription::Label))
			setStructureFlagForId(change->nodeA()->parentId(), change);
	}
}

void Diff::setStructureFlagForId(Model::NodeIdType id, std::shared_ptr<ChangeDescription> causingChange)
{
	if (!changeDescriptions_.contains(id))
	{
		auto change = ChangeDescription::newStructChange(id, causingChange, treeA_, treeB_);
		changeDescriptions_.insert(id, change);
		change->setStructureChangeFlag(true);
	}
	else
		changeDescriptions_.value(id).get()->setStructureChangeFlag(true);

	Q_ASSERT(changeDescriptions_.find(id).value()->hasFlags(ChangeDescription::Structure));
	Q_ASSERT(changeDescriptions_.value(id)->debugHasNodes());
}

void Diff::filterPersistenceUnits(IdToGenericNodeHash& nodes)
{
	for (auto node : nodes.values())
		if (node->type() == GenericNode::PERSISTENT_UNIT_TYPE)
			nodes.remove(node->id(), node);
}

}
<commit_msg>remove comment<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "Diff.h"

#include "GitRepository.h"

#include "../simple/Parser.h"

namespace FilePersistence {

Diff::Diff(){}

Diff::Diff(QList<GenericNode*>& nodesA, std::shared_ptr<GenericTree> treeA,
			  QList<GenericNode*>& nodesB, std::shared_ptr<GenericTree> treeB,
			  const GitRepository*)
{
	treeA_ = treeA;
	treeB_ = treeB;

	IdToGenericNodeHash nodesAHash;

	for (auto node : nodesA)
		nodesAHash.insertMulti(node->id(), node);

	IdToGenericNodeHash nodesBHash;
	for (auto node : nodesB)
		nodesBHash.insertMulti(node->id(), node);

	filterPersistenceUnits(nodesAHash);
	filterPersistenceUnits(nodesBHash);

	computeChanges(nodesAHash, nodesBHash);
	computeStructChanges();
}

IdToChangeDescriptionHash Diff::changes(ChangeType type) const
{
	IdToChangeDescriptionHash changesOfType;
	for (auto change : changeDescriptions_.values())
		if (change->type() == type)
			changesOfType.insert(change->nodeId(), change);
	return changesOfType;
}

IdToChangeDescriptionHash Diff::changes(ChangeType type, ChangeDescription::UpdateFlags flags) const
{
	IdToChangeDescriptionHash changesOfType;
	for (auto change : changeDescriptions_.values())
		if (change->type() == type && change->hasFlags(flags))
			changesOfType.insert(change->nodeId(), change);
	return changesOfType;
}

void Diff::computeChanges(IdToGenericNodeHash& nodesA, IdToGenericNodeHash& nodesB)
{
	QSet<Model::NodeIdType> onlyInNodesB = QSet<Model::NodeIdType>::fromList(nodesB.keys());
	IdToGenericNodeHash::iterator iter;
	for (auto nodeA : nodesA.values())
	{
		iter = nodesB.find(nodeA->id());
		if (iter == nodesB.end())
		{
			// no such id in nodesB
			auto change = std::make_shared<ChangeDescription>(nodeA, nullptr);
			changeDescriptions_.insert(nodeA->id(), change);
		}
		else
		{
			// found id in nodesB
			auto change = std::make_shared<ChangeDescription>(nodeA, iter.value());
			changeDescriptions_.insert(nodeA->id(), change);
			onlyInNodesB.remove(iter.key());
		}
	}
	/* Intermediate state 2
	 * See report for details.
	 * TODO add link to report
	 */
	for (auto id : onlyInNodesB)
	{
		iter = nodesB.find(id);
		auto change = std::make_shared<ChangeDescription>(nullptr, iter.value());
		changeDescriptions_.insert(id, change);
	}
	for (auto change : changeDescriptions_.values())
		if (change->isFake())
			changeDescriptions_.remove(change->nodeId());
}

void Diff::computeStructChanges()
{
	for (auto change : changeDescriptions_.values())
	{
		if (change->type() == ChangeType::Insertion || change->type() == ChangeType::Move)
			setStructureFlagForId(change->nodeB()->parentId(), change);
		if (change->type() == ChangeType::Deletion || change->type() == ChangeType::Move
			 || change->hasFlags(ChangeDescription::Label))
			setStructureFlagForId(change->nodeA()->parentId(), change);
	}
}

void Diff::setStructureFlagForId(Model::NodeIdType id, std::shared_ptr<ChangeDescription> causingChange)
{
	if (!changeDescriptions_.contains(id))
	{
		auto change = ChangeDescription::newStructChange(id, causingChange, treeA_, treeB_);
		changeDescriptions_.insert(id, change);
		change->setStructureChangeFlag(true);
	}
	else
		changeDescriptions_.value(id).get()->setStructureChangeFlag(true);

	Q_ASSERT(changeDescriptions_.find(id).value()->hasFlags(ChangeDescription::Structure));
	Q_ASSERT(changeDescriptions_.value(id)->debugHasNodes());
}

void Diff::filterPersistenceUnits(IdToGenericNodeHash& nodes)
{
	for (auto node : nodes.values())
		if (node->type() == GenericNode::PERSISTENT_UNIT_TYPE)
			nodes.remove(node->id(), node);
}

}
<|endoftext|>


<commit_before>
/**************************************************************************
 * Copyright(c) 2006, ALICE Experiment at CERN, All rights reserved.      *
 *                                                                        *
 * Author: Per Thomas Hille for the ALICE HLT Project.                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include "AliHLTPHOSRawAnalyzerPeakFinder.h"
#include <iostream>

using std::cout;
using std::endl;

ClassImp(AliHLTPHOSRawAnalyzerPeakFinder)

AliHLTPHOSRawAnalyzerPeakFinder::AliHLTPHOSRawAnalyzerPeakFinder(const AliHLTPHOSRawAnalyzerPeakFinder&):AliHLTPHOSRawAnalyzer(),tVector(0), aVector(0)
{

}

/**
 * The AliHLTPHOSPeakfinder class is the class for extracting the basic signal parameters
 * "timing" and "energy" from the PHOS raw data. Physical data will for a given readout channel be
 * a sequense of ADC digitized 10 bit integer values, however for performance reasons all values used in
 * calculation is of type double.
 **/
AliHLTPHOSRawAnalyzerPeakFinder::AliHLTPHOSRawAnalyzerPeakFinder():AliHLTPHOSRawAnalyzer(),tVector(0), aVector(0)
{
  cout <<"PeakFinder:You cannot invoke the Fitter without arguments"<<endl;;
}

AliHLTPHOSRawAnalyzerPeakFinder::~AliHLTPHOSRawAnalyzerPeakFinder()
{

} //end AliHLTPHOSRawAnalyzerPeakFinder

void
AliHLTPHOSRawAnalyzerPeakFinder::SetTVector(double *tVec)
{
  tVector = tVec;
}

void
AliHLTPHOSRawAnalyzerPeakFinder::SetAVector(double *aVec)
{
  aVector = aVec;

}

/**
* Extraction of timing and energy using the Peakfinde Algorithm.
* The. The parameters "start" and "length" defines a sub array  of the data array
* that will be used for the the fit. If start+length must not exeed the total length
* of the Data array. "start" must be chosen as close as possible to t0.
* The baseline must also be subtracted.
* The length of "tVector" and "aVector" mus be equal to length.
* "index + length" must not exeed the length of the data array set in the constructor.
* @param start the start index of the subarray of the data array.
* @param length the number of samples to use starting from index
* @param tVector the peakfinder vector for timing
* @param aVector the peakfinder vector for amplitude (energy)
**/
void
AliHLTPHOSRawAnalyzerPeakFinder::Evaluate(int start, int length)
{
  fDTof = 0;
  fDAmpl = 0;

  if(tVector == 0 || aVector == 0)
    {
      printf("\nError: the peakfinder vectors are not specified, aborting !!!\n");
    }
  else
    {

      printf("\nstart = %d, length = %d\n", start, length);
      double tmpTime[1008];

      for(int i=0; i < length; i++)
	{
	  fDAmpl += aVector[i]*fFloatDataPtr[i];
	}

      for(int i=0; i < length; i++)
	{
	  tmpTime[i] = tVector[i]*fFloatDataPtr[i];
	  fDTof = fDTof + tmpTime[i];
	}

      fDTof = fDTof/fDAmpl;
    }
  //thats all
} //end FitPeakFinder

<commit_msg>removed debugg message when calling default constructor<commit_after>
/**************************************************************************
 * Copyright(c) 2006, ALICE Experiment at CERN, All rights reserved.      *
 *                                                                        *
 * Author: Per Thomas Hille for the ALICE HLT Project.                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include "AliHLTPHOSRawAnalyzerPeakFinder.h"
#include <iostream>

using std::cout;
using std::endl;

ClassImp(AliHLTPHOSRawAnalyzerPeakFinder)

AliHLTPHOSRawAnalyzerPeakFinder::AliHLTPHOSRawAnalyzerPeakFinder(const AliHLTPHOSRawAnalyzerPeakFinder&):AliHLTPHOSRawAnalyzer(),tVector(0), aVector(0)
{

}

/**
 * The AliHLTPHOSPeakfinder class is the class for extracting the basic signal parameters
 * "timing" and "energy" from the PHOS raw data. Physical data will for a given readout channel be
 * a sequense of ADC digitized 10 bit integer values, however for performance reasons all values used in
 * calculation is of type double.
 **/
AliHLTPHOSRawAnalyzerPeakFinder::AliHLTPHOSRawAnalyzerPeakFinder():AliHLTPHOSRawAnalyzer(),tVector(0), aVector(0)
{
  //  cout <<"PeakFinder:You cannot invoke the Fitter without arguments"<<endl;;
}

AliHLTPHOSRawAnalyzerPeakFinder::~AliHLTPHOSRawAnalyzerPeakFinder()
{

} //end AliHLTPHOSRawAnalyzerPeakFinder

void
AliHLTPHOSRawAnalyzerPeakFinder::SetTVector(double *tVec)
{
  tVector = tVec;
}

void
AliHLTPHOSRawAnalyzerPeakFinder::SetAVector(double *aVec)
{
  aVector = aVec;

}

/**
* Extraction of timing and energy using the Peakfinde Algorithm.
* The. The parameters "start" and "length" defines a sub array  of the data array
* that will be used for the the fit. If start+length must not exeed the total length
* of the Data array. "start" must be chosen as close as possible to t0.
* The baseline must also be subtracted.
* The length of "tVector" and "aVector" mus be equal to length.
* "index + length" must not exeed the length of the data array set in the constructor.
* @param start the start index of the subarray of the data array.
* @param length the number of samples to use starting from index
* @param tVector the peakfinder vector for timing
* @param aVector the peakfinder vector for amplitude (energy)
**/
void
AliHLTPHOSRawAnalyzerPeakFinder::Evaluate(int start, int length)
{
  printf("\n AliHLTPHOSRawAnalyzerPeakFinder::Evaluat from index %d to %d\n", start, start + length);
  fDTof = 0;
  fDAmpl = 0;

  if(tVector == 0 || aVector == 0)
    {
      printf("\nError: the peakfinder vectors are not specified, aborting !!!\n");
    }
  else
    {

      printf("\nstart = %d, length = %d\n", start, length);
      double tmpTime[1008];

      for(int i=0; i < length; i++)
	{
	  fDAmpl += aVector[i]*fFloatDataPtr[i];
	}

      for(int i=0; i < length; i++)
	{
	  tmpTime[i] = tVector[i]*fFloatDataPtr[i];
	  fDTof = fDTof + tmpTime[i];
	}

      fDTof = fDTof/fDAmpl;
    }

  //thats all
} //end FitPeakFinder

<|endoftext|>