<commit_before>/*
* Copyright 2016 Esri
*
* 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.
*/

/*
* JPNG band, uses JPEG or PNG encoding, depending on the input data
*/

#include "marfa.h"
#include <cassert>

CPL_C_START
#include <jpeglib.h>

#ifdef INTERNAL_PNG
#include "../png/libpng/png.h"
#else
#include <png.h>
#endif
CPL_C_END

NAMESPACE_MRF_START

// Test that all alpha values are equal to N
template<int N> bool AllAlpha(const buf_mgr &src, const ILImage &img) {
    int stride = img.pagesize.c;
    char *s = src.buffer + img.pagesize.c - 1;
    char *stop = src.buffer + img.pageSizeBytes;
    while (s < stop && N == static_cast<unsigned char>(*s))
        s += stride;
    return (s >= stop);
}

// Fully opaque
#define opaque AllAlpha<255>
// Fully transparent
#define transparent AllAlpha<0>

// Are all pixels in the tile opaque?
//static bool opaque(const buf_mgr &src, const ILImage &img) {
//    int stride = img.pagesize.c;
//    char *s = src.buffer + img.pagesize.c - 1;
//    char *stop = src.buffer + img.pageSizeBytes;
//    while (s < stop && 255 == static_cast<unsigned char>(*s))
//        s += stride;
//    return (s >= stop);
//}

// Strip the alpha from an RGBA buffer, safe to use in place
static void RGBA2RGB(const char *start, const char *stop, char *target) {
    while (start < stop) {
        *target++ = *start++;
        *target++ = *start++;
        *target++ = *start++;
        start++; // Skip the alpha
    }
}

// Add opaque alpha to an RGB buffer, safe to use in place
// works backwards, from stop to start, the last pointer is the end of the source region
static void RGB2RGBA(const char *start, char *stop, const char *source_end) {
    while (start < stop) {
        *--stop = 0xff;
        *--stop = *--source_end;
        *--stop = *--source_end;
        *--stop = *--source_end;
    }
}

// Strip the alpha from an Luma Alpha buffer, fafe to use in place
static void LA2L(const char *start, const char *stop, char *target) {
    while (start < stop) {
        *target++ = *start++;
        start++; // Skip the alpha
    }
}

// Add opaque alpha to a Luma buffer, safe to use in place
// works backwards, from stop to start, the last pointer is the end of the source region
static void L2LA(const char *start, char *stop, const char *source_end) {
    while (start < stop) {
        *--stop = 0xff;
        *--stop = *--source_end;
    }
}

static CPLErr initBuffer(buf_mgr &b)
{
    b.buffer = (char *)(CPLMalloc(b.size));
    if (b.buffer != NULL)
        return CE_None;
    CPLError(CE_Failure, CPLE_OutOfMemory, "Allocating temporary JPNG buffer");
    return CE_Failure;
}

CPLErr JPNG_Band::Decompress(buf_mgr &dst, buf_mgr &src)
{
    CPLErr retval = CE_None;
    const static GUInt32 JPEG_SIG = 0xe0ffd8ff; // JPEG (JFIF) magic int
//  const static GUInt32 PNG_SIG  = 0x474e5089;  // PNG magic int

    ILImage image(img);
    GUInt32 signature;
    memcpy(&signature, src.buffer, sizeof(GUInt32));

    if (signature == JPEG_SIG) {
        image.pagesize.c -= 1;
        JPEG_Codec codec(image);

        // JPEG decoder expects the destination size to be accurate
        buf_mgr temp = dst; // dst still owns the storage
        temp.size = (image.pagesize.c == 3) ? dst.size / 4 * 3 : dst.size / 2;

        retval = codec.DecompressJPEG(temp, src);
        if (CE_None == retval) { // add opaque alpha, in place
            if (image.pagesize.c == 3)
                RGB2RGBA(dst.buffer, dst.buffer + dst.size, temp.buffer + temp.size);
            else
                L2LA(dst.buffer, dst.buffer + dst.size, temp.buffer + temp.size);
        }
    }
    else {
        CPLError(CE_Failure, CPLE_NotSupported, "JPNG functionality not yet implemented");
        return CE_Failure; // Not implemented yet
    }

    return retval;
}

// The PNG internal palette is set on first band write
CPLErr JPNG_Band::Compress(buf_mgr &dst, buf_mgr &src)
{
    ILImage image(img);
    CPLErr retval = CE_None;

    buf_mgr temp = { NULL, img.pageSizeBytes };
    retval = initBuffer(temp);
    if (retval != CE_None)
        return retval;

    try {
        if (opaque(src, image)) { // If all pixels are opaque, compress as JPEG
            if (image.pagesize.c == 4)
                RGBA2RGB(src.buffer, src.buffer + src.size, temp.buffer);
            else
                LA2L(src.buffer, src.buffer + src.size, temp.buffer);

            image.pagesize.c -= 1; // RGB or Grayscale only for JPEG
            JPEG_Codec codec(image);
            codec.rgb = rgb;
            codec.optimize = optimize;
            codec.sameres = sameres;
            retval = codec.CompressJPEG(dst, temp);
        }
        else if (transparent(src, image)) {
            dst.size = 0; // Don't store fully transparent pages
        }
        else
        {
            PNG_Codec codec(image);
            codec.deflate_flags = deflate_flags;
            retval = codec.CompressPNG(dst, src);
        }
    }
    catch (CPLErr err) {
        retval = err;
    }

    CPLFree(temp.buffer);
    return retval;
}

/**
* \Brief For PPNG, builds the data structures needed to write the palette
* The presence of the PNGColors and PNGAlpha is used as a flag for PPNG only
*/

JPNG_Band::JPNG_Band(GDALMRFDataset *pDS, const ILImage &image, int b, int level) :
GDALMRFRasterBand(pDS, image, b, level),
rgb(FALSE), sameres(FALSE), optimize(false)

{   // Check error conditions
    if (image.dt != GDT_Byte) {
	CPLError(CE_Failure, CPLE_NotSupported, "Data type not supported by MRF JPNG");
	return;
    }
    if (image.order != IL_Interleaved || (image.pagesize.c != 4 && image.pagesize.c != 2)) {
	CPLError(CE_Failure, CPLE_NotSupported, "MRF JPNG can only handle 2 or 4 interleaved bands");
	return;
    }

    if (img.pagesize.c == 4) { // RGBA can have storage flavors
        CPLString const &pm = pDS->GetPhotometricInterpretation();
        if (pm == "RGB" || pm == "MULTISPECTRAL") { // Explicit RGB or MS
            rgb = TRUE;
            sameres = TRUE;
        }
        if (pm == "YCC")
            sameres = TRUE;
    }

    optimize = GetOptlist().FetchBoolean("OPTIMIZE", FALSE) != FALSE;

    // PNGs and JPGs can be larger than the source, especially for small page size
    poDS->SetPBufferSize(image.pageSizeBytes + 100);
}

JPNG_Band::~JPNG_Band() {
}

NAMESPACE_MRF_END
<commit_msg>JPNG: Read true color PNG tiles<commit_after>/*
* Copyright 2016 Esri
*
* 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.
*/

/*
* JPNG band, uses JPEG or PNG encoding, depending on the input data
*/

#include "marfa.h"
#include <cassert>

CPL_C_START
#include <jpeglib.h>

#ifdef INTERNAL_PNG
#include "../png/libpng/png.h"
#else
#include <png.h>
#endif
CPL_C_END

NAMESPACE_MRF_START

// Test that all alpha values are equal to N
template<int N> bool AllAlpha(const buf_mgr &src, const ILImage &img) {
    int stride = img.pagesize.c;
    char *s = src.buffer + img.pagesize.c - 1;
    char *stop = src.buffer + img.pageSizeBytes;
    while (s < stop && N == static_cast<unsigned char>(*s))
        s += stride;
    return (s >= stop);
}

// Fully opaque
#define opaque AllAlpha<255>
// Fully transparent
#define transparent AllAlpha<0>

// Are all pixels in the tile opaque?
//static bool opaque(const buf_mgr &src, const ILImage &img) {
//    int stride = img.pagesize.c;
//    char *s = src.buffer + img.pagesize.c - 1;
//    char *stop = src.buffer + img.pageSizeBytes;
//    while (s < stop && 255 == static_cast<unsigned char>(*s))
//        s += stride;
//    return (s >= stop);
//}

// Strip the alpha from an RGBA buffer, safe to use in place
static void RGBA2RGB(const char *start, const char *stop, char *target) {
    while (start < stop) {
        *target++ = *start++;
        *target++ = *start++;
        *target++ = *start++;
        start++; // Skip the alpha
    }
}

// Add opaque alpha to an RGB buffer, safe to use in place
// works backwards, from stop to start, the last pointer is the end of the source region
static void RGB2RGBA(const char *start, char *stop, const char *source_end) {
    while (start < stop) {
        *--stop = 0xff;
        *--stop = *--source_end;
        *--stop = *--source_end;
        *--stop = *--source_end;
    }
}

