#include "Query.hh"

QString generateQuery(QString const &base, QString const &attribute, QString const &value)
{
    QString condition = QString("@%1=\"%2\"").arg(attribute).arg(value);

    return generateQuery(base, condition);
}

QString generateQuery(QString const &base, QString const &condition)
{
    int subSelectionPos = base.lastIndexOf('/');

    if (!subSelectionPos)
        return QString();

    int closingBracketPos = base.mid(subSelectionPos).lastIndexOf(']');

    if (closingBracketPos == -1)
        return QString("%1[%2]").arg(base).arg(condition);
    else
        return QString("%1 and %2%3").arg(
            base.left(subSelectionPos + closingBracketPos),
            condition,
            base.mid(subSelectionPos + closingBracketPos));
}

#include <QtDebug>

#include "Query.hh"

QString generateQuery(QString const &base, QString const &attribute, QString const &value)
{
    QString condition = QString("@%1=\"%2\"").arg(attribute).arg(value);

    return generateQuery(base, condition);
}

QString generateQuery(QString const &base, QString const &condition)
{
    int subSelectionPos = base.lastIndexOf('/');

    if (!subSelectionPos)
        return QString();

    int openingBracketPos = base.indexOf('[', subSelectionPos);

    if (openingBracketPos == -1)
        return QString("%1[%2]").arg(base).arg(condition);

    // Add parenthesis around original predicates.
    QString expanded = base;
    expanded.insert(openingBracketPos + 1, '(');

    int closingBracketPos = expanded.lastIndexOf(']');
    if (closingBracketPos == -1) {
      qDebug() << "Malformed query?: " << base;
      return base;
    }

    expanded.insert(closingBracketPos, QString(") and %1").arg(condition));

    return expanded;
}

Add parenthesis around predicates before query expansion.


#include "stdafx.h"
#include "Collider.h"
#include "Explosion.h"
#include "ColliderManager.h"

//Base Class of All Explosions
bool Explosion::init()
{
	explosion = ParticleExplosion::create();
	this->addChild(explosion);
	isFlying = true;
	lifeTime = 2 * Director::getInstance()->getFrameRate();
	return true;
}

void Explosion::Act()
{
	if (lifeTime > 0)
	{
		lifeTime--;
	}
	else
	{
		SetFlying(false);
		removeFromParent();
		ColliderManager::GetInstance()->EraseCollider(this);
	}
}

bool Explosion::IsFlying()
{
	return isFlying;
}

void Explosion::SetFlying(bool flag)
{
	isFlying = flag;
}

bool Explosion::IsBullet()
{
	return false;
}

void Explosion::SetPosition(Point pos)
{
	setPosition(pos);
	explosion->setPosition(Point::ZERO);
}

#include "stdafx.h"
#include "Collider.h"
#include "Explosion.h"
#include "ColliderManager.h"

//Base Class of All Explosions
bool Explosion::init()
{
	explosion = ParticleExplosion::create();
	this->addChild(explosion);
	isFlying = true;
	lifeTime = 10 * Director::getInstance()->getFrameRate();
	return true;
}

void Explosion::Act()
{
	if (lifeTime > 0)
	{
		lifeTime--;
	}
	else
	{
		SetFlying(false);
		removeFromParent();
		ColliderManager::GetInstance()->EraseCollider(this);
	}
}

bool Explosion::IsFlying()
{
	return isFlying;
}

void Explosion::SetFlying(bool flag)
{
	isFlying = flag;
}

bool Explosion::IsBullet()
{
	return false;
}

void Explosion::SetPosition(Point pos)
{
	setPosition(pos);
	explosion->setPosition(Point::ZERO);
}

SET explosion life time to 10 seconds


// Copyright (c) 2020-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <tinyformat.h>
#include <util/syserror.h>

#include <cstring>

std::string SysErrorString(int err)
{
    char buf[256];
    /* Too bad there are three incompatible implementations of the
     * thread-safe strerror. */
    const char *s = nullptr;
#ifdef WIN32
    if (strerror_s(buf, sizeof(buf), err) == 0) s = buf;
#else
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
    s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
    if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf;
#endif
#endif
    if (s != nullptr) {
        return strprintf("%s (%d)", s, err);
    } else {
        return strprintf("Unknown error (%d)", err);
    }
}

// Copyright (c) 2020-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <tinyformat.h>
#include <util/syserror.h>

#include <cstring>

std::string SysErrorString(int err)
{
    char buf[1024];
    /* Too bad there are three incompatible implementations of the
     * thread-safe strerror. */
    const char *s = nullptr;
#ifdef WIN32
    if (strerror_s(buf, sizeof(buf), err) == 0) s = buf;
#else
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
    s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
    if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf;
#endif
#endif
    if (s != nullptr) {
        return strprintf("%s (%d)", s, err);
    } else {
        return strprintf("Unknown error (%d)", err);
    }
}

Increase buffer size to 1024 in SysErrorString


#include "gtest/gtest.h"
#include "lms/endian.h"

TEST(Endian, uint16) {
    using lms::Endian;
    ASSERT_EQ(0xFECAu, Endian::letoh(Endian::htobe(uint16_t(0xCAFEu))));
    ASSERT_EQ(0xFECAu, Endian::betoh(Endian::htole(uint16_t(0xCAFEu))));
}

TEST(Endian, uint32) {
    using lms::Endian;
    ASSERT_EQ(0xEFBEADDEu, Endian::letoh(Endian::htobe(uint32_t(0xDEADBEEFu))));
    ASSERT_EQ(0xEFBEADDEu, Endian::betoh(Endian::htole(uint32_t(0xDEADBEEFu))));
}

TEST(Endian, uint64) {
    using lms::Endian;
    ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::letoh(Endian::htobe(0xFEEDCAFEDEADBEEFu)));
    ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::betoh(Endian::htole(0xFEEDCAFEDEADBEEFu)));
}

#include "gtest/gtest.h"
#include "lms/endian.h"

TEST(Endian, uint16) {
    using lms::Endian;
    ASSERT_EQ(0xFECAu, Endian::letoh(Endian::htobe(uint16_t(0xCAFEu))));
    ASSERT_EQ(0xFECAu, Endian::betoh(Endian::htole(uint16_t(0xCAFEu))));
}

TEST(Endian, uint32) {
    using lms::Endian;
    ASSERT_EQ(0xEFBEADDEu, Endian::letoh(Endian::htobe(uint32_t(0xDEADBEEFu))));
    ASSERT_EQ(0xEFBEADDEu, Endian::betoh(Endian::htole(uint32_t(0xDEADBEEFu))));
}

TEST(Endian, uint64) {
    using lms::Endian;
    ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::letoh(Endian::htobe(uint64_t(0xFEEDCAFEDEADBEEFu))));
    ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::betoh(Endian::htole(uint64_t(0xFEEDCAFEDEADBEEFu))));
}

Fix type in uint64 Endian test


#include "Selector.h"

bool StartsWith(const std::string& prefix, const std::string& query)
{
  return (query.compare(0, prefix.length(), prefix) == 0);
}

std::string ConsumePrefix(const std::string& prefix, const std::string& query)
{
  if (StartsWith(prefix, query))
    return query.substr(prefix.length());
  else
    return query;
}

#include "Selector.h"

bool StartsWith(const std::string& prefix, const std::string& query)
{
  if (prefix.length() == 0)
    return true;

  if (prefix[0] == '?' && query.length() > 0)
  {
    return StartsWith(prefix.substr(1), query.substr(1));
  }

  return (query.compare(0, prefix.length(), prefix) == 0);
}

std::string ConsumePrefix(const std::string& prefix, const std::string& query)
{
  if (StartsWith(prefix, query))
    return query.substr(prefix.length());
  else
    return query;
}

Support for leading ? wildcards


// RUN: %clang_cc1 -fdelayed-template-parsing -fsyntax-only -verify %s

template <class T>
class A {
   void foo() {
       undeclared();
   }
      void foo2();
};

template <class T>
class B {
   void foo4() { } // expected-note {{previous definition is here}}  expected-note {{previous definition is here}}
   void foo4() { } // expected-error {{class member cannot be redeclared}} expected-error {{redefinition of 'foo4'}}  expected-note {{previous definition is here}}
};

template <class T>
void B<T>::foo4() {// expected-error {{redefinition of 'foo4'}}
}

template <class T>
void A<T>::foo2() {
    undeclared();
}

template <class T>
void foo3() {
   undeclared();
}

template void A<int>::foo2();

void undeclared()
{

}

template <class T> void foo5() {} //expected-note {{previous definition is here}}
template <class T> void foo5() {} // expected-error {{redefinition of 'foo5'}}

Remove hard coded dos line endings, let subversion translate them on update.


#include "Progression.h"

Progression* Progression::m_instance = nullptr;

Progression::Progression()
{

}

Progression::~Progression()
{

}

bool Progression::WriteToFile(std::string filename)
{
	std::ofstream saveFile;

	saveFile.open("..\\Debug\\Saves\\" + filename + ".txt");

	if (!saveFile.is_open()) {
		return false;
	}
	else
	{

		saveFile << "Allhuakbar" << "\r\n";
		saveFile.close();
	}
	return true;
}

bool Progression::ReadFromFile(std::string filename)
{
	return false;
}

#include "Progression.h"

Progression* Progression::m_instance = nullptr;

Progression::Progression()
{
	this->m_currentLevel = 0;
	this->m_currentCheckpoint = 0;
	this->m_unlockedLevels = 0;
}

Progression::~Progression()
{

}

bool Progression::WriteToFile(std::string filename)
{
	std::ofstream saveFile;

	saveFile.open("..\\Debug\\Saves\\" + filename + ".txt");

	if (!saveFile.is_open()) {
		return false;
	}
	else
	{

		saveFile << "Allhuakbar" << "\r\n";
		saveFile.close();
	}
	return true;
}

bool Progression::ReadFromFile(std::string filename)
{
	return false;
}

ADD intialized the Progress variables


Change UART number in uart_example to be compatible with TI lm4f120xl.


#include "../vm/debug.h"
#include "../vm/vm.h"
#include <fstream>

int main(int argc, char *argv[]) {
    std::ifstream bytecode_if;
    std::streamsize bytecode_size;
    uint8_t *bytecode;

    if (argc < 3) {
        printf("Usage: %s <opcodes_key> <program>\n", argv[0]);
        return 1;
    }

    /*
    reading bytecode
    */
    bytecode_if.open(argv[2], std::ios::binary | std::ios::ate);
    bytecode_size = bytecode_if.tellg();
    bytecode_if.seekg(0, std::ios::beg);

    bytecode = new uint8_t[bytecode_size];
    bytecode_if.read((char *) bytecode, bytecode_size);
    VM vm((uint8_t *) argv[1], bytecode, bytecode_size);
    vm.run();
    return 0;
}

#include "../vm/debug.h"
#include "../vm/vm.h"
#include <fstream>

int main(int argc, char *argv[]) {
    std::ifstream bytecode_if;
    std::streamsize bytecode_size;
    uint8_t *bytecode;

    if (argc < 3) {
        printf("Usage: %s <opcodes_key> <program>\n", argv[0]);
        return 1;
    }

    /*
    reading bytecode
    */
    bytecode_if.open(argv[2], std::ios::binary | std::ios::ate);
    if (!bytecode_if.good()) {
        printf("File is not valid.\n");
        return -1;
    }
    bytecode_size = bytecode_if.tellg();
    bytecode_if.seekg(0, std::ios::beg);

    bytecode = new uint8_t[bytecode_size];
    bytecode_if.read((char *) bytecode, bytecode_size);
    VM vm((uint8_t *) argv[1], bytecode, bytecode_size);
    vm.run();
    return 0;
}

