<commit_before>// This file is part of the KDE libraries
// Copyright (C) 2010 Dominik Haumann <dhaumann kde org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) version 3.
//
// 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public License
// along with this library; see the file COPYING.LIB.  If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301, USA.

#include "katescript.h"
#include "katescriptdocument.h"
#include "katescriptview.h"
#include "kateview.h"
#include "katedocument.h"

#include <iostream>

#include <QScriptEngine>
#include <QScriptValue>
#include <QScriptContext>

#include <kdebug.h>
#include <klocale.h>
#include <klocalizedstring.h>
#include <kstandarddirs.h>

namespace Kate {
namespace Script {

bool readFile(const QString& sourceUrl, QString& sourceCode)
{
  sourceCode = QString();

  QFile file(sourceUrl);
  if (!file.open(QIODevice::ReadOnly)) {
    kDebug(13050) << i18n("Unable to find '%1'", sourceUrl);
    return false;
  } else {
    QTextStream stream(&file);
    stream.setCodec("UTF-8");
    sourceCode = stream.readAll();
    file.close();
  }
  return true;
}

QScriptValue require(QScriptContext *context, QScriptEngine *engine)
{
  /**
   * just search for all given scripts and eval them
   */
  for(int i = 0; i < context->argumentCount(); ++i) {
    /**
     * get full name of file
     */
    const QString name = context->argument(i).toString();

    printf ("want to load %s\n", qPrintable (name));

    const QString fullName = KGlobal::dirs()->findResource ("data", "katepart/script/libraries/" + name);

    printf ("want to load fullName %s\n", qPrintable (fullName));

    /**
     * check include guard
     */
    QScriptValue require_guard = engine->globalObject().property ("require_guard");
    if (require_guard.property (fullName).toBool ())
      continue;

    /**
     * try to read complete file
     * skip non-existing files
     */

    printf ("before read fullName %s\n", qPrintable (fullName));
    QString code;
    if (!readFile (fullName, code))
      continue;
    printf ("after read fullName %s\n", qPrintable (fullName));

    /**
     * eval in current script engine
     */
    engine->evaluate (code, fullName);
    if (engine->hasUncaughtException())
      printf ("after eval fullName %s had exception\n", qPrintable (fullName));

    printf ("after eval fullName %s\n", qPrintable (fullName));

    /**
     * set include guard
     */
    require_guard.setProperty (fullName, QScriptValue (true));
  }

  /**
   * no return value
   */
  return engine->nullValue();
}

QScriptValue debug(QScriptContext *context, QScriptEngine *engine)
{
  QStringList message;
  for(int i = 0; i < context->argumentCount(); ++i) {
    message << context->argument(i).toString();
  }
  // debug in blue to distance from other debug output if necessary
  std::cerr << "\033[34m" << qPrintable(message.join(" ")) << "\033[0m\n";
  return engine->nullValue();
}

//BEGIN code adapted from kdelibs/kross/modules/translation.cpp
/// helper function to do the substitution from QtScript > QVariant > real values
KLocalizedString substituteArguments( const KLocalizedString &kls, const QVariantList &arguments, int max = 99 )
{
  KLocalizedString ls = kls;
  int cnt = qMin( arguments.count(), max ); // QString supports max 99
  for ( int i = 0; i < cnt; ++i ) {
    QVariant arg = arguments[i];
    switch ( arg.type() ) {
      case QVariant::Int: ls = ls.subs(arg.toInt()); break;
      case QVariant::UInt: ls = ls.subs(arg.toUInt()); break;
      case QVariant::LongLong: ls = ls.subs(arg.toLongLong()); break;
      case QVariant::ULongLong: ls = ls.subs(arg.toULongLong()); break;
      case QVariant::Double: ls = ls.subs(arg.toDouble()); break;
      default: ls = ls.subs(arg.toString()); break;
    }
  }
  return ls;
}

/// i18n("text", arguments [optional])
QScriptValue i18n( QScriptContext *context, QScriptEngine *engine )
{
  Q_UNUSED(engine)
  QString text;
  QVariantList args;
  const int argCount = context->argumentCount();

  if (argCount == 0) {
    kWarning(13050) << "wrong usage of i18n:" << context->backtrace().join("\n\t");
  }

  if (argCount > 0) {
    text = context->argument(0).toString();
  }

  for (int i = 1; i < argCount; ++i) {
    args << context->argument(i).toVariant();
  }

  KLocalizedString ls = ki18n(text.toUtf8());
  return substituteArguments( ls, args ).toString();
}

/// i18nc("context", "text", arguments [optional])
QScriptValue i18nc( QScriptContext *context, QScriptEngine *engine )
{
  Q_UNUSED(engine)
  QString text;
  QString textContext;
  QVariantList args;
  const int argCount = context->argumentCount();

  if (argCount < 2) {
    kWarning(13050) << "wrong usage of i18nc:" << context->backtrace().join("\n\t");
  }

  if (argCount > 0) {
    textContext = context->argument(0).toString();
  }

  if (argCount > 1) {
    text = context->argument(1).toString();
  }

  for (int i = 2; i < argCount; ++i) {
    args << context->argument(i).toVariant();
  }

  KLocalizedString ls = ki18nc(textContext.toUtf8(), text.toUtf8());
  return substituteArguments( ls, args ).toString();
}

/// i18np("singular", "plural", number, arguments [optional])
QScriptValue i18np( QScriptContext *context, QScriptEngine *engine )
{
  Q_UNUSED(engine)
  QString trSingular;
  QString trPlural;
  int number = 0;
  QVariantList args;
  const int argCount = context->argumentCount();

  if (argCount < 3) {
    kWarning(13050) << "wrong usage of i18np:" << context->backtrace().join("\n\t");
  }

  if (argCount > 0) {
    trSingular = context->argument(0).toString();
  }

  if (argCount > 1) {
    trPlural = context->argument(1).toString();
  }

  if (argCount > 2) {
    number = context->argument(2).toInt32();
  }

  for (int i = 3; i < argCount; ++i) {
    args << context->argument(i).toVariant();
  }

  KLocalizedString ls = ki18np(trSingular.toUtf8(), trPlural.toUtf8()).subs(number);
  return substituteArguments( ls, args, 98 ).toString();
}

/// i18ncp("context", "singular", "plural", number, arguments [optional])
QScriptValue i18ncp( QScriptContext *context, QScriptEngine *engine )
{
  Q_UNUSED(engine)
  QString trContext;
  QString trSingular;
  QString trPlural;
  int number = 0;
  QVariantList args;
  const int argCount = context->argumentCount();

  if (argCount < 4) {
    kWarning(13050) << "wrong usage of i18ncp:" << context->backtrace().join("\n\t");
  }

  if (argCount > 0) {
    trContext = context->argument(0).toString();
  }

  if (argCount > 1) {
    trSingular = context->argument(1).toString();
  }

  if (argCount > 2) {
    trPlural = context->argument(2).toString();
  }

  if (argCount > 3) {
    number = context->argument(3).toInt32();
  }

  for (int i = 4; i < argCount; ++i) {
    args << context->argument(i).toVariant();
  }

  KLocalizedString ls = ki18ncp(trContext.toUtf8(), trSingular.toUtf8(), trPlural.toUtf8()).subs( number );
  return substituteArguments( ls, args, 98 ).toString();
}
//END code adapted from kdelibs/kross/modules/translation.cpp

}
}

// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>require requires some hackery :(<commit_after>// This file is part of the KDE libraries
// Copyright (C) 2010 Dominik Haumann <dhaumann kde org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) version 3.
//
// 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
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public License
// along with this library; see the file COPYING.LIB.  If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301, USA.

#include "katescript.h"
#include "katescriptdocument.h"
#include "katescriptview.h"
#include "kateview.h"
#include "katedocument.h"

#include <iostream>

#include <QScriptEngine>
#include <QScriptValue>
#include <QScriptContext>

#include <kdebug.h>
#include <klocale.h>
#include <klocalizedstring.h>
#include <kstandarddirs.h>

