<commit_before>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * 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) 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
 * 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 "config.h"
#include "core/css/CSSDefaultStyleSheets.h"

#include "MathMLNames.h"
#include "UserAgentStyleSheets.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/RuleSet.h"
#include "core/css/StyleSheetContents.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/rendering/RenderTheme.h"

namespace WebCore {

using namespace HTMLNames;

CSSDefaultStyleSheets& CSSDefaultStyleSheets::instance()
{
#if ENABLE(OILPAN)
    DEFINE_STATIC_LOCAL(Persistent<CSSDefaultStyleSheets>, cssDefaultStyleSheets, (new CSSDefaultStyleSheets()));
    return *cssDefaultStyleSheets;
#else
    DEFINE_STATIC_LOCAL(CSSDefaultStyleSheets, cssDefaultStyleSheets, ());
    return cssDefaultStyleSheets;
#endif
}

static const MediaQueryEvaluator& screenEval()
{
    DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
    return staticScreenEval;
}

static const MediaQueryEvaluator& printEval()
{
    DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
    return staticPrintEval;
}

static PassRefPtrWillBeRawPtr<StyleSheetContents> parseUASheet(const String& str)
{
    RefPtrWillBeRawPtr<StyleSheetContents> sheet = StyleSheetContents::create(CSSParserContext(UASheetMode, 0));
    sheet->parseString(str);
    return sheet.release();
}

static PassRefPtrWillBeRawPtr<StyleSheetContents> parseUASheet(const char* characters, unsigned size)
{
    return parseUASheet(String(characters, size));
}

CSSDefaultStyleSheets::CSSDefaultStyleSheets()
    : m_defaultStyle(nullptr)
    , m_defaultViewportStyle(nullptr)
    , m_defaultQuirksStyle(nullptr)
    , m_defaultPrintStyle(nullptr)
    , m_defaultViewSourceStyle(nullptr)
    , m_defaultXHTMLMobileProfileStyle(nullptr)
    , m_defaultStyleSheet(nullptr)
    , m_viewportStyleSheet(nullptr)
    , m_quirksStyleSheet(nullptr)
    , m_svgStyleSheet(nullptr)
    , m_mathmlStyleSheet(nullptr)
    , m_mediaControlsStyleSheet(nullptr)
    , m_fullscreenStyleSheet(nullptr)
{
    m_defaultStyle = RuleSet::create();
    m_defaultViewportStyle = RuleSet::create();
    m_defaultPrintStyle = RuleSet::create();
    m_defaultQuirksStyle = RuleSet::create();

    // Strict-mode rules.
    String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet();
    m_defaultStyleSheet = parseUASheet(defaultRules);
    m_defaultStyle->addRulesFromSheet(defaultStyleSheet(), screenEval());
#if OS(ANDROID)
    String viewportRules(viewportAndroidUserAgentStyleSheet, sizeof(viewportAndroidUserAgentStyleSheet));
#else
    String viewportRules;
#endif
    m_viewportStyleSheet = parseUASheet(viewportRules);
    m_defaultViewportStyle->addRulesFromSheet(viewportStyleSheet(), screenEval());
    m_defaultPrintStyle->addRulesFromSheet(defaultStyleSheet(), printEval());

    // Quirks-mode rules.
    String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet();
    m_quirksStyleSheet = parseUASheet(quirksRules);
    m_defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet(), screenEval());
}

RuleSet* CSSDefaultStyleSheets::defaultViewSourceStyle()
{
    if (!m_defaultViewSourceStyle) {
        m_defaultViewSourceStyle = RuleSet::create();
        // Loaded stylesheet is leaked on purpose.
        RefPtrWillBeRawPtr<StyleSheetContents> stylesheet = parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet));
        m_defaultViewSourceStyle->addRulesFromSheet(stylesheet.release().leakRef(), screenEval());
    }
    return m_defaultViewSourceStyle.get();
}

RuleSet* CSSDefaultStyleSheets::defaultXHTMLMobileProfileStyle()
{
    if (!m_defaultXHTMLMobileProfileStyle) {
        m_defaultXHTMLMobileProfileStyle = RuleSet::create();
        // Loaded stylesheet is leaked on purpose.
        RefPtrWillBeRawPtr<StyleSheetContents> stylesheet = parseUASheet(xhtmlmpUserAgentStyleSheet, sizeof(xhtmlmpUserAgentStyleSheet));
        m_defaultXHTMLMobileProfileStyle->addRulesFromSheet(stylesheet.release().leakRef(), screenEval());
    }
    return m_defaultXHTMLMobileProfileStyle.get();
}

void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(Element* element, bool& changedDefaultStyle)
{
    // FIXME: We should assert that the sheet only styles SVG elements.
    if (element->isSVGElement() && !m_svgStyleSheet) {
        m_svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
        m_defaultStyle->addRulesFromSheet(svgStyleSheet(), screenEval());
        m_defaultPrintStyle->addRulesFromSheet(svgStyleSheet(), printEval());
        changedDefaultStyle = true;
    }

    // FIXME: We should assert that the sheet only styles MathML elements.
    if (element->namespaceURI() == MathMLNames::mathmlNamespaceURI
        && !m_mathmlStyleSheet) {
        m_mathmlStyleSheet = parseUASheet(mathmlUserAgentStyleSheet,
            sizeof(mathmlUserAgentStyleSheet));
        m_defaultStyle->addRulesFromSheet(mathmlStyleSheet(), screenEval());
        m_defaultPrintStyle->addRulesFromSheet(mathmlStyleSheet(), printEval());
        changedDefaultStyle = true;
    }

    // FIXME: We should assert that this sheet only contains rules for <video> and <audio>.
    if (!m_mediaControlsStyleSheet && (isHTMLVideoElement(*element) || isHTMLAudioElement(*element))) {
        String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::theme().extraMediaControlsStyleSheet();
        m_mediaControlsStyleSheet = parseUASheet(mediaRules);
        m_defaultStyle->addRulesFromSheet(mediaControlsStyleSheet(), screenEval());
        m_defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet(), printEval());
        changedDefaultStyle = true;
    }

    // FIXME: This only works because we Force recalc the entire document so the new sheet
    // is loaded for <html> and the correct styles apply to everyone.
    if (!m_fullscreenStyleSheet && FullscreenElementStack::isFullScreen(element->document())) {
        String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::theme().extraFullScreenStyleSheet();
        m_fullscreenStyleSheet = parseUASheet(fullscreenRules);
        m_defaultStyle->addRulesFromSheet(fullscreenStyleSheet(), screenEval());
        m_defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet(), screenEval());
        changedDefaultStyle = true;
    }

    ASSERT(!m_defaultStyle->features().hasIdsInSelectors());
    ASSERT(m_defaultStyle->features().siblingRules.isEmpty());
}

void CSSDefaultStyleSheets::trace(Visitor* visitor)
{
    visitor->trace(m_defaultStyle);
    visitor->trace(m_defaultViewportStyle);
    visitor->trace(m_defaultQuirksStyle);
    visitor->trace(m_defaultPrintStyle);
    visitor->trace(m_defaultViewSourceStyle);
    visitor->trace(m_defaultXHTMLMobileProfileStyle);
    visitor->trace(m_defaultStyleSheet);
    visitor->trace(m_viewportStyleSheet);
    visitor->trace(m_quirksStyleSheet);
    visitor->trace(m_svgStyleSheet);
    visitor->trace(m_mathmlStyleSheet);
    visitor->trace(m_mediaControlsStyleSheet);
    visitor->trace(m_fullscreenStyleSheet);
}

} // namespace WebCore
<commit_msg>Annotate intentional leak of UA style sheets.<commit_after>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * 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) 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
 * 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 "config.h"
#include "core/css/CSSDefaultStyleSheets.h"

#include "MathMLNames.h"
#include "UserAgentStyleSheets.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/RuleSet.h"
#include "core/css/StyleSheetContents.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/rendering/RenderTheme.h"
#include "wtf/LeakAnnotations.h"

