//=======================================================================
// Copyright (c) 2017 Adrian Schneider
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>
#include "mnist/mnist_reader.hpp"

int main(int argc, char* argv[]) {
    // MNIST_DATA_LOCATION set by MNIST cmake config
    std::cout << "MNIST data directory: " << MNIST_DATA_LOCATION << std::endl;

    // Load MNIST data
    mnist::MNIST_dataset<std::vector, std::vector<uint8_t>, uint8_t> dataSet =
        mnist::read_dataset<std::vector, std::vector, uint8_t, uint8_t>(MNIST_DATA_LOCATION);

    std::cout << "Nbr of training images = " << dataSet.training_images.size() << std::endl;
    std::cout << "Nbr of training labels = " << dataSet.training_labels.size() << std::endl;
    std::cout << "Nbr of test images = " << dataSet.test_images.size() << std::endl;
    std::cout << "Nbr of test labels = " << dataSet.test_labels.size() << std::endl;

    return 0;
}

//=======================================================================
// Copyright (c) 2017 Adrian Schneider
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>
#include "mnist/mnist_reader.hpp"

int main(int argc, char* argv[]) {
    // MNIST_DATA_LOCATION set by MNIST cmake config
    std::cout << "MNIST data directory: " << MNIST_DATA_LOCATION << std::endl;

    // Load MNIST data
    mnist::MNIST_dataset<std::vector, std::vector<uint8_t>, uint8_t> dataset =
        mnist::read_dataset<std::vector, std::vector, uint8_t, uint8_t>(MNIST_DATA_LOCATION);

    std::cout << "Nbr of training images = " << dataset.training_images.size() << std::endl;
    std::cout << "Nbr of training labels = " << dataset.training_labels.size() << std::endl;
    std::cout << "Nbr of test images = " << dataset.test_images.size() << std::endl;
    std::cout << "Nbr of test labels = " << dataset.test_labels.size() << std::endl;

    return 0;
}

Apply naming rule to dataSet -> dataset

Apply naming rule to dataSet -> dataset


#include <HX711.h>
#include "TimerDisplay.h"
#include "GramsDisplay.h"
#include "SmoothingFilter.h"

#define DISP_TIMER_CLK 2
#define DISP_TIMER_DIO 3
#define DISP_SCALE_CLK 8
#define DISP_SCALE_DIO 9

#define FILTER_SIZE 10
#define HYSTERESIS_SIZE 0.1

#define LOAD_CELL_DT A2
#define LOAD_CELL_SCK A1
#define SCALE_FACTOR 1874
#define TARE_AVERAGES 10

HX711 loadCell(LOAD_CELL_DT, LOAD_CELL_SCK);
TimerDisplay timerDisplay(DISP_TIMER_CLK, DISP_TIMER_DIO);
GramsDisplay gramsDisplay(DISP_SCALE_CLK, DISP_SCALE_DIO);
SmoothingFilter filter(FILTER_SIZE, HYSTERESIS_SIZE);

void setup()
{
  // Serial comm
  Serial.begin(38400);

  loadCell.set_scale(SCALE_FACTOR);
  loadCell.tare(TARE_AVERAGES);
}

void loop()
{
  filter.addValue(loadCell.get_units());
  float weight_in_grams = filter.getValue();

  gramsDisplay.display(weight_in_grams);

  if (weight_in_grams > 1)
    timerDisplay.start();

  timerDisplay.refresh();
}

#include <HX711.h>
#include "TimerDisplay.h"
#include "GramsDisplay.h"
#include "SmoothingFilter.h"

#define DISP_TIMER_CLK 2
#define DISP_TIMER_DIO 3
#define DISP_SCALE_CLK 8
#define DISP_SCALE_DIO 9

#define FILTER_SIZE 10
#define HYSTERESIS_SIZE 0.1

#define LOAD_CELL_DT A2
#define LOAD_CELL_SCK A1
#define SCALE_FACTOR 1874
#define TARE_AVERAGES 10

HX711 loadCell(LOAD_CELL_DT, LOAD_CELL_SCK);
TimerDisplay timerDisplay(DISP_TIMER_CLK, DISP_TIMER_DIO);
GramsDisplay gramsDisplay(DISP_SCALE_CLK, DISP_SCALE_DIO);
SmoothingFilter filter(FILTER_SIZE, HYSTERESIS_SIZE);

void setup()
{
  // Serial comm
  Serial.begin(38400);

  delay(500);
  loadCell.set_scale(SCALE_FACTOR);
  loadCell.tare(TARE_AVERAGES);
}

void loop()
{
  filter.addValue(loadCell.get_units());
  float weight_in_grams = filter.getValue();

  gramsDisplay.display(weight_in_grams);

  if (weight_in_grams > 1)
    timerDisplay.start();

  timerDisplay.refresh();
}

Add 500 ms delay on boot

Add 500 ms delay on boot

Fixes #11.


// Copyright 2013 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"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

class WebrtcCastApiTest : public ExtensionApiTest {
};

// Test running the test extension for Cast Mirroring API.
IN_PROC_BROWSER_TEST_F(WebrtcCastApiTest, Basics) {
  ASSERT_TRUE(RunExtensionSubtest("webrtc_cast", "basics.html"));
}

}  // namespace extensions

// Copyright 2013 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"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

class WebrtcCastApiTest : public ExtensionApiTest {
};

// Test running the test extension for Cast Mirroring API.
IN_PROC_BROWSER_TEST_F(WebrtcCastApiTest, DISABLED_Basics) {
  ASSERT_TRUE(RunExtensionSubtest("webrtc_cast", "basics.html"));
}

}  // namespace extensions

Disable webrtc cast api test

Disable webrtc cast api test

BUG=301920
TBR=mattm@chromium.org

Review URL: https://codereview.chromium.org/58953002

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@232914 0039d316-1c4b-4281-b951-d872f2087c98


/**
 * C++ algorithm to get the sum of all prime numbers between a range of 2 and the number desired.
 */

#include <iostream>
#include <cstdlib>

bool is_prime(unsigned int number);

int main(int argc, char* argv[])
{
	const char *num = "2000000";

	if(argv[1])
		num = argv[1];
	else if (argv[1] == "--help")
		std::cerr << "Usage: primes <number_of_primes>" << std::endl;

	std::cerr << "You've choosen the sum of the first " << num
	          << " prime numbers." << std::endl;

	// iteration variables.
	int i = 1;
	int j = 0;
	// the number to reach.
	int number_to = atoi(num);

	int sum = 0;

	while(j < number_to)
	{
		if(is_prime(i))
		{
			std::cerr << i << std::endl;
			sum += i;
			j++;
		}
		i++;
	}

	std::cerr << "The sum of the numbers between 2 and " << number_to
			  << " are: " << sum << std::endl;
	std::cout << sum << std::endl;
}

bool is_prime(unsigned int number)
{
	if (number <= 1)
		return false;

    unsigned int i;
    for (i=2; i*i<=number; i++)
	{
        if (number % i == 0)
		{
			return false;
		}
    }
    return true;
}

/**
 * C++ algorithm to get the sum of all prime numbers between a range of 2 and the number desired.
 */

#include <iostream>
#include <cstdlib>
#include <string.h>

bool is_prime(unsigned int number);

int main(int argc, char* argv[])
{
	const char *num = "2000000";

	if (strcmp(argv[1],"--help") == 0){
		std::cerr << "Usage: primes <number_of_primes>" << std::endl;
		exit(0);
	}
	else if(argv[1]) {
		num = argv[1];
	}

	// iteration variables.
	int i = 1;
	int j = 0;
	// the number to reach.
	int number_to = atoi(num);

	int sum = 0;

	while(j < number_to)
	{
		if(is_prime(i))
		{
			sum += i;
			j++;
		}
		i++;
	}

	std::cout << sum << std::endl;
}

bool is_prime(unsigned int number)
{
	if (number <= 1)
		return false;

    unsigned int i;
    for (i=2; i*i<=number; i++)
	{
        if (number % i == 0)
		{
			return false;
		}
    }
    return true;
}

Fix after @rafaelcn did blame me crying about incorrect usage of cerr


#include <iostream>

// Entry point for Dinit.

int dinit_main(int argc, char **argv);

int main(int argc, char **argv)
{
    try {
        return dinit_main(argc, argv);
    }
    catch (std::bad_alloc &badalloc) {
        std::cout << "dinit: Out-of-memory during initialisation" << std::endl;
        return 1;
    }
    catch (std::system_error &syserr) {
        std::cout << "dinit: unexpected system error during initialisation: " << syserr.what() << std::endl;
        return 1;
    }
    catch (...) {
        std::cout << "dinit: unexpected error during initialisation" << std::endl;
        return 1;
    }
}

#include <iostream>
#include <system_error>
#include <new>

// Entry point for Dinit.

int dinit_main(int argc, char **argv);

int main(int argc, char **argv)
{
    try {
        return dinit_main(argc, argv);
    }
    catch (std::bad_alloc &badalloc) {
        std::cout << "dinit: Out-of-memory during initialisation" << std::endl;
        return 1;
    }
    catch (std::system_error &syserr) {
        std::cout << "dinit: unexpected system error during initialisation: " << syserr.what() << std::endl;
        return 1;
    }
    catch (...) {
        std::cout << "dinit: unexpected error during initialisation" << std::endl;
        return 1;
    }
}

Add some missing includes, necessary on some platforms.


#ifdef __ANDROID__

double nan(const char*);
float nanf(const char*);
long double nanl(const char*);

#endif // __ANDROID__

// Standard Dependencies
#include <cmath>
#include <random>

// Module Dependencies
#include "../include/math.h"

namespace native
{
	static std::default_random_engine engine;

	double Math::sqrt(double value)
	{
		return (double)std::sqrt((long double)value);
	}

	long double Math::random(long double min, long double outerMax)
	{
		return std::uniform_real_distribution<long double>(min, outerMax)(engine);
	}

	double Math::random(double min, double outerMax)
	{
		return std::uniform_real_distribution<double>(min, outerMax)(engine);
	}

	float Math::random(float min, float outerMax)
	{
		return std::uniform_real_distribution<float>(min, outerMax)(engine);
	}

	int Math::random(int min, int outerMax)
	{
		return int(std::uniform_real_distribution<double>(double(min), double(outerMax))(engine));
	}
}

Fix for libc++ not properly declaring nan() functions.


#include <QCoreApplication>
#include <QDebug>

#include "ganalytics.h"

class Watcher : public QObject
{
    Q_OBJECT

public slots:
    void onIsSendingChanged(bool sending)
    {
        if (sending)
            return;

        QCoreApplication::instance()->quit();
    }
};

int main(int argc, char* argv[])
{
    QCoreApplication::setApplicationName("Console-App");
    QCoreApplication::setApplicationVersion("0.1");

    QCoreApplication app(argc, argv);

    // Create the tracker
    GAnalytics tracker("UA-53395376-1");

    Watcher watcher;
    QObject::connect(&tracker, SIGNAL(isSendingChanged(bool)), &watcher, SLOT(onIsSendingChanged(bool)));

    // Shorten the interval
    tracker.setSendInterval(5 * 1000);

    // Send some dummy events
    tracker.sendEvent("lifecycle", "application_started");
    tracker.sendEvent("lifecycle", "application_stopped");

    qDebug() << "Waiting until the evens were sent ...";

    int ret = app.exec();

    qDebug() << "Shutting down.";

    return ret;
}

#include "main.moc"

#include <QCoreApplication>
#include <QDebug>

#include "ganalytics.h"

class Watcher : public QObject
{
    Q_OBJECT

public slots:
    void onIsSendingChanged(bool sending)
    {
        if (sending)
            return;

        QCoreApplication::instance()->quit();
    }
};

int main(int argc, char* argv[])
{
    QCoreApplication::setOrganizationName("HSAnet");
    QCoreApplication::setApplicationName("Console-App");
    QCoreApplication::setApplicationVersion("0.1");

    QCoreApplication app(argc, argv);

    // Create the tracker
    GAnalytics tracker("UA-53395376-1");

    Watcher watcher;
    QObject::connect(&tracker, SIGNAL(isSendingChanged(bool)), &watcher, SLOT(onIsSendingChanged(bool)));

    // Shorten the interval
    tracker.setSendInterval(5 * 1000);

    // Send some dummy events
    tracker.sendEvent("lifecycle", "application_started");
    tracker.sendEvent("lifecycle", "application_stopped");

    qDebug() << "Waiting until the evens were sent ...";

    int ret = app.exec();

    qDebug() << "Shutting down.";

    return ret;
}