namespace Kate {
namespace Script {

bool readFile(const QString& sourceUrl, QString& sourceCode)
{
  sourceCode = QString();

  QFile file(sourceUrl);
  if (!file.open(QIODevice::ReadOnly)) {
    kDebug(13050) << i18n("Unable to find '%1'", sourceUrl);
    return false;
  } else {
    QTextStream stream(&file);
    stream.setCodec("UTF-8");
    sourceCode = stream.readAll();
    file.close();
  }
  return true;
}

QScriptValue require(QScriptContext *context, QScriptEngine *engine)
{
  /**
   * just search for all given scripts and eval them
   */
  for(int i = 0; i < context->argumentCount(); ++i) {
    /**
     * get full name of file
     * skip on errors
     */
    const QString name = context->argument(i).toString();
    const QString fullName = KGlobal::dirs()->findResource ("data", "katepart/script/libraries/" + name);
    if (fullName.isEmpty())
      continue;

    /**
     * check include guard
     */
    QScriptValue require_guard = engine->globalObject().property ("require_guard");
    if (require_guard.property (fullName).toBool ())
      continue;

    /**
     * try to read complete file
     * skip non-existing files
     */
    QString code;
    if (!readFile (fullName, code))
      continue;

    /**
     * fixup QScriptContext
     * else the nested evaluate will not work :/
     * see http://www.qtcentre.org/threads/31027-QtScript-nesting-with-include-imports-or-spawned-script-engines
     * http://www.qtcentre.org/threads/20432-Can-I-include-a-script-from-script
     */
    QScriptContext *context = engine->currentContext();
    QScriptContext *parent = context->parentContext();
    if (parent) {
        context->setActivationObject(context->parentContext()->activationObject());
        context->setThisObject(context->parentContext()->thisObject());
    }

    /**
     * eval in current script engine
     */
    engine->evaluate (code, fullName);

    /**
     * set include guard
     */
    require_guard.setProperty (fullName, QScriptValue (true));
  }

  /**
   * no return value
   */
  return engine->nullValue();
}

QScriptValue debug(QScriptContext *context, QScriptEngine *engine)
{
  QStringList message;
  for(int i = 0; i < context->argumentCount(); ++i) {
    message << context->argument(i).toString();
  }
  // debug in blue to distance from other debug output if necessary
  std::cerr << "\033[34m" << qPrintable(message.join(" ")) << "\033[0m\n";
  return engine->nullValue();
}

//BEGIN code adapted from kdelibs/kross/modules/translation.cpp
/// helper function to do the substitution from QtScript > QVariant > real values
KLocalizedString substituteArguments( const KLocalizedString &kls, const QVariantList &arguments, int max = 99 )
{
  KLocalizedString ls = kls;
  int cnt = qMin( arguments.count(), max ); // QString supports max 99
  for ( int i = 0; i < cnt; ++i ) {
    QVariant arg = arguments[i];
    switch ( arg.type() ) {
      case QVariant::Int: ls = ls.subs(arg.toInt()); break;
      case QVariant::UInt: ls = ls.subs(arg.toUInt()); break;
      case QVariant::LongLong: ls = ls.subs(arg.toLongLong()); break;
      case QVariant::ULongLong: ls = ls.subs(arg.toULongLong()); break;
      case QVariant::Double: ls = ls.subs(arg.toDouble()); break;
      default: ls = ls.subs(arg.toString()); break;
    }
  }
  return ls;
}

/// i18n("text", arguments [optional])
QScriptValue i18n( QScriptContext *context, QScriptEngine *engine )
{
  Q_UNUSED(engine)
  QString text;
  QVariantList args;
  const int argCount = context->argumentCount();

  if (argCount == 0) {
    kWarning(13050) << "wrong usage of i18n:" << context->backtrace().join("\n\t");
  }

  if (argCount > 0) {
    text = context->argument(0).toString();
  }

  for (int i = 1; i < argCount; ++i) {
    args << context->argument(i).toVariant();
  }

  KLocalizedString ls = ki18n(text.toUtf8());
  return substituteArguments( ls, args ).toString();
}

/// i18nc("context", "text", arguments [optional])
QScriptValue i18nc( QScriptContext *context, QScriptEngine *engine )
{
  Q_UNUSED(engine)
  QString text;
  QString textContext;
  QVariantList args;
  const int argCount = context->argumentCount();

  if (argCount < 2) {
    kWarning(13050) << "wrong usage of i18nc:" << context->backtrace().join("\n\t");
  }

  if (argCount > 0) {
    textContext = context->argument(0).toString();
  }

  if (argCount > 1) {
    text = context->argument(1).toString();
  }

  for (int i = 2; i < argCount; ++i) {
    args << context->argument(i).toVariant();
  }

  KLocalizedString ls = ki18nc(textContext.toUtf8(), text.toUtf8());
  return substituteArguments( ls, args ).toString();
}

/// i18np("singular", "plural", number, arguments [optional])
QScriptValue i18np( QScriptContext *context, QScriptEngine *engine )
{
  Q_UNUSED(engine)
  QString trSingular;
  QString trPlural;
  int number = 0;
  QVariantList args;
  const int argCount = context->argumentCount();

  if (argCount < 3) {
    kWarning(13050) << "wrong usage of i18np:" << context->backtrace().join("\n\t");
  }

  if (argCount > 0) {
    trSingular = context->argument(0).toString();
  }

  if (argCount > 1) {
    trPlural = context->argument(1).toString();
  }

  if (argCount > 2) {
    number = context->argument(2).toInt32();
  }

  for (int i = 3; i < argCount; ++i) {
    args << context->argument(i).toVariant();
  }

  KLocalizedString ls = ki18np(trSingular.toUtf8(), trPlural.toUtf8()).subs(number);
  return substituteArguments( ls, args, 98 ).toString();
}

/// i18ncp("context", "singular", "plural", number, arguments [optional])
QScriptValue i18ncp( QScriptContext *context, QScriptEngine *engine )
{
  Q_UNUSED(engine)
  QString trContext;
  QString trSingular;
  QString trPlural;
  int number = 0;
  QVariantList args;
  const int argCount = context->argumentCount();

  if (argCount < 4) {
    kWarning(13050) << "wrong usage of i18ncp:" << context->backtrace().join("\n\t");
  }

  if (argCount > 0) {
    trContext = context->argument(0).toString();
  }

  if (argCount > 1) {
    trSingular = context->argument(1).toString();
  }

  if (argCount > 2) {
    trPlural = context->argument(2).toString();
  }

  if (argCount > 3) {
    number = context->argument(3).toInt32();
  }

  for (int i = 4; i < argCount; ++i) {
    args << context->argument(i).toVariant();
  }

  KLocalizedString ls = ki18ncp(trContext.toUtf8(), trSingular.toUtf8(), trPlural.toUtf8()).subs( number );
  return substituteArguments( ls, args, 98 ).toString();
}
//END code adapted from kdelibs/kross/modules/translation.cpp

}
}

// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|>


<commit_before>#include "response.h"
#include "client.h"
#include "settings.h"

#include "timing/timingfactory.h"
#include "channel.h"
#include "log/logger.h"
#include "types.h"

LOGGER(Response);

Response::Response(QObject *parent)
: QObject(parent)
{
}

Response::~Response()
{
}

void Response::finished()
{
}

LoginResponse::LoginResponse(QObject *parent)
: Response(parent)
, m_registeredDevice(false)
{
}

bool LoginResponse::fillFromVariant(const QVariantMap &variant)
{
    m_apiKey = variant.value("api_key").toString();
    m_registeredDevice = variant.value("registered_device").toBool();

    return !m_apiKey.isEmpty();
}

void LoginResponse::finished()
{
    Client *client = Client::instance();

    // Update the settings
    Settings *settings = client->settings();
    settings->setApiKey(m_apiKey);

    // Set registered status (after settings!)
    client->setStatus(Client::Registered);
}

QString LoginResponse::apiKey() const
{
    return m_apiKey;
}

bool LoginResponse::registeredDevice() const
{
    return m_registeredDevice;
}

RegisterDeviceResponse::RegisterDeviceResponse(QObject *parent)
: Response(parent)
{
}

bool RegisterDeviceResponse::fillFromVariant(const QVariantMap &variant)
{
    Q_UNUSED(variant);
    return true;
}

GetConfigResponse::GetConfigResponse(QObject *parent)
: Response(parent)
{
}

bool GetConfigResponse::fillFromVariant(const QVariantMap &variant)
{
    m_supervisorChannel = Channel::fromVariant(variant.value("supervisor_channel"));
    m_keepaliveChannel = Channel::fromVariant(variant.value("keepalive_channel"));
    m_configChannel = Channel::fromVariant(variant.value("config_channel"));
    m_reportChannel = Channel::fromVariant(variant.value("report_channel"));

    return true;
}

QVariant GetConfigResponse::toVariant() const
{
    QVariantMap map;
    map.insert("supervisor_channel", m_supervisorChannel.toVariant());
    map.insert("keepalive_channel", m_keepaliveChannel.toVariant());
    map.insert("config_channel", m_configChannel.toVariant());
    map.insert("report_channel", m_reportChannel.toVariant());
    return map;
}

void GetConfigResponse::finished()
{
    // Sync the settings
    Client *client = Client::instance();
    Settings *settings = client->settings();
    settings->sync();

    emit responseChanged();
}

QString GetConfigResponse::supervisorAddress() const
{
    return m_supervisorChannel.target();
}

TimingPtr GetConfigResponse::supervisorTiming() const
{
    return m_supervisorChannel.timing();
}

QString GetConfigResponse::keepaliveAddress() const
{
    return m_keepaliveChannel.target();
}

TimingPtr GetConfigResponse::keepaliveTiming() const
{
    return m_keepaliveChannel.timing();
}

void GetConfigResponse::setConfigAddress(const QString &address)
{
    m_configChannel.setTarget(address);
}

QString GetConfigResponse::configAddress() const
{
    return m_configChannel.target();
}

TimingPtr GetConfigResponse::configTiming() const
{
    return m_configChannel.timing();
}

QString GetConfigResponse::reportAddress() const
{
    return m_reportChannel.target();
}

TimingPtr GetConfigResponse::reportTiming() const
{
    return m_reportChannel.timing();
}

QList<int> GetInstructionResponse::taskIds() const
{
    return m_taskIds;
}

QList<int> GetInstructionResponse::scheduleIds() const
{
    return m_scheduleIds;
}

bool GetInstructionResponse::fillFromVariant(const QVariantMap &variant)
{
    m_taskIds.clear();

    foreach (const QVariant &entry, variant.value("tasks").toList())
    {
        m_taskIds.append(entry.toInt());
    }

    m_scheduleIds.clear();

    foreach (const QVariant &entry, variant.value("tasks").toList())
    {
      m_scheduleIds.append(entry.toInt());
    }

    LOG_DEBUG(QString("Received %1 tasks").arg(m_taskIds.size()));
    LOG_DEBUG(QString("Received %1 schedules").arg(m_scheduleIds.size()));

    return true;
}

bool GetScheduleResponse::fillFromVariant(const QVariantMap &variant)
{
    QVariantMap variantMap = variant.value("object").toMap();

    // validate task
    TestDefinition test = TestDefinition::fromVariant(variantMap.value("task"));

    // get timing and merge into task FIXME this is an evil hack
    TimingPtr timing = TimingFactory::timingFromVariant(variantMap.value("timing"));
    test.setTiming(timing);

    if (m_validator.validate(test) == TaskValidator::Valid)
    {
        m_tasks.append(test);
    }
    else
    {
        // TODO: Get more information
        LOG_DEBUG(QString("Received invalid task, ignoring."));
    }

    return true;
}

TestDefinitionList GetScheduleResponse::tasks() const
{
    return m_tasks;
}
<commit_msg>Response function for schedules<commit_after>#include "response.h"
#include "client.h"
#include "settings.h"

#include "timing/timingfactory.h"
#include "channel.h"
#include "log/logger.h"
#include "types.h"

LOGGER(Response);

Response::Response(QObject *parent)
: QObject(parent)
{
}

Response::~Response()
{
}

void Response::finished()
{
}

LoginResponse::LoginResponse(QObject *parent)
: Response(parent)
, m_registeredDevice(false)
{
}

bool LoginResponse::fillFromVariant(const QVariantMap &variant)
{
    m_apiKey = variant.value("api_key").toString();
    m_registeredDevice = variant.value("registered_device").toBool();

    return !m_apiKey.isEmpty();
}

