<commit_before>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008 Nokia Corporation
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/KeyFile>

#include "debug-internal.h"

#include <QtCore/QByteArray>
#include <QtCore/QFile>
#include <QtCore/QHash>

namespace Telepathy
{

struct KeyFile::Private
{
    QString fileName;
    KeyFile::Status status;
    QHash<QString, QHash<QString, QByteArray> > groups;
    QString currentGroup;

    Private();
    Private(const QString &fName);

    void setFileName(const QString &fName);
    void setError(KeyFile::Status status, const QString &reason);
    bool read();

    bool validateKey(const QByteArray &data, int from, int to, QString &result);
    bool unescapeString(const QByteArray &data, int from, int to, QString &result) const;
    bool unescapeStringList(const QByteArray &data, int from, int to, QStringList &result) const;

    QStringList allGroups() const;
    QStringList allKeys() const;
    QStringList keys() const;
    bool contains(const QString &key) const;
    QString rawValue(const QString &key) const;
    QString value(const QString &key) const;
    QStringList valueAsStringList(const QString &key) const;
};

KeyFile::Private::Private()
    : status(KeyFile::None)
{
}

KeyFile::Private::Private(const QString &fName)
    : fileName(fName),
      status(KeyFile::NoError)
{
    read();
}

void KeyFile::Private::setFileName(const QString &fName)
{
    fileName = fName;
    status = KeyFile::NoError;
    currentGroup = QString();
    groups.clear();
    read();
}

void KeyFile::Private::setError(KeyFile::Status st, const QString &reason)
{
    warning() << QString("ERROR: filename(%1) reason(%2)")
                         .arg(fileName).arg(reason);
    status = st;
    groups.clear();
}

bool KeyFile::Private::read()
{
    QFile file(fileName);
    if (!file.exists()) {
        setError(KeyFile::NotFoundError,
                 "file does not exist");
        return false;
    }

    if (!file.open(QFile::ReadOnly)) {
        setError(KeyFile::AccessError,
                 "cannot open file for readonly access");
        return false;
    }

    QByteArray data;
    QByteArray group;
    QString currentGroup;
    QHash<QString, QByteArray> groupMap;
    QByteArray rawValue;
    int line = 0;
    int idx;
    while (!file.atEnd()) {
        data = file.readLine().trimmed();
        line++;

        if (data.size() == 0) {
            // skip empty lines
            continue;
        }

        char ch = data.at(0);
        if (ch == '#') {
            // skip comments
            continue;
        }
        else if (ch == '[') {
            if (groupMap.size()) {
                groups[currentGroup] = groupMap;
                groupMap.clear();
            }

            idx = data.indexOf(']');
            if (idx == -1) {
                // line starts with [ and it's not a group
                setError(KeyFile::FormatError,
                         QString("invalid group at line %2 - missing ']'")
                                 .arg(line));
                return false;
            }

            group = data.mid(1, idx - 1).trimmed();
            if (groups.contains(group)) {
                setError(KeyFile::FormatError,
                         QString("duplicated group '%1' at line %2")
                                 .arg(group.constData()).arg(line));
                return false;
            }

            currentGroup = "";
            if (!unescapeString(group, 0, group.size(), currentGroup)) {
                setError(KeyFile::FormatError,
                         QString("invalid group '%1' at line %2")
                                 .arg(currentGroup).arg(line));
                return false;
            }
        }
        else {
            idx = data.indexOf('=');
            if (idx == -1) {
                setError(KeyFile::FormatError,
                         QString("format error at line %1 - missing '='")
                                 .arg(line));
                return false;
            }

            // remove trailing spaces
            char ch;
            int idxKeyEnd = idx;
            while ((ch = data.at(idxKeyEnd - 1)) == ' ' || ch == '\t') {
                --idxKeyEnd;
            }

            QString key;
            if (!validateKey(data, 0, idxKeyEnd, key)) {
                setError(KeyFile::FormatError,
                         QString("invalid key '%1' at line %2")
                                 .arg(key).arg(line));
                return false;
            }

            if (groupMap.contains(key)) {
                setError(KeyFile::FormatError,
                         QString("duplicated key '%1' on group '%2' at line %3")
                                 .arg(key).arg(currentGroup).arg(line));
                return false;
            }

            data = data.mid(idx + 1).trimmed();
            rawValue = data.mid(0, data.size());
            groupMap[key] = rawValue;
        }
    }

    if (groupMap.size()) {
        groups[currentGroup] = groupMap;
        groupMap.clear();
    }

    return true;
}

bool KeyFile::Private::validateKey(const QByteArray &data, int from, int to, QString &result)
{
    int i = from;
    bool ret = true;
    while (i < to) {
        uint ch = data.at(i++);
        if (!((ch >= 'a' && ch <= 'z') ||
              (ch >= 'A' && ch <= 'Z') ||
              (ch >= '0' && ch <= '9') ||
              (ch == '-'))) {
            ret = false;
        }
        result += ch;
    }
    return ret;
}

bool KeyFile::Private::unescapeString(const QByteArray &data, int from, int to, QString &result) const
{
    int i = from;
    while (i < to) {
        uint ch = data.at(i++);

        if (ch == '\\') {
            if (i == to) {
                result += '\\';
                return true;
            }

            char nextCh = data.at(i++);
            switch (nextCh) {
                case 's':
                    result += ' ';
                    break;
                case 'n':
                    result += '\n';
                    break;
                case 't':
                    result += '\t';
                    break;
                case 'r':
                    result += '\r';
                    break;
                case ';':
                    result += ";";
                    break;
                case '\\':
                    result += '\\';
                    break;
                default:
                    return false;
            }
        }
        else {
            result += ch;
        }
    }

    return true;
}

bool KeyFile::Private::unescapeStringList(const QByteArray &data, int from, int to, QStringList &result) const
{
    QByteArray value;
    QList<QByteArray> valueList;
    int i = from;
    QChar ch;
    while (i < to) {
        ch = data.at(i++);

        if (ch == '\\') {
            value += ch;
            if (i < to) {
                value += data.at(i++);
                continue;
            }
            else {
                valueList << value;
                break;
            }
        }
        else if (ch == ';') {
            valueList << value;
            value = "";
        }
        else {
            value += ch;
        }
    }

    Q_FOREACH (value, valueList) {
        QString str;
        if (!unescapeString(value, 0, value.size(), str)) {
            return false;
        }
        result << str;
    }

    return true;
}

QStringList KeyFile::Private::allGroups() const
{
    return groups.keys();
}

QStringList KeyFile::Private::allKeys() const
{
    QStringList keys;
    QHash<QString, QHash<QString, QByteArray> >::const_iterator itrGroups = groups.begin();
    while (itrGroups != groups.end()) {
        keys << itrGroups.value().keys();
        ++itrGroups;
    }
    return keys;
}

QStringList KeyFile::Private::keys() const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    return groupMap.keys();
}

bool KeyFile::Private::contains(const QString &key) const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    return groupMap.contains(key);
}

QString KeyFile::Private::rawValue(const QString &key) const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    QByteArray rawValue = groupMap.value(key);
    return QString(rawValue);
}

QString KeyFile::Private::value(const QString &key) const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    QString result;
    QByteArray rawValue = groupMap.value(key);
    if (unescapeString(rawValue, 0, rawValue.size(), result)) {
        return result;
    }
    return QString();
}

QStringList KeyFile::Private::valueAsStringList(const QString &key) const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    QStringList result;
    QByteArray rawValue = groupMap.value(key);
    if (unescapeStringList(rawValue, 0, rawValue.size(), result)) {
        return result;
    }
    return QStringList();
}

/**
 * \class KeyFile
 * \headerfile <TelepathyQt4/key-file.h> <TelepathyQt4/KeyFile>
 *
 * The KeyFile class provides an easy way to read key-pair files such as INI
 * style files and .desktop files.
 *
 * It follows the rules regarding string escaping as defined in
 * http://standards.freedesktop.org/desktop-entry-spec/latest/index.html
 */

/**
 * Create a KeyFile object used to read (key-pair) compliant files.
 *
 * The status will be KeyFile::None
 * \sa setFileName()
 */
KeyFile::KeyFile()
    : mPriv(new Private())
{
}

/**
 * Create a KeyFile object used to read (key-pair) compliant files.
 *
 * \param fileName Name of the file to be read.
 */
KeyFile::KeyFile(const QString &fileName)
    : mPriv(new Private(fileName))
{
}

/**
 * Class destructor.
 */
KeyFile::~KeyFile()
{
    delete mPriv;
}

/**
 * Set the name of the file to be read.
 *
 * \param fileName Name of the file to be read.
 */
void KeyFile::setFileName(const QString &fileName)
{
    mPriv->setFileName(fileName);
}

/**
 * Return the name of the file associated with this object.
 *
 * \return Name of the file associated with this object.
 */
QString KeyFile::fileName() const
{
    return mPriv->fileName;
}

/**
 * Return a status code indicating the first error that was met by #KeyFile,
 * or KeyFile::NoError if no error occurred.
 *
 * Make sure to use this method if you set the filename to be read using
 * setFileName().
 *
 * \return Status code.
 * \sa setFileName()
 */
KeyFile::Status KeyFile::status() const
{
    return mPriv->status;
}

/**
 * Set the current group to be used while reading keys.
 *
 * Query functions such as keys(), contains() and value() are based on this
 * group.
 *
 * By default a empty group is used as the group for global
 * keys and is used as the default group if none is set.
 *
 * \param group Name of the group to be used.
 * \sa group()
 */
void KeyFile::setGroup(const QString &group)
{
    mPriv->currentGroup = group;
}

/**
 * Return the current group.
 *
 * \return Name of the current group.
 * \sa setGroup()
 */
QString KeyFile::group() const
{
    return mPriv->currentGroup;
}

/**
 * Return all groups in the desktop file.
 *
 * Global keys will be added to a empty group.
 *
 * \return List of all groups in the desktop file.
 */
QStringList KeyFile::allGroups() const
{
    return mPriv->allGroups();
}

/**
 * Return all keys described in the desktop file.
 *
 * \return List of all keys in the desktop file.
 */
QStringList KeyFile::allKeys() const
{
    return mPriv->allKeys();
}

/**
 * Return a list of keys in the current group.
 *
 * \return List of all keys in the current group.
 * \sa group(), setGroup()
 */
QStringList KeyFile::keys() const
{
    return mPriv->keys();
}

/**
 * Check if the current group contains a key named \a key.
 *
 * \return true if \a key exists, false otherwise.
 * \sa group(), setGroup()
 */
bool KeyFile::contains(const QString &key) const
{
    return mPriv->contains(key);
}

/**
 * Get the raw value for the key in the current group named \a key.
 *
 * The raw value is the value as is in the key file.
 *
 * \return Value of \a key, empty string if not found.
 * \sa group(), setGroup()
 */
QString KeyFile::rawValue(const QString &key) const
{
    return mPriv->rawValue(key);
}

/**
 * Get the value for the key in the current group named \a key.
 *
 * Escape sequences in the value are interpreted as defined in:
 * http://standards.freedesktop.org/desktop-entry-spec/latest/
 *
 * \return Value of \a key, empty string if not found or an error occurred.
 * \sa group(), setGroup()
 */
QString KeyFile::value(const QString &key) const
{
    return mPriv->value(key);
}

/**
 * Get the value for the key in the current group named \a key as a list.
 *
 * Return a list containing all strings on this key separated by ';'.
 * Escape sequences in the value are interpreted as defined in:
 * http://standards.freedesktop.org/desktop-entry-spec/latest/
 *
 * \return Value of \a key as a list, empty string list if not found or an error occurred.
 * \sa group(), setGroup()
 */