#include "main.moc"

Set organization name to save settings

Set organization name to save settings


#include "test_common.h"

#include <evpp/exp.h>
#include <evpp/libevent_headers.h>
#include <evpp/libevent_watcher.h>
#include <thread>

namespace {
static bool g_event_handler_called = false;
static void Handle(struct event_base* base) {
    g_event_handler_called = true;
    event_base_loopexit(base, 0);
}

static void MyEventThread(struct event_base* base, evpp::PipeEventWatcher* ev) {
    if (ev->Init()) {
        ev->AsyncWait();
    }

    event_base_loop(base, 0);
}
}

TEST_UNIT(testPipeEventWatcher) {
    struct event_base* base = event_base_new();
    evpp::PipeEventWatcher ev(base, std::bind(&Handle, base));
    std::thread th(MyEventThread, base, &ev);
    ::usleep(1000 * 100);
    ev.Notify();
    th.join();
    event_base_free(base);
    H_TEST_ASSERT(g_event_handler_called == true);
}

#include "test_common.h"

#include <evpp/exp.h>
#include <evpp/libevent_headers.h>
#include <evpp/libevent_watcher.h>
#include <thread>

namespace {
static bool g_event_handler_called = false;
static void Handle(struct event_base* base) {
    g_event_handler_called = true;
    event_base_loopexit(base, 0);
}

static void MyEventThread(struct event_base* base, evpp::PipeEventWatcher* ev) {
    if (ev->Init()) {
        ev->AsyncWait();
    }

    event_base_loop(base, 0);
    delete ev;// ȷʼͬһ߳
}
}

TEST_UNIT(testPipeEventWatcher) {
    struct event_base* base = event_base_new();
    evpp::PipeEventWatcher* ev = new evpp::PipeEventWatcher(base, std::bind(&Handle, base));
    std::thread th(MyEventThread, base, ev);
    ::usleep(1000 * 100);
    ev->Notify();
    th.join();
    event_base_free(base);
    H_TEST_ASSERT(g_event_handler_called == true);
}

Fix testPipeEventWatcher test case failed


#include "SketchItemEllipse.h"

#include <QGraphicsEllipseItem>

SketchItemEllipse::SketchItemEllipse(qreal x, qreal y)
    : SketchItemBezier(x, y)
{
    addPath(QPointF(30, 0), QPointF(50, 20), QPointF(50, 50));
    addPath(QPointF(50, 80), QPointF(30, 100), QPointF(0, 100));
    addPath(QPointF(-30, 100), QPointF(-40, 80), QPointF(-40, 50));
    addPath(QPointF(-40, 20), QPointF(-30, 0), QPointF(0, 0));
    closePath();
}

SketchItemEllipse::~SketchItemEllipse()
{

}

void SketchItemEllipse::boundBoxPointMoved(BoundingBoxPoint::TranslationDirection direction, QPointF delta)
{

}

#include "SketchItemEllipse.h"

#include <QGraphicsEllipseItem>

// Constants
static const uint TOP_INDEX     = 12;
static const uint RIGHT_INDEX   = 3;
static const uint BOTTOM_INDEX  = 6;
static const uint LEFT_INDEX    = 9;

SketchItemEllipse::SketchItemEllipse(qreal x, qreal y)
    : SketchItemBezier(x, y)
{
    addPath(QPointF(30, 0), QPointF(50, 20), QPointF(50, 50));
    addPath(QPointF(50, 80), QPointF(30, 100), QPointF(0, 100));
    addPath(QPointF(-40, 100), QPointF(-50, 80), QPointF(-50, 50));
    addPath(QPointF(-40, 20), QPointF(-30, 0), QPointF(0, 0));
    closePath();
    mBoundingBox->updateRect();
}

SketchItemEllipse::~SketchItemEllipse()
{

}

void SketchItemEllipse::boundBoxPointMoved(BoundingBoxPoint::TranslationDirection direction, QPointF delta)
{
    // because the path is closed, we don't have to
    // move the first item, the last is enough
    switch (direction) {

        default:
            qErrnoWarning("Unexpected TranslationDirection!");
            break;
    }
    mBoundingBox->updateRect(direction);
}

Prepare bounding box transform for Ellipse


#include "CacheJsonToArticleConverter.h"

ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache)
{
    return articleCache;
}

#include "CacheJsonToArticleConverter.h"

#include <json/json.h>

#include "WalkerException.h"
#include "Article.h"

ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache)
{
    Json::Reader reader;
    Json::Value document;
    bool success = reader.parse(json, document, false);

    if(!success) {
        throw WalkerException("Error parsing JSON");
    }

    // get all "main" articles first
    for(auto &titleElement : document.getMemberNames()) {
        std::string title = titleElement;

        Article *a = articleCache.get(title);

        if(a == nullptr) {
            a = new Article(title);
            articleCache.add(a);
        }

        for(auto linkedArticle :
            document.get(title, Json::Value::nullSingleton())
                    .get("forward_links", Json::Value::nullSingleton()))
        {
            std::string linkedTitle = linkedArticle.asString();
            Article *la = articleCache.get(linkedTitle);

            if(la == nullptr) {
                la = new Article(linkedTitle);
                articleCache.add(la);
            }

            a->addLink(la);
        }
    }

    return articleCache;
/*
    a->setAnalyzed(true); ?
*/
}

Add implementation to cache reader

Add implementation to cache reader


/*
 * Copyright 2015 - 2017 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
#include <iostream>
#include <map>
#include <functional>
#include <ox/std/std.hpp>

using namespace std;
using namespace ox::std;

template<typename T>
int testBigEndianAdapt(string str) {
	auto i = (T) stoul(str, nullptr, 16);
	return !(bigEndianAdapt(bigEndianAdapt(i)) == i);
}

map<string, function<int(string)>> tests = {
	{
		{ "bigEndianAdapt<uint16_t>", testBigEndianAdapt<uint16_t> },
		{ "bigEndianAdapt<uint32_t>", testBigEndianAdapt<uint32_t> },
		{ "bigEndianAdapt<uint64_t>", testBigEndianAdapt<uint64_t> },
	},
};

int main(int argc, const char **args) {
	if (argc > 1) {
		auto testName = args[1];
		auto testArg = args[2];
		if (tests.find(testName) != tests.end()) {
			return tests[testName](testArg);
		}
	}
	return -1;
}

/*
 * Copyright 2015 - 2017 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
#include <map>
#include <ox/std/std.hpp>

using namespace std;
using namespace ox::std;

template<typename T>
int testBigEndianAdapt(string str) {
	auto i = (T) stoull(str, nullptr, 16);
	return !(bigEndianAdapt(bigEndianAdapt(i)) == i);
}

map<string, int(*)(string)> tests = {
	{
		{ "bigEndianAdapt<uint16_t>", testBigEndianAdapt<uint16_t> },
		{ "bigEndianAdapt<uint32_t>", testBigEndianAdapt<uint32_t> },
		{ "bigEndianAdapt<uint64_t>", testBigEndianAdapt<uint64_t> },
	},
};

int main(int argc, const char **args) {
	int retval = -1;
	if (argc > 1) {
		auto testName = args[1];
		string testArg = args[2];
		if (tests.find(testName) != tests.end()) {
			retval = tests[testName](testArg);
		}
	}
	return retval;
}

Fix some PowerPC issues in the byteswap test


#include <QTest>
#include <QObject>

#include "uritests.h"

// This is all you need to run all the tests
int main(int argc, char *argv[])
{
    URITests test1;
    QTest::qExec(&test1);
}

#include <QTest>
#include <QObject>

#include "uritests.h"

// This is all you need to run all the tests
int main(int argc, char *argv[])
{
    bool fInvalid = false;

    URITests test1;
    if (QTest::qExec(&test1) != 0)
        fInvalid = true;

    return fInvalid;
}

Return !0 when qt tests fail.

Return !0 when qt tests fail.


#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#include <QtSingleApplication>

int main(int argc, char *argv[])
{
    // Only allow a single instance running.
    QtSingleApplication app(argc, argv);
    if (app.sendMessage("")) {
        return 0;
    }

    QQmlApplicationEngine engine;
    app.setWindowIcon(QIcon("resources/icons/ykman.png"));
    QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
    putenv(pythonNoBytecode.toUtf8().data());
    QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
    putenv(frameworks.toUtf8().data());
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));

    // Raise the root window on a message from new instance.
    for (auto object : engine.rootObjects()) {
        if (QWindow *window = qobject_cast<QWindow*>(object)) {
            QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() {
                window->raise();
            });
        }
    }
    return app.exec();
}

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#include <QtSingleApplication>

int main(int argc, char *argv[])
{
    // Only allow a single instance running.
    QtSingleApplication app(argc, argv);
    if (app.sendMessage("")) {
        return 0;
    }

    QQmlApplicationEngine engine;
    app.setWindowIcon(QIcon("resources/icons/ykman.png"));
    QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
    putenv(pythonNoBytecode.toUtf8().data());
    QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
    putenv(frameworks.toUtf8().data());
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));

    // Wake up the root window on a message from new instance.
    for (auto object : engine.rootObjects()) {
        if (QWindow *window = qobject_cast<QWindow*>(object)) {
            QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() {
                window->show();
                window->raise();
                window->requestActivate();
            });
        }
    }

    return app.exec();
}

Modify window raise on windows

Modify window raise on windows


#include <algorithm>
#include <cctype>
#include <sstream>

#include "cons.h"
#include "utils.h"

namespace mclisp
{

template<typename T>
std::string ContainerToString(T items)
{
  std::ostringstream oss;
  for(auto item : items)
    oss << item;
  return oss.str();
}

template std::string ContainerToString<>(std::set<Token> items);

// TODO Figure out where to put ShouldQuit
bool ShouldQuit(ConsCell *exp)
{
  std::ostringstream oss;
  oss << *exp;
  return EQ(exp, EOF) || oss.str() == "QUIT" || oss.str() == "(QUIT)";
}

std::string ToUpper(std::string s)
{
  std::transform(s.begin(), s.end(), s.begin(), ::toupper);
  return s;
}

std::string ToLower(std::string s)
{
  std::transform(s.begin(), s.end(), s.begin(), ::tolower);
  return s;
}

} // namespace mclisp

#include <algorithm>
#include <cctype>
#include <sstream>

#include "cons.h"
#include "utils.h"

namespace mclisp
{

template<typename T>
std::string ContainerToString(T items)
{
  std::ostringstream oss;
  for(auto item : items)
    oss << item;
  return oss.str();
}

template std::string ContainerToString<>(std::set<Token> items);

bool ShouldQuit(ConsCell *exp)
{
  std::ostringstream oss;
  oss << *exp;
  return EQ(exp, EOF) || oss.str() == "QUIT" || oss.str() == "(QUIT)";
}

std::string ToUpper(std::string s)
{
  std::transform(s.begin(), s.end(), s.begin(), ::toupper);
  return s;
}

std::string ToLower(std::string s)
{
  std::transform(s.begin(), s.end(), s.begin(), ::tolower);
  return s;
}

} // namespace mclisp

Remove comment about where to put ShouldQuit.


#include "polyChecksum.h"

PolyChecksum::PolyChecksum()
{
	// for all possible byte values
	for (unsigned i = 0; i < 256; ++i)
	{
		unsigned long reg = i << 24;
		// for all bits in a byte
		for (int j = 0; j < 8; ++j)
		{
			bool topBit = (reg & 0x80000000) != 0;
			reg <<= 1;

			if (topBit)
				reg ^= _key;
		}
		_table [i] = reg;
	}
}

void PolyChecksum::putBytes(void* bytes, size_t dataSize)
{
    unsigned char* ptr = (unsigned char*) bytes;

    for (int i = 0; i < dataSize; i++)
    {
        unsigned byte = (unsigned) ptr[i];
        unsigned top = _register >> 24;
        top ^= byte;

        _register = (_register << 8) ^ _table [top];
    }
}

int PolyChecksum::getResult()
{
    return (int) this->_register;
}

#include "polyChecksum.h"

PolyChecksum::PolyChecksum()
{
	// for all possible byte values
	for (unsigned i = 0; i < 256; ++i)
	{
		unsigned long reg = i << 24;
		// for all bits in a byte
		for (int j = 0; j < 8; ++j)
		{
			bool topBit = (reg & 0x80000000) != 0;
			reg <<= 1;

			if (topBit)
				reg ^= _key;
		}
		_table [i] = reg;
	}
}

void PolyChecksum::putBytes(void* bytes, size_t dataSize)
{
    unsigned char* ptr = (unsigned char*) bytes;

    for (size_t i = 0; i < dataSize; i++)
    {
        unsigned byte = *(ptr + i);
        unsigned top = _register >> 24;
        top ^= byte;
        top &= 255;

        _register = (_register << 8) ^ _table [top];
    }
}

int PolyChecksum::getResult()
{
    return (int) this->_register;
}

Fix out of bounds error on Linux.

Fix out of bounds error on Linux.


#include <MinConsole.hpp>
#include <Windows.h>
#include <mutex>

namespace MinConsole
{
void* GetOutputHandle()
{
	static void* Handle = nullptr;
	std::once_flag HandleCached;
	std::call_once(HandleCached, [=]()
		{
			Handle = GetStdHandle(STD_OUTPUT_HANDLE);
		});
	return Handle;
}

void SetTextColor(Color NewColor)
{
	SetConsoleTextAttribute(
		GetOutputHandle(),
		static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor)
	);
}

std::size_t GetWidth()
{
	CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
	if( GetConsoleScreenBufferInfo(
		GetOutputHandle(),
		&ConsoleInfo) )
	{
		return static_cast<size_t>(ConsoleInfo.dwSize.X);
	}
	return 0;
}
}

#include <MinConsole.hpp>
#include <Windows.h>
#include <mutex>

namespace MinConsole
{
void* GetOutputHandle()
{
	static void* Handle = nullptr;
	std::once_flag HandleCached;
	std::call_once(HandleCached, []()
		{
			Handle = GetStdHandle(STD_OUTPUT_HANDLE);
		});
	return Handle;
}

void SetTextColor(Color NewColor)
{
	SetConsoleTextAttribute(
		GetOutputHandle(),
		static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor)
	);
}

std::size_t GetWidth()
{
	CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
	if( GetConsoleScreenBufferInfo(
		GetOutputHandle(),
		&ConsoleInfo) )
	{
		return static_cast<size_t>(ConsoleInfo.dwSize.X);
	}
	return 0;
}
}

Remove capturing lambda capturing of static variable


/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * 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.
 */