void LoginResponse::finished()
{
    Client *client = Client::instance();

    // Update the settings
    Settings *settings = client->settings();
    settings->setApiKey(m_apiKey);

    // Set registered status (after settings!)
    client->setStatus(Client::Registered);
}

QString LoginResponse::apiKey() const
{
    return m_apiKey;
}

bool LoginResponse::registeredDevice() const
{
    return m_registeredDevice;
}

RegisterDeviceResponse::RegisterDeviceResponse(QObject *parent)
: Response(parent)
{
}

bool RegisterDeviceResponse::fillFromVariant(const QVariantMap &variant)
{
    Q_UNUSED(variant);
    return true;
}

GetConfigResponse::GetConfigResponse(QObject *parent)
: Response(parent)
{
}

bool GetConfigResponse::fillFromVariant(const QVariantMap &variant)
{
    m_supervisorChannel = Channel::fromVariant(variant.value("supervisor_channel"));
    m_keepaliveChannel = Channel::fromVariant(variant.value("keepalive_channel"));
    m_configChannel = Channel::fromVariant(variant.value("config_channel"));
    m_reportChannel = Channel::fromVariant(variant.value("report_channel"));

    return true;
}

QVariant GetConfigResponse::toVariant() const
{
    QVariantMap map;
    map.insert("supervisor_channel", m_supervisorChannel.toVariant());
    map.insert("keepalive_channel", m_keepaliveChannel.toVariant());
    map.insert("config_channel", m_configChannel.toVariant());
    map.insert("report_channel", m_reportChannel.toVariant());
    return map;
}

void GetConfigResponse::finished()
{
    // Sync the settings
    Client *client = Client::instance();
    Settings *settings = client->settings();
    settings->sync();

    emit responseChanged();
}

QString GetConfigResponse::supervisorAddress() const
{
    return m_supervisorChannel.target();
}

TimingPtr GetConfigResponse::supervisorTiming() const
{
    return m_supervisorChannel.timing();
}

QString GetConfigResponse::keepaliveAddress() const
{
    return m_keepaliveChannel.target();
}

TimingPtr GetConfigResponse::keepaliveTiming() const
{
    return m_keepaliveChannel.timing();
}

void GetConfigResponse::setConfigAddress(const QString &address)
{
    m_configChannel.setTarget(address);
}

QString GetConfigResponse::configAddress() const
{
    return m_configChannel.target();
}

TimingPtr GetConfigResponse::configTiming() const
{
    return m_configChannel.timing();
}

QString GetConfigResponse::reportAddress() const
{
    return m_reportChannel.target();
}

TimingPtr GetConfigResponse::reportTiming() const
{
    return m_reportChannel.timing();
}

QList<int> GetInstructionResponse::taskIds() const
{
    return m_taskIds;
}

QList<int> GetInstructionResponse::scheduleIds() const
{
    return m_scheduleIds;
}

bool GetInstructionResponse::fillFromVariant(const QVariantMap &variant)
{
    m_taskIds.clear();

    foreach (const QVariant &entry, variant.value("tasks").toList())
    {
        m_taskIds.append(entry.toInt());
    }

    m_scheduleIds.clear();

    foreach (const QVariant &entry, variant.value("tasks").toList())
    {
      m_scheduleIds.append(entry.toInt());
    }

    LOG_DEBUG(QString("Received %1 tasks").arg(m_taskIds.size()));
    LOG_DEBUG(QString("Received %1 schedules").arg(m_scheduleIds.size()));

    return true;
}

bool GetScheduleResponse::fillFromVariant(const QVariantMap &variant)
{

    foreach (const QVariant &entry, variant.value("objects").toList())
    {
        QVariantMap variantMap = entry.toMap();

        // generate task
        TestDefinition test = TestDefinition::fromVariant(variantMap.value("task"));

        // get timing and merge into task FIXME this is an evil hack
        TimingPtr timing = TimingFactory::timingFromVariant(variantMap.value("timing"));
        test.setTiming(timing);

        if (m_validator.validate(test) == TaskValidator::Valid)
        {
            m_tasks.append(test);
        }
        else
        {
            // TODO: Get more information
            LOG_DEBUG(QString("Received invalid task, ignoring."));
        }
    }

    return true;
}

TestDefinitionList GetScheduleResponse::tasks() const
{
    return m_tasks;
}
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

// Include this before af/opencl.h
// Causes conflict between system cl.hpp and opencl/cl.hpp
#if defined(WITH_GRAPHICS)
#include <graphics_common.hpp>
#endif

#if defined(OS_MAC)
#include <OpenGL/OpenGL.h>
#include <libkern/OSAtomic.h>
#else
#include <GL/gl.h>
#endif // !__APPLE__

#include <cl.hpp>

#include <af/version.h>
#include <af/opencl.h>
#include <defines.hpp>
#include <platform.hpp>
#include <functional>
#include <algorithm>
#include <cctype>
#include <vector>
#include <string>
#include <sstream>
#include <stdexcept>
#include <cstring>
#include <algorithm>
#include <map>
#include <errorcodes.hpp>
#include <err_opencl.hpp>

using std::string;
using std::vector;
using std::ostringstream;
using std::runtime_error;

using cl::Platform;
using cl::Context;
using cl::CommandQueue;
using cl::Device;

namespace opencl
{

#if defined (OS_MAC)
static const std::string CL_GL_SHARING_EXT = "cl_APPLE_gl_sharing";
#else
static const std::string CL_GL_SHARING_EXT = "cl_khr_gl_sharing";
#endif

static const char *get_system(void)
{
    return
#if defined(ARCH_32)
    "32-bit "
#elif defined(ARCH_64)
    "64-bit "
#endif

#if defined(OS_LNX)
    "Linux";
#elif defined(OS_WIN)
    "Windows";
#elif defined(OS_MAC)
    "Mac OSX";
#endif
}

DeviceManager& DeviceManager::getInstance()
{
    static DeviceManager my_instance;
    return my_instance;
}

DeviceManager::~DeviceManager()
{
    //TODO: FIXME:
    // OpenCL libs on Windows platforms
    // are crashing the application at program exit
    // most probably a reference counting issue based
    // on the investigation done so far. This problem
    // doesn't seem to happen on Linux or MacOSX.
    // So, clean up OpenCL resources on non-Windows platforms
#ifndef OS_WIN
    for (auto q: mQueues) delete q;
    for (auto d : mDevices) delete d;
    for (auto c : mContexts) delete c;
    for (auto p : mPlatforms) delete p;
#endif
}

void DeviceManager::setContext(int device)
{
    mActiveQId = device;
    mActiveCtxId = device;
}

DeviceManager::DeviceManager()
    : mActiveCtxId(0), mActiveQId(0)
{
    try {
        std::vector<cl::Platform>   platforms;
        Platform::get(&platforms);

        cl_device_type DEVC_TYPES[] = {
            CL_DEVICE_TYPE_GPU,
#ifndef OS_MAC
            CL_DEVICE_TYPE_ACCELERATOR,
            CL_DEVICE_TYPE_CPU
#endif
        };

        for (auto &platform : platforms)
            mPlatforms.push_back(new Platform(platform));

        unsigned nDevices = 0;
        for (auto devType : DEVC_TYPES) {
            for (auto &platform : platforms) {

                cl_context_properties cps[3] = {CL_CONTEXT_PLATFORM,
                    (cl_context_properties)(platform()),
                    0};

                std::vector<Device> devs;
                try {
                    platform.getDevices(devType, &devs);
                } catch(const cl::Error &err) {
                    if (err.err() != CL_DEVICE_NOT_FOUND) {
                        throw;
                    }
                }

                for (auto dev : devs) {
                    nDevices++;
                    Context *ctx = new Context(dev, cps);
                    CommandQueue *cq = new CommandQueue(*ctx, dev);
                    mDevices.push_back(new Device(dev));
                    mContexts.push_back(ctx);
                    mQueues.push_back(cq);
                    mCtxOffsets.push_back(nDevices);
                    mIsGLSharingOn.push_back(false);
                }
            }
        }

        const char* deviceENV = getenv("AF_OPENCL_DEFAULT_DEVICE");
        if(deviceENV) {
            std::stringstream s(deviceENV);
            int def_device = -1;
            s >> def_device;
            if(def_device < 0 || def_device >= (int)nDevices) {
                printf("WARNING: AF_OPENCL_DEFAULT_DEVICE is out of range\n");
                printf("Setting default device as 0\n");
            } else {
                setContext(def_device);
            }
        }
    } catch (const cl::Error &error) {
            CL_TO_AF_ERROR(error);
    }
    /* loop over devices and replace contexts with
     * OpenGL shared contexts whereever applicable */
#if defined(WITH_GRAPHICS)
    // Define AF_DISABLE_GRAPHICS with any value to disable initialization
    const char* noGraphicsENV = getenv("AF_DISABLE_GRAPHICS");
    if(!noGraphicsENV) { // If AF_DISABLE_GRAPHICS is not defined
        try {
            int devCount = mDevices.size();
            fg::Window* wHandle = graphics::ForgeManager::getInstance().getMainWindow();
            for(int i=0; i<devCount; ++i)
                markDeviceForInterop(i, wHandle);
        } catch (...) {
        }
    }
#endif
}

// http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring/217605#217605
// trim from start
static inline std::string &ltrim(std::string &s)
{
    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
                                    std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}

static std::string platformMap(std::string &platStr)
{
    static bool isFirst = true;

    typedef std::map<std::string, std::string> strmap_t;
    static strmap_t platMap;
    if (isFirst) {
        platMap["NVIDIA CUDA"] = "NVIDIA  ";
        platMap["Intel(R) OpenCL"] = "INTEL   ";
        platMap["AMD Accelerated Parallel Processing"] = "AMD     ";
        platMap["Intel Gen OCL Driver"] = "BEIGNET ";
        platMap["Apple"] = "APPLE   ";
        isFirst = false;
    }

    strmap_t::iterator idx = platMap.find(platStr);

    if (idx == platMap.end()) {
        return platStr;
    } else {
        return idx->second;
    }
}

std::string getInfo()
{
    ostringstream info;
    info << "ArrayFire v" << AF_VERSION
         << " (OpenCL, " << get_system() << ", build " << AF_REVISION << ")" << std::endl;

    unsigned nDevices = 0;
    for (auto context : DeviceManager::getInstance().mContexts) {
        vector<Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();

        for(auto &device:devices) {
            const Platform platform(device.getInfo<CL_DEVICE_PLATFORM>());
            string platStr = platform.getInfo<CL_PLATFORM_NAME>();
            bool show_braces = ((unsigned)getActiveDeviceId() == nDevices);
            string dstr = device.getInfo<CL_DEVICE_NAME>();

            string id = (show_braces ? string("[") : "-") + std::to_string(nDevices) +
                        (show_braces ? string("]") : "-");
            info << id << " " << platformMap(platStr) << ": " << ltrim(dstr) << " ";
#ifndef NDEBUG
            info << device.getInfo<CL_DEVICE_VERSION>();
            info << " Device driver " << device.getInfo<CL_DRIVER_VERSION>();
            info << " FP64 Support("
                 << (device.getInfo<CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE>()>0 ? "True" : "False")
                 << ")";
#endif
            info << std::endl;

            nDevices++;
        }
    }
    return info.str();
}

std::string getPlatformName(const cl::Device &device)
{
    const Platform platform(device.getInfo<CL_DEVICE_PLATFORM>());
    std::string platStr = platform.getInfo<CL_PLATFORM_NAME>();
    return platformMap(platStr);
}

int getDeviceCount()
{
    return DeviceManager::getInstance().mQueues.size();
}

int getActiveDeviceId()
{
    return DeviceManager::getInstance().mActiveQId;
}

const Context& getContext()
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return *(devMngr.mContexts[devMngr.mActiveCtxId]);
}

