<commit_before>#include <QQuickWindow>
#include <QEventLoop>
#include <QTimer>
#include <QQuickItem>
#include <QTime>
#include <QTest>
#include "automator.h"

static bool inherited(QObject* object,QString className) {
    bool res = false;

    const QMetaObject *metaObject = object->metaObject();

    while (metaObject) {
        if (metaObject->className() == className) {
            res = true;
            break;
        }
        metaObject = metaObject->superClass();
    }

    return res;
}

static QObjectList uniq(const QObjectList& list) {

    QMap<QObject*, bool> map;
    QObjectList res;

    for (int i = 0 ; i < list.count() ;i++) {
        QObject* object = list.at(i);
        if (!map.contains(object)) {
            res << object;
            map[object] = true;
        }
    }

    return res;
}

static bool hasMethod(QObject* object, QString method) {
    const QMetaObject* meta = object->metaObject();

    int index = -1;

    for (int i = 0 ; i < meta->methodCount(); i++) {
        if (method == meta->method(i).name()) {
            index = i;
            break;
        }
    }

    return index >= 0;
}

static bool hasMethods(QObject* object, QStringList filters) {

    const QMetaObject* meta = object->metaObject();

    bool res = false;

    for (int i = 0 ; i < meta->methodCount(); i++) {
        if (filters.indexOf(meta->method(i).name()) >= 0) {
            res = true;
            break;
        }
    }

    return res;
}

static void invokeMethod(QJSValue jsObject, QString method) {
    QJSValue func = jsObject.property(method);
    QJSValue result = func.call();

    if (result.isError()) {
        QStringList stack = result.property("stack").toString().split("\n");

        QStringList pair = stack[0].split("@");
        QString source = pair[1];

        if (source.indexOf("qrc:///Testable/TestableCase.qml") == 0) {
            pair = stack[1].split("@");
            source = pair[1];
        }

        QString message = result.property("message").toString();

        qWarning().noquote() << source + ":" << "Error:" << message;
    }
}

static void invokeMethodIfPresent(QObject* object, QString method, QJSValue jsObject) {
    if (hasMethod(object, method)) {
        invokeMethod(jsObject, method);
    }
}

static void invokeTestableCase(QQmlEngine* engine, QObject* object, QStringList filters) {
    const QMetaObject* meta = object->metaObject();

    QJSValue jsObject = engine->newQObject(object);

    invokeMethodIfPresent(object,"initTestCase", jsObject);

    for (int j = 0 ; j < meta->methodCount();j++) {
        const QMetaMethod method = meta->method(j);
        QString methodName = method.name();

        if (methodName.indexOf("test_") == 0 &&
            (filters.size() == 0 || filters.indexOf(methodName) >= 0)) {
            invokeMethodIfPresent(object, "init", jsObject);
            invokeMethod(jsObject,methodName);
//            QMetaObject::invokeMethod(object,methodName.toLocal8Bit().constData(),Qt::DirectConnection);
            invokeMethodIfPresent(object, "cleanup", jsObject);
        }
    }

    invokeMethodIfPresent(object,"cleanupTestCase", jsObject);
}

static QObjectList findAllChildren(QObject* object) {
    QObjectList result;

    result << object;

    foreach(QObject* child, object->children()) {
        result.append(findAllChildren(child));
    }

    if (inherited(object, "QQuickFlickable") || inherited(object, "QQuickWindow")) {
        QQuickItem* contentItem = object->property("contentItem").value<QQuickItem*>();
        if (contentItem) {

            QList<QQuickItem *>items = contentItem->childItems();

            foreach(QQuickItem* item, items) {
                result.append(findAllChildren(item));
            }

            result.append(findAllChildren(contentItem));
        }
    }

    return uniq(result);
}

Automator::Automator(QQmlApplicationEngine* engine) : QObject()
{
    setEngine(engine);
    m_anyError = false;
}

QQmlApplicationEngine *Automator::engine() const
{
    return m_engine;
}

void Automator::setEngine(QQmlApplicationEngine *engine)
{
    m_engine = engine;
    connect(engine,SIGNAL(warnings(QList<QQmlError>)),
            this,SLOT(onWarnings(QList<QQmlError>)));
}

void Automator::wait(int timeout) {

    QEventLoop loop;
    QTimer timer;
    QObject::connect(&timer,SIGNAL(timeout()),
            &loop,SLOT(quit()));
    timer.start(timeout);
    loop.exec();

}

QObject *Automator::findObject(QString objectName)
{
    QObjectList list = findObjects(objectName);
    QObject* res = 0;

    if (list.size() > 0) {
        res = list.first();
    }

    return res;
}

QObjectList Automator::findObjects(QString objectName)
{
    QObjectList result;
    QObject *firstObject = m_engine->rootObjects().first();

    if (!firstObject) {
        return result;
    }

    QObjectList subResult = findObjects(firstObject, objectName);

    if (subResult.size() > 0) {
        result << subResult;
    }

    return result;
}

bool Automator::waitExists(QString objectName, int timeout)
{
    QTime time;
    time.start();

    while (true) {
        QObject* object = findObject(objectName);
        if (object) {
            break;
        }
        wait(100);

        if (time.elapsed() > timeout) {
            qWarning() << "waitExists() : Time out";
            return false;
        }
    }

    return true;

}

bool Automator::waitUntil(QObject *object, QString property, QVariant value, int timeout)
{
    QVariant objectValue = object->property(property.toLocal8Bit().constData());
    QTime time;
    time.start();

    while (objectValue != value) {
        wait(100);
        objectValue = object->property(property.toLocal8Bit().constData());

        if (time.elapsed() > timeout) {
            qWarning() << "waitUntil() : Time out";
            return false;
        }
    }
    return true;
}

bool Automator::waitUntil(QString objectName, QString property, QVariant value, int timeout)
{
    QTime time;
    time.start();

    QObject* object = findObject(objectName);
    if (!object) {
        qWarning() << "Object not found" << objectName;
        return false;
    }

    return waitUntil(object, property, value, timeout);
}

bool Automator::click(QQuickItem *item, int delay,  QPointF pt)
{
    QQuickWindow* win = window();
    if (!win) {
        qWarning() << "click: No window object";
        return false;
    }

    QPointF hit;
    if (pt.isNull()) {
        int w = item->width();
        int h = item->height();
        int cx =  w /2;
        int cy =  h / 2;
        hit = item->mapToScene(QPointF(cx,cy));
    } else {
        hit = item->mapToScene(pt);
    }

    QTest::mouseClick(win, Qt::LeftButton,
                      Qt::NoModifier,
                      hit.toPoint(),
                      delay);
    return true;
}

bool Automator::click(QQuickItem *item, QString childObjectName)
{
    QObjectList list = findObjects(item, childObjectName);
    QQuickItem* child = 0;

    if (list.size() == 0) {
        return false;
    }

    child = qobject_cast<QQuickItem*>(list.first());
    if (!child) {
        return false;
    }

    return click(child);
}

bool Automator::click(QString objectName, int delay, QPointF point)
{
    QQuickItem* item = qobject_cast<QQuickItem*>(findObject(objectName));

    if (!item) {
        qWarning() << "Object not found" << objectName;
        return false;
    }

    return click(item, delay, point);
}

QObjectList Automator::findObjects(QObject *object, QString objectName)
{
    QObjectList result;

    if (!object) {
        return result;
    }

    if (object->objectName() == objectName) {
        result << object;
    }

    if ( inherited(object,"QQuickRepeater")) {
        int count = object->property("count").toInt();

        for (int i = 0 ;  i < count ;i++) {
            QQuickItem* item;
            QMetaObject::invokeMethod(object,"itemAt",Qt::DirectConnection,
                                      Q_RETURN_ARG(QQuickItem*,item),
                                      Q_ARG(int,i));
            QObjectList subResult = findObjects(item, objectName);
            if (subResult.size() > 0) {
                result.append(subResult);
            }
        }

    } else if (inherited(object, "QQuickFlickable") || inherited(object, "QQuickWindow")) {

        QQuickItem* contentItem = object->property("contentItem").value<QQuickItem*>();

        if (contentItem) {

            QList<QQuickItem *>items = contentItem->childItems() ;

            for (int i = 0 ;  i < items.size() ; i++) {
                QObjectList subResult = findObjects(items.at(i),objectName);
                if (subResult.size() > 0) {
                    result.append(subResult);
                }
            }

            QObjectList subResult = findObjects(contentItem, objectName);
            if (subResult.size() > 0) {
                result.append(subResult);
            }
        }
    }

    QObjectList children = object->children();

    for (int i = 0 ; i < children.size();i++) {
        QObjectList subResult = findObjects(children.at(i), objectName);

        if (subResult.size() > 0) {
            result.append(subResult);
        }
    }

    return uniq(result);
}

QQuickWindow *Automator::window()
{
    QObject *firstObject = m_engine->rootObjects().first();
    QQuickWindow *window = qobject_cast<QQuickWindow*>(firstObject);

    return window;
}

bool Automator::anyError() const
{
    return m_anyError;
}

void Automator::setAnyError(bool anyError)
{
    m_anyError = anyError;
}

bool Automator::runTestCase(QStringList filters) const
{
    QObjectList list = findAllChildren(m_engine->rootObjects().first());
    bool res = true;

    for (int i = 0 ; i < list.size() ; i++) {
        QObject* object = list.at(i);
        QString className = object->metaObject()->className();

        if (className.indexOf("TestableCase_QMLTYPE") == 0) {

            if (filters.size() == 0 ||
                hasMethods(object,filters)) {

                invokeTestableCase(m_engine.data(), object, filters);
            }
        }

        bool hasError = object->property("hasError").toBool();
        if (hasError) {
            res = false;
        }
    }

    return res;
}

QObject* Automator::obtainSingletonObject(QString package, int versionMajor, int versionMinor, QString typeName)
{
    /// Modified from QFAppDispatcher::singletonObject() in QuickFlux project
    QString pattern  = "import QtQuick 2.0\nimport %1 %2.%3;QtObject { property var object : %4 }";

    QString qml = pattern.arg(package).arg(versionMajor).arg(versionMinor).arg(typeName);

    QObject* holder = 0;

    QQmlComponent comp (m_engine.data());
    comp.setData(qml.toUtf8(),QUrl());
    holder = comp.create();

    if (!holder) {
        qWarning() << QString("Testable: Failed to gain singleton object: %1").arg(typeName);
        qWarning() << QString("Error: ") << comp.errorString();
        return 0;
    }

    QObject* object = holder->property("object").value<QObject*>();
    holder->deleteLater();

    if (!object) {
        qWarning() << QString("Testable: Failed to gain singleton object: %1").arg(typeName);
        qWarning() << QString("Error: Unknown");
    }

    return object;
}