// Strip the alpha from an Luma Alpha buffer, fafe to use in place
static void LA2L(const char *start, const char *stop, char *target) {
    while (start < stop) {
        *target++ = *start++;
        start++; // Skip the alpha
    }
}

// Add opaque alpha to a Luma buffer, safe to use in place
// works backwards, from stop to start, the last pointer is the end of the source region
static void L2LA(const char *start, char *stop, const char *source_end) {
    while (start < stop) {
        *--stop = 0xff;
        *--stop = *--source_end;
    }
}

static CPLErr initBuffer(buf_mgr &b)
{
    b.buffer = (char *)(CPLMalloc(b.size));
    if (b.buffer != NULL)
        return CE_None;
    CPLError(CE_Failure, CPLE_OutOfMemory, "Allocating temporary JPNG buffer");
    return CE_Failure;
}

CPLErr JPNG_Band::Decompress(buf_mgr &dst, buf_mgr &src)
{
    CPLErr retval = CE_None;
    const static GUInt32 JPEG_SIG = 0xe0ffd8ff; // JPEG 4CC code
    const static GUInt32 PNG_SIG  = 0x474e5089;  // PNG 4CC code

    ILImage image(img);
    GUInt32 signature;
    memcpy(&signature, src.buffer, sizeof(GUInt32));

    if (signature == JPEG_SIG) {
        image.pagesize.c -= 1;
        JPEG_Codec codec(image);

        // JPEG decoder expects the destination size to be accurate
        buf_mgr temp = dst; // dst still owns the storage
        temp.size = (image.pagesize.c == 3) ? dst.size / 4 * 3 : dst.size / 2;

        retval = codec.DecompressJPEG(temp, src);
        if (CE_None == retval) { // add opaque alpha, in place
            if (image.pagesize.c == 3)
                RGB2RGBA(dst.buffer, dst.buffer + dst.size, temp.buffer + temp.size);
            else
                L2LA(dst.buffer, dst.buffer + dst.size, temp.buffer + temp.size);
        }
    }
    else { // Should be PNG
        assert(PNG_SIG == signature);
        PNG_Codec codec(image);
        // PNG codec expands to 4 bands
        return codec.DecompressPNG(dst, src);
    }

    return retval;
}

// The PNG internal palette is set on first band write
CPLErr JPNG_Band::Compress(buf_mgr &dst, buf_mgr &src)
{
    ILImage image(img);
    CPLErr retval = CE_None;

    buf_mgr temp = { NULL, img.pageSizeBytes };
    retval = initBuffer(temp);
    if (retval != CE_None)
        return retval;

    try {
        if (opaque(src, image)) { // If all pixels are opaque, compress as JPEG
            if (image.pagesize.c == 4)
                RGBA2RGB(src.buffer, src.buffer + src.size, temp.buffer);
            else
                LA2L(src.buffer, src.buffer + src.size, temp.buffer);

            image.pagesize.c -= 1; // RGB or Grayscale only for JPEG
            JPEG_Codec codec(image);
            codec.rgb = rgb;
            codec.optimize = optimize;
            codec.sameres = sameres;
            retval = codec.CompressJPEG(dst, temp);
        }
        else if (transparent(src, image)) {
            dst.size = 0; // Don't store fully transparent pages
        }
        else
        {
            PNG_Codec codec(image);
            codec.deflate_flags = deflate_flags;
            retval = codec.CompressPNG(dst, src);
        }
    }
    catch (CPLErr err) {
        retval = err;
    }

    CPLFree(temp.buffer);
    return retval;
}

/**
* \Brief For PPNG, builds the data structures needed to write the palette
* The presence of the PNGColors and PNGAlpha is used as a flag for PPNG only
*/

JPNG_Band::JPNG_Band(GDALMRFDataset *pDS, const ILImage &image, int b, int level) :
GDALMRFRasterBand(pDS, image, b, level),
rgb(FALSE), sameres(FALSE), optimize(false)

{   // Check error conditions
    if (image.dt != GDT_Byte) {
	CPLError(CE_Failure, CPLE_NotSupported, "Data type not supported by MRF JPNG");
	return;
    }
    if (image.order != IL_Interleaved || (image.pagesize.c != 4 && image.pagesize.c != 2)) {
	CPLError(CE_Failure, CPLE_NotSupported, "MRF JPNG can only handle 2 or 4 interleaved bands");
	return;
    }

    if (img.pagesize.c == 4) { // RGBA can have storage flavors
        CPLString const &pm = pDS->GetPhotometricInterpretation();
        if (pm == "RGB" || pm == "MULTISPECTRAL") { // Explicit RGB or MS
            rgb = TRUE;
            sameres = TRUE;
        }
        if (pm == "YCC")
            sameres = TRUE;
    }

    optimize = GetOptlist().FetchBoolean("OPTIMIZE", FALSE) != FALSE;

    // PNGs and JPGs can be larger than the source, especially for small page size
    poDS->SetPBufferSize(image.pageSizeBytes + 100);
}

JPNG_Band::~JPNG_Band() {
}

NAMESPACE_MRF_END
<|endoftext|>


<commit_before>/*
 * SerialSensorTest.cpp
 *
 *  Created on: 13 Sep 2015
 *      Author: jeremy
 */

#include "SensorTest.h"

#include <Source/Api/eXaDrumKit.h>

#include "../IO/SpiSensor.h"

using namespace eXaDrumKitApi;
using namespace std::chrono;

namespace Testing
{

	void SensorTest::RunTest()
	{

		std::string moduleLocation("/home/jeremy/Desktop/Prog/eXaDrums/eXaDrums/Data/");
		eXaDrumKit drumKit(moduleLocation.c_str());

		std::string kitLocation("Kits/default.xml");
		drumKit.LoadKit(kitLocation.c_str());

		// Create Sensor
		IO::Sensor sensor(0);

		// Add a trigger for drum id 0
		const int snareId = 0;
		drumKit.AddTrigger(snareId);

		// Start drum module
		drumKit.Start();

		int N = 500000;

		for(int i = 0; i < N; i++)
		{

			short value = sensor.Read();

			drumKit.Trig(snareId, value);

		}

		// Stop drum module
		drumKit.Stop();

		return;
	}

}

<commit_msg>Changed Sensor to SpiSensor in the test function.<commit_after>/*
 * SerialSensorTest.cpp
 *
 *  Created on: 13 Sep 2015
 *      Author: jeremy
 */

#include "SensorTest.h"

#include <Source/Api/eXaDrumKit.h>

#include "../IO/SpiSensor.h"

using namespace eXaDrumKitApi;
using namespace std::chrono;

namespace Testing
{

	void SensorTest::RunTest()
	{

		std::string moduleLocation("/home/jeremy/Desktop/Prog/eXaDrums/eXaDrums/Data/");
		eXaDrumKit drumKit(moduleLocation.c_str());

		std::string kitLocation("Kits/default.xml");
		drumKit.LoadKit(kitLocation.c_str());

		// Create Sensor
		IO::SpiSensor sensor(0);

		// Add a trigger for drum id 0
		const int snareId = 0;
		drumKit.AddTrigger(snareId);

		// Start drum module
		drumKit.Start();

		int N = 500000;

		for(int i = 0; i < N; i++)
		{

			short value = sensor.Read();

			drumKit.Trig(snareId, value);

		}

		// Stop drum module
		drumKit.Stop();

		return;
	}

}

<|endoftext|>


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

#include "qversitdefs_p.h"
#include "ut_qversit.h"
#include "qversitreader.h"
#include "qversitreader_p.h"
#include "qversitcontactimporter.h"
#include "qcontact.h"
#include "qcontactmanager.h"

#include <QtTest/QtTest>
#include <QDebug>
#include <QDir>
#include <QList>

QTM_BEGIN_NAMESPACE
class MyQVersitResourceHandler : public QVersitResourceHandler
{
public:
    MyQVersitResourceHandler() : mIndex(0)
    {
    }

    bool saveResource(const QByteArray& contents, const QVersitProperty& property,
                      QString* location)
    {
        Q_UNUSED(property)
        *location = QString::number(mIndex++);
        mObjects.insert(*location, contents);
        return true;
    }

    bool loadResource(const QString &location, QByteArray *contents, QString *mimeType)
    {
        Q_UNUSED(location)
        Q_UNUSED(contents)
        Q_UNUSED(mimeType)
        return false;
    }

    int mIndex;
    QMap<QString, QByteArray> mObjects;
};
QTM_END_NAMESPACE

QTM_USE_NAMESPACE

#ifndef TESTDATA_DIR
#define TESTDATA_DIR "./"
#endif

Q_DECLARE_METATYPE(QList<QContact>);

