// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "search_session.h"
#include "match_tools.h"
#include "match_context.h"

namespace proton::matching {

SearchSession::SearchSession(const SessionId &id, fastos::TimeStamp time_of_doom,
                             std::unique_ptr<MatchToolsFactory> match_tools_factory,
                             OwnershipBundle &&owned_objects)
    : _session_id(id),
      _create_time(fastos::ClockSystem::now()),
      _time_of_doom(time_of_doom),
      _owned_objects(std::move(owned_objects)),
      _match_tools_factory(std::move(match_tools_factory))
{
}

void
SearchSession::releaseEnumGuards() {
    _owned_objects.context->releaseEnumGuards();
}

SearchSession::~SearchSession() { }

SearchSession::OwnershipBundle::OwnershipBundle() { }
SearchSession::OwnershipBundle::~OwnershipBundle() { }

}

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "search_session.h"
#include "match_tools.h"
#include "match_context.h"

namespace proton::matching {

SearchSession::SearchSession(const SessionId &id, fastos::TimeStamp time_of_doom,
                             std::unique_ptr<MatchToolsFactory> match_tools_factory,
                             OwnershipBundle &&owned_objects)
    : _session_id(id),
      _create_time(fastos::ClockSystem::now()),
      _time_of_doom(time_of_doom),
      _owned_objects(std::move(owned_objects)),
      _match_tools_factory(std::move(match_tools_factory))
{
}

void
SearchSession::releaseEnumGuards() {
    _owned_objects.context->releaseEnumGuards();
}

SearchSession::~SearchSession() { }

SearchSession::OwnershipBundle::OwnershipBundle() = default;
SearchSession::OwnershipBundle::~OwnershipBundle() { }

}

Use = default for default constructor.


#include "BaseString.hpp"

// Apparently, strdup isn't a standard function, and isn't in <cstring>
char* strdup(const char *s) throw () {
  auto n = strlen(s);
  auto d = new char[n + 1];
  return static_cast<char*>(memcpy(d, s, n + 1));
}

namespace K3 {
  template<>
  std::size_t hash_value<K3::base_string>(const K3::base_string& s) {
    std::size_t seed = 0;
    for (auto& i: s) {
      boost::hash_combine(seed, i);
    }
    return seed;
  }
}

#include "BaseString.hpp"

// Apparently, strdup isn't a standard function, and isn't in <cstring>
char* strdup(const char *s) throw () {
  if (!s) {
    return nullptr;
  }

  auto n = strlen(s);
  auto d = new char[n + 1];
  return static_cast<char*>(memcpy(d, s, n + 1));
}

namespace K3 {
  template<>
  std::size_t hash_value<K3::base_string>(const K3::base_string& s) {
    std::size_t seed = 0;
    for (auto& i: s) {
      boost::hash_combine(seed, i);
    }
    return seed;
  }
}

Fix strdup behavior on nullptr.


// index_queue.cc
// Copyright (c) 2014 Jinglei Ren <jinglei@ren.systems>

#include "index_queue.h"

void IndexQueue::Remove(int i) {
  assert(i >= 0);
  const int prev = array_[i].first;
  const int next = array_[i].second;

  if (prev == -EINVAL) {
    assert(Front() == i);
    SetFront(next);
  } else {
    array_[prev].second = next;
  }

  if (next == -EINVAL) {
    assert(Back() == i);
    SetBack(prev);
  } else {
    array_[next].first = prev;
  }

  array_[i].first = -EINVAL;
  array_[i].second = -EINVAL;

  --length_;
}

void IndexQueue::PushBack(int i) {
  if (Empty()) {
    array_[i].first = array_[i].second = -EINVAL;
    SetFront(i);
    SetBack(i);
  } else {
    array_[i].first = Back();
    array_[i].second = -EINVAL;
    BackNode().second = i;
    SetBack(i);
  }

  ++length_;
}

void IndexQueue::Accept(QueueVisitor* visitor) {
  int i = Front();
  while (i != -EINVAL) {
    visitor->Visit(i);
    i = array_[i].second;
  }
}

// index_queue.cc
// Copyright (c) 2014 Jinglei Ren <jinglei@ren.systems>

#include "index_queue.h"

using namespace std;
void IndexQueue::Remove(int i) {
  assert(i >= 0);
  const int prev = array_[i].first;
  const int next = array_[i].second;

  if (prev == -EINVAL) {
    assert(Front() == i);
    SetFront(next);
  } else {
    array_[prev].second = next;
  }

  if (next == -EINVAL) {
    assert(Back() == i);
    SetBack(prev);
  } else {
    array_[next].first = prev;
  }

  array_[i].first = -EINVAL;
  array_[i].second = -EINVAL;

  --length_;
}

void IndexQueue::PushBack(int i) {
  if (Empty()) {
    array_[i].first = array_[i].second = -EINVAL;
    SetFront(i);
    SetBack(i);
  } else {
    array_[i].first = Back();
    array_[i].second = -EINVAL;
    BackNode().second = i;
    SetBack(i);
  }

  ++length_;
}

void IndexQueue::Accept(QueueVisitor* visitor) {
  int i = Front();
  int tmp;
  while (i != -EINVAL) {
    tmp = array_[i].second;
    visitor->Visit(i);
    i = tmp;
  }
}

Fix bug: visitor to IndexQueue may have side effects on first/second.


#include "gtest/gtest.h"

#include "test/support.hpp"

namespace fgt {

TEST(DirectTree, MatchesDirect) {
    auto source = load_ascii_test_matrix("X.txt");
    auto target = load_ascii_test_matrix("Y.txt");
    auto expected = direct(source, target, 0.5);
    auto actual = direct_tree(source, target, 0.5, 1e-4);
    EXPECT_TRUE(actual.isApprox(expected, 1e-4));
}

TEST(DirectTree, WithWeights) {
    auto source = load_ascii_test_matrix("X.txt");
    auto target = load_ascii_test_matrix("Y.txt");
    Vector weights = Vector::LinSpaced(source.rows(), 0.1, 0.9);
    auto expected = direct(source, target, 0.5, weights);
    auto actual = direct_tree(source, target, 0.5, 1e-4, weights);
    EXPECT_TRUE(expected.isApprox(actual));
}

TEST(DirectTree, ClassBased) {
    auto source = load_ascii_test_matrix("X.txt");
    auto target = load_ascii_test_matrix("Y.txt");
    auto expected = direct(source, target, 0.5);
    auto actual = DirectTree(source, 0.5, 1e-4).compute(target);
    EXPECT_TRUE(actual.isApprox(expected, 1e-4));
}
}

#include "gtest/gtest.h"

#include "test/support.hpp"

namespace fgt {

TEST(DirectTree, MatchesDirect) {
    auto source = load_ascii_test_matrix("X.txt");
    auto target = load_ascii_test_matrix("Y.txt");
    double bandwidth = 0.5;
    auto expected = direct(source, target, bandwidth);
    double epsilon = 1e-4;
    auto actual = direct_tree(source, target, bandwidth, epsilon);
    EXPECT_LT((expected - actual).array().abs().maxCoeff() / actual.size(), epsilon);
}

TEST(DirectTree, WithWeights) {
    auto source = load_ascii_test_matrix("X.txt");
    auto target = load_ascii_test_matrix("Y.txt");
    Vector weights = Vector::LinSpaced(source.rows(), 0.1, 0.9);
    double bandwidth = 0.5;
    auto expected = direct(source, target, bandwidth, weights);
    double epsilon = 1e-4;
    auto actual = direct_tree(source, target, bandwidth, epsilon, weights);
    EXPECT_LT((expected - actual).array().abs().maxCoeff() / weights.sum(), epsilon);
}

TEST(DirectTree, ClassBased) {
    auto source = load_ascii_test_matrix("X.txt");
    auto target = load_ascii_test_matrix("Y.txt");
    double bandwidth = 0.5;
    auto expected = direct(source, target, bandwidth);
    double epsilon = 1e-4;
    auto actual = DirectTree(source, bandwidth, epsilon).compute(target);
    EXPECT_LT((expected - actual).array().abs().maxCoeff() / actual.size(), epsilon);
}
}

Test epsilon in direct tree


#include "gtest/gtest.h"
#include "Ant.h"

TEST(AntTest, NewAntIsAlive)
{
	Ant a1;
	EXPECT_EQ(true, a1.isAlive());
}

TEST(AntTest, NewAntIsAgeZero)
{
	Ant a1;
	EXPECT_EQ(0, a1.getAge());
}

TEST(AntTest, AntAgesAfterUpdate)
{
	Ant a1;
	a1.update();
	EXPECT_EQ(1, a1.getAge());
}

TEST(AntTest, AntDiesAfterMaxAge)
{
	Ant a1;
	for(int i=0; i < Ant::MAX_AGE; ++i)
	{
		a1.update();
	}
	EXPECT_FALSE(a1.isAlive());
}

int main(int argc, char **argv)
{
	::testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}

#include "gtest/gtest.h"
#include "Ant.h"

TEST(AntTest, NewAntIsAlive)
{
	Ant a1;
	EXPECT_TRUE(a1.isAlive());
}

TEST(AntTest, NewAntIsAgeZero)
{
	Ant a1;
	EXPECT_EQ(0, a1.getAge());
}

TEST(AntTest, AntAgesAfterUpdate)
{
	Ant a1;
	a1.update();
	EXPECT_EQ(1, a1.getAge());
}

TEST(AntTest, AntDiesAfterMaxAge)
{
	Ant a1;
	for(int i=0; i < Ant::MAX_AGE; ++i)
	{
		a1.update();
	}
	EXPECT_FALSE(a1.isAlive());
}

int main(int argc, char **argv)
{
	::testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}

Switch to using EXPECT_TRUE instead of EXPECT_EQ


// An Homage to Vera Molnar's "An Homange to Durer"
SquareSize = [[Square Size]]
gridHeight = [[Grid Height]]
gridWidth = [[Grid Width]]

columnCounter = [[shiftCounter]]
rowCounter = [[rowCounter]]

if(columnCounter < [[gridWidth]]) {
  drawVeraLines([[columnCounter]], [[rowCounter]])
  columnCounter++;
} else if ([[rowCounter]] < [[gridHeight]]) {
  columnCounter = 0;
  rowCounter++;
} else {
  rowCounter = 0;
  columnCounter = 0;
}

// An homage to Vera Molnar's "Hommage a Durer"
SquareSize = [[Square Size]]
gridHeight = [[Grid Height]]
gridWidth = [[Grid Width]]

columnCounter = [[shiftCounter]]
rowCounter = [[rowCounter]]

if(columnCounter < [[gridWidth]]) {
  drawVeraLines([[columnCounter]], [[rowCounter]])
  columnCounter++;
} else if ([[rowCounter]] < [[gridHeight]]) {
  columnCounter = 0;
  rowCounter++;
} else {
  rowCounter = 0;
  columnCounter = 0;
}