CommandQueue& getQueue()
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return *(devMngr.mQueues[devMngr.mActiveQId]);
}

const cl::Device& getDevice()
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return *(devMngr.mDevices[devMngr.mActiveQId]);
}

bool isGLSharingSupported()
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return devMngr.mIsGLSharingOn[devMngr.mActiveQId];
}

bool isDoubleSupported(int device)
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return (devMngr.mDevices[device]->getInfo<CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE>()>0);
}

void devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)
{
    unsigned nDevices = 0;
    unsigned currActiveDevId = (unsigned)getActiveDeviceId();
    bool devset = false;

    for (auto context : DeviceManager::getInstance().mContexts) {
        vector<Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();

        for (auto &device : devices) {
            const Platform platform(device.getInfo<CL_DEVICE_PLATFORM>());
            string platStr = platform.getInfo<CL_PLATFORM_NAME>();

            if (currActiveDevId == nDevices) {
                string dev_str;
                device.getInfo(CL_DEVICE_NAME, &dev_str);
                string com_str = device.getInfo<CL_DEVICE_VERSION>();
                com_str = com_str.substr(7, 3);

                // strip out whitespace from the device string:
                const std::string& whitespace = " \t";
                const auto strBegin = dev_str.find_first_not_of(whitespace);
                const auto strEnd = dev_str.find_last_not_of(whitespace);
                const auto strRange = strEnd - strBegin + 1;
                dev_str = dev_str.substr(strBegin, strRange);

                // copy to output
                snprintf(d_name, 64, "%s", dev_str.c_str());
                snprintf(d_platform, 10, "OpenCL");
                snprintf(d_toolkit, 64, "%s", platStr.c_str());
                snprintf(d_compute, 10, "%s", com_str.c_str());
                devset = true;
            }
            if(devset) break;
            nDevices++;
        }
        if(devset) break;
    }

    // Sanitize input
    for (int i = 0; i < 31; i++) {
        if (d_name[i] == ' ') {
            if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;
            else d_name[i] = '_';
        }
    }
}

int setDevice(int device)
{
    DeviceManager& devMngr = DeviceManager::getInstance();

    if (device >= (int)devMngr.mQueues.size() ||
            device>= (int)DeviceManager::MAX_DEVICES) {
        //throw runtime_error("@setDevice: invalid device index");
        return -1;
    }
    else {
        int old = devMngr.mActiveQId;
        devMngr.setContext(device);
        return old;
    }
}

void sync(int device)
{
    try {
        int currDevice = getActiveDeviceId();
        setDevice(device);
        getQueue().finish();
        setDevice(currDevice);
    } catch (const cl::Error &ex) {
        CL_TO_AF_ERROR(ex);
    }
}

bool checkExtnAvailability(const Device &pDevice, std::string pName)
{
    bool ret_val = false;
    // find the extension required
    std::string exts = pDevice.getInfo<CL_DEVICE_EXTENSIONS>();
    std::stringstream ss(exts);
    std::string item;
    while (std::getline(ss,item,' ')) {
        if (item==pName) {
            ret_val = true;
            break;
        }
    }
    return ret_val;
}

#if defined(WITH_GRAPHICS)
void DeviceManager::markDeviceForInterop(const int device, const fg::Window* wHandle)
{
    try {
        if (device >= (int)mQueues.size() ||
                device>= (int)DeviceManager::MAX_DEVICES) {
            throw cl::Error(CL_INVALID_DEVICE, "Invalid device passed for CL-GL Interop");
        }
        else {
            mQueues[device]->finish();

            // check if the device has CL_GL sharing extension enabled
            bool temp = checkExtnAvailability(*mDevices[device], CL_GL_SHARING_EXT);
            if (!temp) {
                printf("Device[%d] has no support for OpenGL Interoperation\n",device);
                /* return silently if given device has not OpenGL sharing extension
                 * enabled so that regular queue is used for it */
                return;
            }

            // call forge to get OpenGL sharing context and details
            cl::Platform plat(mDevices[device]->getInfo<CL_DEVICE_PLATFORM>());
#ifdef OS_MAC
            CGLContextObj cgl_current_ctx = CGLGetCurrentContext();
            CGLShareGroupObj cgl_share_group = CGLGetShareGroup(cgl_current_ctx);

            cl_context_properties cps[] = {
                CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)cgl_share_group,
                0
            };
#else
            cl_context_properties cps[] = {
                CL_GL_CONTEXT_KHR, (cl_context_properties)wHandle->context(),
#if defined(_WIN32) || defined(_MSC_VER)
                CL_WGL_HDC_KHR, (cl_context_properties)wHandle->display(),
#else
                CL_GLX_DISPLAY_KHR, (cl_context_properties)wHandle->display(),
#endif
                CL_CONTEXT_PLATFORM, (cl_context_properties)plat(),
                0
            };
#endif
            Context * ctx = new Context(*mDevices[device], cps);
            CommandQueue * cq = new CommandQueue(*ctx, *mDevices[device]);

            delete mContexts[device];
            delete mQueues[device];

            mContexts[device] = ctx;
            mQueues[device] = cq;
        }
        mIsGLSharingOn[device] = true;
    } catch (const cl::Error &ex) {
        /* If replacing the original context with GL shared context
         * failes, don't throw an error and instead fall back to
         * original context and use copy via host to support graphics
         * on that particular OpenCL device. So mark it as no GL sharing */
    }
}
#endif

}

using namespace opencl;

af_err afcl_get_context(cl_context *ctx, const bool retain)
{
    *ctx = getContext()();
    if (retain) clRetainContext(*ctx);
    return AF_SUCCESS;
}

af_err afcl_get_queue(cl_command_queue *queue, const bool retain)
{
    *queue = getQueue()();
    if (retain) clRetainCommandQueue(*queue);
    return AF_SUCCESS;
}

af_err afcl_get_device_id(cl_device_id *id)
{
    *id = getDevice()();
    return AF_SUCCESS;
}
<commit_msg>Moved GL headers in platform.cpp inside WITH_GRAPHICS block<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

// Include this before af/opencl.h
// Causes conflict between system cl.hpp and opencl/cl.hpp
#if defined(WITH_GRAPHICS)

#include <graphics_common.hpp>

#if defined(OS_MAC)
#include <OpenGL/OpenGL.h>
#include <libkern/OSAtomic.h>
#else
#include <GL/gl.h>
#endif // !__APPLE__

#endif

#include <cl.hpp>

#include <af/version.h>
#include <af/opencl.h>
#include <defines.hpp>
#include <platform.hpp>
#include <functional>
#include <algorithm>
#include <cctype>
#include <vector>
#include <string>
#include <sstream>
#include <stdexcept>
#include <cstring>
#include <algorithm>
#include <map>
#include <errorcodes.hpp>
#include <err_opencl.hpp>

using std::string;
using std::vector;
using std::ostringstream;
using std::runtime_error;

using cl::Platform;
using cl::Context;
using cl::CommandQueue;
using cl::Device;