void UT_QVersit::testImportFiles()
{
    QFETCH(QString, filename);
    QFETCH(QByteArray, charset);
    QFETCH(QList<QContact>, expectedContacts);

    QVersitReader reader;
    QFile file(filename);
    QVERIFY2(file.open(QIODevice::ReadOnly), filename.toAscii());
    reader.setDevice(&file);
    if (charset != "") {
        reader.setDefaultCodec(QTextCodec::codecForName(charset));
    }
    QVERIFY(reader.startReading());
    QVERIFY(reader.waitForFinished());
    QList<QVersitDocument> documents = reader.results();
    QCOMPARE(reader.error(), QVersitReader::NoError);
    QVersitContactImporter importer;
    MyQVersitResourceHandler resourceHandler;
    importer.setResourceHandler(&resourceHandler);
    QList<QContact> contacts = importer.importContacts(documents);

    if (expectedContacts.size() > 0) {
        QCOMPARE(contacts.size(), expectedContacts.size());
        QListIterator<QContact> i(expectedContacts);
        foreach (QContact parsed, contacts) {
            QContact expected = i.next();
            QList<QContactDetail> expectedDetails = expected.details();
            foreach(QContactDetail expectedDetail, expectedDetails) {
                QString name = expectedDetail.definitionName();
                QContactDetail parsedDetail = parsed.detail(name);
                if (parsedDetail != expectedDetail) {
                    qDebug() << "Detail: " << name.toAscii();
                    qDebug() << "Actual:" << parsedDetail.variantValues();
                    qDebug() << "Expected:" << expectedDetail.variantValues();
                    QCOMPARE(parsedDetail, expectedDetail);
                }
            }
        }
    }
}

#define QTEST_NEW_ROW(filename,charset,contact) \
        QTest::newRow(filename) \
        << QString::fromAscii(TESTDATA_DIR "testdata/") + QString::fromAscii(filename) \
        << QByteArray(charset) \
        << (contact)

void UT_QVersit::testImportFiles_data()
{
    QTest::addColumn<QString>("filename");
    QTest::addColumn<QByteArray>("charset");
    QTest::addColumn<QList<QContact> >("expectedContacts");

    QTEST_NEW_ROW("AAB4/MultipleAll.vcf", "UTF-16BE", QList<QContact>());
    QTEST_NEW_ROW("AAB4/MultipleAscii.vcf", "", QList<QContact>());
    QTEST_NEW_ROW("AAB4/SingleCompany.vcf", "", QList<QContact>());
    QTEST_NEW_ROW("AAB4/SingleExtensive.vcf", "", QList<QContact>());
    QTEST_NEW_ROW("AAB4/SingleNonAscii.vcf", "UTF-16BE", QList<QContact>());
    QTEST_NEW_ROW("AAB4/SingleNonAsciiWithPhoto.vcf", "UTF-16BE", QList<QContact>());
    QTEST_NEW_ROW("AAB5/SingleNonAscii.vcf", "UTF-8", QList<QContact>());

    {
        QList<QContact> list;
        QContact contact;
        QContactName name;
        name.setCustomLabel(QLatin1String("Firstname Lastname"));
        name.setFirstName(QLatin1String("Firstname"));
        name.setLastName(QLatin1String("Lastname"));
        name.setMiddleName(QString());
        name.setPrefix(QLatin1String("Title"));
        name.setSuffix(QLatin1String("Suffix"));
        contact.saveDetail(&name);
        QContactOrganization org;
        org.setName(QLatin1String("Company Name"));
        org.setDepartment(QStringList(QLatin1String("Department Name")));
        org.setTitle(QLatin1String("Job title"));
        contact.saveDetail(&org);
        list.append(contact);
        QContactNote note;
        note.setNote(QLatin1String("This is a note field.  Pretty boring."));
        contact.saveDetail(&note);
        QContactUrl homeUrl;
        homeUrl.setUrl(QLatin1String("http://mywebpage.com"));
        homeUrl.setContexts(QContactDetail::ContextHome);
        contact.saveDetail(&homeUrl);
        QContactUrl workUrl;
        workUrl.setUrl(QLatin1String("http://workwebpage"));
        workUrl.setContexts(QContactDetail::ContextWork);
        contact.saveDetail(&workUrl);
        QTEST_NEW_ROW("Entourage11/basic.vcf", "UTF-16BE", list);
    }

    QTEST_NEW_ROW("Entourage11/image.vcf", "UTF-16BE", QList<QContact>());

    QTEST_NEW_ROW("Entourage11/nonascii.vcf", "UTF-16BE", QList<QContact>());

    {
        QList<QContact> list;
        QContact contact;
        QContactName name;
        name.setCustomLabel(QLatin1String("first last"));
        name.setFirstName(QLatin1String("first"));
        name.setLastName(QLatin1String("last"));
        name.setMiddleName(QString());
        name.setPrefix(QString());
        name.setSuffix(QString());
        contact.saveDetail(&name);
        QContactOrganization org;
        org.setName(QLatin1String("Nokia"));
        org.setDepartment(QStringList(QLatin1String("Qt DF")));
        contact.saveDetail(&org);
        list.append(contact);
        QTEST_NEW_ROW("Entourage12/basic.vcf", "", list);
    }

    QTEST_NEW_ROW("Entourage12/kevin.vcf", "UTF-8", QList<QContact>());
    QTEST_NEW_ROW("Entourage12/nonascii.vcf", "UTF-8", QList<QContact>());
    QTEST_NEW_ROW("gmail.vcf", "UTF-8", QList<QContact>());
}

QTEST_MAIN(UT_QVersit)
<commit_msg>Fix compile warning on Symbian<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qversitdefs_p.h"
#include "ut_qversit.h"
#include "qversitreader.h"
#include "qversitreader_p.h"
#include "qversitcontactimporter.h"
#include "qcontact.h"
#include "qcontactmanager.h"

#include <QtTest/QtTest>
#include <QDebug>
#include <QDir>
#include <QList>

QTM_BEGIN_NAMESPACE
class MyQVersitResourceHandler : public QVersitResourceHandler
{
public:
    MyQVersitResourceHandler() : mIndex(0)
    {
    }

    bool saveResource(const QByteArray& contents, const QVersitProperty& property,
                      QString* location)
    {
        Q_UNUSED(property)
        *location = QString::number(mIndex++);
        mObjects.insert(*location, contents);
        return true;
    }

    bool loadResource(const QString &location, QByteArray *contents, QString *mimeType)
    {
        Q_UNUSED(location)
        Q_UNUSED(contents)
        Q_UNUSED(mimeType)
        return false;
    }

    int mIndex;
    QMap<QString, QByteArray> mObjects;
};
QTM_END_NAMESPACE

QTM_USE_NAMESPACE

#ifndef TESTDATA_DIR
#define TESTDATA_DIR "./"
#endif

Q_DECLARE_METATYPE(QList<QContact>)

void UT_QVersit::testImportFiles()
{
    QFETCH(QString, filename);
    QFETCH(QByteArray, charset);
    QFETCH(QList<QContact>, expectedContacts);

    QVersitReader reader;
    QFile file(filename);
    QVERIFY2(file.open(QIODevice::ReadOnly), filename.toAscii());
    reader.setDevice(&file);
    if (charset != "") {
        reader.setDefaultCodec(QTextCodec::codecForName(charset));
    }
    QVERIFY(reader.startReading());
    QVERIFY(reader.waitForFinished());
    QList<QVersitDocument> documents = reader.results();
    QCOMPARE(reader.error(), QVersitReader::NoError);
    QVersitContactImporter importer;
    MyQVersitResourceHandler resourceHandler;
    importer.setResourceHandler(&resourceHandler);
    QList<QContact> contacts = importer.importContacts(documents);

    if (expectedContacts.size() > 0) {
        QCOMPARE(contacts.size(), expectedContacts.size());
        QListIterator<QContact> i(expectedContacts);
        foreach (QContact parsed, contacts) {
            QContact expected = i.next();
            QList<QContactDetail> expectedDetails = expected.details();
            foreach(QContactDetail expectedDetail, expectedDetails) {
                QString name = expectedDetail.definitionName();
                QContactDetail parsedDetail = parsed.detail(name);
                if (parsedDetail != expectedDetail) {
                    qDebug() << "Detail: " << name.toAscii();
                    qDebug() << "Actual:" << parsedDetail.variantValues();
                    qDebug() << "Expected:" << expectedDetail.variantValues();
                    QCOMPARE(parsedDetail, expectedDetail);
                }
            }
        }
    }
}

#define QTEST_NEW_ROW(filename,charset,contact) \
        QTest::newRow(filename) \
        << QString::fromAscii(TESTDATA_DIR "testdata/") + QString::fromAscii(filename) \
        << QByteArray(charset) \
        << (contact)