//dummy file, so Android Studio will 'see' these folders

Add copyright notice required for open-sourcing

Test: builds OK
Change-Id: I1f148962d506ae697bc36f31aa8824082eea4171


#include "logic.cpp"
#include <iostream>
#include <cstdlib>

int main( void );
void printCoords( block* b );
int rotationTest( void );

int main( void )
{
  std::cout << "Rotation Test : " << (rotationTest())? "PASSED\n" : "FAILED\n";
  exit( EXIT_SUCCESS );
}

void printCoords( block *b )
{
  for( int i = 0; i < 4; ++i )
    {
      std::cout << i << "(" << b->coord[i].x << "," << b->coord[i].y << ")" << std::endl;
    }
  std::cout << std::endl;
}

int rotationTest( void )
{
  for( int i = 0; i < 5; ++i )
    {
      auto b1 = new block( i );

      printCoords( b1 );
      b1->rotate();
      printCoords( b1 );
      b1->rotate();
      printCoords( b1 );
      b1->rotate();
      printCoords( b1 );
      b1->rotate();
      printCoords( b1 );

      delete b1;
    }

  return 1;
}

#include "logic.cpp"
#include <iostream>
#include <cstdlib>

int main( void );
void printCoords( block* b );
int rotationTest( void );

int main( void )
{
  std::cout << "Rotation Test : " << (rotationTest())? "PASSED\n" : "FAILED\n";
  exit( EXIT_SUCCESS );
}

void printCoords( block *b )
{
  for( int i = 0; i < 4; ++i )
    {
      std::cout << i << "(" << b->coord[i].x << "," << b->coord[i].y << ")" << std::endl;
    }
  std::cout << std::endl;
}

int rotationTest( void )
{
  for( int i = 0; i < 5; ++i )
    {
      auto b1 = new block( i );

      std::cout << i << " {" << std::endl;

      printCoords( b1 );
      b1->rotate();
      printCoords( b1 );
      b1->rotate();
      printCoords( b1 );
      b1->rotate();
      printCoords( b1 );
      b1->rotate();
      printCoords( b1 );

      std::cout << "}" << std::endl;

      delete b1;
    }

  return 1;
}

Add identifying block number in rotation test


#include "unicode-utils.h"
#include <clocale>
#include <stdlib.h>
#include <string>

int UnicodeUtils::characters_in_bytes(const char* string, int bytes) {
  if (bytes == 0)
    return 0;

  mblen(NULL, 0);
  setlocale(LC_CTYPE, "en_US.UTF-8");

  int characters = 0;
  while (bytes > 0) {
    int characterLength = mblen(string, bytes);
    if (characterLength < 1)
      break;
    characters++;
    bytes -= characterLength;
    string += characterLength;
  }
  return characters;
}

int UnicodeUtils::bytes_in_characters(const char* string, int characters) {
  if (characters == 0)
    return 0;

  mblen(NULL, 0);
  setlocale(LC_CTYPE, "en_US.UTF-8");

  int bytes = 0;
  int length = strlen(string);
  while (length > 0) {
    int characterLength = mblen(string, length);
    if (characterLength < 1)
      break;

    bytes += characterLength;
    if (--characters == 0)
      break;

    length -= characterLength;
    string += characterLength;
  }
  return bytes;
}

#include "unicode-utils.h"
#include <clocale>
#include <stdlib.h>
#include <string.h>

int UnicodeUtils::characters_in_bytes(const char* string, int bytes) {
  if (bytes == 0)
    return 0;

  mblen(NULL, 0);
  setlocale(LC_CTYPE, "en_US.UTF-8");

  int characters = 0;
  while (bytes > 0) {
    int characterLength = mblen(string, bytes);
    if (characterLength < 1)
      break;
    characters++;
    bytes -= characterLength;
    string += characterLength;
  }
  return characters;
}

int UnicodeUtils::bytes_in_characters(const char* string, int characters) {
  if (characters == 0)
    return 0;

  mblen(NULL, 0);
  setlocale(LC_CTYPE, "en_US.UTF-8");

  int bytes = 0;
  int length = strlen(string);
  while (length > 0) {
    int characterLength = mblen(string, length);
    if (characterLength < 1)
      break;

    bytes += characterLength;
    if (--characters == 0)
      break;

    length -= characterLength;
    string += characterLength;
  }
  return bytes;
}

Include string.h instead of string

Include string.h instead of string


#include "create/types.h"

namespace create {

  RobotModel::RobotModel(const ProtocolVersion version, const float axleLength, const unsigned int baud, const float maxVelocity, const float wheelDiameter):
    id(nextId),
    version(version),
    axleLength(axleLength),
    baud(baud),
    maxVelocity(maxVelocity),
    wheelDiameter(wheelDiameter) {
    nextId <<= 1;
  }

  bool RobotModel::operator ==(RobotModel& other) const {
    return id == other.id;
  }

  RobotModel::operator uint32_t() const {
    return id;
  }

  uint32_t RobotModel::getId() const {
    return id;
  }

  ProtocolVersion RobotModel::getVersion() const {
    return version;
  }

  float RobotModel::getAxleLength() const {
    return axleLength;
  }

  unsigned int RobotModel::getBaud() const {
    return baud;
  }

  float RobotModel::getMaxVelocity() const {
    return maxVelocity;
  }

  float RobotModel::getWheelDiameter() const {
    return wheelDiameter;
  }

  uint32_t RobotModel::nextId = 1;

  RobotModel RobotModel::ROOMBA_400(V_1, 0.258, 57600);
  RobotModel RobotModel::CREATE_1(V_2, 0.258, 57600);
  RobotModel RobotModel::CREATE_2(V_3, 0.235, 115200);
}

#include "create/types.h"

namespace create {

  RobotModel::RobotModel(const ProtocolVersion version, const float axleLength, const unsigned int baud, const float maxVelocity, const float wheelDiameter):
    id(nextId),
    version(version),
    axleLength(axleLength),
    baud(baud),
    maxVelocity(maxVelocity),
    wheelDiameter(wheelDiameter) {
    nextId <<= 1;
  }

  bool RobotModel::operator ==(RobotModel& other) const {
    return id == other.id;
  }

  RobotModel::operator uint32_t() const {
    return id;
  }

  uint32_t RobotModel::getId() const {
    return id;
  }

  ProtocolVersion RobotModel::getVersion() const {
    return version;
  }

  float RobotModel::getAxleLength() const {
    return axleLength;
  }

  unsigned int RobotModel::getBaud() const {
    return baud;
  }

  float RobotModel::getMaxVelocity() const {
    return maxVelocity;
  }

  float RobotModel::getWheelDiameter() const {
    return wheelDiameter;
  }

  uint32_t RobotModel::nextId = 1;

  RobotModel RobotModel::ROOMBA_400(V_1, 0.258, 57600);
  RobotModel RobotModel::CREATE_1(V_2, 0.258, 57600);
  RobotModel RobotModel::CREATE_2(V_3, 0.235, 115200, 0.5, 0.072);
}

Update wheel diameter for Create 2

Update wheel diameter for Create 2

Now matches the spec from iRobot.

Signed-off-by: Jacob Perron <f862f167b85d41b225785c70d70808bc7337c1fe@openrobotics.org>


#include "test.h"
#include "test-job.h"
#include "test-machine.h"

#include <iostream>

int main()
{
    Test::TestSuite tests(std::cout);

    { // Job
        std::shared_ptr<Test::Test> jt1(new Test::JobID);
        tests.register_test(jt1);
        std::shared_ptr<Test::Test> jt2(new Test::JobMachineName);
        tests.register_test(jt2);
        std::shared_ptr<Test::Test> jt3(new Test::JobDefaultState);
        tests.register_test(jt3);
    }

    { // Machine
        std::shared_ptr<Test::Test> mt1(new Test::MachineName);
        tests.register_test(mt1);
        std::shared_ptr<Test::Test> mt2(new Test::MachineAddJob);
        tests.register_test(mt2);
    }

    { // Pool
    }

    bool all_ok = tests.run_all();
    if (all_ok)
        return 0;
    else
        return 1;
}

#include "test.h"
#include "test-job.h"
#include "test-machine.h"

#include <iostream>
#include <memory>

int main()
{
    Test::TestSuite tests(std::cout);

    // Set up tests - class Job
    tests.register_test(std::make_shared<Test::JobID>());
    tests.register_test(std::make_shared<Test::JobMachineName>());
    tests.register_test(std::make_shared<Test::JobDefaultState>());

    // Set up tests - class Machine
    tests.register_test(std::make_shared<Test::MachineName>());
    tests.register_test(std::make_shared<Test::MachineAddJob>());

    // Set up tests - class Pool

    // Run the tests
    bool all_ok = tests.run_all();
    if (all_ok)
        return 0;
    else
        return 1;
}

Convert to std::make_shared() to avoid allocation overhead

This also tidies up the code in main() in a way that doesn't make it
susceptible to memory leaks.


// Copyright 2015-2018 Elviss Strazdins. All rights reserved.

#include "AudioDeviceWASAPI.hpp"

namespace ouzel
{
    namespace audio
    {
        AudioDeviceWASAPI::AudioDeviceWASAPI(Mixer& initMixer):
            AudioDevice(Driver::WASAPI, initMixer)
        {
        }
    } // namespace audio
} // namespace ouzel

// Copyright 2015-2018 Elviss Strazdins. All rights reserved.

#include <string>
#include <Audioclient.h>
#include <mmdeviceapi.h>
#include "AudioDeviceWASAPI.hpp"

namespace ouzel
{
    namespace audio
    {
        class WASAPIErrorCategory : public std::error_category
        {
        public:
            const char* name() const noexcept override
            {
                return "DirectSound";
            }

            std::string message(int condition) const override
            {
                switch (condition)
                {
                    default: return "Unknown error (" + std::to_string(condition) + ")";
                }
            }
        };

        const WASAPIErrorCategory wasapiErrorCategory{};

