#include "thread_checker.h"

#include <windows.h>
#include "Processthreadsapi.h"

namespace dux {

#ifdef _WIN32

ThreadChecker::ThreadChecker() : thread_id_(GetCurrentThreadId()) {}

bool ThreadChecker::IsCreationThreadCurrent() const {
  return GetCurrentThreadId() == thread_id_;
}

#endif

}  // namespace dux

#include "thread_checker.h"

#ifdef _WIN32

#include <windows.h>
#include "Processthreadsapi.h"

namespace dux {

ThreadChecker::ThreadChecker() : thread_id_(GetCurrentThreadId()) {}

bool ThreadChecker::IsCreationThreadCurrent() const {
  return GetCurrentThreadId() == thread_id_;
}

}  // namespace dux

#endif

Fix build on non-windows platforms.


Add an XFAIL for Newlib's missing uchar.h


#include <iostream>
#include <ccspec/core/formatters/text_formatter.h>

namespace ccspec {
namespace core {
namespace formatters {

using std::endl;
using std::exception;
using std::exception_ptr;
using std::list;
using std::ostream;
using std::rethrow_exception;

// Public methods.

void TextFormatter::afterEachHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `after(:example)` hook" << endl;
    outputException(failure);
}

void TextFormatter::afterAllHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `after(:context)` hook" << endl;
    outputException(failure);
}

void TextFormatter::aroundHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `around(:example)` hook" << endl;
    outputException(failure);
}

void TextFormatter::dumpFailures(const list<exception_ptr>& failures) const {
    if (failures.empty())
        return;

    output_ << "Failures:" << endl;
    for (auto failure : failures)
        outputException(failure);
}

// Protected methods.

TextFormatter::TextFormatter(ostream& output) : Formatter(output) {}

// Private methods.

void TextFormatter::outputException(exception_ptr failure) const {
    try {
        rethrow_exception(failure);
    } catch (const exception& e) {
        output_ << e.what() << endl;
    }
}

} // namespace formatters
} // namespace core
} // namespace ccspec

#include <iostream>
#include <ccspec/core/formatters/text_formatter.h>

namespace ccspec {
namespace core {
namespace formatters {

using std::endl;
using std::exception;
using std::exception_ptr;
using std::list;
using std::ostream;
using std::rethrow_exception;

// Public methods.

void TextFormatter::afterEachHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `after(:example)` hook" << endl;
    outputException(failure);
}

void TextFormatter::afterAllHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `after(:context)` hook" << endl;
    outputException(failure);
}

void TextFormatter::aroundHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `around(:example)` hook" << endl;
    outputException(failure);
}

void TextFormatter::dumpFailures(const list<exception_ptr>& failures) const {
    if (failures.empty())
        return;

    output_ << endl << "Failures:" << endl;
    for (auto failure : failures)
        outputException(failure);
}

// Protected methods.

TextFormatter::TextFormatter(ostream& output) : Formatter(output) {}

// Private methods.

void TextFormatter::outputException(exception_ptr failure) const {
    try {
        rethrow_exception(failure);
    } catch (const exception& e) {
        output_ << e.what() << endl;
    }
}

} // namespace formatters
} // namespace core
} // namespace ccspec

Add line break before "Failures:"


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

#include "chrome/browser/extensions/extension_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, SessionRestoreApis) {
  ASSERT_TRUE(RunExtensionSubtest("session_restore",
                                  "session_restore.html")) << message_;
}

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

#include "chrome/browser/extensions/extension_apitest.h"

// Flaky on ChromeOS http://crbug.com/251199
#if defined(OS_CHROMEOS)
#define MAYBE_SessionRestoreApis DISABLED_SessionRestoreApis
#else
#define MAYBE_SessionRestoreApis SessionRestoreApis
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_SessionRestoreApis) {
  ASSERT_TRUE(RunExtensionSubtest("session_restore",
                                  "session_restore.html")) << message_;
}

Mark SessionRestoureApis as flaky on chromium os


// Copyright 2004-present Facebook. All Rights Reserved.

#include "ApkManager.h"

#include <boost/filesystem.hpp>
#include <iostream>
#include <sstream>

namespace {

bool check_directory(std::string& apkdir) {
  if (!boost::filesystem::is_directory(apkdir.c_str())) {
    std::cerr << "error: apkdir is not a writable directory: " << apkdir
              << std::endl;
    exit(EXIT_FAILURE);
  }
}

}

FILE* ApkManager::new_asset_file(const char* filename) {
  check_directory(m_apk_dir);
  std::ostringstream path;
  path << m_apk_dir << "/assets/";
  if (!boost::filesystem::is_directory(path.str().c_str())) {
    std::cerr << "error: assets dir is not a writable directory: " << path.str()
              << std::endl;
    exit(EXIT_FAILURE);
  }
  path << filename;

  FILE* fd = fopen(path.str().c_str(), "w");
  if (fd != nullptr) {
    m_files.emplace_back(fd);
  } else {
    perror("Error creating new asset file");
  }
  return fd;
}

// Copyright 2004-present Facebook. All Rights Reserved.

#include "ApkManager.h"

#include <boost/filesystem.hpp>
#include <iostream>
#include <sstream>

namespace {

void check_directory(std::string& dir) {
  if (!boost::filesystem::is_directory(dir.c_str())) {
    std::cerr << "error: not a writable directory: " << dir
              << std::endl;
    exit(EXIT_FAILURE);
  }
}

}

FILE* ApkManager::new_asset_file(const char* filename) {
  check_directory(m_apk_dir);
  std::ostringstream path;
  path << m_apk_dir << "/assets/";
  std::string assets_dir = path.str();
  check_directory(assets_dir);
  path << filename;

  FILE* fd = fopen(path.str().c_str(), "w");
  if (fd != nullptr) {
    m_files.emplace_back(fd);
  } else {
    perror("Error creating new asset file");
  }
  return fd;
}

Fix compilation warning when checking for writable directory


#include <iostream>
#include <string>

std::string parse_command(const std::string& input) {
  return input.substr(0, input.find(' '));
}

int main() {
  std::cout << "PUCRS FAT16 SHELL\n";
  std::cout << "$ ";

  std::string cmd;
  getline (std::cin, cmd);
  std::cout << "-> Will execute: " << parse_command(cmd) << "\n";
}

#include <iostream>
#include <string>

std::string parse_command(const std::string& input) {
  return input.substr(0, input.find(' '));
}

int main() {
  std::cout << "PUCRS FAT16 SHELL\n";
  while (true) {
    std::cout << "$ ";
    std::string cmd;
    getline (std::cin, cmd);
    std::cout << "-> Will execute: " << parse_command(cmd) << "\n";
  }
}

Read commands from stdin "forever"


#include <dns_sd.h>
#include <ev++.h>

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

#include <iostream>
#include <dns_sd.h>
#include <ev++.h>

#include "build_version.h"

int main(int argc, char *argv[]) {
    if (2 != argc) {
        std::cerr << argv[0] << " <announce file>" << std::endl;
        std::cerr << "Version: " << VERSION << std::endl;
        return -1;
    }
    return 0;
}

Check if we have enough arguments


// Copyright 2017, Dawid Kurek, <dawikur@gmail.com>

#include "lel/operation/increment_decrement.hpp"

#include "gtest/gtest.h"

TEST(increment_decrement_test, TODO) {}

// Copyright 2017, Dawid Kurek, <dawikur@gmail.com>

#include "lel/operation/increment_decrement.hpp"

#include "gtest/gtest.h"

TEST(increment_decrement_test, preincrement) {
  LeL::Operation::__PreIncrement pre_increment;

  int i = 5;

  ASSERT_EQ(6, pre_increment(i));
}

TEST(increment_decrement_test, postincrement) {
  LeL::Operation::__PostIncrement post_increment;

  int i = 5;

  ASSERT_EQ(5, post_increment(i));
}

TEST(increment_decrement_test, predecrement) {
  LeL::Operation::__PreDecrement pre_decrement;

  int i = 5;

  ASSERT_EQ(4, pre_decrement(i));
}

TEST(increment_decrement_test, postdecrement) {
  LeL::Operation::__PostDecrement post_decrement;

  int i = 5;

  ASSERT_EQ(5, post_decrement(i));
}

Add tests for pre/post inc/decrement


#include "Assignment.h"
#include "Course.h"

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
  if (remove("test-0.sqlite") != 0) {
    cout << "Error with deletion of database file\n";
  } else {
    cout << "Database file successfully deleted\n";
  }

  // test instantiation of a Course object.
  cout << "Testing instantiation of a Course object:" << endl;
  Course course("test-0");
  cout << "Created " << course.getName() << endl;

  cout << "All Assignments: " << course.assignments.size() << endl;
  cout << "All Categories: " << course.categories.size() << endl;
  cout << "All Students: " << course.students.size() << endl;
  cout << "All Submitted: " << course.submitted.size() << endl;

  // Test adding items to the db
  Category c1(0, "Homework", 20, course.getDb());
  Category c2(0, "Labs", 30, course.getDb());
  Category c3(0, "Exams", 50, course.getDb());
  c1.insert();
  c2.insert();
  c3.insert();

  course.categories[c1.getId()] = &c1;
  course.categories[c2.getId()] = &c2;
  course.categories[c3.getId()] = &c3;

  for (auto it : course.categories) {
    cout << it.first << " " << it.second->getName() << endl;
  }
}

#include "Assignment.h"
#include "Course.h"

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
  if (remove("test-0.sqlite") != 0) {
    cout << "Error with deletion of database file\n";
  } else {
    cout << "Database file successfully deleted\n";
  }

  // test instantiation of a Course object.
  cout << "Testing instantiation of a Course object:" << endl;
  Course course("test-0");
  cout << "Created " << course.getName() << endl;

  // cout << "All Assignments: " << course.assignments.size() << endl;
  // cout << "All Categories: " << course.categories.size() << endl;
  // cout << "All Students: " << course.students.size() << endl;
  // cout << "All Submitted: " << course.submitted.size() << endl;

  // // Test adding items to the db
  // Category c1(0, "Homework", 20, course.getDb());
  // Category c2(0, "Labs", 30, course.getDb());
  // Category c3(0, "Exams", 50, course.getDb());
  // c1.insert();
  // c2.insert();
  // c3.insert();

  // course.categories[c1.getId()] = &c1;
  // course.categories[c2.getId()] = &c2;
  // course.categories[c3.getId()] = &c3;

  // for (auto it : course.categories) {
  //   cout << it.first << " " << it.second->getName() << endl;
  // }
}

Comment out test, need to refactor


/* ***** BEGIN LICENSE BLOCK *****
 * Sconspiracy - Copyright (C) IRCAD, 2004-2010.
 * Distributed under the terms of the BSD Licence as
 * published by the Open Source Initiative.
 * ****** END LICENSE BLOCK ****** */

