<commit_before>/* medViewerToolBoxTime.h ---
 *
 * Author: Fatih Arslan and Nicolas Toussaint

 * Change log:
 *
 */

#include "medViewerToolBoxTime.h"

#include <iomanip>
#include <cmath>
#include <sstream>

#include <QListWidget>
#include <QList>
#include <QMouseEvent>

#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkLog.h>

#include <med4DAbstractViewInteractor.h>
#include <medToolBoxTab.h>
#include <medButton.h>

class medViewerToolBoxTimePrivate
{
public:
    QSlider     *timeSlider;
    medButton *playSequencesButton;
    medButton *nextFrameButton;
    medButton *previousFrameButton;
    medButton *stopButton;

    QList <QAction*> actionlist;
    QList<dtkAbstractView*> views;
    QList<med4DAbstractViewInteractor*> interactors;
    QTimeLine *timeLine;
    QSpinBox *spinBox;
    QLabel *labelmin;
    QLabel *labelmax;
    QLabel *labelcurr;
    QLabel *labelspeed;
    double minTime;
    double minTimeStep;
    double maxTime;

    QPixmap playIcon;
};

medViewerToolBoxTime::medViewerToolBoxTime(QWidget *parent) : medToolBox(parent), d(new medViewerToolBoxTimePrivate)
{
    QWidget *box = new QWidget (this);
    d->labelmin = new QLabel(this);
    d->labelmax = new QLabel(this);
    d->labelcurr = new QLabel(this);
    d->labelspeed = new QLabel(this);
    d->labelspeed->setText("Speed %: ");
    d->timeSlider = new QSlider (Qt::Horizontal, this);
    d->timeSlider->setRange (0, 100);
    d->timeSlider->setValue (0);
    d->timeSlider->setTracking( false );
    d->timeSlider->setToolTip(tr("Follow The Sequence"));

    QStringList validDataTypes;
    validDataTypes << "itkDataImageChar4"
            << "itkDataImageUChar4"
            << "itkDataImageShort4"
            << "itkDataImageUShort4"
            << "itkDataImageInt4"
            << "itkDataImageUInt4"
            << "itkDataImageLong4"
            << "itkDataImageULong4"
            << "itkDataImageFloat4"
            << "itkDataImageDouble4";

    setValidDataTypes(validDataTypes);

    d->playIcon = QPixmap(":/icons/play.png");

    d->playSequencesButton = new medButton(this,d->playIcon,
                                           tr("Play Sequence"));

    d->nextFrameButton = new medButton(this,":/icons/forward.png",
                                       tr("Next Frame"));

    d->previousFrameButton = new medButton(this,":/icons/backward.png",
                                               tr("Previous Frame"));

    d->stopButton = new medButton(this,":/icons/stop.png",
                                  tr("Stop Sequence"));

    d->timeLine = new QTimeLine(1000, this);
    d->timeLine->setLoopCount(0);
    d->timeLine->setCurveShape (QTimeLine::LinearCurve);

    d->spinBox = new QSpinBox(this);
    d->spinBox->setRange(1,5000);
    d->spinBox->setSingleStep(10);
    d->spinBox->setValue(100);
    d->spinBox->setToolTip(tr("Control the display speed"));

    connect(d->timeLine, SIGNAL(frameChanged(int)), d->timeSlider, SLOT(setValue(int)));

    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget( d->previousFrameButton,1,Qt::AlignHCenter);
    buttonLayout->addWidget (d->playSequencesButton,1,Qt::AlignHCenter);
    buttonLayout->addWidget( d->nextFrameButton,1,Qt::AlignHCenter);

    buttonLayout->addWidget( d->stopButton,1,Qt::AlignHCenter);

    QHBoxLayout *labelLayout = new QHBoxLayout();
    labelLayout->addWidget( d->labelmin);
    labelLayout->addStretch();
    labelLayout->addWidget( d->labelcurr);
    labelLayout->addStretch();
    labelLayout->addWidget( d->labelmax);

    QHBoxLayout *topLayout = new QHBoxLayout();

    topLayout->addStretch();
    topLayout->addWidget(d->labelspeed);
    topLayout->addWidget(d->spinBox);

    QVBoxLayout* boxlayout = new QVBoxLayout ();
    boxlayout->addLayout(topLayout);
    boxlayout->addLayout( buttonLayout );
    boxlayout->addWidget (d->timeSlider);
    boxlayout->addLayout(labelLayout);

    d->actionlist.insert(0,new QAction("1",this));
    d->actionlist.insert(1,new QAction("5",this));
    d->actionlist.insert(2,new QAction("10",this));
    d->actionlist.insert(3,new QAction("25",this));
    d->actionlist.insert(4,new QAction("50",this));

    connect(d->timeSlider, SIGNAL(sliderMoved(int)), this, SLOT(onTimeChanged(int)));
    connect(d->timeSlider, SIGNAL(valueChanged(int)), this, SLOT(onTimeChanged(int)));
    connect(d->playSequencesButton, SIGNAL(triggered()), this, SLOT(onPlaySequences()));

    connect(d->nextFrameButton, SIGNAL(triggered()), this, SLOT(onNextFrame()));
    connect(d->previousFrameButton, SIGNAL(triggered()), this, SLOT(onPreviousFrame()));
    connect(d->spinBox, SIGNAL(valueChanged(int)),this, SLOT(onSpinBoxChanged(int)));
    connect(d->stopButton, SIGNAL(triggered()),this, SLOT(onStopButton()));

    this->setTitle(tr("Time Management"));
    box->setLayout (boxlayout);
    this->addWidget (box);

    d->minTime = 0.0;
    d->minTimeStep = 1.0;
    d->maxTime = 0.0;

    this->isViewAdded = false;

    this->hide();
}

medViewerToolBoxTime::~medViewerToolBoxTime(void)
{
    delete d;

    d = NULL;
}

void medViewerToolBoxTime::onViewAdded (dtkAbstractView *view)
{
    if (!view)
        return;

    if (med4DAbstractViewInteractor *interactor = dynamic_cast<med4DAbstractViewInteractor*>(view->interactor ("v3dView4DInteractor")))
    {
        if (!d->views.contains (view))
            d->views.append (view);
        if (!d->interactors.contains (interactor))
            d->interactors.append (interactor);
        connect (view, SIGNAL ( dataAdded(dtkAbstractData*)),   this, SLOT (onDataAdded (dtkAbstractData*)));
    }

    this->updateRange();
    this->isViewAdded = true;
}

void medViewerToolBoxTime::onDataAdded (dtkAbstractData *data)
{
    if (!data)
        return;

    this->updateRange();
}

void medViewerToolBoxTime::onViewRemoved (dtkAbstractView *view)
{
    d->timeLine->stop();
    d->timeSlider->setValue(0);

    if (!view)
        return;

    if (med4DAbstractViewInteractor *interactor = dynamic_cast<med4DAbstractViewInteractor*>(view->interactor ("v3dView4DInteractor")))
    {
        d->views.removeOne (view);
        d->interactors.removeOne (interactor);
    }

    this->updateRange();
    this->isViewAdded = false;
}

void medViewerToolBoxTime::AddInteractor (med4DAbstractViewInteractor* interactor)
{
    d->interactors.removeOne (interactor);
    d->interactors.append (interactor);
}
void medViewerToolBoxTime::RemoveInteractor (med4DAbstractViewInteractor* interactor)
{
    d->interactors.removeOne (interactor);
}

void medViewerToolBoxTime::update(dtkAbstractView *view)
{
    //JGG qDebug()<<"updating time tb";
    medToolBox::update(view);
}

void medViewerToolBoxTime::onPlaySequences ()
{
    if ( this->isViewAdded)
    {
        this->updateRange();
        d->timeLine->setDuration((d->maxTime + d->minTimeStep)*(1000/(d->spinBox->value()/100.0)));
        if(d->timeLine->state() == QTimeLine::NotRunning)
        {
            d->timeLine->start();
            d->playSequencesButton->setIcon (QPixmap(":/icons/pause.png"));
            d->playSequencesButton->setToolTip( tr("Pause Sequence"));
        }
        else if(d->timeLine->state() == QTimeLine::Paused )
        {
            d->timeLine->resume();
            d->playSequencesButton->setIcon (QPixmap(":/icons/pause.png"));
            d->playSequencesButton->setToolTip( tr("Pause Sequence"));
        }
        else if(d->timeLine->state() == QTimeLine::Running)
        {
            d->timeLine->setPaused(true);
            d->playSequencesButton->setIcon (QPixmap(":/icons/play.png"));
            d->playSequencesButton->setToolTip( tr("Play Sequence"));
        }
    }
}

void medViewerToolBoxTime::onStopButton ()
{
    if (d->timeLine->state() == QTimeLine::Running)
    {
        d->playSequencesButton->setIcon (QPixmap(":/icons/play.png"));
        d->playSequencesButton->setToolTip( tr("Play Sequence"));
    }
    d->timeLine->stop();
    d->timeSlider->setValue(0);
}

void medViewerToolBoxTime::onNextFrame ()
{
    if ( this->isViewAdded)
	d->timeSlider->setValue(d->timeSlider->value()+1);
}
void medViewerToolBoxTime::onPreviousFrame ()
{
    if ( this->isViewAdded)
	d->timeSlider->setValue(d->timeSlider->value()-1);
}

void medViewerToolBoxTime::onTimeChanged (int val)
{
    double time = this->getTimeFromSliderValue (val);
    for (int i=0; i<d->interactors.size(); i++)
    {
        d->interactors[i]->setCurrentTime (time);
    }

    d->labelcurr->setText( DoubleToQString(( time ) / (d->spinBox->value()/100.0)) + QString(" sec") );
}

void medViewerToolBoxTime::onSpinBoxChanged(int time)
{
    this->updateRange();

    d->timeLine->setDuration((d->maxTime + d->minTimeStep)*(1000/(time/100.0)));
}

double medViewerToolBoxTime::getTimeFromSliderValue (int s)
{
    double value = d->minTime + (double)(s) * (d->minTimeStep);
    return value;
}

unsigned int medViewerToolBoxTime::getSliderValueFromTime (double t)
{
    unsigned int value = std::ceil ((t - d->minTime) / (d->minTimeStep));
    return value;
}

void medViewerToolBoxTime::updateRange (void)
{
    if (!d->interactors.size())
        return;
    double mintime = 3000;
    double maxtime = -3000;
    double mintimestep = 3000;

    for (int i=0; i<d->interactors.size(); i++)
    {
        double range[2]={0,0};
        d->interactors[i]->sequencesRange (range);
        mintimestep = std::min (mintimestep, d->interactors[i]->sequencesMinTimeStep ());
        mintime = std::min (mintime, range[0]);
        maxtime = std::max (maxtime, range[1]);
    }

    unsigned int numberofsteps = std::ceil ((maxtime - mintime) / (mintimestep) + 1.0);

    d->timeSlider->setRange (0, numberofsteps - 1);
    d->timeLine->setFrameRange(d->timeSlider->minimum(), d->timeSlider->maximum() );

    d->minTime = mintime;
    d->minTimeStep = mintimestep;
    d->maxTime = maxtime;

    d->timeLine->setDuration((maxtime+mintimestep)*1000);

    d->labelmin->setText( DoubleToQString(( mintime ) / (d->spinBox->value()/100.0)) + QString(" sec"));
    d->labelmax->setText( DoubleToQString(( maxtime ) / (d->spinBox->value()/100.0)) + QString(" sec"));
}