void UT_QVersit::testImportFiles_data()
{
    QTest::addColumn<QString>("filename");
    QTest::addColumn<QByteArray>("charset");
    QTest::addColumn<QList<QContact> >("expectedContacts");

    QTEST_NEW_ROW("AAB4/MultipleAll.vcf", "UTF-16BE", QList<QContact>());
    QTEST_NEW_ROW("AAB4/MultipleAscii.vcf", "", QList<QContact>());
    QTEST_NEW_ROW("AAB4/SingleCompany.vcf", "", QList<QContact>());
    QTEST_NEW_ROW("AAB4/SingleExtensive.vcf", "", QList<QContact>());
    QTEST_NEW_ROW("AAB4/SingleNonAscii.vcf", "UTF-16BE", QList<QContact>());
    QTEST_NEW_ROW("AAB4/SingleNonAsciiWithPhoto.vcf", "UTF-16BE", QList<QContact>());
    QTEST_NEW_ROW("AAB5/SingleNonAscii.vcf", "UTF-8", QList<QContact>());

    {
        QList<QContact> list;
        QContact contact;
        QContactName name;
        name.setCustomLabel(QLatin1String("Firstname Lastname"));
        name.setFirstName(QLatin1String("Firstname"));
        name.setLastName(QLatin1String("Lastname"));
        name.setMiddleName(QString());
        name.setPrefix(QLatin1String("Title"));
        name.setSuffix(QLatin1String("Suffix"));
        contact.saveDetail(&name);
        QContactOrganization org;
        org.setName(QLatin1String("Company Name"));
        org.setDepartment(QStringList(QLatin1String("Department Name")));
        org.setTitle(QLatin1String("Job title"));
        contact.saveDetail(&org);
        list.append(contact);
        QContactNote note;
        note.setNote(QLatin1String("This is a note field.  Pretty boring."));
        contact.saveDetail(&note);
        QContactUrl homeUrl;
        homeUrl.setUrl(QLatin1String("http://mywebpage.com"));
        homeUrl.setContexts(QContactDetail::ContextHome);
        contact.saveDetail(&homeUrl);
        QContactUrl workUrl;
        workUrl.setUrl(QLatin1String("http://workwebpage"));
        workUrl.setContexts(QContactDetail::ContextWork);
        contact.saveDetail(&workUrl);
        QTEST_NEW_ROW("Entourage11/basic.vcf", "UTF-16BE", list);
    }

    QTEST_NEW_ROW("Entourage11/image.vcf", "UTF-16BE", QList<QContact>());

    QTEST_NEW_ROW("Entourage11/nonascii.vcf", "UTF-16BE", QList<QContact>());

    {
        QList<QContact> list;
        QContact contact;
        QContactName name;
        name.setCustomLabel(QLatin1String("first last"));
        name.setFirstName(QLatin1String("first"));
        name.setLastName(QLatin1String("last"));
        name.setMiddleName(QString());
        name.setPrefix(QString());
        name.setSuffix(QString());
        contact.saveDetail(&name);
        QContactOrganization org;
        org.setName(QLatin1String("Nokia"));
        org.setDepartment(QStringList(QLatin1String("Qt DF")));
        contact.saveDetail(&org);
        list.append(contact);
        QTEST_NEW_ROW("Entourage12/basic.vcf", "", list);
    }

    QTEST_NEW_ROW("Entourage12/kevin.vcf", "UTF-8", QList<QContact>());
    QTEST_NEW_ROW("Entourage12/nonascii.vcf", "UTF-8", QList<QContact>());
    QTEST_NEW_ROW("gmail.vcf", "UTF-8", QList<QContact>());
}

QTEST_MAIN(UT_QVersit)
<|endoftext|>


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

Program:   The OpenIGTLink Library
Language:  C++
Web page:  http://openigtlink.org/

Copyright (c) Insight Software Consortium. All rights reserved.

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

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

#include "igtlMessageFactory.h"

#include "igtlTransformMessage.h"
#include "igtlPositionMessage.h"
#include "igtlImageMessage.h"
#include "igtlClientSocket.h"
#include "igtlStatusMessage.h"
#include "igtlCapabilityMessage.h"

#if OpenIGTLink_PROTOCOL_VERSION >= 2
#include "igtlPointMessage.h"
#include "igtlPolyDataMessage.h"
#include "igtlQuaternionTrackingDataMessage.h"
#include "igtlStringMessage.h"
#include "igtlTrackingDataMessage.h"
#include "igtlTrajectoryMessage.h"
#endif // OpenIGTLink_PROTOCOL_VERSION >= 2

#if OpenIGTLink_HEADER_VERSION >= 2
#include "igtlCommandMessage.h"
#endif // OpenIGTLink_PROTOCOL_VERSION >= 3

#include "igtl_header.h"

#include <algorithm>
#include <cassert>
#include <cstring>
#include <sstream>
#include <stdexcept>

namespace igtl
{

//-----------------------------------------------------------------------------
MessageFactory::MessageFactory()
{
  this->AddMessageType("TRANSFORM", (PointerToMessageBaseNew)&igtl::TransformMessage::New);
  this->AddMessageType("GET_TRANS", (PointerToMessageBaseNew)&igtl::GetTransformMessage::New);
  this->AddMessageType("POSITION", (PointerToMessageBaseNew)&igtl::PositionMessage::New);
  this->AddMessageType("IMAGE", (PointerToMessageBaseNew)&igtl::ImageMessage::New);
  this->AddMessageType("GET_IMAGE", (PointerToMessageBaseNew)&igtl::GetImageMessage::New);
  this->AddMessageType("STATUS", (PointerToMessageBaseNew)&igtl::StatusMessage::New);
  this->AddMessageType("GET_STATUS", (PointerToMessageBaseNew)&igtl::GetStatusMessage::New);
  this->AddMessageType("CAPABILITY", (PointerToMessageBaseNew)&igtl::CapabilityMessage::New);
#if OpenIGTLink_PROTOCOL_VERSION >= 2
  this->AddMessageType("POINT", (PointerToMessageBaseNew)&igtl::PointMessage::New);
  this->AddMessageType("GET_POINT", (PointerToMessageBaseNew)&igtl::GetPointMessage::New);
  this->AddMessageType("TRAJ", (PointerToMessageBaseNew)&igtl::TrajectoryMessage::New);
  this->AddMessageType("GET_TRAJ", (PointerToMessageBaseNew)&igtl::GetTrajectoryMessage::New);
  this->AddMessageType("STRING", (PointerToMessageBaseNew)&igtl::StringMessage::New);
  this->AddMessageType("TDATA", (PointerToMessageBaseNew)&igtl::TrackingDataMessage::New);
  this->AddMessageType("POLYDATA", (PointerToMessageBaseNew)&igtl::PolyDataMessage::New);
  this->AddMessageType("GET_POLYDATA", (PointerToMessageBaseNew)&igtl::GetPolyDataMessage::New);
  this->AddMessageType("RTS_POLYDATA", (PointerToMessageBaseNew)&igtl::RTSPolyDataMessage::New);
  this->AddMessageType("STT_POLYDATA", (PointerToMessageBaseNew)&igtl::StartPolyDataMessage::New);
  this->AddMessageType("STP_POLYDATA", (PointerToMessageBaseNew)&igtl::StopPolyDataMessage::New);
  this->AddMessageType("RTS_TDATA", (PointerToMessageBaseNew)&igtl::RTSTrackingDataMessage::New);
  this->AddMessageType("STT_TDATA", (PointerToMessageBaseNew)&igtl::StartTrackingDataMessage::New);
  this->AddMessageType("STP_TDATA", (PointerToMessageBaseNew)&igtl::StopTrackingDataMessage::New);
  this->AddMessageType("QTDATA", (PointerToMessageBaseNew)&igtl::QuaternionTrackingDataMessage::New);
  this->AddMessageType("RTS_QTDATA", (PointerToMessageBaseNew)&igtl::RTSQuaternionTrackingDataMessage::New);
  this->AddMessageType("STT_QTDATA", (PointerToMessageBaseNew)&igtl::StartQuaternionTrackingDataMessage::New);
  this->AddMessageType("STP_QTDATA", (PointerToMessageBaseNew)&igtl::StopQuaternionTrackingDataMessage::New);
#endif

#if OpenIGTLink_PROTOCOL_VERSION >= 3
  this->AddMessageType("COMMAND", (PointerToMessageBaseNew)&igtl::CommandMessage::New);
  this->AddMessageType("RTS_COMMAND", (PointerToMessageBaseNew)&igtl::RTSCommandMessage::New);
#endif
}

//-----------------------------------------------------------------------------
MessageFactory::~MessageFactory()
{
}

//-----------------------------------------------------------------------------
void MessageFactory::AddMessageType(const std::string& messageTypeName, MessageFactory::PointerToMessageBaseNew messageTypeNewPointer )
{
  this->IgtlMessageTypes[messageTypeName] = messageTypeNewPointer;
}

//----------------------------------------------------------------------------
MessageFactory::PointerToMessageBaseNew MessageFactory::GetMessageTypeNewPointer(const std::string& messageTypeName) const
{
  if ( this->IgtlMessageTypes.find(messageTypeName) != this->IgtlMessageTypes.end() )
    {
    return this->IgtlMessageTypes.find(messageTypeName)->second;
    }

  std::ostringstream oss;
  oss << "Error: In " __FILE__ ", line " << __LINE__ << ", unknown message type constructor requested." << std::endl;
  throw std::invalid_argument(oss.str());

  return NULL;
}

//-----------------------------------------------------------------------------
bool MessageFactory::IsValid(igtl::MessageHeader::Pointer headerMsg)
{
  bool result = false;

#if OpenIGTLink_HEADER_VERSION >= 2
  if (headerMsg.IsNotNull() && IgtlMessageTypes.find(headerMsg->GetMessageType()) != IgtlMessageTypes.end() )
#else
    if (headerMsg.IsNotNull() && IgtlMessageTypes.find(headerMsg->GetDeviceType()) != IgtlMessageTypes.end())
#endif
      {
      result = true;
      }
  return result;
}

//----------------------------------------------------------------------------
bool MessageFactory::IsValid(igtl::MessageHeader::Pointer headerMsg) const
{
  bool result = false;

#if OpenIGTLink_HEADER_VERSION >= 2
  if (headerMsg.IsNotNull() && IgtlMessageTypes.find(headerMsg->GetMessageType()) != IgtlMessageTypes.end() )
#else
    if (headerMsg.IsNotNull() && IgtlMessageTypes.find(headerMsg->GetDeviceType()) != IgtlMessageTypes.end())
#endif
      {
      result = true;
      }
  return result;
}

//-----------------------------------------------------------------------------
igtl::MessageBase::Pointer MessageFactory::GetMessage(igtl::MessageHeader::Pointer headerMsg)
{
  if (headerMsg.IsNull())
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", header is NULL." << std::endl;
    throw std::invalid_argument(oss.str());
    }

#if OpenIGTLink_HEADER_VERSION >= 2
  std::string messageType(headerMsg->GetMessageType());
#else
  std::string messageType(headerMsg->GetDeviceType());
#endif