MiniLauncher::MiniLauncher( ::boost::filesystem::path profilePath )
{
    ::boost::filesystem::path cwd = ::boost::filesystem::current_path();
    ::boost::filesystem::path bundlePath = cwd / "Bundles";

    ::fwRuntime::addBundles(bundlePath);

    if (!::boost::filesystem::exists( profilePath ))
    {
        profilePath = cwd / profilePath;
    }

    if (!::boost::filesystem::exists( profilePath ))
    {
        throw (std::invalid_argument("<" + profilePath.string() + "> not found." ));
    }

    m_profile = ::fwRuntime::io::ProfileReader::createProfile(profilePath);
    ::fwRuntime::profile::setCurrentProfile(m_profile);

    m_profile->setParams(0, NULL);
    m_profile->start();
    // m_profile->run();

}

MiniLauncher::~MiniLauncher()
{
    m_profile->stop();
    m_profile.reset();
    ::fwRuntime::profile::setCurrentProfile(m_profile);
}

/* ***** BEGIN LICENSE BLOCK *****
 * Sconspiracy - Copyright (C) IRCAD, 2004-2010.
 * Distributed under the terms of the BSD Licence as
 * published by the Open Source Initiative.
 * ****** END LICENSE BLOCK ****** */

MiniLauncher::MiniLauncher( ::boost::filesystem::path profilePath )
{
    ::boost::filesystem::path cwd = ::boost::filesystem::current_path();
    ::boost::filesystem::path bundlePath = cwd / "Bundles";

    ::fwRuntime::addBundles(bundlePath);

    if (!::boost::filesystem::exists( profilePath ))
    {
        profilePath = cwd / profilePath;
    }

    if (!::boost::filesystem::exists( profilePath ))
    {
        throw (std::invalid_argument("<" + profilePath.string() + "> not found." ));
    }

    m_profile = ::fwRuntime::io::ProfileReader::createProfile(profilePath);
    ::fwRuntime::profile::setCurrentProfile(m_profile);

    m_profile->setParams(0, NULL);
    m_profile->start();
    ::fwRuntime::profile::getCurrentProfile()->setup();
    // m_profile->run();
}

MiniLauncher::~MiniLauncher()
{
    ::fwRuntime::profile::getCurrentProfile()->cleanup();
    m_profile->stop();
    m_profile.reset();
    ::fwRuntime::profile::setCurrentProfile(m_profile);
}

Add setup/cleanup for bundle test unit


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "System/management.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    // Create management object and register it as context property
    Management *man = new Management();
    engine.rootContext()->setContextProperty("management", man);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QObject *canvas = engine.rootObjects().first()->findChild<QObject*>("canvas");
    man->initialize(&engine, canvas);

    return app.exec();
}

#include <ctime>

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "System/management.h"

int main(int argc, char *argv[]) {
    srand((unsigned)time(NULL));

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    // Create management object and register it as context property
    Management *man = new Management();
    engine.rootContext()->setContextProperty("management", man);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QObject *canvas = engine.rootObjects().first()->findChild<QObject*>("canvas");
    man->initialize(&engine, canvas);

    return app.exec();
}

Initialize seed for better random numbers.


#include <iomanip>
#include <iostream>

#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/console.hpp>

static void color_fmt(boost::log::record_view const& rec, boost::log::formatting_ostream& strm) {
  auto severity = rec[boost::log::trivial::severity];
  bool color = false;
  if (severity) {
    switch (severity.get()) {
      case boost::log::trivial::warning:
        strm << "\033[33m";
        color = true;
        break;
      case boost::log::trivial::error:
      case boost::log::trivial::fatal:
        strm << "\033[31m";
        color = true;
        break;
      default:
        break;
    }
  }
  // setw(7) = the longest log level. eg "warning"
  strm << std::setw(7) << std::setfill(' ') << severity << ": " << rec[boost::log::expressions::smessage];
  if (color) {
    strm << "\033[0m";
  }
}

void logger_init_sink(bool use_colors = false) {
  auto sink = boost::log::add_console_log(std::cout, boost::log::keywords::format = "%Message%",
                                          boost::log::keywords::auto_flush = true);
  if (use_colors) {
    sink->set_formatter(&color_fmt);
  }
}

#include <iomanip>
#include <iostream>

#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/console.hpp>

static void color_fmt(boost::log::record_view const& rec, boost::log::formatting_ostream& strm) {
  auto severity = rec[boost::log::trivial::severity];
  bool color = false;
  if (severity) {
    switch (severity.get()) {
      case boost::log::trivial::warning:
        strm << "\033[33m";
        color = true;
        break;
      case boost::log::trivial::error:
      case boost::log::trivial::fatal:
        strm << "\033[31m";
        color = true;
        break;
      default:
        break;
    }
  }
  // setw(7) = the longest log level. eg "warning"
  strm << std::setw(7) << std::setfill(' ') << severity << ": " << rec[boost::log::expressions::smessage];
  if (color) {
    strm << "\033[0m";
  }
}

void logger_init_sink(bool use_colors = false) {
  auto stream = &std::cerr;
  if (getenv("LOG_STDERR") == nullptr) {
    stream = &std::cout;
  }
  auto sink = boost::log::add_console_log(*stream, boost::log::keywords::format = "%Message%",
                                          boost::log::keywords::auto_flush = true);
  if (use_colors) {
    sink->set_formatter(&color_fmt);
  }
}

Allow logger to use STDERR


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

#include <realm.hpp>
#include "error_handling.hpp"
#include "marshalling.hpp"
#include "realm_export_decls.hpp"

using namespace realm;
using namespace realm::binding;

extern "C" {

REALM_EXPORT void row_destroy(Row* row_ptr)
{
    handle_errors([&]() {
        delete row_ptr;
    });
}

REALM_EXPORT size_t row_get_row_index(const Row* row_ptr)
{
    return handle_errors([&]() {
        return row_ptr->get_index();
    });
}

REALM_EXPORT size_t row_get_is_attached(const Row* row_ptr)
{
    return handle_errors([&]() {
        return bool_to_size_t(row_ptr->is_attached());
    });
}

}   // extern "C"

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

#include <realm.hpp>
#include "error_handling.hpp"
#include "marshalling.hpp"
#include "realm_export_decls.hpp"

using namespace realm;
using namespace realm::binding;

extern "C" {

REALM_EXPORT void row_destroy(Row* row_ptr)
{
    handle_errors([&]() {
        delete row_ptr;
    });
}

REALM_EXPORT size_t row_get_row_index(const Row* row_ptr)
{
    return handle_errors([&]() {
        if (!row_ptr->is_attached())
            throw std::exception();
        return row_ptr->get_index();
    });
}

REALM_EXPORT size_t row_get_is_attached(const Row* row_ptr)
{
    return handle_errors([&]() {
        return bool_to_size_t(row_ptr->is_attached());
    });
}

}   // extern "C"

Throw standard exception on illegal row access


#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main() {
  VideoCapture cap(0);
  if (!cap.isOpened()) {
    cout << "Error opening webcam" << endl;
    return -1;
  }

  int frame_width  = cap.get(CV_CAP_PROP_FRAME_WIDTH);
  int frame_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
  VideoWriter video("out.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, Size(frame_width, frame_height), true);

  for (;;) {
    Mat frame;
    cap >> frame;
    video.write(frame);
    // imshow("Frame", frame);
    if (waitKey(1) == 27) {
      break;
    }
  }
  return 0;
}

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main() {
  VideoCapture cap(0);
  if (!cap.isOpened()) {
    cout << "Error opening webcam" << endl;
    return -1;
  }

  int frame_width  = cap.get(CV_CAP_PROP_FRAME_WIDTH);
  int frame_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
  int four_cc = CV_FOURCC('F', 'M', 'P', '4');
  VideoWriter video("out.avi", four_cc, 10, Size(frame_width, frame_height), true);

  for (;;) {
    Mat frame;
    cap >> frame;
    video.write(frame);
    // imshow("Frame", frame);
    if (waitKey(1) == 27) {
      break;
    }
  }
  return 0;
}

Use FFmpeg mp4 codec for output


#include "gtest/gtest.h"
#include "motor_shield.h"

MotorShield mshield(1, 3, 4, 5);

TEST(MotorShield, Initialization) {
  ASSERT_TRUE(1 == 1);
}

#include "gtest/gtest.h"
#include "motor_shield.h"

#define SPEED_L 1
#define DIR_L 2

#define SPEED_R 3
#define DIR_R 4

MotorShield mshield(SPEED_L, DIR_L, SPEED_R, DIR_R);

TEST(MotorShield, Initialization) {
  ASSERT_EQ(0, mshield.getMinSpeed());
  ASSERT_EQ(255, mshield.getMaxSpeed());

  ASSERT_EQ(SPEED_L, mshield.getLeftSpeedPin());
  ASSERT_EQ(SPEED_R, mshield.getRightSpeedPin());

  ASSERT_EQ(DIR_L, mshield.getLeftDirPin());
  ASSERT_EQ(DIR_R, mshield.getRightDirPin());
}

Add a test for MotorShield constructor


/*
 * msg - user messages - implementation
 * Copyright(c) 2004 of wave++ (Yuri D'Elia) <wavexx@users.sf.net>
 * Distributed under GNU LGPL without ANY warranty.
 */

// c system headers
#include <stdarg.h>
#include <cstdio>
using std::vfprintf;
using std::fprintf;

// data
const char* prg;
bool verbose = false;

// implementation
void
err(const char* fmt, ...)
{
  va_list params;

  fprintf(stderr, "%s: ", prg);

  va_start(params, fmt);
  vfprintf(stderr, fmt, params);
  va_end(params);

  fprintf(stderr, "\n");
}

void
msg(const char* fmt, ...)
{
  if(!verbose)
    return;

  va_list params;

  fprintf(stderr, "%s: ", prg);

  va_start(params, fmt);
  vfprintf(stderr, fmt, params);
  va_end(params);

  fprintf(stderr, "\n");
}

/*
 * msg - user messages - implementation
 * Copyright(c) 2004 of wave++ (Yuri D'Elia) <wavexx@users.sf.net>
 * Distributed under GNU LGPL without ANY warranty.
 */

// local headers
#include "msg.hh"

// c system headers
#include <stdarg.h>
#include <cstdio>
using std::vfprintf;
using std::fprintf;

// data
const char* prg;
bool verbose = false;

// implementation
void
err(const char* fmt, ...)
{
  va_list params;

  fprintf(stderr, "%s: ", prg);

  va_start(params, fmt);
  vfprintf(stderr, fmt, params);
  va_end(params);

  fprintf(stderr, "\n");
}

void
msg(const char* fmt, ...)
{
  if(!verbose)
    return;

  va_list params;

  fprintf(stderr, "%s: ", prg);

  va_start(params, fmt);
  vfprintf(stderr, fmt, params);
  va_end(params);

  fprintf(stderr, "\n");
}

Include the header for safety.


#include "Graph.h"
#include <fstream>

using namespace std;