QString medViewerToolBoxTime::DoubleToQString (double val)
{
    std::ostringstream strs;
    strs <<  std::fixed << std::setprecision(2)<< val;
    std::string str = strs.str();
    return QString(str.c_str());
}

void medViewerToolBoxTime::mouseReleaseEvent ( QMouseEvent *  mouseEvent)
{
    if(mouseEvent->button() == Qt::RightButton)
    {
        QMenu *menu = new QMenu(this);

        QAction *actionNotify = new QAction(tr("Set Speed Increment : "),
                                            this);
        actionNotify->setDisabled(true);

        menu->addAction(actionNotify);
        for (int i = 0; i < d->actionlist.size() ; i++)
        {
            connect(d->actionlist[i], SIGNAL(triggered()), this, SLOT(onStepIncreased()));
            menu->addAction(d->actionlist[i]);

        }

        menu->exec(mouseEvent->globalPos());
    }
}
void medViewerToolBoxTime::onStepIncreased()
{
    if (QObject::sender() == d->actionlist[0])
        d->spinBox->setSingleStep(1);
    else if (QObject::sender() == d->actionlist[1])
        d->spinBox->setSingleStep(5);
    else if (QObject::sender() == d->actionlist[2])
        d->spinBox->setSingleStep(10);
    else if (QObject::sender() == d->actionlist[3])
        d->spinBox->setSingleStep(25);
    else if (QObject::sender() == d->actionlist[4])
        d->spinBox->setSingleStep(50);
}

void medViewerToolBoxTime::clear()
{
    d->minTime = 0.0;
    d->minTimeStep = 1.0;
    d->maxTime = 0.0;

    d->interactors.clear();
    d->views.clear();
}
<commit_msg>Smart pointing what should be smart pointed<commit_after>/* medViewerToolBoxTime.h ---
 *
 * Author: Fatih Arslan and Nicolas Toussaint

 * Change log:
 *
 */

#include "medViewerToolBoxTime.h"

#include <iomanip>
#include <cmath>
#include <sstream>

#include <QListWidget>
#include <QList>
#include <QMouseEvent>

#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkLog.h>
#include <dtkCore/dtkSmartPointer.h>

#include <med4DAbstractViewInteractor.h>
#include <medToolBoxTab.h>
#include <medButton.h>

class medViewerToolBoxTimePrivate
{
public:
    QSlider     *timeSlider;
    medButton *playSequencesButton;
    medButton *nextFrameButton;
    medButton *previousFrameButton;
    medButton *stopButton;

    QList <QAction*> actionlist;
    QList< dtkSmartPointer<dtkAbstractView> > views;
    QList<med4DAbstractViewInteractor*> interactors;
    QTimeLine *timeLine;
    QSpinBox *spinBox;
    QLabel *labelmin;
    QLabel *labelmax;
    QLabel *labelcurr;
    QLabel *labelspeed;
    double minTime;
    double minTimeStep;
    double maxTime;

    QPixmap playIcon;
};

medViewerToolBoxTime::medViewerToolBoxTime(QWidget *parent) : medToolBox(parent), d(new medViewerToolBoxTimePrivate)
{
    QWidget *box = new QWidget (this);
    d->labelmin = new QLabel(this);
    d->labelmax = new QLabel(this);
    d->labelcurr = new QLabel(this);
    d->labelspeed = new QLabel(this);
    d->labelspeed->setText("Speed %: ");
    d->timeSlider = new QSlider (Qt::Horizontal, this);
    d->timeSlider->setRange (0, 100);
    d->timeSlider->setValue (0);
    d->timeSlider->setTracking( false );
    d->timeSlider->setToolTip(tr("Follow The Sequence"));

    QStringList validDataTypes;
    validDataTypes << "itkDataImageChar4"
            << "itkDataImageUChar4"
            << "itkDataImageShort4"
            << "itkDataImageUShort4"
            << "itkDataImageInt4"
            << "itkDataImageUInt4"
            << "itkDataImageLong4"
            << "itkDataImageULong4"
            << "itkDataImageFloat4"
            << "itkDataImageDouble4";

    setValidDataTypes(validDataTypes);

    d->playIcon = QPixmap(":/icons/play.png");

    d->playSequencesButton = new medButton(this,d->playIcon,
                                           tr("Play Sequence"));

    d->nextFrameButton = new medButton(this,":/icons/forward.png",
                                       tr("Next Frame"));

    d->previousFrameButton = new medButton(this,":/icons/backward.png",
                                               tr("Previous Frame"));

    d->stopButton = new medButton(this,":/icons/stop.png",
                                  tr("Stop Sequence"));

    d->timeLine = new QTimeLine(1000, this);
    d->timeLine->setLoopCount(0);
    d->timeLine->setCurveShape (QTimeLine::LinearCurve);

    d->spinBox = new QSpinBox(this);
    d->spinBox->setRange(1,5000);
    d->spinBox->setSingleStep(10);
    d->spinBox->setValue(100);
    d->spinBox->setToolTip(tr("Control the display speed"));

    connect(d->timeLine, SIGNAL(frameChanged(int)), d->timeSlider, SLOT(setValue(int)));

    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget( d->previousFrameButton,1,Qt::AlignHCenter);
    buttonLayout->addWidget (d->playSequencesButton,1,Qt::AlignHCenter);
    buttonLayout->addWidget( d->nextFrameButton,1,Qt::AlignHCenter);

    buttonLayout->addWidget( d->stopButton,1,Qt::AlignHCenter);

    QHBoxLayout *labelLayout = new QHBoxLayout();
    labelLayout->addWidget( d->labelmin);
    labelLayout->addStretch();
    labelLayout->addWidget( d->labelcurr);
    labelLayout->addStretch();
    labelLayout->addWidget( d->labelmax);

    QHBoxLayout *topLayout = new QHBoxLayout();

    topLayout->addStretch();
    topLayout->addWidget(d->labelspeed);
    topLayout->addWidget(d->spinBox);

    QVBoxLayout* boxlayout = new QVBoxLayout ();
    boxlayout->addLayout(topLayout);
    boxlayout->addLayout( buttonLayout );
    boxlayout->addWidget (d->timeSlider);
    boxlayout->addLayout(labelLayout);

    d->actionlist.insert(0,new QAction("1",this));
    d->actionlist.insert(1,new QAction("5",this));
    d->actionlist.insert(2,new QAction("10",this));
    d->actionlist.insert(3,new QAction("25",this));
    d->actionlist.insert(4,new QAction("50",this));

    connect(d->timeSlider, SIGNAL(sliderMoved(int)), this, SLOT(onTimeChanged(int)));
    connect(d->timeSlider, SIGNAL(valueChanged(int)), this, SLOT(onTimeChanged(int)));
    connect(d->playSequencesButton, SIGNAL(triggered()), this, SLOT(onPlaySequences()));

    connect(d->nextFrameButton, SIGNAL(triggered()), this, SLOT(onNextFrame()));
    connect(d->previousFrameButton, SIGNAL(triggered()), this, SLOT(onPreviousFrame()));
    connect(d->spinBox, SIGNAL(valueChanged(int)),this, SLOT(onSpinBoxChanged(int)));
    connect(d->stopButton, SIGNAL(triggered()),this, SLOT(onStopButton()));

    this->setTitle(tr("Time Management"));
    box->setLayout (boxlayout);
    this->addWidget (box);

    d->minTime = 0.0;
    d->minTimeStep = 1.0;
    d->maxTime = 0.0;

    this->isViewAdded = false;

    this->hide();
}

medViewerToolBoxTime::~medViewerToolBoxTime(void)
{
    delete d;

    d = NULL;
}

void medViewerToolBoxTime::onViewAdded (dtkAbstractView *view)
{
    if (!view)
        return;

    if (med4DAbstractViewInteractor *interactor = dynamic_cast<med4DAbstractViewInteractor*>(view->interactor ("v3dView4DInteractor")))
    {
        if (!d->views.contains (view))
            d->views.append (view);
        if (!d->interactors.contains (interactor))
            d->interactors.append (interactor);
        connect (view, SIGNAL ( dataAdded(dtkAbstractData*)),   this, SLOT (onDataAdded (dtkAbstractData*)));
    }

    this->updateRange();
    this->isViewAdded = true;
}

void medViewerToolBoxTime::onDataAdded (dtkAbstractData *data)
{
    if (!data)
        return;

    this->updateRange();
}

void medViewerToolBoxTime::onViewRemoved (dtkAbstractView *view)
{
    d->timeLine->stop();
    d->timeSlider->setValue(0);

    if (!view)
        return;

    if (med4DAbstractViewInteractor *interactor = dynamic_cast<med4DAbstractViewInteractor*>(view->interactor ("v3dView4DInteractor")))
    {
        d->views.removeOne (view);
        d->interactors.removeOne (interactor);
    }

    this->updateRange();
    this->isViewAdded = false;
}

void medViewerToolBoxTime::AddInteractor (med4DAbstractViewInteractor* interactor)
{
    d->interactors.removeOne (interactor);
    d->interactors.append (interactor);
}
void medViewerToolBoxTime::RemoveInteractor (med4DAbstractViewInteractor* interactor)
{
    d->interactors.removeOne (interactor);
}

void medViewerToolBoxTime::update(dtkAbstractView *view)
{
    //JGG qDebug()<<"updating time tb";
    medToolBox::update(view);
}

void medViewerToolBoxTime::onPlaySequences ()
{
    if ( this->isViewAdded)
    {
        this->updateRange();
        d->timeLine->setDuration((d->maxTime + d->minTimeStep)*(1000/(d->spinBox->value()/100.0)));
        if(d->timeLine->state() == QTimeLine::NotRunning)
        {
            d->timeLine->start();
            d->playSequencesButton->setIcon (QPixmap(":/icons/pause.png"));
            d->playSequencesButton->setToolTip( tr("Pause Sequence"));
        }
        else if(d->timeLine->state() == QTimeLine::Paused )
        {
            d->timeLine->resume();
            d->playSequencesButton->setIcon (QPixmap(":/icons/pause.png"));
            d->playSequencesButton->setToolTip( tr("Pause Sequence"));
        }
        else if(d->timeLine->state() == QTimeLine::Running)
        {
            d->timeLine->setPaused(true);
            d->playSequencesButton->setIcon (QPixmap(":/icons/play.png"));
            d->playSequencesButton->setToolTip( tr("Play Sequence"));
        }
    }
}

void medViewerToolBoxTime::onStopButton ()
{
    if (d->timeLine->state() == QTimeLine::Running)
    {
        d->playSequencesButton->setIcon (QPixmap(":/icons/play.png"));
        d->playSequencesButton->setToolTip( tr("Play Sequence"));
    }
    d->timeLine->stop();
    d->timeSlider->setValue(0);
}

void medViewerToolBoxTime::onNextFrame ()
{
    if ( this->isViewAdded)
	d->timeSlider->setValue(d->timeSlider->value()+1);
}
void medViewerToolBoxTime::onPreviousFrame ()
{
    if ( this->isViewAdded)
	d->timeSlider->setValue(d->timeSlider->value()-1);
}