namespace WebCore {

using namespace HTMLNames;

CSSDefaultStyleSheets& CSSDefaultStyleSheets::instance()
{
#if ENABLE(OILPAN)
    DEFINE_STATIC_LOCAL(Persistent<CSSDefaultStyleSheets>, cssDefaultStyleSheets, (new CSSDefaultStyleSheets()));
    return *cssDefaultStyleSheets;
#else
    DEFINE_STATIC_LOCAL(CSSDefaultStyleSheets, cssDefaultStyleSheets, ());
    return cssDefaultStyleSheets;
#endif
}

static const MediaQueryEvaluator& screenEval()
{
    DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
    return staticScreenEval;
}

static const MediaQueryEvaluator& printEval()
{
    DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
    return staticPrintEval;
}

static PassRefPtrWillBeRawPtr<StyleSheetContents> parseUASheet(const String& str)
{
    RefPtrWillBeRawPtr<StyleSheetContents> sheet = StyleSheetContents::create(CSSParserContext(UASheetMode, 0));
    sheet->parseString(str);
    // User Agent stylesheets are parsed once for the lifetime of the renderer
    // and are intentionally leaked.
    WTF_ANNOTATE_LEAKING_OBJECT_PTR(sheet.get());
    return sheet.release();
}

static PassRefPtrWillBeRawPtr<StyleSheetContents> parseUASheet(const char* characters, unsigned size)
{
    return parseUASheet(String(characters, size));
}

CSSDefaultStyleSheets::CSSDefaultStyleSheets()
    : m_defaultStyle(nullptr)
    , m_defaultViewportStyle(nullptr)
    , m_defaultQuirksStyle(nullptr)
    , m_defaultPrintStyle(nullptr)
    , m_defaultViewSourceStyle(nullptr)
    , m_defaultXHTMLMobileProfileStyle(nullptr)
    , m_defaultStyleSheet(nullptr)
    , m_viewportStyleSheet(nullptr)
    , m_quirksStyleSheet(nullptr)
    , m_svgStyleSheet(nullptr)
    , m_mathmlStyleSheet(nullptr)
    , m_mediaControlsStyleSheet(nullptr)
    , m_fullscreenStyleSheet(nullptr)
{
    m_defaultStyle = RuleSet::create();
    m_defaultViewportStyle = RuleSet::create();
    m_defaultPrintStyle = RuleSet::create();
    m_defaultQuirksStyle = RuleSet::create();

    // Strict-mode rules.
    String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet();
    m_defaultStyleSheet = parseUASheet(defaultRules);
    m_defaultStyle->addRulesFromSheet(defaultStyleSheet(), screenEval());
#if OS(ANDROID)
    String viewportRules(viewportAndroidUserAgentStyleSheet, sizeof(viewportAndroidUserAgentStyleSheet));
#else
    String viewportRules;
#endif
    m_viewportStyleSheet = parseUASheet(viewportRules);
    m_defaultViewportStyle->addRulesFromSheet(viewportStyleSheet(), screenEval());
    m_defaultPrintStyle->addRulesFromSheet(defaultStyleSheet(), printEval());

    // Quirks-mode rules.
    String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet();
    m_quirksStyleSheet = parseUASheet(quirksRules);
    m_defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet(), screenEval());
}

RuleSet* CSSDefaultStyleSheets::defaultViewSourceStyle()
{
    if (!m_defaultViewSourceStyle) {
        m_defaultViewSourceStyle = RuleSet::create();
        // Loaded stylesheet is leaked on purpose.
        RefPtrWillBeRawPtr<StyleSheetContents> stylesheet = parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet));
        m_defaultViewSourceStyle->addRulesFromSheet(stylesheet.release().leakRef(), screenEval());
    }
    return m_defaultViewSourceStyle.get();
}

RuleSet* CSSDefaultStyleSheets::defaultXHTMLMobileProfileStyle()
{
    if (!m_defaultXHTMLMobileProfileStyle) {
        m_defaultXHTMLMobileProfileStyle = RuleSet::create();
        // Loaded stylesheet is leaked on purpose.
        RefPtrWillBeRawPtr<StyleSheetContents> stylesheet = parseUASheet(xhtmlmpUserAgentStyleSheet, sizeof(xhtmlmpUserAgentStyleSheet));
        m_defaultXHTMLMobileProfileStyle->addRulesFromSheet(stylesheet.release().leakRef(), screenEval());
    }
    return m_defaultXHTMLMobileProfileStyle.get();
}

void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(Element* element, bool& changedDefaultStyle)
{
    // FIXME: We should assert that the sheet only styles SVG elements.
    if (element->isSVGElement() && !m_svgStyleSheet) {
        m_svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
        m_defaultStyle->addRulesFromSheet(svgStyleSheet(), screenEval());
        m_defaultPrintStyle->addRulesFromSheet(svgStyleSheet(), printEval());
        changedDefaultStyle = true;
    }

    // FIXME: We should assert that the sheet only styles MathML elements.
    if (element->namespaceURI() == MathMLNames::mathmlNamespaceURI
        && !m_mathmlStyleSheet) {
        m_mathmlStyleSheet = parseUASheet(mathmlUserAgentStyleSheet,
            sizeof(mathmlUserAgentStyleSheet));
        m_defaultStyle->addRulesFromSheet(mathmlStyleSheet(), screenEval());
        m_defaultPrintStyle->addRulesFromSheet(mathmlStyleSheet(), printEval());
        changedDefaultStyle = true;
    }

    // FIXME: We should assert that this sheet only contains rules for <video> and <audio>.
    if (!m_mediaControlsStyleSheet && (isHTMLVideoElement(*element) || isHTMLAudioElement(*element))) {
        String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::theme().extraMediaControlsStyleSheet();
        m_mediaControlsStyleSheet = parseUASheet(mediaRules);
        m_defaultStyle->addRulesFromSheet(mediaControlsStyleSheet(), screenEval());
        m_defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet(), printEval());
        changedDefaultStyle = true;
    }

    // FIXME: This only works because we Force recalc the entire document so the new sheet
    // is loaded for <html> and the correct styles apply to everyone.
    if (!m_fullscreenStyleSheet && FullscreenElementStack::isFullScreen(element->document())) {
        String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::theme().extraFullScreenStyleSheet();
        m_fullscreenStyleSheet = parseUASheet(fullscreenRules);
        m_defaultStyle->addRulesFromSheet(fullscreenStyleSheet(), screenEval());
        m_defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet(), screenEval());
        changedDefaultStyle = true;
    }

    ASSERT(!m_defaultStyle->features().hasIdsInSelectors());
    ASSERT(m_defaultStyle->features().siblingRules.isEmpty());
}

void CSSDefaultStyleSheets::trace(Visitor* visitor)
{
    visitor->trace(m_defaultStyle);
    visitor->trace(m_defaultViewportStyle);
    visitor->trace(m_defaultQuirksStyle);
    visitor->trace(m_defaultPrintStyle);
    visitor->trace(m_defaultViewSourceStyle);
    visitor->trace(m_defaultXHTMLMobileProfileStyle);
    visitor->trace(m_defaultStyleSheet);
    visitor->trace(m_viewportStyleSheet);
    visitor->trace(m_quirksStyleSheet);
    visitor->trace(m_svgStyleSheet);
    visitor->trace(m_mathmlStyleSheet);
    visitor->trace(m_mediaControlsStyleSheet);
    visitor->trace(m_fullscreenStyleSheet);
}

} // namespace WebCore
<|endoftext|>


<commit_before>// -*- mode:C++ { } tab-width:4 { } c-basic-offset:4 { } indent-tabs-mode:nil -*-

/*
 * Copyright (C) 2015 iCub Facility
 * Authors: Ali Paikan
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
 *
 */

#include <rtf/dll/Plugin.h>
#include <yarp/manager/utility.h>
#include <yarp/os/Network.h>
#include <yarp/os/Property.h>
#include <yarp/os/ResourceFinder.h>

#include "YarpFixManager.h"

using namespace RTF;
using namespace yarp::os;
using namespace yarp::manager;

PREPARE_FIXTURE_PLUGIN(YarpFixManager)

YarpFixManager::YarpFixManager()
    : initialized(false) { }

YarpFixManager::~YarpFixManager() {
        tearDown();
}

bool YarpFixManager::setup(int argc, char** argv) {
    RTF_FIXTURE_REPORT("yarpmanager is setuping the fixture...");
    bool ret;
    const char* szerror;
    if(!initialized) {
        // check yarp network
        yarp.setVerbosity(-1);
        RTF_ASSERT_ERROR_IF(yarp.checkNetwork(),
                            "YARP network does not seem to be available, is the yarp server accessible?");

        // load the config file and update the environment if available
        // E.g., "--application myapp.xml"
        yarp::os::ResourceFinder rf;
        rf.setVerbose(false);
        rf.setDefaultContext("RobotTesting");
        rf.configure("", argc, argv, false);

        RTF_ASSERT_ERROR_IF(rf.check("fixture"),
                            "No application xml file is set (add --fixture yourfixture.xml)");

        fixtureName = rf.find("fixture").asString();
        std::string appfile = rf.findFileByName(std::string("fixtures/"+fixtureName).c_str());
        RTF_ASSERT_ERROR_IF(appfile.size(),
                            RTF::Asserter::format("yarpmanager cannot find apllication file %s. Is it in the 'fixtures' folder?",
                                                  fixtureName.c_str()));

        // enable restricted mode to ensure all the modules
        // is running and enable watchdog to monitor the modules.
        enableWatchDog();
        enableAutoConnect();
        enableRestrictedMode();

        // load the fixture (application xml)
        char szAppName[255];
        ret = addApplication(appfile.c_str(), szAppName, 254);
        RTF_ASSERT_ERROR_IF(ret,
                            "yarpmanager (addApplication) cannot setup the fixture because " +
                            std::string(getLogger()->getFormatedErrorString()));

        ret = loadApplication(szAppName);
        RTF_ASSERT_ERROR_IF(ret,
                            "yarpmanager (loadApplication) cannot setup the fixture because " +
                            std::string(getLogger()->getFormatedErrorString()));
        initialized = true;
    }

    //run the modules and connect
    ret = run();
    RTF_ASSERT_ERROR_IF(ret,
                        "yarpmanager (run) cannot setup the fixture because " +
                        std::string(getLogger()->getFormatedErrorString()));
    return true;
}