Check if input file is good


#include <exception>

#include "globals.hh"

#include "G4Application.hh"

using namespace g4;
using namespace std;

/**
  * @short Simple main function.
  *
  * It only initializes and runs application and
  * prints out all exceptions.
  */
int main(int argc, char** argv)
{
    try
    {
        // Run the application
        G4Application::CreateInstance(argc, argv);
        G4Application::GetInstance()->RunUI();
    }
    catch (const exception& exc)
    {
        G4cerr << "Exception thrown: " << exc.what() << endl;
        exit(-1);
    }
    catch (const string& exc)
    {
        G4cerr << "Exception thrown: " << exc << endl;
        exit(-1);
    }
    catch (const char* exc)
    {
        G4cerr << "Exception thrown: " << exc << endl;
        exit(-1);
    }
}

#include <exception>

#include "globals.hh"

#include "G4Application.hh"

using namespace g4;
using namespace std;

/**
  * @short Simple main function.
  *
  * It only initializes and runs application and
  * prints out all exceptions.
  */
int main(int argc, char** argv)
{
    try
    {
        // Run the application
        G4Application::CreateInstance(argc, argv);
        G4Application::GetInstance()->RunUI();
    }
    catch (const exception& exc)
    {
        G4cerr << "Exception thrown: " << exc.what() << endl;
        exit(-1);
    }
    catch (const string& exc)
    {
        G4cerr << "Exception thrown: " << exc << endl;
        exit(-1);
    }
    catch (const char* exc)
    {
        G4cerr << "Exception thrown: " << exc << endl;
        exit(-1);
    }
    G4cout << "Application exiting normally..." << G4endl;
}

Add exiting normally to the app


// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/ui/ui_test.h"

class LocaleTestsDa : public UITest {
 public:
  LocaleTestsDa() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"da");
  }
};

class LocaleTestsHe : public UITest {
 public:
  LocaleTestsHe() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"he");
  }
};

class LocaleTestsZhTw : public UITest {
 public:
  LocaleTestsZhTw() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-tw");
  }
};

#if defined(OS_WIN) || defined(OS_LINUX)
// These 3 tests started failing between revisions 13115 and 13120.
// See bug 9758.
TEST_F(LocaleTestsDa, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsHe, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsZhTw, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}
#endif

// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/ui/ui_test.h"

class LocaleTestsDa : public UITest {
 public:
  LocaleTestsDa() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"da");
  }
};

class LocaleTestsHe : public UITest {
 public:
  LocaleTestsHe() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"he");
  }
};

class LocaleTestsZhTw : public UITest {
 public:
  LocaleTestsZhTw() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-TW");
  }
};

#if defined(OS_WIN) || defined(OS_LINUX)
// These 3 tests started failing between revisions 13115 and 13120.
// See bug 9758.
TEST_F(LocaleTestsDa, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsHe, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsZhTw, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}
#endif

Change zh-tw to zh-TW when it's used to find the locale data pack on Linux (case-sensitive file system).


//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "tac/ReduceInStrength.hpp"
#include "tac/OptimizerUtils.hpp"

using namespace eddic;

void tac::ReduceInStrength::operator()(std::shared_ptr<tac::Quadruple>& quadruple){
    switch(quadruple->op){
        case tac::Operator::MUL:
            if(*quadruple->arg1 == 2){
                replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::ADD, *quadruple->arg2);
            } else if(*quadruple->arg2 == 2){
                replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::ADD, *quadruple->arg1);
            }

            break;
        default:
            break;
    }
}

//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "tac/ReduceInStrength.hpp"
#include "tac/OptimizerUtils.hpp"

using namespace eddic;

void tac::ReduceInStrength::operator()(std::shared_ptr<tac::Quadruple>& quadruple){
    switch(quadruple->op){
        case tac::Operator::MUL:
            if(*quadruple->arg1 == 2){
                replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::ADD, *quadruple->arg2);
            } else if(*quadruple->arg2 == 2){
                replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::ADD, *quadruple->arg1);
            }

            break;
        case tac::Operator::FMUL:
            if(*quadruple->arg1 == 2.0){
                replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::FADD, *quadruple->arg2);
            } else if(*quadruple->arg2 == 2.0){
                replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::FADD, *quadruple->arg1);
            }

            break;
        default:
            break;
    }
}

Reduce float multiplication in strength


// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Cards/Entity.h>

namespace Hearthstonepp
{
Entity::Entity(Card& _card) : card(new Card(_card))
{
    // Do nothing
}

Entity::Entity(const Entity& ent)
{
    FreeMemory();

    card = ent.card;
    gameTags = ent.gameTags;
}

Entity::~Entity()
{
    FreeMemory();
}

Entity& Entity::operator=(const Entity& ent)
{
    if (this == &ent)
    {
        return *this;
    }

    FreeMemory();

    card = ent.card;
    gameTags = ent.gameTags;

    return *this;
}

Entity* Entity::Clone() const
{
    return new Entity(*this);
}

void Entity::FreeMemory()
{
    gameTags.clear();

    delete card;
}
}  // namespace Hearthstonepp

// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/Cards/Entity.h>

namespace Hearthstonepp
{
Entity::Entity(Card& _card) : card(new Card(_card))
{
    for (auto& mechanic : card->mechanics)
    {
        gameTags.insert(std::make_pair(mechanic, 1));
    }
}

Entity::Entity(const Entity& ent)
{
    FreeMemory();

    card = ent.card;
    gameTags = ent.gameTags;
}

Entity::~Entity()
{
    FreeMemory();
}

Entity& Entity::operator=(const Entity& ent)
{
    if (this == &ent)
    {
        return *this;
    }

    FreeMemory();

    card = ent.card;
    gameTags = ent.gameTags;

    return *this;
}

Entity* Entity::Clone() const
{
    return new Entity(*this);
}

void Entity::FreeMemory()
{
    gameTags.clear();

    delete card;
}
}  // namespace Hearthstonepp

Insert card game tags in constructor


#include "selection_window.h"
#include "../components/description_component.h"
#include "../core/game_engine.h"
#include "inspection_window.h"
#include "listbox.h"

void SelectionWindow::setup() {
    setEntities(static_cast<EntityHolder*>(getArgs()));

    setEscapeBehaviour(Window::EscapeBehaviour::CloseWindow);
    setWidth(20);
    setHeight(m_entities.size() + 4);
}

void SelectionWindow::registerWidgets() {
    ListBox* box = this->createWidget<ListBox>("lstEntities", 2, 2);

    for (std::string line : m_lines) {
        ListBoxItem item;
        item.setText(line);
        box->addItem(item);
    }

    box->setHeight(m_lines.size());
    box->setItemSelectedCallback([](ListBox* box) {
        SelectionWindow* win = dynamic_cast<SelectionWindow*>(box->getWindow());
        EntityId* l_target =
            new EntityId(win->getEntities()[box->getSelection()]);
        win->getEngine()->getWindows()->createWindow<InspectionWindow>(
            l_target);
    });
}

void SelectionWindow::setEntities(EntityHolder* entities) {
    if (!entities)
        return;

    for (EntityId entity : *entities) {
        DescriptionComponent* desc =
            getEngine()->state()->components()->get<DescriptionComponent>(
                entity);
        if (desc == nullptr)
            continue;

        m_entities.push_back(entity);
        m_lines.push_back(desc->title);
    }
}

#include "selection_window.h"
#include "../components/description_component.h"
#include "../core/game_engine.h"
#include "inspection_window.h"
#include "listbox.h"

void SelectionWindow::setup() {
    setEntities(static_cast<EntityHolder*>(getArgs()));

    setEscapeBehaviour(Window::EscapeBehaviour::CloseWindow);
    setWidth(20);
    setHeight(m_entities.size() + 4);
}

void SelectionWindow::registerWidgets() {
    ListBox* box = this->createWidget<ListBox>("lstEntities", 1, 1);

    for (std::string line : m_lines) {
        ListBoxItem item;
        item.setText(line);
        box->addItem(item);
    }

    box->setHeight(m_lines.size());
    box->setItemSelectedCallback([](ListBox* box) {
        SelectionWindow* win = dynamic_cast<SelectionWindow*>(box->getWindow());
        EntityId* l_target =
            new EntityId(win->getEntities()[box->getSelection()]);
        win->getEngine()->getWindows()->createWindow<InspectionWindow>(
            l_target);
    });
}

void SelectionWindow::setEntities(EntityHolder* entities) {
    if (!entities)
        return;

    for (EntityId entity : *entities) {
        DescriptionComponent* desc =
            getEngine()->state()->components()->get<DescriptionComponent>(
                entity);
        if (desc == nullptr)
            continue;

        m_entities.push_back(entity);
        m_lines.push_back(desc->title);
    }
}

Align list items in selection window


#include "tst_configuration.h"

void TST_Configuration::test()
{
    CWF::Configuration configuration("");
    configuration.setHost(QHostAddress("127.0.0.1"));
    configuration.setPort(8080);
    configuration.setDomain("www.test.com.xyz");

    QVERIFY2(configuration.getHost().toString() == "127.0.0.1", "Should be 127.0.0.1");
    QVERIFY2(configuration.getPort() == 8080, "Should be 8080");
    QVERIFY2(configuration.getDomain() == "www.test.com.xyz", "Should be www.test.com.xyz");
}

#include "tst_configuration.h"

void TST_Configuration::test()
{
    CWF::Configuration configuration("");
    configuration.setHost(QHostAddress("127.0.0.1"));
    configuration.setPort(8080);
    configuration.setDomain("www.test.com.xyz");
    configuration.setMaxThread(200);

    QVERIFY2(configuration.getHost().toString() == "127.0.0.1", "Should be 127.0.0.1");
    QVERIFY2(configuration.getPort() == 8080, "Should be 8080");
    QVERIFY2(configuration.getDomain() == "www.test.com.xyz", "Should be www.test.com.xyz");
    QVERIFY2(configuration.getPort() == 200, "Should be 200");
}

Upgrade tests for Configuration for threads


// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "webkit/extensions/v8/playback_extension.h"

namespace extensions_v8 {

const char* kPlaybackExtensionName = "v8/PlaybackMode";

v8::Extension* PlaybackExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kPlaybackExtensionName,
      "(function () {"
      "  var orig_date = Date;"
      "  Math.random = function() {"
      "    return 0.5;"
      "  };"
      "  Date.__proto__.now = function() {"
      "    return new orig_date(1204251968254);"
      "  };"
      "  Date = function() {"
      "    return Date.now();"
      "  };"
      "})()");
    return extension;
}

}  // namespace extensions_v8

// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "webkit/extensions/v8/playback_extension.h"

namespace extensions_v8 {

const char* kPlaybackExtensionName = "v8/PlaybackMode";

v8::Extension* PlaybackExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kPlaybackExtensionName,
      "(function () {"
      "  var orig_date = Date;"
      "  var x = 0;"
      "  var time_seed = 1204251968254;"
      "  Math.random = function() {"
      "    x += .1;"
      "    return (x % 1);"
      "  };"
      "  Date.__proto__.now = function() {"
      "    time_seed += 50;"
      "    return new orig_date(time_seed);"
      "  };"
      "  Date = function() {"
      "    return Date.now();"
      "  };"
      "})()");
    return extension;
}

}  // namespace extensions_v8

Update playback extension so that javascript functions return consistent (but not constant) values in an attempt to preserve the functionality but improve compatibility of the extension.


#include <gtest/gtest.h>
#include <stan/math/fwd/core/fvar.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/prim/scal/meta/broadcast_array.hpp>