  if (!this->IsValid(headerMsg))
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", receiving message of type:" << messageType << std::endl;
    throw std::invalid_argument(oss.str());
    }

  std::string messageTypeUpper(messageType);
  std::transform(messageTypeUpper.begin(), messageTypeUpper.end(), messageTypeUpper.begin(), ::toupper);

  igtl::MessageBase::Pointer result = NULL;
  if( GetMessageTypeNewPointer(messageTypeUpper) == NULL )
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", unable to create message of type:" << messageTypeUpper << std::endl;
    throw std::invalid_argument(oss.str());
    }
  result = GetMessageTypeNewPointer(messageTypeUpper)();

  // Must have a valid message at this point, otherwise its a programming bug.
  assert(result.IsNotNull());

  result->SetMessageHeader(headerMsg);
  result->InitBuffer();

  return result;
}

//----------------------------------------------------------------------------
igtl::MessageHeader::Pointer MessageFactory::CreateHeaderMessage(int headerVersion) const
{
  igtl::MessageHeader::Pointer headerMsg = igtl::MessageHeader::New();
  headerMsg->SetHeaderVersion(headerVersion);
  headerMsg->InitBuffer();

  return headerMsg;
}

//----------------------------------------------------------------------------
igtl::MessageBase::Pointer MessageFactory::CreateReceiveMessage(igtl::MessageHeader::Pointer headerMsg) const
{
  if (headerMsg.IsNull())
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", header is NULL." << std::endl;
    throw std::invalid_argument(oss.str());
    }

#if OpenIGTLink_HEADER_VERSION >= 2
  std::string messageType(headerMsg->GetMessageType());
#else
  std::string messageType(headerMsg->GetDeviceType());
#endif
  std::string messageTypeUpper(messageType);
  std::transform(messageTypeUpper.begin(), messageTypeUpper.end(), messageTypeUpper.begin(), ::toupper);

  if (!this->IsValid(headerMsg))
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", receiving message of type:" << messageTypeUpper << std::endl;
    throw std::invalid_argument(oss.str());
    }

  igtl::MessageBase::Pointer result = NULL;
  if( GetMessageTypeNewPointer(messageTypeUpper) == NULL )
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", unable to create message of type:" << messageTypeUpper << std::endl;
    throw std::invalid_argument(oss.str());
    }
  result = GetMessageTypeNewPointer(messageTypeUpper)();

  // Must have a valid message at this point, otherwise its a programming bug.
  assert(result.IsNotNull());

  result->SetMessageHeader(headerMsg);
  result->AllocateBuffer();

  return result;
}

//----------------------------------------------------------------------------
igtl::MessageBase::Pointer MessageFactory::CreateSendMessage(const std::string& messageType, int headerVersion) const
{
  if (messageType.empty())
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", message type is undefined." << std::endl;
    throw std::invalid_argument(oss.str());
    }

  std::string messageTypeUpper(messageType);
  std::transform(messageTypeUpper.begin(), messageTypeUpper.end(), messageTypeUpper.begin(), ::toupper);

  igtl::MessageBase::Pointer result = NULL;
  if( GetMessageTypeNewPointer(messageTypeUpper) == NULL )
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", unable to create message of type:" << messageTypeUpper << std::endl;
    throw std::invalid_argument(oss.str());
    }
  result = GetMessageTypeNewPointer(messageTypeUpper)();

  // Must have a valid message at this point, otherwise its a programming bug.
  assert(result.IsNotNull());

  result->SetDeviceType(messageTypeUpper);
  result->SetHeaderVersion(headerVersion);
  result->InitBuffer();
  return result;
}