void YarpFixManager::tearDown() {
    RTF_FIXTURE_REPORT("yarpmanager is tearing down the fixture...");
    bool ret = stop();
    if(!ret)
        ret = kill();
    const char* szerror = getLogger()->getLastError();
    RTF_ASSERT_ERROR_IF(ret,
                        "yarpmanager cannot teardown the fixture because " +
                        std::string((szerror) ? szerror : ""));
}

void YarpFixManager::onExecutableFailed(void* which) {
    Executable* exe = (Executable*) which;
    RTF_ASSERT_ERROR_IF(exe!=NULL, "Executable is null!");
    TestMessage msg(Asserter::format("Fixture %s collapsed", fixtureName.c_str()),
                    Asserter::format("Module %s is failed!", exe->getCommand()),
                    RTF_SOURCEFILE(), RTF_SOURCELINE());
    getDispatcher()->fixtureCollapsed(msg);
}

void YarpFixManager::onCnnFailed(void* which) {
    Connection* cnn = (Connection*) which;
    RTF_ASSERT_ERROR_IF(cnn!=NULL, "Connection is null!");
    TestMessage msg(Asserter::format("Fixture %s collapsed", fixtureName.c_str()),
                    Asserter::format("Connection %s - %s is failed!",
                                     cnn->from(), cnn->to()),
                    RTF_SOURCEFILE(), RTF_SOURCELINE());
    getDispatcher()->fixtureCollapsed(msg);
}
<commit_msg>fixing ResourceFinder::configure() deprecated warning<commit_after>// -*- mode:C++ { } tab-width:4 { } c-basic-offset:4 { } indent-tabs-mode:nil -*-

/*
 * Copyright (C) 2015 iCub Facility
 * Authors: Ali Paikan
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
 *
 */

#include <rtf/dll/Plugin.h>
#include <yarp/manager/utility.h>
#include <yarp/os/Network.h>
#include <yarp/os/Property.h>
#include <yarp/os/ResourceFinder.h>

#include "YarpFixManager.h"

using namespace RTF;
using namespace yarp::os;
using namespace yarp::manager;

PREPARE_FIXTURE_PLUGIN(YarpFixManager)

YarpFixManager::YarpFixManager()
    : initialized(false) { }

YarpFixManager::~YarpFixManager() {
        tearDown();
}

bool YarpFixManager::setup(int argc, char** argv) {
    RTF_FIXTURE_REPORT("yarpmanager is setuping the fixture...");
    bool ret;
    const char* szerror;
    if(!initialized) {
        // check yarp network
        yarp.setVerbosity(-1);
        RTF_ASSERT_ERROR_IF(yarp.checkNetwork(),
                            "YARP network does not seem to be available, is the yarp server accessible?");

        // load the config file and update the environment if available
        // E.g., "--application myapp.xml"
        yarp::os::ResourceFinder rf;
        rf.setVerbose(false);
        rf.setDefaultContext("RobotTesting");
        rf.configure(argc, argv, false);

        RTF_ASSERT_ERROR_IF(rf.check("fixture"),
                            "No application xml file is set (add --fixture yourfixture.xml)");

        fixtureName = rf.find("fixture").asString();
        std::string appfile = rf.findFileByName(std::string("fixtures/"+fixtureName).c_str());
        RTF_ASSERT_ERROR_IF(appfile.size(),
                            RTF::Asserter::format("yarpmanager cannot find apllication file %s. Is it in the 'fixtures' folder?",
                                                  fixtureName.c_str()));

        // enable restricted mode to ensure all the modules
        // is running and enable watchdog to monitor the modules.
        enableWatchDog();
        enableAutoConnect();
        enableRestrictedMode();

        // load the fixture (application xml)
        char szAppName[255];
        ret = addApplication(appfile.c_str(), szAppName, 254);
        RTF_ASSERT_ERROR_IF(ret,
                            "yarpmanager (addApplication) cannot setup the fixture because " +
                            std::string(getLogger()->getFormatedErrorString()));

        ret = loadApplication(szAppName);
        RTF_ASSERT_ERROR_IF(ret,
                            "yarpmanager (loadApplication) cannot setup the fixture because " +
                            std::string(getLogger()->getFormatedErrorString()));
        initialized = true;
    }

    //run the modules and connect
    ret = run();
    RTF_ASSERT_ERROR_IF(ret,
                        "yarpmanager (run) cannot setup the fixture because " +
                        std::string(getLogger()->getFormatedErrorString()));
    return true;
}

void YarpFixManager::tearDown() {
    RTF_FIXTURE_REPORT("yarpmanager is tearing down the fixture...");
    bool ret = stop();
    if(!ret)
        ret = kill();
    const char* szerror = getLogger()->getLastError();
    RTF_ASSERT_ERROR_IF(ret,
                        "yarpmanager cannot teardown the fixture because " +
                        std::string((szerror) ? szerror : ""));
}

void YarpFixManager::onExecutableFailed(void* which) {
    Executable* exe = (Executable*) which;
    RTF_ASSERT_ERROR_IF(exe!=NULL, "Executable is null!");
    TestMessage msg(Asserter::format("Fixture %s collapsed", fixtureName.c_str()),
                    Asserter::format("Module %s is failed!", exe->getCommand()),
                    RTF_SOURCEFILE(), RTF_SOURCELINE());
    getDispatcher()->fixtureCollapsed(msg);
}

void YarpFixManager::onCnnFailed(void* which) {
    Connection* cnn = (Connection*) which;
    RTF_ASSERT_ERROR_IF(cnn!=NULL, "Connection is null!");
    TestMessage msg(Asserter::format("Fixture %s collapsed", fixtureName.c_str()),
                    Asserter::format("Connection %s - %s is failed!",
                                     cnn->from(), cnn->to()),
                    RTF_SOURCEFILE(), RTF_SOURCELINE());
    getDispatcher()->fixtureCollapsed(msg);
}
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Evangelos Anagnostopoulos
 */

#include <shogun/features/streaming/StreamingHashedDocDotFeatures.h>
#include <shogun/lib/SGString.h>
#include <shogun/lib/DelimiterTokenizer.h>
#include <shogun/converter/HashedDocConverter.h>

#include <gtest/gtest.h>

using namespace shogun;

TEST(StreamingHashedDocFeaturesTest, example_reading)
{
	const char* doc_1 = "You're never too old to rock and roll, if you're too young to die";
	const char* doc_2 = "Give me some rope, tie me to dream, give me the hope to run out of steam";
	const char* doc_3 = "Thank you Jack Daniels, Old Number Seven, Tennessee Whiskey got me drinking in heaven";

	SGString<char> string_1(65);
	for (index_t i=0; i<65; i++)
		string_1.string[i] = doc_1[i];

	SGString<char> string_2(72);
	for (index_t i=0; i<72; i++)
		string_2.string[i] = doc_2[i];

	SGString<char> string_3(85);
	for (index_t i=0; i<85; i++)
		string_3.string[i] = doc_3[i];

	SGStringList<char> list(3,85);
	list.strings[0] = string_1;
	list.strings[1] = string_2;
	list.strings[2] = string_3;

	CDelimiterTokenizer* tokenizer = new CDelimiterTokenizer();
	tokenizer->delimiters[' '] = 1;
	tokenizer->delimiters['\''] = 1;
	tokenizer->delimiters[','] = 1;

	CHashedDocConverter* converter = new CHashedDocConverter(tokenizer, 5, false);
	CStringFeatures<char>* doc_collection = new CStringFeatures<char>(list, RAWBYTE);
	CStreamingHashedDocDotFeatures* feats = new CStreamingHashedDocDotFeatures(doc_collection,
			tokenizer, 5);

	index_t i = 0;
	feats->start_parser();
	while (feats->get_next_example())
	{
		SGSparseVector<float64_t> example = feats->get_vector();

		SGVector<char> tmp(list.strings[i].string, list.strings[i].slen, false);
		tmp.vector = list.strings[i].string;
		SGSparseVector<float64_t> converted_doc = converter->apply(tmp);

		EXPECT_EQ(example.num_feat_entries, converted_doc.num_feat_entries);

		for (index_t j=0; j<example.num_feat_entries; j++)
		{
			EXPECT_EQ(example.features[j].feat_index, converted_doc.features[j].feat_index);
			EXPECT_EQ(example.features[j].entry, converted_doc.features[j].entry);
		}
		feats->release_example();
		i++;
	}
	feats->end_parser();
	SG_UNREF(feats);
	SG_UNREF(doc_collection);
	SG_UNREF(converter);
}