void main()
{
	setlocale(LC_ALL, "Russian");
	ifstream inputFile("inputfile.txt");
	int numberOfCountries = 0;
	List **mapOfWorld = creatingCoutries(inputFile);
	printMap(mapOfWorld);
	deleteMap(mapOfWorld);
	system("pause");
}

Add new functions and finished module Graph.h


//
// Created by Konstantin Gredeskoul on 1/23/16.
//

#include "gtest/gtest.h"
#include "macros_color_test.h"

TEST(rgb_pixel, set_color) {
    pixel.setColor(purple);

    EXPECT_EQ_COLORS(pixel.getColor(), purple);
    wait_for(10);
    EXPECT_EQ_COLORS(pixel.getColor(), purple);
}

TEST(rgb_pixel, fade_same_colors) {
    pixel.fade(purple, purple, 100);
    EXPECT_EQ_COLORS(pixel.getColor(), purple);
    wait_for(90);
    EXPECT_EQ_COLORS(pixel.getColor(), purple);
}

TEST(rgb_pixel, tick_100ms) {
    pixel.fade(purple, orange, 200);
    wait_for(100);
    RGBColor dark_grey = (orange - purple) / 2;
    EXPECT_EQ_COLORS(dark_grey, pixel.getColor());
}

//
// Created by Konstantin Gredeskoul on 1/23/16.
//

#include "gtest/gtest.h"
#include "macros_color_test.h"

TEST(rgb_pixel, set_color) {
    pixel.setColor(purple);

    EXPECT_EQ_COLORS(pixel.getColor(), purple);
    wait_for(10);
    EXPECT_EQ_COLORS(pixel.getColor(), purple);
}

//TEST(rgb_pixel, fade_same_colors) {
//    pixel.fade(purple, purple, 100);
//    EXPECT_EQ_COLORS(pixel.getColor(), purple);
//    wait_for(90);
//    EXPECT_EQ_COLORS(pixel.getColor(), purple);
//}
//
//TEST(rgb_pixel, tick_100ms) {
//    pixel.fade(purple, orange, 200);
//    wait_for(100);
//    RGBColor dark_grey = (orange - purple) / 2;
//    EXPECT_EQ_COLORS(dark_grey, pixel.getColor());
//}

Comment out broken tests for now


/*
    googletalkcalldialog.cpp - Google Talk and Google libjingle support

    Copyright (c) 2009 by Pali Rohár <pali.rohar@gmail.com>

    *************************************************************************
    *                                                                       *
    * This library 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 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include <QCloseEvent>

#include "googletalkcalldialog.h"

GoogleTalkCallDialog::GoogleTalkCallDialog(QWidget *parent): QDialog(parent) {
	setupUi(this);
}

void GoogleTalkCallDialog::closeEvent(QCloseEvent * e) {
	e->ignore();
	emit(closed());
}

#include "googletalkcalldialog.moc"

/*
    googletalkcalldialog.cpp - Google Talk and Google libjingle support

    Copyright (c) 2009 by Pali Rohár <pali.rohar@gmail.com>

    *************************************************************************
    *                                                                       *
    * This library 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 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include "googletalkcalldialog.h"

#include <QCloseEvent>

GoogleTalkCallDialog::GoogleTalkCallDialog(QWidget *parent): QDialog(parent) {
	setupUi(this);
}

void GoogleTalkCallDialog::closeEvent(QCloseEvent * e) {
	e->ignore();
	emit(closed());
}

#include "googletalkcalldialog.moc"

Include missing headers & own header as first


// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: not cpp11-migrate -format-style=non_existent_file.yaml -use-auto %t.cpp -- -std=c++11
// RUN: touch %T/non_format_config.yaml
// RUN: not cpp11-migrate -format-style=%T/non_format_config.yaml -use-auto %t.cpp -- -std=c++11
// RUN: cpp11-migrate -format-style=LLVM -use-auto %t.cpp -- -std=c++11
// RUN: FileCheck --strict-whitespace -input-file=%t.cpp %s

class MyType012345678901234567890123456789 {};

int f() {
  MyType012345678901234567890123456789 *a =
      new MyType012345678901234567890123456789();
  // CHECK: {{^\ \ auto\ a\ \=\ new\ MyType012345678901234567890123456789\(\);}}

  delete a;
}

Tweak lit tests to avoid false negatives


#include "cvd/colourspace.h"

namespace CVD {
	namespace ColourSpace {

		inline void yuv420p_to_rgb_c(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height);

		extern "C"{
			void cvd_asm_yuv420p_to_rgb(const unsigned char*, unsigned char*, int);
		}

		void yuv420p_to_rgb(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height) {
			if (is_aligned<8>(y) && (u == y + width*height) && is_aligned<8>(u) && (v == u + width*height/4) && is_aligned<8>(v) &&
			                                                             is_aligned<8>(rgb) && ((width&4) == 0) && ((height&1)==0))
				cvd_asm_yuv420p_to_rgb(y,rgb,width,height);
			else
				yuv420p_to_rgb_c(y, u, v, rgb, width, height);
		}
	}
}

#include "cvd/colourspace.h"
#include "cvd/utility.h"

namespace CVD {
	namespace ColourSpace {

		inline void yuv420p_to_rgb_c(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height);

		extern "C"{
			void cvd_asm_yuv420p_to_rgb(const unsigned char*, unsigned char*, int, int);
		}

		void yuv420p_to_rgb(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height) {
			if (is_aligned<8>(y) && (u == y + width*height) && is_aligned<8>(u) && (v == u + width*height/4) && is_aligned<8>(v) &&
			                                                             is_aligned<8>(rgb) && ((width&4) == 0) && ((height&1)==0))
				cvd_asm_yuv420p_to_rgb(y,rgb,width,height);
			else
				yuv420p_to_rgb_c(y, u, v, rgb, width, height);
		}
	}
}

Patch from Achtelik Markus to fix compile error on 32bit builds.


//
//  MathsUtilities.cpp
//  TimGameLib
//
//  Created by Tim Brier on 10/04/2015.
//  Copyright (c) 2015 tbrier. All rights reserved.
//

#include "MathsUtilities.hpp"
#include <random>
#include <functional>

namespace MathsUtilities
{

std::function<int()> GetRandomGeneratorFunctionForRange(int min, int max)
{
    std::random_device device;
    std::default_random_engine generator(device());
    std::uniform_int_distribution<int> distribution(min, max);
    auto result = std::bind(distribution, generator);
    return result;
}

std::function<float()> GetRandomGeneratorFunctionForRange(float min, float max)
{
    std::random_device device;
    std::default_random_engine generator(device());
    std::uniform_int_distribution<float> distribution(min, max);
    auto result = std::bind(distribution, generator);
    return result;
}

} // namespace MathsUtilities

//
//  MathsUtilities.cpp
//  TimGameLib
//
//  Created by Tim Brier on 10/04/2015.
//  Copyright (c) 2015 tbrier. All rights reserved.
//

#include "MathsUtilities.hpp"
#include <random>
#include <functional>

namespace MathsUtilities
{

std::function<int()> GetRandomGeneratorFunctionForRange(int min, int max)
{
    std::random_device device;
    std::default_random_engine generator(device());
    std::uniform_int_distribution<int> distribution(min, max);
    auto result = std::bind(distribution, generator);
    return result;
}

std::function<float()> GetRandomGeneratorFunctionForRange(float min, float max)
{
    std::random_device device;
    std::default_random_engine generator(device());
    std::uniform_real_distribution<float> distribution(min, max);
    auto result = std::bind(distribution, generator);
    return result;
}

} // namespace MathsUtilities

Use real distribution for random float generator


#include "Control.h"

#include <sstream>

Control::Control() {

}

Control::Control(int id, HWND parent) :
_id(id),
_parent(parent) {
    _hWnd = GetDlgItem(parent, id);
}

Control::~Control() {

}

bool Control::Text(std::wstring text) {
    return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;
}

bool Control::Text(int value) {
    return Text(std::to_wstring(value));
}

std::wstring Control::Text() {
    wchar_t text[MAX_EDITSTR];
    GetDlgItemText(_parent, _id, text, MAX_EDITSTR);
    return std::wstring(text);
}

int Control::TextAsInt() {
    std::wstring str = Text();
    int num;
    std::wistringstream wistr(str);
    wistr >> num;
    return num;
}

void Control::AddWindowExStyle(long exStyle) {
    long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
    exs |= exStyle;
    SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}

RECT Control::Dimensions() {
    RECT r;
    GetWindowRect(_hWnd, &r);
    return r;
}

#include "Control.h"

#include <sstream>

Control::Control() {

}

Control::Control(int id, HWND parent) :
_id(id),
_parent(parent) {
    _hWnd = GetDlgItem(parent, id);
}

Control::~Control() {

}

bool Control::Text(std::wstring text) {
    return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;
}

bool Control::Text(int value) {
    return SetDlgItemInt(_parent, _id, value, TRUE) == TRUE;
}

std::wstring Control::Text() {
    wchar_t text[MAX_EDITSTR];
    GetDlgItemText(_parent, _id, text, MAX_EDITSTR);
    return std::wstring(text);
}

int Control::TextAsInt() {
    std::wstring str = Text();
    int num;
    std::wistringstream wistr(str);
    wistr >> num;
    return num;
}

void Control::AddWindowExStyle(long exStyle) {
    long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
    exs |= exStyle;
    SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}

RECT Control::Dimensions() {
    RECT r;
    GetWindowRect(_hWnd, &r);
    return r;
}

Use Win32 function instead of rolling our own


//===--- DriverOptions.cpp - Driver Options Table -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Options.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"

using namespace clang::driver;
using namespace clang::driver::options;
using namespace llvm::opt;

#define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
#include "clang/Driver/Options.inc"
#undef PREFIX

static const OptTable::Info InfoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)   \
  { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
    FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "clang/Driver/Options.inc"
#undef OPTION
};

namespace {

class DriverOptTable : public OptTable {
public:
  DriverOptTable()
    : OptTable(InfoTable, llvm::array_lengthof(InfoTable)) {}
};

}

OptTable *clang::driver::createDriverOptTable() {
  return new DriverOptTable();
}

//===--- DriverOptions.cpp - Driver Options Table -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Options.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"

using namespace clang::driver;
using namespace clang::driver::options;
using namespace llvm::opt;

#define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
#include "clang/Driver/Options.inc"
#undef PREFIX

static const OptTable::Info InfoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)   \
  { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
    FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "clang/Driver/Options.inc"
#undef OPTION
};

namespace {

class DriverOptTable : public OptTable {
public:
  DriverOptTable()
    : OptTable(InfoTable) {}
};

}

OptTable *clang::driver::createDriverOptTable() {
  return new DriverOptTable();
}

Update clang to match llvm r250901. OptTable constructor now takes an ArrayRef. NFC


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

#include "chrome/browser/chromeos/login/textfield_with_margin.h"

#include "chrome/browser/chromeos/login/helper.h"
#include "ui/base/keycodes/keyboard_codes.h"

namespace {

// Holds ratio of the margin to the preferred text height.
const double kTextMarginRate = 0.33;

// Size of each vertical margin (top, bottom).
const int kVerticalMargin = 3;

}  // namespace

namespace chromeos {

TextfieldWithMargin::TextfieldWithMargin() {
  CorrectTextfieldFontSize(this);
}

TextfieldWithMargin::TextfieldWithMargin(views::Textfield::StyleFlags style)
    : Textfield(style) {
  CorrectTextfieldFontSize(this);
}

void TextfieldWithMargin::Layout() {
  int margin = GetPreferredSize().height() * kTextMarginRate;
  SetHorizontalMargins(margin, margin);
  SetVerticalMargins(kVerticalMargin, kVerticalMargin);
  views::Textfield::Layout();
}

bool TextfieldWithMargin::OnKeyPressed(const views::KeyEvent& e) {
  if (e.key_code() == ui::VKEY_ESCAPE && !text().empty()) {
    SetText(string16());
    return true;
  }
  return false;
}

}  // namespace chromeos

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

#include "chrome/browser/chromeos/login/textfield_with_margin.h"

#include "chrome/browser/chromeos/login/helper.h"
#include "ui/base/keycodes/keyboard_codes.h"

namespace {

// Holds ratio of the margin to the preferred text height.
const double kTextMarginRate = 0.33;

// Size of each vertical margin (top, bottom).
const int kVerticalMargin = 3;

}  // namespace

namespace chromeos {

TextfieldWithMargin::TextfieldWithMargin() {
  CorrectTextfieldFontSize(this);
}

TextfieldWithMargin::TextfieldWithMargin(views::Textfield::StyleFlags style)
    : Textfield(style) {
  CorrectTextfieldFontSize(this);
}

void TextfieldWithMargin::Layout() {
  int margin = GetPreferredSize().height() * kTextMarginRate;
  SetHorizontalMargins(margin, margin);
  SetVerticalMargins(kVerticalMargin, kVerticalMargin);
  views::Textfield::Layout();
}

bool TextfieldWithMargin::OnKeyPressed(const views::KeyEvent& e) {
  if (e.key_code() == ui::VKEY_ESCAPE && !text().empty()) {
    SetText(string16());
    return true;
  }
  return views::Textfield::OnKeyPressed(e);
}

}  // namespace chromeos

Fix to make the behavior of TextfieldWithMargin consistent with Textfield


VectorXf v;
v.setLinSpaced(5,0.5f,1.5f).transpose();
cout << v << endl;

VectorXf v;
v.setLinSpaced(5,0.5f,1.5f);
cout << v << endl;

Remove confusing transpose() in setLinSpaced() docs.


// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/event_emitter_caller.h"

#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
                                        v8::Local<v8::Object> obj,
                                        const char* method,
                                        ValueVector* args) {
  // Perform microtask checkpoint after running JavaScript.
  v8::MicrotasksScope script_scope(isolate,
                                   v8::MicrotasksScope::kRunMicrotasks);
  // Use node::MakeCallback to call the callback, and it will also run pending
  // tasks in Node.js.
  v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method, args->size(), &args->front(),
                            {0, 0});
  if (ret.IsEmpty()) {
    return v8::Boolean::New(isolate, false);
  }
  return ret.ToLocalChecked();
}

}  // namespace internal

}  // namespace mate

Fix line length in caller.cc


// RUN: %clang_cc1 -verify %s
// REQUIRES: thread_support

// expected-warning@* 0-1{{stack nearly exhausted}}
// expected-note@* 0+{{}}

template<int N> struct X : X<N-1> {};
template<> struct X<0> {};
X<1000> x;

template<typename ...T> struct tuple {};
template<typename ...T> auto f(tuple<T...> t) -> decltype(f(tuple<T...>(t))) {} // expected-error {{exceeded maximum depth}}
void g() { f(tuple<int, int>()); }

int f(X<0>);
template<int N> auto f(X<N>) -> f(X<N-1>());

int k = f(X<1000>());

// RUN: %clang_cc1 -verify %s
// REQUIRES: thread_support

// FIXME: Detection of, or recovery from, stack exhaustion does not work on
// NetBSD at the moment. Since this is a best-effort mitigation for exceeding
// implementation limits, just disable the test.
// UNSUPPORTED: system-netbsd

// expected-warning@* 0-1{{stack nearly exhausted}}
// expected-note@* 0+{{}}

template<int N> struct X : X<N-1> {};
template<> struct X<0> {};
X<1000> x;

template<typename ...T> struct tuple {};
template<typename ...T> auto f(tuple<T...> t) -> decltype(f(tuple<T...>(t))) {} // expected-error {{exceeded maximum depth}}
void g() { f(tuple<int, int>()); }

int f(X<0>);
template<int N> auto f(X<N>) -> f(X<N-1>());

int k = f(X<1000>());

Disable stack exhaustion test on NetBSD, where either the detection or recovery mechanism does not appear to work.


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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  dialog->ShowModalDialog();
  active_dialog_ = dialog;
}

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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  // Set active_dialog_ before showing it, because ShowModalDialog can wind up
  // calling ShowNextDialog in some cases, which will change active_dialog_.
  active_dialog_ = dialog;
  dialog->ShowModalDialog();
}

Set active_dialog_ before showing it, since showing a dialog can sometimes actually move to the next one in the queue instead.


#include <immintrin.h>

bool is_sorted_avx512(int32_t* a, size_t n) {

    const __m512i shuffle_pattern = _mm512_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15);

    size_t i = 0;
    while (i < n - 16) {
        const __m512i curr = _mm512_loadu_si512(reinterpret_cast<const __m512i*>(a + i));
        const __m512i next = _mm512_permutexvar_epi32(shuffle_pattern, curr);

        const __mmask16 mask = _mm512_cmpgt_epi32_mask(curr, next);
        if (mask != 0) {
            return false;
        }

        i += 15;
    }

    for (/**/; i + 1 < n; i++) {
        if (a[i] > a[i + 1])
            return false;
    }

    return true;
}