QStringList KeyFile::valueAsStringList(const QString &key) const
{
    return mPriv->valueAsStringList(key);
}

}
<commit_msg>Changed KeyFile key validation to also accept ".", "_" and "@" as valid characters.<commit_after>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008 Nokia Corporation
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/KeyFile>

#include "debug-internal.h"

#include <QtCore/QByteArray>
#include <QtCore/QFile>
#include <QtCore/QHash>

namespace Telepathy
{

struct KeyFile::Private
{
    QString fileName;
    KeyFile::Status status;
    QHash<QString, QHash<QString, QByteArray> > groups;
    QString currentGroup;

    Private();
    Private(const QString &fName);

    void setFileName(const QString &fName);
    void setError(KeyFile::Status status, const QString &reason);
    bool read();

    bool validateKey(const QByteArray &data, int from, int to, QString &result);
    bool unescapeString(const QByteArray &data, int from, int to, QString &result) const;
    bool unescapeStringList(const QByteArray &data, int from, int to, QStringList &result) const;

    QStringList allGroups() const;
    QStringList allKeys() const;
    QStringList keys() const;
    bool contains(const QString &key) const;
    QString rawValue(const QString &key) const;
    QString value(const QString &key) const;
    QStringList valueAsStringList(const QString &key) const;
};

KeyFile::Private::Private()
    : status(KeyFile::None)
{
}

KeyFile::Private::Private(const QString &fName)
    : fileName(fName),
      status(KeyFile::NoError)
{
    read();
}

void KeyFile::Private::setFileName(const QString &fName)
{
    fileName = fName;
    status = KeyFile::NoError;
    currentGroup = QString();
    groups.clear();
    read();
}

void KeyFile::Private::setError(KeyFile::Status st, const QString &reason)
{
    warning() << QString("ERROR: filename(%1) reason(%2)")
                         .arg(fileName).arg(reason);
    status = st;
    groups.clear();
}

bool KeyFile::Private::read()
{
    QFile file(fileName);
    if (!file.exists()) {
        setError(KeyFile::NotFoundError,
                 "file does not exist");
        return false;
    }

    if (!file.open(QFile::ReadOnly)) {
        setError(KeyFile::AccessError,
                 "cannot open file for readonly access");
        return false;
    }

    QByteArray data;
    QByteArray group;
    QString currentGroup;
    QHash<QString, QByteArray> groupMap;
    QByteArray rawValue;
    int line = 0;
    int idx;
    while (!file.atEnd()) {
        data = file.readLine().trimmed();
        line++;

        if (data.size() == 0) {
            // skip empty lines
            continue;
        }

        char ch = data.at(0);
        if (ch == '#') {
            // skip comments
            continue;
        }
        else if (ch == '[') {
            if (groupMap.size()) {
                groups[currentGroup] = groupMap;
                groupMap.clear();
            }

            idx = data.indexOf(']');
            if (idx == -1) {
                // line starts with [ and it's not a group
                setError(KeyFile::FormatError,
                         QString("invalid group at line %2 - missing ']'")
                                 .arg(line));
                return false;
            }

            group = data.mid(1, idx - 1).trimmed();
            if (groups.contains(group)) {
                setError(KeyFile::FormatError,
                         QString("duplicated group '%1' at line %2")
                                 .arg(group.constData()).arg(line));
                return false;
            }

            currentGroup = "";
            if (!unescapeString(group, 0, group.size(), currentGroup)) {
                setError(KeyFile::FormatError,
                         QString("invalid group '%1' at line %2")
                                 .arg(currentGroup).arg(line));
                return false;
            }
        }
        else {
            idx = data.indexOf('=');
            if (idx == -1) {
                setError(KeyFile::FormatError,
                         QString("format error at line %1 - missing '='")
                                 .arg(line));
                return false;
            }

            // remove trailing spaces
            char ch;
            int idxKeyEnd = idx;
            while ((ch = data.at(idxKeyEnd - 1)) == ' ' || ch == '\t') {
                --idxKeyEnd;
            }

            QString key;
            if (!validateKey(data, 0, idxKeyEnd, key)) {
                setError(KeyFile::FormatError,
                         QString("invalid key '%1' at line %2")
                                 .arg(key).arg(line));
                return false;
            }

            if (groupMap.contains(key)) {
                setError(KeyFile::FormatError,
                         QString("duplicated key '%1' on group '%2' at line %3")
                                 .arg(key).arg(currentGroup).arg(line));
                return false;
            }

            data = data.mid(idx + 1).trimmed();
            rawValue = data.mid(0, data.size());
            groupMap[key] = rawValue;
        }
    }

    if (groupMap.size()) {
        groups[currentGroup] = groupMap;
        groupMap.clear();
    }

    return true;
}

bool KeyFile::Private::validateKey(const QByteArray &data, int from, int to, QString &result)
{
    int i = from;
    bool ret = true;
    while (i < to) {
        uint ch = data.at(i++);
        // as an extension to the Desktop Entry spec, we allow "_", "." and "@"
        // as valid key characters - "_" and "." are needed for keys that are
        // D-Bus property names, and GKeyFile and KConfigIniBackend also accept
        // all three of those characters.
        if (!((ch >= 'a' && ch <= 'z') ||
              (ch >= 'A' && ch <= 'Z') ||
              (ch >= '0' && ch <= '9') ||
              (ch == '-') || (ch == '_') ||
              (ch == '.') || (ch == '@'))) {
            ret = false;
        }
        result += ch;
    }
    return ret;
}

bool KeyFile::Private::unescapeString(const QByteArray &data, int from, int to, QString &result) const
{
    int i = from;
    while (i < to) {
        uint ch = data.at(i++);

        if (ch == '\\') {
            if (i == to) {
                result += '\\';
                return true;
            }

            char nextCh = data.at(i++);
            switch (nextCh) {
                case 's':
                    result += ' ';
                    break;
                case 'n':
                    result += '\n';
                    break;
                case 't':
                    result += '\t';
                    break;
                case 'r':
                    result += '\r';
                    break;
                case ';':
                    result += ";";
                    break;
                case '\\':
                    result += '\\';
                    break;
                default:
                    return false;
            }
        }
        else {
            result += ch;
        }
    }

    return true;
}

bool KeyFile::Private::unescapeStringList(const QByteArray &data, int from, int to, QStringList &result) const
{
    QByteArray value;
    QList<QByteArray> valueList;
    int i = from;
    QChar ch;
    while (i < to) {
        ch = data.at(i++);

        if (ch == '\\') {
            value += ch;
            if (i < to) {
                value += data.at(i++);
                continue;
            }
            else {
                valueList << value;
                break;
            }
        }
        else if (ch == ';') {
            valueList << value;
            value = "";
        }
        else {
            value += ch;
        }
    }

    Q_FOREACH (value, valueList) {
        QString str;
        if (!unescapeString(value, 0, value.size(), str)) {
            return false;
        }
        result << str;
    }

    return true;
}

QStringList KeyFile::Private::allGroups() const
{
    return groups.keys();
}

QStringList KeyFile::Private::allKeys() const
{
    QStringList keys;
    QHash<QString, QHash<QString, QByteArray> >::const_iterator itrGroups = groups.begin();
    while (itrGroups != groups.end()) {
        keys << itrGroups.value().keys();
        ++itrGroups;
    }
    return keys;
}

QStringList KeyFile::Private::keys() const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    return groupMap.keys();
}

bool KeyFile::Private::contains(const QString &key) const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    return groupMap.contains(key);
}

QString KeyFile::Private::rawValue(const QString &key) const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    QByteArray rawValue = groupMap.value(key);
    return QString(rawValue);
}

QString KeyFile::Private::value(const QString &key) const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    QString result;
    QByteArray rawValue = groupMap.value(key);
    if (unescapeString(rawValue, 0, rawValue.size(), result)) {
        return result;
    }
    return QString();
}

QStringList KeyFile::Private::valueAsStringList(const QString &key) const
{
    QHash<QString, QByteArray> groupMap = groups[currentGroup];
    QStringList result;
    QByteArray rawValue = groupMap.value(key);
    if (unescapeStringList(rawValue, 0, rawValue.size(), result)) {
        return result;
    }
    return QStringList();
}

/**
 * \class KeyFile
 * \headerfile <TelepathyQt4/key-file.h> <TelepathyQt4/KeyFile>
 *
 * The KeyFile class provides an easy way to read key-pair files such as INI
 * style files and .desktop files.
 *
 * It follows the rules regarding string escaping as defined in
 * http://standards.freedesktop.org/desktop-entry-spec/latest/index.html
 */

/**
 * Create a KeyFile object used to read (key-pair) compliant files.
 *
 * The status will be KeyFile::None
 * \sa setFileName()
 */
KeyFile::KeyFile()
    : mPriv(new Private())
{
}

/**
 * Create a KeyFile object used to read (key-pair) compliant files.
 *
 * \param fileName Name of the file to be read.
 */
KeyFile::KeyFile(const QString &fileName)
    : mPriv(new Private(fileName))
{
}

/**
 * Class destructor.
 */
KeyFile::~KeyFile()
{
    delete mPriv;
}

/**
 * Set the name of the file to be read.
 *
 * \param fileName Name of the file to be read.
 */
void KeyFile::setFileName(const QString &fileName)
{
    mPriv->setFileName(fileName);
}

/**
 * Return the name of the file associated with this object.
 *
 * \return Name of the file associated with this object.
 */
QString KeyFile::fileName() const
{
    return mPriv->fileName;
}

/**
 * Return a status code indicating the first error that was met by #KeyFile,
 * or KeyFile::NoError if no error occurred.
 *
 * Make sure to use this method if you set the filename to be read using
 * setFileName().
 *
 * \return Status code.
 * \sa setFileName()
 */
KeyFile::Status KeyFile::status() const
{
    return mPriv->status;
}

/**
 * Set the current group to be used while reading keys.
 *
 * Query functions such as keys(), contains() and value() are based on this
 * group.
 *
 * By default a empty group is used as the group for global
 * keys and is used as the default group if none is set.
 *
 * \param group Name of the group to be used.
 * \sa group()
 */
void KeyFile::setGroup(const QString &group)
{
    mPriv->currentGroup = group;
}

/**
 * Return the current group.
 *
 * \return Name of the current group.
 * \sa setGroup()
 */
QString KeyFile::group() const
{
    return mPriv->currentGroup;
}

/**
 * Return all groups in the desktop file.
 *
 * Global keys will be added to a empty group.
 *
 * \return List of all groups in the desktop file.
 */
QStringList KeyFile::allGroups() const
{
    return mPriv->allGroups();
}

/**
 * Return all keys described in the desktop file.
 *
 * \return List of all keys in the desktop file.
 */
QStringList KeyFile::allKeys() const
{
    return mPriv->allKeys();
}

/**
 * Return a list of keys in the current group.
 *
 * \return List of all keys in the current group.
 * \sa group(), setGroup()
 */
QStringList KeyFile::keys() const
{
    return mPriv->keys();
}

/**
 * Check if the current group contains a key named \a key.
 *
 * \return true if \a key exists, false otherwise.
 * \sa group(), setGroup()
 */
bool KeyFile::contains(const QString &key) const
{
    return mPriv->contains(key);
}

/**
 * Get the raw value for the key in the current group named \a key.
 *
 * The raw value is the value as is in the key file.
 *
 * \return Value of \a key, empty string if not found.
 * \sa group(), setGroup()
 */
QString KeyFile::rawValue(const QString &key) const
{
    return mPriv->rawValue(key);
}