namespace opencl
{

#if defined (OS_MAC)
static const std::string CL_GL_SHARING_EXT = "cl_APPLE_gl_sharing";
#else
static const std::string CL_GL_SHARING_EXT = "cl_khr_gl_sharing";
#endif

static const char *get_system(void)
{
    return
#if defined(ARCH_32)
    "32-bit "
#elif defined(ARCH_64)
    "64-bit "
#endif

#if defined(OS_LNX)
    "Linux";
#elif defined(OS_WIN)
    "Windows";
#elif defined(OS_MAC)
    "Mac OSX";
#endif
}

DeviceManager& DeviceManager::getInstance()
{
    static DeviceManager my_instance;
    return my_instance;
}

DeviceManager::~DeviceManager()
{
    //TODO: FIXME:
    // OpenCL libs on Windows platforms
    // are crashing the application at program exit
    // most probably a reference counting issue based
    // on the investigation done so far. This problem
    // doesn't seem to happen on Linux or MacOSX.
    // So, clean up OpenCL resources on non-Windows platforms
#ifndef OS_WIN
    for (auto q: mQueues) delete q;
    for (auto d : mDevices) delete d;
    for (auto c : mContexts) delete c;
    for (auto p : mPlatforms) delete p;
#endif
}

void DeviceManager::setContext(int device)
{
    mActiveQId = device;
    mActiveCtxId = device;
}

DeviceManager::DeviceManager()
    : mActiveCtxId(0), mActiveQId(0)
{
    try {
        std::vector<cl::Platform>   platforms;
        Platform::get(&platforms);

        cl_device_type DEVC_TYPES[] = {
            CL_DEVICE_TYPE_GPU,
#ifndef OS_MAC
            CL_DEVICE_TYPE_ACCELERATOR,
            CL_DEVICE_TYPE_CPU
#endif
        };

        for (auto &platform : platforms)
            mPlatforms.push_back(new Platform(platform));

        unsigned nDevices = 0;
        for (auto devType : DEVC_TYPES) {
            for (auto &platform : platforms) {

                cl_context_properties cps[3] = {CL_CONTEXT_PLATFORM,
                    (cl_context_properties)(platform()),
                    0};

                std::vector<Device> devs;
                try {
                    platform.getDevices(devType, &devs);
                } catch(const cl::Error &err) {
                    if (err.err() != CL_DEVICE_NOT_FOUND) {
                        throw;
                    }
                }

                for (auto dev : devs) {
                    nDevices++;
                    Context *ctx = new Context(dev, cps);
                    CommandQueue *cq = new CommandQueue(*ctx, dev);
                    mDevices.push_back(new Device(dev));
                    mContexts.push_back(ctx);
                    mQueues.push_back(cq);
                    mCtxOffsets.push_back(nDevices);
                    mIsGLSharingOn.push_back(false);
                }
            }
        }

        const char* deviceENV = getenv("AF_OPENCL_DEFAULT_DEVICE");
        if(deviceENV) {
            std::stringstream s(deviceENV);
            int def_device = -1;
            s >> def_device;
            if(def_device < 0 || def_device >= (int)nDevices) {
                printf("WARNING: AF_OPENCL_DEFAULT_DEVICE is out of range\n");
                printf("Setting default device as 0\n");
            } else {
                setContext(def_device);
            }
        }
    } catch (const cl::Error &error) {
            CL_TO_AF_ERROR(error);
    }
    /* loop over devices and replace contexts with
     * OpenGL shared contexts whereever applicable */
#if defined(WITH_GRAPHICS)
    // Define AF_DISABLE_GRAPHICS with any value to disable initialization
    const char* noGraphicsENV = getenv("AF_DISABLE_GRAPHICS");
    if(!noGraphicsENV) { // If AF_DISABLE_GRAPHICS is not defined
        try {
            int devCount = mDevices.size();
            fg::Window* wHandle = graphics::ForgeManager::getInstance().getMainWindow();
            for(int i=0; i<devCount; ++i)
                markDeviceForInterop(i, wHandle);
        } catch (...) {
        }
    }
#endif
}

// http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring/217605#217605
// trim from start
static inline std::string &ltrim(std::string &s)
{
    s.erase(s.begin(), std::find_if(s.begin(), s.end(),
                                    std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}

static std::string platformMap(std::string &platStr)
{
    static bool isFirst = true;

    typedef std::map<std::string, std::string> strmap_t;
    static strmap_t platMap;
    if (isFirst) {
        platMap["NVIDIA CUDA"] = "NVIDIA  ";
        platMap["Intel(R) OpenCL"] = "INTEL   ";
        platMap["AMD Accelerated Parallel Processing"] = "AMD     ";
        platMap["Intel Gen OCL Driver"] = "BEIGNET ";
        platMap["Apple"] = "APPLE   ";
        isFirst = false;
    }

    strmap_t::iterator idx = platMap.find(platStr);

    if (idx == platMap.end()) {
        return platStr;
    } else {
        return idx->second;
    }
}

std::string getInfo()
{
    ostringstream info;
    info << "ArrayFire v" << AF_VERSION
         << " (OpenCL, " << get_system() << ", build " << AF_REVISION << ")" << std::endl;

    unsigned nDevices = 0;
    for (auto context : DeviceManager::getInstance().mContexts) {
        vector<Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();

        for(auto &device:devices) {
            const Platform platform(device.getInfo<CL_DEVICE_PLATFORM>());
            string platStr = platform.getInfo<CL_PLATFORM_NAME>();
            bool show_braces = ((unsigned)getActiveDeviceId() == nDevices);
            string dstr = device.getInfo<CL_DEVICE_NAME>();

            string id = (show_braces ? string("[") : "-") + std::to_string(nDevices) +
                        (show_braces ? string("]") : "-");
            info << id << " " << platformMap(platStr) << ": " << ltrim(dstr) << " ";
#ifndef NDEBUG
            info << device.getInfo<CL_DEVICE_VERSION>();
            info << " Device driver " << device.getInfo<CL_DRIVER_VERSION>();
            info << " FP64 Support("
                 << (device.getInfo<CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE>()>0 ? "True" : "False")
                 << ")";
#endif
            info << std::endl;

            nDevices++;
        }
    }
    return info.str();
}

std::string getPlatformName(const cl::Device &device)
{
    const Platform platform(device.getInfo<CL_DEVICE_PLATFORM>());
    std::string platStr = platform.getInfo<CL_PLATFORM_NAME>();
    return platformMap(platStr);
}

int getDeviceCount()
{
    return DeviceManager::getInstance().mQueues.size();
}

int getActiveDeviceId()
{
    return DeviceManager::getInstance().mActiveQId;
}

const Context& getContext()
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return *(devMngr.mContexts[devMngr.mActiveCtxId]);
}

CommandQueue& getQueue()
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return *(devMngr.mQueues[devMngr.mActiveQId]);
}

const cl::Device& getDevice()
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return *(devMngr.mDevices[devMngr.mActiveQId]);
}

bool isGLSharingSupported()
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return devMngr.mIsGLSharingOn[devMngr.mActiveQId];
}

bool isDoubleSupported(int device)
{
    DeviceManager& devMngr = DeviceManager::getInstance();
    return (devMngr.mDevices[device]->getInfo<CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE>()>0);
}

void devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)
{
    unsigned nDevices = 0;
    unsigned currActiveDevId = (unsigned)getActiveDeviceId();
    bool devset = false;

    for (auto context : DeviceManager::getInstance().mContexts) {
        vector<Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();

        for (auto &device : devices) {
            const Platform platform(device.getInfo<CL_DEVICE_PLATFORM>());
            string platStr = platform.getInfo<CL_PLATFORM_NAME>();

            if (currActiveDevId == nDevices) {
                string dev_str;
                device.getInfo(CL_DEVICE_NAME, &dev_str);
                string com_str = device.getInfo<CL_DEVICE_VERSION>();
                com_str = com_str.substr(7, 3);

                // strip out whitespace from the device string:
                const std::string& whitespace = " \t";
                const auto strBegin = dev_str.find_first_not_of(whitespace);
                const auto strEnd = dev_str.find_last_not_of(whitespace);
                const auto strRange = strEnd - strBegin + 1;
                dev_str = dev_str.substr(strBegin, strRange);

                // copy to output
                snprintf(d_name, 64, "%s", dev_str.c_str());
                snprintf(d_platform, 10, "OpenCL");
                snprintf(d_toolkit, 64, "%s", platStr.c_str());
                snprintf(d_compute, 10, "%s", com_str.c_str());
                devset = true;
            }
            if(devset) break;
            nDevices++;
        }
        if(devset) break;
    }

    // Sanitize input
    for (int i = 0; i < 31; i++) {
        if (d_name[i] == ' ') {
            if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;
            else d_name[i] = '_';
        }
    }
}

int setDevice(int device)
{
    DeviceManager& devMngr = DeviceManager::getInstance();

    if (device >= (int)devMngr.mQueues.size() ||
            device>= (int)DeviceManager::MAX_DEVICES) {
        //throw runtime_error("@setDevice: invalid device index");
        return -1;
    }
    else {
        int old = devMngr.mActiveQId;
        devMngr.setContext(device);
        return old;
    }
}

void sync(int device)
{
    try {
        int currDevice = getActiveDeviceId();
        setDevice(device);
        getQueue().finish();
        setDevice(currDevice);
    } catch (const cl::Error &ex) {
        CL_TO_AF_ERROR(ex);
    }
}

bool checkExtnAvailability(const Device &pDevice, std::string pName)
{
    bool ret_val = false;
    // find the extension required
    std::string exts = pDevice.getInfo<CL_DEVICE_EXTENSIONS>();
    std::stringstream ss(exts);
    std::string item;
    while (std::getline(ss,item,' ')) {
        if (item==pName) {
            ret_val = true;
            break;
        }
    }
    return ret_val;
}

#if defined(WITH_GRAPHICS)
void DeviceManager::markDeviceForInterop(const int device, const fg::Window* wHandle)
{
    try {
        if (device >= (int)mQueues.size() ||
                device>= (int)DeviceManager::MAX_DEVICES) {
            throw cl::Error(CL_INVALID_DEVICE, "Invalid device passed for CL-GL Interop");
        }
        else {
            mQueues[device]->finish();

            // check if the device has CL_GL sharing extension enabled
            bool temp = checkExtnAvailability(*mDevices[device], CL_GL_SHARING_EXT);
            if (!temp) {
                printf("Device[%d] has no support for OpenGL Interoperation\n",device);
                /* return silently if given device has not OpenGL sharing extension
                 * enabled so that regular queue is used for it */
                return;
            }

            // call forge to get OpenGL sharing context and details
            cl::Platform plat(mDevices[device]->getInfo<CL_DEVICE_PLATFORM>());
#ifdef OS_MAC
            CGLContextObj cgl_current_ctx = CGLGetCurrentContext();
            CGLShareGroupObj cgl_share_group = CGLGetShareGroup(cgl_current_ctx);

            cl_context_properties cps[] = {
                CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)cgl_share_group,
                0
            };
#else
            cl_context_properties cps[] = {
                CL_GL_CONTEXT_KHR, (cl_context_properties)wHandle->context(),
#if defined(_WIN32) || defined(_MSC_VER)
                CL_WGL_HDC_KHR, (cl_context_properties)wHandle->display(),
#else
                CL_GLX_DISPLAY_KHR, (cl_context_properties)wHandle->display(),
#endif
                CL_CONTEXT_PLATFORM, (cl_context_properties)plat(),
                0
            };
#endif
            Context * ctx = new Context(*mDevices[device], cps);
            CommandQueue * cq = new CommandQueue(*ctx, *mDevices[device]);

            delete mContexts[device];
            delete mQueues[device];

            mContexts[device] = ctx;
            mQueues[device] = cq;
        }
        mIsGLSharingOn[device] = true;
    } catch (const cl::Error &ex) {
        /* If replacing the original context with GL shared context
         * failes, don't throw an error and instead fall back to
         * original context and use copy via host to support graphics
         * on that particular OpenCL device. So mark it as no GL sharing */
    }
}
#endif

}