#include <immintrin.h>

bool is_sorted_avx512(int32_t* a, size_t n) {

    static const __m512i shuffle_pattern = _mm512_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15);

    size_t i = 0;
    while (i < n - 16) {
        const __m512i curr = _mm512_loadu_si512(reinterpret_cast<const __m512i*>(a + i));
        const __m512i next = _mm512_permutexvar_epi32(shuffle_pattern, curr);

        const __mmask16 mask = _mm512_cmpgt_epi32_mask(curr, next);
        if (mask != 0) {
            return false;
        }

        i += 15;
    }

    for (/**/; i + 1 < n; i++) {
        if (a[i] > a[i + 1])
            return false;
    }

    return true;
}

Use static array --- const may not be sufficient


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

#include "crypto/ec_signature_creator.h"

#include "base/logging.h"

namespace crypto {

// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
  NOTIMPLEMENTED();
  return NULL;
}

ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key,
                                       HASH_HashType hash_type)
    : key_(key),
      hash_type_(hash_type) {
  NOTIMPLEMENTED();
}

ECSignatureCreator::~ECSignatureCreator() { }

bool ECSignatureCreator::Sign(const uint8* data,
                              int data_len,
                              std::vector<uint8>* signature) {
  NOTIMPLEMENTED();
  return false;
}

}  // namespace crypto

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

#include "crypto/ec_signature_creator.h"

#include "base/logging.h"

namespace crypto {

// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
  NOTIMPLEMENTED();
  return NULL;
}

ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key)
    : key_(key) {
  NOTIMPLEMENTED();
}

ECSignatureCreator::~ECSignatureCreator() { }

bool ECSignatureCreator::Sign(const uint8* data,
                              int data_len,
                              std::vector<uint8>* signature) {
  NOTIMPLEMENTED();
  return false;
}

}  // namespace crypto

Remove wrong parameter from ECSignatureCreator's constructor in openssl implement.


#include "../Coin.h"
#include "../Params.h"
#include "../../../streams.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(sigma_coin_tests)

BOOST_AUTO_TEST_CASE(pubcoin_serialization)
{
    secp_primitives::GroupElement coin;
    coin.randomize();

    sigma::PublicCoinV3 pubcoin(coin, sigma::ZQ_GOLDWASSER);

    CDataStream serialized(SER_NETWORK, PROTOCOL_VERSION);
    serialized << pubcoin;

    sigma::PublicCoinV3 deserialized;
    serialized >> deserialized;

    BOOST_CHECK(pubcoin == deserialized);
}

BOOST_AUTO_TEST_CASE(pubcoin_validate)
{
    auto params = sigma::ParamsV3::get_default();

    sigma::PrivateCoinV3 privcoin(params);
    auto& pubcoin = privcoin.getPublicCoin();

    BOOST_CHECK(pubcoin.validate());
}

BOOST_AUTO_TEST_SUITE_END()

#include "../Coin.h"
#include "../Params.h"
#include "../../../streams.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(sigma_coin_tests)

BOOST_AUTO_TEST_CASE(pubcoin_serialization)
{
    secp_primitives::GroupElement coin;
    coin.randomize();

    sigma::PublicCoinV3 pubcoin(coin, sigma::ZQ_GOLDWASSER);

    CDataStream serialized(SER_NETWORK, PROTOCOL_VERSION);
    serialized << pubcoin;

    sigma::PublicCoinV3 deserialized;
    serialized >> deserialized;

    BOOST_CHECK(pubcoin == deserialized);
}

BOOST_AUTO_TEST_CASE(pubcoin_validate)
{
    auto params = sigma::ParamsV3::get_default();

    sigma::PrivateCoinV3 privcoin(params);
    auto& pubcoin = privcoin.getPublicCoin();

    BOOST_CHECK(pubcoin.validate());
}

BOOST_AUTO_TEST_CASE(getter_setter_priv)
{
    auto params = sigma::ParamsV3::get_default();

    sigma::PrivateCoinV3 privcoin(params);
    sigma::PrivateCoinV3 new_privcoin(params);

    BOOST_CHECK(privcoin.getPublicCoin() != new_privcoin.getPublicCoin());
    BOOST_CHECK(privcoin.getSerialNumber() != new_privcoin.getSerialNumber());
    BOOST_CHECK(privcoin.getRandomness() != new_privcoin.getRandomness());
    BOOST_CHECK(privcoin.getVersion() == new_privcoin.getVersion());

    new_privcoin.setPublicCoin(privcoin.getPublicCoin());
    new_privcoin.setRandomness(privcoin.getRandomness());
    new_privcoin.setSerialNumber(privcoin.getSerialNumber());
    new_privcoin.setVersion(2);

    BOOST_CHECK(privcoin.getPublicCoin() == new_privcoin.getPublicCoin());
    BOOST_CHECK(privcoin.getSerialNumber() == new_privcoin.getSerialNumber());
    BOOST_CHECK(privcoin.getRandomness() == new_privcoin.getRandomness());
    BOOST_CHECK(new_privcoin.getVersion() == 2);
}

BOOST_AUTO_TEST_SUITE_END()

Add coin serialize deserialize priv coin


/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "os/posix/posix_hook.h"