        AudioDeviceWASAPI::AudioDeviceWASAPI(Mixer& initMixer):
            AudioDevice(Driver::WASAPI, initMixer)
        {
            IMMDeviceEnumerator* enumerator = nullptr;

            HRESULT hr;
            if (FAILED(hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, reinterpret_cast<LPVOID*>(&enumerator))))
                throw std::system_error(hr, wasapiErrorCategory, "Failed to create device enumerator");

            IMMDevice* device;
            if (FAILED(hr = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device)))
                throw std::system_error(hr, wasapiErrorCategory, "Failed to get audio endpoint");

            if (enumerator) enumerator->Release();
        }
    } // namespace audio
} // namespace ouzel

Create device enumerator and get default device for WASAPI


/*
 * Copyright (c) 2017-2018 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#include <vcf2multialign/graph_writer.hh>

namespace vcf2multialign
{
	// Dummy implementation.

	void graph_writer_impl::init(std::size_t n_rows)
	{
		graph.Init(n_rows);
	}

	void graph_writer_impl::process_segment(std::vector <std::vector <std::uint8_t>> const &segment_vec)
	{
		graph.AppendMatrixRange(segment_vec);
	}

	void graph_writer_impl::finish()
	{
		graph.CompleteConstruction();
		graph.PrintToDot(*m_dst_file);
	}
}

/*
 * Copyright (c) 2017-2018 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#include <vcf2multialign/graph_writer.hh>

namespace vcf2multialign
{
	// Dummy implementation.

	void graph_writer_impl::init(std::size_t n_rows)
	{
		graph.Init(n_rows);
	}

	void graph_writer_impl::process_segment(std::vector <std::vector <std::uint8_t>> const &segment_vec)
	{
		graph.AppendMatrixRange(segment_vec);
	}

	void graph_writer_impl::finish()
	{
		graph.CompleteConstruction();
		graph.PrintToGFA(*m_dst_file);
	}
}

Use the GFA output format

Use the GFA output format


#include "CoverReader.h"

#include <fstream>

NetworKit::Cover NetworKit::CoverReader::read(std::string path, NetworKit::Graph &G)
{
	std::ifstream file;
	file.open(path);
	if (!file.good()) {
		throw std::runtime_error("unable to read from file");
	}
	Cover communities(G.upperNodeIdBound());
	std::string line;
	count i = 0;
	node current;

	while (std::getline(file, line)) {
		communities.setUpperBound(i+1);
		std::stringstream linestream(line);
		while (linestream >> current) {
			communities.addToSubset(i, current);
		}
		++i;
	}

	file.close();
	return communities;
}

#include "CoverReader.h"

#include <fstream>

NetworKit::Cover NetworKit::CoverReader::read(std::string path, NetworKit::Graph &G)
{
	std::ifstream file;
	file.open(path);
	if (!file.good()) {
		throw std::runtime_error("unable to read from file");
	}
	Cover communities(G.upperNodeIdBound());
	std::string line;
	count i = 0;
	node current;

	while (std::getline(file, line)) {
		if (line.substr(0, 1) != "#") {
			communities.setUpperBound(i+1);
			std::stringstream linestream(line);
			while (linestream >> current) {
				communities.addToSubset(i, current);
			}
			++i;
		}
	}

	file.close();
	return communities;
}

Support comments in Cover files

Support comments in Cover files


#include <stdio.h>

#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/quick.hpp"

int get_index_smallest(const int k, int *data, const int start, const int end)
{
    if(k < 0 || k > end) return -1; /* Base case */
    int p = partition(data, start, end);

    if(k == 0) return data[start];
    else if(p - start == k) return data[p];
    else if(p - start > k) return get_index_smallest(k, data, start, p - 1);
    else return get_index_smallest(k - p - 1, data, p + 1, end);
}

int main(void)
{
    int k;
    printf("Enter k= ");
    scanf("%d", &k);

    const int size = 100000;
    int *data = make_random_data(size);
    printf("%d\n", get_index_smallest(k, data, 0, size - 1));

    free_random_data(data);
    return 0;
}

#include <stdio.h>

#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/quicksort.hpp"

int get_index_smallest(const int k, int *data, const int start, const int end)
{
    if(k < 0 || k > end) return -1; /* Base case */
    int p = partition(data, start, end);

    if(k == 0) return data[start];
    else if(p - start == k) return data[p];
    else if(p - start > k) return get_index_smallest(k, data, start, p - 1);
    else return get_index_smallest(k - p - 1, data, p + 1, end);
}

int main(void)
{
    int k;
    printf("Enter k= ");
    scanf("%d", &k);

    const int size = 100000;
    int *data = make_random_data(size);
    printf("%d\n", get_index_smallest(k, data, 0, size - 1));

    free_random_data(data);
    return 0;
}

Fix the not matching header file path

Fix the not matching header file path

* This commit due to commit 565888f949aabba22afad22d5d9a51568accfd32


/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mirplatform.h"
#include "mirplatformconnection.h"

#include <QRegion>
#include <QWindow>

namespace Maliit {

MirPlatform::MirPlatform():
    AbstractPlatform(),
    m_mirPlatformConnection(new MirPlatformConnection)
{
}

void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position)
{
    Q_UNUSED(window)
    Q_UNUSED(position)
}

void MirPlatform::setInputRegion(QWindow *window, const QRegion &region)
{
    Q_UNUSED(window)

    m_mirPlatformConnection->setGeometry(region.rects().first());
}

}

/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2014 Dinesh Manajipet <saidinesh5@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mirplatform.h"
#include "mirplatformconnection.h"

#include <QRegion>
#include <QWindow>

namespace Maliit {

MirPlatform::MirPlatform():
    AbstractPlatform(),
    m_mirPlatformConnection(new MirPlatformConnection)
{
}

void MirPlatform::setupInputPanel(QWindow *window, Maliit::Position position)
{
    Q_UNUSED(window)
    Q_UNUSED(position)
}

void MirPlatform::setInputRegion(QWindow *window, const QRegion &region)
{
    Q_UNUSED(window)

    if (!region.rects().isEmpty()) {
        m_mirPlatformConnection->setGeometry(region.rects().first());
    }
}

}

Check that region list isn't empty before attempting to retrieve a region from it


#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>

inline void my_panic(sol::optional<std::string> maybe_msg) {
	std::cerr << "Lua is in a panic state and will now abort() the application" << std::endl;
	if (maybe_msg) {
		const std::string& msg = maybe_msg.value();
		std::cerr << "\terror message: " << msg << std::endl;
	}
	// When this function exits, Lua will exhibit default behavior and abort()
}

int main (int, char*[]) {
	sol::state lua(sol::c_call<decltype(&my_panic), &my_panic>);
	// or, if you already have a lua_State* L
	// lua_atpanic( L, sol::c_call<decltype(&my_panic)>, &my_panic> );
	// or, with state/state_view:
	// sol::state_view lua(L);
	// lua.set_panic( sol::c_call<decltype(&my_panic)>, &my_panic> );

	// uncomment the below to see
	//lua.script("boom_goes.the_dynamite");

	return 0;
}

#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>

inline void my_panic(sol::optional<std::string> maybe_msg) {
	std::cerr << "Lua is in a panic state and will now abort() the application" << std::endl;
	if (maybe_msg) {
		const std::string& msg = maybe_msg.value();
		std::cerr << "\terror message: " << msg << std::endl;
	}
	// When this function exits, Lua will exhibit default behavior and abort()
}

int main (int, char*[]) {
	sol::state lua(sol::c_call<decltype(&my_panic), &my_panic>);
	// or, if you already have a lua_State* L
	// lua_atpanic( L, sol::c_call<decltype(&my_panic), &my_panic> );
	// or, with state/state_view:
	// sol::state_view lua(L);
	// lua.set_panic( sol::c_call<decltype(&my_panic), &my_panic> );

	// uncomment the below to see
	//lua.script("boom_goes.the_dynamite");

	return 0;
}

Fix typo in exception documentation

Fix typo in exception documentation


#include <Magick++/ResourceLimits.h>
#include <Magick++/SecurityPolicy.h>

#ifndef FUZZ_MAX_SIZE
#define FUZZ_MAX_SIZE 2048
#endif