Fix typo in pseudocode comment


#include "TextureAtlas.h"

TextureAtlas::TextureAtlas(const std::string& textureFileName)
{
    sf::Image i;
    if (!i.loadFromFile("Res/Textures/" + textureFileName + ".png"))
    {
        throw std::runtime_error("Unable to open image: " + textureFileName);
    }
    loadFromImage(i);

    m_imageSize             = 256;
    m_individualTextureSize = 16;
}

std::array<GLfloat, 8> TextureAtlas::getTexture(const sf::Vector2i& coords)
{
    static const GLfloat TEX_PER_ROW      = (GLfloat)m_imageSize / (GLfloat)m_individualTextureSize;
    static const GLfloat INDV_TEX_SIZE    = 1.0f / TEX_PER_ROW;
    static const GLfloat PIXEL_SIZE       = 1.0f / (float)m_imageSize;

    GLfloat xMin = (coords.x * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
    GLfloat yMin = (coords.y * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;

    GLfloat xMax = (xMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
    GLfloat yMax = (yMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;

    return
    {
        xMax, yMax,
        xMin, yMax,
        xMin, yMin,
        xMax, yMin
    };
}

#include "TextureAtlas.h"
#include <array>

TextureAtlas::TextureAtlas(const std::string& textureFileName)
{
    sf::Image i;
    if (!i.loadFromFile("Res/Textures/" + textureFileName + ".png"))
    {
        throw std::runtime_error("Unable to open image: " + textureFileName);
    }
    loadFromImage(i);

    m_imageSize             = 256;
    m_individualTextureSize = 16;
}

std::array<GLfloat, 8> TextureAtlas::getTexture(const sf::Vector2i& coords)
{
    static const GLfloat TEX_PER_ROW      = (GLfloat)m_imageSize / (GLfloat)m_individualTextureSize;
    static const GLfloat INDV_TEX_SIZE    = 1.0f / TEX_PER_ROW;
    static const GLfloat PIXEL_SIZE       = 1.0f / (float)m_imageSize;

    GLfloat xMin = (coords.x * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;
    GLfloat yMin = (coords.y * INDV_TEX_SIZE) + 0.5 * PIXEL_SIZE;

    GLfloat xMax = (xMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;
    GLfloat yMax = (yMin + INDV_TEX_SIZE) - 0.5 * PIXEL_SIZE;

    return
    {
        xMax, yMax,
        xMin, yMax,
        xMin, yMin,
        xMax, yMin
    };
}

Fix to compile on MacOSX


#include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
#include <qplatformdefs.h>

#include <LunaWebView.h>

#if defined(MEEGO_EDITION_HARMATTAN)
    #include <MDeclarativeCache>
    #define NEW_QAPPLICATION(x, y) MDeclarativeCache::qApplication((x), (y))
    Q_DECL_EXPORT
#else
    #define NEW_QAPPLICATION(x, y) new QApplication((x), (y))
#endif

int main(int argc, char** argv)
{
    QApplication* app = NEW_QAPPLICATION(argc, argv);

    qmlRegisterType<LunaWebView>("Luna", 1, 0, "LunaWebView");

    QDeclarativeView viewer;
#if defined(MEEGO_EDITION_HARMATTAN)
    viewer.setSource(QUrl("qrc:/qml/main-harmattan.qml"));
    viewer.showFullScreen();
#else
    viewer.setSource(QUrl("qrc:/qml/main-desktop.qml"));
    viewer.show();
#endif

    return app->exec();
}

#include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
#include <QScopedPointer>
#include <qplatformdefs.h>

#include <LunaWebView.h>

#if defined(MEEGO_EDITION_HARMATTAN)
    #include <MDeclarativeCache>
    #define NEW_QAPPLICATION(x, y) MDeclarativeCache::qApplication((x), (y))
    Q_DECL_EXPORT
#else
    #define NEW_QAPPLICATION(x, y) new QApplication((x), (y))
#endif

int main(int argc, char** argv)
{
    QScopedPointer<QApplication> app(NEW_QAPPLICATION(argc, argv));

    qmlRegisterType<LunaWebView>("Luna", 1, 0, "LunaWebView");

    QDeclarativeView viewer;
#if defined(MEEGO_EDITION_HARMATTAN)
    viewer.setSource(QUrl("qrc:/qml/main-harmattan.qml"));
    viewer.showFullScreen();
#else
    viewer.setSource(QUrl("qrc:/qml/main-desktop.qml"));
    viewer.show();
#endif

    return app->exec();
}

Delete qApp instance on exit.


// File: btBoostWrapper.cpp
#ifndef _btBoostWrapper_cpp
#define _btBoostWrapper_cpp

#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wreorder"

#include <boost/python.hpp>
#include <btBoost/btBoostLinearMath.hpp>
#include <btBoost/btBoostDynamics.hpp>

using namespace boost::python;

BOOST_PYTHON_MODULE(bullet)
{
    defineLinearMath();
    defineDynamics();
}

#endif // _btBoostWrapper_cpp

// File: btBoostWrapper.cpp
#ifndef _btBoostWrapper_cpp
#define _btBoostWrapper_cpp

#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wreorder"

#include <boost/python.hpp>
#include <btBoost/btBoostLinearMath.hpp>
#include <btBoost/btBoostDynamics.hpp>
#include <btBoost/btBoostHello.hpp>

using namespace boost::python;

BOOST_PYTHON_MODULE(bullet)
{
    defineHello();
    defineLinearMath();
    defineDynamics();
}

#endif // _btBoostWrapper_cpp

Define a simple hello method for scratch testing


// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -verify -fsyntax-only -std=c++11 -fms-extensions %s

#if !__has_feature(attribute_deprecated_with_replacement)
#error "Missing __has_feature"
#endif

int a1 [[deprecated("warning", "fixit")]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
int a2 [[deprecated("warning", 1)]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}

int b1 [[gnu::deprecated("warning", "fixit")]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
int b2 [[gnu::deprecated("warning", 1)]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}

__declspec(deprecated("warning", "fixit")) int c1; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
__declspec(deprecated("warning", 1)) int c2; // expected-error{{'deprecated' attribute takes no more than 1 argument}}

int d1 __attribute__((deprecated("warning", "fixit")));
int d2 __attribute__((deprecated("warning", 1))); // expected-error{{'deprecated' attribute requires a string}}

// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -verify -fsyntax-only -std=c++11 -fms-extensions %s

#if !__has_feature(attribute_deprecated_with_replacement)
#error "Missing __has_feature"
#endif

int a1 [[deprecated("warning", "fixit")]]; // expected-warning{{use of the 'deprecated' attribute is a C++14 extension}} expected-error{{'deprecated' attribute takes no more than 1 argument}}
int a2 [[deprecated("warning", 1)]]; // expected-warning{{use of the 'deprecated' attribute is a C++14 extension}} expected-error{{'deprecated' attribute takes no more than 1 argument}}

int b1 [[gnu::deprecated("warning", "fixit")]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
int b2 [[gnu::deprecated("warning", 1)]]; // expected-error{{'deprecated' attribute takes no more than 1 argument}}

__declspec(deprecated("warning", "fixit")) int c1; // expected-error{{'deprecated' attribute takes no more than 1 argument}}
__declspec(deprecated("warning", 1)) int c2; // expected-error{{'deprecated' attribute takes no more than 1 argument}}

int d1 __attribute__((deprecated("warning", "fixit")));
int d2 __attribute__((deprecated("warning", 1))); // expected-error{{'deprecated' attribute requires a string}}

Update testing case on swift-3.0 branch.


// 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 "base/message_loop.h"
#include "base/perf_test_suite.h"
#include "chrome/common/chrome_paths.cc"

int main(int argc, char **argv) {
  chrome::RegisterPathProvider();
  MessageLoop main_message_loop;

  return PerfTestSuite(argc, argv).Run();
}

// 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 "base/message_loop.h"
#include "base/perf_test_suite.h"
#include "chrome/common/chrome_paths.cc"

int main(int argc, char **argv) {
  PerfTestSuite suite(argc, argv);
  chrome::RegisterPathProvider();
  MessageLoop main_message_loop;

  return suite.Run();
}

Fix error [FATAL:at_exit.cc(40)] Check failed: false. Tried to RegisterCallback without an AtExitManager in (possibly unused) binary perf_tests


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

#include "impl/external_commit_helper.hpp"

#include "impl/realm_coordinator.hpp"

#include <realm/commit_log.hpp>
#include <realm/replication.hpp>

using namespace realm;
using namespace realm::_impl;

ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent)
{
}

ExternalCommitHelper::~ExternalCommitHelper()
{
}

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

#include "impl/external_commit_helper.hpp"

#include "impl/realm_coordinator.hpp"

#include <realm/commit_log.hpp>
#include <realm/replication.hpp>

using namespace realm;
using namespace realm::_impl;

ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent)
//: m_parent(parent)
//, m_history(realm::make_client_history(parent.get_path(), parent.get_encryption_key().data()))
//, m_sg(*m_history, parent.is_in_memory() ? SharedGroup::durability_MemOnly : SharedGroup::durability_Full,
//       parent.get_encryption_key().data())
//, m_thread(std::async(std::launch::async, [=] {
//    m_sg.begin_read();
//    while (m_sg.wait_for_change()) {
//        m_sg.end_read();
//        m_sg.begin_read();
//        m_parent.on_change();
//    }
//}))
{
}

ExternalCommitHelper::~ExternalCommitHelper()
{
    //m_sg.wait_for_change_release();
    //m_thread.wait(); // Wait for the thread to exit
}

Change generic external commit helper to just be commented out for now


#include "Thread/Win/MutexImpl.hh"
#include "Thread/ThreadException.hh"

namespace LilWrapper
{
  MutexImpl::MutexImpl()
  {
    InitializeCriticalSection(&this->_mutex);
  }

  MutexImpl::~MutexImpl()
  {
    DeleteCriticalSection(&this->_mutex);
  }

  void MutexImpl::lock()
  {
    EnterCriticalSection(&this->_mutex);
  }

  void MutexImpl::unlock()
  {
    LeaveCriticalSection(&this->_mutex);
  }

  bool MutexImpl::trylock()
  {

  }
}

#include "Thread/Win/MutexImpl.hh"
#include "Thread/ThreadException.hh"

namespace LilWrapper
{
  MutexImpl::MutexImpl()
  {
    InitializeCriticalSection(&this->_mutex);
  }

  MutexImpl::~MutexImpl()
  {
    DeleteCriticalSection(&this->_mutex);
  }

  void MutexImpl::lock()
  {
    EnterCriticalSection(&this->_mutex);
  }

  void MutexImpl::unlock()
  {
    LeaveCriticalSection(&this->_mutex);
  }

  bool MutexImpl::trylock()
  {
    return (TryEnterCriticalSection(&this->_mutex) != 0);
  }
}

Add trylock in Windows implementation of mutex.


// 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 "chrome/browser/extensions/extension_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

// 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 "chrome/browser/extensions/extension_apitest.h"

// Started failing with r29947. WebKit merge 49961:49992.
IN_PROC_BROWSER_TEST_F(DISABLED_ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

Disable test failing since r29947.


#include "histogram.h"
#include <QPainter>
#include <QDebug>

Histogram::Histogram(QWidget* p) :QWidget(p) {
}
void
Histogram::setData(const QList<QPair<QString,quint32> >& d) {
    data = d;
    update();
}
typedef QPair<QString, quint32> StringUIntPair;
void
Histogram::paintEvent(QPaintEvent *) {
    if (data.size() == 0) return;
    int w = width();
    int h = height();
    int m = 5;
    int bw = (w-m*(data.size()-1))/data.size();
    uint max = 0;
    foreach (const StringUIntPair& p, data) {
        if (p.second > max) max = p.second;
    }
    QPainter painter(this);
    painter.setPen(palette().highlightedText().color());
    int offset = 0;
    painter.rotate(-90);
    painter.translate(-h, 0);
    foreach (const StringUIntPair& p, data) {
        int bh = p.second*h/max;
        painter.fillRect(0, offset, bh, bw, palette().highlight());
        painter.drawText(QRect(m, offset, bh-m, bw), Qt::AlignVCenter,
            p.first);
        offset += bw + m;
    }
}

#include "histogram.h"
#include <QPainter>
#include <QDebug>

Histogram::Histogram(QWidget* p) :QWidget(p) {
}
void
Histogram::setData(const QList<QPair<QString,quint32> >& d) {
    data = d;
    update();
}
typedef QPair<QString, quint32> StringUIntPair;
void
Histogram::paintEvent(QPaintEvent *) {
    if (data.size() == 0) return;
    int w = width();
    int h = height();
    int m = 5;
    int bw = (w-m*(data.size()-1))/data.size();
    uint max = 0;
    foreach (const StringUIntPair& p, data) {
        if (p.second > max) max = p.second;
    }
    QPainter painter(this);
    painter.setPen(palette().highlightedText().color());
    qreal offset = 0;
    painter.rotate(-90);
    painter.translate(-h, 0);
    foreach (const StringUIntPair& p, data) {
        qreal bh = p.second*h/(qreal)max;
        painter.fillRect(QRectF(0, offset, bh, bw), palette().highlight());
        painter.drawText(QRectF(m, offset, bh-m, bw), Qt::AlignVCenter,
            p.first);
        offset += bw + m;
    }
}

Use qreal instead of int for painting.


/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <iostream>
#include <qi/log.hpp>

#include <qimessaging/session.hpp>
#include <qimessaging/url.hpp>
#include "transportserver_p.hpp"
#include "transportserverdummy_p.hpp"

namespace qi
{
  bool TransportServerDummyPrivate::listen()
  {
    qiLogWarning("TransportServer") << "listen: You are currently running on dummy"
                                    << " TransportServer!";
    return true;
  }

  void TransportServerDummyPrivate::close()
  {
  }

  TransportServerDummyPrivate::TransportServerDummyPrivate(TransportServer* self,
                                                           const qi::Url &url,
                                                           EventLoop* ctx)
    : TransportServerPrivate(self, url, ctx)
  {
  }

  void TransportServerDummyPrivate::destroy()
  {
    delete this;
  }
  TransportServerDummyPrivate::~TransportServerDummyPrivate()
  {
  }
}

/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <iostream>
#include <qi/log.hpp>

#include <qimessaging/session.hpp>
#include <qimessaging/url.hpp>
#include "transportserver_p.hpp"
#include "transportserverdummy_p.hpp"

namespace qi
{
  bool TransportServerDummyPrivate::listen()
  {
    qiLogWarning("TransportServer") << "listen: You are currently running on dummy"
                                    << " TransportServer!";
    return true;
  }

  void TransportServerDummyPrivate::close()
  {
    qiLogVerbose("TransportServer") << "close: You are currently running on dummy"
                                    << " TransportServer!";
  }

  TransportServerDummyPrivate::TransportServerDummyPrivate(TransportServer* self,
                                                           const qi::Url &url,
                                                           EventLoop* ctx)
    : TransportServerPrivate(self, url, ctx)
  {
  }

  void TransportServerDummyPrivate::destroy()
  {
    delete this;
  }
  TransportServerDummyPrivate::~TransportServerDummyPrivate()
  {
  }
}

Revert "TransportServerDummy: no log on close"


// Test that we do not poison the array cookie if the operator new is defined
// inside the class.
// RUN: %clangxx_asan  %s -o %t && %run %t
//
// XFAIL: android
// XFAIL: armv7l-unknown-linux-gnueabihf
#include <new>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
struct Foo {
  void *operator new(size_t s) { return Allocate(s); }
  void *operator new[] (size_t s) { return Allocate(s); }
  ~Foo();
  static void *allocated;
  static void *Allocate(size_t s) {
    assert(!allocated);
    return allocated = ::new char[s];
  }
};

Foo::~Foo() {}
void *Foo::allocated;

Foo *getFoo(size_t n) {
  return new Foo[n];
}

int main() {
  Foo *foo = getFoo(10);
  fprintf(stderr, "foo  : %p\n", foo);
  fprintf(stderr, "alloc: %p\n", Foo::allocated);
  assert(reinterpret_cast<uintptr_t>(foo) ==
         reinterpret_cast<uintptr_t>(Foo::allocated) + sizeof(void*));
  *reinterpret_cast<uintptr_t*>(Foo::allocated) = 42;
  return 0;
}

// Test that we do not poison the array cookie if the operator new is defined
// inside the class.
// RUN: %clangxx_asan  %s -o %t && %run %t
//
// XFAIL: arm
#include <new>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
struct Foo {
  void *operator new(size_t s) { return Allocate(s); }
  void *operator new[] (size_t s) { return Allocate(s); }
  ~Foo();
  static void *allocated;
  static void *Allocate(size_t s) {
    assert(!allocated);
    return allocated = ::new char[s];
  }
};

Foo::~Foo() {}
void *Foo::allocated;

Foo *getFoo(size_t n) {
  return new Foo[n];
}

int main() {
  Foo *foo = getFoo(10);
  fprintf(stderr, "foo  : %p\n", foo);
  fprintf(stderr, "alloc: %p\n", Foo::allocated);
  assert(reinterpret_cast<uintptr_t>(foo) ==
         reinterpret_cast<uintptr_t>(Foo::allocated) + sizeof(void*));
  *reinterpret_cast<uintptr_t*>(Foo::allocated) = 42;
  return 0;
}

Disable array cookie test on ARM, enable on Android/x86.


#include "matcherexception.h"

#include "3rd-party/catch.hpp"

using namespace newsboat;

extern "C" {
	MatcherErrorFfi rs_get_test_attr_unavail_error();
	MatcherErrorFfi rs_get_test_invalid_regex_error();
}

TEST_CASE("Can be constructed from Rust error returned over FFI",
	"[MatcherException]")
{
	SECTION("Attribute unavailable") {
		const auto e = MatcherException::from_rust_error(
				rs_get_test_attr_unavail_error());
		REQUIRE(e.type() == MatcherException::Type::ATTRIB_UNAVAIL);
		REQUIRE(e.info() == "test_attribute");
		REQUIRE(e.info2().empty());
	}

	SECTION("Invalid regex") {
		const auto e = MatcherException::from_rust_error(
				rs_get_test_invalid_regex_error());
		REQUIRE(e.type() == MatcherException::Type::INVALID_REGEX);
		REQUIRE(e.info() == "?!");
		REQUIRE(e.info2() == "inconceivable happened!");
	}
}

#include "matcherexception.h"

#include "3rd-party/catch.hpp"

#include <cstring>

using namespace newsboat;

extern "C" {
	MatcherErrorFfi rs_get_test_attr_unavail_error();
	MatcherErrorFfi rs_get_test_invalid_regex_error();
}

TEST_CASE("Can be constructed from Rust error returned over FFI",
	"[MatcherException]")
{
	SECTION("Attribute unavailable") {
		const auto e = MatcherException::from_rust_error(
				rs_get_test_attr_unavail_error());
		REQUIRE(e.type() == MatcherException::Type::ATTRIB_UNAVAIL);
		REQUIRE(e.info() == "test_attribute");
		REQUIRE(e.info2().empty());
		REQUIRE_FALSE(strlen(e.what()) == 0);
	}

	SECTION("Invalid regex") {
		const auto e = MatcherException::from_rust_error(
				rs_get_test_invalid_regex_error());
		REQUIRE(e.type() == MatcherException::Type::INVALID_REGEX);
		REQUIRE(e.info() == "?!");
		REQUIRE(e.info2() == "inconceivable happened!");
		REQUIRE_FALSE(strlen(e.what()) == 0);
	}
}

Test that MatcherException::what() returns non-empty string


//===- Darwin/MappedFile.cpp - Darwin MappedFile Implementation -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides the Darwin specific implementation of the MappedFile
// concept.
//
//===----------------------------------------------------------------------===//

// Include the generic unix implementation
#include "../Unix/MappedFile.cpp"

// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab

//===- Darwin/MappedFile.cpp - Darwin MappedFile Implementation -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides the Darwin specific implementation of the MappedFile
// concept.
//
//===----------------------------------------------------------------------===//

// Include the generic unix implementation
#include <sys/stat.h>
#include "../Unix/MappedFile.cpp"

// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab

Allow this file to compile on Darwin.


// Check if trailing return types are supported
#include <algorithm>
#include <vector>

void fun() {
  int val = 0;
  std::vector<int> v{0, 1, 2, 4, 8};
  std::sort(v.begin(), v.end(),
            [&](int i, int j)->bool{ val++; return i < j && val++ < i; });
}

// Check if trailing return types are supported
#include <algorithm>
#include <vector>

void fun() {
  int val = 0;
  std::vector<int> v(5);
  std::sort(v.begin(), v.end(),
            [&](int i, int j)->bool{ val++; return i < j && val++ < i; });
}

Make independent of initializer list support.


#include "html.h"
#include "el_li.h"
#include "document.h"

litehtml::el_li::el_li(const std::shared_ptr<litehtml::document>& doc) : litehtml::html_tag(doc)
{
}

int litehtml::el_li::render(int x, int y, int max_width, bool second_pass)
{
	if (m_list_style_type >= list_style_type_armenian && !m_index_initialized)
	{
		if (auto p = parent())
		{
			tchar_t val[2] = { 1, 0 };
			for (int i = 0, n = (int)p->get_children_count(); i < n; ++i)
			{
				auto child = p->get_child(i);
				if (child.get() == this)
				{
					set_attr(_t("list_index"), val);
					break;
				}
				else if (!t_strcmp(child->get_tagName(), _t("li")))
					++val[0];
			}
		}

		m_index_initialized = true;
	}

	return html_tag::render(x, y, max_width, second_pass);
}

#include "html.h"
#include "el_li.h"
#include "document.h"

litehtml::el_li::el_li(const std::shared_ptr<litehtml::document>& doc) : litehtml::html_tag(doc)
{
}

int litehtml::el_li::render(int x, int y, int max_width, bool second_pass)
{
	if (m_list_style_type >= list_style_type_armenian && !m_index_initialized)
	{
		if (auto p = parent())
		{
			const auto hasStart = p->get_attr(_t("start"));
			const int start = hasStart ? t_atoi(hasStart) : 1;
			tchar_t val[2] = { (tchar_t)start, 0 };
			for (int i = 0, n = (int)p->get_children_count(); i < n; ++i)
			{
				auto child = p->get_child(i);
				if (child.get() == this)
				{
					set_attr(_t("list_index"), val);
					break;
				}
				else if (!t_strcmp(child->get_tagName(), _t("li")))
					++val[0];
			}
		}

		m_index_initialized = true;
	}

	return html_tag::render(x, y, max_width, second_pass);
}

Handle start attribute in ordered lists


// REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin10  -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s

// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: Lpubtypes_begin[[SECNUM:[0-9]:]]
//CHECK:         .asciz   "G"
//CHECK-NEXT:    .long   0
//CHECK-NEXT: Lpubtypes_end[[SECNUM]]

class G {
public:
  void foo();
};

void G::foo() {
}

// REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin10  -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s

// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: LpubTypes_begin[[SECNUM:[0-9]:]]
//CHECK:         .asciz   "G"
//CHECK-NEXT:    .long   0
//CHECK-NEXT: LpubTypes_end[[SECNUM]]

class G {
public:
  void foo();
};

void G::foo() {
}

Fix test for LLVM change r203619


#include <iostream>

#include <Python.h>

#include "character.h"

using namespace std;

static int error(const std::string & message){
    std::cout << message << std::endl;
    //PyErr_Print();
    return -1;
}

int main(int argc, char ** argv){
    if (argc > 1){
        Py_Initialize();

        /* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('./')");

        try {
            Character * character = new Character(argv[1]);
            character->addAttribute("name", Character::String);
            std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
            delete character;
        } catch (const PyException & ex){
            error("Problem loading module! Reason: " + ex.getReason());
        }

        Py_Finalize();

        return 0;
    }

    std::cout << "Usage: ./test character.py" << std::endl;

    return 0;

}

#include <iostream>

#include <Python.h>

#include "character.h"

using namespace std;

static int error(const std::string & message){
    std::cout << message << std::endl;
    //PyErr_Print();
    return -1;
}

int main(int argc, char ** argv){
    if (argc > 1){
        Py_Initialize();

        /* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('./')");

        try {
            Character * character = new Character(argv[1]);
            character->addAttribute("name", Character::String);
            std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
            delete character;
        } catch (const PyException & ex){
            error("Problem loading module! Reason: " + ex.getReason());
        }

        Py_Finalize();

        return 0;
    }

    std::cout << "Usage: ./test character_module_name" << std::endl;

    return 0;

}

Correct usage line, no need to include .py in module name.


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

#include "test_all.hpp"

int main(int argc, char* argv[])
{
    return test_all(argc, argv);
}

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

#include "test_all.hpp"
#ifdef _MSC_VER
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#else
#include <unistd.h>
#include <libgen.h>
#endif

int main(int argc, char* argv[])
{
#ifdef _MSC_VER
    char path[MAX_PATH];
    if (GetModuleFileNameA(NULL, path, sizeof(path)) == 0) {
        fprintf(stderr, "Failed to retrieve path to exectuable.\n");
        return 1;
    }
    PathRemoveFileSpecA(path);
    SetCurrentDirectoryA(path);
#else
    char executable[PATH_MAX];
    realpath(argv[0], executable);
    const char* directory = dirname(executable);
    chdir(directory);
#endif

    return test_all(argc, argv);
}

Make realm-tests switch to test directory upon start


// Copyright (c) 2012 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/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.15;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

// Copyright (c) 2012 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/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.0;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

Stop uploading unrecoverable errors to breakpad in preparation for beta.


// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %t
// RUN: rm -rf %T/coverage-maybe-open-file
// RUN: mkdir -p %T/coverage-maybe-open-file && cd %T/coverage-maybe-open-file
// RUN: %env_asan_opts=coverage=1 %run %t | FileCheck %s --check-prefix=CHECK-success
// RUN: %env_asan_opts=coverage=0 %run %t | FileCheck %s --check-prefix=CHECK-fail
// RUN: [ "$(cat test.sancov.packed)" == "test" ]
// RUN: cd .. && rm -rf %T/coverage-maybe-open-file

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <sanitizer/coverage_interface.h>

// FIXME: the code below might not work on Windows.
int main(int argc, char **argv) {
  int fd = __sanitizer_maybe_open_cov_file("test");
  if (fd > 0) {
    printf("SUCCESS\n");
    const char s[] = "test\n";
    write(fd, s, strlen(s));
    close(fd);
  } else {
    printf("FAIL\n");
  }
}

// CHECK-success: SUCCESS
// CHECK-fail: FAIL

// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %t
// RUN: rm -rf %T/coverage-maybe-open-file
// RUN: mkdir -p %T/coverage-maybe-open-file && cd %T/coverage-maybe-open-file
// RUN: %env_asan_opts=coverage=1 %run %t | FileCheck %s --check-prefix=CHECK-success
// RUN: %env_asan_opts=coverage=0 %run %t | FileCheck %s --check-prefix=CHECK-fail
// RUN: FileCheck %s <  test.sancov.packed -implicit-check-not={{.}} --check-prefix=CHECK-test
// RUN: cd .. && rm -rf %T/coverage-maybe-open-file

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <sanitizer/coverage_interface.h>

// FIXME: the code below might not work on Windows.
int main(int argc, char **argv) {
  int fd = __sanitizer_maybe_open_cov_file("test");
  if (fd > 0) {
    printf("SUCCESS\n");
    const char s[] = "test\n";
    write(fd, s, strlen(s));
    close(fd);
  } else {
    printf("FAIL\n");
  }
}

// CHECK-success: SUCCESS
// CHECK-fail: FAIL
// CHECK-test: {{^}}test{{$}}

Use FileCheck instead of [.


// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s

#include <stdio.h>

char bigchunk[1 << 30];

int main() {
  printf("Hello, world!\n");
  scanf("%s", bigchunk);
// CHECK-NOT: Hello, world!
// CHECK: Shadow memory range interleaves with an existing memory mapping.
// CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range.
// CHECK: Dumping process modules:
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}kernel32.dll
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll
}

// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s

#include <stdio.h>

char bigchunk[1 << 30];

int main() {
  printf("Hello, world!\n");
  scanf("%s", bigchunk);
// CHECK-NOT: Hello, world!
// CHECK: Shadow memory range interleaves with an existing memory mapping.
// CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range.
// CHECK: Dumping process modules:
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll
}

Remove CHECK line for kernel32.dll


// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "browser/atom_javascript_dialog_manager.h"

#include "base/utf_string_conversions.h"

namespace atom {

void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
    content::WebContents* web_contents,
    const string16& message_text,
    bool is_reload,
    const DialogClosedCallback& callback) {
  bool prevent_reload = !message_text.empty() ||
                        message_text == ASCIIToUTF16("false");
  callback.Run(!prevent_reload, message_text);
}

}  // namespace atom

// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "browser/atom_javascript_dialog_manager.h"

#include "base/utf_string_conversions.h"

namespace atom {

void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
    content::WebContents* web_contents,
    const string16& message_text,
    bool is_reload,
    const DialogClosedCallback& callback) {

  bool prevent_reload = message_text.empty() ||
                        message_text == ASCIIToUTF16("false");
  callback.Run(!prevent_reload, message_text);
}

}  // namespace atom

Revert ":lipstick: for the beforeunload handler."


#include "game.hpp"
#include "window.hpp"
#include "clock.hpp"
#include "events.hpp"
#include <iostream>

// "Game" specific data
namespace {
	bool gIsRunning = false;

	class GameEventEar : public EventEar {
	public:
		void onWindowClose()
		{
			Game::stop();
		}
	};
	GameEventEar gEar;
}

void Game::run()
{
	// Don't run it twice.
	if (gIsRunning)
		return;

	// Initialize the basics
	Window::open(800, 600);
	Clock::setTime(0.0);
	Events::addEar(&gEar);

	// Run the game loop
	gIsRunning = true;
	Clock::Timer frameCapTimer;
	while (gIsRunning)
	{
		// Poll for new events
		Events::poll();

		// Perform drawing, logic, etc...

		// Cap the framerate at 60
		Clock::sleepFor((1.0 / 60.0) - dt.get());
		frameCapTimer.set(0.0);
	}

	// Close the basics
	Events::removeEar(&gEar);
	Window::close();
}

void Game::stop()
{
	gIsRunning = false;
}

#include "game.hpp"
#include "window.hpp"
#include "clock.hpp"
#include "events.hpp"
#include <iostream>

// "Game" specific data
namespace {
	bool gIsRunning = false;

	class GameEventEar : public EventEar {
	public:
		void onWindowClose()
		{
			Game::stop();
		}
	};
	GameEventEar gEar;
}

void Game::run()
{
	// Don't run it twice.
	if (gIsRunning)
		return;

	// Initialize the basics
	Window::open(800, 600);
	Clock::setTime(0.0);
	Events::addEar(&gEar);

	// Run the game loop
	gIsRunning = true;
	Clock::Timer frameCapTimer;
	while (gIsRunning)
	{
		// Poll for new events
		Events::poll();

		// Perform drawing, logic, etc...

		// Cap the framerate at 60
		Clock::sleepFor((1.0 / 60.0) - frameCapTimer.get());
		frameCapTimer.set(0.0);
	}

	// Close the basics
	Events::removeEar(&gEar);
	Window::close();
}

void Game::stop()
{
	gIsRunning = false;
}

Fix mistaken local variable name.


#include <nan.h>

#include "input.h"
#include "output.h"

Nan::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct;
Nan::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct;

extern "C" {
    void init (v8::Local<v8::Object> target)
    {
        NodeMidiOutput::Init(target);
        NodeMidiInput::Init(target);
    }
    NODE_MODULE(midi, init)
}

#include <nan.h>

#include "input.h"
#include "output.h"

Nan::Persistent<v8::FunctionTemplate> NodeMidiInput::s_ct;
Nan::Persistent<v8::FunctionTemplate> NodeMidiOutput::s_ct;

NAN_MODULE_INIT(InitAll) {
    NodeMidiOutput::Init(target);
    NodeMidiInput::Init(target);
}

NODE_MODULE(midi, InitAll)

Use the NAN module init.


#include <iostream>
#include <vector>
#include "MuMaterial.h"
#include "rhythm.hpp"

using namespace std;

void PrintVector (vector<float> v, string message);

int main ()
{
    MuInit();

    Rhythm rhythm(4, 4, 60);

    rhythm.GenerateBaseRhythm(2);

    vector<float> base_rhythm = rhythm.base_rhythm;

    PrintVector(rhythm.base_rhythm, "base_rhythm");

    cout << endl << "Ok!" << endl;
    return 0;
}

void PrintVector (vector<float> v, string message)
{
    cout << message << ": ";
    for (unsigned int index = 0; index < v.size(); index++)
    {
        cout << v[index] << " ";
    }
    cout << endl;
}

#include <iostream>
#include <vector>
#include "MuMaterial.h"
#include "rhythm.hpp"

using namespace std;

void PrintVector (auto const v, string message);

int main ()
{
    MuInit();

    Rhythm rhythm(4, 4, 60);

    rhythm.GenerateBaseRhythm(2);

    vector<float> base_rhythm = rhythm.base_rhythm;

    PrintVector(rhythm.base_rhythm, "base_rhythm");

    cout << endl << "Ok!" << endl;
    return 0;
}

void PrintVector (auto const v, string message)
{
    cout << message << ": ";
    for (unsigned int index = 0; index < v.size(); index++)
    {
        cout << v[index] << " ";
    }
    cout << endl;
}

Make print vector as auto function


// Function grapher: user can choose among a set of functions (e.g., sin() and
// log(), provide parameters for those functions and then graph them

#include "Simple_window.h"
#include "Graph.h"

int main()
try {
    Point tl(400,150);
    Fgraph_window fwin(tl,800,605,"Function Grapher");
    return gui_main();
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
    keep_window_open();
}
catch (...) {
    cerr << "exception\n";
    keep_window_open();
}

// Chapter 16, exercise 10: function grapher: user can choose among a set of
// functions (e.g., sin() and log(), provide parameters for those functions and
// then graph them

#include "Simple_window.h"
#include "Graph.h"

int main()
try {
    Point tl(400,150);
    Fgraph_window fwin(tl,800,605,"Function Grapher");
    return gui_main();
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
    keep_window_open();
}
catch (...) {
    cerr << "exception\n";
    keep_window_open();
}

Complete header comment of Chapter 16, exercise 10


//
//  Parser.cpp
//  snowcrash
//
//  Created by Zdenek Nemec on 4/8/13.
//  Copyright (c) 2013 Apiary.io. All rights reserved.
//

#include <exception>
#include <sstream>
#include "Parser.h"
#include "MarkdownParser.h"
#include "BlueprintParser.h"

using namespace snowcrash;

const int SourceAnnotation::OK;

void Parser::parse(const SourceData& source, Result& result, Blueprint& blueprint)
{
    try {
        // Parse Markdown
        MarkdownBlock::Stack markdown;
        MarkdownParser markdownParser;
        markdownParser.parse(source, result, markdown);

        if (result.error.code != Error::OK)
            return;

        // Parse Blueprint
        BlueprintParser::Parse(source, markdown, result, blueprint);
    }
    catch (const std::exception& e) {

        std::stringstream ss;
        ss << "parser exception: '" << e.what() << "'";
        result.error = Error(ss.str(), 1);
    }
    catch (...) {

        result.error = Error("parser exception has occured", 1);
    }
}

//
//  Parser.cpp
//  snowcrash
//
//  Created by Zdenek Nemec on 4/8/13.
//  Copyright (c) 2013 Apiary.io. All rights reserved.
//

#include <exception>
#include <sstream>
#include "Parser.h"
#include "MarkdownParser.h"
#include "BlueprintParser.h"

using namespace snowcrash;

const int SourceAnnotation::OK;

// Check source for unsupported character \t & \r
// Returns true if passed (not found), false otherwise
static bool CheckSource(const SourceData& source, Result& result)
{
    std::string::size_type pos = source.find("\t");
    if (pos != std::string::npos) {
        result.error = Error("the use of tab(s) `\\t` in source data isn't currently supported, please contact makers", 2);
        return false;
    }

    pos = source.find("\r");
    if (pos != std::string::npos) {
        result.error = Error("the use of carriage return(s) `\\r` in source data isn't currently supported, please contact makers", 2);
        return false;
    }

    return true;
}

void Parser::parse(const SourceData& source, Result& result, Blueprint& blueprint)
{
    try {

        // Sanity Check
        if (!CheckSource(source, result))
            return;

        // Parse Markdown
        MarkdownBlock::Stack markdown;
        MarkdownParser markdownParser;
        markdownParser.parse(source, result, markdown);

        if (result.error.code != Error::OK)
            return;

        // Parse Blueprint
        BlueprintParser::Parse(source, markdown, result, blueprint);
    }
    catch (const std::exception& e) {

        std::stringstream ss;
        ss << "parser exception: '" << e.what() << "'";
        result.error = Error(ss.str(), 1);
    }
    catch (...) {

        result.error = Error("parser exception has occured", 1);
    }
}

Add tabs & CR sanity check


#include <QApplication>
#include "qkeymapper.h"

#ifdef DEBUG_LOGOUT_ON
//#include "vld.h"
#endif

int main(int argc, char *argv[])
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QApplication a(argc, argv);
    QApplication::setStyle(QStyleFactory::create("Fusion"));

#ifdef ADJUST_PRIVILEGES
//    BOOL adjustresult = QKeyMapper::AdjustPrivileges();
//    qDebug() << "AdjustPrivileges Result:" << adjustresult;

    BOOL adjustresult = QKeyMapper::EnableDebugPrivilege();
    qDebug() << "EnableDebugPrivilege Result:" << adjustresult;
#endif

    QKeyMapper w;

    // Remove "?" Button from QDialog
    Qt::WindowFlags flags = Qt::Dialog;
    flags |= Qt::WindowMinimizeButtonHint;
    flags |= Qt::WindowCloseButtonHint;
    w.setWindowFlags(flags);

    w.show();

    return a.exec();
}

#include <QApplication>
#include "qkeymapper.h"

#ifdef DEBUG_LOGOUT_ON
//#include "vld.h"
#endif

int main(int argc, char *argv[])
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QApplication a(argc, argv);
    QApplication::setStyle(QStyleFactory::create("Fusion"));

#ifdef DEBUG_LOGOUT_ON
    qSetMessagePattern("%{time [hh:mm:ss.zzz]} Message:%{message}");
#endif

#ifdef ADJUST_PRIVILEGES
//    BOOL adjustresult = QKeyMapper::AdjustPrivileges();
//    qDebug() << "AdjustPrivileges Result:" << adjustresult;

    BOOL adjustresult = QKeyMapper::EnableDebugPrivilege();
    qDebug() << "EnableDebugPrivilege Result:" << adjustresult;
#endif

    QKeyMapper w;

    // Remove "?" Button from QDialog
    Qt::WindowFlags flags = Qt::Dialog;
    flags |= Qt::WindowMinimizeButtonHint;
    flags |= Qt::WindowCloseButtonHint;
    w.setWindowFlags(flags);

    w.show();

    return a.exec();
}

Add debug timestamp for log output.


#include "SuffixTree\SuffixTreeBuilder.h"
#include <iostream>
#include <string>
#include <cassert>
#include <ctime>
using namespace std;

int main()
{
    unsigned int length = 100000;
    char* source = new char[length + 1];
    for (unsigned int i = 0; i < length; i++)
    {
        source[i] = rand() % 26 + 'A';
    }
    source[length] = 0;
    string s = source;
    clock_t s_time = clock();
    SuffixTreeBuilder builder(s);
    SuffixTree suffixTree;
    builder.BuildSuffixTree(&suffixTree);
    clock_t e_time = clock();
    cout << e_time - s_time << endl;
    // cout << suffixTree.Show(s, &builder) << endl;
    return 0;
}

#include "SuffixTree/SuffixTreeBuilder.h"
#include <iostream>
#include <string>
#include <cassert>
#include <ctime>
using namespace std;

int main()
{
    unsigned int length = 100000;
    char* source = new char[length + 1];
    for (unsigned int i = 0; i < length; i++)
    {
        source[i] = rand() % 26 + 'A';
    }
    source[length] = 0;
    string s = source;
    clock_t s_time = clock();
    SuffixTreeBuilder builder(s);
    SuffixTree suffixTree;
    builder.BuildSuffixTree(&suffixTree);
    clock_t e_time = clock();
    cout << e_time - s_time << endl;
    // cout << suffixTree.Show(s, &builder) << endl;
    return 0;
}

Fix build error on OSX


#include "glTFForUE4EdPrivatePCH.h"
#include "glTFImportOptions.h"

FglTFImportOptions::FglTFImportOptions()
    : FilePathInOS(TEXT(""))
    , FilePathInEngine(TEXT(""))
    , MeshScaleRatio(1.0f)
    , bInvertNormal(false)
    , bImportMaterial(true)
    , bRecomputeNormals(true)
    , bRecomputeTangents(true)
{
    //
}

const FglTFImportOptions FglTFImportOptions::Default;
FglTFImportOptions FglTFImportOptions::Current;

#include "glTFForUE4EdPrivatePCH.h"
#include "glTFImportOptions.h"

FglTFImportOptions::FglTFImportOptions()
    : FilePathInOS(TEXT(""))
    , FilePathInEngine(TEXT(""))
    , MeshScaleRatio(100.0f)
    , bInvertNormal(false)
    , bImportMaterial(true)
    , bRecomputeNormals(true)
    , bRecomputeTangents(true)
{
    //
}

const FglTFImportOptions FglTFImportOptions::Default;
FglTFImportOptions FglTFImportOptions::Current;

Set the default scale to 100


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

namespace cucumber {
namespace internal {

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

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.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;
    }
}

}
}

Fix compiler warning about member initializer order


/**
 ** \file libport/perror.cc
 ** \brief perror: implements file libport/perror.hh
 */

#include <cstdio>
#include <iostream>

#include "libport/cstring"

namespace libport
{

  void
  perror (const char* s)
  {
#ifndef WIN32
    ::perror(s);
#else
    int errnum;
    const char* errstring;
    const char* colon;

    errnum = WSAGetLastError();
    errstring = strerror(errnum);

    if (s == NULL || *s == '\0')
      s = colon = "";
    else
      colon = ": ";

    std::cerr << s << colon << errstring << std::endl;
#endif
  }

}

/**
 ** \file libport/perror.cc
 ** \brief perror: implements file libport/perror.hh
 */

#include <cstdio>
#include <iostream>

#include "libport/windows.hh"
#include "libport/cstring"

namespace libport
{

  void
  perror (const char* s)
  {
#ifndef WIN32
    ::perror(s);
#else
    int errnum;
    const char* errstring;
    const char* colon;

    errnum = WSAGetLastError();
    errstring = strerror(errnum);

    if (s == NULL || *s == '\0')
      s = colon = "";
    else
      colon = ": ";

    std::cerr << s << colon << errstring << std::endl;
#endif
  }

}

Add missing header for windows.


#include <QThread>

int main()
{
    QThread::sleep(60);
}

#include <QThread>

class MyThread : public QThread
{
public:
    static void mySleep(unsigned long secs) { sleep(secs); } // sleep() is protected in Qt 4.
};

int main()
{
    MyThread::mySleep(60);
}

Fix "inifiniteLoop" test for Qt 4.


#include <miniMAT/util/PrintResult.hpp>

#include <iostream>
#include <iomanip>

namespace miniMAT {
	namespace util {
		void PrintResult(std::string varname, Matrix m, bool suppressed) {
			if (!suppressed) {
                // Print a row at a time (default precision is 4)
                std::cout << varname << " =" << std::endl << std::endl;
                for (int i = 0; i < m.rows(); i++) {
                    std::cout << "    ";
                    for (int j = 0; j < m.cols(); j++)
                        std::cout << std::fixed << std::showpoint << std::setprecision(4) << m(i,j) << " ";
                    std::cout << std::endl;
                }
                std::cout << std::endl;
            }
		}
	}
}

#include <miniMAT/util/PrintResult.hpp>

#include <iostream>
#include <iomanip>
#include <cmath>

namespace miniMAT {
	namespace util {
		void PrintResult(std::string varname, Matrix m, bool suppressed) {
			if (!suppressed) {
                using namespace std;

                int maxdigits = log10(m.maxCoeff()) + 1;    // Get number of digits of max element
                int precision = 4;
                int space = 1, dot = 1;

                // Print a row at a time (default precision is 4)
                cout << varname << " =" << endl << endl;
                for (int i = 0; i < m.rows(); i++) {
                    cout << "    ";
                    for (int j = 0; j < m.cols(); j++)
                        cout << right
                             << fixed
                             << showpoint
                             << setprecision(precision)
                             << setw(maxdigits + precision + dot + space)
                             << m(i,j);
                    cout << endl;
                }
                cout << endl;
            }
		}
	}
}

Fix formatting for matrix output


/**
 * @file Connection.cpp
 * @brief
 * @author Travis Lane
 * @version 0.0.1
 * @date 2016-01-05
 */

#include "Connection.h"

Connection::Connection(Bluetooth &new_bt, int id) : bt(new_bt)
{
  this->id = id;
}

int Connection::write(int percent)
{
  int rc = 0;
  StaticJsonBuffer<200> buffer;
  JsonObject& object = buffer.createObject();

  if (!bt.connected()) {
    return -1;
  }

  object["id"] = this->id;
  object["throttle"] = percent;

  /* Don't pretty print, I deliminate on \n */
  rc = object.printTo(bt);
  bt.write('\n');

  return rc;
}

int Connection::read(int *out_percent)
{
  int rc = 0;
  char buff[200];
  StaticJsonBuffer<200> buffer;

  if (!bt.connected()) {
    return -1;
  }

  rc = bt.readBytesUntil('\n', buff, sizeof(buff));
  if (rc <= 0) {
    return -1;
  }

  /* Set last char to NULL */
  buff[rc] = '\0';

  JsonObject& object = buffer.parseObject(buff);

  if (!object.success()) {
    return -1;
  }

  if (object["id"] != id) {
    /* The ID doesn't match... We should ignore this message */
    return -1;
  }

  *out_percent = object["throttle"];
  return rc;
}

/**
 * @file Connection.cpp
 * @brief
 * @author Travis Lane
 * @version 0.0.1
 * @date 2016-01-05
 */

#include "Connection.h"

Connection::Connection(Bluetooth &new_bt, int id) : bt(new_bt)
{
  this->id = id;
}

int Connection::write(int percent)
{
  int rc = 0;
  StaticJsonBuffer<200> buffer;
  JsonObject& object = buffer.createObject();

  if (!bt.connected()) {
    return -1;
  }

  object["id"] = this->id;
  object["throttle"] = percent;

  /* Don't pretty print, I deliminate on \n */
  rc = object.printTo(bt);
  bt.write('\n');

  return rc;
}

int Connection::read(int *out_percent)
{
  int rc = 0;
  char buff[200];
  StaticJsonBuffer<200> buffer;

  if (!bt.connected()) {
    return -1;
  }

  rc = bt.readBytesUntil('\n', buff, sizeof(buff));
  if (rc <= 0) {
    return -2;
  }

  /* Set last char to NULL */
  buff[rc] = '\0';

  JsonObject& object = buffer.parseObject(buff);

  if (!object.success()) {
    return -3;
  }

  if (object["id"] != id) {
    /* The ID doesn't match... We should ignore this message */
    return -4;
  }

  *out_percent = object["throttle"];
  return rc;
}

Change status codes for debugging


/*
 * This file is part of Peli - universal JSON interaction library
 * Copyright (C) 2014  Alexey Chernov <4ernov@gmail.com>
 *
 * Peli is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <cassert>

#include "peli/json/value.h"

using namespace std;

using namespace peli;

int main(int, char**)
{
	json::value v1(json::make_value<json::object>());
	json::object& obj1(v1);
	obj1["test"] = json::value(52);

	json::value v2;

	static_assert(noexcept(json::value() = std::move(v2)), "Move assignment isn't noexcept");

	v2 = std::move(v1);

	json::object& obj2(v2);
	obj2["tost"] = json::value(false);

	return 0;
}

/*
 * This file is part of Peli - universal JSON interaction library
 * Copyright (C) 2014  Alexey Chernov <4ernov@gmail.com>
 *
 * Peli is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <cassert>

#include "peli/json/value.h"

using namespace std;

using namespace peli;

int main(int, char**)
{
	json::value v1(json::make_value<json::object>());
	json::object& obj1(v1);
	obj1["test"] = json::value(52);

	json::value v2;

	static_assert(noexcept(declval<json::value>().operator=(std::move(v2))), "Move assignment isn't noexcept");

	v2 = std::move(v1);

	json::object& obj2(v2);
	obj2["tost"] = json::value(false);

	return 0;
}

Fix static assertion of exception safety of move assignment


#include "browser/inspectable_web_contents.h"

#include "browser/inspectable_web_contents_impl.h"

namespace brightray {

InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {
  return Create(content::WebContents::Create(create_params));
}

InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {
  return new InspectableWebContentsImpl(web_contents);
}

}

#include "browser/inspectable_web_contents.h"

#include "browser/inspectable_web_contents_impl.h"

#include "content/public/browser/web_contents_view.h"

namespace brightray {

InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {
  auto contents = content::WebContents::Create(create_params);
#if defined(OS_MACOSX)
  // Work around http://crbug.com/279472.
  contents->GetView()->SetAllowOverlappingViews(true);
#endif

  return Create(contents);
}

InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {
  return new InspectableWebContentsImpl(web_contents);
}

}

Fix flashing in WebContents we create


/*
 * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     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.
 *
 */

#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE test_hdf5
#include <boost/test/unit_test.hpp>
#include <votca/xtp/checkpoint.h>

BOOST_AUTO_TEST_SUITE(test_hdf5)

BOOST_AUTO_TEST_CASE(constructor_test) {
    votca::xtp::CheckpointFile cpf("xtp_testing.hdf5"); }

BOOST_AUTO_TEST_SUITE_END()

/*
 * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     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.
 *
 */

#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE test_hdf5
#include <boost/test/unit_test.hpp>
#include <votca/xtp/checkpoint.h>

BOOST_AUTO_TEST_SUITE(test_hdf5)

BOOST_AUTO_TEST_CASE(checkpoint_file_test) {
    votca::xtp::CheckpointFile cpf("xtp_testing.hdf5");

    // Write orbitals
    votca::xtp::Orbitals orbWrite;

    orbWrite.setBasisSetSize(17);
    orbWrite.setNumberOfLevels(4,13);

    Eigen::VectorXd moeTest = Eigen::VectorXd::Zero(17);
    Eigen::MatrixXd mocTest = Eigen::MatrixXd::Zero(17,17);

    orbWrite.MOEnergies()=moeTest;
    orbWrite.MOCoefficients()=mocTest;

    cpf.WriteOrbitals(orbWrite, "Test Orb");

    // Read Orbitals
    votca::xtp::Orbitals orbRead;

}

BOOST_AUTO_TEST_SUITE_END()

Add orbfile write code to checkpoint file writing


#include "Benchmark.h"
#include "SkPMFloat.h"
#include "SkRandom.h"

struct PMFloatBench : public Benchmark {
    explicit PMFloatBench(bool clamp) : fClamp(clamp) {}

    const char* onGetName() SK_OVERRIDE { return fClamp ? "SkPMFloat_clamp" : "SkPMFloat_get"; }
    bool isSuitableFor(Backend backend) SK_OVERRIDE { return backend == kNonRendering_Backend; }

    void onDraw(const int loops, SkCanvas* canvas) SK_OVERRIDE {
        SkRandom rand;
        for (int i = 0; i < loops; i++) {
            SkPMColor c = SkPreMultiplyColor(rand.nextU());
            SkPMFloat pmf;
            pmf.set(c);
            SkPMColor back = fClamp ? pmf.clamped() : pmf.get();
            if (c != back) { SkFAIL("no joy"); }  // This conditional makes this not compile away.
        }
    }

    bool fClamp;
};
DEF_BENCH(return new PMFloatBench( true);)
DEF_BENCH(return new PMFloatBench(false);)

#include "Benchmark.h"
#include "SkPMFloat.h"

// Used to prevent the compiler from optimizing away the whole loop.
volatile uint32_t blackhole = 0;

// Not a great random number generator, but it's very fast.
// The code we're measuring is quite fast, so low overhead is essential.
static uint32_t lcg_rand(uint32_t* seed) {
    *seed *= 1664525;
    *seed += 1013904223;
    return *seed;
}

struct PMFloatBench : public Benchmark {
    explicit PMFloatBench(bool clamp) : fClamp(clamp) {}

    const char* onGetName() SK_OVERRIDE { return fClamp ? "SkPMFloat_clamp" : "SkPMFloat_get"; }
    bool isSuitableFor(Backend backend) SK_OVERRIDE { return backend == kNonRendering_Backend; }

    void onDraw(const int loops, SkCanvas* canvas) SK_OVERRIDE {
        // Unlike blackhole, junk can and probably will be a register.
        uint32_t junk = 0;
        uint32_t seed = 0;
        for (int i = 0; i < loops; i++) {
        #ifdef SK_DEBUG
            // Our SkASSERTs will remind us that it's technically required that we premultiply.
            SkPMColor c = SkPreMultiplyColor(lcg_rand(&seed));
        #else
            // But it's a lot faster not to, and this code won't really mind the non-PM colors.
            SkPMColor c = lcg_rand(&seed);
        #endif
            SkPMFloat pmf;
            pmf.set(c);
            SkPMColor back = fClamp ? pmf.clamped() : pmf.get();
            junk ^= back;
        }
        blackhole ^= junk;
    }

    bool fClamp;
};
DEF_BENCH(return new PMFloatBench( true);)
DEF_BENCH(return new PMFloatBench(false);)

Trim the fat off SkPMFloat bench.


// RUN: %clang_cc1 -fsyntax-only -verify %s
// PR7800

class NoDestroy { ~NoDestroy(); }; // expected-note {{declared private here}}
struct A {
  virtual ~A();
};
struct B : public virtual A {
  NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}}
};
struct D : public virtual B {
  virtual void foo();
  ~D();
};
void D::foo() { // expected-note {{implicit default destructor for 'B' first required here}}
}

// RUN: %clang_cc1 -fsyntax-only -verify %s
// PR7800

class NoDestroy { ~NoDestroy(); }; // expected-note 3 {{declared private here}}
struct A {
  virtual ~A();
};

struct B : public virtual A {
  NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}}
};
struct D : public virtual B {
  virtual void foo();
  ~D();
};
void D::foo() { // expected-note {{implicit default destructor for 'B' first required here}}
}

struct E : public virtual A {
  NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}}
};
struct F : public E { // expected-note {{implicit default destructor for 'E' first required here}}
};
struct G : public virtual F {
  virtual void foo();
  ~G();
};
void G::foo() { // expected-note {{implicit default destructor for 'F' first required here}}
}

struct H : public virtual A {
  NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}}
};
struct I : public virtual H {
  ~I();
};
struct J : public I {
  virtual void foo();
  ~J();
};
void J::foo() { // expected-note {{implicit default destructor for 'H' first required here}}
}

Make this test check a few more cases which didn't work correctly before r110526.


/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "RootShadowNode.h"

#include <react/components/view/conversions.h>

namespace facebook {
namespace react {

const char RootComponentName[] = "RootView";

void RootShadowNode::layout() {
  ensureUnsealed();
  layout(getProps()->layoutContext);

  // This is the rare place where shadow node must layout (set `layoutMetrics`)
  // itself because there is no a parent node which usually should do it.
  setLayoutMetrics(layoutMetricsFromYogaNode(yogaNode_));
}

} // namespace react
} // namespace facebook

/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "RootShadowNode.h"

#include <react/components/view/conversions.h>
#include <react/debug/SystraceSection.h>

namespace facebook {
namespace react {

const char RootComponentName[] = "RootView";

void RootShadowNode::layout() {
  SystraceSection s("RootShadowNode::layout");
  ensureUnsealed();
  layout(getProps()->layoutContext);

  // This is the rare place where shadow node must layout (set `layoutMetrics`)
  // itself because there is no a parent node which usually should do it.
  setLayoutMetrics(layoutMetricsFromYogaNode(yogaNode_));
}

} // namespace react
} // namespace facebook

Add systrace to calculation of Yoga layout() in Fabric


//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "CorLib.h"

HRESULT Library_corlib_native_System_Diagnostics_Debugger::get_IsAttached___STATIC__BOOLEAN( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)

    stack.SetResult_Boolean( CLR_EE_DBG_IS( SourceLevelDebugging ));

#else

    stack.SetResult_Boolean( false );

#endif

    NANOCLR_NOCLEANUP_NOLABEL();
}

HRESULT Library_corlib_native_System_Diagnostics_Debugger::Break___STATIC__VOID( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)

    if(stack.m_customState == 0)
    {
        stack.m_customState++;
        g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Break( &stack );

        hr = CLR_E_RESCHEDULE;  NANOCLR_LEAVE();
    }

    NANOCLR_NOCLEANUP();

#else

    NANOCLR_NOCLEANUP_NOLABEL();

#endif

}