QQuickItem *Automator::createTracker(QQuickItem *target, QColor color, qreal opacity)
{
    QString qml  = "import QtQuick 2.0\nRectangle {anchors.centerIn:parent; width: parent ? parent.width: 0; height:parent ? parent.height : 0; }";

    QQuickItem* tracker = 0;

    QQmlComponent comp (m_engine.data());
    comp.setData(qml.toUtf8(),QUrl());
    tracker = qobject_cast<QQuickItem*>(comp.create());

    Q_ASSERT(tracker);

    tracker->setParentItem(target);
    tracker->setProperty("color", color);
    tracker->setProperty("opacity", opacity);

    return tracker;
}

void Automator::onWarnings(QList<QQmlError> warnings)
{
    for (int i = 0 ; i < warnings.size();i++){
        if (warnings.at(i).toString().indexOf("Error") != -1) {
            setAnyError(true);
        }
    }
}
<commit_msg>Automator::runTestCase() - Minor changes on exception handling<commit_after>#include <QQuickWindow>
#include <QEventLoop>
#include <QTimer>
#include <QQuickItem>
#include <QTime>
#include <QTest>
#include "automator.h"

static bool inherited(QObject* object,QString className) {
    bool res = false;

    const QMetaObject *metaObject = object->metaObject();

    while (metaObject) {
        if (metaObject->className() == className) {
            res = true;
            break;
        }
        metaObject = metaObject->superClass();
    }

    return res;
}

static QObjectList uniq(const QObjectList& list) {

    QMap<QObject*, bool> map;
    QObjectList res;

    for (int i = 0 ; i < list.count() ;i++) {
        QObject* object = list.at(i);
        if (!map.contains(object)) {
            res << object;
            map[object] = true;
        }
    }

    return res;
}

static bool hasMethod(QObject* object, QString method) {
    const QMetaObject* meta = object->metaObject();

    int index = -1;

    for (int i = 0 ; i < meta->methodCount(); i++) {
        if (method == meta->method(i).name()) {
            index = i;
            break;
        }
    }

    return index >= 0;
}

static bool hasMethods(QObject* object, QStringList filters) {

    const QMetaObject* meta = object->metaObject();

    bool res = false;

    for (int i = 0 ; i < meta->methodCount(); i++) {
        if (filters.indexOf(meta->method(i).name()) >= 0) {
            res = true;
            break;
        }
    }

    return res;
}

static void invokeMethod(QJSValue jsObject, QString method) {
    QJSValue func = jsObject.property(method);
    QJSValue result = func.call();

    if (result.isError()) {
        QStringList stack = result.property("stack").toString().split("\n");

        QStringList pair = stack[0].split("@");
        QString source = pair[1];

        if (source.indexOf(QRegExp("qrc:/*Testable/TestableCase.qml")) == 0) {
            pair = stack[1].split("@");
            source = pair[1];
        }

        QString message = result.property("message").toString();

        qWarning().noquote() << source + ":" << "Error:" << message;
    }
}

static void invokeMethodIfPresent(QObject* object, QString method, QJSValue jsObject) {
    if (hasMethod(object, method)) {
        invokeMethod(jsObject, method);
    }
}

static void invokeTestableCase(QQmlEngine* engine, QObject* object, QStringList filters) {
    const QMetaObject* meta = object->metaObject();

    QJSValue jsObject = engine->newQObject(object);

    invokeMethodIfPresent(object,"initTestCase", jsObject);

    for (int j = 0 ; j < meta->methodCount();j++) {
        const QMetaMethod method = meta->method(j);
        QString methodName = method.name();

        if (methodName.indexOf("test_") == 0 &&
            (filters.size() == 0 || filters.indexOf(methodName) >= 0)) {
            invokeMethodIfPresent(object, "init", jsObject);
            invokeMethod(jsObject,methodName);
//            QMetaObject::invokeMethod(object,methodName.toLocal8Bit().constData(),Qt::DirectConnection);
            invokeMethodIfPresent(object, "cleanup", jsObject);
        }
    }

    invokeMethodIfPresent(object,"cleanupTestCase", jsObject);
}

static QObjectList findAllChildren(QObject* object) {
    QObjectList result;

    result << object;

    foreach(QObject* child, object->children()) {
        result.append(findAllChildren(child));
    }

    if (inherited(object, "QQuickFlickable") || inherited(object, "QQuickWindow")) {
        QQuickItem* contentItem = object->property("contentItem").value<QQuickItem*>();
        if (contentItem) {

            QList<QQuickItem *>items = contentItem->childItems();

            foreach(QQuickItem* item, items) {
                result.append(findAllChildren(item));
            }

            result.append(findAllChildren(contentItem));
        }
    }

    return uniq(result);
}

Automator::Automator(QQmlApplicationEngine* engine) : QObject()
{
    setEngine(engine);
    m_anyError = false;
}

QQmlApplicationEngine *Automator::engine() const
{
    return m_engine;
}

void Automator::setEngine(QQmlApplicationEngine *engine)
{
    m_engine = engine;
    connect(engine,SIGNAL(warnings(QList<QQmlError>)),
            this,SLOT(onWarnings(QList<QQmlError>)));
}

void Automator::wait(int timeout) {

    QEventLoop loop;
    QTimer timer;
    QObject::connect(&timer,SIGNAL(timeout()),
            &loop,SLOT(quit()));
    timer.start(timeout);
    loop.exec();

}

QObject *Automator::findObject(QString objectName)
{
    QObjectList list = findObjects(objectName);
    QObject* res = 0;

    if (list.size() > 0) {
        res = list.first();
    }

    return res;
}

QObjectList Automator::findObjects(QString objectName)
{
    QObjectList result;
    QObject *firstObject = m_engine->rootObjects().first();

    if (!firstObject) {
        return result;
    }

    QObjectList subResult = findObjects(firstObject, objectName);

    if (subResult.size() > 0) {
        result << subResult;
    }

    return result;
}

bool Automator::waitExists(QString objectName, int timeout)
{
    QTime time;
    time.start();

    while (true) {
        QObject* object = findObject(objectName);
        if (object) {
            break;
        }
        wait(100);

        if (time.elapsed() > timeout) {
            qWarning() << "waitExists() : Time out";
            return false;
        }
    }

    return true;

}

bool Automator::waitUntil(QObject *object, QString property, QVariant value, int timeout)
{
    QVariant objectValue = object->property(property.toLocal8Bit().constData());
    QTime time;
    time.start();

    while (objectValue != value) {
        wait(100);
        objectValue = object->property(property.toLocal8Bit().constData());

        if (time.elapsed() > timeout) {
            qWarning() << "waitUntil() : Time out";
            return false;
        }
    }
    return true;
}

bool Automator::waitUntil(QString objectName, QString property, QVariant value, int timeout)
{
    QTime time;
    time.start();

    QObject* object = findObject(objectName);
    if (!object) {
        qWarning() << "Object not found" << objectName;
        return false;
    }

    return waitUntil(object, property, value, timeout);
}

bool Automator::click(QQuickItem *item, int delay,  QPointF pt)
{
    QQuickWindow* win = window();
    if (!win) {
        qWarning() << "click: No window object";
        return false;
    }

    QPointF hit;
    if (pt.isNull()) {
        int w = item->width();
        int h = item->height();
        int cx =  w /2;
        int cy =  h / 2;
        hit = item->mapToScene(QPointF(cx,cy));
    } else {
        hit = item->mapToScene(pt);
    }

    QTest::mouseClick(win, Qt::LeftButton,
                      Qt::NoModifier,
                      hit.toPoint(),
                      delay);
    return true;
}

bool Automator::click(QQuickItem *item, QString childObjectName)
{
    QObjectList list = findObjects(item, childObjectName);
    QQuickItem* child = 0;

    if (list.size() == 0) {
        return false;
    }

    child = qobject_cast<QQuickItem*>(list.first());
    if (!child) {
        return false;
    }

    return click(child);
}

bool Automator::click(QString objectName, int delay, QPointF point)
{
    QQuickItem* item = qobject_cast<QQuickItem*>(findObject(objectName));

    if (!item) {
        qWarning() << "Object not found" << objectName;
        return false;
    }

    return click(item, delay, point);
}

QObjectList Automator::findObjects(QObject *object, QString objectName)
{
    QObjectList result;

    if (!object) {
        return result;
    }

    if (object->objectName() == objectName) {
        result << object;
    }

    if ( inherited(object,"QQuickRepeater")) {
        int count = object->property("count").toInt();

        for (int i = 0 ;  i < count ;i++) {
            QQuickItem* item;
            QMetaObject::invokeMethod(object,"itemAt",Qt::DirectConnection,
                                      Q_RETURN_ARG(QQuickItem*,item),
                                      Q_ARG(int,i));
            QObjectList subResult = findObjects(item, objectName);
            if (subResult.size() > 0) {
                result.append(subResult);
            }
        }

    } else if (inherited(object, "QQuickFlickable") || inherited(object, "QQuickWindow")) {

        QQuickItem* contentItem = object->property("contentItem").value<QQuickItem*>();

        if (contentItem) {

            QList<QQuickItem *>items = contentItem->childItems() ;

            for (int i = 0 ;  i < items.size() ; i++) {
                QObjectList subResult = findObjects(items.at(i),objectName);
                if (subResult.size() > 0) {
                    result.append(subResult);
                }
            }

            QObjectList subResult = findObjects(contentItem, objectName);
            if (subResult.size() > 0) {
                result.append(subResult);
            }
        }
    }

    QObjectList children = object->children();

    for (int i = 0 ; i < children.size();i++) {
        QObjectList subResult = findObjects(children.at(i), objectName);

        if (subResult.size() > 0) {
            result.append(subResult);
        }
    }

    return uniq(result);
}

QQuickWindow *Automator::window()
{
    QObject *firstObject = m_engine->rootObjects().first();
    QQuickWindow *window = qobject_cast<QQuickWindow*>(firstObject);

    return window;
}

bool Automator::anyError() const
{
    return m_anyError;
}

void Automator::setAnyError(bool anyError)
{
    m_anyError = anyError;
}