/**
 * Get the value for the key in the current group named \a key.
 *
 * Escape sequences in the value are interpreted as defined in:
 * http://standards.freedesktop.org/desktop-entry-spec/latest/
 *
 * \return Value of \a key, empty string if not found or an error occurred.
 * \sa group(), setGroup()
 */
QString KeyFile::value(const QString &key) const
{
    return mPriv->value(key);
}

/**
 * Get the value for the key in the current group named \a key as a list.
 *
 * Return a list containing all strings on this key separated by ';'.
 * Escape sequences in the value are interpreted as defined in:
 * http://standards.freedesktop.org/desktop-entry-spec/latest/
 *
 * \return Value of \a key as a list, empty string list if not found or an error occurred.
 * \sa group(), setGroup()
 */
QStringList KeyFile::valueAsStringList(const QString &key) const
{
    return mPriv->valueAsStringList(key);
}

}
<|endoftext|>


<commit_before>//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <charles.dubout@idiap.ch>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License version 3 as published by the Free Software Foundation.
//
// FFLDv2 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 Affero
// General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------

#include "Scene.h"

#include <algorithm>
#include <iostream>
#include <sstream>

#include <libxml/parser.h>

using namespace FFLD;
using namespace std;

Scene::Scene() : width_(0), height_(0), depth_(0)
{
}

Scene::Scene(int width, int height, int depth, const string & filename,
			 const vector<Object> & objects) : width_(width), height_(height), depth_(depth),
filename_(filename), objects_(objects)
{
}

bool Scene::empty() const
{
	return ((width() <= 0) || (height() <= 0) || (depth() <= 0) || filename().empty()) &&
		   objects().empty();
}

template <typename Result>
static inline Result content(const xmlNodePtr cur)
{
	if ((cur == NULL) || (cur->xmlChildrenNode == NULL))
		return Result();

	istringstream iss(reinterpret_cast<const char *>(cur->xmlChildrenNode->content));
	std::cout << "Content str " << iss.str() << std::endl;
	Result result;
	istringstream(iss.str()) >> skipws >> result;
	return result;
}

Scene::Scene(const string & filename)
{
	// const string Names[20] =
	// {
	// 	"aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
	// 	"diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa",
	// 	"train", "tvmonitor"
	// };

        const string Names[80] =
        {
            "airplane", "apple", "backpack", "banana", "baseball bat",
            "baseball glove", "bear", "bed", "bench", "bicycle", "bird",
            "boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
            "car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
            "cow", "cup", "dining table", "dog", "donut", "elephant",
            "fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
            "handbag", "horse", "hot dog", "keyboard", "kite", "knife",
            "laptop", "microwave", "motorcycle", "mouse", "orange",
            "oven", "parking meter", "person", "pizza", "potted plant",
            "refrigerator", "remote", "sandwich", "scissors", "sheep",
            "sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
            "stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
            "tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
            "truck", "tv", "umbrella", "vase", "wine", "zebra"
        };

	const string Poses[4] =
	{
		"Frontal", "Left", "Rear", "Right"
	};

	xmlDoc * doc = xmlParseFile(filename.c_str());

	if (doc == NULL) {
		cerr << "Could not open " << filename << endl;
		return;
	}

	xmlNodePtr cur = xmlDocGetRootElement(doc);

	if (cur == NULL) {
		xmlFreeDoc(doc);
		cerr << "Could not open " << filename << endl;
		return;
	}

	if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("annotation"))) {
		xmlFreeDoc(doc);
		cerr << "Could not open " << filename << endl;
		return;
	}

	cur = cur->xmlChildrenNode;

	while (cur != NULL) {
		if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("filename"))) {
			// Full path
			size_t last = filename.rfind('/');

			if (last != string::npos) {
				last = filename.rfind('/', last - 1);

				if (last != string::npos)
					filename_ = filename.substr(0, last) + "/JPEGImages/" +
								content<string>(cur);
			}
		}
		else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("size"))) {
			xmlNodePtr cur2 = cur->xmlChildrenNode;

			while (cur2 != NULL) {
				if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("width")))
					width_ = content<int>(cur2);
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("height")))
					height_ = content<int>(cur2);
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("depth")))
					depth_ = content<int>(cur2);

				cur2 = cur2->next;
			}
		}
		else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("object"))) {
			objects_.push_back(Object());

			xmlNodePtr cur2 = cur->xmlChildrenNode;

			while (cur2 != NULL) {
				if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("name"))) {
					std::cout << "XML Name " << content<string>(cur2) << std::endl;
					const string * iter =
						find(Names, Names + 80, content<string>(cur2));

					if (iter != Names + 80)
						objects_.back().setName(static_cast<Object::Name>(iter - Names));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("pose"))) {
					const string * iter =
						find(Poses, Poses + 4, content<string>(cur2));

					if (iter != Poses + 4)
						objects_.back().setPose(static_cast<Object::Pose>(iter - Poses));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("truncated"))) {
					objects_.back().setTruncated(content<bool>(cur2));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("difficult"))) {
					objects_.back().setDifficult(content<bool>(cur2));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("bndbox"))) {
					Rectangle bndbox;

					xmlNodePtr cur3 = cur2->xmlChildrenNode;

					while (cur3 != NULL) {
						if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmin")))
							bndbox.setX(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymin")))
							bndbox.setY(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmax")))
							bndbox.setWidth(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymax")))
							bndbox.setHeight(content<int>(cur3));

						cur3 = cur3->next;
					}

					// Only set the bounding box if all values have been assigned
					if (bndbox.x() && bndbox.y() && bndbox.width() && bndbox.height()) {
						bndbox.setX(bndbox.x() - 1);
						bndbox.setY(bndbox.y() - 1);
						bndbox.setWidth(bndbox.width() - bndbox.x());
						bndbox.setHeight(bndbox.height() - bndbox.y());
						objects_.back().setBndbox(bndbox);
					}
				}

				cur2 = cur2->next;
			}
		}

		cur = cur->next;
	}

	xmlFreeDoc(doc);
}

int Scene::width() const
{
	return width_;
}

void Scene::setWidth(int width)
{
	width_ = width;
}

int Scene::height() const
{
	return height_;
}

void Scene::setHeight(int height)
{
	height_ = height;
}

int Scene::depth() const
{
	return depth_;
}

void Scene::setDepth(int depth)
{
	depth_ = depth;
}

const string & Scene::filename() const
{
	return filename_;
}

void Scene::setFilename(const string &filename)
{
	filename_ = filename;
}

const vector<Object> & Scene::objects() const
{
	return objects_;
}

void Scene::setObjects(const vector<Object> &objects)
{
	objects_ = objects;
}

ostream & FFLD::operator<<(ostream & os, const Scene & scene)
{
	os << scene.width() << ' ' << scene.height() << ' ' << scene.depth() << ' '
	   << scene.objects().size() << ' ' << scene.filename() << endl;

	for (int i = 0; i < scene.objects().size(); ++i)
		os << scene.objects()[i] << endl;

	return os;
}

istream & FFLD::operator>>(istream & is, Scene & scene)
{
	int width, height, depth, nbObjects;

    is >> width >> height >> depth >> nbObjects;
	is.get(); // Remove the space

	string filename;
	getline(is, filename);

	vector<Object> objects(nbObjects);

	for (int i = 0; i < nbObjects; ++i)
		is >> objects[i];

	if (!is) {
		scene = Scene();
		return is;
	}

	scene = Scene(width, height, depth, filename, objects);

	return is;
}
<commit_msg>test str<commit_after>//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <charles.dubout@idiap.ch>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License version 3 as published by the Free Software Foundation.
//
// FFLDv2 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 Affero
// General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------

#include "Scene.h"

#include <algorithm>
#include <iostream>
#include <sstream>

#include <libxml/parser.h>

using namespace FFLD;
using namespace std;

Scene::Scene() : width_(0), height_(0), depth_(0)
{
}

Scene::Scene(int width, int height, int depth, const string & filename,
			 const vector<Object> & objects) : width_(width), height_(height), depth_(depth),
filename_(filename), objects_(objects)
{
}

bool Scene::empty() const
{
	return ((width() <= 0) || (height() <= 0) || (depth() <= 0) || filename().empty()) &&
		   objects().empty();
}

template <typename Result>
static inline Result content(const xmlNodePtr cur)
{
	if ((cur == NULL) || (cur->xmlChildrenNode == NULL))
		return Result();

	istringstream iss(reinterpret_cast<const string&>(cur->xmlChildrenNode->content));
	Result result;
	iss >> result;
	// istringstream iss(reinterpret_cast<const char *>(cur->xmlChildrenNode->content));
	// Result result;
	// iss >> result;
	return result;
}

Scene::Scene(const string & filename)
{
	// const string Names[20] =
	// {
	// 	"aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
	// 	"diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa",
	// 	"train", "tvmonitor"
	// };

        const string Names[80] =
        {
            "airplane", "apple", "backpack", "banana", "baseball bat",
            "baseball glove", "bear", "bed", "bench", "bicycle", "bird",
            "boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
            "car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
            "cow", "cup", "dining table", "dog", "donut", "elephant",
            "fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
            "handbag", "horse", "hot dog", "keyboard", "kite", "knife",
            "laptop", "microwave", "motorcycle", "mouse", "orange",
            "oven", "parking meter", "person", "pizza", "potted plant",
            "refrigerator", "remote", "sandwich", "scissors", "sheep",
            "sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
            "stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
            "tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
            "truck", "tv", "umbrella", "vase", "wine", "zebra"
        };

	const string Poses[4] =
	{
		"Frontal", "Left", "Rear", "Right"
	};

	xmlDoc * doc = xmlParseFile(filename.c_str());

	if (doc == NULL) {
		cerr << "Could not open " << filename << endl;
		return;
	}

	xmlNodePtr cur = xmlDocGetRootElement(doc);

	if (cur == NULL) {
		xmlFreeDoc(doc);
		cerr << "Could not open " << filename << endl;
		return;
	}

	if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("annotation"))) {
		xmlFreeDoc(doc);
		cerr << "Could not open " << filename << endl;
		return;
	}

	cur = cur->xmlChildrenNode;

	while (cur != NULL) {
		if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("filename"))) {
			// Full path
			size_t last = filename.rfind('/');

			if (last != string::npos) {
				last = filename.rfind('/', last - 1);

				if (last != string::npos)
					filename_ = filename.substr(0, last) + "/JPEGImages/" +
								content<string>(cur);
			}
		}
		else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("size"))) {
			xmlNodePtr cur2 = cur->xmlChildrenNode;

			while (cur2 != NULL) {
				if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("width")))
					width_ = content<int>(cur2);
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("height")))
					height_ = content<int>(cur2);
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("depth")))
					depth_ = content<int>(cur2);

				cur2 = cur2->next;
			}
		}
		else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("object"))) {
			objects_.push_back(Object());

			xmlNodePtr cur2 = cur->xmlChildrenNode;

			while (cur2 != NULL) {
				if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("name"))) {
					std::cout << "XML Name " << content<string>(cur2) << std::endl;
					const string * iter =
						find(Names, Names + 80, content<string>(cur2));

					if (iter != Names + 80)
						objects_.back().setName(static_cast<Object::Name>(iter - Names));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("pose"))) {
					const string * iter =
						find(Poses, Poses + 4, content<string>(cur2));

					if (iter != Poses + 4)
						objects_.back().setPose(static_cast<Object::Pose>(iter - Poses));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("truncated"))) {
					objects_.back().setTruncated(content<bool>(cur2));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("difficult"))) {
					objects_.back().setDifficult(content<bool>(cur2));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("bndbox"))) {
					Rectangle bndbox;

					xmlNodePtr cur3 = cur2->xmlChildrenNode;

					while (cur3 != NULL) {
						if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmin")))
							bndbox.setX(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymin")))
							bndbox.setY(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmax")))
							bndbox.setWidth(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymax")))
							bndbox.setHeight(content<int>(cur3));

						cur3 = cur3->next;
					}

					// Only set the bounding box if all values have been assigned
					if (bndbox.x() && bndbox.y() && bndbox.width() && bndbox.height()) {
						bndbox.setX(bndbox.x() - 1);
						bndbox.setY(bndbox.y() - 1);
						bndbox.setWidth(bndbox.width() - bndbox.x());
						bndbox.setHeight(bndbox.height() - bndbox.y());
						objects_.back().setBndbox(bndbox);
					}
				}

				cur2 = cur2->next;
			}
		}

		cur = cur->next;
	}

	xmlFreeDoc(doc);
}