//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "CorLib.h"

HRESULT Library_corlib_native_System_Diagnostics_Debugger::get_IsAttached___STATIC__BOOLEAN( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)

    stack.SetResult_Boolean( CLR_EE_DBG_IS( SourceLevelDebugging ));

#else

    stack.SetResult_Boolean( false );

#endif

    NANOCLR_NOCLEANUP_NOLABEL();
}

HRESULT Library_corlib_native_System_Diagnostics_Debugger::Break___STATIC__VOID( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_CORE();
    NANOCLR_HEADER();

#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)

    if(stack.m_customState == 0)
    {
        stack.m_customState++;
        g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Break( &stack );

        hr = CLR_E_RESCHEDULE;  NANOCLR_LEAVE();
    }

    NANOCLR_NOCLEANUP();

#else
    (void)stack;
    NANOCLR_NOCLEANUP_NOLABEL();

#endif

}

Fix potential issue with Diagnostics_Debugger::Break


#include <polar/core/log.h>
#include <polar/fs/local.h>
#include <polar/util/sdl.h>

namespace polar::core {
	std::shared_ptr<logger> logger::instance;

	void logger::msgbox(std::string title, std::string msg) {
#if defined(_WIN32)
		SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.data(), msg.data(), NULL);
#endif
		std::cerr << title << ": " << msg << std::endl;
	}

	logger::logger(priority_t priority)
	  : file((fs::local::app_dir() / "log.txt").str(), std::ios::out | std::ios::binary | std::ios::trunc),
	    priority(priority) {}
}