void medViewerToolBoxTime::onTimeChanged (int val)
{
    double time = this->getTimeFromSliderValue (val);
    for (int i=0; i<d->interactors.size(); i++)
    {
        d->interactors[i]->setCurrentTime (time);
    }

    d->labelcurr->setText( DoubleToQString(( time ) / (d->spinBox->value()/100.0)) + QString(" sec") );
}

void medViewerToolBoxTime::onSpinBoxChanged(int time)
{
    this->updateRange();

    d->timeLine->setDuration((d->maxTime + d->minTimeStep)*(1000/(time/100.0)));
}

double medViewerToolBoxTime::getTimeFromSliderValue (int s)
{
    double value = d->minTime + (double)(s) * (d->minTimeStep);
    return value;
}

unsigned int medViewerToolBoxTime::getSliderValueFromTime (double t)
{
    unsigned int value = std::ceil ((t - d->minTime) / (d->minTimeStep));
    return value;
}

void medViewerToolBoxTime::updateRange (void)
{
    if (!d->interactors.size())
        return;
    double mintime = 3000;
    double maxtime = -3000;
    double mintimestep = 3000;

    for (int i=0; i<d->interactors.size(); i++)
    {
        double range[2]={0,0};
        d->interactors[i]->sequencesRange (range);
        mintimestep = std::min (mintimestep, d->interactors[i]->sequencesMinTimeStep ());
        mintime = std::min (mintime, range[0]);
        maxtime = std::max (maxtime, range[1]);
    }

    unsigned int numberofsteps = std::ceil ((maxtime - mintime) / (mintimestep) + 1.0);

    d->timeSlider->setRange (0, numberofsteps - 1);
    d->timeLine->setFrameRange(d->timeSlider->minimum(), d->timeSlider->maximum() );

    d->minTime = mintime;
    d->minTimeStep = mintimestep;
    d->maxTime = maxtime;

    d->timeLine->setDuration((maxtime+mintimestep)*1000);

    d->labelmin->setText( DoubleToQString(( mintime ) / (d->spinBox->value()/100.0)) + QString(" sec"));
    d->labelmax->setText( DoubleToQString(( maxtime ) / (d->spinBox->value()/100.0)) + QString(" sec"));
}

QString medViewerToolBoxTime::DoubleToQString (double val)
{
    std::ostringstream strs;
    strs <<  std::fixed << std::setprecision(2)<< val;
    std::string str = strs.str();
    return QString(str.c_str());
}

void medViewerToolBoxTime::mouseReleaseEvent ( QMouseEvent *  mouseEvent)
{
    if(mouseEvent->button() == Qt::RightButton)
    {
        QMenu *menu = new QMenu(this);

        QAction *actionNotify = new QAction(tr("Set Speed Increment : "),
                                            this);
        actionNotify->setDisabled(true);

        menu->addAction(actionNotify);
        for (int i = 0; i < d->actionlist.size() ; i++)
        {
            connect(d->actionlist[i], SIGNAL(triggered()), this, SLOT(onStepIncreased()));
            menu->addAction(d->actionlist[i]);

        }

        menu->exec(mouseEvent->globalPos());
    }
}
void medViewerToolBoxTime::onStepIncreased()
{
    if (QObject::sender() == d->actionlist[0])
        d->spinBox->setSingleStep(1);
    else if (QObject::sender() == d->actionlist[1])
        d->spinBox->setSingleStep(5);
    else if (QObject::sender() == d->actionlist[2])
        d->spinBox->setSingleStep(10);
    else if (QObject::sender() == d->actionlist[3])
        d->spinBox->setSingleStep(25);
    else if (QObject::sender() == d->actionlist[4])
        d->spinBox->setSingleStep(50);
}

void medViewerToolBoxTime::clear()
{
    d->minTime = 0.0;
    d->minTimeStep = 1.0;
    d->maxTime = 0.0;

    d->interactors.clear();
    d->views.clear();
}
<|endoftext|>


<commit_before>// $Id: patch_recovery_error_estimator.C,v 1.21 2007-01-22 23:36:07 roystgnr Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include <algorithm> // for std::fill
#include <cmath>     // for std::sqrt std::pow std::abs

// Local Includes
#include "libmesh_common.h"
#include "patch_recovery_error_estimator.h"
#include "dof_map.h"
#include "fe.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "error_vector.h"
#include "quadrature_gauss.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "patch.h"
#include "quadrature_grid.h"
#include "system.h"
#include "mesh.h"

//-----------------------------------------------------------------
// PatchRecoveryErrorEstimator implementations
std::vector<Real> PatchRecoveryErrorEstimator::specpoly(const unsigned int dim,
							const Order order,
							const Point p,
							const unsigned int matsize)
{
  std::vector<Real> psi;
  psi.reserve(matsize);
  Real x = p(0), y, z;
  if (dim > 1)
    y = p(1);
  if (dim > 2)
    z = p(2);

  // builds psi vector of form 1 x y z x^2 xy xz y^2 yz z^2 etc..
  // I haven't added 1D support here
  for (unsigned int poly_deg=0; poly_deg <= static_cast<unsigned int>(order) ; poly_deg++)
    { // loop over all polynomials of total degreee = poly_deg

      switch (dim)
	{
	  // 3D spectral polynomial basis functions
	case 3:
	  {
	    for (int xexp=poly_deg; xexp >= 0; xexp--) // use an int for xexp since we -- it
	      for (int yexp=poly_deg-xexp; yexp >= 0; yexp--)
                {
                  int zexp = poly_deg - xexp - yexp;
		  psi.push_back(std::pow(x,xexp)*std::pow(y,yexp)*std::pow(z,zexp));
                }
	    break;
	  }

	  // 2D spectral polynomial basis functions
	case 2:
	  {
	    for (int xexp=poly_deg; xexp >= 0; xexp--) // use an int for xexp since we -- it
              {
                int yexp = poly_deg - xexp;
		psi.push_back(std::pow(x,xexp)*std::pow(y,yexp));
              }
	    break;
	  }

	  // 1D spectral polynomial basis functions
	case 1:
	  {
            int xexp = poly_deg;
	    psi.push_back(std::pow(x,xexp));
	    break;
	  }

	default:
	  error();
	}
    }

  return psi;
}

void PatchRecoveryErrorEstimator::estimate_error (const System& system,
						  ErrorVector& error_per_cell,
					          bool)
{
  START_LOG("estimate_error()", "PatchRecoveryErrorEstimator");

  // The current mesh
  const Mesh& mesh = system.get_mesh();

  // The dimensionality of the mesh
  const unsigned int dim = mesh.mesh_dimension();

  // The number of variables in the system
  const unsigned int n_vars = system.n_vars();

  // The DofMap for this system
  const DofMap& dof_map = system.get_dof_map();

  // Resize the error_per_cell vector to be
  // the number of elements, initialize it to 0.
  error_per_cell.resize (mesh.n_elem());
  std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);

  // Check for the use of component_mask
  this->convert_component_mask_to_scale();

  // Check for a valid component_scale
  if (!component_scale.empty())
    if (component_scale.size() != n_vars)
      {
	std::cerr << "ERROR: component_scale is the wrong size:"
		  << std::endl
		  << " component_scale.size()=" << component_scale.size()
		  << std::endl
		  << ", n_vars=" << n_vars
		  << std::endl;
	error();
      }

  //------------------------------------------------------------
  // Iterate over all the active elements in the mesh
  // that live on this processor.
  MeshBase::const_element_iterator       elem_it  = mesh.active_local_elements_begin();
  const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end();

  for (; elem_it != elem_end; ++elem_it)
    {
      // elem is necessarily an active element on the local processor
      const Elem* elem = *elem_it;

      // Build a patch containing the current element
      // and its neighbors on the local processor
      Patch patch;

      // We log the time spent building patches separately
      PAUSE_LOG("estimate_error()", "PatchRecoveryErrorEstimator");

      // Use default patch size and growth strategy
      patch.build_around_element (elem);

      RESTART_LOG("estimate_error()", "PatchRecoveryErrorEstimator");

      //------------------------------------------------------------
      // Process each variable in the system using the current patch
      for (unsigned int var=0; var<n_vars; var++)
	{
	  // Possibly skip this variable
	  if (!component_scale.empty())
	    if (component_scale[var] == 0.0) continue;

	  // The type of finite element to use for this variable
	  const FEType& fe_type = dof_map.variable_type (var);

          const Order element_order  = static_cast<Order>
            (fe_type.order + elem->p_level());

	  // Finite element object for use in this patch
	  AutoPtr<FEBase> fe (FEBase::build (dim, fe_type));

	  // Build an appropriate Gaussian quadrature rule
	  AutoPtr<QBase> qrule (fe_type.default_quadrature_rule(dim));

	  // Tell the finite element about the quadrature rule.
	  fe->attach_quadrature_rule (qrule.get());

	  // Get Jacobian values, etc..
	  const std::vector<Real>&                       JxW     = fe->get_JxW();
	  const std::vector<Point>&                      q_point = fe->get_xyz();
	  const std::vector<std::vector<Real> >&         phi     = fe->get_phi();
	  const std::vector<std::vector<RealGradient> >& dphi    = fe->get_dphi();

	  // global DOF indices
	  std::vector<unsigned int> dof_indices;

	  // Compute the approprite size for the patch projection matrices
	  // and vectors;
	  unsigned int matsize;

          switch (dim)
	    {
	    case 3:
	      {
                matsize = (element_order + 1)*
                          (element_order + 2)*
                          (element_order + 3)/6;
	        break;
              }
	    case 2:
	      {
                matsize = (element_order + 1)*
                          (element_order + 2)/2;
	        break;
              }
	    case 1:
	      {
                matsize = element_order + 1;
	        break;
              }
	    default:
	      error();
	    }

	  DenseMatrix<Number> Kp(matsize,matsize);
	  DenseVector<Number>
	    Fx(matsize), Pu_x_h(matsize),
	    Fy(matsize), Pu_y_h(matsize),
	    Fz(matsize), Pu_z_h(matsize);

	  //------------------------------------------------------
	  // Loop over each element in the patch and compute their
	  // contribution to the patch gradient projection.
	  Patch::const_iterator        patch_it  = patch.begin();
	  const Patch::const_iterator  patch_end = patch.end();

	  for (; patch_it != patch_end; ++patch_it)
	    {
	      // The pth element in the patch
	      const Elem* e_p = *patch_it;

	      // Reinitialize the finite element data for this element
	      fe->reinit (e_p);

	      // Get the global DOF indices for the current variable
	      // in the current element
	      dof_map.dof_indices (e_p, dof_indices, var);
	      assert (dof_indices.size() == phi.size());

	      const unsigned int n_dofs = dof_indices.size();
	      const unsigned int n_qp   = qrule->n_points();

	      // Compute the projection components from this cell.
	      // \int_{Omega_e} \psi_i \psi_j = \int_{Omega_e} du_h/dx_k \psi_i
	      for (unsigned int qp=0; qp<n_qp; qp++)
		{
		  // Compute the gradient on the current patch element
		  // at the quadrature point
		  Gradient grad_u_h;

		  for (unsigned int i=0; i<n_dofs; i++)
		    // grad_u_h += dphi[i][qp]*system.current_solution(dof_indices[i]);
		    grad_u_h.add_scaled (dphi[i][qp],
					 system.current_solution(dof_indices[i]));

		  // Construct the shape function values for the patch projection
		  std::vector<Real> psi(specpoly(dim, element_order, q_point[qp], matsize));

		  // Patch matrix contribution
		  for (unsigned int i=0; i<Kp.m(); i++)
		    for (unsigned int j=0; j<Kp.n(); j++)
		      Kp(i,j) += JxW[qp]*psi[i]*psi[j];

		  // Patch RHS contributions
		  for (unsigned int i=0; i<psi.size(); i++)
		    {
		      Fx(i) += JxW[qp]*grad_u_h(0)*psi[i];
		      Fy(i) += JxW[qp]*grad_u_h(1)*psi[i];
		      Fz(i) += JxW[qp]*grad_u_h(2)*psi[i];
		    }
		} // end quadrature loop
	    } // end patch loop

	  //--------------------------------------------------
	  // Now we have fully assembled the projection system
	  // for this patch.  Project the gradient components.
	  // MAY NEED TO USE PARTIAL PIVOTING!
	  Kp.lu_solve (Fx, Pu_x_h);
	  Kp.lu_solve (Fy, Pu_y_h);
	  Kp.lu_solve (Fz, Pu_z_h);

	  //--------------------------------------------------
	  // Finally, estimate the error in the current variable
	  // for the current element by computing ||Pgrad_u_h - grad_u_h||

	  fe->reinit(elem);
	  //reinitialize element

	  dof_map.dof_indices (elem, dof_indices, var);
	  const unsigned int n_dofs = dof_indices.size();

	  // For linear elments, grad is a constant, so we need to compute
	  // grad u_h once on the element.  Also as G_H u_h - gradu_h is linear
	  // on an element, it assumes its maximum at a vertex of the element
	  Real error = 0;
	  // we approximate the max norm by sampling over a set of points
	  // in future we may add specialized routines for specific cases
	  // or use some optimization package
	  const Order qorder = element_order;

	  // build a "fake" quadrature rule for the element
	  QGrid samprule (dim, qorder);
	  fe->attach_quadrature_rule (&samprule);
	  fe->reinit(elem);

	  const std::vector<Point>&                      samppt   = fe->get_xyz();
	  const std::vector<std::vector<RealGradient> >& dphi2    = fe->get_dphi();

	  const unsigned int n_sp = samprule.n_points();
	  for (unsigned int sp=0; sp< n_sp; sp++)
	    {
	      // Real temperrx=0,temperry=0,temperrz=0;
	      Number temperrx=0,temperry=0,temperrz=0;

	      // Comput the gradient at the current sample point
	      Gradient grad_u_h;

	      for (unsigned int i=0; i<n_dofs; i++)
	        grad_u_h.add_scaled (dphi2[i][sp],
			             system.current_solution(dof_indices[i]));
	      // Compute the phi values at the current sample point
	      std::vector<Real> psi(specpoly(dim,element_order, samppt[sp], matsize));
	      for (unsigned int i=0; i<matsize; i++)
	        {
	          temperrx += psi[i]*Pu_x_h(i);
	          temperry += psi[i]*Pu_y_h(i);
	          temperrz += psi[i]*Pu_z_h(i);
	        }
	      temperrx -= grad_u_h(0);
	      temperry -= grad_u_h(1);
	      temperrz -= grad_u_h(2);

	      // temperrx = std::abs(temperrx);
	      // temperry = std::abs(temperry);
	      // temperrz = std::abs(temperrz);

	      // error = std::max(temperrz,std::max(temperry,temperrx));

	      error = std::max(std::abs(temperrz),
			       std::max(std::abs(temperry),
				        std::abs(temperrx)));

	    } // end sample_point_loop
	  const int e_id=elem->id();
	  error_per_cell[e_id] += error;
	} // end variable loop
    } // end element loop

  // Each processor has now computed the error contribuions
  // for its local elements, and error_per_cell contains 0 for all the
  // non-local elements.  Summing the vector will provide the L_oo value
  // for each element, local or remote
  this->reduce_error(error_per_cell);

  STOP_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
}
<commit_msg>Fix non-initialized variable warning.<commit_after>// $Id: patch_recovery_error_estimator.C,v 1.22 2007-02-09 22:27:20 jwpeterson Exp $