#include <dlfcn.h>

void PosixHookInit()
{
}

bool PosixHookDetect(const char *identifier)
{
  return dlsym(RTLD_DEFAULT, identifier) != NULL;
}

void PosixHookLibrary(const char *name, dlopenCallback cb)
{
}

/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "os/posix/posix_hook.h"

#include <dlfcn.h>
#include <stddef.h>

void PosixHookInit()
{
}

bool PosixHookDetect(const char *identifier)
{
  return dlsym(RTLD_DEFAULT, identifier) != NULL;
}

void PosixHookLibrary(const char *name, dlopenCallback cb)
{
}

Apply same fix to apple


// ep1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <gtest\gtest.h>

int _tmain(int argc, _TCHAR* argv[])
{
	testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}

// ep1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <memory>
#include <gtest\gtest.h>

using namespace std;

struct Foo {
	virtual int Plus(int left, int right)
	{
		return 2;
	}
};

struct Bar : public Foo {
	virtual int Plus(int left, short right)
	{
		return 4;
	}
};

TEST(Episode1, OverrideTest_CallParent)
{
	unique_ptr<Foo> op(new Foo());
	EXPECT_EQ(2, op->Plus(1, 1));
}

TEST(Episode1, OverrideTest_CallDerived)
{
	unique_ptr<Foo> op(new Bar());
	EXPECT_EQ(4, op->Plus(1, 1));
}

int _tmain(int argc, _TCHAR* argv[])
{
	testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}

Add two tests to demo 'override' specifier.


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

#include "compat/sanity.h"
#include "key.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(basic_sanity)
{
  BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test");
  BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test");
  BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test");
}

BOOST_AUTO_TEST_SUITE_END()

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

#include "compat/sanity.h"
#include "key.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(basic_sanity)
{
  BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test");
  BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test");
  BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test");
  BOOST_CHECK_MESSAGE(init_and_check_sodium() == 0, "libsodium sanity test");
}

BOOST_AUTO_TEST_SUITE_END()

Add the sanity test for libsodium.


/*
 * Unit tests for the checkerboard.
 * Author: Dino Wernli
 */

#include <gtest/gtest.h>

#include "scene/texture/checkerboard.h"
#include "test/test_util.h"

namespace {

static IntersectionData DataWithCoords(Scalar ss, Scalar tt) {
  Ray r(Point3(0, 0, 0), Vector3(0, 0, 1));
  IntersectionData data(r);
  data.texture_coordinate.s = ss;
  data.texture_coordinate.t = tt;
  return data;
}

TEST(Checkerboard, IsChanging) {
  Color3 blue(0, 0, 1);
  Color3 red(1, 0, 0);
  Checkerboard cb(blue, red);

  EXPECT_TRUE(TestUtil::ColorsEqual(blue, cb.Evaluate(DataWithCoords(0, 0))));
  EXPECT_TRUE(TestUtil::ColorsEqual(red, cb.Evaluate(DataWithCoords(0, 0.1))));
}

}

/*
 * Unit tests for the checkerboard.
 * Author: Dino Wernli
 */

#include <gtest/gtest.h>

#include "scene/texture/checkerboard.h"
#include "test/test_util.h"

namespace {

static IntersectionData DataWithCoords(Scalar ss, Scalar tt) {
  Ray r(Point3(0, 0, 0), Vector3(0, 0, 1));
  IntersectionData data(r);
  data.texture_coordinate.s = ss;
  data.texture_coordinate.t = tt;
  return data;
}

TEST(Checkerboard, IsChanging) {
  Color3 blue(0, 0, 1);
  Color3 red(1, 0, 0);
  Checkerboard cb(blue, red, 5 /* length */);

  EXPECT_TRUE(TestUtil::ColorsEqual(blue, cb.Evaluate(DataWithCoords(0, 0))));
  EXPECT_TRUE(TestUtil::ColorsEqual(red, cb.Evaluate(DataWithCoords(0, 0.1))));
}

}

Fix failing test due to missing checkerboard constructor param.


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"

using namespace autowiring;

// Index that will be given to the next auto_id instance.  Zero is reserved.
static int s_index = 1;

const auto_id_block auto_id_t<void>::s_block{
  0,
  &typeid(void),
  &typeid(s<void>),
  0,
  0,
  nullptr,
  nullptr
};

int autowiring::CreateIndex(void) {
  return s_index++;
}

std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
  return nullptr;
}

std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
  return nullptr;
}

// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"

using namespace autowiring;

// Index that will be given to the next auto_id instance.  Zero is reserved.
static int s_index = 1;

const auto_id_block auto_id_t<void>::s_block{
  0,
  &typeid(void),
  &typeid(s<void>),
  0,
  0,
  nullptr,
  nullptr
};

const auto_id_t_init<void, true> auto_id_t_init<void, true>::init;
const auto_id_t_init<void, false> auto_id_t_init<void, false>::init;

int autowiring::CreateIndex(void) {
  return s_index++;
}

std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
  return nullptr;
}

std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
  return nullptr;
}

Fix msvc14 64-bit release mode linker error


#include "codearea.h"

#include <algorithm>

namespace openlocationcode {

const double kLatitudeMaxDegrees = 90;
const double kLongitudeMaxDegrees = 180;

CodeArea::CodeArea(double latitude_lo, double longitude_lo, double latitude_hi,
                   double longitude_hi, size_t code_length) {
  latitude_lo_ = latitude_lo;
  longitude_lo_ = longitude_lo;
  latitude_hi_ = latitude_hi;
  longitude_hi_ = longitude_hi;
  code_length_ = code_length;
}

double CodeArea::GetLatitudeLo() const{
  return latitude_lo_;
}

double CodeArea::GetLongitudeLo() const {
  return longitude_lo_;
}

double CodeArea::GetLatitudeHi() const {
  return latitude_hi_;
}

double CodeArea::GetLongitudeHi() const {
  return longitude_hi_;
}

size_t CodeArea::GetCodeLength() const { return code_length_; }

LatLng CodeArea::GetCenter() const {
  double latitude_center = std::min(latitude_lo_ + (latitude_hi_ - latitude_lo_) / 2, kLatitudeMaxDegrees);
  double longitude_center = std::min(longitude_lo_ + (longitude_hi_ - longitude_lo_) / 2, kLongitudeMaxDegrees);
  LatLng center = {latitude: latitude_center, longitude: longitude_center};
  return center;
}

} // namespace openlocationcode

#include "codearea.h"

#include <algorithm>

namespace openlocationcode {

const double kLatitudeMaxDegrees = 90;
const double kLongitudeMaxDegrees = 180;

CodeArea::CodeArea(double latitude_lo, double longitude_lo, double latitude_hi,
                   double longitude_hi, size_t code_length) {
  latitude_lo_ = latitude_lo;
  longitude_lo_ = longitude_lo;
  latitude_hi_ = latitude_hi;
  longitude_hi_ = longitude_hi;
  code_length_ = code_length;
}

double CodeArea::GetLatitudeLo() const{
  return latitude_lo_;
}

double CodeArea::GetLongitudeLo() const {
  return longitude_lo_;
}

double CodeArea::GetLatitudeHi() const {
  return latitude_hi_;
}

double CodeArea::GetLongitudeHi() const {
  return longitude_hi_;
}

size_t CodeArea::GetCodeLength() const { return code_length_; }

LatLng CodeArea::GetCenter() const {
  const double latitude_center = std::min(
      latitude_lo_ + (latitude_hi_ - latitude_lo_) / 2, kLatitudeMaxDegrees);
  const double longitude_center =
      std::min(longitude_lo_ + (longitude_hi_ - longitude_lo_) / 2,
               kLongitudeMaxDegrees);
  const LatLng center = {latitude_center, longitude_center};
  return center;
}

} // namespace openlocationcode

Fix obsolete structure init in CodeArea::GetCenter()


// Copyright 2013 The Flutter 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 "impeller/archivist/archivist_fixture.h"

#include "flutter/fml/paths.h"

namespace impeller {
namespace testing {

ArchivistFixture::ArchivistFixture() {
  std::stringstream stream;
  stream << flutter::testing::GetCurrentTestName() << ".db";
  archive_file_name_ = fml::paths::JoinPaths(
      {flutter::testing::GetFixturesPath(), stream.str()});
}

ArchivistFixture::~ArchivistFixture() = default;

const std::string ArchivistFixture::GetArchiveFileName() const {
  return archive_file_name_;
}

void ArchivistFixture::SetUp() {
  DeleteArchiveFile();
}

void ArchivistFixture::TearDown() {
  // TODO: Tear this down. For now, I am inspecting the files for readability of
  // schema.
  // DeleteArchiveFile();
}

void ArchivistFixture::DeleteArchiveFile() const {
  fml::UnlinkFile(archive_file_name_.c_str());
}

}  // namespace testing
}  // namespace impeller

// Copyright 2013 The Flutter 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 "impeller/archivist/archivist_fixture.h"

#include "flutter/fml/paths.h"

namespace impeller {
namespace testing {

ArchivistFixture::ArchivistFixture() {
  std::stringstream stream;
  stream << "Test" << flutter::testing::GetCurrentTestName() << ".db";
  archive_file_name_ = stream.str();
}

ArchivistFixture::~ArchivistFixture() = default;

const std::string ArchivistFixture::GetArchiveFileName() const {
  return fml::paths::JoinPaths(
      {flutter::testing::GetFixturesPath(), archive_file_name_});
}

void ArchivistFixture::SetUp() {
  DeleteArchiveFile();
}

void ArchivistFixture::TearDown() {
  DeleteArchiveFile();
}

void ArchivistFixture::DeleteArchiveFile() const {
  auto fixtures = flutter::testing::OpenFixturesDirectory();
  if (fml::FileExists(fixtures, archive_file_name_.c_str())) {
    fml::UnlinkFile(fixtures, archive_file_name_.c_str());
  }
}

}  // namespace testing
}  // namespace impeller

Fix temporary database file deletion.


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

#include "chrome/browser/extensions/api/system_info_cpu/cpu_info_provider.h"

namespace extensions {

bool CpuInfoProvider::QueryCpuTimePerProcessor(std::vector<CpuTime>* times) {
  // TODO(hongbo): Query the cpu time.
  return false;
}

}  // namespace extensions

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

#include "chrome/browser/extensions/api/system_info_cpu/cpu_info_provider.h"

#include <mach/mach_host.h>

#include "base/mac/scoped_mach_port.h"