#include <polar/core/log.h>
#include <polar/fs/local.h>
#include <polar/util/sdl.h>

namespace polar::core {
	std::shared_ptr<logger> logger::instance;

	void logger::msgbox(std::string title, std::string msg) {
#if defined(_WIN32)
		SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.data(), msg.data(), NULL);
#endif
		std::cerr << title << ": " << msg << std::endl;
		throw std::runtime_error("fatal error");
	}

	logger::logger(priority_t priority)
	  : file((fs::local::app_dir() / "log.txt").str(), std::ios::out | std::ios::binary | std::ios::trunc),
	    priority(priority) {}
}

Throw exception on fatal error


// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "bin/directory.h"

bool Directory::Open(const char* path, intptr_t* dir) {
  UNIMPLEMENTED();
  return false;
}

bool Directory::Close(intptr_t dir) {
  UNIMPLEMENTED();
  return false;
}

void Directory::List(intptr_t dir,
                     bool recursive,
                     Dart_Port dir_handler,
                     Dart_Port file_handler,
                     Dart_Port done_handler,
                     Dart_Port dir_error_handler) {
  UNIMPLEMENTED();
}

// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "bin/directory.h"

bool Directory::Open(const char* path, intptr_t* dir) {
  UNIMPLEMENTED();
  return false;
}