// The libMesh Finite Element Library.
// Copyright (C) 2002-2005  Benjamin S. Kirk, John W. Peterson

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include <algorithm> // for std::fill
#include <cmath>     // for std::sqrt std::pow std::abs

// Local Includes
#include "libmesh_common.h"
#include "patch_recovery_error_estimator.h"
#include "dof_map.h"
#include "fe.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "error_vector.h"
#include "quadrature_gauss.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "patch.h"
#include "quadrature_grid.h"
#include "system.h"
#include "mesh.h"

//-----------------------------------------------------------------
// PatchRecoveryErrorEstimator implementations
std::vector<Real> PatchRecoveryErrorEstimator::specpoly(const unsigned int dim,
							const Order order,
							const Point p,
							const unsigned int matsize)
{
  std::vector<Real> psi;
  psi.reserve(matsize);
  Real x = p(0), y=0., z=0.;
  if (dim > 1)
    y = p(1);
  if (dim > 2)
    z = p(2);

  // builds psi vector of form 1 x y z x^2 xy xz y^2 yz z^2 etc..
  // I haven't added 1D support here
  for (unsigned int poly_deg=0; poly_deg <= static_cast<unsigned int>(order) ; poly_deg++)
    { // loop over all polynomials of total degreee = poly_deg

      switch (dim)
	{
	  // 3D spectral polynomial basis functions
	case 3:
	  {
	    for (int xexp=poly_deg; xexp >= 0; xexp--) // use an int for xexp since we -- it
	      for (int yexp=poly_deg-xexp; yexp >= 0; yexp--)
                {
                  int zexp = poly_deg - xexp - yexp;
		  psi.push_back(std::pow(x,xexp)*std::pow(y,yexp)*std::pow(z,zexp));
                }
	    break;
	  }

	  // 2D spectral polynomial basis functions
	case 2:
	  {
	    for (int xexp=poly_deg; xexp >= 0; xexp--) // use an int for xexp since we -- it
              {
                int yexp = poly_deg - xexp;
		psi.push_back(std::pow(x,xexp)*std::pow(y,yexp));
              }
	    break;
	  }

	  // 1D spectral polynomial basis functions
	case 1:
	  {
            int xexp = poly_deg;
	    psi.push_back(std::pow(x,xexp));
	    break;
	  }

	default:
	  error();
	}
    }

  return psi;
}

void PatchRecoveryErrorEstimator::estimate_error (const System& system,
						  ErrorVector& error_per_cell,
					          bool)
{
  START_LOG("estimate_error()", "PatchRecoveryErrorEstimator");

  // The current mesh
  const Mesh& mesh = system.get_mesh();

  // The dimensionality of the mesh
  const unsigned int dim = mesh.mesh_dimension();

  // The number of variables in the system
  const unsigned int n_vars = system.n_vars();

  // The DofMap for this system
  const DofMap& dof_map = system.get_dof_map();

  // Resize the error_per_cell vector to be
  // the number of elements, initialize it to 0.
  error_per_cell.resize (mesh.n_elem());
  std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);

  // Check for the use of component_mask
  this->convert_component_mask_to_scale();

  // Check for a valid component_scale
  if (!component_scale.empty())
    if (component_scale.size() != n_vars)
      {
	std::cerr << "ERROR: component_scale is the wrong size:"
		  << std::endl
		  << " component_scale.size()=" << component_scale.size()
		  << std::endl
		  << ", n_vars=" << n_vars
		  << std::endl;
	error();
      }

  //------------------------------------------------------------
  // Iterate over all the active elements in the mesh
  // that live on this processor.
  MeshBase::const_element_iterator       elem_it  = mesh.active_local_elements_begin();
  const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end();

  for (; elem_it != elem_end; ++elem_it)
    {
      // elem is necessarily an active element on the local processor
      const Elem* elem = *elem_it;

      // Build a patch containing the current element
      // and its neighbors on the local processor
      Patch patch;

      // We log the time spent building patches separately
      PAUSE_LOG("estimate_error()", "PatchRecoveryErrorEstimator");

      // Use default patch size and growth strategy
      patch.build_around_element (elem);

      RESTART_LOG("estimate_error()", "PatchRecoveryErrorEstimator");

      //------------------------------------------------------------
      // Process each variable in the system using the current patch
      for (unsigned int var=0; var<n_vars; var++)
	{
	  // Possibly skip this variable
	  if (!component_scale.empty())
	    if (component_scale[var] == 0.0) continue;

	  // The type of finite element to use for this variable
	  const FEType& fe_type = dof_map.variable_type (var);

          const Order element_order  = static_cast<Order>
            (fe_type.order + elem->p_level());

	  // Finite element object for use in this patch
	  AutoPtr<FEBase> fe (FEBase::build (dim, fe_type));

	  // Build an appropriate Gaussian quadrature rule
	  AutoPtr<QBase> qrule (fe_type.default_quadrature_rule(dim));

	  // Tell the finite element about the quadrature rule.
	  fe->attach_quadrature_rule (qrule.get());

	  // Get Jacobian values, etc..
	  const std::vector<Real>&                       JxW     = fe->get_JxW();
	  const std::vector<Point>&                      q_point = fe->get_xyz();
	  const std::vector<std::vector<Real> >&         phi     = fe->get_phi();
	  const std::vector<std::vector<RealGradient> >& dphi    = fe->get_dphi();

	  // global DOF indices
	  std::vector<unsigned int> dof_indices;

	  // Compute the approprite size for the patch projection matrices
	  // and vectors;
	  unsigned int matsize;

          switch (dim)
	    {
	    case 3:
	      {
                matsize = (element_order + 1)*
                          (element_order + 2)*
                          (element_order + 3)/6;
	        break;
              }
	    case 2:
	      {
                matsize = (element_order + 1)*
                          (element_order + 2)/2;
	        break;
              }
	    case 1:
	      {
                matsize = element_order + 1;
	        break;
              }
	    default:
	      error();
	    }

	  DenseMatrix<Number> Kp(matsize,matsize);
	  DenseVector<Number>
	    Fx(matsize), Pu_x_h(matsize),
	    Fy(matsize), Pu_y_h(matsize),
	    Fz(matsize), Pu_z_h(matsize);

	  //------------------------------------------------------
	  // Loop over each element in the patch and compute their
	  // contribution to the patch gradient projection.
	  Patch::const_iterator        patch_it  = patch.begin();
	  const Patch::const_iterator  patch_end = patch.end();

	  for (; patch_it != patch_end; ++patch_it)
	    {
	      // The pth element in the patch
	      const Elem* e_p = *patch_it;

	      // Reinitialize the finite element data for this element
	      fe->reinit (e_p);

	      // Get the global DOF indices for the current variable
	      // in the current element
	      dof_map.dof_indices (e_p, dof_indices, var);
	      assert (dof_indices.size() == phi.size());

	      const unsigned int n_dofs = dof_indices.size();
	      const unsigned int n_qp   = qrule->n_points();

	      // Compute the projection components from this cell.
	      // \int_{Omega_e} \psi_i \psi_j = \int_{Omega_e} du_h/dx_k \psi_i
	      for (unsigned int qp=0; qp<n_qp; qp++)
		{
		  // Compute the gradient on the current patch element
		  // at the quadrature point
		  Gradient grad_u_h;

		  for (unsigned int i=0; i<n_dofs; i++)
		    // grad_u_h += dphi[i][qp]*system.current_solution(dof_indices[i]);
		    grad_u_h.add_scaled (dphi[i][qp],
					 system.current_solution(dof_indices[i]));

		  // Construct the shape function values for the patch projection
		  std::vector<Real> psi(specpoly(dim, element_order, q_point[qp], matsize));

		  // Patch matrix contribution
		  for (unsigned int i=0; i<Kp.m(); i++)
		    for (unsigned int j=0; j<Kp.n(); j++)
		      Kp(i,j) += JxW[qp]*psi[i]*psi[j];

		  // Patch RHS contributions
		  for (unsigned int i=0; i<psi.size(); i++)
		    {
		      Fx(i) += JxW[qp]*grad_u_h(0)*psi[i];
		      Fy(i) += JxW[qp]*grad_u_h(1)*psi[i];
		      Fz(i) += JxW[qp]*grad_u_h(2)*psi[i];
		    }
		} // end quadrature loop
	    } // end patch loop

	  //--------------------------------------------------
	  // Now we have fully assembled the projection system
	  // for this patch.  Project the gradient components.
	  // MAY NEED TO USE PARTIAL PIVOTING!
	  Kp.lu_solve (Fx, Pu_x_h);
	  Kp.lu_solve (Fy, Pu_y_h);
	  Kp.lu_solve (Fz, Pu_z_h);

	  //--------------------------------------------------
	  // Finally, estimate the error in the current variable
	  // for the current element by computing ||Pgrad_u_h - grad_u_h||

	  fe->reinit(elem);
	  //reinitialize element

	  dof_map.dof_indices (elem, dof_indices, var);
	  const unsigned int n_dofs = dof_indices.size();

	  // For linear elments, grad is a constant, so we need to compute
	  // grad u_h once on the element.  Also as G_H u_h - gradu_h is linear
	  // on an element, it assumes its maximum at a vertex of the element
	  Real error = 0;
	  // we approximate the max norm by sampling over a set of points
	  // in future we may add specialized routines for specific cases
	  // or use some optimization package
	  const Order qorder = element_order;

	  // build a "fake" quadrature rule for the element
	  QGrid samprule (dim, qorder);
	  fe->attach_quadrature_rule (&samprule);
	  fe->reinit(elem);

	  const std::vector<Point>&                      samppt   = fe->get_xyz();
	  const std::vector<std::vector<RealGradient> >& dphi2    = fe->get_dphi();

	  const unsigned int n_sp = samprule.n_points();
	  for (unsigned int sp=0; sp< n_sp; sp++)
	    {
	      // Real temperrx=0,temperry=0,temperrz=0;
	      Number temperrx=0,temperry=0,temperrz=0;

	      // Comput the gradient at the current sample point
	      Gradient grad_u_h;

	      for (unsigned int i=0; i<n_dofs; i++)
	        grad_u_h.add_scaled (dphi2[i][sp],
			             system.current_solution(dof_indices[i]));
	      // Compute the phi values at the current sample point
	      std::vector<Real> psi(specpoly(dim,element_order, samppt[sp], matsize));
	      for (unsigned int i=0; i<matsize; i++)
	        {
	          temperrx += psi[i]*Pu_x_h(i);
	          temperry += psi[i]*Pu_y_h(i);
	          temperrz += psi[i]*Pu_z_h(i);
	        }
	      temperrx -= grad_u_h(0);
	      temperry -= grad_u_h(1);
	      temperrz -= grad_u_h(2);

	      // temperrx = std::abs(temperrx);
	      // temperry = std::abs(temperry);
	      // temperrz = std::abs(temperrz);

	      // error = std::max(temperrz,std::max(temperry,temperrx));

	      error = std::max(std::abs(temperrz),
			       std::max(std::abs(temperry),
				        std::abs(temperrx)));

	    } // end sample_point_loop
	  const int e_id=elem->id();
	  error_per_cell[e_id] += error;
	} // end variable loop
    } // end element loop

  // Each processor has now computed the error contribuions
  // for its local elements, and error_per_cell contains 0 for all the
  // non-local elements.  Summing the vector will provide the L_oo value
  // for each element, local or remote
  this->reduce_error(error_per_cell);

  STOP_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
}
<|endoftext|>