namespace extensions {

bool CpuInfoProvider::QueryCpuTimePerProcessor(std::vector<CpuTime>* times) {
  natural_t num_of_processors;
  base::mac::ScopedMachPort host(mach_host_self());
  mach_msg_type_number_t type;
  processor_cpu_load_info_data_t* cpu_infos;

  if (host_processor_info(host.get(),
                          PROCESSOR_CPU_LOAD_INFO,
                          &num_of_processors,
                          reinterpret_cast<processor_info_array_t*>(&cpu_infos),
                          &type) == KERN_SUCCESS) {
    std::vector<CpuTime> results;
    int64 user = 0, nice = 0, sys = 0, idle = 0;

    for (natural_t i = 0; i < num_of_processors; ++i) {
      CpuTime time;

      user = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_USER]);
      sys  = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_SYSTEM]);
      nice = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_NICE]);
      idle = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_IDLE]);

      time.kernel = sys;
      time.user = user + nice;
      time.idle = idle;
      results.push_back(time);
    }

    vm_deallocate(mach_task_self(),
                  reinterpret_cast<vm_address_t>(cpu_infos),
                  num_of_processors * sizeof(processor_cpu_load_info));

    times->swap(results);
    return true;
  }

  return false;
}

}  // namespace extensions

Add code to implement querying CPU time for each processor on Mac for systemInfo.cpu API.


// Copyright 2015 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 "skia/ext/opacity_filter_canvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkTLazy.h"

namespace skia {

OpacityFilterCanvas::OpacityFilterCanvas(SkCanvas* canvas,
                                         float opacity,
                                         bool disable_image_filtering)
    : INHERITED(canvas->imageInfo().width(), canvas->imageInfo().height()),
      alpha_(SkScalarRoundToInt(opacity * 255)),
      disable_image_filtering_(disable_image_filtering) {
  this->addCanvas(canvas);
}

void OpacityFilterCanvas::onFilterPaint(SkPaint* paint, Type) const {
  if (alpha_ < 255)
    paint->setAlpha(alpha_);

  if (disable_image_filtering_)
    paint->setFilterQuality(kNone_SkFilterQuality);
}

void OpacityFilterCanvas::onDrawPicture(const SkPicture* picture,
                                        const SkMatrix* matrix,
                                        const SkPaint* paint) {
  SkTLazy<SkPaint> filteredPaint;
  if (paint) {
    this->onFilterPaint(filteredPaint.set(*paint), kPicture_Type);
  }

  // Unfurl pictures in order to filter nested paints.
  this->SkCanvas::onDrawPicture(picture, matrix, filteredPaint.getMaybeNull());
}

}  // namespace skia

// Copyright 2015 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 "skia/ext/opacity_filter_canvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkTLazy.h"

namespace skia {

OpacityFilterCanvas::OpacityFilterCanvas(SkCanvas* canvas,
                                         float opacity,
                                         bool disable_image_filtering)
    : INHERITED(canvas),
      alpha_(SkScalarRoundToInt(opacity * 255)),
      disable_image_filtering_(disable_image_filtering) { }

void OpacityFilterCanvas::onFilterPaint(SkPaint* paint, Type) const {
  if (alpha_ < 255)
    paint->setAlpha(alpha_);

  if (disable_image_filtering_)
    paint->setFilterQuality(kNone_SkFilterQuality);
}

void OpacityFilterCanvas::onDrawPicture(const SkPicture* picture,
                                        const SkMatrix* matrix,
                                        const SkPaint* paint) {
  SkTLazy<SkPaint> filteredPaint;
  if (paint) {
    this->onFilterPaint(filteredPaint.set(*paint), kPicture_Type);
  }

  // Unfurl pictures in order to filter nested paints.
  this->SkCanvas::onDrawPicture(picture, matrix, filteredPaint.getMaybeNull());
}

}  // namespace skia

Use the canvas-based SkPaintFilterCanvas ctor in OpacityFilterCanvas


#include "SliderKnob.h"

SliderKnob::SliderKnob(std::wstring bitmapName,
    int x, int y, int width, int height) :
Meter(bitmapName, x, y, 1),
_track(x, y, width, height) {
    _units = _track.Width - _rect.Width;
}

Gdiplus::Rect SliderKnob::Location() {
    return _rect;
}

void SliderKnob::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
    graphics->DrawImage(_bitmap, _rect,
        0, 0, _rect.Width, _track.Height, Gdiplus::UnitPixel);
}

void SliderKnob::Value(float value) {
    Meter::Value(value);
    X(_trackX + CalcUnits());
}

int SliderKnob::TrackX() const {
    return _trackX;
}

int SliderKnob::TrackY() const {
    return _trackY;
}

int SliderKnob::TrackWidth() const {
    return _trackWidth;
}

int SliderKnob::TrackHeight() const {
    return _trackHeight;
}

int SliderKnob::X() const {
    return Meter::X();
}

int SliderKnob::Y() const {
    return Meter::Y();
}

void SliderKnob::X(int x) {
    _rect.X = x;
}

void SliderKnob::Y(int y) {
    _rect.Y = y;
}

#include "SliderKnob.h"

SliderKnob::SliderKnob(std::wstring bitmapName,
    int x, int y, int width, int height) :
Meter(bitmapName, x, y, 1),
_track(x, y, width, height) {
    _units = _track.Width - _rect.Width;
}

Gdiplus::Rect SliderKnob::Location() {
    return _rect;
}

void SliderKnob::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
    graphics->DrawImage(_bitmap, _rect,
        0, 0, _rect.Width, _track.Height, Gdiplus::UnitPixel);
}

void SliderKnob::Value(float value) {
    Meter::Value(value);
    X(TrackX() + CalcUnits());
}

int SliderKnob::TrackX() const {
    return _track.X;
}

int SliderKnob::TrackY() const {
    return _track.Y;
}

int SliderKnob::TrackWidth() const {
    return _track.Width;
}

int SliderKnob::TrackHeight() const {
    return _track.Height;
}

int SliderKnob::X() const {
    return _rect.X;
}

int SliderKnob::Y() const {
    return _rect.Y;
}

void SliderKnob::X(int x) {
    _rect.X = x;
}

void SliderKnob::Y(int y) {
    _rect.Y = y;
}

int SliderKnob::Width() const {
    return _rect.Width;
}

int SliderKnob::Height() const {
    return _rect.Height;
}

Update for new rect tracking


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

  MYPROJECT: A software package for whatever.

  Copyright (c) University College London (UCL). All rights reserved.

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

  See LICENSE.txt in the top level directory for details.

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

#include <mpMyFunctions.h>
#include <iostream>

#ifdef BUILD_Eigen
#include <Eigen/Dense>
#endif

#ifdef BUILD_Boost
#include <boost/math/special_functions/round.hpp>
#endif

#ifdef BUILD_OpenCV
#include <cv.h>
#endif

int main(int argc, char** argv)
{

#ifdef BUILD_Eigen
  Eigen::MatrixXd m(2,2);
  std::cout << "Printing 2x2 matrix ..." << m << std::endl;
#endif

#ifdef BUILD_Boost
  std::cout << "Rounding to ... " << boost::math::round(0.123) << std::endl;
#endif

#ifdef BUILD_OpenCV
  cv::Matx44d matrix = cv::Matx44d::eye();
  std::cout << "Printing 4x4 matrix ..." << matrix << std::endl;
#endif

  std::cout << "Calculating ... " << mp::MyFirstFunction(1) << std::endl;
  return 0;
}

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

  MYPROJECT: A software package for whatever.

  Copyright (c) University College London (UCL). All rights reserved.

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

  See LICENSE.txt in the top level directory for details.

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

#include <mpMyFunctions.h>
#include <iostream>

#ifdef BUILD_Eigen
#include <Eigen/Dense>
#endif

#ifdef BUILD_Boost
#include <boost/math/special_functions/round.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem/path.hpp>
#endif

#ifdef BUILD_OpenCV
#include <cv.h>
#endif

int main(int argc, char** argv)
{

#ifdef BUILD_Eigen
  Eigen::MatrixXd m(2,2);
  std::cout << "Printing 2x2 matrix ..." << m << std::endl;
#endif

#ifdef BUILD_Boost
  std::cout << "Rounding to ... " << boost::math::round(0.123) << std::endl;
  boost::posix_time::ptime startTime = boost::posix_time::second_clock::local_time();
  boost::filesystem::path pathname( "/tmp/tmp.txt" );
#endif

#ifdef BUILD_OpenCV
  cv::Matx44d matrix = cv::Matx44d::eye();
  std::cout << "Printing 4x4 matrix ..." << matrix << std::endl;
#endif

  std::cout << "Calculating ... " << mp::MyFirstFunction(1) << std::endl;
  return 0;
}

Make sure Im using Boost libraries, not just headers.


#include "fade_effect.h"

unsigned int FadeEffect::maxDelay()
{
    return -1;
}

void FadeEffect::init()
{
    // Handle a corner case in which the update just increments
    // a color and overflows the byte
    if( R() == 255 ) R(254);
    if( G() == 255 ) G(254);
    if( B() == 255 ) R(254);
    stage = 0;
    renderTime = 0;
}

void FadeEffect::update()
{
    if( millis() < renderTime ) return;

    switch(stage)
    {
    case 0:
        if( G( G()+1 ) == 255 ) ++stage;
        break;
    case 1:
        if( R( R()-1 ) == 0 ) ++stage;
        break;
    case 2:
        if( B( B()+1 ) == 255 ) ++stage;
        break;
    case 3:
        if( G( G()-1 ) == 0 ) ++stage;
        break;
    case 4:
        if( R( R()+1 ) == 255 ) ++stage;
        break;
    case 5:
        if( B( B()-1 ) == 0 ) ++stage;
        break;
    }
    if( stage == 6 )
        stage = 0;

    renderTime += ceil((float)m_duration / 1536);
}

#include "fade_effect.h"

unsigned int FadeEffect::maxDelay()
{
    return -1;
}

void FadeEffect::init()
{
    // Handle a corner case in which the update just increments
    // a color and overflows the byte
    if( R() == 255 ) R(254);
    if( G() == 255 ) G(254);
    if( B() == 255 ) R(254);
    if( R() == 0 ) R(1);
    if( G() == 0 ) G(1);
    if( B() == 0 ) R(1);
    stage = 0;
    renderTime = 0;
}

void FadeEffect::update()
{
    if( millis() < renderTime ) return;

    switch(stage)
    {
    case 0:
        if( G( G()+1 ) == 255 ) ++stage;
        break;
    case 1:
        if( R( R()-1 ) == 0 ) ++stage;
        break;
    case 2:
        if( B( B()+1 ) == 255 ) ++stage;
        break;
    case 3:
        if( G( G()-1 ) == 0 ) ++stage;
        break;
    case 4:
        if( R( R()+1 ) == 255 ) ++stage;
        break;
    case 5:
        if( B( B()-1 ) == 0 ) ++stage;
        break;
    }
    if( stage == 6 )
        stage = 0;

    renderTime += ceil((float)m_duration / 1536);
}

Handle another fade effect corner case when colour is black


// Nikita Kouevda
// 2013/11/01

#include <iostream>

#include "prime.hpp"

using namespace std;

int main(int argc, char *argv[]) {
  if (argc < 2) {
    cerr << "Usage: prime number ..." << endl;
    return 1;
  }

  for (int i = 1; i < argc; ++i) {
    cout << argv[i] << " is";

    if (!isPrime(atol(argv[i]))) {
      cout << " not";
    }

    cout << " prime" << endl;
  }

  return 0;
}