bool Directory::Close(intptr_t dir) {
  UNIMPLEMENTED();
  return false;
}

void Directory::List(const char* path,
                     intptr_t dir,
                     bool recursive,
                     Dart_Port dir_handler,
                     Dart_Port file_handler,
                     Dart_Port done_handler,
                     Dart_Port dir_error_handler) {
  UNIMPLEMENTED();
}

Fix Windows build after directory library changes.


#include "gtest/gtest.h"

#include "tcframe_test_commons.cpp"
#include "tcframe/problem.hpp"

using tcframe::BaseProblem;

class MyProblem : public BaseProblem {
protected:
    void Config() {
        setSlug("foo");
        setTimeLimit(2);
        setMemoryLimit(256);
    }

    void InputFormat() { }

    void OutputFormat() { }
};

TEST(ProblemTest, DefaultOptions) {
    BaseProblem* problem = new DefaultProblem();

    EXPECT_EQ("problem", problem->getSlug());
    EXPECT_EQ(0, problem->getTimeLimit());
    EXPECT_EQ(0, problem->getMemoryLimit());
}

TEST(ProblemTest, MyOptions) {
    BaseProblem* problem = new MyProblem();
    problem->applyProblemConfiguration();

    EXPECT_EQ("foo", problem->getSlug());
    EXPECT_EQ(2, problem->getTimeLimit());
    EXPECT_EQ(256, problem->getMemoryLimit());
}