<commit_before>#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>

struct Interface {
    std::string to_string(int i) const { throw std::runtime_error("Not implemented!"); }
};

template <class Derived>
struct printer {

    ~printer() {
        static_assert(
            std::is_base_of<Interface, Derived>::value,
            "Derived must implement Interface!");
        static_assert(
            std::is_base_of<printer, Derived>::value,
            "Derived must derive from printer!");
        static_assert(
            std::is_base_of<Interface, Derived>::value,
            "Derived must not be Interface!");
    }

    std::string to_string(int i) const { return static_cast<const Derived*>(this)->to_string(i); }
};

struct Implementation : printer<Implementation>, Interface {
    std::string to_string(int i) const { return boost::lexical_cast<std::string>(i); }
};

struct Implementation2 : printer<Implementation> {
    std::string to_string(int i) const { return boost::lexical_cast<std::string>(i); }
};

BOOST_AUTO_TEST_CASE( test_static_polymorphism )
{
    printer<Implementation> p;
    std::string r = p.to_string(1);

    BOOST_REQUIRE_EQUAL("1", r);

    //printer<Implementation2> p2;
}
<commit_msg>Commented out breaking test<commit_after>#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>

struct Interface {
    std::string to_string(int i) const { throw std::runtime_error("Not implemented!"); }
};

template <class Derived>
struct printer {

    ~printer() {
        static_assert(
            std::is_base_of<Interface, Derived>::value,
            "Derived must implement Interface!");
        static_assert(
            std::is_base_of<printer, Derived>::value,
            "Derived must derive from printer!");
        static_assert(
            std::is_base_of<Interface, Derived>::value,
            "Derived must not be Interface!");
    }

    std::string to_string(int i) const { return static_cast<const Derived*>(this)->to_string(i); }
};

struct Implementation : printer<Implementation>, Interface {
    std::string to_string(int i) const { return boost::lexical_cast<std::string>(i); }
};

struct Implementation2 : printer<Implementation> {
    std::string to_string(int i) const { return boost::lexical_cast<std::string>(i); }
};

BOOST_AUTO_TEST_CASE( test_static_polymorphism )
{
    printer<Implementation> p;
    std::string r = p.to_string(1);

    BOOST_REQUIRE_EQUAL("1", r);

    //Interface* pi = reinterpret_cast<Interface*>(&p);

    //std::string s = pi->to_string(2);
    //BOOST_REQUIRE_EQUAL("2", r);

    //printer<Implementation2> p2;
}
<|endoftext|>


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

#include <svx/svdpagv.hxx>
#include <svx/svdview.hxx>
#include <svx/ruler.hxx>
#include <idxmrk.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
#include <swmodule.hxx>
#include <viewopt.hxx>
#include <docsh.hxx>
#include <globdoc.hxx>
#include <navipi.hxx>
#include <fldwrap.hxx>
#include <redlndlg.hxx>
#include <dpage.hxx>
#include <edtwin.hxx>
#include "formatclipboard.hxx"
#include <cmdid.h>
// header for class SfxRequest
#include <sfx2/request.hxx>

#include <sfx2/viewfrm.hxx>

extern int bDocSzUpdated;

void SwView::Activate(sal_Bool bMDIActivate)
{
    // aktuelle View anmelden an der DocShell
    // die View bleibt solange an der DocShell
    // aktiv bis Sie zerstoert wird oder durch Activate eine
    // neue gesetzt wird
    SwDocShell* pDocSh = GetDocShell();
    if(pDocSh)
        pDocSh->SetView(this);
    SwModule* pSwMod = SW_MOD();
    pSwMod->SetView(this);

    // Dokumentgroesse hat sich geaendert
    if(!bDocSzUpdated)
        DocSzChgd(aDocSz);

    // make selection visible
    if(bMakeSelectionVisible)
    {
        pWrtShell->MakeSelVisible();
        bMakeSelectionVisible = sal_False;
    }
    pHRuler->SetActive( sal_True );
    pVRuler->SetActive( sal_True );

    if ( bMDIActivate )
    {
        pWrtShell->ShGetFcs(sal_False);     // Selektionen sichtbar

        if( sSwViewData.Len() )
        {
            ReadUserData( sSwViewData, sal_False );
            sSwViewData.Erase();
        }

        AttrChangedNotify(pWrtShell);

        // Flddlg ggf neu initialisieren (z.B. fuer TYP_SETVAR)
        sal_uInt16 nId = SwFldDlgWrapper::GetChildWindowId();
        SfxViewFrame* pVFrame = GetViewFrame();
        SwFldDlgWrapper *pWrp = (SwFldDlgWrapper*)pVFrame->GetChildWindow(nId);
        if (pWrp)
            pWrp->ReInitDlg(GetDocShell());

        // RedlineDlg ggf neu initialisieren
        nId = SwRedlineAcceptChild::GetChildWindowId();
        SwRedlineAcceptChild *pRed = (SwRedlineAcceptChild*)pVFrame->GetChildWindow(nId);
        if (pRed)
            pRed->ReInitDlg(GetDocShell());

        // reinit IdxMarkDlg
        nId = SwInsertIdxMarkWrapper::GetChildWindowId();
        SwInsertIdxMarkWrapper *pIdxMrk = (SwInsertIdxMarkWrapper*)pVFrame->GetChildWindow(nId);
        if (pIdxMrk)
            pIdxMrk->ReInitDlg(*pWrtShell);

        // reinit AuthMarkDlg
        nId = SwInsertAuthMarkWrapper::GetChildWindowId();
        SwInsertAuthMarkWrapper *pAuthMrk = (SwInsertAuthMarkWrapper*)pVFrame->
                                                                GetChildWindow(nId);
        if (pAuthMrk)
            pAuthMrk->ReInitDlg(*pWrtShell);
    }
    else
        //Wenigstens das Notify rufen (vorsichtshalber wegen der SlotFilter
        AttrChangedNotify(pWrtShell);

    SfxViewShell::Activate(bMDIActivate);
}

void SwView::Deactivate(sal_Bool bMDIActivate)
{
    extern sal_Bool bFlushCharBuffer ;
        // Befinden sich noch Zeichen im Input Buffer?
    if( bFlushCharBuffer )
        GetEditWin().FlushInBuffer();

    if( bMDIActivate )
    {
        pWrtShell->ShLooseFcs();    // Selektionen unsichtbar

        pHRuler->SetActive( sal_False );
        pVRuler->SetActive( sal_False );
    }
    SfxViewShell::Deactivate(bMDIActivate);
}

void SwView::MarginChanged()
{
    GetWrtShell().SetBrowseBorder( GetMargin() );
}

void SwView::ExecFormatPaintbrush(SfxRequest& rReq)
{
    if(!pFormatClipboard)
        return;

    if( pFormatClipboard->HasContent() )
    {
        pFormatClipboard->Erase();

        SwApplyTemplate aTemplate;
        GetEditWin().SetApplyTemplate(aTemplate);
    }
    else
    {
        bool bPersistentCopy = false;
        const SfxItemSet *pArgs = rReq.GetArgs();
        if( pArgs && pArgs->Count() >= 1 )
        {
            bPersistentCopy = static_cast<bool>(((SfxBoolItem &)pArgs->Get(
                                    SID_FORMATPAINTBRUSH)).GetValue());
        }

        pFormatClipboard->Copy( GetWrtShell(), GetPool(), bPersistentCopy );

        SwApplyTemplate aTemplate;
        aTemplate.pFormatClipboard = pFormatClipboard;
        GetEditWin().SetApplyTemplate(aTemplate);
    }
    GetViewFrame()->GetBindings().Invalidate(SID_FORMATPAINTBRUSH);
}