using namespace opencl;

af_err afcl_get_context(cl_context *ctx, const bool retain)
{
    *ctx = getContext()();
    if (retain) clRetainContext(*ctx);
    return AF_SUCCESS;
}

af_err afcl_get_queue(cl_command_queue *queue, const bool retain)
{
    *queue = getQueue()();
    if (retain) clRetainCommandQueue(*queue);
    return AF_SUCCESS;
}

af_err afcl_get_device_id(cl_device_id *id)
{
    *id = getDevice()();
    return AF_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * This is mcs; a modular configuration system.
 *
 * Copyright (c) 2007 Diego Pettenò <flameeyes@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <kconfig.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <assert.h>

extern "C" {

  #include "libmcs/mcs.h"

/* ***************************************************************** */

  extern mcs_backend_t mcs_backend;
}

typedef struct {
	KConfig *cfg;
} mcs_kconfig_handle_t;

namespace {

	mcs_handle_t *
	mcs_kconfig_new(char *domain)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *)calloc(sizeof(mcs_kconfig_handle_t), 1);
		mcs_handle_t *out = (mcs_handle_t *)calloc(sizeof(mcs_handle_t), 1);

		if (!KApplication::kApplication())
		{
	  		/* Initialise a fake KDE application if none present */
			static char *fake_argv[] = { "mcs_backend" };

			KCmdLineArgs::init(1, fake_argv, "mcs_backend", "MCS KConfig Backend",
				"Just a fake application to be able to use KConfig backend with non-KDE applications.",
				"9999", false);
			new KApplication(false, false);
		}

		out->base = &mcs_backend;
		out->mcs_priv_handle = h;

		h->cfg = new KConfig(domain);

		return out;
	}

	void
	mcs_kconfig_destroy(mcs_handle_t *self)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		delete h->cfg;
		free(h);

		free(self);
	}

	mcs_response_t
	mcs_kconfig_get_string(mcs_handle_t *self, const char *section,
			       const char *key, char **value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		QString entry = h->cfg->readEntry(key);
		*value = strdup(entry.latin1());

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_get_int(mcs_handle_t *self, const char *section,
		    const char *key, int *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		*value = h->cfg->readNumEntry(key);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_get_bool(mcs_handle_t *self, const char *section,
			     const char *key, int *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		*value = h->cfg->readBoolEntry(key);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_get_float(mcs_handle_t *self, const char *section,
			      const char *key, float *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		*value = (float)(h->cfg->readDoubleNumEntry(key));

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_get_double(mcs_handle_t *self, const char *section,
			       const char *key, double *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		*value = h->cfg->readDoubleNumEntry(key);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_string(mcs_handle_t *self, const char *section,
			       const char *key, const char *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		if ( ! value )
			h->cfg->writeEntry(key, QString::null);
		else
			h->cfg->writeEntry(key, value);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_int(mcs_handle_t *self, const char *section,
			    const char *key, int value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		h->cfg->writeEntry(key, value);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_bool(mcs_handle_t *self, const char *section,
			     const char *key, int value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		h->cfg->writeEntry(key, bool(value));

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_float(mcs_handle_t *self, const char *section,
			      const char *key, float value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		h->cfg->writeEntry(key, value);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_double(mcs_handle_t *self, const char *section,
			       const char *key, double value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		h->cfg->writeEntry(key, value);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_unset_key(mcs_handle_t *self, const char *section,
			      const char *key)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->deleteEntry(section, key);

		return MCS_OK;
	}

	mcs_list_t *
	mcs_kconfig_get_groups(mcs_handle_t *self)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;
		mcs_list_t *out = NULL;

		QStringList list = h->cfg->groupList();

		for (QStringList::const_iterator i = list.constBegin();
			i != list.constEnd(); i++)
		{
			QString str = *i;

			out = mcs_list_append(out, strdup(str.toLocal8Bit().constData()));
		}

		return out;
	}
};

mcs_backend_t mcs_backend = {
	NULL,
	"kconfig",
	mcs_kconfig_new,
	mcs_kconfig_destroy,

	mcs_kconfig_get_string,
	mcs_kconfig_get_int,
	mcs_kconfig_get_bool,
	mcs_kconfig_get_float,
	mcs_kconfig_get_double,

	mcs_kconfig_set_string,
	mcs_kconfig_set_int,
	mcs_kconfig_set_bool,
	mcs_kconfig_set_float,
	mcs_kconfig_set_double,

	mcs_kconfig_unset_key,

	NULL,
	mcs_kconfig_get_groups
};
<commit_msg>thanks for the tip Crazy_Hopper.<commit_after>/*
 * This is mcs; a modular configuration system.
 *
 * Copyright (c) 2007 Diego Pettenò <flameeyes@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <kconfig.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <assert.h>

extern "C" {

  #include "libmcs/mcs.h"

/* ***************************************************************** */

  extern mcs_backend_t mcs_backend;
}

typedef struct {
	KConfig *cfg;
} mcs_kconfig_handle_t;

namespace {

	mcs_handle_t *
	mcs_kconfig_new(char *domain)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *)calloc(sizeof(mcs_kconfig_handle_t), 1);
		mcs_handle_t *out = (mcs_handle_t *)calloc(sizeof(mcs_handle_t), 1);

		if (!KApplication::kApplication())
		{
	  		/* Initialise a fake KDE application if none present */
			static char *fake_argv[] = { "mcs_backend" };

			KCmdLineArgs::init(1, fake_argv, "mcs_backend", "MCS KConfig Backend",
				"Just a fake application to be able to use KConfig backend with non-KDE applications.",
				"9999", false);
			new KApplication(false, false);
		}

		out->base = &mcs_backend;
		out->mcs_priv_handle = h;

		h->cfg = new KConfig(domain);

		return out;
	}

	void
	mcs_kconfig_destroy(mcs_handle_t *self)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		delete h->cfg;
		free(h);

		free(self);
	}

	mcs_response_t
	mcs_kconfig_get_string(mcs_handle_t *self, const char *section,
			       const char *key, char **value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		QString entry = h->cfg->readEntry(key);
		*value = strdup(entry.latin1());

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_get_int(mcs_handle_t *self, const char *section,
		    const char *key, int *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		*value = h->cfg->readNumEntry(key);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_get_bool(mcs_handle_t *self, const char *section,
			     const char *key, int *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		*value = h->cfg->readBoolEntry(key);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_get_float(mcs_handle_t *self, const char *section,
			      const char *key, float *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		*value = (float)(h->cfg->readDoubleNumEntry(key));

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_get_double(mcs_handle_t *self, const char *section,
			       const char *key, double *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		if ( ! h->cfg->hasGroup(section) )
			return MCS_FAIL;

		h->cfg->setGroup(section);
		if ( ! h->cfg->hasKey(key) )
			return MCS_FAIL;

		*value = h->cfg->readDoubleNumEntry(key);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_string(mcs_handle_t *self, const char *section,
			       const char *key, const char *value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		if ( ! value )
			h->cfg->writeEntry(key, QString::null);
		else
			h->cfg->writeEntry(key, value);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_int(mcs_handle_t *self, const char *section,
			    const char *key, int value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		h->cfg->writeEntry(key, value);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_bool(mcs_handle_t *self, const char *section,
			     const char *key, int value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		h->cfg->writeEntry(key, bool(value));

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_float(mcs_handle_t *self, const char *section,
			      const char *key, float value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		h->cfg->writeEntry(key, value);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_set_double(mcs_handle_t *self, const char *section,
			       const char *key, double value)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->setGroup(section);
		h->cfg->writeEntry(key, value);

		return MCS_OK;
	}

	mcs_response_t
	mcs_kconfig_unset_key(mcs_handle_t *self, const char *section,
			      const char *key)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;

		h->cfg->deleteEntry(section, key);

		return MCS_OK;
	}

	mcs_list_t *
	mcs_kconfig_get_groups(mcs_handle_t *self)
	{
		mcs_kconfig_handle_t *h = (mcs_kconfig_handle_t *) self->mcs_priv_handle;
		mcs_list_t *out = NULL;

		QStringList list = h->cfg->groupList();

		for (QStringList::const_iterator i = list.constBegin();
			i != list.constEnd(); i++)
		{
			QString str = *i;

			out = mcs_list_append(out, strdup(str.local8Bit().constData()));
		}

		return out;
	}
};

mcs_backend_t mcs_backend = {
	NULL,
	"kconfig",
	mcs_kconfig_new,
	mcs_kconfig_destroy,

	mcs_kconfig_get_string,
	mcs_kconfig_get_int,
	mcs_kconfig_get_bool,
	mcs_kconfig_get_float,
	mcs_kconfig_get_double,

	mcs_kconfig_set_string,
	mcs_kconfig_set_int,
	mcs_kconfig_set_bool,
	mcs_kconfig_set_float,
	mcs_kconfig_set_double,

	mcs_kconfig_unset_key,

	NULL,
	mcs_kconfig_get_groups
};
<|endoftext|>


<commit_before>#include <stan/gm/arguments/argument_parser.hpp>
#include <stan/gm/arguments/arg_id.hpp>
#include <stan/gm/arguments/arg_data.hpp>
#include <stan/gm/arguments/arg_init.hpp>
#include <stan/gm/arguments/arg_random.hpp>
#include <stan/gm/arguments/arg_output.hpp>
#include <gtest/gtest.h>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/null.hpp>

using stan::gm::argument;
using stan::gm::arg_id;
using stan::gm::arg_data;
using stan::gm::arg_init;
using stan::gm::arg_random;
using stan::gm::arg_output;
using stan::gm::argument_parser;
using stan::gm::error_codes;

class StanGmArgumentsArgumentParser : public testing::Test {
public:
  void SetUp() {
    // copied setup from src/stan/gm/command.hpp
    // FIXME: move to factory?
    valid_arguments.push_back(new arg_id());
    valid_arguments.push_back(new arg_data());
    valid_arguments.push_back(new arg_init());
    valid_arguments.push_back(new arg_random());
    valid_arguments.push_back(new arg_output());

    parser = new argument_parser(valid_arguments);
  }
  void TearDown() {
    for (int i = 0; i < valid_arguments.size(); ++i)
      delete valid_arguments.at(i);
    delete(parser);
  }

  std::vector<argument*> valid_arguments;
  argument_parser* parser;
  int err_code;
  boost::iostreams::stream< boost::iostreams::null_sink > null_ostream;
};

TEST_F(StanGmArgumentsArgumentParser, default) {
  const char* argv[] = {};
  int argc = 0;

  err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);
  EXPECT_EQ(int(error_codes::USAGE), err_code);
}

TEST_F(StanGmArgumentsArgumentParser, help) {
  const char* argv[] = {"help"};
  int argc = 1;

  err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);
  EXPECT_EQ(int(error_codes::OK), err_code);
}

TEST_F(StanGmArgumentsArgumentParser, unrecognized_argument) {
  const char* argv[] = {"foo"};
  int argc = 1;

  err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);
  EXPECT_EQ(int(error_codes::USAGE), err_code);
}
<commit_msg>Fixed argument_parser_test to account for argv requiring that the first element be the executable name<commit_after>#include <stan/gm/arguments/argument_parser.hpp>
#include <stan/gm/arguments/arg_id.hpp>
#include <stan/gm/arguments/arg_data.hpp>
#include <stan/gm/arguments/arg_init.hpp>
#include <stan/gm/arguments/arg_random.hpp>
#include <stan/gm/arguments/arg_output.hpp>
#include <gtest/gtest.h>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/null.hpp>

using stan::gm::argument;
using stan::gm::arg_id;
using stan::gm::arg_data;
using stan::gm::arg_init;
using stan::gm::arg_random;
using stan::gm::arg_output;
using stan::gm::argument_parser;
using stan::gm::error_codes;

class StanGmArgumentsArgumentParser : public testing::Test {
public:
  void SetUp() {
    // copied setup from src/stan/gm/command.hpp
    // FIXME: move to factory?
    valid_arguments.push_back(new arg_id());
    valid_arguments.push_back(new arg_data());
    valid_arguments.push_back(new arg_init());
    valid_arguments.push_back(new arg_random());
    valid_arguments.push_back(new arg_output());

    parser = new argument_parser(valid_arguments);
  }
  void TearDown() {
    for (int i = 0; i < valid_arguments.size(); ++i)
      delete valid_arguments.at(i);
    delete(parser);
  }

  std::vector<argument*> valid_arguments;
  argument_parser* parser;
  int err_code;
  boost::iostreams::stream< boost::iostreams::null_sink > null_ostream;
};

TEST_F(StanGmArgumentsArgumentParser, default) {
  const char* argv[] = {};
  int argc = 0;

  err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);
  EXPECT_EQ(int(error_codes::USAGE), err_code);
}

TEST_F(StanGmArgumentsArgumentParser, help) {
  const char* argv[] = {"model_name", "help"};
  int argc = 2;

  err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);
  EXPECT_EQ(int(error_codes::OK), err_code);
}

TEST_F(StanGmArgumentsArgumentParser, unrecognized_argument) {
  const char* argv[] = {"foo"};
  int argc = 1;

  err_code = parser->parse_args(argc, argv, &null_ostream, &null_ostream);
  EXPECT_EQ(int(error_codes::USAGE), err_code);
}
<|endoftext|>


<commit_before>#include "counter.h"

namespace best_documenter {
    Counter::Counter(std::shared_ptr<github::Client> github) {
        github_ = github;
    }

    Counter::~Counter() {
    }

    std::shared_ptr<model::Result> Counter::compute() {
        auto result = std::make_shared<model::Result>();

        for (auto& repo : repos_) {
            auto commits = github->fetchReposCommits("pine613", "dotfiles", &err);
            if (!err.empty()) std::cout << err << std::endl;
        }

        return result;
    }

    GitHubCommitArrayPtr Counter::fetchReposCommits(
            const std::string& repo,
            std::string* err
            )
    {
        auto slashPos = repo.find('/');

        if (slashPos == std::string::npos) {
            *err = "Invalid repository name";
            return GitHubCommitArrayPtr();
        }

        auto owner   = repo.substr(0, repo.find('/'));
        auto name    = repo.substr(repo.find('/') + 1);
        auto commits = github_->fetchReposCommits(
                std::move(owner),
                std::move(name),
                err);

        return std::move(commits);
    }
}
<commit_msg>fix(counter): fix compile errors<commit_after>#include "counter.h"

namespace best_documenter {
    Counter::Counter(std::shared_ptr<github::Client> github) {
        github_ = github;
    }

    Counter::~Counter() {
    }

    std::shared_ptr<model::Result> Counter::compute() {
        auto result = std::make_shared<model::Result>();
        std::string err;

        for (auto& repo : repos_) {
            auto commits = github_->fetchReposCommits("pine613", "dotfiles", &err);
            if (!err.empty()) {
                std::cout << err << std::endl;
                return result;
            }
        }

        return std::move(result);
    }

    GitHubCommitArrayPtr Counter::fetchReposCommits(
            const std::string& repo,
            std::string* err
            )
    {
        auto slashPos = repo.find('/');

        if (slashPos == std::string::npos) {
            *err = "Invalid repository name";
            return GitHubCommitArrayPtr();
        }

        auto owner   = repo.substr(0, repo.find('/'));
        auto name    = repo.substr(repo.find('/') + 1);
        auto commits = github_->fetchReposCommits(
                std::move(owner),
                std::move(name),
                err);

        return std::move(commits);
    }
}
<|endoftext|>


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

 The Medical Imaging Interaction Toolkit (MITK)

 Copyright (c) German Cancer Research Center,
 Division of Medical and Biological Informatics.
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without
 even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.

 See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkEventFactory.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <mitkMousePressEvent.h>
#include <mitkMouseMoveEvent.h>
#include <mitkMouseReleaseEvent.h>
#include <mitkMouseWheelEvent.h>
#include <mitkInteractionKeyEvent.h>
#include <mitkInteractionEventConst.h>
#include <mitkInteractionPositionEvent.h>
#include <mitkInternalEvent.h>

namespace
{
  std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems)
  {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    {
      elems.push_back(item);
    }
    return elems;
  }

  std::vector<std::string> split(const std::string &s, char delim)
  {
    std::vector < std::string > elems;
    return split(s, delim, elems);
  }
}

mitk::InteractionEvent::Pointer mitk::EventFactory::CreateEvent(PropertyList::Pointer list)
{
//
  std::string eventClass, eventVariant;
  list->GetStringProperty(InteractionEventConst::xmlParameterEventClass().c_str(), eventClass);
  list->GetStringProperty(InteractionEventConst::xmlParameterEventVariant().c_str(), eventVariant);

// Query all possible attributes, if they are not present, set their default values.
// Position Events & Key Events
  std::string strModifiers;
  InteractionEvent::ModifierKeys modifiers = InteractionEvent::NoKey;
  std::string strEventButton;
  InteractionEvent::MouseButtons eventButton = InteractionEvent::NoButton;
  std::string strButtonState;
  InteractionEvent::MouseButtons buttonState = InteractionEvent::NoButton;
  std::string strKey;
  std::string key;
  std::string strWheelDelta;
  int wheelDelta;
  std::string strSignalName = "";

  Point2D pos;
  pos.Fill(0);

// Parse modifier information
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyModifier().c_str(), strModifiers))
  {
    std::vector<std::string> mods = split(strModifiers, ',');
    for (std::vector<std::string>::iterator it = mods.begin(); it != mods.end(); ++it)
    {
      std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper);
      if (*it == "CTRL")
      {
        modifiers = modifiers | InteractionEvent::ControlKey;
      }
      else if (*it == "ALT")
      {
        modifiers = modifiers | InteractionEvent::AltKey;
      }
      else if (*it == "SHIFT")
      {
        modifiers = modifiers | InteractionEvent::ShiftKey;
      }
      else
      {
        MITK_WARN<< "mitkEventFactory: Invalid event modifier in config file :" << (*it);
      }
    }
  }

// Set EventButton
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyEventButton().c_str(), strEventButton))
  {
    std::transform(strEventButton.begin(), strEventButton.end(), strEventButton.begin(), ::toupper);
    if (strEventButton == "MIDDLEMOUSEBUTTON")
    {
      eventButton = InteractionEvent::MiddleMouseButton;
    }
    else if (strEventButton == "LEFTMOUSEBUTTON")
    {
      eventButton = InteractionEvent::LeftMouseButton;
    }
    else if (strEventButton == "RIGHTMOUSEBUTTON")
    {
      eventButton = InteractionEvent::RightMouseButton;
    }
    else
    {
      MITK_WARN<< "mitkEventFactory: Invalid event button in config file: " << strEventButton;
    }
  }