TEST(ProblemTest, CommandLineOptions) {
    char* argv[] = {(char*) "<runner>", (char*)"--slug=bar", (char*)"--time-limit=3", (char*)"--memory-limit=64"};

    BaseProblem* problem = new MyProblem();
    problem->applyProblemConfiguration();
    problem->applyProblemCommandLineOptions(4, argv);

    EXPECT_EQ("bar", problem->getSlug());
    EXPECT_EQ(3, problem->getTimeLimit());
    EXPECT_EQ(64, problem->getMemoryLimit());
}

TEST(ProblemTest, CommandLineOptionsWithNos) {
    char* argv[] = {(char*) "<runner>", (char*)"--no-time-limit", (char*)"--no-memory-limit"};

    BaseProblem* problem = new MyProblem();
    problem->applyProblemConfiguration();
    problem->applyProblemCommandLineOptions(3, argv);

    EXPECT_EQ("foo", problem->getSlug());
    EXPECT_EQ(0, problem->getTimeLimit());
    EXPECT_EQ(0, problem->getMemoryLimit());
}

Add Problem's command-line options tests


#include <iostream>

int main() {
  std::cout << "Fractalogy!\n";

  return 0;
}

#include <iostream>
#include <complex>

using std::cout;
using std::complex;
using std::exp;
using std::norm;