TEST(foo, bar) {
  using stan::math::detail::broadcast_array;
  using stan::math::fvar;
  using stan::math::var;

  fvar<var> fv(0.0);
  broadcast_array<fvar<var> > ba(fv);
  EXPECT_EQ(0.0, ba[0].val_.vi_->val_);
  EXPECT_EQ(0.0, ba[2].val_.vi_->val_);
}

#include <gtest/gtest.h>
#include <stan/math/fwd/core/fvar.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/prim/scal/meta/broadcast_array.hpp>

TEST(foo, bar) {
  using stan::math::detail::broadcast_array;
  using stan::math::fvar;
  using stan::math::var;

  fvar<var> fv(1.0, 2.1);
  broadcast_array<fvar<var> > ba(fv);
  EXPECT_EQ(1.0, ba[0].val_.vi_->val_);
  EXPECT_EQ(1.0, ba[2].val_.vi_->val_);
}

Fix broadcast_array test to use new fvar ctor


#include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

#include "utils.cc"

#define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name)
#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#ifndef FUZZ_ENCODER
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER)
#endif

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  image.magick(FUZZ_ENCODER);
  image.fileName(std::string(FUZZ_ENCODER) + ":");
  try {
    image.read(blob);
  }
  catch (Magick::Exception &e) {
    return 0;
  }

  Magick::Blob outBlob;
  try {
    image.write(&outBlob, FUZZ_ENCODER);
  }
  catch (Magick::Exception &e) {
  }
  return 0;
}

#include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

#include "utils.cc"

#define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name)
#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#ifndef FUZZ_ENCODER
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER)
#endif
#define FUZZ_IMAGEMAGICK_ENCODER_WRITE 1

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  image.magick(FUZZ_ENCODER);
  image.fileName(std::string(FUZZ_ENCODER) + ":");
  try {
    image.read(blob);
  }
  catch (Magick::Exception &e) {
    return 0;
  }

#if FUZZ_IMAGEMAGICK_ENCODER_WRITE

  Magick::Blob outBlob;
  try {
    image.write(&outBlob, FUZZ_ENCODER);
  }
  catch (Magick::Exception &e) {
  }
#endif
  return 0;
}

Prepare for flag to allow writing.


// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <service>

extern "C" const char* service_name__ = SERVICE_NAME;
extern "C" const char* service_binary_name__ = SERVICE;

// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <service>

const char* service_name__ = SERVICE_NAME;
const char* service_binary_name__ = SERVICE;

Remove erroneous extern C from service name


//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "DependenciesResolver.hpp"

#include "ast/SourceFile.hpp"

#include "VisitorUtils.hpp"
#include "ASTVisitor.hpp"

using namespace eddic;

DependenciesResolver::DependenciesResolver(SpiritParser& p) : parser(p) {}

void DependenciesResolver::resolve(ast::SourceFile& program) const {
    //TODO
}

//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "DependenciesResolver.hpp"

#include "ast/SourceFile.hpp"

#include "VisitorUtils.hpp"
#include "ASTVisitor.hpp"

using namespace eddic;

DependenciesResolver::DependenciesResolver(SpiritParser& p) : parser(p) {}

class DependencyVisitor : public boost::static_visitor<> {
    private:
        SpiritParser& parser;

    public:
        DependencyVisitor(SpiritParser& p) : parser(p) {}

        AUTO_RECURSE_PROGRAM()

        void operator()(ast::StandardImport& import){
            //TODO
        }

        void operator()(ast::Import& import){
            //TODO
        }

        template<typename T>
        void operator()(T&){
            //Nothing to include there
        }
};

void DependenciesResolver::resolve(ast::SourceFile& program) const {
    DependencyVisitor visitor(parser);
    visitor(program);
}

Create the visitor for includes


// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Tasks/SimpleTasks/AddEnchantmentTask.hpp>

namespace RosettaStone::SimpleTasks
{
AddEnchantmentTask::AddEnchantmentTask(std::string&& cardID,
                                       EntityType entityType)
    : ITask(entityType), m_cardID(cardID)
{
    // Do nothing
}

TaskID AddEnchantmentTask::GetTaskID() const
{
    return TaskID::ADD_ENCHANTMENT;
}

TaskStatus AddEnchantmentTask::Impl(Player&)
{
    Card enchantmentCard = Cards::FindCardByID(m_cardID);
    if (enchantmentCard.id.empty())
    {
        return TaskStatus::STOP;
    }

    Power power = Cards::FindCardByID(m_cardID).power;
    if (power.GetEnchant().has_value())
    {
        power.GetEnchant().value().ActivateTo(
            dynamic_cast<Character*>(m_target));
    }

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Tasks/SimpleTasks/AddEnchantmentTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>

namespace RosettaStone::SimpleTasks
{
AddEnchantmentTask::AddEnchantmentTask(std::string&& cardID,
                                       EntityType entityType)
    : ITask(entityType), m_cardID(cardID)
{
    // Do nothing
}

TaskID AddEnchantmentTask::GetTaskID() const
{
    return TaskID::ADD_ENCHANTMENT;
}

TaskStatus AddEnchantmentTask::Impl(Player& player)
{
    Card enchantmentCard = Cards::FindCardByID(m_cardID);
    if (enchantmentCard.id.empty())
    {
        return TaskStatus::STOP;
    }

    Power power = Cards::FindCardByID(m_cardID).power;
    if (power.GetEnchant().has_value())
    {
        auto entities =
            IncludeTask::GetEntities(m_entityType, player, m_source, m_target);

        for (auto& entity : entities)
        {
            power.GetEnchant().value().ActivateTo(
                dynamic_cast<Character*>(entity));
        }
    }

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

Add code to include entities and change target to entity


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by eeGeo";
                std::string popupBody = "The " + m_appName + " app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/findoutmore?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by eeGeo";
                std::string popupBody = "The " + m_appName + " app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

Watermark nows points to eegeo.com. Buddy: Ian H


#include <bts/blockchain/address.hpp>
#include <fc/crypto/elliptic.hpp>

#include <iostream>

int main( int argc, char** argv )
{
   if( argc == 1 )
   {
      auto key = fc::ecc::private_key::generate();
      std::cout << "private key: "
                << std::string( key.get_secret() ) <<"\n";

      std::cout << "bts address: "
                << std::string( bts::blockchain::address( key.get_public_key() ) ) <<"\n";
      return 0;
   }
}

#include <bts/blockchain/address.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/filesystem.hpp>

#include <iostream>

int main( int argc, char** argv )
{
   if( argc == 1 )
   {
      auto key = fc::ecc::private_key::generate();
      std::cout << "private key: "
                << std::string( key.get_secret() ) <<"\n";

      std::cout << "bts address: "
                << std::string( bts::blockchain::address( key.get_public_key() ) ) <<"\n";
      return 0;
   }
   else if (argc == 2)
   {
     std::cout << "writing new private key to JSON file " << argv[1] << "\n";
     fc::ecc::private_key key(fc::ecc::private_key::generate());
     fc::json::save_to_file(key, fc::path(argv[1]));

     std::cout << "bts address: "
       << std::string(bts::blockchain::address(key.get_public_key())) << "\n";

     return 0;
   }
}

Add option to write created key to a JSON file for use in bts_xt_client.


#include "elapsedtimer.h"

ElapsedTimer::ElapsedTimer(QObject* parent) : QObject(parent) {
    connect(&_interval, &QTimer::timeout, this, [=] () {
        emit timeElapsed(_elapsed.elapsed());
    });
}

qint64 ElapsedTimer::elapsed()
{
    if (_elapsed.isValid()) {
        return _elapsed.elapsed();
    }
    return finalTime;
}

bool ElapsedTimer::isRunning() {
    return _elapsed.isValid();
}

void ElapsedTimer::start(int updateRate) {
    _interval.start(updateRate);
    _elapsed.start();
}

void ElapsedTimer::stop() {
    _interval.stop();
    finalTime = _elapsed.elapsed();
    _elapsed.invalidate();
}

#include "elapsedtimer.h"

ElapsedTimer::ElapsedTimer(QObject* parent) : QObject(parent) {
    connect(&_interval, &QTimer::timeout, this, [=] () {
        emit timeElapsed(_elapsed.elapsed());
    });
}

qint64 ElapsedTimer::elapsed()
{
    if (_elapsed.isValid()) {
        return _elapsed.elapsed();
    }
    return finalTime;
}

bool ElapsedTimer::isRunning() {
    return _elapsed.isValid();
}

void ElapsedTimer::start(int updateRate) {
    _interval.start(updateRate);
    _elapsed.start();
}

void ElapsedTimer::stop() {
    _interval.stop();
    if (_elapsed.isValid()) {
        finalTime = _elapsed.elapsed();
        _elapsed.invalidate();
    }
}

Fix elapsed timer bug when stopped multiple times


#include <string>
#include <ccspec/expectation/unexpected_throw.h>

namespace ccspec {
namespace expectation {

using std::string;

UnexpectedThrow::UnexpectedThrow(const std::exception& cause)
    : cause_(cause) {}

string UnexpectedThrow::toString() {
    return string("Unexpected exception: ") + cause_.what();
}

} // namespace expectation
} // namespace ccspec

#include <string>
#include <ccspec/expectation/unexpected_throw.h>

namespace ccspec {
namespace expectation {

using std::exception;
using std::string;

UnexpectedThrow::UnexpectedThrow(const exception& cause)
    : cause_(cause) {}

string UnexpectedThrow::toString() {
    return string("Unexpected exception: ") + cause_.what();
}

} // namespace expectation
} // namespace ccspec

Include std::exception into the namespace


// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

// Qt.
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    App app;

    MainWindow w(&app);
    w.setMinimumSize(640, 480);
    w.show();

    app.setUI(&w);

    return a.exec();
}

// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

// Qt.
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    App app;

    MainWindow w(&app);
    w.setMinimumSize(640, 480);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

Set MainWindow as delegate of app.


/*
 *  Copyright 2002 California Institute of Technology
 */

#include "cantera/IdealGasMix.h"
#include "cantera/equilibrium.h"
#include "cantera/thermo/IdealSolnGasVPSS.h"
#include "cantera/thermo/ThermoFactory.h"

using namespace std;
using namespace Cantera;

int main(int argc, char** argv)
{
#ifdef _MSC_VER
    _set_output_format(_TWO_DIGIT_EXPONENT);
#endif
    try {
        Cantera::IdealSolnGasVPSS gg("silane.xml", "silane");
        ThermoPhase* g = ≫
        //ThermoPhase *g = newPhase("silane.xml", "silane");
        cout.precision(4);
        g->setState_TPX(1500.0, 100.0, "SIH4:0.01, H2:0.99");
        //g.setState_TPX(1500.0, 1.0132E5, "SIH4:0.01, H2:0.99");
        Cantera::ChemEquil_print_lvl = 40;
        equilibrate(*g, "TP");
        std::string r = g->report(true);
        cout << r;
        cout << endl;
        return 0;
    } catch (CanteraError& err) {
        std::cerr << err.what() << std::endl;
        cerr << "program terminating." << endl;
        return -1;
    }
}

/*
 *  Copyright 2002 California Institute of Technology
 */

#include "cantera/IdealGasMix.h"
#include "cantera/equilibrium.h"
#include "cantera/thermo/IdealSolnGasVPSS.h"
#include "cantera/thermo/ThermoFactory.h"

using namespace std;
using namespace Cantera;

int main(int argc, char** argv)
{
#ifdef _MSC_VER
    _set_output_format(_TWO_DIGIT_EXPONENT);
#endif
    try {
        Cantera::IdealSolnGasVPSS gg("silane.xml", "silane");
        ThermoPhase* g = ≫
        //ThermoPhase *g = newPhase("silane.xml", "silane");
        cout.precision(4);
        g->setState_TPX(1500.0, 100.0, "SIH4:0.01, H2:0.99");
        //g.setState_TPX(1500.0, 1.0132E5, "SIH4:0.01, H2:0.99");
        equilibrate(*g, "TP");
        std::string r = g->report(true);
        cout << r;
        cout << endl;
        return 0;
    } catch (CanteraError& err) {
        std::cerr << err.what() << std::endl;
        cerr << "program terminating." << endl;
        return -1;
    }
}

Fix failure of VPsilane_test when debug_verbose=y


#include <qpiekey.h>
#include <QSizePolicy>
#include <QPainter>
#include <QPaintEvent>

QPieKey::QPieKey(QWidget *parent) : QWidget(parent)
{
    bitmap = new QBitmap(40,40);
    QPainter painter(bitmap);

    bitmap->clear();
    painter.drawEllipse(0, 0, 40, 40);
    setFixedSize(40, 40);
    setMask(*bitmap);
}

QPieKey::~QPieKey()
{
}

void QPieKey::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    painter.setBrush(QColor(128, 128, 128));
    painter.drawRect(event->rect());
}

#include <qpiekey.h>
#include <QSizePolicy>
#include <QPainter>
#include <QPaintEvent>

#define SIZE 60

QPieKey::QPieKey(QWidget *parent) : QWidget(parent)
{
    bitmap = new QBitmap(SIZE*2,SIZE*2);
    QPainter painter(bitmap);

    setFixedSize(SIZE*2, SIZE*2);

    bitmap->clear();
    painter.setBrush(Qt::color1);
    painter.drawEllipse(1, 1, SIZE*2-2, SIZE*2-2);
    painter.setBrush(Qt::color0);
    painter.drawEllipse(SIZE/2, SIZE/2, SIZE, SIZE);
    setMask(*bitmap);
    hide();
}

QPieKey::~QPieKey()
{
}

void QPieKey::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    painter.setBrush(QColor(128, 128, 128));
    painter.drawRect(event->rect());
}

Set the transparent region appropriately


#include <cstring>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, const char* argv[]) {
    // Print help
    if (argc == 1 || strcmp(argv[0], "--help") == 0) {
        cout << "GLSLPreprocessor is a simple preprocessor for GLSL files." << endl
             << "Usage:" << endl
             << "GLSLPreprocessor input output" << endl;
        return 0;
    }