// Nikita Kouevda
// 2013/11/04

#include <iostream>

#include "prime.hpp"

using namespace std;

int main(int argc, char *argv[]) {
  int i, n;
  char *endptr;

  if (argc < 2) {
    cerr << "usage: prime number ..." << endl;
    return 1;
  }

  for (i = 1; i < argc; ++i) {
    n = strtol(argv[i], &endptr, 10);

    if (*endptr) {
      cerr << "prime: illegal argument: " << argv[i] << endl;
      continue;
    }

    cout << argv[i] << " is";

    if (!isPrime(n)) {
      cout << " not";
    }

    cout << " prime" << endl;
  }

  return 0;
}

Use strtol instead of atol; verify conversion.


#include "MediaServiceHandler.h"

using namespace ::com::kurento::kms::api;

namespace com { namespace kurento { namespace kms {

MediaServerServiceHandler::MediaServerServiceHandler()
{
	manager = MediaSessionManager::getInstance();
}

MediaServerServiceHandler::~MediaServerServiceHandler() {
	MediaSessionManager::releaseInstance(manager);
}

void MediaServerServiceHandler::createMediaSession(MediaSession& _return) {
	_return = manager->createMediaSession();
}

void MediaServerServiceHandler::deleteMediaSession(const MediaSession& session) {
	manager->deleteMediaSession(session);
}

}}} // com::kurento::kms

#include "MediaServiceHandler.h"
#include "log.h"

using namespace ::com::kurento::kms::api;

using ::com::kurento::log::Log;

static Log l("MediaServiceHandler");
#define d(...) aux_debug(l, __VA_ARGS__);
#define i(...) aux_info(l, __VA_ARGS__);

namespace com { namespace kurento { namespace kms {

MediaServerServiceHandler::MediaServerServiceHandler()
{
	manager = MediaSessionManager::getInstance();
}

MediaServerServiceHandler::~MediaServerServiceHandler() {
	MediaSessionManager::releaseInstance(manager);
}

void MediaServerServiceHandler::createMediaSession(MediaSession& _return) {
	i("createMediaSession");
	_return = manager->createMediaSession();
}

void MediaServerServiceHandler::deleteMediaSession(const MediaSession& session) {
	i("deleteMediaSession");
	manager->deleteMediaSession(session);
}

}}} // com::kurento::kms

Add basic log on MediaService


// Insure __block_holder_tmp is allocated on the stack.
// RUN: %llvmgxx %s -S -O2 -o - | egrep {__block_holder_tmp.*alloca}
// <rdar://problem/5865221>
extern void fubar_dispatch_sync(void (^PP)(void));
void fubar() {
  __block void *voodoo;
 fubar_dispatch_sync(^(void){voodoo=0;});
}

// Insure __block_holder_tmp is allocated on the stack.  Darwin only.
// RUN: %llvmgxx %s -S -O2 -o - | egrep {__block_holder_tmp.*alloca}
// XFAIL: *
// XTARGET: darwin
// <rdar://problem/5865221>
// END.
extern void fubar_dispatch_sync(void (^PP)(void));
void fubar() {
  __block void *voodoo;
 fubar_dispatch_sync(^(void){voodoo=0;});
}

Mark this test as Darwin only. Patch by Bill Wendling.


// StackTrace.cpp

// Implements the functions to print current stack traces

#include "Globals.h"
#include "StackTrace.h"
#ifdef _WIN32
	#include "../StackWalker.h"
#else
	#ifdef __GLIBC__
		#include <execinfo.h>
	#endif
	#include <unistd.h>
#endif

// FreeBSD uses size_t for the return type of backtrace()
#if defined(__FreeBSD__) && (__FreeBSD__ >= 10)
	#define btsize size_t
#else
	#define btsize int
#endif

void PrintStackTrace(void)
{
	#ifdef _WIN32
		// Reuse the StackWalker from the LeakFinder project already bound to MCS
		// Define a subclass of the StackWalker that outputs everything to stdout
		class PrintingStackWalker :
			public StackWalker
		{
			virtual void OnOutput(LPCSTR szText) override
			{
				puts(szText);
			}
		} sw;
		sw.ShowCallstack();
	#else
		#ifdef __GLIBC__
			// Use the backtrace() function to get and output the stackTrace:
			// Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
			void * stackTrace[30];
			btsize numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace));
			backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO);
		#endif
	#endif
}

// StackTrace.cpp

// Implements the functions to print current stack traces

#include "Globals.h"
#include "StackTrace.h"
#ifdef _WIN32
	#include "../StackWalker.h"
#else
	#ifdef __GLIBC__
		#include <execinfo.h>
	#endif
	#include <unistd.h>
#endif

void PrintStackTrace(void)
{
	#ifdef _WIN32
		// Reuse the StackWalker from the LeakFinder project already bound to MCS
		// Define a subclass of the StackWalker that outputs everything to stdout
		class PrintingStackWalker :
			public StackWalker
		{
			virtual void OnOutput(LPCSTR szText) override
			{
				puts(szText);
			}
		} sw;
		sw.ShowCallstack();
	#else
		#ifdef __GLIBC__
			// Use the backtrace() function to get and output the stackTrace:
			// Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
			void * stackTrace[30];
			auto numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace));
			backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO);
		#endif
	#endif
}

Use C++11 auto instead of per-platform types.


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

#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new TextFileNFDelegate);
    app.loadScriptNodes("Nodin/NodeScripts/Lua");

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

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

    return a.exec();
}

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

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.loadScriptNodes("Nodin/NodeScripts/Lua");

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

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

    return a.exec();
}

Stop using redundant class TextFileNFDelegate.


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

#include "content/browser/renderer_host/render_view_host_observer.h"

#include "content/browser/renderer_host/render_view_host.h"

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_->RemoveObserver(this);
  RenderViewHostDestroyed();
  render_view_host_ = NULL;
}

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

#include "content/browser/renderer_host/render_view_host_observer.h"

#include "content/browser/renderer_host/render_view_host.h"

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_ = NULL;
  RenderViewHostDestroyed();
}

Fix heap corruption that occurs when RenderViewHostObserver calls RenderViewHost to unregister when the latter is in its destructor.


#include <constrained_ik/enum_types.h>
#include <ros/console.h>

using namespace constrained_ik::constraint_types;

const std::string ConstraintType::names_[] = {"Primary", "Auxiliary", "Inactive"};
const std::map<std::string, ConstraintTypes> ConstraintType::name_to_enum_map_ = boost::assign::map_list_of ("Primary", Primary) ("Auxiliary", Auxiliary) ("Inactive", Inactive);

ConstraintTypes ConstraintType::stringToEnum(std::string constraint_type_name)
{
  std::map<std::string, ConstraintTypes>::const_iterator it;
  it = name_to_enum_map_.find(constraint_type_name);
  if (it != name_to_enum_map_.end())
    return it->second;
  else
    ROS_ERROR("No enumerator named %s. Valid names: Primary, Auxiliary, Inactive", constraint_type_name.c_str());
}

#include <constrained_ik/enum_types.h>
#include <ros/console.h>

using namespace constrained_ik::constraint_types;

const std::string ConstraintType::names_[] = {"Primary", "Auxiliary", "Inactive"};
const std::map<std::string, ConstraintTypes> ConstraintType::name_to_enum_map_ = boost::assign::map_list_of ("primary", Primary) ("auxiliary", Auxiliary) ("inactive", Inactive);

ConstraintTypes ConstraintType::stringToEnum(std::string constraint_type_name)
{
  std::map<std::string, ConstraintTypes>::const_iterator it;
  std::transform(constraint_type_name.begin(), constraint_type_name.end(), constraint_type_name.begin(), ::tolower);
  it = name_to_enum_map_.find(constraint_type_name);
  if (it != name_to_enum_map_.end())
    return it->second;
  else
    ROS_ERROR("No enumerator named %s. Valid names (Not case sensitive): Primary, Auxiliary, Inactive", constraint_type_name.c_str());
}

Make ConstraintType::stringToEnum not case sensitive


#include <xpcc/architecture.hpp>
#include "../stm32f4_discovery.hpp"

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	defaultSystemClock::enable();

	LedOrange::setOutput(xpcc::Gpio::High);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::High);
	LedBlue::setOutput(xpcc::Gpio::High);

	// Enable USART 2
	GpioOutputA2::connect(Usart2::Tx);
	GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
	Usart2::initialize<defaultSystemClock, 9600>(12);

	while (1)
	{
		static uint8_t c = 'A';
		LedRed::toggle();
		LedGreen::toggle();
		Usart2::write(c);
		++c;
		if (c == 'Z' + 1) {
			c = 'A';
		}
		xpcc::delay_ms(500);
	}

	return 0;
}

#include <xpcc/architecture.hpp>
#include "../stm32f4_discovery.hpp"

// ----------------------------------------------------------------------------
/**
 * Very basic example of USART usage.
 * The ASCII sequence 'A', 'B', 'C, ... , 'Z', 'A', 'B', 'C', ...
 * is printed with 9600 baud, 8N1 at pin PA3.
 */
MAIN_FUNCTION
{
	defaultSystemClock::enable();

	LedOrange::setOutput(xpcc::Gpio::High);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::High);
	LedBlue::setOutput(xpcc::Gpio::High);

	// Enable USART 2
	GpioOutputA2::connect(Usart2::Tx);
	GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
	Usart2::initialize<defaultSystemClock, 9600>(12);

	while (1)
	{
		static uint8_t c = 'A';
		LedRed::toggle();
		LedGreen::toggle();
		Usart2::write(c);
		++c;
		if (c > 'Z') {
			c = 'A';
		}
		xpcc::delay_ms(500);
	}

	return 0;
}

Document what is expected from UART example


#include "hapticbutton.h"
#include <QPainter>

HapticButton::HapticButton(const QString &label) :
    QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
    setMinimumSize(100, 100);
}

void HapticButton::mousePressEvent(QMouseEvent *)
{
    if (m_checkable) {
        m_checked = !m_checked;
        emit toggled(m_checked);
    } else {
        emit clicked();
    }
}

void HapticButton::paintEvent(QPaintEvent *)
{
    QPainter paint(this);

    QRect r(0, 0, width()-1, height()-1);
    paint.drawRoundedRect(r, 10, 10);
    paint.drawText(r, Qt::AlignCenter, m_label);
}

#include "hapticbutton.h"
#include <QPainter>

HapticButton::HapticButton(const QString &label) :
    QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
    setMinimumSize(100, 100);
}

void HapticButton::mousePressEvent(QMouseEvent *)
{
    if (m_checkable) {
        m_checked = !m_checked;
        emit toggled(m_checked);
    } else {
        emit clicked();
    }
}

void HapticButton::paintEvent(QPaintEvent *)
{
    QPainter paint(this);

    QRect r(1, 1, width()-2, height()-2);
    paint.drawRoundedRect(r, 10, 10);
    paint.drawText(r, Qt::AlignCenter, m_label);
}