TEST(StreamingHashedDocFeaturesTest, dot_tests)
{
	const char* doc_1 = "You're never too old to rock and roll, if you're too young to die";
	const char* doc_2 = "Give me some rope, tie me to dream, give me the hope to run out of steam";
	const char* doc_3 = "Thank you Jack Daniels, Old Number Seven, Tennessee Whiskey got me drinking in heaven";

	SGString<char> string_1(65);
	for (index_t i=0; i<65; i++)
		string_1.string[i] = doc_1[i];

	SGString<char> string_2(72);
	for (index_t i=0; i<72; i++)
		string_2.string[i] = doc_2[i];

	SGString<char> string_3(85);
	for (index_t i=0; i<85; i++)
		string_3.string[i] = doc_3[i];

	SGStringList<char> list(3,85);
	list.strings[0] = string_1;
	list.strings[1] = string_2;
	list.strings[2] = string_3;

	CDelimiterTokenizer* tokenizer = new CDelimiterTokenizer();
	tokenizer->delimiters[' '] = 1;
	tokenizer->delimiters['\''] = 1;
	tokenizer->delimiters[','] = 1;

	CHashedDocConverter* converter = new CHashedDocConverter(tokenizer, 5, false);
	CStringFeatures<char>* doc_collection = new CStringFeatures<char>(list, RAWBYTE);
	CStreamingHashedDocDotFeatures* feats = new CStreamingHashedDocDotFeatures(doc_collection,
			tokenizer, 5);
	feats->start_parser();

	SGVector<float32_t> dense_vec(32);
	for (index_t j=0; j<32; j++)
		dense_vec[j] = CMath::random();

	index_t i = 0;
	while (feats->get_next_example())
	{
		/** Dense dot test */
		SGVector<char> tmp(list.strings[i].string, list.strings[i].slen, false);
		tmp.vector = list.strings[i].string;
		SGSparseVector<float64_t> converted_doc = converter->apply(tmp);

		float32_t tmp_res = 0;
		for (index_t j=0; j<converted_doc.num_feat_entries; j++)
			tmp_res += dense_vec[converted_doc.features[j].feat_index] * converted_doc.features[j].entry;

		EXPECT_EQ(tmp_res, feats->dense_dot(dense_vec.vector, dense_vec.vlen));

		/** Add to dense test */
		SGSparseVector<float64_t> example = feats->get_vector();
		SGVector<float32_t> dense_vec2(32);
		for (index_t j=0; j<32; j++)
			dense_vec2[j] = dense_vec[j];

		feats->add_to_dense_vec(1, dense_vec2.vector, dense_vec2.vlen);
		index_t sparse_idx = 0;
		for (index_t j=0; j<32; j++)
		{
			if ( (sparse_idx < example.num_feat_entries) &&
					(example.features[sparse_idx].feat_index == j) )
			{
				EXPECT_EQ(dense_vec2[j], dense_vec[j] + example.features[sparse_idx].entry);
				sparse_idx++;
			}
			else
				EXPECT_EQ(dense_vec2[j], dense_vec[j]);
		}

		feats->release_example();
		i++;
	}

	feats->end_parser();
	SG_UNREF(feats);
	SG_UNREF(doc_collection);
	SG_UNREF(converter);
}
<commit_msg>use expect_near instead of eq for double/float<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Evangelos Anagnostopoulos
 */

#include <shogun/features/streaming/StreamingHashedDocDotFeatures.h>
#include <shogun/lib/SGString.h>
#include <shogun/lib/DelimiterTokenizer.h>
#include <shogun/converter/HashedDocConverter.h>

#include <gtest/gtest.h>

using namespace shogun;

TEST(StreamingHashedDocFeaturesTest, example_reading)
{
	const char* doc_1 = "You're never too old to rock and roll, if you're too young to die";
	const char* doc_2 = "Give me some rope, tie me to dream, give me the hope to run out of steam";
	const char* doc_3 = "Thank you Jack Daniels, Old Number Seven, Tennessee Whiskey got me drinking in heaven";

	SGString<char> string_1(65);
	for (index_t i=0; i<65; i++)
		string_1.string[i] = doc_1[i];

	SGString<char> string_2(72);
	for (index_t i=0; i<72; i++)
		string_2.string[i] = doc_2[i];

	SGString<char> string_3(85);
	for (index_t i=0; i<85; i++)
		string_3.string[i] = doc_3[i];

	SGStringList<char> list(3,85);
	list.strings[0] = string_1;
	list.strings[1] = string_2;
	list.strings[2] = string_3;

	CDelimiterTokenizer* tokenizer = new CDelimiterTokenizer();
	tokenizer->delimiters[' '] = 1;
	tokenizer->delimiters['\''] = 1;
	tokenizer->delimiters[','] = 1;

	CHashedDocConverter* converter = new CHashedDocConverter(tokenizer, 5, false);
	CStringFeatures<char>* doc_collection = new CStringFeatures<char>(list, RAWBYTE);
	CStreamingHashedDocDotFeatures* feats = new CStreamingHashedDocDotFeatures(doc_collection,
			tokenizer, 5);

	index_t i = 0;
	feats->start_parser();
	while (feats->get_next_example())
	{
		SGSparseVector<float64_t> example = feats->get_vector();

		SGVector<char> tmp(list.strings[i].string, list.strings[i].slen, false);
		tmp.vector = list.strings[i].string;
		SGSparseVector<float64_t> converted_doc = converter->apply(tmp);

		EXPECT_EQ(example.num_feat_entries, converted_doc.num_feat_entries);

		for (index_t j=0; j<example.num_feat_entries; j++)
		{
			EXPECT_EQ(example.features[j].feat_index, converted_doc.features[j].feat_index);
			EXPECT_EQ(example.features[j].entry, converted_doc.features[j].entry);
		}
		feats->release_example();
		i++;
	}
	feats->end_parser();
	SG_UNREF(feats);
	SG_UNREF(doc_collection);
	SG_UNREF(converter);
}

TEST(StreamingHashedDocFeaturesTest, dot_tests)
{
	const char* doc_1 = "You're never too old to rock and roll, if you're too young to die";
	const char* doc_2 = "Give me some rope, tie me to dream, give me the hope to run out of steam";
	const char* doc_3 = "Thank you Jack Daniels, Old Number Seven, Tennessee Whiskey got me drinking in heaven";

	SGString<char> string_1(65);
	for (index_t i=0; i<65; i++)
		string_1.string[i] = doc_1[i];

	SGString<char> string_2(72);
	for (index_t i=0; i<72; i++)
		string_2.string[i] = doc_2[i];

	SGString<char> string_3(85);
	for (index_t i=0; i<85; i++)
		string_3.string[i] = doc_3[i];

	SGStringList<char> list(3,85);
	list.strings[0] = string_1;
	list.strings[1] = string_2;
	list.strings[2] = string_3;

	CDelimiterTokenizer* tokenizer = new CDelimiterTokenizer();
	tokenizer->delimiters[' '] = 1;
	tokenizer->delimiters['\''] = 1;
	tokenizer->delimiters[','] = 1;

	CHashedDocConverter* converter = new CHashedDocConverter(tokenizer, 5, false);
	CStringFeatures<char>* doc_collection = new CStringFeatures<char>(list, RAWBYTE);
	CStreamingHashedDocDotFeatures* feats = new CStreamingHashedDocDotFeatures(doc_collection,
			tokenizer, 5);
	feats->start_parser();

	SGVector<float32_t> dense_vec(32);
	for (index_t j=0; j<32; j++)
		dense_vec[j] = CMath::random();

	index_t i = 0;
	while (feats->get_next_example())
	{
		/** Dense dot test */
		SGVector<char> tmp(list.strings[i].string, list.strings[i].slen, false);
		tmp.vector = list.strings[i].string;
		SGSparseVector<float64_t> converted_doc = converter->apply(tmp);

		float32_t tmp_res = 0;
		for (index_t j=0; j<converted_doc.num_feat_entries; j++)
			tmp_res += dense_vec[converted_doc.features[j].feat_index] * converted_doc.features[j].entry;

		EXPECT_EQ(tmp_res, feats->dense_dot(dense_vec.vector, dense_vec.vlen));

		/** Add to dense test */
		SGSparseVector<float64_t> example = feats->get_vector();
		SGVector<float32_t> dense_vec2(32);
		for (index_t j=0; j<32; j++)
			dense_vec2[j] = dense_vec[j];

		feats->add_to_dense_vec(1, dense_vec2.vector, dense_vec2.vlen);
		index_t sparse_idx = 0;
		for (index_t j=0; j<32; j++)
		{
			if ( (sparse_idx < example.num_feat_entries) &&
					(example.features[sparse_idx].feat_index == j) )
			{
				EXPECT_NEAR(dense_vec2[j], dense_vec[j] + example.features[sparse_idx].entry, 1e-10);
				sparse_idx++;
			}
			else
				EXPECT_NEAR(dense_vec2[j], dense_vec[j], 1e-10);
		}

		feats->release_example();
		i++;
	}

	feats->end_parser();
	SG_UNREF(feats);
	SG_UNREF(doc_collection);
	SG_UNREF(converter);
}
<|endoftext|>