/// returns -1 on failing to escape
int iteration(complex<double> c, int limit = 1000) {
  int i = 0;
  double n;
  complex<double> z(0, 0);
  while ((n = norm(z)) < 4 && i < limit) {
    z = exp(z) - c;
    ++i;
  }

  if (n < 4)
    return -1;
  else
    return i;
}

int main() {
  std::cout << "Fractalogy!\n";
  double lower = -2, upper = 2;
  int width = 100, height = 100;
  for (int i = 0; i <= width; ++i) {
    for (int j = 0; j <= height; ++j) {
      complex<double> t;
      t = complex<double>(lower + (upper - lower) * i / width, lower + (upper - lower) * j / height);
      cout << iteration(t) << " ";
    }
    cout << std::endl;
  }

  return 0;
}

Add the iteration function for the fractals


#include "ImageWriter.h"

uint32 ImageWriter::GetChannelForPixel(uint32 x, uint32 y, uint32 ch) {
	uint32 bytesPerRow = GetWidth() * 4;
	uint32 byteLocation = y * bytesPerRow + x*4 + ch;
	return m_PixelData[byteLocation];
}

#include "ImageWriter.h"

uint32 ImageWriter::GetChannelForPixel(uint32 x, uint32 y, uint32 ch) {

  // Assume pixels are in block stream order, hence we would need to first find
  // the block that contains pixel (x, y) and then find the byte location for it.

  const uint32 blocksPerRow = GetWidth() / 4;
  const uint32 blockIdxX = x / 4;
  const uint32 blockIdxY = y / 4;
  const uint32 blockIdx = blockIdxY * blocksPerRow + blockIdxX;

  // Now we find the offset in the block
  const uint32 blockOffsetX = x % 4;
  const uint32 blockOffsetY = y % 4;
  const uint32 pixelOffset = blockOffsetY * 4 + blockOffsetX;

  // There are 16 pixels per block and bytes per pixel...
  uint32 dataOffset = blockIdx * 4 * 16;
  dataOffset += 4 * pixelOffset;
  dataOffset += ch;

  return m_PixelData[dataOffset];
}