class FuzzingLimits {
public:
  FuzzingLimits() {
    Magick::SecurityPolicy::maxMemoryRequest(256000000);
    Magick::ResourceLimits::memory(1000000000);
    Magick::ResourceLimits::map(500000000);
    Magick::ResourceLimits::width(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::height(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::listLength(32);
  }
};

FuzzingLimits fuzzingLimits;

#if BUILD_MAIN
#include "encoder_format.h"

EncoderFormat encoderFormat;

#define FUZZ_ENCODER encoderFormat.get()
#endif // BUILD_MAIN

#include <Magick++/Functions.h>
#include <Magick++/ResourceLimits.h>
#include <Magick++/SecurityPolicy.h>

#ifndef FUZZ_MAX_SIZE
#define FUZZ_MAX_SIZE 2048
#endif

class FuzzingInitializer {
public:
  FuzzingInitializer() {
    Magick::InitializeMagick((const char *) NULL);
    Magick::SecurityPolicy::maxMemoryRequest(256000000);
    Magick::ResourceLimits::memory(1000000000);
    Magick::ResourceLimits::map(500000000);
    Magick::ResourceLimits::width(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::height(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::listLength(32);
  }
};

FuzzingInitializer fuzzingInitializer;

#if BUILD_MAIN
#include "encoder_format.h"

EncoderFormat encoderFormat;

#define FUZZ_ENCODER encoderFormat.get()
#endif // BUILD_MAIN

Call InitializeMagick to make sure all initializers are called.


//===-- asan_preinit.cc ---------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Call __asan_init at the very early stage of process startup.
//===----------------------------------------------------------------------===//
#include "asan_internal.h"

#if SANITIZER_CAN_USE_PREINIT_ARRAY
  // The symbol is called __local_asan_preinit, because it's not intended to be
  // exported.
  __attribute__((section(".preinit_array"), used))
  void (*__local_asan_preinit)(void) = __asan_init;
#endif

//===-- asan_preinit.cc ---------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Call __asan_init at the very early stage of process startup.
//===----------------------------------------------------------------------===//
#include "asan_internal.h"

using namespace __asan;

#if SANITIZER_CAN_USE_PREINIT_ARRAY
  // The symbol is called __local_asan_preinit, because it's not intended to be
  // exported.
  __attribute__((section(".preinit_array"), used))
  void (*__local_asan_preinit)(void) = AsanInitFromRtl;
#endif

[asan] Switch to AsanInitFromRtl in .preinit_array.

There is no functionality change due to a check in AsanActivate.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@221882 91177308-0d34-0410-b5e6-96231b3b80d8


#define NO_EXTERN
#include"variables.hpp"
#include"processes.hpp"
#include<iostream>

int main(int argc, const char* argv[]){
	globals.reset(new Globals());
	NILATOM = globals->lookup("nil");
	TATOM = globals->lookup("t");

	/*tests!*/
	Process proc;
	/*allocate stuff*/
	//(cons t ...)
	proc.stack.push(new(proc) Sym(TATOM));//t
	//(cons t nil)
	proc.stack.push(new(proc) Sym(TATOM)); //t
	proc.stack.push(new(proc) Sym(NILATOM)); //nil
	//cons
	{
		Cons* cp = new(proc) Cons();
		cp->a = proc.stack.top(2);
		cp->d = proc.stack.top();
		proc.stack.top(2) = cp;
		proc.stack.pop();
	}
	//another cons
	{
		Cons* cp = new(proc) Cons();
		cp->a = proc.stack.top(2);
		cp->d = proc.stack.top();
		proc.stack.top(2) = cp;
		proc.stack.pop();
	}

	proc.stack.top()->probe(0);
}

#include"variables.hpp"
#include"processes.hpp"
#include<iostream>

int main(int argc, const char* argv[]){
	variables_init();

	/*tests!*/
	Process proc;
	/*allocate stuff*/
	//(cons t ...)
	proc.stack.push(new(proc) Sym(TATOM));//t
	//(cons t nil)
	proc.stack.push(new(proc) Sym(TATOM)); //t
	proc.stack.push(new(proc) Sym(NILATOM)); //nil
	//cons
	{
		Cons* cp = new(proc) Cons();
		cp->a = proc.stack.top(2);
		cp->d = proc.stack.top();
		proc.stack.top(2) = cp;
		proc.stack.pop();
	}
	//another cons
	{
		Cons* cp = new(proc) Cons();
		cp->a = proc.stack.top(2);
		cp->d = proc.stack.top();
		proc.stack.top(2) = cp;
		proc.stack.pop();
	}

	proc.stack.top()->probe(0);
}

Test now initializes using variables_init()


#include<cmath>
#include<iostream>

using namespace std;

bool isPrimeBruteForce(double x)
{
	if (x < 2)
		return false;
	double sqroot_x = sqrt(x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return false;
	}
	return true;
}

int main(int argc, char* argv[])
{
	double number;
	bool result;
	cout << "Enter number to test if it's prime: ";
	cin >> number;
	result = isPrimeBruteForce(number);
	if (result) {
		cout << number << " is a prime number.";
	} else {
		cout << number << " is not a prime number.";
	}
	return 0;
}

#include<math.h>
#include<stdio.h>
/*#include<iostream>

using namespace std;*/

int isPrimeBruteForce(int x)
{
	if (x < 2)
		return false;
	double sqroot_x;
	sqroot_x = sqrt (x);
	for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
		if (x%i==0)
			return 0;
	}
	return 1;
}

int main(int argc, char* argv[])
{
	int result;
/*	int number;
	cout << "Enter number to test if it's prime: ";
	cin >> number;
	result = isPrimeBruteForce(number);
	if (result) {
		cout << number << " is a prime number.";
	} else {
		cout << number << " is not a prime number.";
	}*/
	result = isPrimeBruteForce(37);
	printf("Is 37 a prime number? %i", result);
	return 0;
}

Replace c++ libraries by c standard libraries, make working for c language too


// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -emit-llvm -o - %s | FileCheck %s
// PR7490

int main() {
  // CHECK: {{for.cond:|:4}}
  // CHECK: %{{.*}} = icmp ult i64 %{{.*}}, 1133
  // CHECK: {{for.body:|:6}}
  // CHECK: store i8 0
  // CHECK: br label %{{for.inc|7}}
  // CHECK: {{for.inc:|:7}}
  // CHECK: %{{.*}} = add i64 %{{.*}}, 1
  // CHECK: store i64 %{{.*}}
  // CHECK: br label %{{for.cond|4}}
  // CHECK: {{for.end:|:12}}
  volatile char *buckets = new char[1133]();
}

// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -O3 -emit-llvm -o - %s | FileCheck %s
// PR7490

// CHECK: define signext i8 @_Z2f0v
// CHECK: ret i8 0
// CHECK: }
inline void* operator new[](unsigned long, void* __p)  { return __p; }
static void f0_a(char *a) {
  new (a) char[4]();
}
char f0() {
  char a[4];
  f0_a(a);
  return a[0] + a[1] + a[2] + a[3];
}

tests: Rewrite test to check intent instead of implementation.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@107024 91177308-0d34-0410-b5e6-96231b3b80d8


#include "common.th"
#include "vga.th"

_start:
    prologue
    b <- 0              // indicate non-completion to testbench

    call(init_display)

restart:
    c <- 0
    j <- @VGA_BASE
    k <- (ROWS * COLS)
    k <- k + j

top:
    c -> [j]
    c <- c + 1
    c <- c & 0xff

    j <- j + 1
    n <- j < k
    p <- @+top & n + p

    b <- -1             // indicate completion to testbench
    p <- p + @+restart     // restartable, but exits to testbench by default
    illegal

#include "common.th"
#include "vga.th"

_start:
    prologue
    b <- 0              // indicate non-completion to testbench

    call(init_display)

restart:
    c <- 0
    j <- @VGA_BASE
    k <- (ROWS * COLS)
    k <- k + j

top:
    c -> [j]
    c <- c + 1
    c <- c & 0xff

    j <- j + 1
    n <- j < k
    p <- @+top & n + p

    b <- -1             // indicate completion to testbench
    //p <- p + @+restart  // restartable, but exits to testbench by default
    illegal

Make bm_chars match its internal comment


// RUN: rm -rf %t

// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/modules.cache \
// RUN:  -I %S/Inputs/odr_hash-Friend \
// RUN:  -emit-obj -o /dev/null \
// RUN:  -fmodules \
// RUN:  -fimplicit-module-maps \
// RUN:  -fmodules-cache-path=%t/modules.cache \
// RUN:  -std=c++11 -x c++ %s -verify

// UNSUPPORTED: system-windows

// expected-no-diagnostics

#include "Box.h"
#include "M1.h"
#include "M3.h"

void Run() {
  Box<> Present;
}

// RUN: rm -rf %t

// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/modules.cache \
// RUN:  -I %S/Inputs/odr_hash-Friend \
// RUN:  -emit-obj -o /dev/null \
// RUN:  -fmodules \
// RUN:  -fimplicit-module-maps \
// RUN:  -fmodules-cache-path=%t/modules.cache \
// RUN:  -std=c++11 -x c++ %s -verify

// PR35939: MicrosoftMangle.cpp triggers an assertion failure on this test.
// UNSUPPORTED: system-windows

// expected-no-diagnostics

#include "Box.h"
#include "M1.h"
#include "M3.h"

void Run() {
  Box<> Present;
}

Add context to why test was disabled on Windows

test/Modules/odr_hash-Friend.cpp triggers an assertion in MicrosoftMangle.cpp
This has been reported in PR35939

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@322593 91177308-0d34-0410-b5e6-96231b3b80d8


int main(int argc, char **argv)
{
	return 0;
}

#include "heap.h"
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <glibmm/error.h>

int main(int argc, char **argv)
{
	VM::Heap heap;
	const size_t ARR_SIZE = 128;
	const size_t TEST_SIZE = 50;
	size_t ptrs[ARR_SIZE] = { 0 };
	srand(0);

	try
	{
		for(size_t i = 0; i < TEST_SIZE; i ++)
		{
			size_t index = rand() % ARR_SIZE;
			if(ptrs[index])
			{
				std::cout << "= Free " << ptrs[index] << std::endl;
				heap.Detach(ptrs[index]);
				ptrs[index] = 0;
			}
			else
			{
				ptrs[index] = heap.Alloc(0x1, i);
				std::cout << "= Alloc " << ptrs[index] << std::endl;
				if(! ptrs[index])
				{
					std::cout << "Error Alloc" << std::endl;
					break;
				}
			}
		}
		for(size_t index = 0; index < ARR_SIZE; index ++)
		{
			if(ptrs[index])
			{
				heap.Detach(ptrs[index]);
			}
		}
	}
	catch(Glib::Error &e)
	{
		std::cout << "Glib::Error: " << e.what() << std::endl;
	}
	catch(std::exception &e)
	{
		std::cout << "std::exception: " << e.what() << std::endl;
	}

	return 0;
}

Add test for allocation/freeing heap.

Add test for allocation/freeing heap.


#include "stdafx.h"
#include "SettingsUI.h"
#include "SettingsSheet.h"

IMPLEMENT_DYNAMIC(SettingsSheet, CPropertySheet)

SettingsSheet::SettingsSheet(
    UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) :
CPropertySheet(nIDCaption, pParentWnd, iSelectPage) {

}

SettingsSheet::SettingsSheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage)
    : CPropertySheet(pszCaption, pParentWnd, iSelectPage) {
}

SettingsSheet::~SettingsSheet() {
}

BOOL SettingsSheet::OnInitDialog() {
    CPropertySheet::OnInitDialog();
    return TRUE;
}

BEGIN_MESSAGE_MAP(SettingsSheet, CPropertySheet)
END_MESSAGE_MAP()

#include "stdafx.h"
#include "SettingsUI.h"
#include "SettingsSheet.h"

IMPLEMENT_DYNAMIC(SettingsSheet, CPropertySheet)

SettingsSheet::SettingsSheet(
    UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) :
CPropertySheet(nIDCaption, pParentWnd, iSelectPage) {

}

SettingsSheet::SettingsSheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage)
    : CPropertySheet(pszCaption, pParentWnd, iSelectPage) {
}

SettingsSheet::~SettingsSheet() {
}

BOOL SettingsSheet::OnInitDialog() {
    CPropertySheet::OnInitDialog();
    return TRUE;
}

LRESULT SettingsSheet::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) {
    if (message == WM_3RVX_SETTINGSCTRL) {
        SetForegroundWindow();
    }
    return CPropertySheet::WindowProc(message, wParam, lParam);
}

BEGIN_MESSAGE_MAP(SettingsSheet, CPropertySheet)
END_MESSAGE_MAP()

Raise window to foreground if another instance was launched


#include "Server.h"
#include "WebPage.h"
#include "Connection.h"

#include <QTcpServer>

Server::Server(QObject *parent, bool ignoreSslErrors) : QObject(parent) {
  m_tcp_server = new QTcpServer(this);
  m_page = new WebPage(this);
  m_page->setIgnoreSslErrors(ignoreSslErrors);
}

bool Server::start() {
  connect(m_tcp_server, SIGNAL(newConnection()), this, SLOT(handleConnection()));
  return m_tcp_server->listen(QHostAddress::Any, 0);
}

quint16 Server::server_port() const {
  return m_tcp_server->serverPort();
}

void Server::handleConnection() {
  QTcpSocket *socket = m_tcp_server->nextPendingConnection();
  new Connection(socket, m_page, this);
}

#include "Server.h"
#include "WebPage.h"
#include "Connection.h"

#include <QTcpServer>

Server::Server(QObject *parent, bool ignoreSslErrors) : QObject(parent) {
  m_tcp_server = new QTcpServer(this);
  m_page = new WebPage(this);
  m_page->setIgnoreSslErrors(ignoreSslErrors);
}

bool Server::start() {
  connect(m_tcp_server, SIGNAL(newConnection()), this, SLOT(handleConnection()));
  return m_tcp_server->listen(QHostAddress::LocalHost, 0);
}

quint16 Server::server_port() const {
  return m_tcp_server->serverPort();
}

void Server::handleConnection() {
  QTcpSocket *socket = m_tcp_server->nextPendingConnection();
  new Connection(socket, m_page, this);
}

Make the server bind to localhost. We don't really want to expose it to the world, and it pops up firewall warnings if you have an app aware firewall enabled (e.g. OSX firewall).


#include <cmath>

#include <ros/ros.h>
#include <geometry_msgs/TransformStamped.h>
#include <rviz_visual_tools/rviz_visual_tools.h>
#include <tf2_eigen/tf2_eigen.h>
#include <tf2_ros/transform_listener.h>

#include <Eigen/Geometry>

int main(int argc, char** argv)
{
  ros::init(argc, argv, "body_angle_visualizer");
  ros::NodeHandle n {};
  ros::Rate r {5};
  tf2_ros::Buffer tfBuffer {};
  tf2_ros::TransformListener tfListener {tfBuffer};
  rviz_visual_tools::RvizVisualTools rvt {"openni_depth_frame", "rviz_visual_markers"};

  while (ros::ok()) {
    auto head_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "head", ros::Time {0}))};
    auto torso_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "torso", ros::Time {0}))};
    const auto stand_vec {head_pos.translation() - torso_pos.translation()};

    Eigen::Affine3d arrow {};
    arrow.translation() = stand_vec;

    rvt.deleteAllMarkers();
    rvt.publishArrow(arrow);

    rvt.trigger();

    r.sleep();
  }
}

#include <cmath>

#include <ros/ros.h>
#include <rviz_visual_tools/rviz_visual_tools.h>
#include <tf2_eigen/tf2_eigen.h>
#include <tf2_ros/transform_listener.h>

#include <Eigen/Geometry>

int main(int argc, char** argv)
{
  ros::init(argc, argv, "body_angle_visualizer");
  ros::NodeHandle n {};
  ros::Rate r {5};
  tf2_ros::Buffer tfBuffer {};
  tf2_ros::TransformListener tfListener {tfBuffer};
  rviz_visual_tools::RvizVisualTools rvt {"openni_depth_frame", "rviz_visual_markers"};

  while (ros::ok()) {
    try {
      const auto head_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "head_1", ros::Time {0}))};
      const auto torso_pos {tf2::transformToEigen(tfBuffer.lookupTransform("openni_depth_frame", "torso_1", ros::Time {0}))};
      const auto stand_vec {head_pos.translation() - torso_pos.translation()};
      const auto stand_quaternion {Eigen::Quaterniond::FromTwoVectors(Eigen::Vector3d::UnitX(), stand_vec)};

      rvt.deleteAllMarkers();

      Eigen::Affine3d arrow {stand_quaternion};
      rvt.publishArrow(arrow);

      rvt.trigger();
    } catch (tf2::TransformException &e) {
      ROS_WARN("%s", e.what());
    }

    r.sleep();
  }
}