int Scene::width() const
{
	return width_;
}

void Scene::setWidth(int width)
{
	width_ = width;
}

int Scene::height() const
{
	return height_;
}

void Scene::setHeight(int height)
{
	height_ = height;
}

int Scene::depth() const
{
	return depth_;
}

void Scene::setDepth(int depth)
{
	depth_ = depth;
}

const string & Scene::filename() const
{
	return filename_;
}

void Scene::setFilename(const string &filename)
{
	filename_ = filename;
}

const vector<Object> & Scene::objects() const
{
	return objects_;
}

void Scene::setObjects(const vector<Object> &objects)
{
	objects_ = objects;
}

ostream & FFLD::operator<<(ostream & os, const Scene & scene)
{
	os << scene.width() << ' ' << scene.height() << ' ' << scene.depth() << ' '
	   << scene.objects().size() << ' ' << scene.filename() << endl;

	for (int i = 0; i < scene.objects().size(); ++i)
		os << scene.objects()[i] << endl;

	return os;
}

istream & FFLD::operator>>(istream & is, Scene & scene)
{
	int width, height, depth, nbObjects;

    is >> width >> height >> depth >> nbObjects;
	is.get(); // Remove the space

	string filename;
	getline(is, filename);

	vector<Object> objects(nbObjects);

	for (int i = 0; i < nbObjects; ++i)
		is >> objects[i];

	if (!is) {
		scene = Scene();
		return is;
	}

	scene = Scene(width, height, depth, filename, objects);

	return is;
}
<|endoftext|>


<commit_before>//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <charles.dubout@idiap.ch>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License version 3 as published by the Free Software Foundation.
//
// FFLDv2 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 Affero
// General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------

#include "Scene.h"

#include <algorithm>
#include <iostream>
#include <sstream>

#include <libxml/parser.h>

using namespace FFLD;
using namespace std;

Scene::Scene() : width_(0), height_(0), depth_(0)
{
}

Scene::Scene(int width, int height, int depth, const string & filename,
			 const vector<Object> & objects) : width_(width), height_(height), depth_(depth),
filename_(filename), objects_(objects)
{
}

bool Scene::empty() const
{
	return ((width() <= 0) || (height() <= 0) || (depth() <= 0) || filename().empty()) &&
		   objects().empty();
}

template <typename Result>
static inline Result content(const xmlNodePtr cur)
{
	if ((cur == NULL) || (cur->xmlChildrenNode == NULL))
		return Result();

	istringstream iss(reinterpret_cast<const char *>(cur->xmlChildrenNode->content));
	Result result;
	iss >> noskipws >> result;
	return result;
}

Scene::Scene(const string & filename)
{
	// const string Names[20] =
	// {
	// 	"aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
	// 	"diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa",
	// 	"train", "tvmonitor"
	// };

        const string Names[80] =
        {
            "airplane", "apple", "backpack", "banana", "baseball bat",
            "baseball glove", "bear", "bed", "bench", "bicycle", "bird",
            "boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
            "car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
            "cow", "cup", "dining table", "dog", "donut", "elephant",
            "fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
            "handbag", "horse", "hot dog", "keyboard", "kite", "knife",
            "laptop", "microwave", "motorcycle", "mouse", "orange",
            "oven", "parking meter", "person", "pizza", "potted plant",
            "refrigerator", "remote", "sandwich", "scissors", "sheep",
            "sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
            "stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
            "tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
            "truck", "tv", "umbrella", "vase", "wine", "zebra"
        };

	const string Poses[4] =
	{
		"Frontal", "Left", "Rear", "Right"
	};

	xmlDoc * doc = xmlParseFile(filename.c_str());

	if (doc == NULL) {
		cerr << "Could not open " << filename << endl;
		return;
	}

	xmlNodePtr cur = xmlDocGetRootElement(doc);

	if (cur == NULL) {
		xmlFreeDoc(doc);
		cerr << "Could not open " << filename << endl;
		return;
	}

	if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("annotation"))) {
		xmlFreeDoc(doc);
		cerr << "Could not open " << filename << endl;
		return;
	}

	cur = cur->xmlChildrenNode;

	while (cur != NULL) {
		if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("filename"))) {
			// Full path
			size_t last = filename.rfind('/');

			if (last != string::npos) {
				last = filename.rfind('/', last - 1);

				if (last != string::npos)
					filename_ = filename.substr(0, last) + "/JPEGImages/" +
								content<string>(cur);
			}
		}
		else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("size"))) {
			xmlNodePtr cur2 = cur->xmlChildrenNode;

			while (cur2 != NULL) {
				if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("width")))
					width_ = content<int>(cur2);
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("height")))
					height_ = content<int>(cur2);
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("depth")))
					depth_ = content<int>(cur2);

				cur2 = cur2->next;
			}
		}
		else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("object"))) {
			objects_.push_back(Object());

			xmlNodePtr cur2 = cur->xmlChildrenNode;

			while (cur2 != NULL) {
				if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("name"))) {
					std::cout << "XML Name " << content<string>(cur2) << std::endl;
					const string * iter =
						find(Names, Names + 80, content<string>(cur2));

					if (iter != Names + 80)
						objects_.back().setName(static_cast<Object::Name>(iter - Names));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("pose"))) {
					const string * iter =
						find(Poses, Poses + 4, content<string>(cur2));

					if (iter != Poses + 4)
						objects_.back().setPose(static_cast<Object::Pose>(iter - Poses));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("truncated"))) {
					objects_.back().setTruncated(content<bool>(cur2));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("difficult"))) {
					objects_.back().setDifficult(content<bool>(cur2));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("bndbox"))) {
					Rectangle bndbox;

					xmlNodePtr cur3 = cur2->xmlChildrenNode;

					while (cur3 != NULL) {
						if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmin")))
							bndbox.setX(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymin")))
							bndbox.setY(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmax")))
							bndbox.setWidth(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymax")))
							bndbox.setHeight(content<int>(cur3));

						cur3 = cur3->next;
					}

					// Only set the bounding box if all values have been assigned
					if (bndbox.x() && bndbox.y() && bndbox.width() && bndbox.height()) {
						bndbox.setX(bndbox.x() - 1);
						bndbox.setY(bndbox.y() - 1);
						bndbox.setWidth(bndbox.width() - bndbox.x());
						bndbox.setHeight(bndbox.height() - bndbox.y());
						objects_.back().setBndbox(bndbox);
					}
				}

				cur2 = cur2->next;
			}
		}

		cur = cur->next;
	}

	xmlFreeDoc(doc);
}

int Scene::width() const
{
	return width_;
}

void Scene::setWidth(int width)
{
	width_ = width;
}

int Scene::height() const
{
	return height_;
}

void Scene::setHeight(int height)
{
	height_ = height;
}

int Scene::depth() const
{
	return depth_;
}

void Scene::setDepth(int depth)
{
	depth_ = depth;
}

const string & Scene::filename() const
{
	return filename_;
}

void Scene::setFilename(const string &filename)
{
	filename_ = filename;
}

const vector<Object> & Scene::objects() const
{
	return objects_;
}

void Scene::setObjects(const vector<Object> &objects)
{
	objects_ = objects;
}

ostream & FFLD::operator<<(ostream & os, const Scene & scene)
{
	os << scene.width() << ' ' << scene.height() << ' ' << scene.depth() << ' '
	   << scene.objects().size() << ' ' << scene.filename() << endl;

	for (int i = 0; i < scene.objects().size(); ++i)
		os << scene.objects()[i] << endl;

	return os;
}

istream & FFLD::operator>>(istream & is, Scene & scene)
{
	int width, height, depth, nbObjects;

    is >> width >> height >> depth >> nbObjects;
	is.get(); // Remove the space

	string filename;
	getline(is, filename);

	vector<Object> objects(nbObjects);

	for (int i = 0; i < nbObjects; ++i)
		is >> objects[i];

	if (!is) {
		scene = Scene();
		return is;
	}

	scene = Scene(width, height, depth, filename, objects);

	return is;
}
<commit_msg>ad cout xml content<commit_after>//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <charles.dubout@idiap.ch>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License version 3 as published by the Free Software Foundation.
//
// FFLDv2 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 Affero
// General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------

#include "Scene.h"

#include <algorithm>
#include <iostream>
#include <sstream>

#include <libxml/parser.h>

using namespace FFLD;
using namespace std;

Scene::Scene() : width_(0), height_(0), depth_(0)
{
}

Scene::Scene(int width, int height, int depth, const string & filename,
			 const vector<Object> & objects) : width_(width), height_(height), depth_(depth),
filename_(filename), objects_(objects)
{
}

bool Scene::empty() const
{
	return ((width() <= 0) || (height() <= 0) || (depth() <= 0) || filename().empty()) &&
		   objects().empty();
}

template <typename Result>
static inline Result content(const xmlNodePtr cur)
{
	if ((cur == NULL) || (cur->xmlChildrenNode == NULL))
		return Result();

	istringstream iss(reinterpret_cast<const char *>(cur->xmlChildrenNode->content));
	std::cout << "Content " << iss.str() << std::endl;
	Result result;
	iss >> noskipws >> result;
	return result;
}