// Parse ButtonStates
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyButtonState().c_str(), strButtonState))
  {
    std::vector<std::string> mods = split(strButtonState, ',');
    for (std::vector<std::string>::iterator it = mods.begin(); it != mods.end(); ++it)
    {
      std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper);
      if (*it == "MIDDLEMOUSEBUTTON")
      {
        buttonState = buttonState | InteractionEvent::MiddleMouseButton;
      }
      else if (*it == "LEFTMOUSEBUTTON")
      {
        buttonState = buttonState | InteractionEvent::LeftMouseButton;
      }
      else if (*it == "RIGHTMOUSEBUTTON")
      {
        buttonState = buttonState | InteractionEvent::RightMouseButton;
      }
      else
      {
        MITK_WARN<< "mitkEventFactory: Invalid event buttonstate in config file:" << (*it);
      }
    }
  }

// Key
  if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyKey().c_str(), strKey))
  {
    key = "";
  }
  else
  {
    key = strKey;
  }
// WheelDelta
  if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyScrollDirection().c_str(), strWheelDelta))
  {
    wheelDelta = 0;
  }
  else
  {
    std::transform(strWheelDelta.begin(), strWheelDelta.end(), strWheelDelta.begin(), ::toupper);
    if (strWheelDelta == "DOWN")
    {
      wheelDelta = -1;
    }
    else
    {
      wheelDelta = 1;
    }
  }