void SwView::StateFormatPaintbrush(SfxItemSet &rSet)
{
    if(!pFormatClipboard)
        return;

    bool bHasContent = pFormatClipboard && pFormatClipboard->HasContent();
    rSet.Put(SfxBoolItem(SID_FORMATPAINTBRUSH, bHasContent));
    if(!bHasContent)
    {
        if( !pFormatClipboard->CanCopyThisType( GetWrtShell().GetSelectionType() ) )
            rSet.DisableItem( SID_FORMATPAINTBRUSH );
    }
}

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

#include <svx/svdpagv.hxx>
#include <svx/svdview.hxx>
#include <svx/ruler.hxx>
#include <idxmrk.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
#include <swmodule.hxx>
#include <viewopt.hxx>
#include <docsh.hxx>
#include <globdoc.hxx>
#include <navipi.hxx>
#include <fldwrap.hxx>
#include <redlndlg.hxx>
#include <dpage.hxx>
#include <edtwin.hxx>
#include "formatclipboard.hxx"
#include <cmdid.h>
// header for class SfxRequest
#include <sfx2/request.hxx>

#include <sfx2/viewfrm.hxx>

extern int bDocSzUpdated;

void SwView::Activate(sal_Bool bMDIActivate)
{
    // fdo#40438 Update the layout to make sure everything is correct before showing the content
    pWrtShell->StartAction();
    pWrtShell->EndAction( sal_True );

    // aktuelle View anmelden an der DocShell
    // die View bleibt solange an der DocShell
    // aktiv bis Sie zerstoert wird oder durch Activate eine
    // neue gesetzt wird
    SwDocShell* pDocSh = GetDocShell();
    if(pDocSh)
        pDocSh->SetView(this);
    SwModule* pSwMod = SW_MOD();
    pSwMod->SetView(this);

    // Dokumentgroesse hat sich geaendert
    if(!bDocSzUpdated)
        DocSzChgd(aDocSz);

    // make selection visible
    if(bMakeSelectionVisible)
    {
        pWrtShell->MakeSelVisible();
        bMakeSelectionVisible = sal_False;
    }
    pHRuler->SetActive( sal_True );
    pVRuler->SetActive( sal_True );

    if ( bMDIActivate )
    {
        pWrtShell->ShGetFcs(sal_False);     // Selektionen sichtbar

        if( sSwViewData.Len() )
        {
            ReadUserData( sSwViewData, sal_False );
            sSwViewData.Erase();
        }

        AttrChangedNotify(pWrtShell);

        // Flddlg ggf neu initialisieren (z.B. fuer TYP_SETVAR)
        sal_uInt16 nId = SwFldDlgWrapper::GetChildWindowId();
        SfxViewFrame* pVFrame = GetViewFrame();
        SwFldDlgWrapper *pWrp = (SwFldDlgWrapper*)pVFrame->GetChildWindow(nId);
        if (pWrp)
            pWrp->ReInitDlg(GetDocShell());

        // RedlineDlg ggf neu initialisieren
        nId = SwRedlineAcceptChild::GetChildWindowId();
        SwRedlineAcceptChild *pRed = (SwRedlineAcceptChild*)pVFrame->GetChildWindow(nId);
        if (pRed)
            pRed->ReInitDlg(GetDocShell());

        // reinit IdxMarkDlg
        nId = SwInsertIdxMarkWrapper::GetChildWindowId();
        SwInsertIdxMarkWrapper *pIdxMrk = (SwInsertIdxMarkWrapper*)pVFrame->GetChildWindow(nId);
        if (pIdxMrk)
            pIdxMrk->ReInitDlg(*pWrtShell);

        // reinit AuthMarkDlg
        nId = SwInsertAuthMarkWrapper::GetChildWindowId();
        SwInsertAuthMarkWrapper *pAuthMrk = (SwInsertAuthMarkWrapper*)pVFrame->
                                                                GetChildWindow(nId);
        if (pAuthMrk)
            pAuthMrk->ReInitDlg(*pWrtShell);
    }
    else
        //Wenigstens das Notify rufen (vorsichtshalber wegen der SlotFilter
        AttrChangedNotify(pWrtShell);

    SfxViewShell::Activate(bMDIActivate);
}

void SwView::Deactivate(sal_Bool bMDIActivate)
{
    extern sal_Bool bFlushCharBuffer ;
        // Befinden sich noch Zeichen im Input Buffer?
    if( bFlushCharBuffer )
        GetEditWin().FlushInBuffer();

    if( bMDIActivate )
    {
        pWrtShell->ShLooseFcs();    // Selektionen unsichtbar

        pHRuler->SetActive( sal_False );
        pVRuler->SetActive( sal_False );
    }
    SfxViewShell::Deactivate(bMDIActivate);
}

void SwView::MarginChanged()
{
    GetWrtShell().SetBrowseBorder( GetMargin() );
}

void SwView::ExecFormatPaintbrush(SfxRequest& rReq)
{
    if(!pFormatClipboard)
        return;

    if( pFormatClipboard->HasContent() )
    {
        pFormatClipboard->Erase();

        SwApplyTemplate aTemplate;
        GetEditWin().SetApplyTemplate(aTemplate);
    }
    else
    {
        bool bPersistentCopy = false;
        const SfxItemSet *pArgs = rReq.GetArgs();
        if( pArgs && pArgs->Count() >= 1 )
        {
            bPersistentCopy = static_cast<bool>(((SfxBoolItem &)pArgs->Get(
                                    SID_FORMATPAINTBRUSH)).GetValue());
        }

        pFormatClipboard->Copy( GetWrtShell(), GetPool(), bPersistentCopy );

        SwApplyTemplate aTemplate;
        aTemplate.pFormatClipboard = pFormatClipboard;
        GetEditWin().SetApplyTemplate(aTemplate);
    }
    GetViewFrame()->GetBindings().Invalidate(SID_FORMATPAINTBRUSH);
}