<commit_before>//____________________________________________________
void AliTRDmakeRecoParamFirstPhysics()
{
  AliCDBMetaData *metaData= new AliCDBMetaData();
  metaData->SetObjectClassName("TObjArray");
  metaData->SetResponsible("Alexandru Bercuci");
  metaData->SetBeamPeriod(1);
  metaData->SetAliRootVersion("05-21-01"); //root version
  metaData->SetComment("First Physics reconstruction parameters for low, high and cosmic runs");

  AliCDBId id("TRD/Calib/RecoParam", 95352, AliCDBRunRange::Infinity());
  AliCDBManager *man = AliCDBManager::Instance();
  AliCDBStorage *gStorLoc = man->GetStorage("local://$ALICE_ROOT/OCDB");
  if (!gStorLoc) {
    return;
  }
  gStorLoc->Put(CreateRecoParamObject(), id, metaData);

  return;
}

//____________________________________________________
TObjArray* CreateRecoParamObject()
{
  TObjArray *recos = new TObjArray(5);

  AliTRDrecoParam *rec = 0x0;
  Double_t cov[]={1., 1., 0., 0., 0.};
  recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
  rec->SetEventSpecie(AliRecoParam::kLowMult);
  rec->SetNameTitle("Default", "TRD Default Reco Param");
  rec->SetNameTitle("LOW", "TRD Low Flux Reco Param");
  rec->SetRawStreamVersion("DEFAULT");
  rec->SetXenon();
  rec->SetVertexConstrained();
  rec->SetSysCovMatrix(cov);
  rec->SetChi2YSlope(0.11853);
  rec->SetChi2ZSlope(0.04527);
  rec->SetChi2YCut(1.);
  rec->SetPhiSlope(10.); //3.17954;
  rec->SetMaxTheta(2.1445);
  rec->SetMaxPhi(2.7475);
  rec->SetNMeanClusters(12.89);
  rec->SetNSigmaClusters(2.095);
  rec->SetRoadzMultiplicator(3.);
  rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);
  rec->SetAsDefault();

  recos->AddLast(rec = AliTRDrecoParam::GetHighFluxParam());
  rec->SetEventSpecie(AliRecoParam::kHighMult);
  rec->SetNameTitle("HIGH", "TRD High Flux Reco Param");
  rec->SetRawStreamVersion("DEFAULT");
  rec->SetXenon();
  rec->SetVertexConstrained();
  rec->SetSysCovMatrix(cov);
  rec->SetChi2YSlope(0.11853);
  rec->SetChi2ZSlope(0.04527);
  rec->SetChi2YCut(1.);
  rec->SetPhiSlope(10.); //3.17954;
  rec->SetMaxTheta(2.1445);
  rec->SetMaxPhi(2.7475);
  rec->SetNMeanClusters(12.89);
  rec->SetNSigmaClusters(2.095);

  recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
  rec->SetEventSpecie(AliRecoParam::kCosmic);
  rec->SetNameTitle("COSMIC", "TRD Cosmic Reco Param");
  rec->SetRawStreamVersion("DEFAULT");
  rec->SetXenon();

  recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
  rec->SetEventSpecie(AliRecoParam::kCalib);
  rec->SetNameTitle("CALIBRATION", "TRD Calibration Reco Param");
  rec->SetRawStreamVersion("DEFAULT");
  rec->SetXenon();

//  recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
//  rec->SetNameTitle("HLT", "TRD HLT Reco Param");
//  rec->SetChi2Y(.1);
//  rec->SetChi2Z(5.);

  return recos;
}
<commit_msg>Follow PB requested that, for the time being, TRD info is not used to update tracks. (Markus Alex)<commit_after>//____________________________________________________
void AliTRDmakeRecoParamFirstPhysics()
{
  AliCDBMetaData *metaData= new AliCDBMetaData();
  metaData->SetObjectClassName("TObjArray");
  metaData->SetResponsible("Alexandru Bercuci / Markus Fasel");
  metaData->SetBeamPeriod(1);
  metaData->SetAliRootVersion("05-27-06b"); //root version
  metaData->SetComment(
  "Reconstruction parameters for low, high, cosmic and calibration runs.\n"
  "Issue date 24th Feb 2011. TRD not updating tracks.");
  AliCDBId id("TRD/Calib/RecoParam", 95352, AliCDBRunRange::Infinity());
  AliCDBManager *man = AliCDBManager::Instance();
  AliCDBStorage *gStorLoc = man->GetStorage("local://$ALICE_ROOT/OCDB");
  if (!gStorLoc) {
    return;
  }
  gStorLoc->Put(CreateRecoParamObject(), id, metaData);

  return;
}

//____________________________________________________
TObjArray* CreateRecoParamObject()
{
  TObjArray *recos = new TObjArray(5);

  AliTRDrecoParam *rec = 0x0;
  Double_t cov[]={1., 1., 0., 0., 0.};
  recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
  rec->SetEventSpecie(AliRecoParam::kLowMult);
  rec->SetNameTitle("Default", "TRD Default Reco Param");
  rec->SetNameTitle("LOW", "TRD Low Flux Reco Param");
  rec->SetRawStreamVersion("DEFAULT");
  rec->SetXenon();
  rec->SetVertexConstrained();
  rec->SetSysCovMatrix(cov);
  rec->SetChi2YSlope(0.11853);
  rec->SetChi2ZSlope(0.04527);
  rec->SetChi2YCut(1.);
  rec->SetPhiSlope(10.); //3.17954;
  rec->SetMaxTheta(2.1445);
  rec->SetMaxPhi(2.7475);
  rec->SetNMeanClusters(12.89);
  rec->SetNSigmaClusters(2.095);
  rec->SetRoadzMultiplicator(3.);
  rec->SetPtThreshold(100.);
  rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);
  rec->SetAsDefault();

  recos->AddLast(rec = AliTRDrecoParam::GetHighFluxParam());
  rec->SetEventSpecie(AliRecoParam::kHighMult);
  rec->SetNameTitle("HIGH", "TRD High Flux Reco Param");
  rec->SetRawStreamVersion("DEFAULT");
  rec->SetXenon();
  rec->SetVertexConstrained();
  rec->SetSysCovMatrix(cov);
  rec->SetChi2YSlope(0.11853);
  rec->SetChi2ZSlope(0.04527);
  rec->SetChi2YCut(1.);
  rec->SetPhiSlope(10.); //3.17954;
  rec->SetMaxTheta(2.1445);
  rec->SetMaxPhi(2.7475);
  rec->SetNMeanClusters(12.89);
  rec->SetNSigmaClusters(2.095);
  rec->SetPtThreshold(100.);
  rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);

  recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
  rec->SetEventSpecie(AliRecoParam::kCosmic);
  rec->SetNameTitle("COSMIC", "TRD Cosmic Reco Param");
  rec->SetRawStreamVersion("DEFAULT");
  rec->SetXenon();
//  rec->SetPtThreshold(100.);
  rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);

  recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
  rec->SetEventSpecie(AliRecoParam::kCalib);
  rec->SetNameTitle("CALIBRATION", "TRD Calibration Reco Param");
  rec->SetRawStreamVersion("DEFAULT");
  rec->SetXenon();
//  rec->SetPtThreshold(100.);
  rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);

  return recos;
}
<|endoftext|>


<commit_before>#include "PubSubClient.h"
#include "ShimClient.h"
#include "Buffer.h"
#include "BDDTest.h"
#include "trace.h"

byte server[] = { 172, 16, 0, 2 };

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
}