    // Get input and output names.
    string inputName = argv[1];
    string outputName;
    if (argc > 2)
        outputName = argv[2];
    else
        outputName = inputName;

    return 0;
}

#include <cstring>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main(int argc, const char* argv[]) {
    // Print help
    if (argc == 1 || strcmp(argv[0], "--help") == 0) {
        cout << "GLSLPreprocessor is a simple preprocessor for GLSL files." << endl
             << "Usage:" << endl
             << "GLSLPreprocessor input output" << endl;
        return 0;
    }

    // Get input and output names.
    string inputName = argv[1];
    string outputName;
    if (argc > 2)
        outputName = argv[2];
    else
        outputName = inputName;

    // TODO: Process file.
    string output = "";

    // Write output file.
    ofstream outFile(outputName.c_str());
    outFile << output;
    outFile.close();

    return 0;
}

Write output to output file


#include "gtest/gtest.h"

#include "paxos/messages.hpp"

TEST(MessageTest, testMessageResponseUpdatesSenderAndReceiver)
{
    Replica from("from_hostname");
    Replica to("to_hostname");

    Decree the_decree(from, 1, "", DecreeType::UserDecree);
    Message m(the_decree, from, to, MessageType::RequestMessage);

    Message response = Response(m, MessageType::PromiseMessage);

    ASSERT_EQ(response.from.hostname, m.to.hostname);
    ASSERT_EQ(response.to.hostname, m.from.hostname);
    ASSERT_EQ(response.type, MessageType::PromiseMessage);
}

TEST(MessageTest, testMessageTypeHashFunction)
{
    ASSERT_EQ(0, MessageTypeHash()(MessageType::RequestMessage));
    ASSERT_EQ(1, MessageTypeHash()(MessageType::RetryRequestMessage));
    ASSERT_EQ(2, MessageTypeHash()(MessageType::PrepareMessage));
    ASSERT_EQ(3, MessageTypeHash()(MessageType::RetryPrepareMessage));
    ASSERT_EQ(4, MessageTypeHash()(MessageType::PromiseMessage));
    ASSERT_EQ(5, MessageTypeHash()(MessageType::NackMessage));
    ASSERT_EQ(6, MessageTypeHash()(MessageType::AcceptMessage));
    ASSERT_EQ(7, MessageTypeHash()(MessageType::AcceptedMessage));
    ASSERT_EQ(8, MessageTypeHash()(MessageType::UpdateMessage));
    ASSERT_EQ(9, MessageTypeHash()(MessageType::UpdatedMessage));
}

Add unittests for message type hash


#include <iostream>
using namespace std;

#define out if(1)cout
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
#define abs(a)   (((a)<0)?(-(a)):(a))

static const int MAXN = 10000001;

typedef long long int i64;
static i64 ar[MAXN];

int main()
{
	int N, M;
	cin >> N >> M;

	for (int i = 0; i < M; i++) {
		int a, b, k;
		cin >> a >> b >> k;
		ar[a] += k;
		ar[b+1] -= k;
	}

	i64 cur = 0;
	i64 max = 0;
	for (int i = 1; i <= N; i++) {
		cur += ar[i];
		if (cur > max) max = cur;
	}
	cout << max << endl;
	return 0;
}

#include <iostream>
using namespace std;

#define out if(1)cout
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
#define abs(a)   (((a)<0)?(-(a)):(a))

static const int MAXN = 10000001;

typedef long long int i64;
static i64 ar[MAXN];

int main()
{
	ios::sync_with_stdio(false);

	int N, M;
	cin >> N >> M;

	for (int i = 0; i < M; i++) {
		int a, b, k;
		cin >> a >> b >> k;
		ar[a] += k;
		ar[b+1] -= k;
	}

	i64 cur = 0;
	i64 max = 0;
	for (int i = 1; i <= N; i++) {
		cur += ar[i];
		if (cur > max) max = cur;
	}
	cout << max << endl;
	return 0;
}

Improve iostream with stdio unsync: real 0m1.029s -> 0m1.020s user 0m0.538s -> 0m0.569s sys 0m0.311s -> 0m0.262s refs: 148,846,05 -> 53,570,098


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

namespace phosphor
{
namespace inventory
{
namespace manager
{
void InterfaceError::log() const
{
    logging::log<logging::level::ERR>(
        what(), phosphor::logging::entry("INTERFACE=%s", interface));
}
} // namespace manager
} // namespace inventory
} // namespace phosphor

// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

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

namespace phosphor
{
namespace inventory
{
namespace manager
{
void InterfaceError::log() const
{
    logging::log<logging::level::ERR>(
        what(), phosphor::logging::entry("INTERFACE=%s", interface.c_str()));
}
} // namespace manager
} // namespace inventory
} // namespace phosphor

// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

Use s.c_str() in log messages