void SwView::StateFormatPaintbrush(SfxItemSet &rSet)
{
    if(!pFormatClipboard)
        return;

    bool bHasContent = pFormatClipboard && pFormatClipboard->HasContent();
    rSet.Put(SfxBoolItem(SID_FORMATPAINTBRUSH, bHasContent));
    if(!bHasContent)
    {
        if( !pFormatClipboard->CanCopyThisType( GetWrtShell().GetSelectionType() ) )
            rSet.DisableItem( SID_FORMATPAINTBRUSH );
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "rtkTestConfiguration.h"
#include "itkRandomImageSource.h"
#include "rtkTotalVariationImageFilter.h"
#include "rtkTotalVariationDenoisingBPDQImageFilter.h"
#include "rtkMacro.h"

template<class TImage>
#if FAST_TESTS_NO_CHECKS
void CheckTotalVariation(typename TImage::Pointer itkNotUsed(before), typename TImage::Pointer itkNotUsed(after))
{
}
#else
void CheckTotalVariation(typename TImage::Pointer before, typename TImage::Pointer after)
{
  typedef rtk::TotalVariationImageFilter<TImage> TotalVariationFilterType;
  typename TotalVariationFilterType::Pointer tv = TotalVariationFilterType::New();

  double totalVariationBefore;
  double totalVariationAfter;

  tv->SetInput(before);
  tv->Update();
  totalVariationBefore = tv->GetTotalVariation();
  std::cout << "Total variation before denoising is " << totalVariationBefore << std::endl;

  tv->SetInput(after);
  tv->Update();
  totalVariationAfter = tv->GetTotalVariation();
  std::cout << "Total variation after denoising is " << totalVariationAfter << std::endl;

  // Checking results
  if (totalVariationBefore/2 < totalVariationAfter)
  {
    std::cerr << "Test Failed: total variation was not reduced" << std::endl;
    exit( EXIT_FAILURE);
  }
}
#endif

/**
 * \file rtktotalvariationtest.cxx
 *
 * \brief Tests whether the Total Variation denoising filters indeed
 * reduce the total variation of a random image
 *
 * This test generates a random volume and performs TV denoising on this
 * volume. It measures its total variation before and after denoising and
 * compares. Note that the TV denoising filters do not minimize TV alone,
 * but TV + a data attachment term (they compute the proximal operator of TV).
 * Nevertheless, in most cases, it is expected that the output has
 * a lower TV than the input.
 *
 * \author Cyril Mory
 */

int main(int, char** )
{
  typedef float OutputPixelType;
  const unsigned int Dimension = 3;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
  typedef itk::CudaImage< itk::CovariantVector
      < OutputPixelType, Dimension >, Dimension >                GradientOutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension >     OutputImageType;
  typedef itk::Image< itk::CovariantVector
      < OutputPixelType, Dimension >, Dimension >                GradientOutputImageType;
#endif

  // Random image sources
  typedef itk::RandomImageSource< OutputImageType > RandomImageSourceType;
  RandomImageSourceType::Pointer randomVolumeSource  = RandomImageSourceType::New();

  // Image meta data
  RandomImageSourceType::PointType origin;
  RandomImageSourceType::SizeType size;
  RandomImageSourceType::SpacingType spacing;

  // Volume metadata
  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  randomVolumeSource->SetOrigin( origin );
  randomVolumeSource->SetSpacing( spacing );
  randomVolumeSource->SetSize( size );
  randomVolumeSource->SetMin( 0. );
  randomVolumeSource->SetMax( 1. );
  randomVolumeSource->SetNumberOfThreads(2); //With 1, it's deterministic

  // Update the source
  TRY_AND_EXIT_ON_ITK_EXCEPTION( randomVolumeSource->Update() );

  // Create and set the TV denoising filter
  typedef rtk::TotalVariationDenoisingBPDQImageFilter
    <OutputImageType, GradientOutputImageType>                TVDenoisingFilterType;
  TVDenoisingFilterType::Pointer TVdenoising = TVDenoisingFilterType::New();
  TVdenoising->SetInput(randomVolumeSource->GetOutput());
  TVdenoising->SetNumberOfIterations(15);
  TVdenoising->SetLambda(0.005);
  bool dimsProcessed[Dimension];
  for (int i=0; i<Dimension; i++)
    {
    dimsProcessed[i] = true;
    }
  TVdenoising->SetDimensionsProcessed(dimsProcessed);

  // Update the TV denoising filter
  TRY_AND_EXIT_ON_ITK_EXCEPTION( TVdenoising->Update() );

  CheckTotalVariation<OutputImageType>(randomVolumeSource->GetOutput(), TVdenoising->GetOutput());

  std::cout << "\n\nTest PASSED! " << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>COMP: Warning<commit_after>#include "rtkTestConfiguration.h"
#include "itkRandomImageSource.h"
#include "rtkTotalVariationImageFilter.h"
#include "rtkTotalVariationDenoisingBPDQImageFilter.h"
#include "rtkMacro.h"

template<class TImage>
#if FAST_TESTS_NO_CHECKS
void CheckTotalVariation(typename TImage::Pointer itkNotUsed(before), typename TImage::Pointer itkNotUsed(after))
{
}
#else
void CheckTotalVariation(typename TImage::Pointer before, typename TImage::Pointer after)
{
  typedef rtk::TotalVariationImageFilter<TImage> TotalVariationFilterType;
  typename TotalVariationFilterType::Pointer tv = TotalVariationFilterType::New();

  double totalVariationBefore;
  double totalVariationAfter;

  tv->SetInput(before);
  tv->Update();
  totalVariationBefore = tv->GetTotalVariation();
  std::cout << "Total variation before denoising is " << totalVariationBefore << std::endl;

  tv->SetInput(after);
  tv->Update();
  totalVariationAfter = tv->GetTotalVariation();
  std::cout << "Total variation after denoising is " << totalVariationAfter << std::endl;

  // Checking results
  if (totalVariationBefore/2 < totalVariationAfter)
  {
    std::cerr << "Test Failed: total variation was not reduced" << std::endl;
    exit( EXIT_FAILURE);
  }
}
#endif

/**
 * \file rtktotalvariationtest.cxx
 *
 * \brief Tests whether the Total Variation denoising filters indeed
 * reduce the total variation of a random image
 *
 * This test generates a random volume and performs TV denoising on this
 * volume. It measures its total variation before and after denoising and
 * compares. Note that the TV denoising filters do not minimize TV alone,
 * but TV + a data attachment term (they compute the proximal operator of TV).
 * Nevertheless, in most cases, it is expected that the output has
 * a lower TV than the input.
 *
 * \author Cyril Mory
 */

int main(int, char** )
{
  typedef float OutputPixelType;
  const unsigned int Dimension = 3;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
  typedef itk::CudaImage< itk::CovariantVector
      < OutputPixelType, Dimension >, Dimension >                GradientOutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension >     OutputImageType;
  typedef itk::Image< itk::CovariantVector
      < OutputPixelType, Dimension >, Dimension >                GradientOutputImageType;
#endif

  // Random image sources
  typedef itk::RandomImageSource< OutputImageType > RandomImageSourceType;
  RandomImageSourceType::Pointer randomVolumeSource  = RandomImageSourceType::New();

  // Image meta data
  RandomImageSourceType::PointType origin;
  RandomImageSourceType::SizeType size;
  RandomImageSourceType::SpacingType spacing;

  // Volume metadata
  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  randomVolumeSource->SetOrigin( origin );
  randomVolumeSource->SetSpacing( spacing );
  randomVolumeSource->SetSize( size );
  randomVolumeSource->SetMin( 0. );
  randomVolumeSource->SetMax( 1. );
  randomVolumeSource->SetNumberOfThreads(2); //With 1, it's deterministic

  // Update the source
  TRY_AND_EXIT_ON_ITK_EXCEPTION( randomVolumeSource->Update() );

  // Create and set the TV denoising filter
  typedef rtk::TotalVariationDenoisingBPDQImageFilter
    <OutputImageType, GradientOutputImageType>                TVDenoisingFilterType;
  TVDenoisingFilterType::Pointer TVdenoising = TVDenoisingFilterType::New();
  TVdenoising->SetInput(randomVolumeSource->GetOutput());
  TVdenoising->SetNumberOfIterations(15);
  TVdenoising->SetLambda(0.005);
  bool dimsProcessed[Dimension];
  for (unsigned int i=0; i<Dimension; i++)
    {
    dimsProcessed[i] = true;
    }
  TVdenoising->SetDimensionsProcessed(dimsProcessed);

  // Update the TV denoising filter
  TRY_AND_EXIT_ON_ITK_EXCEPTION( TVdenoising->Update() );

  CheckTotalVariation<OutputImageType>(randomVolumeSource->GetOutput(), TVdenoising->GetOutput());

  std::cout << "\n\nTest PASSED! " << std::endl;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright Steinwurf ApS 2015.
// All Rights Reserved

#pragma once

#include <cassert>
#include <cstdint>

#include "descriptor.hpp"

#include "../byte_stream.hpp"

namespace petro
{
namespace descriptor
{
    class sl_config_descriptor : public descriptor
    {
    public:
        sl_config_descriptor(byte_stream& bs, uint8_t tag):
            descriptor(bs, tag)
        {
            assert(m_tag == 0x06);
            auto predefined = bs.read_uint8_t();
            if (predefined == 0)
            {
                auto d1 = bs.read_uint8_t();
                m_remaining_bytes -= 1;

                m_use_access_unit_start_flag = ((d1 & 0x01) >> 1) == 1;
                m_use_access_unit_end_flag = ((d1 & 0x02) >> 2) == 1;
                m_use_random_access_point_flag = ((d1 & 0x04) >> 3) == 1;
                m_has_random_access_units_only_flag = ((d1 & 0x08) >> 4) == 1;
                m_use_padding_flag = ((d1 & 0x10) >> 5) == 1;
                m_use_time_stamps_flag = ((d1 & 0x20) >> 6) == 1;
                m_use_idle_flag = ((d1 & 0x40) >> 7) == 1;
                m_duration_flag = ((d1 & 0x80) >> 8) == 1;

                m_time_stamp_resolution = bs.read_uint32_t();
                m_remaining_bytes -= 4;

                m_ocr_resolution = bs.read_uint32_t();
                m_remaining_bytes -= 4;

                m_time_stamp_length = bs.read_uint8_t(); // must be less than 64
                m_remaining_bytes -= 1;

                m_ocr_length = bs.read_uint8_t(); // must be less than 64
                m_remaining_bytes -= 1;

                m_au_length = bs.read_uint8_t(); // must be less than 32
                m_remaining_bytes -= 1;

                m_instant_bitrate_length = bs.read_uint8_t();
                m_remaining_bytes -= 1;

                auto d2 = bs.read_uint16_t();
                m_remaining_bytes -= 2;
                m_degradation_priority_length = d2;
                m_au_sequence_number_length = d2;
                m_packet_sequence_number_length = d2;

                if (m_duration_flag)
                {
                    m_time_scale = bs.read_uint32_t();
                    m_remaining_bytes -= 4;

                    m_access_unit_duration = bs.read_uint16_t();
                    m_remaining_bytes -= 2;

                    m_composition_unit_duration = bs.read_uint16_t();
                    m_remaining_bytes -= 2;
                }

                if (!m_use_time_stamps_flag)
                {
                    auto time_stamp_length_bytes = m_time_stamp_length / 8;
                    if (m_time_stamp_length % 8 != 0)
                        time_stamp_length_bytes += 1;

                    //m_start_decoding_time_stamp = bs.read_bits(time_stamp_length_bytes);
                    bs.skip(time_stamp_length_bytes);
                    m_remaining_bytes -= time_stamp_length_bytes;

                    //m_start_composition_time_stamp = bs.read_bits(time_stamp_length_bytes);
                    bs.skip(time_stamp_length_bytes);
                    m_remaining_bytes -= time_stamp_length_bytes;
                }
            }
        }

    private:
            bool m_use_access_unit_start_flag;
            bool m_use_access_unit_end_flag;
            bool m_use_random_access_point_flag;
            bool m_has_random_access_units_only_flag;
            bool m_use_padding_flag;
            bool m_use_time_stamps_flag;
            bool m_use_idle_flag;
            bool m_duration_flag;

            uint32_t m_time_stamp_resolution;
            uint32_t m_ocr_resolution;
            uint8_t m_time_stamp_length; // must be less than 64
            uint8_t m_ocr_length; // must be less than 64
            uint8_t m_au_length; // must be less than 32
            uint8_t m_instant_bitrate_length;
            uint8_t m_degradation_priority_length; //bit 4
            uint8_t m_au_sequence_number_length; //bit 5
            uint8_t m_packet_sequence_number_length; //bit 5

            uint32_t m_time_scale;
            uint16_t m_access_unit_duration;
            uint16_t m_composition_unit_duration;

            uint64_t m_start_decoding_time_stamp; // bit(timeStampLength)
            uint64_t m_start_composition_time_stamp; // bit(timeStampLength)
    };
}
}
<commit_msg>readied for new sync layer descriptors<commit_after>// Copyright Steinwurf ApS 2015.
// All Rights Reserved

#pragma once

#include <cassert>
#include <cstdint>

#include "descriptor.hpp"

#include "../byte_stream.hpp"

namespace petro
{
namespace descriptor
{
    // sync layer config descriptor
    class sl_config_descriptor : public descriptor
    {
    public:
        sl_config_descriptor(byte_stream& bs, uint8_t tag):
            descriptor(bs, tag)
        {
            assert(m_tag == 0x06);
            auto predefined = bs.read_uint8_t();

            switch(predefined)
            {
                case 0x00:
                {
                    auto d1 = bs.read_uint8_t();
                    m_remaining_bytes -= 1;

                    m_use_access_unit_start_flag = ((d1 & 0x01) >> 1) == 1;
                    m_use_access_unit_end_flag = ((d1 & 0x02) >> 2) == 1;
                    m_use_random_access_point_flag = ((d1 & 0x04) >> 3) == 1;
                    m_has_random_access_units_only_flag =
                        ((d1 & 0x08) >> 4) == 1;
                    m_use_padding_flag = ((d1 & 0x10) >> 5) == 1;
                    m_use_timestamps_flag = ((d1 & 0x20) >> 6) == 1;
                    m_use_idle_flag = ((d1 & 0x40) >> 7) == 1;
                    m_duration_flag = ((d1 & 0x80) >> 8) == 1;

                    m_time_stamp_resolution = bs.read_uint32_t();
                    m_remaining_bytes -= 4;

                    m_ocr_resolution = bs.read_uint32_t();
                    m_remaining_bytes -= 4;

                    // must be less than 64
                    m_time_stamp_length = bs.read_uint8_t();
                    m_remaining_bytes -= 1;

                    // must be less than 64
                    m_ocr_length = bs.read_uint8_t();
                    m_remaining_bytes -= 1;

                    // must be less than 32
                    m_au_length = bs.read_uint8_t();
                    m_remaining_bytes -= 1;

                    m_instant_bitrate_length = bs.read_uint8_t();
                    m_remaining_bytes -= 1;

                    auto d2 = bs.read_uint16_t();
                    m_remaining_bytes -= 2;
                    m_degradation_priority_length = d2;
                    m_au_sequence_number_length = d2;
                    m_packet_sequence_number_length = d2;

                    if (m_duration_flag)
                    {
                        m_time_scale = bs.read_uint32_t();
                        m_remaining_bytes -= 4;

                        m_access_unit_duration = bs.read_uint16_t();
                        m_remaining_bytes -= 2;

                        m_composition_unit_duration = bs.read_uint16_t();
                        m_remaining_bytes -= 2;
                    }

                    if (!m_use_timestamps_flag)
                    {
                        auto time_stamp_length_bytes = m_time_stamp_length / 8;
                        if (m_time_stamp_length % 8 != 0)
                            time_stamp_length_bytes += 1;

                        /// @todo read the next time_stamp_length_bytes
                        // m_start_decoding_time_stamp =
                        //     bs.read_bits(time_stamp_length_bytes);
                        bs.skip(time_stamp_length_bytes);
                        m_remaining_bytes -= time_stamp_length_bytes;

                        /// @todo read the next time_stamp_length_bytes
                        // m_start_composition_time_stamp =
                        //     bs.read_bits(time_stamp_length_bytes);
                        bs.skip(time_stamp_length_bytes);
                        m_remaining_bytes -= time_stamp_length_bytes;
                    }
                    break;
                }
                default:
                {
                    // unsupported sync layer descriptor predefine
                }
            }
        }

    private:
            bool m_use_access_unit_start_flag;
            bool m_use_access_unit_end_flag;
            bool m_use_random_access_point_flag;
            bool m_has_random_access_units_only_flag;
            bool m_use_padding_flag;
            bool m_use_timestamps_flag;
            bool m_use_idle_flag;
            bool m_duration_flag;

            uint32_t m_time_stamp_resolution;
            uint32_t m_ocr_resolution;
            uint8_t m_time_stamp_length; // must be less than 64
            uint8_t m_ocr_length; // must be less than 64
            uint8_t m_au_length; // must be less than 32
            uint8_t m_instant_bitrate_length;
            uint8_t m_degradation_priority_length; //bit 4
            uint8_t m_au_sequence_number_length; //bit 5
            uint8_t m_packet_sequence_number_length; //bit 5

            uint32_t m_time_scale;
            uint16_t m_access_unit_duration;
            uint16_t m_composition_unit_duration;

            uint64_t m_start_decoding_time_stamp; // bit(timeStampLength)
            uint64_t m_start_composition_time_stamp; // bit(timeStampLength)
    };
}
}
<|endoftext|>


<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// 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.

#include "source/example_component/example_base_class.hpp"
#include "test.hpp"

using namespace ::testing;
using ::testing::Return;

namespace example
{
namespace test
{
/// @req IOX_SWRS_112, IOX_SWRS_200
/// @brief Test goal: "This test suite verifies that the BaseClass function is verified"
/// @pre describe what needs to be done in setup()
/// @post describe what needs to be done in teardown()
/// @note name of the Testfixture should match to the Class you want to test
template <typename T>
class ExampleBaseClass_test : public Test
{
  public:
    void SetUp() override
    {
    }

    void TearDown() override
    {
    }
};

/// @note name of the Testcase shall describe the test case in detail to avoid additional comments
TEST_F(ExampleBaseClass_test, FirstUnitTestCase)
{
    ExampleBaseClass<T> testInstance(1, 2);

    testinstance.simplerMethod();

    EXPECT_THAT(testInstance.m_memberVariable, Eq(100u));
}

} // namespace test
} // namespace example<commit_msg>iox-#198 sut in test example<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// 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.

#include "source/example_component/example_base_class.hpp"
#include "test.hpp"

using namespace ::testing;
using ::testing::Return;

namespace example
{
namespace test
{
/// @req IOX_SWRS_112, IOX_SWRS_200
/// @brief Test goal: "This test suite verifies that the BaseClass function is verified"
/// @pre describe what needs to be done in setup()
/// @post describe what needs to be done in teardown()
/// @note name of the Testfixture should match to the Class you want to test
template <typename T>
class ExampleBaseClass_test : public Test
{
  public:
    void SetUp() override
    {
    }

    void TearDown() override
    {
    }
};

/// @note name of the Testcase shall describe the test case in detail to avoid additional comments
TEST_F(ExampleBaseClass_test, FirstUnitTestCase)
{
    ExampleBaseClass<T> sut(1, 2);

    sut.simplerMethod();

    EXPECT_THAT(sut.m_memberVariable, Eq(100u));
}

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


<commit_before>// 2008
// Jon 'jonanin' Morton

#include "luainc.h"
#include "Common.h"
#include "LuaInterface.h"
#include "LuaArgument.h"
#include <list>

int main() {

    LuaInterface lu;
    lu.ExecuteFile("test.lua");

    vector<LuaArgument> retargs;

    // arguments for lua function
    LuaArgument largs[] = { LuaArgument(5) };
    // index, function name,  args array,  number of args, number of results (return args), return args vector
    lu.CallLua(LUA_GLOBALSINDEX, "doStuff", largs, 1, 4, &retargs);

    int i = 0;
    for (vector<LuaArgument>::iterator it = retargs.begin(); it < retargs.end(); it++) {
        printf("arg %i: ", i++);
        it->PrintDebug();
        printf("\n");
    }
}
<commit_msg>removing unneeded include<commit_after>// 2008
// Jon 'jonanin' Morton

#include "luainc.h"
#include "Common.h"
#include "LuaInterface.h"
#include "LuaArgument.h"s

int main() {

    LuaInterface lu;
    lu.ExecuteFile("test.lua");

    vector<LuaArgument> retargs;

    // arguments for lua function
    LuaArgument largs[] = { LuaArgument(5) };
    // index, function name,  args array,  number of args, number of results (return args), return args vector
    lu.CallLua(LUA_GLOBALSINDEX, "doStuff", largs, 1, 4, &retargs);

    int i = 0;
    for (vector<LuaArgument>::iterator it = retargs.begin(); it < retargs.end(); it++) {
        printf("arg %i: ", i++);
        it->PrintDebug();
        printf("\n");
    }
}
<|endoftext|>


<commit_before>#include "../../source/thewizardplusplus/wizard_parser/parser/rule_parser.hpp"
#include "../../source/thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp"
#include "../../source/thewizardplusplus/wizard_parser/lexer/token.hpp"
#include "../../source/thewizardplusplus/wizard_parser/parser/ast_node.hpp"
#include "../../source/thewizardplusplus/wizard_parser/utilities/utilities.hpp"
#include "../vendor/catch/catch.hpp"
#include "../vendor/fakeit/fakeit.hpp"

TEST_CASE("parser::lookahead_parser class", "[parser]") {
	using namespace thewizardplusplus::wizard_parser;
	using namespace thewizardplusplus::wizard_parser::parser::operators;

	SECTION("positive lookahead without tokens") {
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			&parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse({});
		CHECK(!ast.has_value());
		CHECK(rest_tokens.empty());

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("positive lookahead without a match") {
		auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{{}, tokens});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			&parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
		CHECK(!ast.has_value());
		CHECK(rest_tokens == lexer::token_span{tokens});

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("positive lookahead with a match") {
		const auto type = (+parser::ast_node_type::nothing)._to_string();
		auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{
				parser::ast_node{"one", "two", {}, 1},
				lexer::token_span{tokens}.subspan(1)
			});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			&parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
		REQUIRE(ast.has_value());
		CHECK(*ast == parser::ast_node{type, {}, {}, 1});
		CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1));

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("negative lookahead without tokens") {
		const auto type = (+parser::ast_node_type::nothing)._to_string();
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			!parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse({});
		REQUIRE(ast.has_value());
		CHECK(*ast == parser::ast_node{type, {}, {}, utilities::integral_infinity});
		CHECK(rest_tokens.empty());

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("negative lookahead without a match") {
		const auto type = (+parser::ast_node_type::nothing)._to_string();
		auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{{}, tokens});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			!parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
		REQUIRE(ast.has_value());
		CHECK(*ast == parser::ast_node{type, {}, {}, 1});
		CHECK(rest_tokens == lexer::token_span{tokens});

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("negative lookahead with a match") {
		auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{
				parser::ast_node{"one", "two", {}, 1},
				lexer::token_span{tokens}.subspan(1)
			});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			!parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
		CHECK(!ast.has_value());
		CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1));

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}
}
<commit_msg>Upgrade and improve tests of the `parser::lookahead_parser` class<commit_after>#include "../../source/thewizardplusplus/wizard_parser/parser/rule_parser.hpp"
#include "../../source/thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp"
#include "../../source/thewizardplusplus/wizard_parser/lexer/token.hpp"
#include "../../source/thewizardplusplus/wizard_parser/parser/ast_node.hpp"
#include "../../source/thewizardplusplus/wizard_parser/utilities/utilities.hpp"
#include "../vendor/catch/catch.hpp"
#include "../vendor/fakeit/fakeit.hpp"

TEST_CASE("parser::lookahead_parser class", "[parser]") {
	using namespace thewizardplusplus::wizard_parser;
	using namespace thewizardplusplus::wizard_parser::parser::operators;

	SECTION("positive lookahead without tokens") {
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			&parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse({});
		CHECK(!ast.has_value());
		CHECK(rest_tokens.empty());

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("positive lookahead without a match") {
		auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{{}, lexer::token_span{tokens}.subspan(1)});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			&parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
		CHECK(!ast.has_value());
		CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1));

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("positive lookahead with a match") {
		const auto type = (+parser::ast_node_type::nothing)._to_string();
		auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{
				parser::ast_node{"one", "two", {}, 1},
				lexer::token_span{tokens}.subspan(1)
			});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			&parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
		REQUIRE(ast.has_value());
		CHECK(*ast == parser::ast_node{type, {}, {}, 1});
		CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1));

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("negative lookahead without tokens") {
		const auto type = (+parser::ast_node_type::nothing)._to_string();
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			!parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse({});
		REQUIRE(ast.has_value());
		CHECK(*ast == parser::ast_node{type, {}, {}, utilities::integral_infinity});
		CHECK(rest_tokens.empty());

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("negative lookahead without a match") {
		const auto type = (+parser::ast_node_type::nothing)._to_string();
		auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{{}, lexer::token_span{tokens}.subspan(1)});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			!parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
		REQUIRE(ast.has_value());
		CHECK(*ast == parser::ast_node{type, {}, {}, 1});
		CHECK(rest_tokens == lexer::token_span{tokens});

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}

	SECTION("negative lookahead with a match") {
		auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
		auto mock_parser = fakeit::Mock<parser::rule_parser>{};
		fakeit::When(Method(mock_parser, parse))
			.Return(parser::parsing_result{
				parser::ast_node{"one", "two", {}, 1},
				lexer::token_span{tokens}.subspan(1)
			});
		fakeit::Fake(Dtor(mock_parser));

		const auto lookahead_parser =
			!parser::rule_parser::pointer{&mock_parser.get()};
		const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
		CHECK(!ast.has_value());
		CHECK(rest_tokens == lexer::token_span{tokens});

		fakeit::Verify(Method(mock_parser, parse)).Once();
	}
}
<|endoftext|>