bool Automator::runTestCase(QStringList filters) const
{
    QObjectList list = findAllChildren(m_engine->rootObjects().first());
    bool res = true;

    for (int i = 0 ; i < list.size() ; i++) {
        QObject* object = list.at(i);
        QString className = object->metaObject()->className();

        if (className.indexOf("TestableCase_QMLTYPE") == 0) {

            if (filters.size() == 0 ||
                hasMethods(object,filters)) {

                invokeTestableCase(m_engine.data(), object, filters);
            }
        }

        bool hasError = object->property("hasError").toBool();
        if (hasError) {
            res = false;
        }
    }

    return res;
}

QObject* Automator::obtainSingletonObject(QString package, int versionMajor, int versionMinor, QString typeName)
{
    /// Modified from QFAppDispatcher::singletonObject() in QuickFlux project
    QString pattern  = "import QtQuick 2.0\nimport %1 %2.%3;QtObject { property var object : %4 }";

    QString qml = pattern.arg(package).arg(versionMajor).arg(versionMinor).arg(typeName);

    QObject* holder = 0;

    QQmlComponent comp (m_engine.data());
    comp.setData(qml.toUtf8(),QUrl());
    holder = comp.create();

    if (!holder) {
        qWarning() << QString("Testable: Failed to gain singleton object: %1").arg(typeName);
        qWarning() << QString("Error: ") << comp.errorString();
        return 0;
    }

    QObject* object = holder->property("object").value<QObject*>();
    holder->deleteLater();

    if (!object) {
        qWarning() << QString("Testable: Failed to gain singleton object: %1").arg(typeName);
        qWarning() << QString("Error: Unknown");
    }

    return object;
}

QQuickItem *Automator::createTracker(QQuickItem *target, QColor color, qreal opacity)
{
    QString qml  = "import QtQuick 2.0\nRectangle {anchors.centerIn:parent; width: parent ? parent.width: 0; height:parent ? parent.height : 0; }";

    QQuickItem* tracker = 0;

    QQmlComponent comp (m_engine.data());
    comp.setData(qml.toUtf8(),QUrl());
    tracker = qobject_cast<QQuickItem*>(comp.create());

    Q_ASSERT(tracker);

    tracker->setParentItem(target);
    tracker->setProperty("color", color);
    tracker->setProperty("opacity", opacity);

    return tracker;
}

void Automator::onWarnings(QList<QQmlError> warnings)
{
    for (int i = 0 ; i < warnings.size();i++){
        if (warnings.at(i).toString().indexOf("Error") != -1) {
            setAnyError(true);
        }
    }
}
<|endoftext|>


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

#include <realm.hpp>
#include "error_handling.hpp"
#include "marshalling.hpp"
#include "realm_export_decls.hpp"
#include "sync/sync_manager.hpp"
#include "sync/sync_user.hpp"
#include "sync/sync_session.hpp"

using namespace realm;
using namespace realm::binding;

using SharedSyncUser = std::shared_ptr<SyncUser>;
using SharedSyncSession = std::shared_ptr<SyncSession>;

extern "C" {

REALM_EXPORT SharedSyncUser* realm_get_sync_user(const uint16_t* identity_buf, size_t identity_len,
                                                 const uint16_t* auth_server_url_buf, size_t auth_server_url_len,
                                                 const uint16_t* refresh_token_buf, size_t refresh_token_len,
                                                 bool is_admin, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        Utf16StringAccessor identity(identity_buf, identity_len);
        Utf16StringAccessor auth_server_url(auth_server_url_buf, auth_server_url_len);
        Utf16StringAccessor refresh_token(refresh_token_buf, refresh_token_len);

        auto user = SyncManager::shared().get_user({identity, auth_server_url}, refresh_token);
        user->set_is_admin(is_admin);
        return new SharedSyncUser(user);
    });
}

REALM_EXPORT SharedSyncUser* realm_get_admintoken_user(const uint16_t* auth_server_url_buf, size_t auth_server_url_len,
                                                       const uint16_t* token_buf, size_t token_len,
                                                       NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        Utf16StringAccessor auth_server_url(auth_server_url_buf, auth_server_url_len);
        Utf16StringAccessor token(token_buf, token_len);

        return new SharedSyncUser(SyncManager::shared().get_admin_token_user(auth_server_url, token));
    });
}

REALM_EXPORT SharedSyncUser* realm_get_current_sync_user(NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&]() -> SharedSyncUser* {
        auto ptr = SyncManager::shared().get_current_user();
        if (ptr == nullptr) {
            return nullptr;
        }

        return new SharedSyncUser(std::move(ptr));
    });
}

REALM_EXPORT size_t realm_get_logged_in_users(SharedSyncUser** buffer, size_t buffer_length, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&]() -> size_t {
        auto users = SyncManager::shared().all_logged_in_users();
        if (users.size() > buffer_length) {
            return users.size();
        }

        if (users.size() <= 0) {
            return 0;
        }

        for (size_t i = 0; i < users.size(); i++) {
            buffer[i] = new SharedSyncUser(users.at(i));
        }

        return users.size();
    });
}

REALM_EXPORT SharedSyncUser* realm_get_logged_in_user(const uint16_t* identity_buf, size_t identity_len, const uint16_t* auth_server_url_buf, size_t auth_server_url_len, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&]() -> SharedSyncUser* {
        Utf16StringAccessor identity(identity_buf, identity_len);
        Utf16StringAccessor auth_server_url(auth_server_url_buf, auth_server_url_len);

        auto ptr = SyncManager::shared().get_existing_logged_in_user({identity, auth_server_url});
        if (ptr == nullptr) {
            return nullptr;
        }

        return new SharedSyncUser(std::move(ptr));
    });
}

REALM_EXPORT SharedSyncSession* realm_syncuser_get_session(SharedSyncUser& user, const uint16_t* path_buf, size_t path_len, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        Utf16StringAccessor path(path_buf, path_len);
        return new SharedSyncSession(user->session_for_on_disk_path(path));
    });
}

REALM_EXPORT void realm_syncuser_log_out(SharedSyncUser& user, NativeException::Marshallable& ex)
{
    handle_errors(ex, [&] {
        user->log_out();
    });
}

REALM_EXPORT size_t realm_syncuser_get_identity(SharedSyncUser& user, uint16_t* buffer, size_t buffer_length, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        std::string identity(user->identity());
        return stringdata_to_csharpstringbuffer(identity, buffer, buffer_length);
    });
}

REALM_EXPORT size_t realm_syncuser_get_refresh_token(SharedSyncUser& user, uint16_t* buffer, size_t buffer_length, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        std::string refresh_token(user->refresh_token());
        return stringdata_to_csharpstringbuffer(refresh_token, buffer, buffer_length);
    });
}

REALM_EXPORT size_t realm_syncuser_get_server_url(SharedSyncUser& user, uint16_t* buffer, size_t buffer_length, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        const std::string& server_url(user->server_url());
        return stringdata_to_csharpstringbuffer(server_url, buffer, buffer_length);
    });
}

REALM_EXPORT SyncUser::State realm_syncuser_get_state(SharedSyncUser& user, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        return user->state();
    });
}

REALM_EXPORT bool realm_syncuser_get_is_admin(SharedSyncUser& user)
{
    return user->is_admin();
}

REALM_EXPORT void realm_syncuser_destroy(SharedSyncUser* user)
{
    delete user;
}

}
<commit_msg>Handle case where looking up session by path might return null (#1630)<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

#include <realm.hpp>
#include "error_handling.hpp"
#include "marshalling.hpp"
#include "realm_export_decls.hpp"
#include "sync/sync_manager.hpp"
#include "sync/sync_user.hpp"
#include "sync/sync_session.hpp"

using namespace realm;
using namespace realm::binding;

using SharedSyncUser = std::shared_ptr<SyncUser>;
using SharedSyncSession = std::shared_ptr<SyncSession>;

extern "C" {

REALM_EXPORT SharedSyncUser* realm_get_sync_user(const uint16_t* identity_buf, size_t identity_len,
                                                 const uint16_t* auth_server_url_buf, size_t auth_server_url_len,
                                                 const uint16_t* refresh_token_buf, size_t refresh_token_len,
                                                 bool is_admin, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        Utf16StringAccessor identity(identity_buf, identity_len);
        Utf16StringAccessor auth_server_url(auth_server_url_buf, auth_server_url_len);
        Utf16StringAccessor refresh_token(refresh_token_buf, refresh_token_len);

        auto user = SyncManager::shared().get_user({identity, auth_server_url}, refresh_token);
        user->set_is_admin(is_admin);
        return new SharedSyncUser(user);
    });
}

REALM_EXPORT SharedSyncUser* realm_get_admintoken_user(const uint16_t* auth_server_url_buf, size_t auth_server_url_len,
                                                       const uint16_t* token_buf, size_t token_len,
                                                       NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        Utf16StringAccessor auth_server_url(auth_server_url_buf, auth_server_url_len);
        Utf16StringAccessor token(token_buf, token_len);

        return new SharedSyncUser(SyncManager::shared().get_admin_token_user(auth_server_url, token));
    });
}

REALM_EXPORT SharedSyncUser* realm_get_current_sync_user(NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&]() -> SharedSyncUser* {
        auto ptr = SyncManager::shared().get_current_user();
        if (ptr == nullptr) {
            return nullptr;
        }

        return new SharedSyncUser(std::move(ptr));
    });
}

REALM_EXPORT size_t realm_get_logged_in_users(SharedSyncUser** buffer, size_t buffer_length, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&]() -> size_t {
        auto users = SyncManager::shared().all_logged_in_users();
        if (users.size() > buffer_length) {
            return users.size();
        }

        if (users.size() <= 0) {
            return 0;
        }

        for (size_t i = 0; i < users.size(); i++) {
            buffer[i] = new SharedSyncUser(users.at(i));
        }

        return users.size();
    });
}

REALM_EXPORT SharedSyncUser* realm_get_logged_in_user(const uint16_t* identity_buf, size_t identity_len, const uint16_t* auth_server_url_buf, size_t auth_server_url_len, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&]() -> SharedSyncUser* {
        Utf16StringAccessor identity(identity_buf, identity_len);
        Utf16StringAccessor auth_server_url(auth_server_url_buf, auth_server_url_len);

        auto ptr = SyncManager::shared().get_existing_logged_in_user({identity, auth_server_url});
        if (ptr == nullptr) {
            return nullptr;
        }

        return new SharedSyncUser(std::move(ptr));
    });
}