/*
 * TimeStamp.cpp
 *
 * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2001, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include <log4cpp/TimeStamp.hh>

#include <cstring>

#ifdef LOG4CPP_HAVE_GETTIMEOFDAY
#include <sys/time.h>
#else
#ifdef LOG4CPP_HAVE_FTIME
#include <sys/timeb.h>
#else
#include <time.h>
#endif
#endif

namespace log4cpp {

    TimeStamp TimeStamp::_startStamp;

    TimeStamp::TimeStamp() {
#ifdef LOG4CPP_HAVE_GETTIMEOFDAY
        struct timeval tv;
        ::gettimeofday(&tv, NULL);
        _seconds = tv.tv_sec;
        _microSeconds = tv.tv_usec;
#else
#ifdef LOG4CPP_HAVE_FTIME
        struct timeb tb;
        ::ftime(&tb);
        _seconds = tb.time;
        _microSeconds = 1000 * tb.millitm;
#else
        _seconds = ::time(NULL);
        _microSeconds = 0;
#endif
#endif
    }

    TimeStamp::TimeStamp(unsigned int seconds, unsigned int microSeconds) :
        _seconds(seconds),
        _microSeconds(microSeconds) {
    }
}

/*
 * TimeStamp.cpp
 *
 * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2001, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include <log4cpp/TimeStamp.hh>

#include <cstring>

#ifdef LOG4CPP_HAVE_GETTIMEOFDAY
#include <sys/time.h>
#else
#ifdef LOG4CPP_HAVE_FTIME
#include <sys/timeb.h>
#else
#include <time.h>
#endif
#endif

namespace log4cpp {

    LOG4CPP_EXPORT TimeStamp TimeStamp::_startStamp;

    TimeStamp::TimeStamp() {
#ifdef LOG4CPP_HAVE_GETTIMEOFDAY
        struct timeval tv;
        ::gettimeofday(&tv, NULL);
        _seconds = tv.tv_sec;
        _microSeconds = tv.tv_usec;
#else
#ifdef LOG4CPP_HAVE_FTIME
        struct timeb tb;
        ::ftime(&tb);
        _seconds = tb.time;
        _microSeconds = 1000 * tb.millitm;
#else
        _seconds = ::time(NULL);
        _microSeconds = 0;
#endif
#endif
    }

    TimeStamp::TimeStamp(unsigned int seconds, unsigned int microSeconds) :
        _seconds(seconds),
        _microSeconds(microSeconds) {
    }
}

Add LOG4CPP_EXPORT for win32 dll


#include "Foo.hh"
#include <string>
#include <iostream>

#define EXPORT __attribute__((visibility("default")))

EXPORT
int Foo::PrintFoo()
{
    std::cout << "This is in a C++ in a dynamically linked framework!" << std::endl;
    return 1;
}

#include "Foo.hh"
#include <string>
#include <iostream>

#define EXPORT __attribute__((visibility("default")))

EXPORT
int Foo::PrintFoo()
{
#if __cplusplus
    std::cout << "C++ environment detected." << std::endl;
#endif
    std::cout << "Foo::PrintFoo() called." << std::endl;
    return 1;
}

Add logging to show c++ environment.


#include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>

namespace cucumber {
namespace internal {

SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
    protocolHandler(protocolHandler),
    ios(),
    acceptor(ios) {
}

void SocketServer::listen(const port_type port) {
    tcp::endpoint endpoint(tcp::v4(), port);
    acceptor.open(endpoint.protocol());
    acceptor.set_option(tcp::acceptor::reuse_address(true));
    acceptor.bind(endpoint);
    acceptor.listen(1);
}

void SocketServer::acceptOnce() {
    tcp::iostream stream;
    acceptor.accept(*stream.rdbuf());
    processStream(stream);
}

void SocketServer::processStream(tcp::iostream &stream) {
    std::string request;
    while (getline(stream, request)) {
        stream << protocolHandler->handle(request) << std::endl << std::flush;
    }
}

}
}

#include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>

namespace cucumber {
namespace internal {

SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
    protocolHandler(protocolHandler),
    ios(),
    acceptor(ios) {
}

void SocketServer::listen(const port_type port) {
    tcp::endpoint endpoint(tcp::v4(), port);
    acceptor.open(endpoint.protocol());
    acceptor.set_option(tcp::acceptor::reuse_address(true));
    acceptor.set_option(tcp::no_delay(true));
    acceptor.bind(endpoint);
    acceptor.listen(1);
}

void SocketServer::acceptOnce() {
    tcp::iostream stream;
    acceptor.accept(*stream.rdbuf());
    processStream(stream);
}

void SocketServer::processStream(tcp::iostream &stream) {
    std::string request;
    while (getline(stream, request)) {
        stream << protocolHandler->handle(request) << std::endl << std::flush;
    }
}

}
}

Disable Nagle on TCP socket: too slow for interactive


FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "catcat", true, "catcat", "cat");
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "dogdog", true, "dogdog", "dog");
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "snek",   true, "",       "");
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "catdog", false);
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "dogcat", false);
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "cat",    false);

Add a potential buffer overrun test.


#include "writer/verilog/dataflow_in.h"

#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "writer/module_template.h"
#include "writer/verilog/insn_writer.h"
#include "writer/verilog/module.h"
#include "writer/verilog/shared_reg.h"

namespace iroha {
namespace writer {
namespace verilog {

DataFlowIn::DataFlowIn(const IResource &res, const Table &table)
  : Resource(res, table) {
}

void DataFlowIn::BuildResource() {
}

void DataFlowIn::BuildInsn(IInsn *insn, State *st) {
  IResource *res = insn->GetResource();
  IResource *parent = res->GetParentResource();
  if (insn->outputs_.size() == 1 && parent != nullptr &&
      resource::IsSharedReg(*(parent->GetClass()))) {
    ostream &ws = tmpl_->GetStream(kInsnWireValueSection);
    ws << "  assign " << InsnWriter::InsnOutputWireName(*insn, 0)
       << " = " << SharedReg::RegName(*parent) << ";\n";
  }
}

}  // namespace verilog
}  // namespace writer
}  // namespace iroha

#include "writer/verilog/dataflow_in.h"

#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "writer/module_template.h"
#include "writer/verilog/insn_writer.h"
#include "writer/verilog/module.h"
#include "writer/verilog/shared_reg.h"

namespace iroha {
namespace writer {
namespace verilog {

DataFlowIn::DataFlowIn(const IResource &res, const Table &table)
  : Resource(res, table) {
}

void DataFlowIn::BuildResource() {
}

void DataFlowIn::BuildInsn(IInsn *insn, State *st) {
  IResource *res = insn->GetResource();
  IResource *parent = res->GetParentResource();
  if (parent != nullptr &&
      resource::IsSharedReg(*(parent->GetClass()))) {
    int s = 0;
    for (int i = 0; i < insn->outputs_.size(); ++i) {
      ostream &ws = tmpl_->GetStream(kInsnWireValueSection);
      ws << "  assign " << InsnWriter::InsnOutputWireName(*insn, i)
	 << " = " << SharedReg::RegName(*parent);
      if (insn->outputs_.size() > 1) {
	IRegister *reg = insn->outputs_[i];
	int w = reg->value_type_.GetWidth();
	ws << "[" << (s + w - 1) << ":" << s << "]";
	s += w;
      }
      ws << ";\n";
    }
  }
}

}  // namespace verilog
}  // namespace writer
}  // namespace iroha

Allow dataflow-in to accept multiple values.


#include "AboutDarkThemePluginDialog.h"
#include "ui_AboutDarkThemePluginDialog.h"

using namespace libqdark;

AboutDarkThemePluginDialog::AboutDarkThemePluginDialog(QWidget* parent)
    : QDialog(parent)
    , ui(new Ui::AboutDarkThemePluginDialog)
{
    ui->setupUi(this);

    //ui->nameLabel->setText(m_ui->nameLabel->text() + " " + KEEPASSX_VERSION);

    auto nameLabelFont = ui->nameLabel->font();
    nameLabelFont.setBold(true);
    nameLabelFont.setPointSize(nameLabelFont.pointSize() + 4);
    ui->nameLabel->setFont(nameLabelFont);
}

AboutDarkThemePluginDialog::~AboutDarkThemePluginDialog() = default;

#include "AboutDarkThemePluginDialog.h"
#include "ui_AboutDarkThemePluginDialog.h"

#include <string>

using namespace libqdark;

AboutDarkThemePluginDialog::AboutDarkThemePluginDialog(QWidget* parent)
    : QDialog(parent)
    , ui(new Ui::AboutDarkThemePluginDialog)
{
    ui->setupUi(this);

    ui->nameLabel->setText(ui->nameLabel->text() + " " + LIBQDARK_VERSION);

    auto nameLabelFont = ui->nameLabel->font();
    nameLabelFont.setBold(true);
    nameLabelFont.setPointSize(nameLabelFont.pointSize() + 4);
    ui->nameLabel->setFont(nameLabelFont);

    QString commitHash;
    if (!QString(GIT_VERSION).isEmpty()) {
        commitHash = GIT_VERSION;
    }

    if (!commitHash.isEmpty()) {
        QString labelText = tr("Revision").append(": ").append(commitHash);
        ui->label_git->setText(labelText);
    }

    auto libs = QString("%1\n- Qt %2")
            .arg(ui->label_libs->text())
            .arg(QString::fromLocal8Bit(qVersion()));
    ui->label_libs->setText(libs);
}

AboutDarkThemePluginDialog::~AboutDarkThemePluginDialog() = default;

Add to about dialog info about current version


//#include <iostream>
#include SPECIFIC_HEADER

int main(int /*argc*/, char** /*argv*/)
{
  unsigned out {};
  constexpr unsigned num_runs = 1e7;
  for (unsigned run_id {} ; run_id != num_runs ; ++run_id)
  {
    out += most_significant_position(run_id);
  }
  //std::cout << out;
  bool success = out == unsigned(223222785);
  return !success;
}

//#include <iostream>
#include SPECIFIC_HEADER

int main(int /*argc*/, char** /*argv*/)
{
  unsigned out {};
  constexpr unsigned num_runs = 10000000;
  for (unsigned run_id {} ; run_id != num_runs ; ++run_id)
  {
    out += most_significant_position(run_id);
  }
  //std::cout << out;
  bool success = out == unsigned(223222785);
  return !success;
}

Fix compile double to unsigned


#include "Topology.hpp"
#include "Host.hpp"
#include "Hop.hpp"

using namespace std;

/*nmap -oX traceroute_all_subnet.xml -O -sV localhost*/
int main(int argc, char **argv)
{
  if(argc < 1)
  {
    cout << "Invalid number of program arguments: ";
    cout << "Usage ./build_topology <traceroute_file.xml>" << endl;
    exit(EXIT_FAILURE);
  }
  Host host(argv[1]);
  Hop hop(argv[2]);
  host.load();
  hop.load();
  host.print_vulnerabilities();
  cout << host.toJSON() << endl;
  cout << hop.toJSON() << endl;
  return 0;
}

#include "Topology.hpp"
#include "Host.hpp"
#include "Hop.hpp"
#include <fstream>

using namespace std;

/*nmap -oX traceroute_all_subnet.xml -O -sV localhost*/
int main(int argc, char **argv)
{
  if(argc < 1)
  {
    cout << "Invalid number of program arguments: ";
    cout << "Usage ./build_topology <traceroute_file.xml>" << endl;
    exit(EXIT_FAILURE);
  }
  Host host(argv[1]);
  Hop hop(argv[2]);
  host.load();
  hop.load();
  ofstream services, topology;
  services.open("services.json");
  topology.open("topology.json");
  //host.print_vulnerabilities();
  services << host.toJSON() << endl;
  topology << hop.toJSON() << endl;
  services.close();
  topology.close();
  return 0;
}

Write services and topology JSONs to file


#include <os>
#include "../x86_pc/idt.hpp"

void __arch_poweroff()
{
  asm("cli; hlt;");
  __builtin_unreachable();
}

void __platform_init()
{
  // setup CPU exception handlers
  x86::idt_initialize_for_cpu(0);
}

// not supported!
int64_t __arch_now() { return 0; }

void __arch_reboot(){}
void __arch_enable_legacy_irq(unsigned char){}
void __arch_disable_legacy_irq(unsigned char){}

void SMP::global_lock() noexcept {}
void SMP::global_unlock() noexcept {}
int SMP::cpu_id() noexcept { return 0; }
int SMP::cpu_count() noexcept { return 1; }

// Support for the boot_logger plugin.
__attribute__((weak))
bool os_enable_boot_logging = false;

#include <os>
#include "../x86_pc/idt.hpp"

void __arch_poweroff()
{
  asm("cli; hlt;");
  __builtin_unreachable();
}

void __platform_init()
{
  // setup CPU exception handlers
  x86::idt_initialize_for_cpu(0);
}

// not supported!
int64_t __arch_time_now() noexcept {
  return 0;
}

void __arch_reboot(){}
void __arch_enable_legacy_irq(unsigned char){}
void __arch_disable_legacy_irq(unsigned char){}

void SMP::global_lock() noexcept {}
void SMP::global_unlock() noexcept {}
int SMP::cpu_id() noexcept { return 0; }
int SMP::cpu_count() noexcept { return 1; }

// Support for the boot_logger plugin.
__attribute__((weak))
bool os_enable_boot_logging = false;

Fix arch_time_now wrong function name


#include "primitives.hpp"
#include "event.hpp"
#include "gen/includes.hpp"

namespace rubinius {
  bool Primitives::unknown_primitive(STATE, VMExecutable* exec, Task* task, Message& msg) {
    std::cout << "\n";
    state->print_backtrace();
    std::cout << "Called unbound/invalid primitive: " << *msg.name->to_str(state) <<"\n";
    abort();
  }

#include "gen/primitives_glue.gen.cpp"
}

#include "primitives.hpp"
#include "event.hpp"
#include "gen/includes.hpp"

namespace rubinius {
  bool Primitives::unknown_primitive(STATE, VMExecutable* exec, Task* task, Message& msg) {
    std::cout << "\n";
    state->print_backtrace();
    std::cout << "Called unbound or invalid primitive from: " << *msg.name->to_str(state) <<"\n";
    abort();
  }

#include "gen/primitives_glue.gen.cpp"
}

Improve error message about primitive failures


#include <Python.h>

#include "module_lock.h"

#include "classad/classad.h"

using namespace condor;

pthread_mutex_t ModuleLock::m_mutex = PTHREAD_MUTEX_INITIALIZER;

ModuleLock::ModuleLock()
    : m_release_gil(!classad::ClassAdGetExpressionCaching()),
      m_owned(false)
{
    acquire();
}

void
ModuleLock::acquire()
{
    if (m_release_gil && !m_owned)
    {
        m_save = PyEval_SaveThread();
        pthread_mutex_lock(&m_mutex);
        m_owned = true;
    }
}

ModuleLock::~ModuleLock()
{
    release();
}

void
ModuleLock::release()
{
    if (m_release_gil && m_owned)
    {
        pthread_mutex_unlock(&m_mutex);
        PyEval_RestoreThread(m_save);
    }
}

#include <Python.h>

#include "module_lock.h"

#include "classad/classad.h"

using namespace condor;

pthread_mutex_t ModuleLock::m_mutex = PTHREAD_MUTEX_INITIALIZER;

ModuleLock::ModuleLock()
    : m_release_gil(!classad::ClassAdGetExpressionCaching()),
      m_owned(false), m_save(0)
{
    acquire();
}

void
ModuleLock::acquire()
{
    if (m_release_gil && !m_owned)
    {
        m_save = PyEval_SaveThread();
        pthread_mutex_lock(&m_mutex);
        m_owned = true;
    }
}

ModuleLock::~ModuleLock()
{
    release();
}

void
ModuleLock::release()
{
    if (m_release_gil && m_owned)
    {
        pthread_mutex_unlock(&m_mutex);
        PyEval_RestoreThread(m_save);
    }
}

Fix minor coverity unitialized ptr warning


#include "test.h"
#include "vast/util/visitor.h"

struct base;
struct t1;
struct t2;

typedef vast::util::const_visitor<base, t1, t2> concrete_visitor;