Fix cropped hapticsquare buttons on devices


#include <ccspec/core/formatter.h>

namespace ccspec {
namespace core {

using std::exception_ptr;
using std::list;
using std::ostream;

// public methods.

void Formatter::examplePassed(const ExecutionResult& execution_result) const {
    (void) execution_result;
}

void Formatter::exampleFailed(const ExecutionResult& execution_result) const {
    (void) execution_result;
}

void Formatter::afterEachHookFailed(exception_ptr failure) const {
    (void) failure;
}

void Formatter::aroundHookFailed(exception_ptr failure) const {
    (void) failure;
}

void Formatter::startDump() const {}

void Formatter::dumpFailures(const list<exception_ptr>& failures) const {
    (void) failures;
}

// Protected methods.

Formatter::Formatter(ostream& output) : output_(output) {}

} // namespace core
} // namespace ccspec

#include <ccspec/core/formatter.h>

namespace ccspec {
namespace core {

using std::exception_ptr;
using std::list;
using std::ostream;

// public methods.

void Formatter::examplePassed(const ExecutionResult&) const {}

void Formatter::exampleFailed(const ExecutionResult&) const {}

void Formatter::afterEachHookFailed(exception_ptr) const {}

void Formatter::aroundHookFailed(exception_ptr) const {}

void Formatter::startDump() const {}

void Formatter::dumpFailures(const list<exception_ptr>&) const {}

// Protected methods.

Formatter::Formatter(ostream& output) : output_(output) {}

} // namespace core
} // namespace ccspec

Remove formal parameters to avoid complier warning


#include <exception>
#include <iostream>
#include <cstdlib>
#include "IMPL/LCIOExceptionHandler.h"

namespace IMPL {

  // create one globale instance of the handler
  LCIOExceptionHandler* LCIOExceptionHandler::_me = 0 ;

/** Method catches any std::exception, prints the message to stdout
 * and then exits the program.
 */
void lcio_unexpected(){

  try{

    throw ;

  }catch( std::exception& e){

    std::cout << " A runtime error has occured : "
	      << e.what()
	      << std::endl
	      << " the program will have to be terminated - sorry." << std::endl ;
    exit(1) ;
  }
}

  LCIOExceptionHandler::LCIOExceptionHandler(){

    std::set_unexpected( lcio_unexpected ) ;
    std::set_terminate( lcio_unexpected ) ;
  }

  LCIOExceptionHandler* LCIOExceptionHandler::createInstance(){

    if( ! _me ){
      _me = new LCIOExceptionHandler ;
    }

    return _me ;
  }
}

#include <exception>
#include <iostream>
#include <cstdlib>
#include "IMPL/LCIOExceptionHandler.h"

namespace IMPL {

  // create one globale instance of the handler
  LCIOExceptionHandler* LCIOExceptionHandler::_me = 0 ;

/** Method catches any std::exception, prints the message to stdout
 * and then exits the program.
 */
void lcio_unexpected(){

  try{

    throw ;

  }catch( std::exception& e){

    std::cout << " A runtime error has occured : "
	      << e.what()
	      << std::endl
	      << " the program will have to be terminated - sorry." << std::endl ;
    exit(1) ;
  }
}

  LCIOExceptionHandler::LCIOExceptionHandler(){}

  LCIOExceptionHandler* LCIOExceptionHandler::createInstance(){

    if( ! _me ){
      _me = new LCIOExceptionHandler ;
    }

    return _me ;
  }
}

Remove deprecated set_unexpected and set_terminate


#include "./compile.h"
#include "tree_sitter/compiler.h"

namespace node_tree_sitter_compiler {

using namespace v8;

NAN_METHOD(Compile) {
  String::Utf8Value grammar_json(info[0]);
  TSCompileResult compile_result = ts_compile_grammar(*grammar_json);

  if (compile_result.error_message) {
    Local<Value> error = Nan::Error(compile_result.error_message);
    Local<Object>::Cast(error)->Set(Nan::New("isGrammarError").ToLocalChecked(), Nan::True());
    Nan::ThrowError(error);
  } else {
    info.GetReturnValue().Set(Nan::New(compile_result.code).ToLocalChecked());
  }
}

}  // namespace node_tree_sitter_compiler

#include "./compile.h"
#include "tree_sitter/compiler.h"

namespace node_tree_sitter_compiler {

using namespace v8;

NAN_METHOD(Compile) {
  String::Utf8Value grammar_json(info[0]);
  TSCompileResult compile_result = ts_compile_grammar(*grammar_json);

  if (compile_result.error_type != TSCompileErrorTypeNone) {
    Local<Value> error = Nan::Error(compile_result.error_message);
    Local<Object>::Cast(error)->Set(Nan::New("isGrammarError").ToLocalChecked(), Nan::True());
    Nan::ThrowError(error);
  } else {
    info.GetReturnValue().Set(Nan::New(compile_result.code).ToLocalChecked());
  }
}

}  // namespace node_tree_sitter_compiler

Use the error_type field to check for errors


#include "platform/platform.h"
#include "WProgram.h"

void openxc::platform::initialize() {
    // this is required to initialize the Wiring library from MPIDE's toolchain
    // (inspired by Arduino)
    init();
}

#include "platform/platform.h"
#include "WProgram.h"

extern "C" {
extern void __use_isr_install(void);
__attribute__((section(".comment"))) void (*__use_force_isr_install)(void) = &__use_isr_install;
}

void openxc::platform::initialize() {
    // this is required to initialize the Wiring library from MPIDE's toolchain
    // (inspired by Arduino)
    init();
}

Install ISR on PIC32 with updated build script.


// RUN: %clang_cc1 -emit-llvm-only -triple %itanium_abi_triple -fdump-record-layouts %s 2>/dev/null \
// RUN:            | FileCheck %s

union A {
  int f1: 3;
  A();
};

A::A() {}

union B {
  int f1: 69;
  B();
};

B::B() {}

// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT:   0 | union A
// CHECK-NEXT:   0 |   int f1
// CHECK-NEXT:     | [sizeof=4, dsize=1, align=4
// CHECK-NEXT:     |  nvsize=1, nvalign=4]

// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT:   0 | union B
// CHECK-NEXT:   0 |   int f1
// CHECK-NEXT:     | [{{sizeof=16, dsize=9, align=8|sizeof=12, dsize=9, align=4}}
// CHECK-NEXT:     |  {{nvsize=9, nvalign=8|nvsize=9, nvalign=4}}]

// RUN: %clang_cc1 -emit-llvm-only -triple %itanium_abi_triple -fdump-record-layouts %s 2>/dev/null \
// RUN:            | FileCheck %s

union A {
  int f1: 3;
  A();
};

A::A() {}

union B {
  char f1: 35;
  B();
};

B::B() {}

// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT:   0 | union A
// CHECK-NEXT:   0 |   int f1
// CHECK-NEXT:     | [sizeof=4, dsize=1, align=4
// CHECK-NEXT:     |  nvsize=1, nvalign=4]

// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT:   0 | union B
// CHECK-NEXT:   0 |   int f1
// CHECK-NEXT:     | [sizeof=8, dsize=5, align=4
// CHECK-NEXT:     |  nvsize=5, nvalign=4]

Test case B is updated to work for 32-bit and 64-bit platforms


#include "utils.h"

#include <nlohmann/json.hpp>

using json = nlohmann::json;

std::string get_with_def(const std::map<std::string, std::string> &m, const std::string &key,
                         const std::string &defval)
{
  auto it = m.find(key);
  if (it == m.end())
    return defval;
  return it->second;
}

std::map<std::string, std::string> parse_to_map(const std::string &js)
{
  std::map<std::string, std::string> m;
  if (js.size())
    {
      json j = json::parse(js);
      for (auto v : j.items())
        m[v.key()] = v.value();
    }
  return m;
}

std::string geocoder_type(const std::string &t_class, const std::string &t_value)
{
  if (t_class == "building" || t_value == "yes")
    return t_class;
  return t_class + "_" + t_value;
}

#include "utils.h"

#include <nlohmann/json.hpp>

using json = nlohmann::json;

std::string get_with_def(const std::map<std::string, std::string> &m, const std::string &key,
                         const std::string &defval)
{
  auto it = m.find(key);
  if (it == m.end())
    return defval;
  return it->second;
}

std::map<std::string, std::string> parse_to_map(const std::string &js)
{
  std::map<std::string, std::string> m;
  if (js.size())
    {
      json j = json::parse(js);
      for (auto v : j.items())
        m[v.key()] = v.value();
    }
  return m;
}

std::string geocoder_type(const std::string &t_class, const std::string &t_value)
{
  if (t_value == "yes")
    return t_class;
  return t_class + "_" + t_value;
}

Use full tag for buildings if available


#include "utils/LinearAlg2D.h"

int main(int argc, char** argv)
{
	// Pick a function that's not defined in the header.
	const float angle =
		cura::LinearAlg2D::getAngleLeft
		(
			cura::Point(1.0, 1.0),
			cura::Point(1.0, 2.0),
			cura::Point(3.0, 3.0)
		);
	return (angle != 0.f) ? 0 : 1;
}

#include "settings/Settings.h"  // For the default definition of 'CURA_ENGINE_VERSION' if none is given.
#include "utils/LinearAlg2D.h"  // For testing calling a simple non-header function.

#include <cstdio>

int main(int argc, char** argv)
{
	// Test which version do we have here?
	std::fprintf(stdout, "test-package called for version: %s\n", CURA_ENGINE_VERSION);

	// Pick a function that's not defined in the header.
	const float angle =
		cura::LinearAlg2D::getAngleLeft
		(
			cura::Point(1.0, 1.0),
			cura::Point(1.0, 2.0),
			cura::Point(3.0, 3.0)
		);
	return (angle != 0.f) ? 0 : 1;
}

Debug which version is build with test-package.


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

#include <thread>
#include <mutex>

struct Complex {
    std::mutex mutex;
    int i;

    Complex() : i(0) {}

    void mul(int x){
        std::lock_guard<std::mutex> lock(mutex);
        i *= x;
    }

    void div(int x){
        std::lock_guard<std::mutex> lock(mutex);
        i /= x;
    }

    void both(int x, int y){
        std::lock_guard<std::mutex> lock(mutex);
        mul(x);
        div(y);
    }
};

int main(){
    Complex complex;
    complex.both(32, 23);

    return 0;
}

Set the code to MIT license


// RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s

int a<::> = { 1, 2, 3 };
int b = a<:::a<:0:>:>;
bool c = a<:0:><::b;

template<int &n> void f() {}
template void f<::b>();

#define x a<:: ## : b :>
int d = x; // expected-error {{pasting formed ':::', an invalid preprocessing token}} expected-error {{expected unqualified-id}}

const char xs[] = R"(\
??=\U0000)";
static_assert(sizeof(xs) == 12, "did not revert all changes");

Test that we correctly handle reversion of line splicing etc in raw string literals. As suggested by Sean Silva.