Scene::Scene(const string & filename)
{
	// const string Names[20] =
	// {
	// 	"aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow",
	// 	"diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa",
	// 	"train", "tvmonitor"
	// };

        const string Names[80] =
        {
            "airplane", "apple", "backpack", "banana", "baseball bat",
            "baseball glove", "bear", "bed", "bench", "bicycle", "bird",
            "boat", "book", "bottle", "bowl", "broccoli", "bus", "cake",
            "car", "carrot", "cat", "cell phone", "chair", "clock", "couch",
            "cow", "cup", "dining table", "dog", "donut", "elephant",
            "fire hydrant", "fork", "frisbee", "giraffe", "hair drier",
            "handbag", "horse", "hot dog", "keyboard", "kite", "knife",
            "laptop", "microwave", "motorcycle", "mouse", "orange",
            "oven", "parking meter", "person", "pizza", "potted plant",
            "refrigerator", "remote", "sandwich", "scissors", "sheep",
            "sink", "skateboard", "skis", "snowboard", "spoon", "sports ball",
            "stop sign", "suitcase", "surfboard", "teddy bear", "tennis racket",
            "tie", "toaster", "toilet", "toothbrush", "traffic light", "train",
            "truck", "tv", "umbrella", "vase", "wine", "zebra"
        };

	const string Poses[4] =
	{
		"Frontal", "Left", "Rear", "Right"
	};

	xmlDoc * doc = xmlParseFile(filename.c_str());

	if (doc == NULL) {
		cerr << "Could not open " << filename << endl;
		return;
	}

	xmlNodePtr cur = xmlDocGetRootElement(doc);

	if (cur == NULL) {
		xmlFreeDoc(doc);
		cerr << "Could not open " << filename << endl;
		return;
	}

	if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("annotation"))) {
		xmlFreeDoc(doc);
		cerr << "Could not open " << filename << endl;
		return;
	}

	cur = cur->xmlChildrenNode;

	while (cur != NULL) {
		if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("filename"))) {
			// Full path
			size_t last = filename.rfind('/');

			if (last != string::npos) {
				last = filename.rfind('/', last - 1);

				if (last != string::npos)
					filename_ = filename.substr(0, last) + "/JPEGImages/" +
								content<string>(cur);
			}
		}
		else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("size"))) {
			xmlNodePtr cur2 = cur->xmlChildrenNode;

			while (cur2 != NULL) {
				if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("width")))
					width_ = content<int>(cur2);
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("height")))
					height_ = content<int>(cur2);
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("depth")))
					depth_ = content<int>(cur2);

				cur2 = cur2->next;
			}
		}
		else if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar *>("object"))) {
			objects_.push_back(Object());

			xmlNodePtr cur2 = cur->xmlChildrenNode;

			while (cur2 != NULL) {
				if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("name"))) {
					std::cout << "XML Name " << content<string>(cur2) << std::endl;
					const string * iter =
						find(Names, Names + 80, content<string>(cur2));

					if (iter != Names + 80)
						objects_.back().setName(static_cast<Object::Name>(iter - Names));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("pose"))) {
					const string * iter =
						find(Poses, Poses + 4, content<string>(cur2));

					if (iter != Poses + 4)
						objects_.back().setPose(static_cast<Object::Pose>(iter - Poses));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("truncated"))) {
					objects_.back().setTruncated(content<bool>(cur2));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("difficult"))) {
					objects_.back().setDifficult(content<bool>(cur2));
				}
				else if (!xmlStrcmp(cur2->name, reinterpret_cast<const xmlChar *>("bndbox"))) {
					Rectangle bndbox;

					xmlNodePtr cur3 = cur2->xmlChildrenNode;

					while (cur3 != NULL) {
						if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmin")))
							bndbox.setX(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymin")))
							bndbox.setY(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("xmax")))
							bndbox.setWidth(content<int>(cur3));
						else if (!xmlStrcmp(cur3->name, reinterpret_cast<const xmlChar *>("ymax")))
							bndbox.setHeight(content<int>(cur3));

						cur3 = cur3->next;
					}

					// Only set the bounding box if all values have been assigned
					if (bndbox.x() && bndbox.y() && bndbox.width() && bndbox.height()) {
						bndbox.setX(bndbox.x() - 1);
						bndbox.setY(bndbox.y() - 1);
						bndbox.setWidth(bndbox.width() - bndbox.x());
						bndbox.setHeight(bndbox.height() - bndbox.y());
						objects_.back().setBndbox(bndbox);
					}
				}

				cur2 = cur2->next;
			}
		}

		cur = cur->next;
	}

	xmlFreeDoc(doc);
}

int Scene::width() const
{
	return width_;
}

void Scene::setWidth(int width)
{
	width_ = width;
}

int Scene::height() const
{
	return height_;
}

void Scene::setHeight(int height)
{
	height_ = height;
}

int Scene::depth() const
{
	return depth_;
}

void Scene::setDepth(int depth)
{
	depth_ = depth;
}

const string & Scene::filename() const
{
	return filename_;
}

void Scene::setFilename(const string &filename)
{
	filename_ = filename;
}

const vector<Object> & Scene::objects() const
{
	return objects_;
}

void Scene::setObjects(const vector<Object> &objects)
{
	objects_ = objects;
}

ostream & FFLD::operator<<(ostream & os, const Scene & scene)
{
	os << scene.width() << ' ' << scene.height() << ' ' << scene.depth() << ' '
	   << scene.objects().size() << ' ' << scene.filename() << endl;

	for (int i = 0; i < scene.objects().size(); ++i)
		os << scene.objects()[i] << endl;

	return os;
}

istream & FFLD::operator>>(istream & is, Scene & scene)
{
	int width, height, depth, nbObjects;

    is >> width >> height >> depth >> nbObjects;
	is.get(); // Remove the space

	string filename;
	getline(is, filename);

	vector<Object> objects(nbObjects);

	for (int i = 0; i < nbObjects; ++i)
		is >> objects[i];

	if (!is) {
		scene = Scene();
		return is;
	}

	scene = Scene(width, height, depth, filename, objects);

	return is;
}
<|endoftext|>


<commit_before>/*
 * Jingle call example
 * Copyright 2004--2005, Google Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "talk/base/stringencode.h"
#include "talk/examples/login/presencepushtask.h"
#include "talk/xmpp/constants.h"
#include <sstream>

namespace buzz {

// string helper functions -----------------------------------------------------

static bool
IsXmlSpace(int ch) {
  return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
}

static bool
ListContainsToken(const std::string & list, const std::string & token) {
  size_t i = list.find(token);
  if (i == std::string::npos || token.empty())
    return false;
  bool boundary_before = (i == 0 || IsXmlSpace(list[i - 1]));
  bool boundary_after = (i == list.length() - token.length() || IsXmlSpace(list[i + token.length()]));
  return boundary_before && boundary_after;
}

bool
PresencePushTask::HandleStanza(const XmlElement * stanza) {
  if (stanza->Name() != QN_PRESENCE)
    return false;
  if (stanza->HasAttr(QN_TYPE) && stanza->Attr(QN_TYPE) != STR_UNAVAILABLE)
    return false;
  QueueStanza(stanza);
  return true;
}

static bool IsUtf8FirstByte(int c) {
  return (((c)&0x80)==0) || // is single byte
    ((unsigned char)((c)-0xc0)<0x3e); // or is lead byte
}

int
PresencePushTask::ProcessStart() {
  const XmlElement * stanza = NextStanza();
  if (stanza == NULL)
    return STATE_BLOCKED;
  Status s;

  s.set_jid(Jid(stanza->Attr(QN_FROM)));

  if (stanza->Attr(QN_TYPE) == STR_UNAVAILABLE) {
    s.set_available(false);
    SignalStatusUpdate(s);
  }
  else {
    s.set_available(true);
    const XmlElement * status = stanza->FirstNamed(QN_STATUS);
    if (status != NULL) {
      s.set_status(status->BodyText());

      // Truncate status messages longer than 300 bytes
      if (s.status().length() > 300) {
        size_t len = 300;

        // Be careful not to split legal utf-8 chars in half
        while (!IsUtf8FirstByte(s.status()[len]) && len > 0) {
          len -= 1;
        }
        std::string truncated(s.status(), 0, len);
        s.set_status(truncated);
      }
    }

    const XmlElement * priority = stanza->FirstNamed(QN_PRIORITY);
    if (priority != NULL) {
      int pri;
      if (talk_base::FromString(priority->BodyText(), &pri)) {
        s.set_priority(pri);
      }
    }

    const XmlElement * show = stanza->FirstNamed(QN_SHOW);
    if (show == NULL || show->FirstChild() == NULL) {
      s.set_show(Status::SHOW_ONLINE);
    }
    else {
      if (show->BodyText() == "away") {
        s.set_show(Status::SHOW_AWAY);
      }
      else if (show->BodyText() == "xa") {
        s.set_show(Status::SHOW_XA);
      }
      else if (show->BodyText() == "dnd") {
        s.set_show(Status::SHOW_DND);
      }
      else if (show->BodyText() == "chat") {
        s.set_show(Status::SHOW_CHAT);
      }
      else {
        s.set_show(Status::SHOW_ONLINE);
      }
    }

    const XmlElement * caps = stanza->FirstNamed(QN_CAPS_C);
    if (caps != NULL) {
      std::string node = caps->Attr(QN_NODE);
      std::string ver = caps->Attr(QN_VER);
      std::string exts = caps->Attr(QN_EXT);

      s.set_know_capabilities(true);

      if (node == GOOGLE_CLIENT_NODE || node == GMAIL_CLIENT_NODE) {
        s.set_is_google_client(true);
        s.set_version(ver);
        if (ListContainsToken(exts, "voice-v1")) {
          s.set_phone_capability(true);
        }
	if (ListContainsToken(exts, "share-v1")) {
	 s.set_fileshare_capability(true);
	}
      }
    }

    const XmlElement* delay = stanza->FirstNamed(kQnDelayX);
    if (delay != NULL) {
      // Ideally we would parse this according to the Psuedo ISO-8601 rules
      // that are laid out in JEP-0082:
      // http://www.jabber.org/jeps/jep-0082.html
      std::string stamp = delay->Attr(kQnStamp);
      s.set_sent_time(stamp);
    }

    SignalStatusUpdate(s);
  }

  return STATE_START;
}

}

<commit_msg>enable google libjingle functions for other client (not only for google example apps and google talk)<commit_after>/*
 * Jingle call example
 * Copyright 2004--2005, Google Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "talk/base/stringencode.h"
#include "talk/examples/login/presencepushtask.h"
#include "talk/xmpp/constants.h"
#include <sstream>

namespace buzz {

// string helper functions -----------------------------------------------------

static bool
IsXmlSpace(int ch) {
  return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
}

static bool
ListContainsToken(const std::string & list, const std::string & token) {
  size_t i = list.find(token);
  if (i == std::string::npos || token.empty())
    return false;
  bool boundary_before = (i == 0 || IsXmlSpace(list[i - 1]));
  bool boundary_after = (i == list.length() - token.length() || IsXmlSpace(list[i + token.length()]));
  return boundary_before && boundary_after;
}

bool
PresencePushTask::HandleStanza(const XmlElement * stanza) {
  if (stanza->Name() != QN_PRESENCE)
    return false;
  if (stanza->HasAttr(QN_TYPE) && stanza->Attr(QN_TYPE) != STR_UNAVAILABLE)
    return false;
  QueueStanza(stanza);
  return true;
}

static bool IsUtf8FirstByte(int c) {
  return (((c)&0x80)==0) || // is single byte
    ((unsigned char)((c)-0xc0)<0x3e); // or is lead byte
}

int
PresencePushTask::ProcessStart() {
  const XmlElement * stanza = NextStanza();
  if (stanza == NULL)
    return STATE_BLOCKED;
  Status s;

  s.set_jid(Jid(stanza->Attr(QN_FROM)));

  if (stanza->Attr(QN_TYPE) == STR_UNAVAILABLE) {
    s.set_available(false);
    SignalStatusUpdate(s);
  }
  else {
    s.set_available(true);
    const XmlElement * status = stanza->FirstNamed(QN_STATUS);
    if (status != NULL) {
      s.set_status(status->BodyText());

      // Truncate status messages longer than 300 bytes
      if (s.status().length() > 300) {
        size_t len = 300;

        // Be careful not to split legal utf-8 chars in half
        while (!IsUtf8FirstByte(s.status()[len]) && len > 0) {
          len -= 1;
        }
        std::string truncated(s.status(), 0, len);
        s.set_status(truncated);
      }
    }

    const XmlElement * priority = stanza->FirstNamed(QN_PRIORITY);
    if (priority != NULL) {
      int pri;
      if (talk_base::FromString(priority->BodyText(), &pri)) {
        s.set_priority(pri);
      }
    }

    const XmlElement * show = stanza->FirstNamed(QN_SHOW);
    if (show == NULL || show->FirstChild() == NULL) {
      s.set_show(Status::SHOW_ONLINE);
    }
    else {
      if (show->BodyText() == "away") {
        s.set_show(Status::SHOW_AWAY);
      }
      else if (show->BodyText() == "xa") {
        s.set_show(Status::SHOW_XA);
      }
      else if (show->BodyText() == "dnd") {
        s.set_show(Status::SHOW_DND);
      }
      else if (show->BodyText() == "chat") {
        s.set_show(Status::SHOW_CHAT);
      }
      else {
        s.set_show(Status::SHOW_ONLINE);
      }
    }

    const XmlElement * caps = stanza->FirstNamed(QN_CAPS_C);
    if (caps != NULL) {
      std::string node = caps->Attr(QN_NODE);
      std::string ver = caps->Attr(QN_VER);
      std::string exts = caps->Attr(QN_EXT);

      s.set_know_capabilities(true);

      if (node == GOOGLE_CLIENT_NODE || node == GMAIL_CLIENT_NODE) {
        s.set_is_google_client(true);
        s.set_version(ver);
      }
      if (ListContainsToken(exts, "voice-v1")) {
        s.set_phone_capability(true);
      }
      if (ListContainsToken(exts, "share-v1")) {
        s.set_fileshare_capability(true);
      }
    }

    const XmlElement* delay = stanza->FirstNamed(kQnDelayX);
    if (delay != NULL) {
      // Ideally we would parse this according to the Psuedo ISO-8601 rules
      // that are laid out in JEP-0082:
      // http://www.jabber.org/jeps/jep-0082.html
      std::string stamp = delay->Attr(kQnStamp);
      s.set_sent_time(stamp);
    }

    SignalStatusUpdate(s);
  }

  return STATE_START;
}

}

<|endoftext|>


<commit_before>/*
 * copyright: (c) RDO-Team, 2011
 * filename : main.cpp
 * author   :  , Evgeny Proydakov
 * date     : 07.07.2009
 * bref     :
 * indent   : 4T
 */