struct base
{
  VAST_ACCEPT(concrete_visitor)
  VAST_ACCEPT_CONST(concrete_visitor)
};

struct t1 : base
{
  VAST_ACCEPT(concrete_visitor)
  VAST_ACCEPT_CONST(concrete_visitor)

  int i = 42;
};

struct t2 : base
{
  VAST_ACCEPT(concrete_visitor)
  VAST_ACCEPT_CONST(concrete_visitor)

  double d = 4.2;
};

struct printer : concrete_visitor
{
  virtual void visit(base const& x)
  {
    BOOST_CHECK(! "should not be invoked");
  }

  virtual void visit(t1 const& x)
  {
    BOOST_CHECK_EQUAL(x.i, 42);
  }

  virtual void visit(t2 const& x)
  {
    BOOST_CHECK_EQUAL(x.d, 4.2);
  }
};

BOOST_AUTO_TEST_CASE(visitor)
{
  t1 x;
  t2 y;

  base* b1 = &x;
  base* b2 = &y;

  printer p;
  b1->accept(p);
  b2->accept(p);
}

#include "test.h"
#include "vast/util/visitor.h"

struct base;
struct t1;
struct t2;

typedef vast::util::const_visitor<base, t1, t2> concrete_visitor;

struct base
{
  VAST_ACCEPT(concrete_visitor)
  VAST_ACCEPT_CONST(concrete_visitor)
};

struct t1 : base
{
  VAST_ACCEPT(concrete_visitor)
  VAST_ACCEPT_CONST(concrete_visitor)

  int i = 42;
};

struct t2 : base
{
  VAST_ACCEPT(concrete_visitor)
  VAST_ACCEPT_CONST(concrete_visitor)

  double d = 4.2;
};

struct printer : concrete_visitor
{
  virtual void visit(base const&)
  {
    BOOST_CHECK(! "should not be invoked");
  }

  virtual void visit(t1 const& x)
  {
    BOOST_CHECK_EQUAL(x.i, 42);
  }

  virtual void visit(t2 const& x)
  {
    BOOST_CHECK_EQUAL(x.d, 4.2);
  }
};

BOOST_AUTO_TEST_CASE(visitor)
{
  t1 x;
  t2 y;

  base* b1 = &x;
  base* b2 = &y;

  printer p;
  b1->accept(p);
  b2->accept(p);
}

Fix warning about unused parameter.


// Ensure that we have a quiet startup when we don't have the XRay
// instrumentation sleds.
//
// RUN: %clangxx -std=c++11 %s -o %t %xraylib
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1" %run %t 2>&1 | \
// RUN:    FileCheck %s --check-prefix NOISY
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=0" %run %t 2>&1 | \
// RUN:    FileCheck %s --check-prefix QUIET
// RUN: XRAY_OPTIONS="" %run %t 2>&1 | FileCheck %s --check-prefix DEFAULT
//
// FIXME: Understand how to make this work on other platforms
// REQUIRES: built-in-llvm-tree
// REQUIRES: x86_64-linux
#include <iostream>

using namespace std;

int main(int, char**) {
  // NOISY: {{.*}}XRay instrumentation map missing. Not initializing XRay.
  // QUIET-NOT: {{.*}}XRay instrumentation map missing. Not initializing XRay.
  // DEFAULT-NOT: {{.*}}XRay instrumentation map missing. Not initializing XRay.
  cout << "Hello, XRay!" << endl;
  // NOISY-NEXT: Hello, XRay!
  // QUIET: Hello, XRay!
  // DEFAULT: Hello, XRay!
}

// Ensure that we have a quiet startup when we don't have the XRay
// instrumentation sleds.
//
// RUN: %clangxx -std=c++11 %s -o %t %xraylib
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1" %run %t 2>&1 | \
// RUN:    FileCheck %s --check-prefix NOISY
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=0" %run %t 2>&1 | \
// RUN:    FileCheck %s --check-prefix QUIET
// RUN: XRAY_OPTIONS="" %run %t 2>&1 | FileCheck %s --check-prefix DEFAULT
//
// FIXME: Understand how to make this work on other platforms
// REQUIRES: built-in-llvm-tree
// REQUIRES: x86_64-linux
#include <iostream>

using namespace std;

int main(int, char**) {
  // NOISY: {{.*}}XRay instrumentation map missing. Not initializing XRay.
  // QUIET-NOT: {{.*}}XRay instrumentation map missing. Not initializing XRay.
  // DEFAULT-NOT: {{.*}}XRay instrumentation map missing. Not initializing XRay.
  cout << "Hello, XRay!" << endl;
  // NOISY: Hello, XRay!
  // QUIET: Hello, XRay!
  // DEFAULT: Hello, XRay!
}

Fix test to not be too strict with output order.


#include "DoorEntity.h"

DoorEntity::DoorEntity()
{
}

DoorEntity::~DoorEntity()
{
}

int DoorEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp)
{
	this->InitializeBase(entityID, pComp, gComp);

	this->m_isOpened = false;

	return 0;
}

int DoorEntity::Update(float dT, InputHandler * inputHandler)
{
	this->SyncComponents();

	return 0;
}

int DoorEntity::React(int entityID, EVENT reactEvent)
{
	if (reactEvent == EVENT::BUTTON_PRESSED)
	{
		if (!this->m_isOpened)
		{
			this->m_isOpened = true;
			this->m_pComp->PC_rotation = DirectX::XMVectorSet(0.f, 3.f, 0.f, 0.f);
		}
		else
		{
			this->m_isOpened = false;
			this->m_pComp->PC_rotation = DirectX::XMVectorSet(0.f, 0.f, 0.f, 0.f);
		}
	}

	return 0;
}

#include "DoorEntity.h"

DoorEntity::DoorEntity()
{
}

DoorEntity::~DoorEntity()
{
}

int DoorEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp)
{
	this->InitializeBase(entityID, pComp, gComp);

	this->m_isOpened = false;

	return 0;
}

int DoorEntity::Update(float dT, InputHandler * inputHandler)
{
	return 0;
}

int DoorEntity::React(int entityID, EVENT reactEvent)
{
	if (reactEvent == EVENT::BUTTON_PRESSED)
	{
		if (!this->m_isOpened)
		{
			this->m_isOpened = true;
			this->m_pComp->PC_rotation = DirectX::XMVectorSet(0.f, 3.f, 0.f, 0.f);
		}
		else
		{
			this->m_isOpened = false;
			this->m_pComp->PC_rotation = DirectX::XMVectorSet(0.f, 0.f, 0.f, 0.f);
		}
		this->SyncComponents();
	}

	return 0;
}

UPDATE moved component sync from update to react


#include <Pith/Config.hpp>
#include <Pith/Version.hpp>
#include <iostream>

extern "C" int pith_main(int argc, char** argv) {
	std::cout << "Pith version " << Pith::Version::STRING << " " << Pith::Version::COMMIT
		  << std::endl;
	return 0;
}

/// When no main is defined, pith defines a main that prints version information.
// int main (int argc, char** argv) __attribute__((weak alias("pith_main")));
#pragma weak main = pith_main

#include <Pith/Config.hpp>
#include <Pith/Version.hpp>
#include <iostream>

extern "C" auto pith_main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) -> int {
	std::cout << "Pith version " << Pith::Version::STRING << " " << Pith::Version::COMMIT
		  << std::endl;
	return 0;
}

/// When no main is defined, pith defines a main that prints version information.
// int main (int argc, char** argv) __attribute__((weak alias("pith_main")));
#pragma weak main = pith_main

Mark parameters of weak main as unused


#include <Halide.h>
#include <stdio.h>
#include <stdlib.h>

using namespace Halide;