Make sure that we assume pixels are in block stream order when accessing.


// 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/Games/Game.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Tasks/PlayerTasks/EndTurnTask.hpp>

namespace RosettaStone::PlayerTasks
{
TaskID EndTurnTask::GetTaskID() const
{
    return TaskID::END_TURN;
}

TaskStatus EndTurnTask::Impl(Player& player)
{
    player.GetGame()->step = Step::MAIN_END;
    player.GetGame()->MainEnd();

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

// 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/Games/Game.hpp>
#include <Rosetta/Games/GameManager.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Tasks/PlayerTasks/EndTurnTask.hpp>

namespace RosettaStone::PlayerTasks
{
TaskID EndTurnTask::GetTaskID() const
{
    return TaskID::END_TURN;
}

TaskStatus EndTurnTask::Impl(Player& player)
{
    auto game = player.GetGame();

    game->nextStep = Step::MAIN_END;
    GameManager::ProcessNextStep(*game, game->nextStep);

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

Use 'nextStep' instead of 'step' and call ProcessNextStep()


/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <iostream>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include "AssimpImporter.hpp"

namespace AssimpWorker {

	AssimpImporter::AssimpImporter() :
		importer()
	{
		return;
	}

	AssimpImporter::~AssimpImporter(){
		return;
	}

	const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){
		importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys
		importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons
		importer.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true);
		importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles
		const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality);
		if (!scene) {
			log.error("Scene not imported: "+fileName);
		}
		log.error(importer.GetErrorString());
		return scene;
	}

}

/*
* This file is part of ATLAS. It is subject to the license terms in
* the LICENSE file found in the top-level directory of this distribution.
* (Also avialable at http://www.apache.org/licenses/LICENSE-2.0.txt)
* You may not use this file except in compliance with the License.
*/
#include <iostream>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include "AssimpImporter.hpp"

namespace AssimpWorker {

	AssimpImporter::AssimpImporter() :
		importer()
	{
		return;
	}

	AssimpImporter::~AssimpImporter(){
		return;
	}

	const aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){
		importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); //remove degenerate polys
		importer.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); //do not import skeletons
		importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); //Drop all primitives that aren't triangles
		const aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality);
		if (!scene) {
			log.error("Scene not imported: "+fileName);
		}
		log.error(importer.GetErrorString());
		return scene;
	}

}

Remove no longer necessary assimp import flag


/*
 * CardDeck.cpp
 *
 *  Created on: 2014年10月25日
 *      Author: nemo
 */

#include "CardDeck.h"

#include <iostream>

CardDeck::CardDeck()
{
	LOG_TRACE("Construct CardDeck.")

}

CardDeck::~CardDeck()
{
	// TODO Auto-generated destructor stub
}

///	Insert card into card deck.
/**
 * @brief	Insert card into card deck.
 *
 * @param 	card	Input card pointer.
 */
void CardDeck::push_back(Card *card)
{
	_card.push_back(card);
}

///	Show all card in card deck.
void CardDeck::show()
{
	for(auto card :_card)
	{
		card->show();
	}

}

/*
 * CardDeck.cpp
 *
 *  Created on: 2014年10月25日
 *      Author: nemo
 */

#include "CardDeck.h"

#include <iostream>

CardDeck::CardDeck()
{
	LOG_TRACE("Construct CardDeck.")

}

CardDeck::~CardDeck()
{
	// TODO Auto-generated destructor stub
}

///	Insert card into card deck.
/**
 * @brief	Insert card into card deck.
 *
 * @param 	card	Input card pointer.
 */
void CardDeck::push_back(Card *card)
{
	_card.push_back(card);
}

///	Show all card in card deck.
void CardDeck::show()
{
	for(const auto card :_card)
	{
		card->show();
	}
}

Set auto card in show(0) as const.


/* This file is part of VoltDB.
 * Copyright (C) 2008-2012 VoltDB Inc.
 *
 * VoltDB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * VoltDB is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with VoltDB.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <sstream>
#include "tablecountnode.h"
#include "common/common.h"
#include "expressions/abstractexpression.h"
#include "storage/table.h"

namespace voltdb {

TableCountPlanNode::~TableCountPlanNode() {
}

std::string TableCountPlanNode::debugInfo(const std::string &spacer) const {
    std::ostringstream buffer;
    buffer << this->AbstractScanPlanNode::debugInfo(spacer);
    assert(m_predicate == NULL);
    buffer << spacer << "TABLE COUNT Expression: <NULL>";
    return (buffer.str());
}

}

/* This file is part of VoltDB.
 * Copyright (C) 2008-2012 VoltDB Inc.
 *
 * VoltDB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * VoltDB is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with VoltDB.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <sstream>
#include "tablecountnode.h"
#include "common/common.h"
#include "expressions/abstractexpression.h"
#include "storage/table.h"

namespace voltdb {

TableCountPlanNode::~TableCountPlanNode() {
    delete getOutputTable();
    setOutputTable(NULL);
}

std::string TableCountPlanNode::debugInfo(const std::string &spacer) const {
    std::ostringstream buffer;
    buffer << this->AbstractScanPlanNode::debugInfo(spacer);
    assert(m_predicate == NULL);
    buffer << spacer << "TABLE COUNT Expression: <NULL>";
    return (buffer.str());
}

}

Resolve the valgrind memory leak problem


// 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 "courgette/crc.h"

#ifdef OS_CHROMEOS
#  include "zlib.h"
#else
extern "C" {
#  include "third_party/lzma_sdk/7zCrc.h"
}
#endif

#include "base/basictypes.h"

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  uint32 crc;

#ifdef OS_CHROMEOS
  // Calculate Crc by calling CRC method in zlib
  crc = crc32(0, buffer, size);
#else
  // Calculate Crc by calling CRC method in LZMA SDK
  CrcGenerateTable();
  crc = CrcCalc(buffer, size);
#endif

  return ~crc;
}

}  // namespace

// 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.

// Calculate Crc by calling CRC method in LZMA SDK

#include "courgette/crc.h"

extern "C" {
#include "third_party/lzma_sdk/7zCrc.h"
}

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  CrcGenerateTable();
  uint32 crc = 0xffffffffL;
  crc = ~CrcCalc(buffer, size);
  return crc;
}

}  // namespace

Revert 112083 - Try a different library for Crc32.


/* 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 <ncurses.h>
#include <csignal>
#include <cstdlib>

#include "signals.hh"

extern "C" {
static void myexit(int i) {
    endwin();
    SIG_DFL(i);
}
}

namespace vick {

void setup_signal_handling() {
    signal(SIGABRT, myexit);
    signal(SIGFPE, myexit);
    signal(SIGILL, myexit);
    signal(SIGINT, myexit);
    signal(SIGSEGV, myexit);
    signal(SIGTERM, myexit);
}
}

/* 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 <ncurses.h>
#include <signal.h>
#include <stdlib.h>

#include "signals.hh"

extern "C" {
static void myexit(int i) {
    endwin();
    SIG_DFL(i);
}
}

namespace vick {

void setup_signal_handling() {
    signal(SIGABRT, myexit);
    signal(SIGFPE, myexit);
    signal(SIGILL, myexit);
    signal(SIGINT, myexit);
    signal(SIGSEGV, myexit);
    signal(SIGTERM, myexit);
}
}

Use `*.h` headers rather than `c*`


#include "commands.h"
#include "sim/except.h"
#include <iostream>

using namespace std;

void PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)
{
    out << endl << e.what() << endl;

    auto se = dynamic_cast<const Simulator::SimulationException*>(&e);
    if (se != NULL)
    {
        // SimulationExceptions hold more information, print it
        for (auto& p : se->GetDetails())
            out << p << endl;

        auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);
        if (te == NULL && se->GetPC() != 0)
        {
            // We avoid printing the backtrace when receiving an exception
            // for normal program termination.
            assert(sys != NULL);
            sys->Disassemble(se->GetPC());
        }
    }
}

#include "commands.h"
#include "sim/except.h"
#include <iostream>

using namespace std;

void PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)
{
    out << endl << e.what() << endl;

    auto se = dynamic_cast<const Simulator::SimulationException*>(&e);
    if (se != NULL)
    {
        // SimulationExceptions hold more information, print it
        for (auto& p : se->GetDetails())
            out << p << endl;

        auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);
        if (te == NULL && se->GetPC() != 0)
        {
            // We avoid printing the backtrace when receiving an exception
            // for normal program termination.
            if (sys != NULL)
                // Only disassemble if there is a system to do so.
                sys->Disassemble(se->GetPC());
        }
    }
}

Enable using PrintException even when no MGSystem is present.


/*############################################################################################
 Garden System
 Wireless controller for watering electropumps

 Author: Daniele Colanardi
 License: BSD, see LICENSE file
############################################################################################*/

#include <Wire.h>
#include "input.h"

LightMPR121 touch;

void init_buttons() {
	Wire.begin();
    touch.begin();
}

bool update_buttons() {
    touch.update();
}

bool is_pressed(uint8_t i) { return touch.touched(i); }
bool   released(uint8_t i) { return true; }

/*############################################################################################
 Garden System
 Wireless controller for watering electropumps

 Author: Daniele Colanardi
 License: BSD, see LICENSE file
############################################################################################*/

#include <Wire.h>
#include "input.h"

LightMPR121 touch;
int last_status;
long repeat_timer;
bool changed;

void init_buttons() {
	Wire.begin();
    touch.begin();
}

bool update_buttons() {
    int new_status = touch.update();

    changed = new_status != last_status;

    last_status = new_status;

    if (changed || millis() - repeat_timer > 150) {
    	repeat_timer = millis();
		if(!changed) changed = true;
    }
}

bool is_pressed(uint8_t i) { return touch.touched(i) && changed; }
bool   released(uint8_t i) { return true; }

Add basic retriggering to input