// Internal Signals Name
  list->GetStringProperty(InteractionEventConst::xmlEventPropertySignalName().c_str(), strSignalName);

  /*
   * Here the objects are created
   */

  mitk::InteractionEvent::Pointer event;
  std::transform(eventClass.begin(), eventClass.end(), eventClass.begin(), ::toupper);

  if (eventClass == "MOUSEPRESSEVENT")
  {
    // buttonstates incorporate the event button (as in Qt)
    buttonState = buttonState | eventButton;
    event = MousePressEvent::New(NULL, pos, buttonState, modifiers, eventButton);
  }
  else if (eventClass == "MOUSEMOVEEVENT")
  {
    event = MouseMoveEvent::New(NULL, pos, buttonState, modifiers);
  }
  else if (eventClass == "MOUSERELEASEEVENT")
  {
    event = MouseReleaseEvent::New(NULL, pos, buttonState, modifiers, eventButton);
  }
  else if (eventClass == "INTERACTIONKEYEVENT")
  {
    event = InteractionKeyEvent::New(NULL, key, modifiers);
  }
  else if (eventClass == "MOUSEWHEELEVENT")
  {
    event = MouseWheelEvent::New(NULL, pos, buttonState, modifiers, wheelDelta);
  }
  else if (eventClass == "INTERACTIONPOSITIONEVENT")
  {
    event = InteractionPositionEvent::New(NULL, pos);
  }
  else if (eventClass == "INTERNALEVENT")
  {
    event = InternalEvent::New(NULL, NULL, strSignalName);
  }
  else if (eventClass == "INTERACTIONEVENT")
  {
    event = InteractionEvent::New(NULL);
  }
  if (event.IsNull())
  {
    MITK_WARN<< "Event couldn't be constructed. Please check your StateMachine patterns and config files\n for the following event class, which is not valid: " << eventClass;
    return NULL;
  }
  return event;
}
<commit_msg>added mousedoubleclick event to EventFactory<commit_after>/*===================================================================

 The Medical Imaging Interaction Toolkit (MITK)

 Copyright (c) German Cancer Research Center,
 Division of Medical and Biological Informatics.
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without
 even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.

 See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkEventFactory.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <mitkMousePressEvent.h>
#include <mitkMouseDoubleClickEvent.h>
#include <mitkMouseMoveEvent.h>
#include <mitkMouseReleaseEvent.h>
#include <mitkMouseWheelEvent.h>
#include <mitkInteractionKeyEvent.h>
#include <mitkInteractionEventConst.h>
#include <mitkInteractionPositionEvent.h>
#include <mitkInternalEvent.h>

namespace
{
  std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems)
  {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    {
      elems.push_back(item);
    }
    return elems;
  }

  std::vector<std::string> split(const std::string &s, char delim)
  {
    std::vector < std::string > elems;
    return split(s, delim, elems);
  }
}

mitk::InteractionEvent::Pointer mitk::EventFactory::CreateEvent(PropertyList::Pointer list)
{
//
  std::string eventClass, eventVariant;
  list->GetStringProperty(InteractionEventConst::xmlParameterEventClass().c_str(), eventClass);
  list->GetStringProperty(InteractionEventConst::xmlParameterEventVariant().c_str(), eventVariant);

// Query all possible attributes, if they are not present, set their default values.
// Position Events & Key Events
  std::string strModifiers;
  InteractionEvent::ModifierKeys modifiers = InteractionEvent::NoKey;
  std::string strEventButton;
  InteractionEvent::MouseButtons eventButton = InteractionEvent::NoButton;
  std::string strButtonState;
  InteractionEvent::MouseButtons buttonState = InteractionEvent::NoButton;
  std::string strKey;
  std::string key;
  std::string strWheelDelta;
  int wheelDelta;
  std::string strSignalName = "";

  Point2D pos;
  pos.Fill(0);

// Parse modifier information
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyModifier().c_str(), strModifiers))
  {
    std::vector<std::string> mods = split(strModifiers, ',');
    for (std::vector<std::string>::iterator it = mods.begin(); it != mods.end(); ++it)
    {
      std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper);
      if (*it == "CTRL")
      {
        modifiers = modifiers | InteractionEvent::ControlKey;
      }
      else if (*it == "ALT")
      {
        modifiers = modifiers | InteractionEvent::AltKey;
      }
      else if (*it == "SHIFT")
      {
        modifiers = modifiers | InteractionEvent::ShiftKey;
      }
      else
      {
        MITK_WARN<< "mitkEventFactory: Invalid event modifier in config file :" << (*it);
      }
    }
  }

// Set EventButton
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyEventButton().c_str(), strEventButton))
  {
    std::transform(strEventButton.begin(), strEventButton.end(), strEventButton.begin(), ::toupper);
    if (strEventButton == "MIDDLEMOUSEBUTTON")
    {
      eventButton = InteractionEvent::MiddleMouseButton;
    }
    else if (strEventButton == "LEFTMOUSEBUTTON")
    {
      eventButton = InteractionEvent::LeftMouseButton;
    }
    else if (strEventButton == "RIGHTMOUSEBUTTON")
    {
      eventButton = InteractionEvent::RightMouseButton;
    }
    else
    {
      MITK_WARN<< "mitkEventFactory: Invalid event button in config file: " << strEventButton;
    }
  }

// Parse ButtonStates
  if (list->GetStringProperty(InteractionEventConst::xmlEventPropertyButtonState().c_str(), strButtonState))
  {
    std::vector<std::string> mods = split(strButtonState, ',');
    for (std::vector<std::string>::iterator it = mods.begin(); it != mods.end(); ++it)
    {
      std::transform((*it).begin(), (*it).end(), (*it).begin(), ::toupper);
      if (*it == "MIDDLEMOUSEBUTTON")
      {
        buttonState = buttonState | InteractionEvent::MiddleMouseButton;
      }
      else if (*it == "LEFTMOUSEBUTTON")
      {
        buttonState = buttonState | InteractionEvent::LeftMouseButton;
      }
      else if (*it == "RIGHTMOUSEBUTTON")
      {
        buttonState = buttonState | InteractionEvent::RightMouseButton;
      }
      else
      {
        MITK_WARN<< "mitkEventFactory: Invalid event buttonstate in config file:" << (*it);
      }
    }
  }

// Key
  if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyKey().c_str(), strKey))
  {
    key = "";
  }
  else
  {
    key = strKey;
  }
// WheelDelta
  if (!list->GetStringProperty(InteractionEventConst::xmlEventPropertyScrollDirection().c_str(), strWheelDelta))
  {
    wheelDelta = 0;
  }
  else
  {
    std::transform(strWheelDelta.begin(), strWheelDelta.end(), strWheelDelta.begin(), ::toupper);
    if (strWheelDelta == "DOWN")
    {
      wheelDelta = -1;
    }
    else
    {
      wheelDelta = 1;
    }
  }
// Internal Signals Name
  list->GetStringProperty(InteractionEventConst::xmlEventPropertySignalName().c_str(), strSignalName);

  /*
   * Here the objects are created
   */

  mitk::InteractionEvent::Pointer event;
  std::transform(eventClass.begin(), eventClass.end(), eventClass.begin(), ::toupper);

  if (eventClass == "MOUSEPRESSEVENT")
  {
    // buttonstates incorporate the event button (as in Qt)
    buttonState = buttonState | eventButton;
    event = MousePressEvent::New(NULL, pos, buttonState, modifiers, eventButton);
  }
  else if (eventClass == "MOUSEDOUBLECLICKEVENT")
  {
    buttonState = buttonState | eventButton;
    event = MouseDoubleClickEvent::New(NULL, pos, buttonState, modifiers, eventButton);
  }
  else if (eventClass == "MOUSEMOVEEVENT")
  {
    event = MouseMoveEvent::New(NULL, pos, buttonState, modifiers);
  }
  else if (eventClass == "MOUSERELEASEEVENT")
  {
    event = MouseReleaseEvent::New(NULL, pos, buttonState, modifiers, eventButton);
  }
  else if (eventClass == "INTERACTIONKEYEVENT")
  {
    event = InteractionKeyEvent::New(NULL, key, modifiers);
  }
  else if (eventClass == "MOUSEWHEELEVENT")
  {
    event = MouseWheelEvent::New(NULL, pos, buttonState, modifiers, wheelDelta);
  }
  else if (eventClass == "INTERACTIONPOSITIONEVENT")
  {
    event = InteractionPositionEvent::New(NULL, pos);
  }
  else if (eventClass == "INTERNALEVENT")
  {
    event = InternalEvent::New(NULL, NULL, strSignalName);
  }
  else if (eventClass == "INTERACTIONEVENT")
  {
    event = InteractionEvent::New(NULL);
  }
  if (event.IsNull())
  {
    MITK_WARN<< "Event couldn't be constructed. Please check your StateMachine patterns and config files\n for the following event class, which is not valid: " << eventClass;
    return NULL;
  }
  return event;
}
<|endoftext|>


<commit_before>#pragma once
#include "neural_network.hpp"

namespace Hippocrates::Trained {

template<typename Classification>
class Classifier : public NeuralNetwork {
public:
	using NeuralNetwork::NeuralNetwork;
	Classifier() : NeuralNetwork(){ };
	Classifier(const NeuralNetwork& other) : NeuralNetwork(other){};
	Classifier(NeuralNetwork&& other) : NeuralNetwork(std::move(other)){};

	auto Classify(const Type::neuron_values_t& inputs) {
		const auto outputs = GetOutputsUsingInputs(inputs);
		const auto maxOutput = std::max_element(outputs.begin(), outputs.end());
		const auto outputIndex = std::distance(outputs.begin(), maxOutput);
		return static_cast<Classification>(outputIndex);
	}
};

}
<commit_msg>Add dependency<commit_after>#pragma once
#include <memory>
#include "neural_network.hpp"

namespace Hippocrates::Trained {

template<typename Classification>
class Classifier : public NeuralNetwork {
public:
	using NeuralNetwork::NeuralNetwork;
	Classifier() : NeuralNetwork(){ };
	Classifier(const NeuralNetwork& other) : NeuralNetwork(other){};
	Classifier(NeuralNetwork&& other) : NeuralNetwork(std::move(other)){};

	auto Classify(const Type::neuron_values_t& inputs) {
		const auto outputs = GetOutputsUsingInputs(inputs);
		const auto maxOutput = std::max_element(outputs.begin(), outputs.end());
		const auto outputIndex = std::distance(outputs.begin(), maxOutput);
		return static_cast<Classification>(outputIndex);
	}
};

}
<|endoftext|>