int main() {
    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL))  {
        fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    Func f;
    Var x, y, c;

    f(x, y, c) = cast<uint8_t>(select(c == 0, 10*x + y,
                                      c == 1, 127, 12));

    Image<uint8_t> out(10, 10, 3);
    f.bound(c, 0, 3).glsl(x, y, c);
    f.realize(out);

    out.copy_to_host();
    for (int y=0; y<out.height(); y++) {
        for (int x=0; x<out.width(); x++) {
            if (!(out(x, y, 0) == 10*x+y && out(x, y, 1) == 127 && out(x, y, 2) == 12)) {
                fprintf(stderr, "Incorrect pixel (%d, %d, %d) at x=%d y=%d.\n",
                        out(x, y, 0), out(x, y, 1), out(x, y, 2),
                        x, y);
                return 1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}

#include <Halide.h>
#include <stdio.h>
#include <stdlib.h>

using namespace Halide;

int main() {
    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL))  {
        fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    Func f;
    Var x, y, c;

    f(x, y, c) = cast<uint8_t>(42);

    Image<uint8_t> out(10, 10, 3);
    f.bound(c, 0, 3).glsl(x, y, c);
    f.realize(out);

    out.copy_to_host();
    for (int y=0; y<out.height(); y++) {
        for (int x=0; x<out.width(); x++) {
            for (int z=0; x<out.channels(); x++) {
                if (!(out(x, y, z) == 42)) {
                    fprintf(stderr, "Incorrect pixel (%d) at x=%d y=%d z=%d.\n",
                            out(x, y, z), x, y, z);
                    return 1;
                }
            }
        }
    }

    printf("Success!\n");
    return 0;
}

Add a trivial write only GLSL test.


// RUN: %clang_cc1 -std=c++17 -verify -emit-llvm-only %s

// expected-no-diagnostics

template <class T> void bar(const T &t) { foo(t); }

template <class>
struct HasFriend {
  template <class T>
  friend void foo(const HasFriend<T> &m) noexcept(false);
};

template <class T>
void foo(const HasFriend<T> &m) noexcept(false) {}

void f() {
  HasFriend<int> x;
  foo(x);
  bar(x);
}

namespace PR39742 {
template<typename>
struct wrapper {
  template<typename>
  friend void friend_function_template() {}
};

wrapper<bool> x;
wrapper<int> y;
}

// RUN: %clang_cc1 -std=c++17 -verify -emit-llvm-only %s

// expected-no-diagnostics

template <class T> void bar(const T &t) { foo(t); }

template <class>
struct HasFriend {
  template <class T>
  friend void foo(const HasFriend<T> &m) noexcept(false);
};

template <class T>
void foo(const HasFriend<T> &m) noexcept(false) {}

void f() {
  HasFriend<int> x;
  foo(x);
  bar(x);
}

namespace PR39742 {
template<typename>
struct wrapper {
  template<typename>
  friend void friend_function_template() {}
};

wrapper<bool> x;
// FIXME: We should really error here because of the redefinition of
// friend_function_template.
wrapper<int> y;
}

Address a post-commit review comment on r348325.


/*
 * Copyright 2016 - 2019 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <cstdio>

#include "../media.hpp"

namespace nostalgia::core {

uint8_t *loadRom(const char *path) {
	auto file = fopen(path, "r");
	if (file) {
		fseek(file, 0, SEEK_END);
		const auto size = ftell(file);
		rewind(file);
		auto buff = new uint8_t[size];
		fread(buff, size, 1, file);
		fclose(file);
		return buff;
	} else {
		return nullptr;
	}
}

void unloadRom(uint8_t *rom) {
	delete rom;
}

}

/*
 * Copyright 2016 - 2019 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <fstream>

#include <ox/std/trace.hpp>

#include "../media.hpp"

namespace nostalgia::core {

uint8_t *loadRom(const char *path) {
	std::ifstream file(path, std::ios::binary | std::ios::ate);
	if (!file.good()) {
		oxTrace("nostalgia::core::userland::loadRom") << "Read failed:" << path;
		return nullptr;
	}

	const std::size_t size = file.tellg();
	file.seekg(0, std::ios::beg);
	auto buff = new uint8_t[size];
	file.read(reinterpret_cast<char*>(buff), size);
	return buff;
}

void unloadRom(uint8_t *rom) {
	delete rom;
}

}

Replace C file I/O with C++ file I/O to comply with handbook


#include "catch.hpp"
#include "../src/Board.h"

TEST_CASE("Board class tests", "[Board]")
{
  SECTION("The constructor properly sets width and height of the board")
  {
    const int desired_width = 11;
    const int desired_height = 12;
    Board b(desired_width, desired_height);
    REQUIRE(desired_width == b.width());
    REQUIRE(desired_height == b.height());
  }
}

#include "catch.hpp"
#include "../src/Board.h"

TEST_CASE("Board class tests", "[Board]")
{
  SECTION("The constructor properly sets width and height of the board")
  {
    const int desired_width = 11;
    const int desired_height = 12;
    Board b(desired_height, desired_width);
    REQUIRE(desired_height == b.height());
    REQUIRE(desired_width == b.width());
  }
}

Fix the order of parameters in Board class tests


#include <tightdb/row.hpp>
#include <tightdb/table.hpp>

using namespace std;
using namespace tightdb;

void RowBase::attach(Table* table, size_t row_ndx)
{
    if (table) {
        table->register_row_accessor(this); // Throws
        m_table.reset(table);
        m_row_ndx = row_ndx;
    }
}

void RowBase::reattach(Table* table, size_t row_ndx)
{
    if (m_table.get() != table) {
        if (table)
            table->register_row_accessor(this); // Throws
        if (m_table)
            m_table->unregister_row_accessor(this);
        m_table.reset(table);
    }
    m_row_ndx = row_ndx;
}

void RowBase::impl_detach() TIGHTDB_NOEXCEPT
{
    if (m_table) {
        m_table->unregister_row_accessor(this);
        m_table.reset();
    }
}

#include <tightdb/row.hpp>
#include <tightdb/table.hpp>

using namespace std;
using namespace tightdb;

void RowBase::attach(Table* table, size_t row_ndx)
{
    if (table) {
        table->register_row_accessor(this); // Throws
        m_table.reset(table);
        m_row_ndx = row_ndx;
    }
}

void RowBase::reattach(Table* table, size_t row_ndx)
{
    if (m_table.get() != table) {
        if (m_table)
            m_table->unregister_row_accessor(this);
        if (table)
            table->register_row_accessor(this); // Throws
        m_table.reset(table);
    }
    m_row_ndx = row_ndx;
}

void RowBase::impl_detach() TIGHTDB_NOEXCEPT
{
    if (m_table) {
        m_table->unregister_row_accessor(this);
        m_table.reset();
    }
}

Detach table accessors before attaching to a new table


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/cancellation_flag.h"

#include "base/logging.h"

namespace base {

void CancellationFlag::Set() {
#if !defined(NDEBUG)
  DCHECK(set_on_ == PlatformThread::CurrentId());
#endif
  base::subtle::Release_Store(&flag_, 1);
}

bool CancellationFlag::IsSet() const {
  return base::subtle::Acquire_Load(&flag_) != 0;
}

}  // namespace base

// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/cancellation_flag.h"

#include "base/logging.h"

namespace base {

void CancellationFlag::Set() {
#if !defined(NDEBUG)
  DCHECK_EQ(set_on_, PlatformThread::CurrentId());
#endif
  base::subtle::Release_Store(&flag_, 1);
}

bool CancellationFlag::IsSet() const {
  return base::subtle::Acquire_Load(&flag_) != 0;
}

}  // namespace base

Replace a DCHECK with DCHECK_EQ.


#include "SerialCommand.h"
#include "anyware_serial.h"

void unrecognized(const char *cmd)
{
  printError(F("unrecognized command"), cmd);
}

/*!
  RESET [<bool>]
*/
void reset_action()
{
  char *debugarg = sCmd.next();
  bool debug = false;
  if (debugarg) debug = atoi(debugarg);
  reset(debug);
}

/*!
  IDENTITY <userid>
*/
void identity_action()
{
  char *userarg = sCmd.next();
  if (!userarg) {
    printError(F("protocol error"), F("wrong # of parameters to IDENTITY"));
    return;
  }
  global_userid = getUserIdArg(userarg);
  // FIXME: Validity check?

  if (global_debug) {
    Serial.print(F("DEBUG Identity set, userid="));
    Serial.println(global_userid);
  }
}

void setupCommonCommands()
{
  sCmd.addCommand("RESET", reset_action);
  sCmd.addCommand("IDENTITY", identity_action);
  sCmd.setDefaultHandler(unrecognized);
}

#include "SerialCommand.h"
#include "anyware_serial.h"

void unrecognized(const char *cmd)
{
  printError(F("unrecognized command"), cmd);
}

/*!
  RESET [<bool>]
*/
void reset_action()
{
  char *debugarg = sCmd.next();
  bool debug = false;
  if (debugarg) debug = atoi(debugarg);
  reset(debug);
}

/*!
  IDENTITY <userid>
*/
void identity_action()
{
  char *userarg = sCmd.next();
  if (!userarg) {
    printError(F("protocol error"), F("wrong # of parameters to IDENTITY"));
    return;
  }
  uint8_t userid = getUserIdArg(userarg);
  if (userid > 2) {
    printError(F("protocol error"), F("Illegal userid argument"));
    return;
  }
  global_userid = userid;

  if (global_debug) {
    Serial.print(F("DEBUG Identity set, userid="));
    Serial.println(global_userid);
  }
}

void setupCommonCommands()
{
  sCmd.addCommand("RESET", reset_action);
  sCmd.addCommand("IDENTITY", identity_action);
  sCmd.setDefaultHandler(unrecognized);
}

Validate userid for IDENTITY command


#include "memory.h"

namespace EPITOME
{
	template <typename T>
	Room<T>::Room() {}

	template <typename T>
	Room<T>::~Room()
	{
		Empty();
	}

	template <typename T>
	Room<T>::Room(Room&& other)
	{
		items = other.items;
		other.items.clear();
	}

	template<typename T>
	void Room<T>::Add(T* item)
	{
		items.push_back(item);
	}

	template <typename T>
	void Room<T>::Empty()
	{
		for (T* a : items)
		{
			a->Dispose();
			delete a;
		}
		items.clear();
	}

	template <typename T>
	Disposable<T>::Disposable(T item)
	{
		this->item = item;
	}

	template <typename T>
	Disposable<T>::Dispose() {}
}

#include "memory.h"

namespace EPITOME
{
	template <typename T>
	Room<T>::Room() {}

	template <typename T>
	Room<T>::~Room()
	{
		Empty();
	}

	template <typename T>
	Room<T>::Room(Room&& other)
	{
		items = other.items;
		other.items.clear();
	}

	template<typename T>
	void Room<T>::Add(T* item)
	{
		items.push_back(item);
	}

	template <typename T>
	void Room<T>::Empty()
	{
		for (T* a : items)
		{
			a->Dispose();
			delete a;
		}
		items.clear();
	}

	template <typename T>
	Disposable<T>::Disposable(T item)
	{
		this->item = item;
	}

	template <typename T>
	void Disposable<T>::Dispose() {}
}

Add void to fix error


#include "core.h"
#include "main.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(main_tests)

BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
    uint64_t nSum = 0;
    for (int nHeight = 0; nHeight < 7000000; nHeight += 1000) {
        uint64_t nSubsidy = GetBlockValue(nHeight, 0);
        BOOST_CHECK(nSubsidy <= 50 * COIN);
        nSum += nSubsidy * 1000;
        BOOST_CHECK(MoneyRange(nSum));
    }
    BOOST_CHECK(nSum == 2099999997690000ULL);
}

BOOST_AUTO_TEST_SUITE_END()

#include "core.h"
#include "main.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(main_tests)

BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
    uint64_t nSum = 0;
    for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {
        uint64_t nSubsidy = GetBlockValue(nHeight, 0);
        BOOST_CHECK(nSubsidy <= 50 * COIN);
        nSum += nSubsidy * 1000;
        BOOST_CHECK(MoneyRange(nSum));
    }
    BOOST_CHECK(nSum == 2099999997690000ULL);
}

BOOST_AUTO_TEST_SUITE_END()

Edit subsidy_limit_test to account for BIP42


// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "v8.h"

#include "function-tester.h"

using namespace v8::internal;
using namespace v8::internal::compiler;

TEST(TurboSimpleDeopt) {
  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  FunctionTester T(
      "(function f(a) {"
      "var b = 1;"
      "if (!%IsOptimized()) return 0;"
      "%DeoptimizeFunction(f);"
      "if (%IsOptimized()) return 0;"
      "return a + b; })");

  T.CheckCall(T.Val(2), T.Val(1));
}

TEST(TurboTrivialDeopt) {
  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  FunctionTester T(
      "(function foo() {"
      "%DeoptimizeFunction(foo);"
      "return 1; })");

  T.CheckCall(T.Val(1));
}

// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/v8.h"

#include "test/cctest/compiler/function-tester.h"

using namespace v8::internal;
using namespace v8::internal::compiler;

TEST(TurboSimpleDeopt) {
  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  FunctionTester T(
      "(function f(a) {"
      "var b = 1;"
      "if (!%IsOptimized()) return 0;"
      "%DeoptimizeFunction(f);"
      "if (%IsOptimized()) return 0;"
      "return a + b; })");

  T.CheckCall(T.Val(2), T.Val(1));
}

TEST(TurboTrivialDeopt) {
  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  FunctionTester T(
      "(function foo() {"
      "%DeoptimizeFunction(foo);"
      "return 1; })");

  T.CheckCall(T.Val(1));
}

Fix relative include path in cctest case.


// Copyright 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ozone/ui/desktop_aura/desktop_factory_wayland.h"

#include "ozone/ui/desktop_aura/desktop_screen_wayland.h"
#include "ozone/ui/desktop_aura/desktop_window_tree_host_wayland.h"
#include "ozone/wayland/display.h"

namespace views {

DesktopFactoryWayland::DesktopFactoryWayland() : views::DesktopFactoryOzone(),
    desktop_screen_(NULL) {
  LOG(INFO) << "Ozone: DesktopFactoryWayland";
  DesktopFactoryOzone::SetInstance(this);
}

DesktopFactoryWayland::~DesktopFactoryWayland() {
  DesktopFactoryOzone::SetInstance(NULL);
  delete desktop_screen_;
}

DesktopWindowTreeHost* DesktopFactoryWayland::CreateWindowTreeHost(
    internal::NativeWidgetDelegate* native_widget_delegate,
    DesktopNativeWidgetAura* desktop_native_widget_aura) {
  return new DesktopWindowTreeHostWayland(native_widget_delegate,
                                          desktop_native_widget_aura);
}

gfx::Screen* DesktopFactoryWayland::CreateDesktopScreen() {
  if (!desktop_screen_) {
    desktop_screen_ = new DesktopScreenWayland();
    ozonewayland::WaylandDisplay::LookAheadOutputGeometry();
  }

  return desktop_screen_;
}

}  // namespace views

// Copyright 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ozone/ui/desktop_aura/desktop_factory_wayland.h"

#include "ozone/ui/desktop_aura/desktop_screen_wayland.h"
#include "ozone/ui/desktop_aura/desktop_window_tree_host_wayland.h"
#include "ozone/ui/gfx/ozone_display.h"