<commit_before>#include "MaximumProductSubarray.hpp"

using namespace std;

int MaximumProductSubarray::maxProduct(vector<int> &nums) {
    int n = nums.size();

    if (n == 0)
        return 0;

    vector<int> a(n, 0);
    vector<int> b(n, 0);
    a[0] = b[0] = nums[0];

    for (int i = 1; i < n; i++) {
        int v1 = nums[i];
        int v2 = a[i - 1] * nums[i];
        int v3 = b[i - 1] * nums[i];
        a[i] = max(v1, max(v2, v3));
        b[i] = min(v1, min(v2, v3));
    }

    int ret = a[0];

    for (int i = 1; i < n; i++)
        ret = max(ret, a[i]);

    return ret;
}
<commit_msg>Refine Problem 152. Maximum Product Subarray<commit_after>#include "MaximumProductSubarray.hpp"

#include <algorithm>

using namespace std;

int MaximumProductSubarray::maxProduct(vector<int> &nums) {
    int n = nums.size();

    if (n == 0)
        return 0;

    vector<int> a(n, 0);
    vector<int> b(n, 0);
    a[0] = b[0] = nums[0];

    for (int i = 1; i < n; i++) {
        int v1 = nums[i];
        int v2 = a[i - 1] * nums[i];
        int v3 = b[i - 1] * nums[i];
        a[i] = max(v1, max(v2, v3));
        b[i] = min(v1, min(v2, v3));
    }

    int ret = a[0];

    for (int i = 1; i < n; i++)
        ret = max(ret, a[i]);

    return ret;
}
<|endoftext|>