int test_subscribe_no_qos() {
    IT("subscribe without qos defaults to 0");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    byte subscribe[] = { 0x82,0xa,0x0,0x2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x0 };
    shimClient.expect(subscribe,12);
    byte suback[] = { 0x90,0x3,0x0,0x2,0x0 };
    shimClient.respond(suback,5);

    rc = client.subscribe((char*)"topic");
    IS_TRUE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_subscribe_qos_1() {
    IT("subscribes qos 1");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    byte subscribe[] = { 0x82,0xa,0x0,0x2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x1 };
    shimClient.expect(subscribe,12);
    byte suback[] = { 0x90,0x3,0x0,0x2,0x1 };
    shimClient.respond(suback,5);

    rc = client.subscribe((char*)"topic",1);
    IS_TRUE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_subscribe_not_connected() {
    IT("subscribe fails when not connected");
    ShimClient shimClient;

    PubSubClient client(server, 1883, callback, shimClient);

    int rc = client.subscribe((char*)"topic");
    IS_FALSE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_subscribe_invalid_qos() {
    IT("subscribe fails with invalid qos values");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    rc = client.subscribe((char*)"topic",2);
    IS_FALSE(rc);
    rc = client.subscribe((char*)"topic",254);
    IS_FALSE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_subscribe_too_long() {
    IT("subscribe fails with too long topic");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    // max length should be allowed
    //                            0        1         2         3         4         5         6         7         8         9         0         1         2
    rc = client.subscribe((char*)"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789");
    IS_TRUE(rc);

    //                            0        1         2         3         4         5         6         7         8         9         0         1         2
    rc = client.subscribe((char*)"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");
    IS_FALSE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_unsubscribe() {
    IT("unsubscribes");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    byte unsubscribe[] = { 0xA2,0x9,0x0,0x2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63 };
    shimClient.expect(unsubscribe,12);
    byte unsuback[] = { 0xB0,0x2,0x0,0x2 };
    shimClient.respond(unsuback,4);

    rc = client.unsubscribe((char*)"topic");
    IS_TRUE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_unsubscribe_not_connected() {
    IT("unsubscribe fails when not connected");
    ShimClient shimClient;

    PubSubClient client(server, 1883, callback, shimClient);

    int rc = client.unsubscribe((char*)"topic");
    IS_FALSE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int main()
{
    SUITE("Subscribe");
    test_subscribe_no_qos();
    test_subscribe_qos_1();
    test_subscribe_not_connected();
    test_subscribe_invalid_qos();
    test_subscribe_too_long();
    test_unsubscribe();
    test_unsubscribe_not_connected();
    FINISH
}
<commit_msg>Update subscribe_spec.cpp<commit_after>#include "PubSubClient.h"
#include "ShimClient.h"
#include "Buffer.h"
#include "BDDTest.h"
#include "trace.h"

byte server[] = { 172, 16, 0, 2 };

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
}

int test_subscribe_no_qos() {
    IT("subscribe without qos defaults to 0");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    byte subscribe[] = { 0x82,0xa,0x0,0x2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x0 };
    shimClient.expect(subscribe,12);
    byte suback[] = { 0x90,0x3,0x0,0x2,0x0 };
    shimClient.respond(suback,5);

    rc = client.subscribe((char*)"topic");
    IS_TRUE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_subscribe_qos_1() {
    IT("subscribes qos 1");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    byte subscribe[] = { 0x82,0xa,0x0,0x2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x1 };
    shimClient.expect(subscribe,12);
    byte suback[] = { 0x90,0x3,0x0,0x2,0x1 };
    shimClient.respond(suback,5);

    rc = client.subscribe((char*)"topic",1);
    IS_TRUE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_subscribe_not_connected() {
    IT("subscribe fails when not connected");
    ShimClient shimClient;

    PubSubClient client(server, 1883, callback, shimClient);

    int rc = client.subscribe((char*)"topic");
    IS_FALSE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_subscribe_invalid_qos() {
    IT("subscribe fails with invalid qos values");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    rc = client.subscribe((char*)"topic",2);
    IS_FALSE(rc);
    rc = client.subscribe((char*)"topic",254);
    IS_FALSE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_subscribe_too_long() {
    IT("subscribe fails with too long topic");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    // max length should be allowed
    //                            0        1         2         3         4         5         6         7         8         9         0         1         2
    rc = client.subscribe((char*)"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678912345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567891234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678912345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789");
    IS_TRUE(rc);

    //                            0        1         2         3         4         5         6         7         8         9         0         1         2
    rc = client.subscribe((char*)"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678912345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567891234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678912345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789");
    IS_FALSE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_unsubscribe() {
    IT("unsubscribes");
    ShimClient shimClient;
    shimClient.setAllowConnect(true);

    byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
    shimClient.respond(connack,4);

    PubSubClient client(server, 1883, callback, shimClient);
    int rc = client.connect((char*)"client_test1");
    IS_TRUE(rc);

    byte unsubscribe[] = { 0xA2,0x9,0x0,0x2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63 };
    shimClient.expect(unsubscribe,12);
    byte unsuback[] = { 0xB0,0x2,0x0,0x2 };
    shimClient.respond(unsuback,4);

    rc = client.unsubscribe((char*)"topic");
    IS_TRUE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int test_unsubscribe_not_connected() {
    IT("unsubscribe fails when not connected");
    ShimClient shimClient;

    PubSubClient client(server, 1883, callback, shimClient);

    int rc = client.unsubscribe((char*)"topic");
    IS_FALSE(rc);

    IS_FALSE(shimClient.error());

    END_IT
}

int main()
{
    SUITE("Subscribe");
    test_subscribe_no_qos();
    test_subscribe_qos_1();
    test_subscribe_not_connected();
    test_subscribe_invalid_qos();
    test_subscribe_too_long();
    test_unsubscribe();
    test_unsubscribe_not_connected();
    FINISH
}
<|endoftext|>


<commit_before>#ifndef STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP
#define STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP

#include <stan/math/prim/mat.hpp>
#include <algorithm>
#include <vector>

namespace stan {
  namespace analyze {

    /**
     * Returns the effective sample size for the specified parameter
     * across all kept samples.
     *
     * See more details in Stan reference manual section "Effective
     * Sample Size". http://mc-stan.org/users/documentation
     *
     * Current implementation assumes chains are all of equal size and
     * draws are stored in contiguous blocks of memory.
     *
     * @param std::vector stores pointers to arrays of chains
     * @param std::vector stores sizes of chains
     * @return effective sample size for the specified parameter
     */
    double compute_effective_sample_size(std::vector<const double*> draws,
                                         std::vector<size_t> sizes) {
      size_t num_chains = sizes.size();

      // need to generalize to each jagged draws per chain
      size_t num_draws = sizes[0];
      for (size_t chain = 1; chain < num_chains; ++chain) {
        num_draws = std::min(num_draws, sizes[chain]);
      }

      Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains);
      Eigen::VectorXd chain_mean(num_chains);
      Eigen::VectorXd chain_var(num_chains);
      for (size_t chain = 0; chain < num_chains; ++chain) {
        Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>>
          draw(draws[chain], sizes[chain]);
        math::autocovariance<double>(draw, acov(chain));
        chain_mean(chain) = draw.mean();
        chain_var(chain) = acov(chain)(0) * num_draws / (num_draws - 1);
      }

      double mean_var = chain_var.mean();
      double var_plus = mean_var * (num_draws - 1) / num_draws;
      if (num_chains > 1)
        var_plus += math::variance(chain_mean);
      Eigen::VectorXd rho_hat_s(num_draws);
      rho_hat_s.setZero();
      Eigen::VectorXd acov_s(num_chains);
      for (size_t chain = 0; chain < num_chains; ++chain)
        acov_s(chain) = acov(chain)(1);
      double rho_hat_even = 1;
      double rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;
      rho_hat_s(1) = rho_hat_odd;
      // Geyer's initial positive sequence
      size_t max_s = 1;
      for (size_t s = 1;
           (s < (num_draws - 2) && (rho_hat_even + rho_hat_odd) >= 0);
           s += 2) {
        for (size_t chain = 0; chain < num_chains; ++chain)
          acov_s(chain) = acov(chain)(s + 1);
        rho_hat_even = 1 - (mean_var - acov_s.mean()) / var_plus;
        for (size_t chain = 0; chain < num_chains; ++chain)
          acov_s(chain) = acov(chain)(s + 2);
        rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;
        if ((rho_hat_even + rho_hat_odd) >= 0) {
          rho_hat_s(s + 1) = rho_hat_even;
          rho_hat_s(s + 2) = rho_hat_odd;
        }
        max_s = s + 2;
      }
      // Geyer's initial monotone sequence
      for (size_t s = 3; s <= max_s - 2; s += 2) {
        if (rho_hat_s(s + 1) + rho_hat_s(s + 2) >
            rho_hat_s(s - 1) + rho_hat_s(s)) {
          rho_hat_s(s + 1) = (rho_hat_s(s - 1) + rho_hat_s(s)) / 2;
          rho_hat_s(s + 2) = rho_hat_s(s + 1);
        }
      }

      return num_chains * num_draws / (1 + 2 * rho_hat_s.sum());
    }

    double compute_effective_sample_size(std::vector<const double*> draws,
                                         size_t size) {
      size_t num_chains = draws.size();
      std::vector<size_t> sizes(num_chains, size);
      return compute_effective_sample_size(draws, sizes);
    }
  }
}

#endif
<commit_msg>replace size_t with in, save when warned about comparison issues.<commit_after>#ifndef STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP
#define STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP

#include <stan/math/prim/mat.hpp>
#include <algorithm>
#include <vector>

namespace stan {
  namespace analyze {

    /**
     * Returns the effective sample size for the specified parameter
     * across all kept samples.
     *
     * See more details in Stan reference manual section "Effective
     * Sample Size". http://mc-stan.org/users/documentation
     *
     * Current implementation assumes chains are all of equal size and
     * draws are stored in contiguous blocks of memory.
     *
     * @param std::vector stores pointers to arrays of chains
     * @param std::vector stores sizes of chains
     * @return effective sample size for the specified parameter
     */
    double compute_effective_sample_size(std::vector<const double*> draws,
                                         std::vector<size_t> sizes) {
      int num_chains = sizes.size();

      // need to generalize to each jagged draws per chain
      size_t num_draws = sizes[0];
      for (int chain = 1; chain < num_chains; ++chain) {
        num_draws = std::min(num_draws, sizes[chain]);
      }

      Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains);
      Eigen::VectorXd chain_mean(num_chains);
      Eigen::VectorXd chain_var(num_chains);
      for (int chain = 0; chain < num_chains; ++chain) {
        Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>>
          draw(draws[chain], sizes[chain]);
        math::autocovariance<double>(draw, acov(chain));
        chain_mean(chain) = draw.mean();
        chain_var(chain) = acov(chain)(0) * num_draws / (num_draws - 1);
      }

      double mean_var = chain_var.mean();
      double var_plus = mean_var * (num_draws - 1) / num_draws;
      if (num_chains > 1)
        var_plus += math::variance(chain_mean);
      Eigen::VectorXd rho_hat_s(num_draws);
      rho_hat_s.setZero();
      Eigen::VectorXd acov_s(num_chains);
      for (int chain = 0; chain < num_chains; ++chain)
        acov_s(chain) = acov(chain)(1);
      double rho_hat_even = 1;
      double rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;
      rho_hat_s(1) = rho_hat_odd;
      // Geyer's initial positive sequence
      int max_s = 1;
      for (size_t s = 1;
           (s < (num_draws - 2) && (rho_hat_even + rho_hat_odd) >= 0);
           s += 2) {
        for (int chain = 0; chain < num_chains; ++chain)
          acov_s(chain) = acov(chain)(s + 1);
        rho_hat_even = 1 - (mean_var - acov_s.mean()) / var_plus;
        for (int chain = 0; chain < num_chains; ++chain)
          acov_s(chain) = acov(chain)(s + 2);
        rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;
        if ((rho_hat_even + rho_hat_odd) >= 0) {
          rho_hat_s(s + 1) = rho_hat_even;
          rho_hat_s(s + 2) = rho_hat_odd;
        }
        max_s = s + 2;
      }
      // Geyer's initial monotone sequence
      for (int s = 3; s <= max_s - 2; s += 2) {
        if (rho_hat_s(s + 1) + rho_hat_s(s + 2) >
            rho_hat_s(s - 1) + rho_hat_s(s)) {
          rho_hat_s(s + 1) = (rho_hat_s(s - 1) + rho_hat_s(s)) / 2;
          rho_hat_s(s + 2) = rho_hat_s(s + 1);
        }
      }

      return num_chains * num_draws / (1 + 2 * rho_hat_s.sum());
    }

    double compute_effective_sample_size(std::vector<const double*> draws,
                                         size_t size) {
      int num_chains = draws.size();
      std::vector<size_t> sizes(num_chains, size);
      return compute_effective_sample_size(draws, sizes);
    }
  }
}

#endif
<|endoftext|>


<commit_before>//
// Created by Sebastian on 24.05.2015.
//

#include "Conversions.h"
#include "Crypto.h"

#include <stdexcept>
#include <iostream>
#include <algorithm>

ByteArray Conversions::fromHex(const std::string &hex)
{
    ByteArray ret(hex.size() / 2 + (hex.size() % 2));
    for (size_t i = 0; i < hex.size(); i += 1)
    {
        char charVal;
        char charCode = (char) tolower(hex[i]);
        if (charCode >= '0' && charCode <= '9')
        {
            charVal = charCode - '0';
        }
        else if (charCode >= 'a' && charCode <= 'f')
        {
            charVal = (char) (charCode - 'a' + 10);
        }
        else
        {
            throw std::runtime_error("A character in the given string wasn't HEX.");
        }
        if (i % 2 == 1)
        {
            ret[i / 2] += charVal;
        }
        else
        {
            ret[i / 2] += 16 * charVal;
        }
    }

    return ret;
}

std::string Conversions::toHex(const ByteArray &bytes)
{
    std::string base16 = "0123456789abcdef";
    std::string ret;

    for (ByteArray::const_iterator it = bytes.begin(); it != bytes.end(); it++)
    {
        ret.append(1, base16[(*it) / 16]);
        ret.append(1, base16[(*it) % 16]);
    }

    return ret;
}

ByteArray Conversions::fromBase58(const std::string &base58)
{
    ByteArray base256(base58.size() * 733 / 1000 + 1);

    std::string::const_iterator base58It = base58.begin();
    int zeroes = 0;

    while (base58It != base58.end() && *base58It == '1')
    {
        zeroes++;
        base58It++;
    }

    unsigned int carry;
    for (; base58It != base58.end(); base58It++)
    {
        if ((*base58It) >= '1' && (*base58It) <= '9')
        {
            carry = (unsigned int) ((*base58It) - '1');
        }
        else if ((*base58It) >= 'A' && (*base58It) <= 'H')
        {
            carry = (unsigned int) ((*base58It) - 'A' + 9);
        }
        else if ((*base58It) >= 'J' && (*base58It) <= 'N')
        {
            carry = (unsigned int) ((*base58It) - 'J' + 17);
        }
        else if ((*base58It) >= 'P' && (*base58It) <= 'Z')
        {
            carry = (unsigned int) ((*base58It) - 'P' + 22);
        }
        else if ((*base58It) >= 'a' && (*base58It) <= 'k')
        {
            carry = (unsigned int) ((*base58It) - 'a' + 33);
        }
        else if ((*base58It) >= 'm' && (*base58It) <= 'z')
        {
            carry = (unsigned int) ((*base58It) - 'm' + 44);
        }
        else
        {
            throw std::runtime_error("One characte in the string isn't BASE58");
        }

        for (ByteArray::reverse_iterator retIt = base256.rbegin(); retIt != base256.rend(); retIt++)
        {
            carry += 58 * (*retIt);
            *retIt = (Byte) (carry % 256);
            carry /= 256;
        }
    }

    ByteArray ret;
    ByteArray::iterator base256It = base256.begin();

    while (base256It != base256.end() && *base256It == 0)
    {
        base256It++;
    }

    ret.assign(zeroes, 0x00);
    ret.insert(ret.end(), base256It, base256.end());

    return ret;
}

ByteArray Conversions::fromBase58Check(const std::string &base58, Byte version)
{
    ByteArray ret = fromBase58(base58);

    if (ret[0] != version)
    {
        ret.erase(ret.begin() + 1, ret.end());
        throw std::runtime_error("Wrong version byte! (0x" + Conversions::toHex(ret) + ")");
    }

    if (ret.size() <= 4)
    {
        throw  std::runtime_error("data too short (no checksum found)");
    }

    ByteArray checksum = ByteArray(4);
    for (ByteArray::size_type i = 0; i < 4; i += 1)
    {
        checksum[3 - i] = ret.back();
        ret.pop_back();
    }

    ByteArray hash = Crypto::sha256(Crypto::sha256(ret));

    ret.erase(ret.begin(), ret.begin() + 1);

    for (ByteArray::size_type i = 0; i < 4; i += 1)
    {
        if (hash[i] != checksum[i])
        {
            throw std::runtime_error("Checksum not valid, data corrupted?");
        }
    }

    return ret;
}

std::string Conversions::toBase58(const ByteArray &data)
{
    std::string base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

    ByteArray encoded(data.size() * 138 / 100 + 1);

    ByteArray::const_iterator dataIt = data.begin();
    unsigned int zeroes = 0;

    while (dataIt != data.end() && *dataIt == 0)
    {
        zeroes++;
        dataIt++;
    }

    for (; dataIt != data.end(); dataIt++)
    {
        int carry = *dataIt;

        for (ByteArray::reverse_iterator encodedIt = encoded.rbegin(); encodedIt != encoded.rend(); encodedIt++)
        {
            carry += 256 * (*encodedIt);
            *encodedIt = (Byte) (carry % 58);
            carry /= 58;
        }
    }

    ByteArray::iterator encodedIt = encoded.begin();

    while (encodedIt != encoded.end() && *encodedIt == 0)
    {
        encodedIt++;
    }

    std::string ret;
    ret.assign(zeroes, '1');

    while (encodedIt != encoded.end())
    {
        ret += base58[*(encodedIt++)];
    }

    return ret;
}

std::string Conversions::toBase58Check(ByteArray data, Byte version)
{
    data.insert(data.begin(), version);

    ByteArray hash = Crypto::sha256(Crypto::sha256(data));
    data.insert(data.end(), hash.begin(), hash.begin() + 4);

    return toBase58(data);
}

ByteArray Conversions::fromUInt32(uint32_t num)
{
    ByteArray ret(4);

    for (unsigned int bNum = 0; bNum < 4; bNum++)
    {
        ret[3 - bNum] = (Byte) (num / (1 << (8 * (3 - bNum))));
        num %= (1 << (8 * (3 - bNum)));
    }

    return ret;
}

ByteArray Conversions::fromUInt64(uint64_t num)
{
    ByteArray ret(8);

    for (unsigned int bNum = 0; bNum < 8; bNum++)
    {
        ret[7 - bNum] = (Byte) (num / (1 << (8 * (7 - bNum))));
        num %= (1 << (8 * (7 - bNum)));
    }

    return ret;
}

ByteArray Conversions::fromVarInt(uint64_t num)
{
    size_t len;
    Byte firstByte;

    if (num < 0xfd)
    {
        len = 0;
        firstByte = (Byte) num;
    }
    else if (num <= 0xffff)
    {
        len = 2;
        firstByte = 0xfd;
    }
    else if (num <= 0xffffffff)
    {
        len = 4;
        firstByte = 0xfe;
    }
    else
    {
        len = 8;
        firstByte = 0xff;
    }

    ByteArray ret(len + 1);
    ret[0] = firstByte;

    for (int bytePos = len; bytePos >= 1; --bytePos)
    {
        ret[bytePos] = (Byte) (num / (1 << (8 * (bytePos - 1))));
        num %= (1 << (8 * (bytePos - 1)));
    }

    return ret;
}

ByteArray Conversions::reverse(ByteArray inp)
{
    std::reverse(inp.begin(), inp.end());
    return inp;
}
<commit_msg>fixes for fromUint32/64<commit_after>//
// Created by Sebastian on 24.05.2015.
//

#include "Conversions.h"
#include "Crypto.h"

#include <stdexcept>
#include <iostream>
#include <algorithm>

ByteArray Conversions::fromHex(const std::string &hex)
{
    ByteArray ret(hex.size() / 2 + (hex.size() % 2));
    for (size_t i = 0; i < hex.size(); i += 1)
    {
        char charVal;
        char charCode = (char) tolower(hex[i]);
        if (charCode >= '0' && charCode <= '9')
        {
            charVal = charCode - '0';
        }
        else if (charCode >= 'a' && charCode <= 'f')
        {
            charVal = (char) (charCode - 'a' + 10);
        }
        else
        {
            throw std::runtime_error("A character in the given string wasn't HEX.");
        }
        if (i % 2 == 1)
        {
            ret[i / 2] += charVal;
        }
        else
        {
            ret[i / 2] += 16 * charVal;
        }
    }

    return ret;
}

std::string Conversions::toHex(const ByteArray &bytes)
{
    std::string base16 = "0123456789abcdef";
    std::string ret;

    for (ByteArray::const_iterator it = bytes.begin(); it != bytes.end(); it++)
    {
        ret.append(1, base16[(*it) / 16]);
        ret.append(1, base16[(*it) % 16]);
    }

    return ret;
}

ByteArray Conversions::fromBase58(const std::string &base58)
{
    ByteArray base256(base58.size() * 733 / 1000 + 1);

    std::string::const_iterator base58It = base58.begin();
    int zeroes = 0;

    while (base58It != base58.end() && *base58It == '1')
    {
        zeroes++;
        base58It++;
    }

    unsigned int carry;
    for (; base58It != base58.end(); base58It++)
    {
        if ((*base58It) >= '1' && (*base58It) <= '9')
        {
            carry = (unsigned int) ((*base58It) - '1');
        }
        else if ((*base58It) >= 'A' && (*base58It) <= 'H')
        {
            carry = (unsigned int) ((*base58It) - 'A' + 9);
        }
        else if ((*base58It) >= 'J' && (*base58It) <= 'N')
        {
            carry = (unsigned int) ((*base58It) - 'J' + 17);
        }
        else if ((*base58It) >= 'P' && (*base58It) <= 'Z')
        {
            carry = (unsigned int) ((*base58It) - 'P' + 22);
        }
        else if ((*base58It) >= 'a' && (*base58It) <= 'k')
        {
            carry = (unsigned int) ((*base58It) - 'a' + 33);
        }
        else if ((*base58It) >= 'm' && (*base58It) <= 'z')
        {
            carry = (unsigned int) ((*base58It) - 'm' + 44);
        }
        else
        {
            throw std::runtime_error("One characte in the string isn't BASE58");
        }

        for (ByteArray::reverse_iterator retIt = base256.rbegin(); retIt != base256.rend(); retIt++)
        {
            carry += 58 * (*retIt);
            *retIt = (Byte) (carry % 256);
            carry /= 256;
        }
    }

    ByteArray ret;
    ByteArray::iterator base256It = base256.begin();

    while (base256It != base256.end() && *base256It == 0)
    {
        base256It++;
    }

    ret.assign(zeroes, 0x00);
    ret.insert(ret.end(), base256It, base256.end());

    return ret;
}

ByteArray Conversions::fromBase58Check(const std::string &base58, Byte version)
{
    ByteArray ret = fromBase58(base58);

    if (ret[0] != version)
    {
        ret.erase(ret.begin() + 1, ret.end());
        throw std::runtime_error("Wrong version byte! (0x" + Conversions::toHex(ret) + ")");
    }

    if (ret.size() <= 4)
    {
        throw  std::runtime_error("data too short (no checksum found)");
    }

    ByteArray checksum = ByteArray(4);
    for (ByteArray::size_type i = 0; i < 4; i += 1)
    {
        checksum[3 - i] = ret.back();
        ret.pop_back();
    }

    ByteArray hash = Crypto::sha256(Crypto::sha256(ret));

    ret.erase(ret.begin(), ret.begin() + 1);

    for (ByteArray::size_type i = 0; i < 4; i += 1)
    {
        if (hash[i] != checksum[i])
        {
            throw std::runtime_error("Checksum not valid, data corrupted?");
        }
    }

    return ret;
}

std::string Conversions::toBase58(const ByteArray &data)
{
    std::string base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

    ByteArray encoded(data.size() * 138 / 100 + 1);

    ByteArray::const_iterator dataIt = data.begin();
    unsigned int zeroes = 0;

    while (dataIt != data.end() && *dataIt == 0)
    {
        zeroes++;
        dataIt++;
    }

    for (; dataIt != data.end(); dataIt++)
    {
        int carry = *dataIt;

        for (ByteArray::reverse_iterator encodedIt = encoded.rbegin(); encodedIt != encoded.rend(); encodedIt++)
        {
            carry += 256 * (*encodedIt);
            *encodedIt = (Byte) (carry % 58);
            carry /= 58;
        }
    }

    ByteArray::iterator encodedIt = encoded.begin();

    while (encodedIt != encoded.end() && *encodedIt == 0)
    {
        encodedIt++;
    }

    std::string ret;
    ret.assign(zeroes, '1');

    while (encodedIt != encoded.end())
    {
        ret += base58[*(encodedIt++)];
    }

    return ret;
}

std::string Conversions::toBase58Check(ByteArray data, Byte version)
{
    data.insert(data.begin(), version);

    ByteArray hash = Crypto::sha256(Crypto::sha256(data));
    data.insert(data.end(), hash.begin(), hash.begin() + 4);

    return toBase58(data);
}

ByteArray Conversions::fromUInt32(uint32_t num)
{
    ByteArray ret(4);

    for (unsigned int bNum = 0; bNum < 4; bNum++)
    {
        ret[3 - bNum] = (Byte) (num / (((uint32_t) 1) << (8 * (3 - bNum))));
        num %= (((uint32_t) 1) << (8 * (3 - bNum)));
    }

    return ret;
}

ByteArray Conversions::fromUInt64(uint64_t num)
{
    ByteArray ret(8);

    for (unsigned int bNum = 0; bNum < 8; bNum++)
    {
        ret[7 - bNum] = (Byte) (num / (((uint64_t) 1) << (8 * (7 - bNum))));
        num %= (((uint64_t) 1) << (8 * (7 - bNum)));
    }

    return ret;
}

ByteArray Conversions::fromVarInt(uint64_t num)
{
    size_t len;
    Byte firstByte;

    if (num < 0xfd)
    {
        len = 0;
        firstByte = (Byte) num;
    }
    else if (num <= 0xffff)
    {
        len = 2;
        firstByte = 0xfd;
    }
    else if (num <= 0xffffffff)
    {
        len = 4;
        firstByte = 0xfe;
    }
    else
    {
        len = 8;
        firstByte = 0xff;
    }

    ByteArray ret(len + 1);
    ret[0] = firstByte;

    for (int bytePos = len; bytePos >= 1; --bytePos)
    {
        ret[bytePos] = (Byte) (num / (1 << (8 * (bytePos - 1))));
        num %= (1 << (8 * (bytePos - 1)));
    }

    return ret;
}

ByteArray Conversions::reverse(ByteArray inp)
{
    std::reverse(inp.begin(), inp.end());
    return inp;
}
<|endoftext|>