REALM_EXPORT SharedSyncSession* realm_syncuser_get_session(SharedSyncUser& user, const uint16_t* path_buf, size_t path_len, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        Utf16StringAccessor path(path_buf, path_len);
        if (auto session = user->session_for_on_disk_path(path)) {
            return new SharedSyncSession(std::move(session));
        }
        return nullptr;
    });
}

REALM_EXPORT void realm_syncuser_log_out(SharedSyncUser& user, NativeException::Marshallable& ex)
{
    handle_errors(ex, [&] {
        user->log_out();
    });
}

REALM_EXPORT size_t realm_syncuser_get_identity(SharedSyncUser& user, uint16_t* buffer, size_t buffer_length, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        std::string identity(user->identity());
        return stringdata_to_csharpstringbuffer(identity, buffer, buffer_length);
    });
}

REALM_EXPORT size_t realm_syncuser_get_refresh_token(SharedSyncUser& user, uint16_t* buffer, size_t buffer_length, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        std::string refresh_token(user->refresh_token());
        return stringdata_to_csharpstringbuffer(refresh_token, buffer, buffer_length);
    });
}

REALM_EXPORT size_t realm_syncuser_get_server_url(SharedSyncUser& user, uint16_t* buffer, size_t buffer_length, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        const std::string& server_url(user->server_url());
        return stringdata_to_csharpstringbuffer(server_url, buffer, buffer_length);
    });
}

REALM_EXPORT SyncUser::State realm_syncuser_get_state(SharedSyncUser& user, NativeException::Marshallable& ex)
{
    return handle_errors(ex, [&] {
        return user->state();
    });
}

REALM_EXPORT bool realm_syncuser_get_is_admin(SharedSyncUser& user)
{
    return user->is_admin();
}

REALM_EXPORT void realm_syncuser_destroy(SharedSyncUser* user)
{
    delete user;
}

}
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(n)

class Solution {
public:
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1+1, index2+1] (index1 < index2)
     */
    vector<int> twoSum(vector<int> &nums, int target) {
        unordered_map<int, int> hash;

        for (int i = 0; i < nums.size(); ++i) {
            // Check if "target - nums[i]" exists or not
            if (hash.find(target - nums[i]) != hash.end()) {
                return vector<int>{hash[target - nums[i]] + 1, i + 1};
            }
            hash[nums[i]] = i;
        }

        return vector<int>();
    }
};

<commit_msg>update<commit_after>// Time:  O(n)
// Space: O(n)

class Solution {
public:
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1+1, index2+1] (index1 < index2)
     */
    vector<int> twoSum(vector<int> &nums, int target) {
        unordered_map<int, int> hash;

        for (int i = 0; i < nums.size(); ++i) {
            // Check if "target - nums[i]" exists or not
            if (hash.find(target - nums[i]) != hash.end()) {
                return {hash[target - nums[i]] + 1, i + 1};
            }
            hash[nums[i]] = i;
        }

        return {};
    }
};

<|endoftext|>