namespace views {

DesktopFactoryWayland::DesktopFactoryWayland() : views::DesktopFactoryOzone(),
    desktop_screen_(NULL) {
  LOG(INFO) << "Ozone: DesktopFactoryWayland";
  DesktopFactoryOzone::SetInstance(this);
}

DesktopFactoryWayland::~DesktopFactoryWayland() {
  DesktopFactoryOzone::SetInstance(NULL);
  delete desktop_screen_;
}

DesktopWindowTreeHost* DesktopFactoryWayland::CreateWindowTreeHost(
    internal::NativeWidgetDelegate* native_widget_delegate,
    DesktopNativeWidgetAura* desktop_native_widget_aura) {
  return new DesktopWindowTreeHostWayland(native_widget_delegate,
                                          desktop_native_widget_aura);
}

gfx::Screen* DesktopFactoryWayland::CreateDesktopScreen() {
  if (!desktop_screen_) {
    desktop_screen_ = new DesktopScreenWayland();
    gfx::OzoneDisplay::GetInstance()->LookAheadOutputGeometry();
  }

  return desktop_screen_;
}

}  // namespace views

Prepare to build desktop_aura/ as part of views only.


//
// Created by Timo on 18.04.2016.
//

#include <cmath>
#include "fixed_point.h"

fixed_point::fixed_point(float x) {
    q = x * std::pow(2, 16);
}

fixed_point::operator int() const {
    return q / std::pow(2, 16);
}

fixed_point::operator float() const {
    return q / std::pow(2, 16);
}

fixed_point abs(fixed_point fixedPoint) {
    float temp = (float) fixedPoint;
    if (temp >= 0) {
        return fixed_point(temp);
    } else {
        return fixed_point(-temp);
    }
}

bool fixed_point::operator==(fixed_point rhs) const {
    return q == rhs.q;
}

bool fixed_point::operator!=(fixed_point rhs) const {
    return q != rhs.q;
}

bool fixed_point::operator<(fixed_point rhs) const {
    return q < rhs.q;
}

bool fixed_point::operator>(fixed_point rhs) const {
    return q > rhs.q;
}

bool fixed_point::operator<=(fixed_point rhs) const {
    return q <= rhs.q;
}

bool fixed_point::operator>=(fixed_point rhs) const {
    return q >= rhs.q;
}

//
// Created by Timo on 18.04.2016.
//

#include <cmath>
#include "fixed_point.h"

fixed_point::fixed_point(float x) {
    q = x * std::pow(2, 16);
}

fixed_point::operator int() const {
    return q / std::pow(2, 16);
}

fixed_point::operator float() const {
    return q / std::pow(2, 16);
}

fixed_point abs(fixed_point fixedPoint) {
    if (fixedPoint >= 0) {
        return fixedPoint;
    } else {
        return -fixedPoint;
    }
}

bool fixed_point::operator==(fixed_point rhs) const {
    return q == rhs.q;
}

bool fixed_point::operator!=(fixed_point rhs) const {
    return q != rhs.q;
}

bool fixed_point::operator<(fixed_point rhs) const {
    return q < rhs.q;
}

bool fixed_point::operator>(fixed_point rhs) const {
    return q > rhs.q;
}

bool fixed_point::operator<=(fixed_point rhs) const {
    return q <= rhs.q;
}

bool fixed_point::operator>=(fixed_point rhs) const {
    return q >= rhs.q;
}

Update abs() to not use float.


#include <QtCore/QCoreApplication>
#include "signalwatcher.h"

static SignalWatcher* g_instance = 0;

SignalWatcher::SignalWatcher(void)
	: QObject(qApp)
{
}

bool SignalWatcher::watch(int sig)
{
	Q_UNUSED(sig)
	return false;
}

bool SignalWatcher::unwatch(int sig)
{
	Q_UNUSED(sig)
	return false;
}

SignalWatcher::~SignalWatcher(void)
{
	g_instance = 0;
}

SignalWatcher* SignalWatcher::instance(void)
{
	if (!g_instance) {
		g_instance = new SignalWatcher();
	}

	return g_instance;
}

#include <QtCore/QCoreApplication>
#include "signalwatcher.h"

class SignalWatcherPrivate {}

static SignalWatcher* g_instance = 0;

SignalWatcher::SignalWatcher(void)
	: QObject(qApp)
{
}

bool SignalWatcher::watch(int sig)
{
	Q_UNUSED(sig)
	return false;
}

bool SignalWatcher::unwatch(int sig)
{
	Q_UNUSED(sig)
	return false;
}

SignalWatcher::~SignalWatcher(void)
{
	g_instance = 0;
}

SignalWatcher* SignalWatcher::instance(void)
{
	if (!g_instance) {
		g_instance = new SignalWatcher();
	}

	return g_instance;
}

Fix for really weird compile time configurations


#include <Zmey/Components/TransformManager.h>

#include <nlohmann/json.hpp>

#include <Zmey/Components/ComponentRegistry.h>

namespace Zmey
{
namespace Components
{

void TransformComponentToBlob(const nlohmann::json& rawJson, IDataBlob& blob)
{
	//float position[3];
	//position[0] = rawJson["Position"][0];
	//position[1] = rawJson["Position"][1];
	//position[2] = rawJson["Position"][2];
	//blob.WriteData("Position", reinterpret_cast<uint8_t*>(position), sizeof(position));
	//
	//float rotation[4];
	//rotation[0] = rawJson["Rotation"][0];
	//rotation[1] = rawJson["Rotation"][1];
	//rotation[2] = rawJson["Rotation"][2];
	//rotation[2] = rawJson["Rotation"][3];
	//blob.WriteData("Rotation", reinterpret_cast<uint8_t*>(rotation), sizeof(rotation));
	//
	//float scale[3];
	//scale[0] = rawJson["Scale"][0];
	//scale[1] = rawJson["Scale"][1];
	//scale[2] = rawJson["Scale"][2];
	//blob.WriteData("Scale", reinterpret_cast<uint8_t*>(scale), sizeof(scale));
}

}
}
REGISTER_COMPONENT_MANAGER(Transform, nullptr, nullptr); // Replace with correct implementations

#include <Zmey/Components/TransformManager.h>

#include <nlohmann/json.hpp>

#include <Zmey/Components/ComponentRegistry.h>

namespace Zmey
{
namespace Components
{

void TransformComponentToBlob(const nlohmann::json& rawJson, IDataBlob& blob)
{
	float position[3];
	position[0] = rawJson["Position"][0];
	position[1] = rawJson["Position"][1];
	position[2] = rawJson["Position"][2];
	blob.WriteData("Position", reinterpret_cast<uint8_t*>(position), sizeof(position));

	float rotation[4];
	rotation[0] = rawJson["Rotation"][0];
	rotation[1] = rawJson["Rotation"][1];
	rotation[2] = rawJson["Rotation"][2];
	rotation[2] = rawJson["Rotation"][3];
	blob.WriteData("Rotation", reinterpret_cast<uint8_t*>(rotation), sizeof(rotation));

	float scale[3];
	scale[0] = rawJson["Scale"][0];
	scale[1] = rawJson["Scale"][1];
	scale[2] = rawJson["Scale"][2];
	blob.WriteData("Scale", reinterpret_cast<uint8_t*>(scale), sizeof(scale));
}

}
}
REGISTER_COMPONENT_MANAGER(Transform, &Zmey::Components::TransformComponentToBlob, nullptr); // Replace with correct implementations

Implement ComponentToBlob for the transform manager.


// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chrome_browser_main_aura.h"

#include "base/logging.h"

ChromeBrowserMainPartsAura::ChromeBrowserMainPartsAura(
    const MainFunctionParams& parameters) {
  NOTIMPLEMENTED();
}

void ChromeBrowserMainPartsAura::PreEarlyInitialization() {
  NOTIMPLEMENTED();
}

void ChromeBrowserMainPartsAura::PostMainMessageLoopStart() {
  NOTIMPLEMENTED();
}

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chrome_browser_main_aura.h"

#include "base/logging.h"

ChromeBrowserMainPartsAura::ChromeBrowserMainPartsAura(
    const MainFunctionParams& parameters)
  : ChromeBrowserMainParts(parameters) {
  NOTIMPLEMENTED();
}

void ChromeBrowserMainPartsAura::PreEarlyInitialization() {
  NOTIMPLEMENTED();
}

void ChromeBrowserMainPartsAura::PostMainMessageLoopStart() {
  NOTIMPLEMENTED();
}

Fix Aura compile error. My bad.


#define BOOST_ERROR_CODE_HEADER_ONLY
#include <Combaseapi.h>
#include <boost/system/error_code.hpp>

#define BOOST_ERROR_CODE_HEADER_ONLY
#include <boost/system/error_code.hpp>

Remove (unnecessary) win32 only header.


/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SKNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW(SkNWayCanvas);
}

/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SKNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW(SkNWayCanvas(0,0));
}

Fix SkNWayCanvas cons call when creating null canvas.


#include "mytablemodel.h"

int MyTableModel::rowCount(const QModelIndex &parent) const
{
    return m_data.size();
}

int MyTableModel::columnCount(const QModelIndex &parent) const
{
    return 2;
}

QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
    Record const& dataElem = m_data[index.row()];

    if (index.column() == 0)
        return QVariant(dataElem.label);
    else
        return QVariant(dataElem.number);
}

bool MyTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    return false;
}

Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
    return Qt::ItemFlags();
}

void MyTableModel::insertRow()
{
    m_data.push_back({ "label", 0 });
}

#include "mytablemodel.h"

int MyTableModel::rowCount(const QModelIndex &parent) const
{
    return m_data.size();
}

int MyTableModel::columnCount(const QModelIndex &parent) const
{
    return 2;
}

QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
    Record const& dataElem = m_data[index.row()];

    if (index.column() == 0)
        return QVariant(dataElem.label);
    else
        return QVariant(dataElem.number);
}

bool MyTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    return false;
}

Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
    return Qt::ItemFlags();
}

void MyTableModel::insertRow()
{
    m_data.push_back({ "label", 0 });
    emit layoutChanged();
}

Update table view on add row


#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;

typedef TestBaseWithParam< pair<string, string> > ImagePair;

pair<string, string> impair(const char* im1, const char* im2)
{
    return make_pair(string(im1), string(im2));
}

PERF_TEST_P(ImagePair, OpticalFlowDual_TVL1, testing::Values(impair("cv/optflow/RubberWhale1.png", "cv/optflow/RubberWhale2.png")))
{
    declare.time(40);

    Mat frame1 = imread(getDataPath(GetParam().first), IMREAD_GRAYSCALE);
    Mat frame2 = imread(getDataPath(GetParam().second), IMREAD_GRAYSCALE);
    ASSERT_FALSE(frame1.empty());
    ASSERT_FALSE(frame2.empty());

    Mat flow;

    OpticalFlowDual_TVL1 tvl1;

    TEST_CYCLE()
    {
        tvl1(frame1, frame2, flow);
    }

    SANITY_CHECK(flow);
}

#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;

typedef TestBaseWithParam< pair<string, string> > ImagePair;

pair<string, string> impair(const char* im1, const char* im2)
{
    return make_pair(string(im1), string(im2));
}

PERF_TEST_P(ImagePair, OpticalFlowDual_TVL1, testing::Values(impair("cv/optflow/RubberWhale1.png", "cv/optflow/RubberWhale2.png")))
{
    declare.time(40);

    Mat frame1 = imread(getDataPath(GetParam().first), IMREAD_GRAYSCALE);
    Mat frame2 = imread(getDataPath(GetParam().second), IMREAD_GRAYSCALE);
    ASSERT_FALSE(frame1.empty());
    ASSERT_FALSE(frame2.empty());

    Mat flow;

    OpticalFlowDual_TVL1 tvl1;

    TEST_CYCLE()
    {
        tvl1(frame1, frame2, flow);
    }

    SANITY_CHECK(flow, 0.02);
}

Set sanity threshold for TVL1 optical flow to 0.02