//----------------------------------------------------------------------------
void MessageFactory::GetAvailableMessageTypes(std::vector<std::string>& types) const
{
  types.clear();
  for( std::map<std::string, PointerToMessageBaseNew>::const_iterator it = IgtlMessageTypes.begin(); it != IgtlMessageTypes.end(); ++it )
    {
    types.push_back(it->first);
    }

  return;
}

} // end namespace
<commit_msg>ENH: Add IMGMETA, GET_IMGMETA, LBMETA, and GET_LBMETA to message factory<commit_after>/*=========================================================================

Program:   The OpenIGTLink Library
Language:  C++
Web page:  http://openigtlink.org/

Copyright (c) Insight Software Consortium. All rights reserved.

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

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

#include "igtlMessageFactory.h"

#include "igtlTransformMessage.h"
#include "igtlPositionMessage.h"
#include "igtlImageMessage.h"
#include "igtlClientSocket.h"
#include "igtlStatusMessage.h"
#include "igtlCapabilityMessage.h"

#if OpenIGTLink_PROTOCOL_VERSION >= 2
#include "igtlPointMessage.h"
#include "igtlPolyDataMessage.h"
#include "igtlQuaternionTrackingDataMessage.h"
#include "igtlStringMessage.h"
#include "igtlTrackingDataMessage.h"
#include "igtlTrajectoryMessage.h"
#include "igtlImageMetaMessage.h"
#include "igtlLabelMetaMessage.h"
#endif // OpenIGTLink_PROTOCOL_VERSION >= 2

#if OpenIGTLink_HEADER_VERSION >= 2
#include "igtlCommandMessage.h"
#endif // OpenIGTLink_PROTOCOL_VERSION >= 3

#include "igtl_header.h"

#include <algorithm>
#include <cassert>
#include <cstring>
#include <sstream>
#include <stdexcept>

namespace igtl
{

//-----------------------------------------------------------------------------
MessageFactory::MessageFactory()
{
  this->AddMessageType("TRANSFORM", (PointerToMessageBaseNew)&igtl::TransformMessage::New);
  this->AddMessageType("GET_TRANS", (PointerToMessageBaseNew)&igtl::GetTransformMessage::New);
  this->AddMessageType("POSITION", (PointerToMessageBaseNew)&igtl::PositionMessage::New);
  this->AddMessageType("IMAGE", (PointerToMessageBaseNew)&igtl::ImageMessage::New);
  this->AddMessageType("GET_IMAGE", (PointerToMessageBaseNew)&igtl::GetImageMessage::New);
  this->AddMessageType("STATUS", (PointerToMessageBaseNew)&igtl::StatusMessage::New);
  this->AddMessageType("GET_STATUS", (PointerToMessageBaseNew)&igtl::GetStatusMessage::New);
  this->AddMessageType("CAPABILITY", (PointerToMessageBaseNew)&igtl::CapabilityMessage::New);
#if OpenIGTLink_PROTOCOL_VERSION >= 2
  this->AddMessageType("POINT", (PointerToMessageBaseNew)&igtl::PointMessage::New);
  this->AddMessageType("GET_POINT", (PointerToMessageBaseNew)&igtl::GetPointMessage::New);
  this->AddMessageType("TRAJ", (PointerToMessageBaseNew)&igtl::TrajectoryMessage::New);
  this->AddMessageType("GET_TRAJ", (PointerToMessageBaseNew)&igtl::GetTrajectoryMessage::New);
  this->AddMessageType("STRING", (PointerToMessageBaseNew)&igtl::StringMessage::New);
  this->AddMessageType("TDATA", (PointerToMessageBaseNew)&igtl::TrackingDataMessage::New);
  this->AddMessageType("POLYDATA", (PointerToMessageBaseNew)&igtl::PolyDataMessage::New);
  this->AddMessageType("GET_POLYDATA", (PointerToMessageBaseNew)&igtl::GetPolyDataMessage::New);
  this->AddMessageType("RTS_POLYDATA", (PointerToMessageBaseNew)&igtl::RTSPolyDataMessage::New);
  this->AddMessageType("STT_POLYDATA", (PointerToMessageBaseNew)&igtl::StartPolyDataMessage::New);
  this->AddMessageType("STP_POLYDATA", (PointerToMessageBaseNew)&igtl::StopPolyDataMessage::New);
  this->AddMessageType("RTS_TDATA", (PointerToMessageBaseNew)&igtl::RTSTrackingDataMessage::New);
  this->AddMessageType("STT_TDATA", (PointerToMessageBaseNew)&igtl::StartTrackingDataMessage::New);
  this->AddMessageType("STP_TDATA", (PointerToMessageBaseNew)&igtl::StopTrackingDataMessage::New);
  this->AddMessageType("QTDATA", (PointerToMessageBaseNew)&igtl::QuaternionTrackingDataMessage::New);
  this->AddMessageType("RTS_QTDATA", (PointerToMessageBaseNew)&igtl::RTSQuaternionTrackingDataMessage::New);
  this->AddMessageType("STT_QTDATA", (PointerToMessageBaseNew)&igtl::StartQuaternionTrackingDataMessage::New);
  this->AddMessageType("STP_QTDATA", (PointerToMessageBaseNew)&igtl::StopQuaternionTrackingDataMessage::New);
  this->AddMessageType("GET_IMGMETA", (PointerToMessageBaseNew)&igtl::GetImageMetaMessage::New);
  this->AddMessageType("IMGMETA", (PointerToMessageBaseNew)&igtl::ImageMetaMessage::New);
  this->AddMessageType("GET_LBMETA", (PointerToMessageBaseNew)&igtl::GetLabelMetaMessage::New);
  this->AddMessageType("LBMETA", (PointerToMessageBaseNew)&igtl::LabelMetaMessage::New);
#endif

#if OpenIGTLink_PROTOCOL_VERSION >= 3
  this->AddMessageType("COMMAND", (PointerToMessageBaseNew)&igtl::CommandMessage::New);
  this->AddMessageType("RTS_COMMAND", (PointerToMessageBaseNew)&igtl::RTSCommandMessage::New);
#endif
}

//-----------------------------------------------------------------------------
MessageFactory::~MessageFactory()
{
}

//-----------------------------------------------------------------------------
void MessageFactory::AddMessageType(const std::string& messageTypeName, MessageFactory::PointerToMessageBaseNew messageTypeNewPointer )
{
  this->IgtlMessageTypes[messageTypeName] = messageTypeNewPointer;
}

//----------------------------------------------------------------------------
MessageFactory::PointerToMessageBaseNew MessageFactory::GetMessageTypeNewPointer(const std::string& messageTypeName) const
{
  if ( this->IgtlMessageTypes.find(messageTypeName) != this->IgtlMessageTypes.end() )
    {
    return this->IgtlMessageTypes.find(messageTypeName)->second;
    }

  std::ostringstream oss;
  oss << "Error: In " __FILE__ ", line " << __LINE__ << ", unknown message type constructor requested." << std::endl;
  throw std::invalid_argument(oss.str());

  return NULL;
}

//-----------------------------------------------------------------------------
bool MessageFactory::IsValid(igtl::MessageHeader::Pointer headerMsg)
{
  bool result = false;

#if OpenIGTLink_HEADER_VERSION >= 2
  if (headerMsg.IsNotNull() && IgtlMessageTypes.find(headerMsg->GetMessageType()) != IgtlMessageTypes.end() )
#else
    if (headerMsg.IsNotNull() && IgtlMessageTypes.find(headerMsg->GetDeviceType()) != IgtlMessageTypes.end())
#endif
      {
      result = true;
      }
  return result;
}

//----------------------------------------------------------------------------
bool MessageFactory::IsValid(igtl::MessageHeader::Pointer headerMsg) const
{
  bool result = false;

#if OpenIGTLink_HEADER_VERSION >= 2
  if (headerMsg.IsNotNull() && IgtlMessageTypes.find(headerMsg->GetMessageType()) != IgtlMessageTypes.end() )
#else
    if (headerMsg.IsNotNull() && IgtlMessageTypes.find(headerMsg->GetDeviceType()) != IgtlMessageTypes.end())
#endif
      {
      result = true;
      }
  return result;
}

//-----------------------------------------------------------------------------
igtl::MessageBase::Pointer MessageFactory::GetMessage(igtl::MessageHeader::Pointer headerMsg)
{
  if (headerMsg.IsNull())
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", header is NULL." << std::endl;
    throw std::invalid_argument(oss.str());
    }

#if OpenIGTLink_HEADER_VERSION >= 2
  std::string messageType(headerMsg->GetMessageType());
#else
  std::string messageType(headerMsg->GetDeviceType());
#endif

  if (!this->IsValid(headerMsg))
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", receiving message of type:" << messageType << std::endl;
    throw std::invalid_argument(oss.str());
    }

  std::string messageTypeUpper(messageType);
  std::transform(messageTypeUpper.begin(), messageTypeUpper.end(), messageTypeUpper.begin(), ::toupper);

  igtl::MessageBase::Pointer result = NULL;
  if( GetMessageTypeNewPointer(messageTypeUpper) == NULL )
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", unable to create message of type:" << messageTypeUpper << std::endl;
    throw std::invalid_argument(oss.str());
    }
  result = GetMessageTypeNewPointer(messageTypeUpper)();

  // Must have a valid message at this point, otherwise its a programming bug.
  assert(result.IsNotNull());

  result->SetMessageHeader(headerMsg);
  result->InitBuffer();

  return result;
}

//----------------------------------------------------------------------------
igtl::MessageHeader::Pointer MessageFactory::CreateHeaderMessage(int headerVersion) const
{
  igtl::MessageHeader::Pointer headerMsg = igtl::MessageHeader::New();
  headerMsg->SetHeaderVersion(headerVersion);
  headerMsg->InitBuffer();

  return headerMsg;
}

//----------------------------------------------------------------------------
igtl::MessageBase::Pointer MessageFactory::CreateReceiveMessage(igtl::MessageHeader::Pointer headerMsg) const
{
  if (headerMsg.IsNull())
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", header is NULL." << std::endl;
    throw std::invalid_argument(oss.str());
    }

#if OpenIGTLink_HEADER_VERSION >= 2
  std::string messageType(headerMsg->GetMessageType());
#else
  std::string messageType(headerMsg->GetDeviceType());
#endif
  std::string messageTypeUpper(messageType);
  std::transform(messageTypeUpper.begin(), messageTypeUpper.end(), messageTypeUpper.begin(), ::toupper);

  if (!this->IsValid(headerMsg))
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", receiving message of type:" << messageTypeUpper << std::endl;
    throw std::invalid_argument(oss.str());
    }

  igtl::MessageBase::Pointer result = NULL;
  if( GetMessageTypeNewPointer(messageTypeUpper) == NULL )
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", unable to create message of type:" << messageTypeUpper << std::endl;
    throw std::invalid_argument(oss.str());
    }
  result = GetMessageTypeNewPointer(messageTypeUpper)();

  // Must have a valid message at this point, otherwise its a programming bug.
  assert(result.IsNotNull());

  result->SetMessageHeader(headerMsg);
  result->AllocateBuffer();

  return result;
}

//----------------------------------------------------------------------------
igtl::MessageBase::Pointer MessageFactory::CreateSendMessage(const std::string& messageType, int headerVersion) const
{
  if (messageType.empty())
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", message type is undefined." << std::endl;
    throw std::invalid_argument(oss.str());
    }

  std::string messageTypeUpper(messageType);
  std::transform(messageTypeUpper.begin(), messageTypeUpper.end(), messageTypeUpper.begin(), ::toupper);

  igtl::MessageBase::Pointer result = NULL;
  if( GetMessageTypeNewPointer(messageTypeUpper) == NULL )
    {
    std::ostringstream oss;
    oss << "Error: In " __FILE__ ", line " << __LINE__ << ", unable to create message of type:" << messageTypeUpper << std::endl;
    throw std::invalid_argument(oss.str());
    }
  result = GetMessageTypeNewPointer(messageTypeUpper)();

  // Must have a valid message at this point, otherwise its a programming bug.
  assert(result.IsNotNull());

  result->SetDeviceType(messageTypeUpper);
  result->SetHeaderVersion(headerVersion);
  result->InitBuffer();
  return result;
}

//----------------------------------------------------------------------------
void MessageFactory::GetAvailableMessageTypes(std::vector<std::string>& types) const
{
  types.clear();
  for( std::map<std::string, PointerToMessageBaseNew>::const_iterator it = IgtlMessageTypes.begin(); it != IgtlMessageTypes.end(); ++it )
    {
    types.push_back(it->first);
    }

  return;
}

} // end namespace
<|endoftext|>


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

#include "DiffManager.h"
#include "items/ObjectPathCrumb.h"
#include "handlers/HObjectPathCrumb.h"
#include "commands/CClear.h"
#include "commands/CDiff.h"
#include "commands/CHistory.h"
#include "VersionControlUIPlugin.h"

#include "Logger/src/Log.h"

#include "SelfTest/src/TestManager.h"

#include "InteractionBase/src/handlers/HSceneHandlerItem.h"
#include "InteractionBase/src/input_actions/ActionRegistry.h"

namespace VersionControlUI {

Logger::Log& VersionControlUIPlugin::log()
{
	static auto log = Logger::Log::getLogger("PLUGIN_NAME_LOWER");
	return *log;
}

bool VersionControlUIPlugin::initialize(Core::EnvisionManager&)
{
	VersionControlUI::ObjectPathCrumb::setDefaultClassHandler(HObjectPathCrumb::instance());

	Interaction::ActionRegistry::instance()->registerInputHandler("GenericHandler.NameChangeFilter",
																					  DiffManager::toggleNameChangeHighlights);

	Interaction::HSceneHandlerItem::instance()->addCommand(new CClear{});
	Interaction::HSceneHandlerItem::instance()->addCommand(new CDiff{});
	Interaction::HSceneHandlerItem::instance()->addCommand(new CHistory{});

	return true;
}

void VersionControlUIPlugin::unload()
{
}

void VersionControlUIPlugin::selfTest(QString testid)
{
	if (testid.isEmpty()) SelfTest::TestManager<VersionControlUIPlugin>::runAllTests().printResultStatistics();
	else SelfTest::TestManager<VersionControlUIPlugin>::runTest(testid).printResultStatistics();
}

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

#include "DiffManager.h"
#include "items/ObjectPathCrumb.h"
#include "handlers/HObjectPathCrumb.h"
#include "commands/CClear.h"
#include "commands/CDiff.h"
#include "commands/CHistory.h"

#include "Logger/src/Log.h"

#include "SelfTest/src/TestManager.h"

#include "InteractionBase/src/handlers/HSceneHandlerItem.h"
#include "InteractionBase/src/input_actions/ActionRegistry.h"

namespace VersionControlUI {

Logger::Log& VersionControlUIPlugin::log()
{
	static auto log = Logger::Log::getLogger("PLUGIN_NAME_LOWER");
	return *log;
}

bool VersionControlUIPlugin::initialize(Core::EnvisionManager&)
{
	VersionControlUI::ObjectPathCrumb::setDefaultClassHandler(HObjectPathCrumb::instance());

	Interaction::ActionRegistry::instance()->registerInputHandler("GenericHandler.NameChangeFilter",
																					  DiffManager::toggleNameChangeHighlights);

	Interaction::HSceneHandlerItem::instance()->addCommand(new CClear{});
	Interaction::HSceneHandlerItem::instance()->addCommand(new CDiff{});
	Interaction::HSceneHandlerItem::instance()->addCommand(new CHistory{});

	return true;
}

void VersionControlUIPlugin::unload()
{
}

void VersionControlUIPlugin::selfTest(QString testid)
{
	if (testid.isEmpty()) SelfTest::TestManager<VersionControlUIPlugin>::runAllTests().printResultStatistics();
	else SelfTest::TestManager<VersionControlUIPlugin>::runTest(testid).printResultStatistics();
}

}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include <dune/stuff/test/test_common.hh>

#include <dune/common/exceptions.hh>

#ifndef HAVE_ALUGRID
static_assert(false, "This test requires alugrid!");
#endif
#include <dune/grid/alugrid.hh>

#undef HAVE_FASP

#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
#include "elliptic-sipdg-discretization.hh"
#include "elliptic-swipdg-discretization.hh"

class errors_are_not_as_expected
  : public Dune::Exception
{};

typedef Dune::ALUConformGrid< 2, 2 > AluConform2dGridType;

// change this to toggle output
std::ostream& out = std::cout;
//std::ostream& out = DSC_LOG.devnull();

typedef testing::Types< EllipticTestCase::ESV07< AluConform2dGridType >
                      , EllipticTestCase::LocalThermalBlock< AluConform2dGridType >
                      , EllipticTestCase::ER07< AluConform2dGridType >
                      , EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >
                      , EllipticTestCase::Spe10Model1< AluConform2dGridType >
                      > AluConform2dTestCases;

template< class TestCase >
struct EllipticCGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    const TestCase test_case;
    test_case.print_header(out);
    out << std::endl;
    EllipticCG::EocStudy< TestCase, 1 > eoc_study(test_case);
    auto errors = eoc_study.run(out);
    for (const auto& norm : eoc_study.provided_norms())
      if (errors[norm] > eoc_study.expected_results(norm))
        DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
  }
};

TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results) {
  this->check();
}

template< class TestCase >
struct EllipticSIPDGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    if (std::is_same< TestCase, EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > > >::value) {
      std::cerr << "EllipticSIPDGDiscretization does not work for EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!";
    } else {
      const TestCase test_case;
      test_case.print_header(out);
      out << std::endl;
      size_t failure = 0;
      EllipticSIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
      auto errors_1 = eoc_study_1.run(out);
      out << std::endl;
      EllipticSIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
      auto errors_2 = eoc_study_2.run(out);
      for (const auto& norm : eoc_study_1.provided_norms())
        if (errors_1[norm] > eoc_study_1.expected_results(norm))
          ++failure;
      for (const auto& norm : eoc_study_2.provided_norms())
        if (errors_2[norm] > eoc_study_2.expected_results(norm))
          ++failure;
      if (failure)
        DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
    }
  }
};

TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) {
  this->check();
}

template< class TestCase >
struct EllipticSWIPDGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    const TestCase test_case;
    test_case.print_header(out);
    out << std::endl;
    size_t failure = 0;
    EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
    auto errors_1 = eoc_study_1.run(out);
    out << std::endl;
    EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
    auto errors_2 = eoc_study_2.run(out);
    for (const auto& norm : eoc_study_1.provided_norms())
      if (errors_1[norm] > eoc_study_1.expected_results(norm))
        ++failure;
    for (const auto& norm : eoc_study_2.provided_norms())
      if (errors_2[norm] > eoc_study_2.expected_results(norm))
        ++failure;
    if (failure)
      DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
  }
};

TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
  this->check();
}

int main(int argc, char** argv)
{
  try {
    test_init(argc, argv);
    return RUN_ALL_TESTS();
  } catch (Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
}
<commit_msg>[tests.elliptic-discretizations] added relative<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include <dune/stuff/test/test_common.hh>

#include <dune/common/exceptions.hh>

#ifndef HAVE_ALUGRID
static_assert(false, "This test requires alugrid!");
#endif
#include <dune/grid/alugrid.hh>

#undef HAVE_FASP

#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
#include "elliptic-sipdg-discretization.hh"
#include "elliptic-swipdg-discretization.hh"

class errors_are_not_as_expected
  : public Dune::Exception
{};

typedef Dune::ALUConformGrid< 2, 2 > AluConform2dGridType;

// change this to toggle output
std::ostream& out = std::cout;
//std::ostream& out = DSC_LOG.devnull();

typedef testing::Types< EllipticTestCase::ESV07< AluConform2dGridType >
                      , EllipticTestCase::LocalThermalBlock< AluConform2dGridType >
                      , EllipticTestCase::ER07< AluConform2dGridType >
                      , EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >
                      , EllipticTestCase::Spe10Model1< AluConform2dGridType >
                      > AluConform2dTestCases;

template< class TestCase >
struct EllipticCGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    const TestCase test_case;
    test_case.print_header(out);
    out << std::endl;
    EllipticCG::EocStudy< TestCase, 1 > eoc_study(test_case);
    auto errors = eoc_study.run(true, out);
    for (const auto& norm : eoc_study.provided_norms())
      if (errors[norm] > eoc_study.expected_results(norm))
        DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
  }
};

TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results) {
  this->check();
}

template< class TestCase >
struct EllipticSIPDGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    if (std::is_same< TestCase, EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > > >::value) {
      std::cerr << "EllipticSIPDGDiscretization does not work for EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!";
    } else {
      const TestCase test_case;
      test_case.print_header(out);
      out << std::endl;
      size_t failure = 0;
      EllipticSIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
      auto errors_1 = eoc_study_1.run(true, out);
      out << std::endl;
      EllipticSIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
      auto errors_2 = eoc_study_2.run(true, out);
      for (const auto& norm : eoc_study_1.provided_norms())
        if (errors_1[norm] > eoc_study_1.expected_results(norm))
          ++failure;
      for (const auto& norm : eoc_study_2.provided_norms())
        if (errors_2[norm] > eoc_study_2.expected_results(norm))
          ++failure;
      if (failure)
        DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
    }
  }
};

TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) {
  this->check();
}

template< class TestCase >
struct EllipticSWIPDGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    const TestCase test_case;
    test_case.print_header(out);
    out << std::endl;
    size_t failure = 0;
    EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
    auto errors_1 = eoc_study_1.run(true, out);
    out << std::endl;
    EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
    auto errors_2 = eoc_study_2.run(true, out);
    for (const auto& norm : eoc_study_1.provided_norms())
      if (errors_1[norm] > eoc_study_1.expected_results(norm))
        ++failure;
    for (const auto& norm : eoc_study_2.provided_norms())
      if (errors_2[norm] > eoc_study_2.expected_results(norm))
        ++failure;
    if (failure)
      DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
  }
};

TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
  this->check();
}

int main(int argc, char** argv)
{
  try {
    test_init(argc, argv);
    return RUN_ALL_TESTS();
  } catch (Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
}
<|endoftext|>


<commit_before>#pragma once

namespace odlib
{
    namespace utils
    {
        namespace number
        {
            template<typename T>
            const bool is_float(const std::basic_string<T>& text)
            {
                float number;

                std::basic_istringstream<T> stream(text);
                stream >> std::noskipws >> number;

                return stream.eof() && (stream.fail() == false);
            }

            template<typename T>
            const bool is_integer(const std::basic_string<T>& text, const std::locale& locale = std::locale())
            {
                if (text.length() == 0)
                {
                    return false;
                }

                for (size_t i = 0; i < text.length(); i++)
                {
                    if (std::isdigit(text[i], locale) == false)
                    {
                        return false;
                    }
                }

                return true;
            }
        }
    }
}<commit_msg>Add "numeric::is_valid"<commit_after>#pragma once

namespace odlib
{
    namespace utils
    {
        namespace number
        {
            template<typename T>
            const bool is_float(const std::basic_string<T>& text)
            {
                float number;

                std::basic_istringstream<T> stream(text);
                stream >> std::noskipws >> number;

                return stream.eof() && (stream.fail() == false);
            }

            template<typename T>
            const bool is_integer(const std::basic_string<T>& text, const std::locale& locale = std::locale())
            {
                if (text.length() == 0)
                {
                    return false;
                }

                for (size_t i = 0; i < text.length(); i++)
                {
                    if (std::isdigit(text[i], locale) == false)
                    {
                        return false;
                    }
                }

                return true;
            }

            template<typename T, typename Elem>
            const bool is_valid(const std::basic_string<Elem>& text)
            {
                T value;

                std::basic_istringstream<Elem> stream(text);
                stream >> value;

                return stream.eof() && (stream.fail() == false);
            }
        }
    }
}<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include <dune/stuff/test/test_common.hh>

#include <dune/common/exceptions.hh>

#ifndef HAVE_ALUGRID
static_assert(false, "This test requires alugrid!");
#endif
#include <dune/grid/alugrid.hh>

#undef HAVE_FASP

#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
#include "elliptic-sipdg-discretization.hh"
#include "elliptic-swipdg-discretization.hh"

class errors_are_not_as_expected
  : public Dune::Exception
{};

typedef Dune::ALUConformGrid< 2, 2 > AluConform2dGridType;

// change this to toggle output
std::ostream& out = std::cout;
//std::ostream& out = DSC_LOG.devnull();

typedef testing::Types< EllipticTestCase::ESV07< AluConform2dGridType >
                      , EllipticTestCase::LocalThermalBlock< AluConform2dGridType >
                      , EllipticTestCase::ER07< AluConform2dGridType >
                      , EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >
                      , EllipticTestCase::Spe10Model1< AluConform2dGridType >
                      > AluConform2dTestCases;

template< class TestCase >
struct EllipticCGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    const TestCase test_case;
    test_case.print_header(out);
    out << std::endl;
    EllipticCG::EocStudy< TestCase, 1 > eoc_study(test_case);
    auto errors = eoc_study.run(true, out);
    for (const auto& norm : eoc_study.provided_norms())
      if (errors[norm] > eoc_study.expected_results(norm))
        DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
  }
};

TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results) {
  this->check();
}

template< class TestCase >
struct EllipticSIPDGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    if (std::is_same< TestCase, EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > > >::value) {
      std::cerr << "EllipticSIPDGDiscretization does not work for EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!";
    } else {
      const TestCase test_case;
      test_case.print_header(out);
      out << std::endl;
      size_t failure = 0;
      EllipticSIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
      auto errors_1 = eoc_study_1.run(true, out);
      out << std::endl;
      EllipticSIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
      auto errors_2 = eoc_study_2.run(true, out);
      for (const auto& norm : eoc_study_1.provided_norms())
        if (errors_1[norm] > eoc_study_1.expected_results(norm))
          ++failure;
      for (const auto& norm : eoc_study_2.provided_norms())
        if (errors_2[norm] > eoc_study_2.expected_results(norm))
          ++failure;
      if (failure)
        DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
    }
  }
};

TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) {
  this->check();
}

template< class TestCase >
struct EllipticSWIPDGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    const TestCase test_case;
    test_case.print_header(out);
    out << std::endl;
    size_t failure = 0;
    EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
    auto errors_1 = eoc_study_1.run(true, out);
    out << std::endl;
    EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
    auto errors_2 = eoc_study_2.run(true, out);
    for (const auto& norm : eoc_study_1.provided_norms())
      if (errors_1[norm] > eoc_study_1.expected_results(norm))
        ++failure;
    for (const auto& norm : eoc_study_2.provided_norms())
      if (errors_2[norm] > eoc_study_2.expected_results(norm))
        ++failure;
    if (failure)
      DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
  }
};

TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
  this->check();
}

int main(int argc, char** argv)
{
  try {
    test_init(argc, argv);
    return RUN_ALL_TESTS();
  } catch (Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
}
<commit_msg>[tests.elliptic-discretizations] update<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include <dune/stuff/test/test_common.hh>

#include <dune/common/exceptions.hh>

#ifndef HAVE_ALUGRID
static_assert(false, "This test requires alugrid!");
#endif
#include <dune/grid/alugrid.hh>

#undef HAVE_FASP

#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
#include "elliptic-sipdg-discretization.hh"
#include "elliptic-swipdg-discretization.hh"

class errors_are_not_as_expected
  : public Dune::Exception
{};

typedef Dune::ALUConformGrid< 2, 2 > AluConform2dGridType;

// change this to toggle output
std::ostream& out = std::cout;
//std::ostream& out = DSC_LOG.devnull();

typedef testing::Types< EllipticTestCase::ESV07< AluConform2dGridType >
                      , EllipticTestCase::LocalThermalBlock< AluConform2dGridType >
                      , EllipticTestCase::ER07< AluConform2dGridType >
                      , EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >
                      , EllipticTestCase::Spe10Model1< AluConform2dGridType >
                      > AluConform2dTestCases;

template< class TestCase >
struct EllipticCGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    const TestCase test_case;
    test_case.print_header(out);
    out << std::endl;
    EllipticCG::EocStudy< TestCase, 1 > eoc_study(test_case);
    auto errors = eoc_study.run(out);
    for (const auto& norm : eoc_study.provided_norms())
      if (errors[norm] > eoc_study.expected_results(norm))
        DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
  }
};

TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results) {
  this->check();
}

template< class TestCase >
struct EllipticSIPDGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    if (std::is_same< TestCase, EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > > >::value) {
      std::cerr << "EllipticSIPDGDiscretization does not work for EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!";
    } else {
      const TestCase test_case;
      test_case.print_header(out);
      out << std::endl;
      size_t failure = 0;
      EllipticSIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
      auto errors_1 = eoc_study_1.run(out);
      out << std::endl;
      EllipticSIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
      auto errors_2 = eoc_study_2.run(out);
      for (const auto& norm : eoc_study_1.provided_norms())
        if (errors_1[norm] > eoc_study_1.expected_results(norm))
          ++failure;
      for (const auto& norm : eoc_study_2.provided_norms())
        if (errors_2[norm] > eoc_study_2.expected_results(norm))
          ++failure;
      if (failure)
        DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
    }
  }
};

TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) {
  this->check();
}

template< class TestCase >
struct EllipticSWIPDGDiscretization
  : public ::testing::Test
{
  void check() const
  {
    const TestCase test_case;
    test_case.print_header(out);
    out << std::endl;
    size_t failure = 0;
    EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
    auto errors_1 = eoc_study_1.run(out);
    out << std::endl;
    EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
    auto errors_2 = eoc_study_2.run(out);
    for (const auto& norm : eoc_study_1.provided_norms())
      if (errors_1[norm] > eoc_study_1.expected_results(norm))
        ++failure;
    for (const auto& norm : eoc_study_2.provided_norms())
      if (errors_2[norm] > eoc_study_2.expected_results(norm))
        ++failure;
    if (failure)
      DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!");
  }
};

TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
  this->check();
}

int main(int argc, char** argv)
{
  try {
    test_init(argc, argv);
    return RUN_ALL_TESTS();
  } catch (Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
    std::abort();
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    std::abort();
  } catch (...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
    std::abort();
  } // try
}
<|endoftext|>