Update view for angle arrow

Update view for angle arrow


#include "ImageData.h"

#include <OpenGL/gl3.h>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include "stb/stb_image.h"
#pragma clang diagnostic pop

bool ImageData::LoadPng(const char* filePath)
{
	int components = 0;
	data = stbi_load(filePath, &size.x, &size.y, &components, 0);

	if (data != nullptr)
	{
		pixelFormat = (components == 4 ? GL_RGBA : GL_RGB);
		return true;
	}
	else
	{
		assert(false);
		return false;
	}
}

void ImageData::DeallocateData()
{
	if (data != nullptr)
		stbi_image_free(data);
}

#include "ImageData.h"

#include <OpenGL/gl3.h>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast"
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include "stb/stb_image.h"
#pragma clang diagnostic pop

bool ImageData::LoadPng(const char* filePath)
{
	int components = 0;
	data = stbi_load(filePath, &size.x, &size.y, &components, 0);

	if (data != nullptr)
	{
		assert(components >= 0 && components < 4);

		static const GLenum formats[] = { GL_RED, GL_RG, GL_RGB, GL_RGBA };
		pixelFormat = formats[components - 1];

		return true;
	}
	else
	{
		assert(false);
		return false;
	}
}

void ImageData::DeallocateData()
{
	if (data != nullptr)
		stbi_image_free(data);
}

Change image data components detection

Change image data components detection


#include "runtime_internal.h"

#ifdef BITS_64
#define WIN32API
#else
#define WIN32API __stdcall
#endif

extern "C" {

WIN32API void *LoadLibrary(const char *);
WIN32API void *GetProcAddress(void *, const char *);

WEAK void *halide_get_symbol(const char *name) {
    return GetProcAddress(NULL, name);
}

WEAK void *halide_load_library(const char *name) {
    return LoadLibrary(name);
}

WEAK void *halide_get_library_symbol(void *lib, const char *name) {
    return GetProcAddress(lib, name);
}

}

#include "runtime_internal.h"

#ifdef BITS_64
#define WIN32API
#else
#define WIN32API __stdcall
#endif

extern "C" {

WIN32API void *LoadLibraryA(const char *);
WIN32API void *GetProcAddress(void *, const char *);

WEAK void *halide_get_symbol(const char *name) {
    return GetProcAddress(NULL, name);
}

WEAK void *halide_load_library(const char *name) {
    return LoadLibraryA(name);
}

WEAK void *halide_get_library_symbol(void *lib, const char *name) {
    return GetProcAddress(lib, name);
}

}

Fix missing LoadLibrary symbol on windows.

Former-commit-id: 43619e309e8a912aaf57011937121c77d2b5c16a


Set size policy associated with view description label

* Doing so will ensure the label doesn't expand.


#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <jni.h>
#include <android/log.h>

#define LOG_TAG "codec_unittest"
#define LOGI(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)

int CodecUtMain(int argc, char** argv);
extern "C"
JNIEXPORT void JNICALL Java_com_cisco_codec_unittest_MainActivity_DoUnittest
(JNIEnv* env, jobject thiz,jstring jspath) {
  /**************** Add the native codes/API *****************/
  char* argv[2];
  int  argc = 2;
  argv[0] = (char*) ("codec_unittest.exe");
  argv[1] = (char*) ((*env).GetStringUTFChars (jspath,NULL));
  LOGI ("PATH:",+argv[1]);
  LOGI ("Start to run JNI module!+++");
 CodecUtMain(argc,argv);
  LOGI ("End to run JNI module!+++");
}

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <jni.h>
#include <android/log.h>

#define LOG_TAG "codec_unittest"
#define LOGI(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)

int CodecUtMain(int argc, char** argv);
extern "C"
JNIEXPORT void JNICALL Java_com_cisco_codec_unittest_MainActivity_DoUnittest
(JNIEnv* env, jobject thiz,jstring jspath) {
  /**************** Add the native codes/API *****************/
  char* argv[2];
  int  argc = 2;
  argv[0] = (char*) ("codec_unittest.exe");
  argv[1] = (char*) ((*env).GetStringUTFChars (jspath,NULL));
  LOGI ("PATH: %s", argv[1]);
  LOGI ("Start to run JNI module!+++");
 CodecUtMain(argc,argv);
  LOGI ("End to run JNI module!+++");
}

Use a correct format string in the unittest JNI wrapper


/////////////////////////////////////////////////////////////////////////////
// This file is part of EasyRPG.
//
// EasyRPG 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.
//
// EasyRPG 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
/////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "rpg_event.h"

////////////////////////////////////////////////////////////
/// Constructor
////////////////////////////////////////////////////////////
RPG::Event::Event() {
	ID = 0;
	name = "";
	x = 0;
	y = 5;
}

/////////////////////////////////////////////////////////////////////////////
// This file is part of EasyRPG.
//
// EasyRPG 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.
//
// EasyRPG 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
/////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "rpg_event.h"

////////////////////////////////////////////////////////////
/// Constructor
////////////////////////////////////////////////////////////
RPG::Event::Event() {
	ID = 0;
	name = "";
	x = 0;
	y = 0;
}

Reset hero graphic on map change (if it was changed by a move event). Fix RPG::Event default value for y. Minor cleanups.


#include <cmath>

#include "clock_converter.h"
#include "log.h"

UInt64 convertCycleCount(UInt64 cycle_count, volatile float from_frequency, volatile float to_frequency)
{
   UInt64 converted_cycle_count = (UInt64) ceil(((float) cycle_count) * (to_frequency / from_frequency));

   LOG_PRINT("convertCycleCount(%llu): from_frequency(%f), to_frequency(%f) -> (%llu)",
             cycle_count, from_frequency, to_frequency, converted_cycle_count);

   return converted_cycle_count;
}

#include <cmath>

#include "clock_converter.h"
#include "log.h"

UInt64 convertCycleCount(UInt64 cycle_count, volatile float from_frequency, volatile float to_frequency)
{
   UInt64 converted_cycle_count = (UInt64) ceil(((double) cycle_count) * (to_frequency / from_frequency));

   LOG_PRINT("convertCycleCount(%llu): from_frequency(%f), to_frequency(%f) -> (%llu)",
             cycle_count, from_frequency, to_frequency, converted_cycle_count);

   return converted_cycle_count;
}

Revert "[dynamic frequency scaling] Fixed the bug on the convertCycleCount function."

This reverts commit 46a484a5e4288f7da92e6f789687d2d141fbcf15.


#include <boost/test/unit_test.hpp>

#include "../uint256.h"

extern void SHA256Transform(void* pstate, void* pinput, const void* pinit);

BOOST_AUTO_TEST_SUITE(miner_tests)