// ====================================================================== PCH
// ====================================================================== INCLUDES
#include <vector>
#include <list>
#include <iostream>
#define BOOST_TEST_MODULE RdoInterfaceTest
#include <boost/test/included/unit_test.hpp>
// ====================================================================== SYNOPSIS
#include "rdo_common/rdointerface.h"
// ===============================================================================

#define DISABLE_CONSOLE_OUTPUT

const tstring strIMy1            = _T("void fun1():  ");
const tstring strIMy2            = _T("void fun2():  ");
const tstring strIMy3            = _T("void fun3():  ");
const tstring strMyClass1Create  = _T("MyClass1():"   );
const tstring strMyClass1Destroy = _T("~MyClass1():"  );
const tstring strMyClass2Create  = _T("MyClass2():"   );
const tstring strMyClass2Destroy = _T("~MyClass2():"  );
const tstring strMyClass3Create  = _T("MyClass3():"   );
const tstring strMyClass3Destroy = _T("~MyClass3():"  );

typedef std::list<tstring> LogList;
LogList s_logList;

class IMy1
{
public:
	virtual tstring fun1() = 0;
};

class IMy2
{
public:
	virtual tstring fun2() = 0;
};

class IMy3
{
public:
	virtual tstring fun3() = 0;
};

class IMy4
{
public:
	virtual tstring fun4() = 0;
};

INTERFACE_REGISTRATOR(IMy1, 1);
INTERFACE_REGISTRATOR(IMy2, 2);
INTERFACE_REGISTRATOR(IMy3, 3);
INTERFACE_REGISTRATOR(IMy4, 4);

class MyClass1: public rdo::IGetUnknown, public IMy1, public IMy2, public IInit
{
QUERY_INTERFACE_BEGIN
	QUERY_INTERFACE(IMy1)
	QUERY_INTERFACE(IMy2)
	QUERY_INTERFACE(IInit)
QUERY_INTERFACE_END

protected:
	MyClass1(char i)
		: m_i(i)
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass1Create << i << std::endl;
#endif
		s_logList.push_back(strMyClass1Create + i);
	}
	~MyClass1()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass1Destroy << m_i << std::endl;
#endif
		s_logList.push_back(strMyClass1Destroy + m_i);
	}
	rbool init()
	{
		return true;
	}

protected:
	char m_i;

private:
	tstring fun1()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strIMy1 << m_i << std::endl;
#endif
		return strIMy1 + m_i;
	}
	tstring fun2()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strIMy2 << m_i << std::endl;
#endif
		return strIMy2 + m_i;
	}
};

class MyClass2: public MyClass1, public IMy3
{
DEFINE_IFACTORY(MyClass2);
QUERY_INTERFACE_BEGIN
	QUERY_INTERFACE_PARENT(MyClass1)
	QUERY_INTERFACE(IMy3)
QUERY_INTERFACE_END

private:
	MyClass2(char i)
		: MyClass1(i)
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass2Create << i << std::endl;
#endif
		s_logList.push_back(strMyClass2Create + i);
	}
	~MyClass2()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass2Destroy << m_i << std::endl;
#endif
		s_logList.push_back(strMyClass2Destroy + m_i);
	}
	tstring fun3()
	{
		ASSERT(this);
		LPIMy1 int1 = this;
		ASSERT(int1)

#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strIMy3 << m_i << std::endl;
#endif
		return strIMy3 + m_i;
	}
};

class MyClass3: public IMy3, public rdo::IGetUnknown
{
DEFINE_IFACTORY(MyClass3);
QUERY_INTERFACE_BEGIN
	QUERY_INTERFACE(IMy3)
QUERY_INTERFACE_END

protected:
	MyClass3(char i)
		: m_i(i)
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass3Create << i << std::endl;
#endif
		s_logList.push_back(strMyClass3Create + i);
	}
	~MyClass3()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass3Destroy << m_i << std::endl;
#endif
		s_logList.push_back(strMyClass3Destroy + m_i);
	}

protected:
	char m_i;

private:
	tstring fun3()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strIMy3 << m_i << std::endl;
#endif
		return strIMy3 + m_i;
	}
};

typedef rdo::Interface<IMy3>     MyInterface;
typedef std::vector<MyInterface> MyInterfaceList;

BOOST_AUTO_TEST_SUITE(RdoInterfaceTest)

BOOST_AUTO_TEST_CASE(RdoInterfaceTest_CheckingOnTheSameOperator)
{
	char initValue = _T('1');
	rdo::UnknownPointer smptr = F(MyClass2)::create(initValue);
	BOOST_REQUIRE(smptr);

	LogList::const_iterator it = s_logList.begin();
	BOOST_CHECK_EQUAL(*it,     strMyClass1Create + initValue);
	BOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);
	s_logList.clear();

	BOOST_CHECK_EQUAL(smptr.query_cast<IMy1>()->fun1(), strIMy1 + initValue);
	BOOST_CHECK_EQUAL(smptr.query_cast<IMy3>()->fun3(), strIMy3 + initValue);

	initValue = _T('2');
	MyInterface         imy3 = smptr;
	rdo::UnknownPointer smptr2;
	smptr2 = F(MyClass2)::create(initValue);
	it = s_logList.begin();
	BOOST_CHECK_EQUAL(*it,     strMyClass1Create + initValue);
	BOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);
	s_logList.clear();

	rdo::UnknownPointer smptr2_2 = smptr2;
	BOOST_CHECK(!(smptr2_2 == smptr));
	BOOST_CHECK(smptr2_2 == smptr2);

	rdo::Interface<IMy1> int1_1 = smptr;
	rdo::Interface<IMy1> int2_1 = smptr2;
	rdo::Interface<IMy1> int1_2 = smptr;
	BOOST_CHECK(!(int1_1 == int2_1));
	BOOST_CHECK(int1_1 == int1_2);
}

BOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest1)
{
	LogList::iterator it = s_logList.begin();
	BOOST_CHECK_EQUAL(*it, strMyClass2Destroy + _T('2'));
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass1Destroy + _T('2'));
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass2Destroy + _T('1'));
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass1Destroy + _T('1'));
	s_logList.clear();
}

BOOST_AUTO_TEST_CASE(RdoInterfaceTest_Working)
{
	char initFValue = _T('1');
	rdo::UnknownPointer smptr = F(MyClass2)::create(initFValue);
	LogList::iterator iter = s_logList.begin();
	BOOST_CHECK_EQUAL(*iter, strMyClass1Create + initFValue);
	BOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initFValue);
	s_logList.clear();

	char initSValue = _T('2');
	rdo::UnknownPointer smptr2 = F(MyClass2)::create(initSValue);
	iter = s_logList.begin();
	BOOST_CHECK_EQUAL(*iter, strMyClass1Create + initSValue);
	BOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initSValue);
	s_logList.clear();

	MyInterfaceList myInterfaceList;

	char initTValue = _T('3');
	myInterfaceList.push_back(F(MyClass3)::create(initTValue));
	myInterfaceList.push_back(smptr );
	myInterfaceList.push_back(smptr2);

	char symbolT = _T('0');

	STL_FOR_ALL_CONST(myInterfaceList, it)
	{
		rdo::Interface<IMy1> ptr1;
		ptr1 = *it;
		if (ptr1)
		{
			symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
			BOOST_CHECK_EQUAL(ptr1->fun1(), strIMy1 + symbolT);
		}

		rdo::Interface<IMy2> ptr2 = *it;
		if (ptr2)
		{
			symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
			BOOST_CHECK_EQUAL(ptr2->fun2(), strIMy2 + symbolT);
		}

		rdo::Interface<IMy3> ptr3 = *it;
		if (ptr3)
		{
			symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
			BOOST_CHECK_EQUAL(ptr3->fun3(), strIMy3 + symbolT);
		}
	}
	s_logList.clear();
}

BOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest2)
{
	LogList::iterator it = s_logList.begin();
	BOOST_CHECK_EQUAL(*it, strMyClass3Destroy + _T('3'));
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass2Destroy + _T('2'));
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass1Destroy + _T('2'));
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass2Destroy + _T('1'));
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass1Destroy + _T('1'));
	s_logList.clear();
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg> - возврат к одному тесту<commit_after>/*
 * copyright: (c) RDO-Team, 2011
 * filename : main.cpp
 * author   :  , Evgeny Proydakov
 * date     : 07.07.2009
 * bref     :
 * indent   : 4T
 */

// ====================================================================== PCH
// ====================================================================== INCLUDES
#include <vector>
#include <list>
#include <iostream>
#define BOOST_TEST_MODULE RDOInterfaceTest
#include <boost/test/included/unit_test.hpp>
// ====================================================================== SYNOPSIS
#include "rdo_common/rdointerface.h"
// ===============================================================================

#define DISABLE_CONSOLE_OUTPUT

const tstring strIMy1            = _T("void fun1():  ");
const tstring strIMy2            = _T("void fun2():  ");
const tstring strIMy3            = _T("void fun3():  ");
const tstring strMyClass1Create  = _T("MyClass1():"   );
const tstring strMyClass1Destroy = _T("~MyClass1():"  );
const tstring strMyClass2Create  = _T("MyClass2():"   );
const tstring strMyClass2Destroy = _T("~MyClass2():"  );
const tstring strMyClass3Create  = _T("MyClass3():"   );
const tstring strMyClass3Destroy = _T("~MyClass3():"  );
const char    initFValue         = _T('1');
const char    initSValue         = _T('2');
const char    initTValue         = _T('3');

typedef std::list<tstring> LogList;
LogList s_logList;

class IMy1
{
public:
	virtual tstring fun1() = 0;
};

class IMy2
{
public:
	virtual tstring fun2() = 0;
};

class IMy3
{
public:
	virtual tstring fun3() = 0;
};

class IMy4
{
public:
	virtual tstring fun4() = 0;
};

INTERFACE_REGISTRATOR(IMy1, 1);
INTERFACE_REGISTRATOR(IMy2, 2);
INTERFACE_REGISTRATOR(IMy3, 3);
INTERFACE_REGISTRATOR(IMy4, 4);