<commit_before>/*
 * Metric.hpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef MONITOR_METRIC_METRIC_HPP
#define MONITOR_METRIC_METRIC_HPP

#include <string>
#include <vector>

#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <core/json/Json.hpp>

namespace core {
   class Error;
}

namespace monitor {
namespace metrics {

// convenience base class for Metric and MultiMetric
class MetricBase
{
protected:
   MetricBase() {}

   MetricBase(const std::string& scope,
              int intervalSeconds,
              const std::string& type,
              const std::string& unit,
              boost::posix_time::ptime timestamp)
      : scope_(scope),
        intervalSeconds_(intervalSeconds),
        type_(type),
        unit_(unit),
        timestamp_(timestamp)
   {
   }

public:
   // check for empty
   bool isEmpty() const { return scope_.empty(); }

   // property accessors
   const std::string& scope() const { return scope_; }
   int intervalSeconds() const { return intervalSeconds_; }
   const std::string& type() const { return type_; }
   const std::string& unit() const { return unit_; }
   const boost::posix_time::ptime& timestamp() const { return timestamp_; }

private:
   std::string scope_;
   int intervalSeconds_;
   std::string type_;
   std::string unit_;
   boost::posix_time::ptime timestamp_;
};

struct MetricData
{
   MetricData()
      : value(0)
   {
   }

   MetricData(const MetricData& data)
      : name(data.name), value(data.value)
   {
   }

   MetricData(const std::string& name, double value)
      : name(name), value(value)
   {
   }

   bool isEmpty() const { return name.empty(); }

   std::string name;
   double value;
};

class Metric : public MetricBase
{
public:
   Metric() : MetricBase() {}

   Metric(const std::string& scope,
          int intervalSeconds,
          const MetricData& data,
          const std::string& type = "gauge",
          const std::string& unit = std::string(),
          boost::posix_time::ptime timestamp =
                     boost::posix_time::microsec_clock::universal_time())
      : MetricBase(scope, intervalSeconds, type, unit, timestamp),
        data_(data)
   {
   }

public:
   const MetricData& data() const { return data_; }

private:
   MetricData data_;
};

class MultiMetric : public MetricBase
{
public:
   MultiMetric() : MetricBase() {}

   MultiMetric(const std::string& scope,
               int intervalSeconds,
               const std::vector<MetricData>& data,
               const std::string& type = "gauge",
               const std::string& unit = std::string(),
               boost::posix_time::ptime timestamp =
                           boost::posix_time::microsec_clock::universal_time())
      : MetricBase(scope, intervalSeconds, type, unit, timestamp),
        data_(data)
   {
   }

public:
   const std::vector<MetricData>& data() const { return data_; }

private:
   std::vector<MetricData> data_;
};

// metric handlers
typedef boost::function<void(const Metric&)> MetricHandler;
typedef boost::function<void(const Metric&)> MultiMetricHandler;

// json serialization
core::json::Object metricToJson(const Metric& metric);
core::Error metricFromJson(const core::json::Object& metricJson,
                           Metric* pMetric);

core::json::Object metricToJson(const MultiMetric& multiMetric);
core::Error metricFromJson(const core::json::Object& multiMetricJson,
                           MultiMetric* pMultiMetric);

} // namespace metrics
} // namespace monitor

#endif // MONITOR_METRIC_METRIC_HPP

<commit_msg>correct typedef for multi metric handler<commit_after>/*
 * Metric.hpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef MONITOR_METRIC_METRIC_HPP
#define MONITOR_METRIC_METRIC_HPP

#include <string>
#include <vector>

#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <core/json/Json.hpp>

namespace core {
   class Error;
}

namespace monitor {
namespace metrics {

// convenience base class for Metric and MultiMetric
class MetricBase
{
protected:
   MetricBase() {}

   MetricBase(const std::string& scope,
              int intervalSeconds,
              const std::string& type,
              const std::string& unit,
              boost::posix_time::ptime timestamp)
      : scope_(scope),
        intervalSeconds_(intervalSeconds),
        type_(type),
        unit_(unit),
        timestamp_(timestamp)
   {
   }

public:
   // check for empty
   bool isEmpty() const { return scope_.empty(); }

   // property accessors
   const std::string& scope() const { return scope_; }
   int intervalSeconds() const { return intervalSeconds_; }
   const std::string& type() const { return type_; }
   const std::string& unit() const { return unit_; }
   const boost::posix_time::ptime& timestamp() const { return timestamp_; }

private:
   std::string scope_;
   int intervalSeconds_;
   std::string type_;
   std::string unit_;
   boost::posix_time::ptime timestamp_;
};

struct MetricData
{
   MetricData()
      : value(0)
   {
   }

   MetricData(const MetricData& data)
      : name(data.name), value(data.value)
   {
   }

   MetricData(const std::string& name, double value)
      : name(name), value(value)
   {
   }

   bool isEmpty() const { return name.empty(); }

   std::string name;
   double value;
};

class Metric : public MetricBase
{
public:
   Metric() : MetricBase() {}

   Metric(const std::string& scope,
          int intervalSeconds,
          const MetricData& data,
          const std::string& type = "gauge",
          const std::string& unit = std::string(),
          boost::posix_time::ptime timestamp =
                     boost::posix_time::microsec_clock::universal_time())
      : MetricBase(scope, intervalSeconds, type, unit, timestamp),
        data_(data)
   {
   }

public:
   const MetricData& data() const { return data_; }

private:
   MetricData data_;
};

class MultiMetric : public MetricBase
{
public:
   MultiMetric() : MetricBase() {}

   MultiMetric(const std::string& scope,
               int intervalSeconds,
               const std::vector<MetricData>& data,
               const std::string& type = "gauge",
               const std::string& unit = std::string(),
               boost::posix_time::ptime timestamp =
                           boost::posix_time::microsec_clock::universal_time())
      : MetricBase(scope, intervalSeconds, type, unit, timestamp),
        data_(data)
   {
   }

public:
   const std::vector<MetricData>& data() const { return data_; }

private:
   std::vector<MetricData> data_;
};

// metric handlers
typedef boost::function<void(const Metric&)> MetricHandler;
typedef boost::function<void(const MultiMetric&)> MultiMetricHandler;

// json serialization
core::json::Object metricToJson(const Metric& metric);
core::Error metricFromJson(const core::json::Object& metricJson,
                           Metric* pMetric);

core::json::Object metricToJson(const MultiMetric& multiMetric);
core::Error metricFromJson(const core::json::Object& multiMetricJson,
                           MultiMetric* pMultiMetric);

} // namespace metrics
} // namespace monitor

#endif // MONITOR_METRIC_METRIC_HPP

<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

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

// C++ includes
#include <iomanip>
#include <fstream>

// Local includes
#include "libmesh/libmesh_config.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/mesh_base.h"
#include "libmesh/medit_io.h"
#include "libmesh/elem.h"

namespace libMesh
{

// ------------------------------------------------------------
// MEDITIO  members
void MEDITIO::write (const std::string& fname)
{
  if (libMesh::processor_id() == 0)
    if (!this->binary())
      this->write_ascii  (fname);
}

void MEDITIO::write_nodal_data (const std::string& fname,
			      const std::vector<Number>& soln,
			      const std::vector<std::string>& names)
{
  START_LOG("write_nodal_data()", "MEDITIO");

  if (libMesh::processor_id() == 0)
    if (!this->binary())
      this->write_ascii  (fname, &soln, &names);

  STOP_LOG("write_nodal_data()", "MEDITIO");
}

void MEDITIO::write_ascii (const std::string& fname,
			   const std::vector<Number>* vec,
			   const std::vector<std::string>* solution_names)
{
  // Current lacks in implementation:
  //  (i)   only 3D meshes.
  //  (ii)  only QUAD4, TRI3, TET4 elements, others are omitted !
  //  (iii) no distinction between materials.
  //  (iv)  no vector output, just first scalar as output

  // libmesh_assert three dimensions (should be extended later)
  libmesh_assert_equal_to (MeshOutput<MeshBase>::mesh().mesh_dimension(), 3);

  // Open the output file stream
  std::ofstream out (fname.c_str());

  // Make sure it opened correctly
  if (!out.good())
    libmesh_file_error(fname.c_str());

  // Get a reference to the mesh
  const MeshBase& mesh = MeshOutput<MeshBase>::mesh();

  // Begin interfacing with the MEdit data file
  {
    // header:
    out << "MeshVersionFormatted  1\n";
    out << "Dimension  3\n";
    out << "# Mesh generated by libmesh\n\n";

    // write the nodes:
    out << "# Set of mesh vertices\n";
    out << "Vertices\n";
    out << mesh.n_nodes() << "\n";

    for (unsigned int v=0; v<mesh.n_nodes(); v++)
      out << mesh.point(v)(0) << " " << mesh.point(v)(1) << " " << mesh.point(v)(2) << " 0\n";
  }

  {
    // write the connectivity:
    out << "\n# Set of Polys\n\n";

    // count occurrences of output elements:
    int n_tri3  = 0;
    int n_quad4 = 0;
    int n_tet4  = 0;

    {
//       const_active_elem_iterator       it (mesh.elements_begin());
//       const const_active_elem_iterator end(mesh.elements_end());

      MeshBase::const_element_iterator       it  = mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = mesh.active_elements_end();

      for ( ; it != end; ++it)
	{
	  if ((*it)->type() == TRI3)  n_tri3++;
	  if ((*it)->type() == QUAD4) n_quad4++;
	  if ((*it)->type() == QUAD9) n_quad4+=4; // (QUAD9 is written as 4 QUAD4.)
	  if ((*it)->type() == TET4)  n_tet4++;
	} // for
    }

    // First: write out TRI3 elements:
    out << "Triangles\n";
    out << n_tri3 << "\n";

    {
//       const_active_elem_iterator       it (mesh.elements_begin());
//       const const_active_elem_iterator end(mesh.elements_end());

      MeshBase::const_element_iterator       it  = mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = mesh.active_elements_end();

      for ( ; it != end; ++it)
	if ((*it)->type() == TRI3)
	  out << (*it)->node(0)+1  << " " << (*it)->node(1)+1  << " " << (*it)->node(2)+1  << " 0\n";
    }

    // Second: write out QUAD4 elements:
    out << "Quadrilaterals\n";
    out << n_quad4 << "\n";

    {
//       const_active_elem_iterator       it (mesh.elements_begin());
//       const const_active_elem_iterator end(mesh.elements_end());

      MeshBase::const_element_iterator       it  = mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = mesh.active_elements_end();

      for ( ; it != end; ++it)
	if ((*it)->type() == QUAD4)
	  {
	    out << (*it)->node(0)+1  << " "
		<< (*it)->node(1)+1  << " "
		<< (*it)->node(2)+1  << " "
		<< (*it)->node(3)+1  <<" 0\n";
	  } // if
	else if ((*it)->type() == QUAD9)
	  {
	    out << (*it)->node(0)+1  << " "
		<< (*it)->node(4)+1  << " "
		<< (*it)->node(8)+1  << " "
		<< (*it)->node(7)+1  <<" 0\n";
	    out << (*it)->node(7)+1  << " "
		<< (*it)->node(8)+1  << " "
		<< (*it)->node(6)+1  << " "
		<< (*it)->node(3)+1  <<" 0\n";
	    out << (*it)->node(4)+1  << " "
		<< (*it)->node(1)+1  << " "
		<< (*it)->node(5)+1  << " "
		<< (*it)->node(8)+1  <<" 0\n";
	    out << (*it)->node(8)+1  << " "
		<< (*it)->node(5)+1  << " "
		<< (*it)->node(2)+1  << " "
		<< (*it)->node(6)+1  <<" 0\n";
	  } // if
    }

    // Third: write out TET4 elements:
    out << "Tetrahedra\n";
    out << n_tet4 << "\n";

    {
//       const_active_elem_iterator       it (mesh.elements_begin());
//       const const_active_elem_iterator end(mesh.elements_end());

      MeshBase::const_element_iterator       it  = mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = mesh.active_elements_end();

      for ( ; it != end; ++it)
	if ((*it)->type() == TET4)
	  {
	    out << (*it)->node(0)+1  << " "
		<< (*it)->node(1)+1  << " "
		<< (*it)->node(2)+1  << " "
		<< (*it)->node(3)+1  <<" 0\n";
	  } // if
    }

  }
  // end of the out file
  out << '\n' << "# end of file\n";

  // optionally write the data
  if ((solution_names != NULL) &&
      (vec != NULL))
    {
      // Open the ".bb" file stream
      int idx = fname.find_last_of(".");
      std::string bbname = fname.substr(0,idx) + ".bb";

      std::ofstream bbout (bbname.c_str());

      // Make sure it opened correctly
      if (!out.good())
        libmesh_file_error(bbname.c_str());

      // Header: 3: 3D mesh, 1: scalar output, 2: node-indexed
      const unsigned int n_vars = solution_names->size();
      bbout << "3 1 " << mesh.n_nodes() << " 2\n";
      for (unsigned int n=0; n<mesh.n_nodes(); n++)
	bbout << std::setprecision(10) << (*vec)[n*n_vars + scalar_idx] << " ";
      bbout << "\n";
    } // endif
}

} // namespace libMesh

<commit_msg>Changes in medit_io.C for -Wshadow.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

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

// C++ includes
#include <iomanip>
#include <fstream>

// Local includes
#include "libmesh/libmesh_config.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/mesh_base.h"
#include "libmesh/medit_io.h"
#include "libmesh/elem.h"

namespace libMesh
{

// ------------------------------------------------------------
// MEDITIO  members
void MEDITIO::write (const std::string& fname)
{
  if (libMesh::processor_id() == 0)
    if (!this->binary())
      this->write_ascii  (fname);
}

void MEDITIO::write_nodal_data (const std::string& fname,
			      const std::vector<Number>& soln,
			      const std::vector<std::string>& names)
{
  START_LOG("write_nodal_data()", "MEDITIO");

  if (libMesh::processor_id() == 0)
    if (!this->binary())
      this->write_ascii  (fname, &soln, &names);

  STOP_LOG("write_nodal_data()", "MEDITIO");
}

void MEDITIO::write_ascii (const std::string& fname,
			   const std::vector<Number>* vec,
			   const std::vector<std::string>* solution_names)
{
  // Current lacks in implementation:
  //  (i)   only 3D meshes.
  //  (ii)  only QUAD4, TRI3, TET4 elements, others are omitted !
  //  (iii) no distinction between materials.
  //  (iv)  no vector output, just first scalar as output

  // libmesh_assert three dimensions (should be extended later)
  libmesh_assert_equal_to (MeshOutput<MeshBase>::mesh().mesh_dimension(), 3);

  // Open the output file stream
  std::ofstream out_stream (fname.c_str());

  // Make sure it opened correctly
  if (!out_stream.good())
    libmesh_file_error(fname.c_str());

  // Get a reference to the mesh
  const MeshBase& the_mesh = MeshOutput<MeshBase>::mesh();

  // Begin interfacing with the MEdit data file
  {
    // header:
    out_stream << "MeshVersionFormatted  1\n";
    out_stream << "Dimension  3\n";
    out_stream << "# Mesh generated by libmesh\n\n";

    // write the nodes:
    out_stream << "# Set of mesh vertices\n";
    out_stream << "Vertices\n";
    out_stream << the_mesh.n_nodes() << "\n";

    for (unsigned int v=0; v<the_mesh.n_nodes(); v++)
      out_stream << the_mesh.point(v)(0) << " " << the_mesh.point(v)(1) << " " << the_mesh.point(v)(2) << " 0\n";
  }

  {
    // write the connectivity:
    out_stream << "\n# Set of Polys\n\n";

    // count occurrences of output elements:
    int n_tri3  = 0;
    int n_quad4 = 0;
    int n_tet4  = 0;

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
	{
	  if ((*it)->type() == TRI3)  n_tri3++;
	  if ((*it)->type() == QUAD4) n_quad4++;
	  if ((*it)->type() == QUAD9) n_quad4+=4; // (QUAD9 is written as 4 QUAD4.)
	  if ((*it)->type() == TET4)  n_tet4++;
	} // for
    }

    // First: write out TRI3 elements:
    out_stream << "Triangles\n";
    out_stream << n_tri3 << "\n";

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
	if ((*it)->type() == TRI3)
	  out_stream << (*it)->node(0)+1  << " " << (*it)->node(1)+1  << " " << (*it)->node(2)+1  << " 0\n";
    }

    // Second: write out QUAD4 elements:
    out_stream << "Quadrilaterals\n";
    out_stream << n_quad4 << "\n";

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
	if ((*it)->type() == QUAD4)
	  {
	    out_stream << (*it)->node(0)+1  << " "
		<< (*it)->node(1)+1  << " "
		<< (*it)->node(2)+1  << " "
		<< (*it)->node(3)+1  <<" 0\n";
	  } // if
	else if ((*it)->type() == QUAD9)
	  {
	    out_stream << (*it)->node(0)+1  << " "
		<< (*it)->node(4)+1  << " "
		<< (*it)->node(8)+1  << " "
		<< (*it)->node(7)+1  <<" 0\n";
	    out_stream << (*it)->node(7)+1  << " "
		<< (*it)->node(8)+1  << " "
		<< (*it)->node(6)+1  << " "
		<< (*it)->node(3)+1  <<" 0\n";
	    out_stream << (*it)->node(4)+1  << " "
		<< (*it)->node(1)+1  << " "
		<< (*it)->node(5)+1  << " "
		<< (*it)->node(8)+1  <<" 0\n";
	    out_stream << (*it)->node(8)+1  << " "
		<< (*it)->node(5)+1  << " "
		<< (*it)->node(2)+1  << " "
		<< (*it)->node(6)+1  <<" 0\n";
	  } // if
    }

    // Third: write out TET4 elements:
    out_stream << "Tetrahedra\n";
    out_stream << n_tet4 << "\n";

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
	if ((*it)->type() == TET4)
	  {
	    out_stream << (*it)->node(0)+1  << " "
		<< (*it)->node(1)+1  << " "
		<< (*it)->node(2)+1  << " "
		<< (*it)->node(3)+1  <<" 0\n";
	  } // if
    }

  }
  // end of the out file
  out_stream << '\n' << "# end of file\n";

  // optionally write the data
  if ((solution_names != NULL) &&
      (vec != NULL))
    {
      // Open the ".bb" file stream
      int idx = fname.find_last_of(".");
      std::string bbname = fname.substr(0,idx) + ".bb";

      std::ofstream bbout (bbname.c_str());

      // Make sure it opened correctly
      if (!bbout.good())
        libmesh_file_error(bbname.c_str());

      // Header: 3: 3D mesh, 1: scalar output, 2: node-indexed
      const unsigned int n_vars = solution_names->size();
      bbout << "3 1 " << the_mesh.n_nodes() << " 2\n";
      for (unsigned int n=0; n<the_mesh.n_nodes(); n++)
	bbout << std::setprecision(10) << (*vec)[n*n_vars + scalar_idx] << " ";
      bbout << "\n";
    } // endif
}

} // namespace libMesh

<|endoftext|>


<commit_before><commit_msg>ApeAssimpAssetLoader, texture support was added<commit_after><|endoftext|>


<commit_before>#include "MainCamera.h"
#include "Utility.hpp"
#include "Matrix.h"
#include "LightCullingUtility.h"
#include "CameraManager.h"
#include "ObjectManager.h"

using namespace Utility;
using namespace Device;
using namespace Core;
using namespace Rendering;
using namespace Rendering::Buffer;
using namespace Rendering::Shader;
using namespace Rendering::Camera;
using namespace Device;
using namespace Math;
using namespace Rendering::Manager;
using namespace Rendering::Geometry;

void MainCamera::Initialize(DirectX& dx, ShaderManager& shaderMgr, const Rect<uint>& rect)
{
	// setting desc
	{
		auto size = rect.size.Cast<float>();
		_desc.aspect = size.w / size.h;
		_desc.renderRect = rect;
	}

	_camCB.Initialize(dx);
}

bool MainCamera::UpdateCB(Device::DirectX & dx, const Core::Transform& dirtyTransform)
{
	assert(dirtyTransform.GetObjectID() == _objID);

	bool changedTF = dirtyTransform.GetDirty() | _dirty;
	if (changedTF)
		_camCBChangeState = TransformCB::ChangeState::HasChanged;

	if ((_camCBChangeState != TransformCB::ChangeState::No) == false)
		return false;

	const Matrix& worldMat = dirtyTransform.GetWorldMatrix();

	{
		_camCBData.viewMat = Matrix::ComputeViewMatrix(worldMat);
		Matrix& viewMat = _camCBData.viewMat;

		_projMat = ComputePerspectiveMatrix(true);
		_viewProjMat = viewMat * _projMat;

		_camCBData.viewProjMat = _viewProjMat;

		_camCBData.worldPos = Vector3(worldMat._41, worldMat._42, worldMat._43);
		_camCBData.prevViewProjMat = _prevViewProjMat;
		_camCBData.packedCamNearFar = (Half(_desc.near).GetValue() << 16) | Half(_desc.far).GetValue();
	}

	// Make Frustum
	if (changedTF)
	{
		Matrix notInvProj = ComputePerspectiveMatrix(false);
		_frustum.Make(_camCBData.viewMat * notInvProj);
	}

	_camCBData.viewMat				= Matrix::Transpose(_camCBData.viewMat);
	_camCBData.viewProjMat			= Matrix::Transpose(_camCBData.viewProjMat);
	_camCBData.prevViewProjMat		= Matrix::Transpose(_camCBData.prevViewProjMat);

	_camCB.UpdateSubResource(dx, _camCBData);

	_camCBChangeState = TransformCB::ChangeState((static_cast<uint>(_camCBChangeState) + 1) % static_cast<uint>(TransformCB::ChangeState::MAX));
	_prevViewProjMat = _viewProjMat;

	_dirty = false;
	return true;
}

Math::Matrix MainCamera::ComputePerspectiveMatrix(bool isInverted) const
{
	float fovRadian = DEG_2_RAD(_desc.fieldOfViewDegree);

	float near = _desc.near;
	float far = _desc.far;

	if (isInverted)
		std::swap(near, far);

	return Matrix::PerspectiveFovLH(_desc.aspect, fovRadian, near, far);
}

Math::Matrix Rendering::Camera::MainCamera::ComputeOrthogonalMatrix(bool isInverted) const
{
	float near = _desc.near;
	float far = _desc.far;

	if (isInverted)
		std::swap(near, far);

	auto size = _desc.renderRect.size.Cast<float>();
	return Matrix::OrthoLH(size.w, size.h, near, far);
}

const Transform& MainCamera::_FindTransform(
	const Geometry::Mesh& mesh,
	const Core::TransformPool& transformPool)
{
	auto id = mesh.GetObjectID();
	uint findIdx = transformPool.GetIndexer().Find(id.Literal());
	assert(findIdx != TransformPool::IndexerType::FailIndex());

	return transformPool.Get(findIdx);
}

void MainCamera::_SortTransparentMesh(const Core::TransformPool& transformPool)
{
	//camCBData was transposed.
	Vector3 viewDir = Vector3(	_camCBData.viewMat._31,
								_camCBData.viewMat._32,
								_camCBData.viewMat._33	);

	auto SortingByDistance = [&transformPool, &viewDir](const Mesh* left, const Mesh* right) -> bool
	{
		auto SortKey = [&viewDir, &transformPool](const Mesh* mesh) -> float
		{
			auto& pos = MainCamera::_FindTransform(*mesh, transformPool).GetWorldPosition();

			return Vector3::Dot(pos, viewDir);
		};

		return SortKey(left) < SortKey(right);
	};

	std::sort(_transparentMeshes.begin(), _transparentMeshes.end(), SortingByDistance);
}<commit_msg>MainCamera - ClassifyTransparentMesh 관련 기능 제거<commit_after>#include "MainCamera.h"
#include "Utility.hpp"
#include "Matrix.h"
#include "LightCullingUtility.h"
#include "CameraManager.h"
#include "ObjectManager.h"

using namespace Utility;
using namespace Device;
using namespace Core;
using namespace Rendering;
using namespace Rendering::Buffer;
using namespace Rendering::Shader;
using namespace Rendering::Camera;
using namespace Device;
using namespace Math;
using namespace Rendering::Manager;
using namespace Rendering::Geometry;

void MainCamera::Initialize(DirectX& dx, ShaderManager& shaderMgr, const Rect<uint>& rect)
{
	// setting desc
	{
		auto size = rect.size.Cast<float>();
		_desc.aspect = size.w / size.h;
		_desc.renderRect = rect;
	}

	_camCB.Initialize(dx);
}

bool MainCamera::UpdateCB(Device::DirectX & dx, const Core::Transform& dirtyTransform)
{
	assert(dirtyTransform.GetObjectID() == _objID);

	bool changedTF = dirtyTransform.GetDirty() | _dirty;
	if (changedTF)
		_camCBChangeState = TransformCB::ChangeState::HasChanged;

	if ((_camCBChangeState != TransformCB::ChangeState::No) == false)
		return false;

	const Matrix& worldMat = dirtyTransform.GetWorldMatrix();

	{
		_camCBData.viewMat = Matrix::ComputeViewMatrix(worldMat);
		Matrix& viewMat = _camCBData.viewMat;

		_projMat = ComputePerspectiveMatrix(true);
		_viewProjMat = viewMat * _projMat;

		_camCBData.viewProjMat = _viewProjMat;

		_camCBData.worldPos = Vector3(worldMat._41, worldMat._42, worldMat._43);
		_camCBData.prevViewProjMat = _prevViewProjMat;
		_camCBData.packedCamNearFar = (Half(_desc.near).GetValue() << 16) | Half(_desc.far).GetValue();
	}

	// Make Frustum
	if (changedTF)
	{
		Matrix notInvProj = ComputePerspectiveMatrix(false);
		_frustum.Make(_camCBData.viewMat * notInvProj);
	}

	_camCBData.viewMat				= Matrix::Transpose(_camCBData.viewMat);
	_camCBData.viewProjMat			= Matrix::Transpose(_camCBData.viewProjMat);
	_camCBData.prevViewProjMat		= Matrix::Transpose(_camCBData.prevViewProjMat);

	_camCB.UpdateSubResource(dx, _camCBData);

	_camCBChangeState = TransformCB::ChangeState((static_cast<uint>(_camCBChangeState) + 1) % static_cast<uint>(TransformCB::ChangeState::MAX));
	_prevViewProjMat = _viewProjMat;

	_dirty = false;
	return true;
}

Math::Matrix MainCamera::ComputePerspectiveMatrix(bool isInverted) const
{
	float fovRadian = DEG_2_RAD(_desc.fieldOfViewDegree);

	float near = _desc.near;
	float far = _desc.far;

	if (isInverted)
		std::swap(near, far);

	return Matrix::PerspectiveFovLH(_desc.aspect, fovRadian, near, far);
}

Math::Matrix Rendering::Camera::MainCamera::ComputeOrthogonalMatrix(bool isInverted) const
{
	float near = _desc.near;
	float far = _desc.far;

	if (isInverted)
		std::swap(near, far);

	auto size = _desc.renderRect.size.Cast<float>();
	return Matrix::OrthoLH(size.w, size.h, near, far);
}
<|endoftext|>


<commit_before>// Copyright (c) 2014 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "eutil.h"
#include "el_ini_parser.h"

namespace el {

enum class Type {
  TYPE_ERR = 0,
  TYPE_EOF,
  TYPE_COMMENT,

  TYPE_VALUE,

  TYPE_LBRACKET,
  TYPE_RBRACKET,
  TYPE_ASSIGN,
};

class IniLexer : private UnCopyable {
  enum {BSIZE = 256};
  enum class State {
    STATE_BEGIN = 0,
    STATE_FINISH,

    STATE_VALUE,
    STATE_COMMENT,
  };

  typedef std::shared_ptr<FILE> FilePtr;

  int     lineno_;
  int     bsize_;
  bool    eof_;
  FilePtr file_;
  int     lexpos_;
  char    lexbuf_[BSIZE];
public:
  IniLexer(void);
  ~IniLexer(void);

  bool Open(const char* fname);
  void Close(void);

  Type GetToken(std::string& token);
private:
  int GetChar(void);
  void UngetChar(void);

  Type LexerBegin(int c, State& out_state, bool& out_save);
  Type LexerFinish(int c, State& out_state, bool& out_save);
  Type LexerValue(int c, State& out_state, bool& out_save);
  Type LexerComment(int c, State& out_state, bool& out_save);
};

IniLexer::IniLexer(void)
  : lineno_(1)
  , bsize_(0)
  , eof_(false)
  , file_(FilePtr(nullptr))
  , lexpos_(0) {
}

IniLexer::~IniLexer(void) {
}

bool IniLexer::Open(const char* fname) {
  file_.reset(fopen(fname, "r"), fclose);
  if (!file_)
    return false;

  lineno_ = 1;
  bsize_  = 0;
  eof_    = false;
  lexpos_ = 0;

  return true;
}

void IniLexer::Close(void) {
}

Type IniLexer::GetToken(std::string& token) {
  Type type = Type::TYPE_ERR;
  State state = State::STATE_BEGIN;
  bool  save;
  int   c;

  token.clear();
  while (State::STATE_FINISH != state) {
    c = GetChar();
    save = true;

    switch (state) {
    case State::STATE_BEGIN:
      type = LexerBegin(c, state, save);
      break;
    case State::STATE_FINISH:
      type = LexerFinish(c, state, save);
      break;
    case State::STATE_VALUE:
      type = LexerValue(c, state, save);
      break;
    case State::STATE_COMMENT:
      type = LexerComment(c, state, save);
      break;
    }

    if (save)
      token += static_cast<char>(c);
  }

  return type;
}

int IniLexer::GetChar(void) {
  if (lexpos_ >= bsize_) {
    if (nullptr != fgets(lexbuf_, BSIZE, file_.get())) {
      bsize_ = static_cast<int>(strlen(lexbuf_));
      lexpos_ = 0;
    }
    else {
      eof_ = true;
      return EOF;
    }
  }

  return lexbuf_[lexpos_++];
}

void IniLexer::UngetChar(void) {
  if (!eof_)
    --lexpos_;
}

Type IniLexer::LexerBegin(
    int c, State& out_state, bool& out_save) {
  Type type = Type::TYPE_ERR;

  if (' ' == c || '\t' == c) {
    out_save = false;
  }
  else if ('\n' == c) {
    out_save = false;
    ++lineno_;
  }
  else if ('#' == c) {
    out_state = State::STATE_COMMENT;
    out_save = false;
  }
  else if ('[' == c) {
    out_state = State::STATE_FINISH;
    type = Type::TYPE_LBRACKET;
  }
  else if (']' == c) {
    out_state = State::STATE_FINISH;
    type = Type::TYPE_RBRACKET;
  }
  else if ('=' == c) {
    out_state = State::STATE_FINISH;
    type = Type::TYPE_ASSIGN;
  }
  else if (EOF == c) {
    out_state = State::STATE_FINISH;
    out_save = false;
    type = Type::TYPE_EOF;
  }
  else {
    out_state = State::STATE_VALUE;
  }

  return type;
}

Type IniLexer::LexerFinish(
    int c, State& out_state, bool& out_save) {
  out_state = State::STATE_FINISH;
  out_save = false;

  return Type::TYPE_ERR;;
}

Type IniLexer::LexerValue(
    int c, State& out_state, bool& out_save) {
  if (' ' == c || '\t' == c || '\n' == c
      || '#' == c || '=' == c || ']' == c) {
    if ('\n' == c || '#' == c || '=' == c || ']' == c)
      UngetChar();

    out_state = State::STATE_FINISH;
    out_save = false;

    return Type::TYPE_VALUE;
  }

  return Type::TYPE_ERR;
}

Type IniLexer::LexerComment(
    int c, State& out_state, bool& out_save) {
  out_save = false;
  if (EOF == c) {
    out_state = State::STATE_FINISH;
    return Type::TYPE_EOF;
  }
  else if ('\n' == c) {
    ++lineno_;
    out_state = State::STATE_BEGIN;
  }

  return Type::TYPE_ERR;
}

IniParser::IniParser(void)
  : lexer_(IniLexerPtr(new IniLexer()))
  , section_("") {
}

IniParser::~IniParser(void) {
}

bool IniParser::Open(const char* fname) {
  if (!lexer_->Open(fname))
    return false;
  section_ = "";
  values_.clear();

  Parse();

  return true;
}

void IniParser::Close(void) {
  if (lexer_) {
    lexer_->Close();

    section_ = "";
    values_.clear();
  }
}

std::string IniParser::Get(
    const std::string& section, const std::string& key) {
  std::string value_key(section + key);

  IniValueMap::iterator found(values_.find(value_key));
  if (found != values_.end())
    return (*found).second;

  return std::string("");
}

void IniParser::Parse(void) {
  std::string token;
  Type type;
  do {
    type = lexer_->GetToken(token);
    if (Type::TYPE_LBRACKET == type)
      ParseSection();
    else if (Type::TYPE_VALUE == type)
      ParseValue(token);
  } while(Type::TYPE_EOF != type);
}

void IniParser::ParseSection(void) {
  std::string token;
  Type type = lexer_->GetToken(token);
  EL_ASSERT(Type::TYPE_VALUE == type);

  section_ = token;
  EL_ASSERT(Type::TYPE_RBRACKET == lexer_->GetToken(token));
}

void IniParser::ParseValue(const std::string& value) {
  std::string token;
  EL_ASSERT(Type::TYPE_ASSIGN == lexer_->GetToken(token));

  EL_ASSERT(Type::TYPE_VALUE == lexer_->GetToken(token));

  std::string key(section_ + value);
  values_.insert(std::make_pair(key, token));
}

}
<commit_msg>chore(ini): updated ini parser<commit_after>// Copyright (c) 2014 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "eutil.h"
#include "el_ini_parser.h"

namespace el {

enum class Type {
  TYPE_ERR = 0,
  TYPE_EOF,
  TYPE_COMMENT,

  TYPE_VALUE,

  TYPE_LBRACKET,
  TYPE_RBRACKET,
  TYPE_ASSIGN,
};

class IniLexer : private UnCopyable {
  enum {BSIZE = 256};
  enum class State {
    STATE_BEGIN = 0,
    STATE_FINISH,

    STATE_VALUE,
    STATE_COMMENT,
  };

  typedef std::unique_ptr<FILE, decltype(fclose)*> FilePtr;

  int     lineno_;
  int     bsize_;
  bool    eof_;
  FilePtr file_;
  int     lexpos_;
  char    lexbuf_[BSIZE];
public:
  IniLexer(void);
  ~IniLexer(void);

  bool Open(const char* fname);
  void Close(void);

  Type GetToken(std::string& token);
private:
  int GetChar(void);
  void UngetChar(void);

  Type LexerBegin(int c, State& out_state, bool& out_save);
  Type LexerFinish(int c, State& out_state, bool& out_save);
  Type LexerValue(int c, State& out_state, bool& out_save);
  Type LexerComment(int c, State& out_state, bool& out_save);
};

IniLexer::IniLexer(void)
  : lineno_(1)
  , bsize_(0)
  , eof_(false)
  , file_(FilePtr(nullptr, fclose))
  , lexpos_(0) {
}

IniLexer::~IniLexer(void) {
}

bool IniLexer::Open(const char* fname) {
  file_.reset(fopen(fname, "r"));
  if (!file_)
    return false;

  lineno_ = 1;
  bsize_  = 0;
  eof_    = false;
  lexpos_ = 0;

  return true;
}

void IniLexer::Close(void) {
}

Type IniLexer::GetToken(std::string& token) {
  Type type = Type::TYPE_ERR;
  State state = State::STATE_BEGIN;
  bool  save;
  int   c;

  token.clear();
  while (State::STATE_FINISH != state) {
    c = GetChar();
    save = true;

    switch (state) {
    case State::STATE_BEGIN:
      type = LexerBegin(c, state, save);
      break;
    case State::STATE_FINISH:
      type = LexerFinish(c, state, save);
      break;
    case State::STATE_VALUE:
      type = LexerValue(c, state, save);
      break;
    case State::STATE_COMMENT:
      type = LexerComment(c, state, save);
      break;
    }

    if (save)
      token += static_cast<char>(c);
  }

  return type;
}

int IniLexer::GetChar(void) {
  if (lexpos_ >= bsize_) {
    if (nullptr != fgets(lexbuf_, BSIZE, file_.get())) {
      bsize_ = static_cast<int>(strlen(lexbuf_));
      lexpos_ = 0;
    }
    else {
      eof_ = true;
      return EOF;
    }
  }

  return lexbuf_[lexpos_++];
}

void IniLexer::UngetChar(void) {
  if (!eof_)
    --lexpos_;
}

Type IniLexer::LexerBegin(
    int c, State& out_state, bool& out_save) {
  Type type = Type::TYPE_ERR;

  if (' ' == c || '\t' == c) {
    out_save = false;
  }
  else if ('\n' == c) {
    out_save = false;
    ++lineno_;
  }
  else if ('#' == c) {
    out_state = State::STATE_COMMENT;
    out_save = false;
  }
  else if ('[' == c) {
    out_state = State::STATE_FINISH;
    type = Type::TYPE_LBRACKET;
  }
  else if (']' == c) {
    out_state = State::STATE_FINISH;
    type = Type::TYPE_RBRACKET;
  }
  else if ('=' == c) {
    out_state = State::STATE_FINISH;
    type = Type::TYPE_ASSIGN;
  }
  else if (EOF == c) {
    out_state = State::STATE_FINISH;
    out_save = false;
    type = Type::TYPE_EOF;
  }
  else {
    out_state = State::STATE_VALUE;
  }

  return type;
}

Type IniLexer::LexerFinish(
    int c, State& out_state, bool& out_save) {
  out_state = State::STATE_FINISH;
  out_save = false;

  return Type::TYPE_ERR;;
}

Type IniLexer::LexerValue(
    int c, State& out_state, bool& out_save) {
  if (' ' == c || '\t' == c || '\n' == c
      || '#' == c || '=' == c || ']' == c) {
    if ('\n' == c || '#' == c || '=' == c || ']' == c)
      UngetChar();

    out_state = State::STATE_FINISH;
    out_save = false;

    return Type::TYPE_VALUE;
  }

  return Type::TYPE_ERR;
}

Type IniLexer::LexerComment(
    int c, State& out_state, bool& out_save) {
  out_save = false;
  if (EOF == c) {
    out_state = State::STATE_FINISH;
    return Type::TYPE_EOF;
  }
  else if ('\n' == c) {
    ++lineno_;
    out_state = State::STATE_BEGIN;
  }

  return Type::TYPE_ERR;
}

IniParser::IniParser(void)
  : lexer_(new IniLexer())
  , section_("") {
}

IniParser::~IniParser(void) {
}

bool IniParser::Open(const char* fname) {
  if (!lexer_->Open(fname))
    return false;
  section_ = "";
  values_.clear();

  Parse();

  return true;
}

void IniParser::Close(void) {
  if (lexer_) {
    lexer_->Close();

    section_ = "";
    values_.clear();
  }
}

std::string IniParser::Get(
    const std::string& section, const std::string& key) {
  std::string value_key(section + key);

  IniValueMap::iterator found(values_.find(value_key));
  if (found != values_.end())
    return (*found).second;

  return std::string("");
}

void IniParser::Parse(void) {
  std::string token;
  Type type;
  do {
    type = lexer_->GetToken(token);
    if (Type::TYPE_LBRACKET == type)
      ParseSection();
    else if (Type::TYPE_VALUE == type)
      ParseValue(token);
  } while(Type::TYPE_EOF != type);
}

void IniParser::ParseSection(void) {
  std::string token;
  Type type = lexer_->GetToken(token);
  EL_ASSERT(Type::TYPE_VALUE == type);

  section_ = token;
  EL_ASSERT(Type::TYPE_RBRACKET == lexer_->GetToken(token));
}

void IniParser::ParseValue(const std::string& value) {
  std::string token;
  EL_ASSERT(Type::TYPE_ASSIGN == lexer_->GetToken(token));

  EL_ASSERT(Type::TYPE_VALUE == lexer_->GetToken(token));

  std::string key(section_ + value);
  values_.insert(std::make_pair(key, token));
}

}
<|endoftext|>


<commit_before>/*  -*- c++ -*-
    htmlstatusbar.cpp

    This file is part of KMail, the KDE mail client.
    Copyright (c) 2002 Ingo Kloecker <kloecker@kde.org>
    Copyright (c) 2003 Marc Mutz <mutz@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "htmlstatusbar.h"

#ifndef KMAIL_TESTING
#include "kmkernel.h"
#else
#endif

#include <klocale.h>
#include <kconfig.h>
#include <kconfiggroup.h>

#include <QColor>
#include <QString>
//Added by qt3to4:
#include <QLabel>

KMail::HtmlStatusBar::HtmlStatusBar( QWidget * parent, const char * name, Qt::WFlags f )
  : QLabel( parent, f ),
    mMode( Normal )
{
  setObjectName( name );
  setAlignment( Qt::AlignHCenter | Qt::AlignTop );
  // Don't force a minimum height to the reader widget
  setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Ignored ) );
  upd();
}

KMail::HtmlStatusBar::~HtmlStatusBar() {}

void KMail::HtmlStatusBar::upd() {
  QPalette pal = palette();
  pal.setColor( backgroundRole(), bgColor() );
  pal.setColor( foregroundRole(), fgColor() );
  setPalette( pal );
  setText( message() );
}

void KMail::HtmlStatusBar::setNormalMode() {
  setMode( Normal );
}

void KMail::HtmlStatusBar::setHtmlMode() {
  setMode( Html );
}

void KMail::HtmlStatusBar::setNeutralMode() {
  setMode( Neutral );
}

void KMail::HtmlStatusBar::setMode( Mode m ) {
  if ( m == mode() )
    return;
  mMode = m;
  upd();
}

QString KMail::HtmlStatusBar::message() const {
  switch ( mode() ) {
  case Html: // bold: "HTML Message"
    return i18n( "<qt>
H
T
M
L
 "
		 "
M
e
s
s
a
g
e</qt>" );
  case Normal: // normal: "No HTML Message"
    return i18n( "<qt>
N
o
 "
		 "
H
T
M
L
 "
		 "
M
e
s
s
a
g
e</qt>" );
  default:
  case Neutral:
    return QString();
  }
}

namespace {
  inline KConfig * config() {
#ifndef KMAIL_TESTING
    return KMKernel::config();
#else
    return kApp->config();
#endif
  }
}

QColor KMail::HtmlStatusBar::fgColor() const {
  KConfigGroup conf( config(), "Reader" );
  QColor def;
  switch ( mode() ) {
  case Html:
    def = Qt::white;
    return conf.readEntry( "ColorbarForegroundHTML", def );
  case Normal:
    def = Qt::black;
    return conf.readEntry( "ColorbarForegroundPlain", def );
  default:
  case Neutral:
    return Qt::black;
  }
}

QColor KMail::HtmlStatusBar::bgColor() const {
  KConfigGroup conf( config(), "Reader" );

  QColor def;
  switch ( mode() ) {
  case Html:
    def = Qt::black;
    return conf.readEntry( "ColorbarBackgroundHTML", def );
  case Normal:
    def = Qt::lightGray;
    return conf.readEntry( "ColorbarBackgroundPlain", def );
  default:
  case Neutral:
    return Qt::white;
  }
}

#include "htmlstatusbar.moc"
<commit_msg>HTML statusbar: - show the correct background color again - remove tabs<commit_after>/*  -*- c++ -*-
    htmlstatusbar.cpp

    This file is part of KMail, the KDE mail client.
    Copyright (c) 2002 Ingo Kloecker <kloecker@kde.org>
    Copyright (c) 2003 Marc Mutz <mutz@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "htmlstatusbar.h"

#ifndef KMAIL_TESTING
#include "kmkernel.h"
#else
#endif

#include <klocale.h>
#include <kconfig.h>
#include <kconfiggroup.h>

#include <QColor>
#include <QString>
//Added by qt3to4:
#include <QLabel>

KMail::HtmlStatusBar::HtmlStatusBar( QWidget * parent, const char * name, Qt::WFlags f )
  : QLabel( parent, f ),
    mMode( Normal )
{
  setObjectName( name );
  setAlignment( Qt::AlignHCenter | Qt::AlignTop );
  // Don't force a minimum height to the reader widget
  setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Ignored ) );
  setAutoFillBackground( true );
  upd();
}

KMail::HtmlStatusBar::~HtmlStatusBar() {}

void KMail::HtmlStatusBar::upd() {
  QPalette pal = palette();
  pal.setColor( backgroundRole(), bgColor() );
  pal.setColor( foregroundRole(), fgColor() );
  setPalette( pal );
  setText( message() );
}

void KMail::HtmlStatusBar::setNormalMode() {
  setMode( Normal );
}

void KMail::HtmlStatusBar::setHtmlMode() {
  setMode( Html );
}

void KMail::HtmlStatusBar::setNeutralMode() {
  setMode( Neutral );
}

void KMail::HtmlStatusBar::setMode( Mode m ) {
  if ( m == mode() )
    return;
  mMode = m;
  upd();
}

QString KMail::HtmlStatusBar::message() const {
  switch ( mode() ) {
  case Html: // bold: "HTML Message"
    return i18n( "<qt>
H
T
M
L
 "
                 "
M
e
s
s
a
g
e</qt>" );
  case Normal: // normal: "No HTML Message"
    return i18n( "<qt>
N
o
 "
                 "
H
T
M
L
 "
                 "
M
e
s
s
a
g
e</qt>" );
  default:
  case Neutral:
    return QString();
  }
}

namespace {
  inline KConfig * config() {
#ifndef KMAIL_TESTING
    return KMKernel::config();
#else
    return kApp->config();
#endif
  }
}

QColor KMail::HtmlStatusBar::fgColor() const {
  KConfigGroup conf( config(), "Reader" );
  QColor def;
  switch ( mode() ) {
  case Html:
    def = Qt::white;
    return conf.readEntry( "ColorbarForegroundHTML", def );
  case Normal:
    def = Qt::black;
    return conf.readEntry( "ColorbarForegroundPlain", def );
  default:
  case Neutral:
    return Qt::black;
  }
}

QColor KMail::HtmlStatusBar::bgColor() const {
  KConfigGroup conf( config(), "Reader" );

  QColor def;
  switch ( mode() ) {
  case Html:
    def = Qt::black;
    return conf.readEntry( "ColorbarBackgroundHTML", def );
  case Normal:
    def = Qt::lightGray;
    return conf.readEntry( "ColorbarBackgroundPlain", def );
  default:
  case Neutral:
    return Qt::white;
  }
}

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


<commit_before>// Time:  O(m * n)
// Space: O(m * n)

class Solution {
public:
    int findBlackPixel(vector<vector<char>>& picture, int N) {
        vector<int> rows = vector<int>(picture.size());
        vector<int> cols = vector<int>(picture[0].size());

        unordered_map<string,int> lookup;
        vector<string> srows;
        for (int i = 0; i < picture.size(); ++i) {
            string s;
            for (int j = 0; j < picture[0].size(); ++j) {
                if (picture[i][j] == 'B') {
                    ++rows[i];
                    ++cols[j];
                }
                s.push_back(picture[i][j]);
            }
            ++lookup[s];
            srows.emplace_back(move(s));
        }

        int result = 0;
        for (int i = 0; i < picture.size(); ++i) {
            if (rows[i] == N && lookup[srows[i]] == N) {
                for (int j = 0; j < picture[0].size(); ++j) {
                     result += picture[i][j] == 'B' && cols[j] == N;
                }
            }
        }
        return result;
    }
};
<commit_msg>Update lonely-pixel-ii.cpp<commit_after>// Time:  O(m * n)
// Space: O(m + n)

class Solution {
public:
    int findBlackPixel(vector<vector<char>>& picture, int N) {
        vector<int> rows = vector<int>(picture.size());
        vector<int> cols = vector<int>(picture[0].size());

        unordered_map<string,int> lookup;
        vector<string> srows;
        for (int i = 0; i < picture.size(); ++i) {
            string s;
            for (int j = 0; j < picture[0].size(); ++j) {
                if (picture[i][j] == 'B') {
                    ++rows[i];
                    ++cols[j];
                }
                s.push_back(picture[i][j]);
            }
            ++lookup[s];
            srows.emplace_back(move(s));
        }

        int result = 0;
        for (int i = 0; i < picture.size(); ++i) {
            if (rows[i] == N && lookup[srows[i]] == N) {
                for (int j = 0; j < picture[0].size(); ++j) {
                     result += picture[i][j] == 'B' && cols[j] == N;
                }
            }
        }
        return result;
    }
};
<|endoftext|>