BOOST_AUTO_TEST_CASE(sha256transform_equality)
{
    unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

    unsigned char pstate[32];
    unsigned char pinput[32];

    int i;

    for (i = 0; i < 32; i++) {
        pinput[i] = i;
        pstate[i] = 0;
    }

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

		BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

#include <boost/test/unit_test.hpp>

#include "../uint256.h"

extern void SHA256Transform(void* pstate, void* pinput, const void* pinit);

BOOST_AUTO_TEST_SUITE(miner_tests)

BOOST_AUTO_TEST_CASE(sha256transform_equality)
{
    unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

    unsigned char pstate[32];
    unsigned char pinput[64];

    int i;

    for (i = 0; i < 32; i++) {
        pinput[i] = i;
        pinput[i+32] = 0;
    }

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

    BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

Fix miner_test unit test bug

Fix miner_test unit test bug


//===- unittests/TimerTest.cpp - Timer tests ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Timer.h"
#include "gtest/gtest.h"
#include <chrono>
#include <thread>

using namespace llvm;

namespace {

TEST(Timer, Additivity) {
  Timer T1("T1");

  EXPECT_TRUE(T1.isInitialized());

  T1.startTimer();
  T1.stopTimer();
  auto TR1 = T1.getTotalTime();

  T1.startTimer();
  std::this_thread::sleep_for(std::chrono::milliseconds(1));
  T1.stopTimer();
  auto TR2 = T1.getTotalTime();

  EXPECT_TRUE(TR1 < TR2);
}

TEST(Timer, CheckIfTriggered) {
  Timer T1("T1");

  EXPECT_FALSE(T1.hasTriggered());
  T1.startTimer();
  EXPECT_TRUE(T1.hasTriggered());
  T1.stopTimer();
  EXPECT_TRUE(T1.hasTriggered());

  T1.clear();
  EXPECT_FALSE(T1.hasTriggered());
}

} // end anon namespace

//===- unittests/TimerTest.cpp - Timer tests ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Timer.h"
#include "llvm/Support/Thread.h"
#include "gtest/gtest.h"
#include <chrono>

using namespace llvm;

namespace {

TEST(Timer, Additivity) {
  Timer T1("T1");

  EXPECT_TRUE(T1.isInitialized());

  T1.startTimer();
  T1.stopTimer();
  auto TR1 = T1.getTotalTime();

  T1.startTimer();
  std::this_thread::sleep_for(std::chrono::milliseconds(1));
  T1.stopTimer();
  auto TR2 = T1.getTotalTime();

  EXPECT_TRUE(TR1 < TR2);
}

TEST(Timer, CheckIfTriggered) {
  Timer T1("T1");

  EXPECT_FALSE(T1.hasTriggered());
  T1.startTimer();
  EXPECT_TRUE(T1.hasTriggered());
  T1.stopTimer();
  EXPECT_TRUE(T1.hasTriggered());

  T1.clear();
  EXPECT_FALSE(T1.hasTriggered());
}

} // end anon namespace

[unittest] Use Support/Thread.h instead of <thread> to fix the Windows build

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@256290 91177308-0d34-0410-b5e6-96231b3b80d8


#include <iostream>
#include <stdexcept>
#include <type_traits>

#include "fsm.h"

class state_machine: public fsmlite::fsm<state_machine> {
    friend class fsm;  // base class needs access to transition_table
public:
    enum states { Init, Exit };

private:
    void process(const int& event) {
        std::cout << "Processing event: " << event << "\n";
#ifdef NDEBUG
        if (event != 0) {
            throw std::logic_error("recursive invocation detected");
        }
#endif
        process_event(event + 1);
    }

private:
    typedef state_machine m;

    using transition_table = table<
//              Start Event  Target Action
//  -----------+-----+------+------+-----------+-
    mem_fn_row< Init, int,   Exit,  &m::process >
//  -----------+-----+------+------+-----------+-
    >;
};

int main()
{
    state_machine m;
    try {
        m.process_event(0);
    } catch (std::logic_error& e) {
        std::cerr << e.what() << "\n";
        return 0;
    }
    return 1;
}

#include <iostream>
#include <stdexcept>
#include <type_traits>

#include "fsm.h"

class state_machine: public fsmlite::fsm<state_machine> {
    friend class fsm;  // base class needs access to transition_table
public:
    enum states { Init, Exit };

private:
    void process(const int& event) {
        std::cout << "Processing event: " << event << "\n";
#ifdef NDEBUG
        if (event != 0) {
            throw std::logic_error("recursive invocation detected");
        }
#endif
        process_event(event + 1);
    }

private:
    typedef state_machine m;

    using transition_table = table<
//              Start Event  Target Action
//  -----------+-----+------+------+-----------+-
    mem_fn_row< Init, int,   Exit,  &m::process >
//  -----------+-----+------+------+-----------+-
    >;
};

int main()
{
    state_machine m;
    try {
        m.process_event(0);
    } catch (std::logic_error& e) {
        std::cerr << e.what() << "\n";
        return 0;
    }
    return 1;  /* LCOV_EXCL_LINE */
}

Exclude skipped lines from coverage.

Exclude skipped lines from coverage.


#include "catch.hpp"

#include "visual.hh"
#include "configuration.hh"

using namespace vick;

TEST_CASE("to_visual")
{
    std::string first("assert"), second("\tblah");
    for (int i = 0; i < first.size(); i++)
        REQUIRE(i == to_visual(first, i));
    for (int i = 0; i < second.size(); i++)
        REQUIRE(TAB_SIZE - 1 + i == to_visual(second, i));
}

TEST_CASE("from_visual")
{
    std::string first("\thi"), second("\t\thi");
    for (int i = 1; i < TAB_SIZE - 1; i++) {
        REQUIRE(0 == from_visual(first, TAB_SIZE - i));
    }
    REQUIRE(0 == from_visual(first, TAB_SIZE - 1));
    REQUIRE(1 == from_visual(first, TAB_SIZE));
    REQUIRE(2 == from_visual(first, TAB_SIZE + 1));
}

#include "catch.hpp"

#include "visual.hh"
#include "configuration.hh"

using namespace vick;

TEST_CASE("to_visual")
{
    std::string first("assert"), second("\tblah");
    for (size_t i = 0; i < first.size(); i++)
        REQUIRE(i == to_visual(first, i));
    for (size_t i = 0; i < second.size(); i++)
        REQUIRE(TAB_SIZE - 1 + i == to_visual(second, i));
}

TEST_CASE("from_visual")
{
    std::string first("\thi"), second("\t\thi");
    for (int i = 1; i < TAB_SIZE - 1; i++) {
        REQUIRE(0 == from_visual(first, TAB_SIZE - i));
    }
    REQUIRE(0 == from_visual(first, TAB_SIZE - 1));
    REQUIRE(1 == from_visual(first, TAB_SIZE));
    REQUIRE(2 == from_visual(first, TAB_SIZE + 1));
}

Use `size_t` when needed instead of just `int`


#include "dlgfilters.h"
#include "filterwidget.h"

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>

DlgFilters::DlgFilters(const QList<QPair<bool,QString> >& filters,
            QWidget *parent)
        : QDialog(parent, Qt::Dialog) {
    setWindowTitle(tr("strigiclient - Edit filters"));
    filterwidget = new FilterWidget();
    filterwidget->setFilters(filters);
    QPushButton* ok = new QPushButton(tr("&Ok"));
    ok->setDefault(true);
    QPushButton* cancel = new QPushButton(tr("&Cancel"));

    QVBoxLayout* layout = new QVBoxLayout();
    setLayout(layout);
    layout->addWidget(filterwidget);
    QHBoxLayout* hl = new QHBoxLayout();
    layout->addLayout(hl);
    hl->addStretch();
    hl->addWidget(ok);
    hl->addWidget(cancel);
    connect(ok, SIGNAL(clicked()), this, SLOT(accept()));
    connect(cancel, SIGNAL(clicked()), this, SLOT(reject()));
}
const QList<QPair<bool,QString> >&
DlgFilters::getFilters() const {
    return filterwidget->getFilters();
}

#include "dlgfilters.h"
#include "filterwidget.h"

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>

DlgFilters::DlgFilters(const QList<QPair<bool,QString> >& filters,
            QWidget *parent)
        : QDialog(parent, Qt::Dialog) {
    setWindowTitle(tr("strigiclient - Edit filters"));
    QLabel* explanation = new QLabel(tr("Define filters that determine which files will be included and which will be excluded from the index, e.g. '*.html' or '.svn/' (do not index directories called '.svn')."));
    explanation->setWordWrap(true);
    filterwidget = new FilterWidget();
    filterwidget->setFilters(filters);
    QPushButton* ok = new QPushButton(tr("&Ok"));
    ok->setDefault(true);
    QPushButton* cancel = new QPushButton(tr("&Cancel"));

    QVBoxLayout* layout = new QVBoxLayout();
    setLayout(layout);
    layout->addWidget(explanation);
    layout->addWidget(filterwidget);
    QHBoxLayout* hl = new QHBoxLayout();
    layout->addLayout(hl);
    hl->addStretch();
    hl->addWidget(ok);
    hl->addWidget(cancel);
    connect(ok, SIGNAL(clicked()), this, SLOT(accept()));
    connect(cancel, SIGNAL(clicked()), this, SLOT(reject()));
}
const QList<QPair<bool,QString> >&
DlgFilters::getFilters() const {
    return filterwidget->getFilters();
}

Add small explanation to the filter dialog.

svn path=/trunk/playground/base/strigi/; revision=609264


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

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(main_tests)

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

BOOST_AUTO_TEST_SUITE_END()

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

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(main_tests)

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

BOOST_AUTO_TEST_SUITE_END()

Edit subsidy_limit_test to account for BIP42

Because no one wants 4 gold mines being discovered every mibillenium.


Fix compilation error with C++11 compliant compiler (user-defined literals)


//Injector source file for the Tech Target Check hook module.
#include "tech_target_check.h"
#include <hook_tools.h>

namespace {

const u32 Func_GetTechUseErrorMessage = 0x00491E80;

void __declspec(naked) getTechUseErrorMessageWrapper() {
  static CUnit *target;
  static u8 castingPlayer;
  static u16 techId;
  static u16 errorMessage;

  __asm {
    PUSHAD
    MOV target, EAX
    MOV castingPlayer, BL
    MOV EAX, [EBP + 4]
    MOV techId, AX
  }

  errorMessage = hooks::getTechUseErrorMessageHook(target, castingPlayer, techId);

  __asm {
    POPAD
    MOV AX, errorMessage
    RETN 4
  }
}

} //Unnamed namespace

namespace hooks {

void injectTechTargetCheckHooks() {
  jmpPatch(getTechUseErrorMessageWrapper, Func_GetTechUseErrorMessage);
}

u16 getTechUseErrorMessage(const CUnit *target, s8 castingPlayer, u16 techId) {
  u32 techId_ = techId;
  static u16 errorMessage;

  __asm {
    PUSHAD
    PUSH techId_
    MOV BL, castingPlayer
    MOV EAX, target
    CALL Func_GetTechUseErrorMessage
    MOV errorMessage, AX
    POPAD
  }

  return errorMessage;
}

} //hooks

//Injector source file for the Tech Target Check hook module.
#include "tech_target_check.h"
#include <hook_tools.h>

namespace {

const u32 Func_GetTechUseErrorMessage = 0x00491E80;

void __declspec(naked) getTechUseErrorMessageWrapper() {
  static CUnit *target;
  static u8 castingPlayer;
  static u16 techId;
  static u16 errorMessage;

  __asm {
    PUSHAD
    MOV EBP, ESP
    MOV target, EAX
    MOV castingPlayer, BL
    MOV EAX, [ESP + 36]   ;// (PUSHAD saves 32) + (CALL saves 4) == 36
    MOV techId, AX
  }

  errorMessage = hooks::getTechUseErrorMessageHook(target, castingPlayer, techId);

  __asm {
    POPAD
    MOV AX, errorMessage
    RETN 4
  }
}

} //Unnamed namespace

namespace hooks {

void injectTechTargetCheckHooks() {
  jmpPatch(getTechUseErrorMessageWrapper, Func_GetTechUseErrorMessage);
}

u16 getTechUseErrorMessage(const CUnit *target, s8 castingPlayer, u16 techId) {
  u32 techId_ = techId;
  static u16 errorMessage;

  __asm {
    PUSHAD
    PUSH techId_
    MOV BL, castingPlayer
    MOV EAX, target
    CALL Func_GetTechUseErrorMessage
    MOV errorMessage, AX
    POPAD
  }

  return errorMessage;
}

} //hooks

Fix bug in Tech Target Check hook module.


struct Foo {
  Foo(int);
};
void foo() {
  struct {
    Foo name;
  } Int[] =  { 1 };
}

struct Foo {
  Foo(int);
  ~Foo();
};
void foo() {
  struct {
    Foo name;
  } Int[] =  { 1 };
}

Add a dtor to ensure that they are called the right number of times.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@9721 91177308-0d34-0410-b5e6-96231b3b80d8


#include "settings.h"

int N_POLY_POINTS = 4;
int N_COLOR_VAR = 5;
int N_POS_VAR = 5;
int SHAPE_OPT_FREQ = 25;
int GUI_REFRESH_RATE = 1;

int AUTOFOCUS_RES = 2;

int FOCUS_LEFT=0, FOCUS_RIGHT=100, FOCUS_TOP=0, FOCUS_BOTTOM=100;

#include "settings.h"

int N_POLY_POINTS = 4;
int N_COLOR_VAR = 5;
int N_POS_VAR = 5;
int SHAPE_OPT_FREQ = 0;
int GUI_REFRESH_RATE = 1;

int AUTOFOCUS_RES = 2;

int FOCUS_LEFT=0, FOCUS_RIGHT=100, FOCUS_TOP=0, FOCUS_BOTTOM=100;

Disable random shape optimizations by default

Since it's not very effective. It only works well when adding a new
poly.


#include "gamelib/components/update/CameraTracker.hpp"
#include "gamelib/core/rendering/CameraSystem.hpp"
#include "gamelib/core/ecs/Entity.hpp"

namespace gamelib
{
    CameraTracker::CameraTracker() :
        UpdateComponent(1, UpdateHookType::PostPostFrame),
        camera(0),
        shakerad(5),
        _shake(false)
    {
        _props.registerProperty("shakeradius", shakerad);
        _props.registerProperty("camera", camera);
    }

    void CameraTracker::update(float elapsed)
    {
        auto ent = getEntity();
        if (!ent)
            return;

        Camera* cam = getCamera();
        if (!cam)
            return;

        if (_shake)
        {
            _secondsleft -= elapsed;
            if (_secondsleft <= 0)
            {
                _shake = false;
                return;
            }

            math::Vec2f off(-shakerad, -shakerad);
            off += math::Vec2f(std::fmod(random(), shakerad * 2),
                               std::fmod(random(), shakerad * 2));

            cam->center(ent->getTransform().getBBox().getCenter() + off);
        }
        else
        {
            cam->center(ent->getTransform().getBBox().getCenter());
        }
    }

    void CameraTracker::shake(float seconds)
    {
        _shake = true;
        _secondsleft = seconds;
    }

    Camera* CameraTracker::getCamera() const
    {
        return getSubsystem<CameraSystem>()->get(camera);
    }
}

#include "gamelib/components/update/CameraTracker.hpp"
#include "gamelib/core/rendering/CameraSystem.hpp"
#include "gamelib/core/ecs/Entity.hpp"

namespace gamelib
{
    CameraTracker::CameraTracker() :
        UpdateComponent(1, UpdateHookType::PostPostFrame),
        camera(0),
        shakerad(5),
        _shake(false)
    {
        _props.registerProperty("shakeradius", shakerad);
        _props.registerProperty("camera", camera);
    }

    void CameraTracker::update(float elapsed)
    {
        auto ent = getEntity();
        if (!ent)
            return;

        Camera* cam = getCamera();
        if (!cam)
            return;

        math::Vec2f offset;

        if (_shake)
        {
            _secondsleft -= elapsed;
            if (_secondsleft <= 0)
            {
                _shake = false;
                return;
            }

            offset.fill(-shakerad);
            offset += math::Vec2f(std::fmod(random(), shakerad * 2),
                                  std::fmod(random(), shakerad * 2));
        }
        cam->center(ent->getTransform().getPosition() + offset);
    }

    void CameraTracker::shake(float seconds)
    {
        _shake = true;
        _secondsleft = seconds;
    }

    Camera* CameraTracker::getCamera() const
    {
        return getSubsystem<CameraSystem>()->get(camera);
    }
}

Use entity position rather than bbox center

Prevents camera jumping when the player size changes.


#include <franka/robot.h>
#include <iostream>

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage: ./echo_robot_state <robot-hostname>" << std::endl;
    return -1;
  }

  try {
    franka::Robot robot(argv[1]);

    size_t count = 0;
    robot.read([&count](const franka::RobotState& robot_state) {
      std::cout << robot_state << std::endl;
      return count++ < 100;
    });

    std::cout << "Done." << std::endl;
  } catch (franka::Exception const& e) {
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}

#include <franka/robot.h>
#include <iostream>

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage: ./echo_robot_state <robot-hostname>" << std::endl;
    return -1;
  }

  try {
    franka::Robot robot(argv[1]);

    size_t count = 0;
    robot.read([&count](const franka::RobotState& robot_state) {
      // Printing to std::cout adds a delay. This is acceptable for a read loop such as this,
      // but should not be done in a control loop.
      std::cout << robot_state << std::endl;
      return count++ < 100;
    });

    std::cout << "Done." << std::endl;
  } catch (franka::Exception const& e) {
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}

Add comment regarding use of std::cout.

examples: Add comment regarding use of std::cout.