class MyClass1: public rdo::IGetUnknown, public IMy1, public IMy2, public IInit
{
QUERY_INTERFACE_BEGIN
	QUERY_INTERFACE(IMy1)
	QUERY_INTERFACE(IMy2)
	QUERY_INTERFACE(IInit)
QUERY_INTERFACE_END

protected:
	MyClass1(char i)
		: m_i(i)
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass1Create << i << std::endl;
#endif
		s_logList.push_back(strMyClass1Create + i);
	}
	~MyClass1()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass1Destroy << m_i << std::endl;
#endif
		s_logList.push_back(strMyClass1Destroy + m_i);
	}
	rbool init()
	{
		return true;
	}

protected:
	char m_i;

private:
	tstring fun1()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strIMy1 << m_i << std::endl;
#endif
		return strIMy1 + m_i;
	}
	tstring fun2()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strIMy2 << m_i << std::endl;
#endif
		return strIMy2 + m_i;
	}
};

class MyClass2: public MyClass1, public IMy3
{
DEFINE_IFACTORY(MyClass2);
QUERY_INTERFACE_BEGIN
	QUERY_INTERFACE_PARENT(MyClass1)
	QUERY_INTERFACE(IMy3)
QUERY_INTERFACE_END

private:
	MyClass2(char i)
		: MyClass1(i)
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass2Create << i << std::endl;
#endif
		s_logList.push_back(strMyClass2Create + i);
	}
	~MyClass2()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass2Destroy << m_i << std::endl;
#endif
		s_logList.push_back(strMyClass2Destroy + m_i);
	}
	tstring fun3()
	{
		ASSERT(this);
		LPIMy1 int1 = this;
		ASSERT(int1)

#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strIMy3 << m_i << std::endl;
#endif
		return strIMy3 + m_i;
	}
};

class MyClass3: public IMy3, public rdo::IGetUnknown
{
DEFINE_IFACTORY(MyClass3);
QUERY_INTERFACE_BEGIN
	QUERY_INTERFACE(IMy3)
QUERY_INTERFACE_END

protected:
	MyClass3(char i)
		: m_i(i)
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass3Create << i << std::endl;
#endif
		s_logList.push_back(strMyClass3Create + i);
	}
	~MyClass3()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strMyClass3Destroy << m_i << std::endl;
#endif
		s_logList.push_back(strMyClass3Destroy + m_i);
	}

protected:
	char m_i;

private:
	tstring fun3()
	{
#ifndef DISABLE_CONSOLE_OUTPUT
		std::cout << strIMy3 << m_i << std::endl;
#endif
		return strIMy3 + m_i;
	}
};

typedef rdo::Interface<IMy3>     MyInterface;
typedef std::vector<MyInterface> MyInterfaceList;

BOOST_AUTO_TEST_SUITE(RDOInterfaceTest)

BOOST_AUTO_TEST_CASE(RdoInterfaceTest)
{
	{
		rdo::UnknownPointer smptr = F(MyClass2)::create(initFValue);
		BOOST_REQUIRE(smptr);

		LogList::const_iterator it = s_logList.begin();
		BOOST_CHECK_EQUAL(*it,     strMyClass1Create + initFValue);
		BOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initFValue);
		s_logList.clear();

		BOOST_CHECK_EQUAL(smptr.query_cast<IMy1>()->fun1(), strIMy1 + initFValue);
		BOOST_CHECK_EQUAL(smptr.query_cast<IMy3>()->fun3(), strIMy3 + initFValue);

		MyInterface         imy3 = smptr;
		rdo::UnknownPointer smptr2;
		smptr2 = F(MyClass2)::create(initSValue);
		it = s_logList.begin();
		BOOST_CHECK_EQUAL(*it,     strMyClass1Create + initSValue);
		BOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initSValue);
		s_logList.clear();

		rdo::UnknownPointer smptr2_2 = smptr2;
		BOOST_CHECK(!(smptr2_2 == smptr));
		BOOST_CHECK(smptr2_2 == smptr2);

		rdo::Interface<IMy1> int1_1 = smptr;
		rdo::Interface<IMy1> int2_1 = smptr2;
		rdo::Interface<IMy1> int1_2 = smptr;
		BOOST_CHECK(!(int1_1 == int2_1));
		BOOST_CHECK(int1_1 == int1_2);

		MyInterfaceList myInterfaceList;
		myInterfaceList.push_back(F(MyClass3)::create(initTValue));
		myInterfaceList.push_back(smptr );
		myInterfaceList.push_back(smptr2);

		char symbolT = _T('0');
		STL_FOR_ALL_CONST(myInterfaceList, it)
		{
			rdo::Interface<IMy1> ptr1;
			ptr1 = *it;
			if (ptr1)
			{
				symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
				BOOST_CHECK_EQUAL(ptr1->fun1(), strIMy1 + symbolT);
			}

			rdo::Interface<IMy2> ptr2 = *it;
			if (ptr2)
			{
				symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
				BOOST_CHECK_EQUAL(ptr2->fun2(), strIMy2 + symbolT);
			}

			rdo::Interface<IMy3> ptr3 = *it;
			if (ptr3)
			{
				symbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));
				BOOST_CHECK_EQUAL(ptr3->fun3(), strIMy3 + symbolT);
			}
		}
		s_logList.clear();
	}

	LogList::iterator it = s_logList.begin();
	BOOST_CHECK_EQUAL(*it, strMyClass3Destroy + initTValue);
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass2Destroy + initSValue);
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass1Destroy + initSValue);
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass2Destroy + initFValue);
	++it;
	BOOST_CHECK_EQUAL(*it, strMyClass1Destroy + initFValue);
	s_logList.clear();
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include <d3d11.h>
#include "../../../lib/DirectXTex/DirectXTex/DDS.h"
#include <cstdio>
#include <new>

using namespace DirectX;

struct DDS
{
	DWORD dwMagic;
	DDS_HEADER header;
	DDS_HEADER_DXT10 header10;
};

int main(int argc, char* argv[])
{
	auto size = 128;
	auto channels = 1;

	DDS dds = { 0 };

	dds.dwMagic = DDS_MAGIC;

	dds.header.dwSize = sizeof(DDS_HEADER);
	dds.header.dwFlags = DDS_HEADER_FLAGS_TEXTURE | DDS_HEADER_FLAGS_VOLUME | DDS_HEADER_FLAGS_PITCH;
	dds.header.dwHeight = size;
	dds.header.dwWidth = size;
	dds.header.dwDepth = size;
	dds.header.dwPitchOrLinearSize = (size * (sizeof(FLOAT) * channels) + 7) / 8;
	dds.header.dwMipMapCount = 0;
	dds.header.ddspf = DDSPF_DX10;
	dds.header.dwCaps = DDS_SURFACE_FLAGS_TEXTURE | DDS_SURFACE_FLAGS_CUBEMAP;
	dds.header.dwCaps2 = DDS_FLAGS_VOLUME;

	dds.header10.dxgiFormat = DXGI_FORMAT_R32G32B32A32_FLOAT;
	dds.header10.resourceDimension = DDS_DIMENSION_TEXTURE3D;
	dds.header10.arraySize = 1;
	dds.header10.miscFlag = 0;
	dds.header10.miscFlags2 = 0;

	const auto total_size = size * size* size * (sizeof(FLOAT) * channels);
	auto *data = new (std::nothrow) FLOAT[total_size];
	if (!data) {
		return 1;
	}

	for (int z = 0; z < size; z++) {
		for (int y = 0; y < size; y++) {
			for (int x = 0; x < size; x++) {
				*(data + size*size*z + size*y + x) = 1.;
			}
		}
	}

	FILE *file = fopen("noise3d.dds", "wb+");
	if (!file) {
		return 2;
	}
	fwrite(&dds, sizeof(dds), 1, file);
	fwrite(data, sizeof(FLOAT) * channels, size * size * size, file);
	fclose(file);

	delete[] data;

	return 0;
}<commit_msg>fixed pixel format; replaced naked ptrs with RAII equiv<commit_after>#include <d3d11.h>
#include "../../../lib/DirectXTex/DirectXTex/DDS.h"
#include <cstdio>
#include <memory>
#include <new>

using namespace DirectX;

struct DDS
{
	DWORD dwMagic;
	DDS_HEADER header;
	DDS_HEADER_DXT10 header10;
};

int main(int argc, char* argv[])
{
	auto size = 128;
	auto channels = 1;

	DDS dds = { 0 };

	dds.dwMagic = DDS_MAGIC;

	dds.header.dwSize = sizeof(DDS_HEADER);
	dds.header.dwFlags = DDS_HEADER_FLAGS_TEXTURE | DDS_HEADER_FLAGS_VOLUME | DDS_HEADER_FLAGS_PITCH;
	dds.header.dwHeight = size;
	dds.header.dwWidth = size;
	dds.header.dwDepth = size;
	dds.header.dwPitchOrLinearSize = (size * (sizeof(FLOAT) * channels) + 7) / 8;
	dds.header.dwMipMapCount = 0;
	dds.header.ddspf = DDSPF_DX10;
	dds.header.dwCaps = DDS_SURFACE_FLAGS_TEXTURE | DDS_SURFACE_FLAGS_CUBEMAP;
	dds.header.dwCaps2 = DDS_FLAGS_VOLUME;

	dds.header10.dxgiFormat = DXGI_FORMAT_R32_FLOAT;
	dds.header10.resourceDimension = DDS_DIMENSION_TEXTURE3D;
	dds.header10.arraySize = 1;
	dds.header10.miscFlag = 0;
	dds.header10.miscFlags2 = 0;

	const auto total_size = size * size* size * (sizeof(FLOAT) * channels);
	std::unique_ptr<FLOAT[]> data;
	data.reset(new (std::nothrow) FLOAT[total_size]);
	if (!data) {
		return 1;
	}

	for (int z = 0; z < size; z++) {
		for (int y = 0; y < size; y++) {
			for (int x = 0; x < size; x++) {
				*(data.get() + size*size*z + size*y + x) = 1.;
			}
		}
	}

	struct FileCloser {
		void operator()(FILE *f) {
			::fclose(f);
		}
	};
	std::unique_ptr<FILE, FileCloser> file;
	file.reset(fopen("noise3d.dds", "wb+"));
	if (!file) {
		return 2;
	}
	fwrite(&dds, sizeof(dds), 1, file.get());
	fwrite(data.get(), sizeof(FLOAT) * channels, size * size * size, file.get());

	return 0;
}<|endoftext|>


<commit_before>#include "listservices.h"
#include <vector>

listServices::listServices()
{
    bool isEndOfFile;
    do {
        scientistList nextScientist();
        isEndOfFile = nextScientist.readFile();
        _computerScientists.push_back(nextScientist);
    }while(!isEndOfFile); //This loop fills the computerScientist vector ( a member variable) with computer scientists from the list class.

}

void   listServices::sortByName()
{
    //TODO: flokka eftir nafni
}
void   listServices::sortByBirth()
{

}

void   listServices::sortByAlive()
{
    //TODO
}

void   listServices::sortByAward()
{
    //TODO
}

void   listServices::addNew(string firstName, string lastName, char gender, int birthYear, int deathYear, int awardYear)
{
    //TODO
}

vector<list> listServices::searchLastName(string lastName)
{
    vector<list> matchingNames;
    //TODO
    return matchingNames;
}

vector<list> listServices::searchBirth(int birthYear)
{
    vector<list> matchingBirthYears;
    //TODO
    return matchingBirthYears;
}

vector<list> listServices::searchAlive(int deathYear)
{
    vector<list> livingScientists;
    //TODO
    return livingScientists;
}