// Standard headers
#include <cmath>
#include <iostream>

// Libraries
#include "Math.hpp"

const double PI = 3.141592653589793238462643;

unsigned long int factorial (unsigned long int n) {
  return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}

double fixRadians_impl(double radians) {
  if (radians > 2*PI)
    return fixRadians_impl(radians - 2*PI);
  return radians;
}

double fixRadians(double radians) {
  return fixRadians_impl(std::abs(radians));
}

double calculateCosine(double radians) {
  double cos = 0;
  radians = fixRadians(radians);

  for (int n = 0; n < 10; n++) {
    int signal = n % 2 == 0 ? 1 : -1;
    cos += signal * (std::pow(radians, 2*n) / factorial(2*n));
  }

  return cos;
}

// Standard headers
#include <cmath>
#include <iostream>

// Libraries
#include "Math.hpp"

const double PI = 3.141592653589793238462643;

// Alias
using mpz = unsigned long int;
using mpf = double;

mpz factorial (mpz n) {
  return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}

mpf fixRadians_impl(mpf radians) {
  if (radians > 2*PI)
    return fixRadians_impl(radians - 2*PI);
  return radians;
}

mpf fixRadians(mpf radians) {
  return fixRadians_impl(std::abs(radians));
}

mpf calculateCosine(mpf radians) {
  mpf cos = 0;
  radians = fixRadians(radians);

  for (int n = 0; n < 10; n++) {
    int signal = n % 2 == 0 ? 1 : -1;
    cos += signal * (std::pow(radians, 2*n) / factorial(2*n));
  }

  return cos;
}

Create alias for integer and floating point type


#include "GlobalContext.hpp"
#include "ast/SourceFile.hpp"
#include "parser/SpiritParser.hpp"

int main(int argc, char* args[])
{
    const std::vector<std::string> argv(args+1, args+argc);

    using namespace eddic;
    using namespace eddic::parser;

    for (int i=0; i<5; i++)
        for (auto& fname : argv)
        {
            SpiritParser parser;

            eddic::ast::SourceFile program;
            parser.parse(fname, program, std::make_shared<GlobalContext>(Platform::INTEL_X86_64));
        }
}

#include "GlobalContext.hpp"
#include "ast/SourceFile.hpp"
#include "parser/SpiritParser.hpp"

int main(int argc, char* args[])
{
    const std::vector<std::string> argv(args+1, args+argc);

    using namespace eddic;
    using namespace eddic::parser;

    for (int i=0; i<100; i++)
        for (auto& fname : argv)
        {
            SpiritParser parser;

            eddic::ast::SourceFile program;
            parser.parse(fname, program, std::make_shared<GlobalContext>(Platform::INTEL_X86_64));
        }
}

Update the number of iterations

Update the number of iterations


/*
 * Justin's Awesome Game Engine
 * or *
 * Just Another Game Engine
 *
 * Copyright 2016 Justin White
 *
 * See included LICENSE file for distribution and reuse.
*/

#include <cstdio>

#include <Engine.hpp>

int main(const int argc, const char** argv) {
    std::cout << "Start" << std::endl;;
    Engine theGame(argc, argv);
    if (theGame.ready()) {
        if (theGame.run()) {
        } else {
            std::cerr << "Error running Engine, quitting." << std::endl;;
            return EXIT_FAILURE;
        }
    } else {
        std::cerr << "Could not initialize Engine, quitting." << std::endl;;
        return EXIT_FAILURE;
    }
    std::cout << "Done" << std::endl;;

    return EXIT_SUCCESS;
}

/*
 * Justin's Awesome Game Engine
 * or *
 * Just Another Game Engine
 *
 * Copyright 2016 Justin White
 *
 * See included LICENSE file for distribution and reuse.
*/

#include <Engine.hpp>

static std::unique_ptr<Engine> theGame;

int success(const std::string& msg);
int fail(const std::string& msg);

int main(const int argc, const char** argv) {
    std::cout << "Start" << std::endl;
    theGame = std::make_unique<Engine>(argc, argv);
    if (not theGame->ready()) {
        return fail("Could not initialize Engine, quitting.");
    }
    if (not theGame->run()) {
        return fail("Error running Engine, quitting.");
    }
    return success("Done");
}

int success(const std::string& msg) {
    theGame.release();
    std::cout << msg << std::endl;
    return EXIT_SUCCESS;
}

int fail(const std::string& msg) {
    theGame.release();
    std::cerr << msg << std::endl;
    return EXIT_FAILURE;
}

Reorganize main() for clarity and modern C++-ness.


#include <iostream>
#include "Board.h"
#include "Renderer.h"

int main(int argc, char** argv)
{
	Board board(10, 10, 2);
	Renderer renderer;
	if(renderer.init() != 0)
	{
		renderer.quit();
		return 1;
	}

	for(int i = 0; i < 5; ++i)
	{
		renderer.render();
		SDL_Delay(1000);
	}

	renderer.quit();

	return 0;
}

#include <iostream>
#include "Board.h"
#include "Renderer.h"

int main(int argc, char** argv)
{
	Board board(10, 10, 2);
	Renderer renderer;
	if(renderer.init() != 0)
	{
		renderer.quit();
		return 1;
	}

	bool running = true;
	SDL_Event event;
	while(running)
	{
		while(SDL_PollEvent(&event))
		{
			// Close window
			if(event.type == SDL_QUIT)
			{
				running = false;
			}
			// Presses any key
			if(event.type == SDL_KEYDOWN)
			{
				running = false;
			}
			// Click the mouse
			if(event.type == SDL_MOUSEBUTTONDOWN)
			{
				running = false;
			}

		}
		renderer.render();

	}

	renderer.quit();

	return 0;
}

Add simple event handling to quit

Add simple event handling to quit


#include "../src/vault.h"

#include <fstream>
#include <iostream>

namespace
{

// Copy example/credentials.txt.example to example/credentials.txt and
// put your username and then password on the next line.

std::pair<std::string, std::string> read_credentials()
{
    std::ifstream f("example/credentials.txt");
    if (!f.is_open())
        throw std::runtime_error("Failed to open credentials file");

    std::string username;
    std::string password;
    f >> username >> password;

    return std::make_pair(username, password);
}

}

int main(int argc, char const *argv[])
{
    using namespace lastpass;

    try
    {
        auto credentials = read_credentials();

        auto vault = Vault::create(credentials.first, credentials.second);
        for (auto const &i: vault.accounts())
        {
            std::cout << "      id: " << i.id() << '\n'
                      << "    name: " << i.name() << '\n'
                      << "username: " << i.username() << '\n'
                      << "password: " << i.password() << '\n'
                      << "   group: " << i.group() << '\n'
                      << "     url: " << i.url() << '\n'
                      << '\n';
        }
    }
    catch (std::exception const &e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

#include "../src/vault.h"

#include <fstream>
#include <iostream>

namespace
{

// Copy example/credentials.txt.example to example/credentials.txt and
// put your username and then password on the next line.

std::pair<std::string, std::string> read_credentials()
{
    std::string username;
    std::string password;

    std::ifstream f("example/credentials.txt");
    if (f.is_open())
    {
        f >> username >> password;
    }
    else
    {
        std::cout << "Enter username: " << std::flush;
        std::cin >> username;

        std::cout << "Enter password: " << std::flush;
        std::cin >> password;
    }

    return std::make_pair(username, password);
}

}

int main(int argc, char const *argv[])
{
    using namespace lastpass;

    try
    {
        auto credentials = read_credentials();

        auto vault = Vault::create(credentials.first, credentials.second);
        for (auto const &i: vault.accounts())
        {
            std::cout << "      id: " << i.id() << '\n'
                      << "    name: " << i.name() << '\n'
                      << "username: " << i.username() << '\n'
                      << "password: " << i.password() << '\n'
                      << "   group: " << i.group() << '\n'
                      << "     url: " << i.url() << '\n'
                      << '\n';
        }
    }
    catch (std::exception const &e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

Read credentials from the keyboard if the file is not found


#include "InternalCommands.h"
#include "Environment.h"
#include "Feeder.h"
#include <iostream>
using namespace std;

int InternalCommands::exec(int argc, char const** argv,Environment *e,Feeder *f)
{
	if(strncmp(argv[0],"echo",4) == 0){
		exit( echo(argc,argv) );
	}else if(strncmp(argv[0],"pid",3) == 0){
		exit( pid(argc,argv,e) );
	}
	return -1;
}

int InternalCommands::echo(int argc, char const** argv)
{
	for(int i = 1; i < argc-1; i++){
		cout << argv[i] << " ";
	}
	if(argc > 1)
		cout << argv[argc-1] << endl;

	return 0;
}

int InternalCommands::pid(int argc, char const** argv,Environment *e)
{
	cout << e->m_pid << endl;
	return 0;
}

#include "InternalCommands.h"
#include "Environment.h"
#include "Feeder.h"
#include <iostream>
#include <string.h>
using namespace std;

int InternalCommands::exec(int argc, char const** argv,Environment *e,Feeder *f)
{
	if(strncmp(argv[0],"echo",4) == 0){
		exit( echo(argc,argv) );
	}else if(strncmp(argv[0],"pid",3) == 0){
		exit( pid(argc,argv,e) );
	}
	return -1;
}

int InternalCommands::echo(int argc, char const** argv)
{
	for(int i = 1; i < argc-1; i++){
		cout << argv[i] << " ";
	}
	if(argc > 1)
		cout << argv[argc-1] << endl;

	return 0;
}

int InternalCommands::pid(int argc, char const** argv,Environment *e)
{
	cout << e->m_pid << endl;
	return 0;
}

Add a header file for linux

Add a header file for linux


// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s

// PR39118
// Make sure that attributes are properly applied to explicit template
// instantiations.

#define HIDDEN __attribute__((__visibility__("hidden")))
#define VISIBLE __attribute__((__visibility__("default")))

namespace ns HIDDEN {
    struct A { };
    template <typename T> struct B { static A a; };
    template <typename T> A B<T>::a;

    // CHECK: @_ZN2ns1BIiE1aE = weak_odr global
    // CHECK-NOT: hidden
    template VISIBLE A B<int>::a;
}

struct C { };
template <typename T> struct D { static C c; };
template <typename T> C D<T>::c;

// CHECK-DAG: @_ZN1DIiE1cB3TAGE
template __attribute__((abi_tag("TAG"))) C D<int>::c;

// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm %s -o - | FileCheck %s

// PR39118
// Make sure that attributes are properly applied to explicit template
// instantiations.

#define HIDDEN __attribute__((__visibility__("hidden")))
#define VISIBLE __attribute__((__visibility__("default")))

namespace ns HIDDEN {
    struct A { };
    template <typename T> struct B { static A a; };
    template <typename T> A B<T>::a;

    // CHECK: @_ZN2ns1BIiE1aE = weak_odr global
    // CHECK-NOT: hidden
    template VISIBLE A B<int>::a;
}

struct C { };
template <typename T> struct D { static C c; };
template <typename T> C D<T>::c;

// CHECK-DAG: @_ZN1DIiE1cB3TAGE
template __attribute__((abi_tag("TAG"))) C D<int>::c;

Fix failing attribute test on Windows

[clang] Fix failing attribute test on Windows

The test added in r344146 was failing because the ABI on Windows is
different, and that test includes ABI-specific details. The test now
harcodes which ABI to use so we can rely on those details.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@344159 91177308-0d34-0410-b5e6-96231b3b80d8


#include "PythonParserBase.h"

using namespace antlr4;

PythonParserBase::PythonParserBase(antlr4::TokenStream *input) : Parser(input)
{
}

bool PythonParserBase::CheckVersion(int version)
{
	return Version == PythonVersion::Autodetect || version == (int) Version;
}

void PythonParserBase::SetVersion(int requiredVersion)
{
	Version = (PythonVersion) requiredVersion;
}

#include "PythonParserBase.h"

using namespace antlr4;

PythonParserBase::PythonParserBase(antlr4::TokenStream *input) : Parser(input)
{
	Version = PythonVersion::Autodetect;
}

bool PythonParserBase::CheckVersion(int version)
{
	return Version == PythonVersion::Autodetect || version == (int) Version;
}

void PythonParserBase::SetVersion(int requiredVersion)
{
	Version = (PythonVersion) requiredVersion;
}

Fix bug in Cpp parser base class initialization. Regression tests all pass now.