vector<list> listServices::searchAward(int awardYear)
{
    vector<list> matchingAwardYear;
    //TODO
    return matchingAwardYear;
}
<commit_msg>C-c-c-changes<commit_after>#include "listservices.h"
#include <vector>

listServices::listServices()
{
    bool isEndOfFile;
    do {
        scientistList nextScientist;
        isEndOfFile = nextScientist.readFile();
        _computerScientists.push_back(nextScientist);
    }while(!isEndOfFile); //This loop fills the computerScientist vector ( a member variable) with computer scientists from the list class.

}

void   listServices::sortByName()
{
    //TODO: flokka eftir nafni
}
void   listServices::sortByBirth()
{

}

void   listServices::sortByAlive()
{
    //TODO
}

void   listServices::sortByAward()
{
    //TODO
}

void   listServices::addNew(string firstName, string lastName, char gender, int birthYear, int deathYear, int awardYear)
{
    //TODO
}

vector<scientistList> listServices::searchLastName(string lastName)
{
    vector<scientistList> matchingNames;
    //TODO
    return matchingNames;
}

vector<scientistList> listServices::searchBirth(int birthYear)
{
    vector<scientistList> matchingBirthYears;
    //TODO
    return matchingBirthYears;
}

vector<scientistList> listServices::searchAlive(int deathYear)
{
    vector<scientistList> livingScientists;
    //TODO
    return livingScientists;
}

vector<scientistList> listServices::searchAward(int awardYear)
{
    vector<scientistList> matchingAwardYear;
    //TODO
    return matchingAwardYear;
}
<|endoftext|>


<commit_before>// $Id: LEF.C,v 1.1 2000/07/03 20:02:15 oliver Exp $

#include<BALL/NMR/LEF.h>

using namespace std;

namespace BALL
{

//Konstruktor

LEFShift::LEFShift()
	{
	//cout << endl << "LEFShift::LEFShift()";
	//pb_=new FDPB;
	//pb_->options.setReal(FDPB::Option::SOLVENT_DC,1.0);
	}

//Destruktor

LEFShift::~LEFShift()
	{
	//cout << endl << "LEFShift::~LEFShift()";
	}

//StartFunktion

bool LEFShift::start()
	{
	// hier passiert nichts
	//cout << endl << "LEFShift::start()";
	return 1;
	}

//FinishFunktion

bool LEFShift::finish()
	{
	//cout << endl << "LEF Modul";

	Vector3 proton,bindung,atom,prot_bin,prot_atom;
	float sc,theta,ladung,Ez,Efact,b_prot_bin,b_prot_atom;

	const float QC=1.6;
	const float QN=-1.7;
	const float QH=0.7;
	const float QO=-2.3;
	const float sigmaE=0.6;

	list<PDBAtom*>::iterator proton_iter;
	list<PDBAtom*>::iterator atom_iter;
	proton_iter=proton_list_.begin();

	if ( (proton_list_.begin()!=NULL) && (atom_list_.begin()!=NULL) )
		{
		for(;proton_iter!=proton_list_.end();++proton_iter)
			{
			//cout << endl<< "Bearbeite jetzt Hydrogen : " << (*proton_iter)->getName();
			proton=(*proton_iter)->getPosition();
			bindung=(*proton_iter)->getBond(0)->getBondedAtomOf(*(*proton_iter))->getPosition();
			prot_bin=proton-bindung;
			Ez=0;
			for(atom_iter=atom_list_.begin();atom_iter!=atom_list_.end();++atom_iter)
				{
				//cout << endl <<"	"<< (*atom_iter)->getName()<<"?";
				if ( (*atom_iter)->getResidue()!=(*proton_iter)->getResidue() )
					{
					//cout << " jep";
					if ((*atom_iter)->getName()=="C") ladung=QC;
					if ((*atom_iter)->getName()=="N") ladung=QN;
					if ((*atom_iter)->getName()=="H") ladung=QH;
					if ((*atom_iter)->getName()=="O") ladung=QO;
					//cout << "	ladung:"<< ladung;
					atom=(*atom_iter)->getPosition();
					prot_atom=proton-atom;
					sc=prot_bin*prot_atom;
					b_prot_bin=prot_bin.getLength();
					b_prot_atom=prot_atom.getLength();
					theta=sc / (b_prot_bin*b_prot_atom);
					Efact=ladung/(b_prot_atom*b_prot_atom);
					Ez=Ez+(theta*Efact);
					}
				}
			shift_=(*proton_iter)->getProperty("chemical_shift").getFloat();
			shift_-=Ez*sigmaE;
			(*proton_iter)->setProperty("chemical_shift", shift_);
			//Log.level(LogStream::INFORMATION)  << "chemical_shift :" << shift_ << endl;
			//cout << endl <<"LEF:Residue :"<<(*proton_iter)->getResidue()->getName()<<" Atom :"<<(*proton_iter)->getName()<< " chemical_shift :" << shift_;

			}
		}
	return 1;
	}

//apply Funktion

Processor::Result LEFShift::operator()(Object&  object)
	{
	// ist das Objekt ein Atom und noch dazu ein Wasserstoff
	// und hngt es an einem Kohlenstoff, so wird es in der _proton_list gespeichert

	if (RTTI::isKindOf<PDBAtom>(object))
		{
		//cout  << endl << "Object is ProteinAtom";

		// Baustelle : berprfe ob Hydrogen an einem Kohlenstoff hngt !!
		patom_=RTTI::castTo<PDBAtom>(object);
		//cout  << endl << "		atom name : " << patom_->getName();
		//cout  << endl << "		Element : " << (patom_->getElement()).getName();
		if (patom_->getElement()==PTE[Element::H])
			{
			if (patom_->getName()=="H")
				{
				atom_list_.push_back(patom_);
				//cout << "...in atom_list_ eingefuegt.";
				}
			else
				{

				// Wasserstoffe haben nur eine Bindung : Index = 1 oder 0 ?
				// Hole diese Bindung und berprfe ob Kohlenstoff

				if (patom_->isBonded())
					{
					if ((patom_->getBond(0)->getBondedAtomOf(*patom_)->getElement())==PTE[Element::C])
						{
						proton_list_.push_back(patom_);
	 	 				//cout  << "...in proton_list_ eingefuegt.";
	 					}
					}
				}
			}
		else if ( (patom_->getName()=="C") || (patom_->getName()=="N") || (patom_->getName()=="O") )
			{
			atom_list_.push_back(patom_);
			//cout << "...in atom_list_ eingefuegt.";
			}

		} // Ende is kind of ProteinAtom : die Listen wurden gesetzt

	return Processor::CONTINUE;
	}

} // namespace Ball
<commit_msg>fixed: incorect usage of begin()<commit_after>// $Id: LEF.C,v 1.2 2000/07/04 13:52:13 oliver Exp $

#include<BALL/NMR/LEF.h>

using namespace std;

namespace BALL
{

//Konstruktor

LEFShift::LEFShift()
	{
	//cout << endl << "LEFShift::LEFShift()";
	//pb_=new FDPB;
	//pb_->options.setReal(FDPB::Option::SOLVENT_DC,1.0);
	}

//Destruktor

LEFShift::~LEFShift()
	{
	//cout << endl << "LEFShift::~LEFShift()";
	}

//StartFunktion

bool LEFShift::start()
	{
	// hier passiert nichts
	//cout << endl << "LEFShift::start()";
	return 1;
	}

//FinishFunktion

bool LEFShift::finish()
	{
	//cout << endl << "LEF Modul";

	Vector3 proton,bindung,atom,prot_bin,prot_atom;
	float sc,theta,ladung,Ez,Efact,b_prot_bin,b_prot_atom;

	const float QC=1.6;
	const float QN=-1.7;
	const float QH=0.7;
	const float QO=-2.3;
	const float sigmaE=0.6;

	list<PDBAtom*>::iterator proton_iter;
	list<PDBAtom*>::iterator atom_iter;
	proton_iter=proton_list_.begin();

	if ( (proton_list_.size() > 0) && (atom_list_.size() > 0))
		{
		for(;proton_iter!=proton_list_.end();++proton_iter)
			{
			//cout << endl<< "Bearbeite jetzt Hydrogen : " << (*proton_iter)->getName();
			proton=(*proton_iter)->getPosition();
			bindung=(*proton_iter)->getBond(0)->getBondedAtomOf(*(*proton_iter))->getPosition();
			prot_bin=proton-bindung;
			Ez=0;
			for(atom_iter=atom_list_.begin();atom_iter!=atom_list_.end();++atom_iter)
				{
				//cout << endl <<"	"<< (*atom_iter)->getName()<<"?";
				if ( (*atom_iter)->getResidue()!=(*proton_iter)->getResidue() )
					{
					//cout << " jep";
					if ((*atom_iter)->getName()=="C") ladung=QC;
					if ((*atom_iter)->getName()=="N") ladung=QN;
					if ((*atom_iter)->getName()=="H") ladung=QH;
					if ((*atom_iter)->getName()=="O") ladung=QO;
					//cout << "	ladung:"<< ladung;
					atom=(*atom_iter)->getPosition();
					prot_atom=proton-atom;
					sc=prot_bin*prot_atom;
					b_prot_bin=prot_bin.getLength();
					b_prot_atom=prot_atom.getLength();
					theta=sc / (b_prot_bin*b_prot_atom);
					Efact=ladung/(b_prot_atom*b_prot_atom);
					Ez=Ez+(theta*Efact);
					}
				}
			shift_=(*proton_iter)->getProperty("chemical_shift").getFloat();
			shift_-=Ez*sigmaE;
			(*proton_iter)->setProperty("chemical_shift", shift_);
			//Log.level(LogStream::INFORMATION)  << "chemical_shift :" << shift_ << endl;
			//cout << endl <<"LEF:Residue :"<<(*proton_iter)->getResidue()->getName()<<" Atom :"<<(*proton_iter)->getName()<< " chemical_shift :" << shift_;

			}
		}
	return 1;
	}

//apply Funktion

Processor::Result LEFShift::operator()(Object&  object)
	{
	// ist das Objekt ein Atom und noch dazu ein Wasserstoff
	// und hngt es an einem Kohlenstoff, so wird es in der _proton_list gespeichert

	if (RTTI::isKindOf<PDBAtom>(object))
		{
		//cout  << endl << "Object is ProteinAtom";

		// Baustelle : berprfe ob Hydrogen an einem Kohlenstoff hngt !!
		patom_=RTTI::castTo<PDBAtom>(object);
		//cout  << endl << "		atom name : " << patom_->getName();
		//cout  << endl << "		Element : " << (patom_->getElement()).getName();
		if (patom_->getElement()==PTE[Element::H])
			{
			if (patom_->getName()=="H")
				{
				atom_list_.push_back(patom_);
				//cout << "...in atom_list_ eingefuegt.";
				}
			else
				{

				// Wasserstoffe haben nur eine Bindung : Index = 1 oder 0 ?
				// Hole diese Bindung und berprfe ob Kohlenstoff

				if (patom_->isBonded())
					{
					if ((patom_->getBond(0)->getBondedAtomOf(*patom_)->getElement())==PTE[Element::C])
						{
						proton_list_.push_back(patom_);
	 	 				//cout  << "...in proton_list_ eingefuegt.";
	 					}
					}
				}
			}
		else if ( (patom_->getName()=="C") || (patom_->getName()=="N") || (patom_->getName()=="O") )
			{
			atom_list_.push_back(patom_);
			//cout << "...in atom_list_ eingefuegt.";
			}

		} // Ende is kind of ProteinAtom : die Listen wurden gesetzt

	return Processor::CONTINUE;
	}

} // namespace Ball
<|endoftext|>