#include <puppet/compiler/settings.hpp>
#include <boost/filesystem.hpp>
#include <unistd.h>

using namespace std;
namespace fs = boost::filesystem;
namespace sys = boost::system;

namespace puppet { namespace compiler {

    string settings::default_code_directory()
    {
        auto home = getenv("HOME");

        // For root or if the directory exists, use the global code directory
        sys::error_code ec;
        if (!home || geteuid() == 0 || fs::is_directory("/etc/puppetlabs/code", ec)) {
            return "/etc/puppetlabs/code";
        }

        // Otherwise, use the local directory
        return (fs::path(home) / ".puppetlabs" / "etc" / "code").string();
    }

    vector<string> settings::default_environment_directories()
    {
        vector<string> directories = {
            "$codedir/environments",
        };
        return directories;
    }

    vector<string> settings::default_module_directories()
    {
        vector<string> directories = {
            "$codedir/modules",
            "/opt/puppetlabs/puppet/modules",
        };
        return directories;
    }

}}  // namespace puppet::compiler

#include <puppet/compiler/settings.hpp>
#include <boost/filesystem.hpp>
#include <unistd.h>

using namespace std;
namespace fs = boost::filesystem;
namespace sys = boost::system;

namespace puppet { namespace compiler {

    string settings::default_code_directory()
    {
        auto home = getenv("HOME");

        // For root or users without a HOME directory, use the global location
        if (!home || geteuid() == 0) {
            return "/etc/puppetlabs/code";
        }

        // Otherwise, use the local directory
        return (fs::path(home) / ".puppetlabs" / "etc" / "code").string();
    }

    vector<string> settings::default_environment_directories()
    {
        vector<string> directories = {
            "$codedir/environments",
        };
        return directories;
    }

    vector<string> settings::default_module_directories()
    {
        vector<string> directories = {
            "$codedir/modules",
            "/opt/puppetlabs/puppet/modules",
        };
        return directories;
    }

}}  // namespace puppet::compiler

Fix default code directory for non-root user.


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <regex>

// class match_results<BidirectionalIterator, Allocator>

// match_results(const match_results&& m) noexcept;

#include <regex>
#include <cassert>
#include "test_macros.h"
#include "test_allocator.h"

template <class CharT, class Allocator>
void
test(const Allocator& a)
{
    typedef std::match_results<const CharT*, Allocator> SM;
    ASSERT_NOEXCEPT(SM(std::declval<SM&&>()));

    SM m0(a);
    SM m1(std::move(m0));
    assert(m1.size() == 0);
    assert(m1.str() == std::basic_string<CharT>());
    assert(m1.get_allocator() == a);
}

int main()
{
    test<char>   (std::allocator<std::sub_match<const char *> >());
    test<wchar_t>(std::allocator<std::sub_match<const wchar_t *> >());

    test<char>   (test_allocator<std::sub_match<const char*> >(3));
    test<wchar_t>(test_allocator<std::sub_match<const wchar_t*> >(3));
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <regex>

// class match_results<BidirectionalIterator, Allocator>

// match_results(match_results&& m) noexcept;

#include <regex>
#include <cassert>
#include "test_macros.h"
#include "test_allocator.h"

template <class CharT, class Allocator>
void
test(const Allocator& a)
{
    typedef std::match_results<const CharT*, Allocator> SM;
    ASSERT_NOEXCEPT(SM(std::declval<SM&&>()));

    SM m0(a);
    SM m1(std::move(m0));
    assert(m1.size() == 0);
    assert(m1.str() == std::basic_string<CharT>());
    assert(m1.get_allocator() == a);
}

int main()
{
    test<char>   (std::allocator<std::sub_match<const char *> >());
    test<wchar_t>(std::allocator<std::sub_match<const wchar_t *> >());

    test<char>   (test_allocator<std::sub_match<const char*> >(3));
    test<wchar_t>(test_allocator<std::sub_match<const wchar_t*> >(3));
}

Remove a 'const' from the synopsis. NFC


// Native C++ Libraries
#include <iostream>
#include <string>

// C++ Interpreter Libraries
#include <Console.h>

Add C++ Interpreter Libraries to the main source.


/******************************************************************
*
* Copyright 2014 Samsung Electronics All Rights Reserved.
*
*
*
* 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 "ResourceConnectivity.h"

SSMRESULT CResourceConnectivity::finalConstruct()
{
	SSMRESULT res = SSM_E_FAIL;
    OC::PlatformConfig cfg(OC::ServiceType::InProc, OC::ModeType::Both,
            "134.134.161.33", 56831, OC::QualityOfService::NonConfirmable);

	m_pPlatform = new OC::OCPlatform(cfg);

	SSM_CLEANUP_NULL_ASSERT(m_pPlatform);
	res = SSM_S_OK;

CLEANUP:
	return res;
}

void CResourceConnectivity::finalRelease()
{
}

void* CResourceConnectivity::getPlatform()
{
	return m_pPlatform;
}

/******************************************************************
*
* Copyright 2014 Samsung Electronics All Rights Reserved.
*
*
*
* 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 "ResourceConnectivity.h"

SSMRESULT CResourceConnectivity::finalConstruct()
{
	SSMRESULT res = SSM_E_FAIL;
    OC::PlatformConfig cfg(OC::ServiceType::InProc, OC::ModeType::Both,
            "134.134.161.33", 56831, OC::QualityOfService::NonConfirmable);

	m_pPlatform = new OC::OCPlatform(cfg);

	SSM_CLEANUP_NULL_ASSERT(m_pPlatform);

	res = SSM_S_OK;

CLEANUP:
	return res;
}

void CResourceConnectivity::finalRelease()
{
	SAFE_DELETE(m_pPlatform);
}

void* CResourceConnectivity::getPlatform()
{
	return m_pPlatform;
}

Fix to call OIC platform destructor


#include <cmath>
#include <stdexcept>

#include "Layer/filter.hpp"
#include "Utility/utility.hpp"

using namespace Convolutional;
using namespace Convolutional::Layer;

Filter::Filter(std::size_t size) :
bias{Utility::GetRandomNumberBetween(-1.0, 1.0)} {
	// TODO jnf: constexpr check if size is perfect square
	weights.reserve(size);
	for (size_t i = 0; i < size; ++i) {
		weights.push_back(Utility::GetRandomNumberBetween(-1.0, 1.0));
	}
}

auto Filter::ProcessMatrix(Matrix matrix) const -> Matrix {
	if (matrix.GetElementCount() != weights.size()) {
		throw std::invalid_argument("Number of weights in filter does not match number of elements in matrix");
	}

	Matrix featureMap{matrix.GetSubmatrix(position, GetReceptiveField(matrix.GetSize()))};

	auto featureValue = bias;
	auto weight = weights.begin();
	for (const auto& element : featureMap) {
		featureValue += element * *weight;
		++weight;
	}
	featureValue = sigmoid(featureValue);

	for (auto& element : featureMap) {
		element = featureValue;
	}

	return featureMap;
}

auto Filter::sigmoid(Matrix::element_t n) -> double {
	return tanh(n);
}

#include <cmath>
#include <stdexcept>

#include "Layer/filter.hpp"
#include "Utility/utility.hpp"

using namespace Convolutional;
using namespace Convolutional::Layer;

Filter::Filter(std::size_t size) :
bias{Utility::GetRandomNumberBetween(-1.0, 1.0)} {
	// TODO jnf: constexpr check if size is perfect square
	weights.reserve(size);
	for (size_t i = 0; i < size; ++i) {
		weights.push_back(Utility::GetRandomNumberBetween(-1.0, 1.0));
	}
}

auto Filter::ProcessMatrix(Matrix matrix) const -> Matrix {
	if (matrix.GetElementCount() != weights.size()) {
		throw std::invalid_argument("Number of weights in filter does not match number of elements in matrix");
	}

	auto featureValue = bias;
	auto weight = weights.begin();
	for (const auto& element : matrix) {
		featureValue += element * *weight;
		++weight;
	}
	featureValue = sigmoid(featureValue);

	for (auto& element : matrix) {
		element = featureValue;
	}

	return matrix;
}

auto Filter::sigmoid(Matrix::element_t n) -> double {
	return tanh(n);
}

Remove corpses from old code


#include <iostream>

#include "..\..\shared\ProblemEngine.h"

int FindShortestPath(const int * const data, int size);

int main(int argc, char * argv[])
{
	ProblemEngine<> engine("input.txt");
	if (!engine.IsFileOk())
	{
		std::cout << "Unable to open input.txt" << std::endl;
		return 1;
	}

	auto testCases = engine.LoadTestCases();

	for (const auto& testCase : testCases)
	{
		auto data = testCase.Datas.front().get();
		auto size = testCase.Sizes.front();

		auto sp = FindShortestPath(data, size);

		std::cout << sp << std::endl;
	}

	return 0;
}

int FindShortestPath(const int * const data, int size)
{
	return 0;
}

#include <iostream>

#include "..\..\shared\ProblemEngine.h"

int FindShortestPath(int ** data, int rowSize);

int** CreateMatrix(const int * const input, int rowSize)
{
	auto ret = new int*[rowSize];
	for (int i = 0; i < rowSize; ++i)
	{
		ret[i] = new int[rowSize];
		for (int j = 0; j < rowSize; ++j)
			ret[i][j] = input == nullptr ? 0 : input[i * rowSize + j];
	}
	return ret;
}

void DeleteMatrix(int **& input, int rowSize)
{
	for (int i = 0; i < rowSize; ++i)
		delete[] input[i];
	delete[] input;
	input = nullptr;
}

int min(int a, int b, int c)
{
	if (a < b && a < c) return a;
	if (b < a && b < c) return b;
	return c;
}

int main(int argc, char * argv[])
{
	ProblemEngine<> engine("input.txt");
	if (!engine.IsFileOk())
	{
		std::cout << "Unable to open input.txt" << std::endl;
		return 1;
	}

	auto testCases = engine.LoadTestCases();

	for (const auto& testCase : testCases)
	{
		auto data = testCase.Datas.front().get();
		auto size = testCase.Sizes.front();

		auto rowSize = static_cast<int>(sqrt(size));
		if (size != rowSize * rowSize)
			throw std::exception("input data is not a square matrix");

		int ** matrix = CreateMatrix(data, rowSize);
		auto sp = FindShortestPath(matrix, rowSize);
		DeleteMatrix(matrix, rowSize);

		std::cout << sp << std::endl;
	}

	return 0;
}

int FindShortestPath(int ** ptr, int rowSize)
{
	return 0;
}

Create matrix out of input data to simplify algorithm


#include <cstdlib>
#include <ATK/EQ/BesselFilter.h>
#include <ATK/EQ/IIRFilter.h>

#include <ATK/Mock/SimpleSinusGeneratorFilter.h>

int main(int argc, char** argv)
{
  ATK::SimpleSinusGeneratorFilter<double> generator;
  generator.set_output_sampling_rate(1024 * 64);
  generator.set_amplitude(1);
  generator.set_frequency(1000);

  ATK::IIRFilter<ATK::BesselLowPassCoefficients<double> > filter;
  filter.set_input_sampling_rate(1024 * 64);
  filter.set_output_sampling_rate(1024 * 64);
  filter.set_cut_frequency(100);
  filter.set_order(3);

  filter.set_input_port(0, &generator, 0);

  for(size_t i = 0; i < 1024*1024; ++i)
    filter.process(1024);

  return EXIT_SUCCESS;
}

#include <cstdlib>
#include <ATK/EQ/BesselFilter.h>
#include <ATK/EQ/IIRFilter.h>

#include <ATK/Mock/SimpleSinusGeneratorFilter.h>

int main(int argc, char** argv)
{
  ATK::SimpleSinusGeneratorFilter<double> generator;
  generator.set_output_sampling_rate(1024 * 64);
  generator.set_amplitude(1);
  generator.set_frequency(1000);

  ATK::IIRFilter<ATK::BesselLowPassCoefficients<double> > filter;
  filter.set_input_sampling_rate(1024 * 64);
  filter.set_output_sampling_rate(1024 * 64);
  filter.set_cut_frequency(100);
  filter.set_order(7);

  filter.set_input_port(0, &generator, 0);

  for(size_t i = 0; i < 1024*1024; ++i)
    filter.process(1024);

  return EXIT_SUCCESS;
}

MAke it simpler to vectorize (even if this is not the proper way)


// Copyright 2017 Google Inc. All rights reserved.
//
// 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 <stdlib.h>
#include <sys/wait.h>

#include "gtest/gtest.h"

const int kDefaultLibFuzzerError = 77;

TEST(LibFuzzerExampleTest, Crash) {
  char dir_template[] = "/tmp/libfuzzer_example_test_XXXXXX";
  auto dir = mkdtemp(dir_template);
  ASSERT_TRUE(dir);

  std::string cmd =
      "./libfuzzer_example -max_len=10000 -runs=100000 -artifact_prefix=" +
      std::string(dir) + "/ " + dir;
  int retvalue = std::system(cmd.c_str());
  EXPECT_EQ(kDefaultLibFuzzerError, WSTOPSIG(retvalue));

  // Cleanup.
  EXPECT_EQ(0, std::system((std::string("rm -rf ") + dir).c_str()));
}

// Copyright 2017 Google Inc. All rights reserved.
//
// 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 <stdlib.h>
#include <sys/wait.h>

#include "gtest/gtest.h"

const int kDefaultLibFuzzerError = 77;

TEST(LibFuzzerExampleTest, Crash) {
  char dir_template[] = "/tmp/libfuzzer_example_test_XXXXXX";
  auto dir = mkdtemp(dir_template);
  ASSERT_TRUE(dir);

  std::string cmd =
      "./libfuzzer_example -max_len=10000 -runs=300000 -artifact_prefix=" +
      std::string(dir) + "/ " + dir;
  int retvalue = std::system(cmd.c_str());
  EXPECT_EQ(kDefaultLibFuzzerError, WSTOPSIG(retvalue));

  // Cleanup.
  EXPECT_EQ(0, std::system((std::string("rm -rf ") + dir).c_str()));
}

Increase number of iterations in libFuzzer test


#include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"

static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
    return NULL;
}

static PyMethodDef QuantucciaMethods[] = {
	{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
	{NULL, NULL, 0, NULL}
};

static struct PyModuleDef quantuccia_module_def = {
	PyModuleDef_HEAD_INIT,
	"quantuccia",
	NULL,
	-1,
	QuantucciaMethods,
	NULL,
	NULL,
	NULL,
	NULL
};

PyMODINIT_FUNC PyInit_quantuccia(void){
    PyObject *m;
    m = PyModule_Create(&quantuccia_module_def);
    return m;
}

#include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"

static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
    return Py_None;
}

static PyMethodDef QuantucciaMethods[] = {
	{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
	{NULL, NULL, 0, NULL}
};

static struct PyModuleDef quantuccia_module_def = {
	PyModuleDef_HEAD_INIT,
	"quantuccia",
	NULL,
	-1,
	QuantucciaMethods,
	NULL,
	NULL,
	NULL,
	NULL
};

PyMODINIT_FUNC PyInit_quantuccia(void){
    PyObject *m;
    m = PyModule_Create(&quantuccia_module_def);
    return m;
}

Change return NULL -> return Py_None.


#include <iostream>
#include <string>
#include <utility>
#include <map>
#include <vector>
#include <functional>

#include <useful/sort.hpp>
#include <useful/range.hpp>

using namespace useful;

using wcount = std::map<std::string, int>;

int main(void) {
	wcount words;
	std::string word;

	while (std::cin >> word)
		words[word] += 1;

	std::vector<std::pair<std::string, int>> wordv(words.begin(), words.end());
	std::partial_sort(wordv.begin(), wordv.begin() + 10, wordv.end(),
			cmp2nd<std::string, int, std::greater<int>>()
			//std::not2(cmp2nd<std::string, int>())
			//[](auto &a, auto &b) { return a.second > b.second; }
			);

	for (const auto p : take(wordv, 10))
		std::cout << p.second << ": " << p.first << '\n';

	return 0;
}

#include <iostream>
#include <string>
#include <utility>
#include <map>
#include <vector>
#include <functional>
#include <algorithm>

#include <useful/sort.hpp>
#include <useful/range.hpp>

using namespace useful;

using wcount = std::map<std::string, int>;

int main(void) {
	wcount words;
	std::string word;

	while (std::cin >> word)
		words[word] += 1;

	std::vector<std::pair<std::string, int>> wordv(words.begin(), words.end());
	std::partial_sort(wordv.begin(), wordv.begin() + 10, wordv.end(),
			cmp2nd<std::string, int, std::greater<int>>()
			//std::not2(cmp2nd<std::string, int>())
			//[](auto &a, auto &b) { return a.second > b.second; }
			);

	for (const auto p : take(wordv, 10))
		std::cout << p.second << ": " << p.first << '\n';

	return 0;
}

Add test program demonstrating finding most common words.


#include <aerial_autonomy/common/html_utils.h>
#include <gtest/gtest.h>
#include <iostream>

/// \brief TEST
/// Simple Html table tests
TEST(HtmlTableWriterTests, SimpleTable) {
  HtmlTableWriter table_writer;
  table_writer.beginRow();
  table_writer.addHeader("Header");
  table_writer.beginRow();
  double data = 2.0;
  table_writer.addCell(data, "Hello");
  table_writer.addCell("Data");
  table_writer.addCell("Data", "Hello", Colors::white);
  std::cout << "Table: \n" << table_writer.getTableString() << std::endl;
}
TEST(HtmlTableWriterTests, TableError) {
  HtmlTableWriter table_writer;
  EXPECT_THROW(table_writer.addHeader("Hello"), std::runtime_error);
  EXPECT_THROW(table_writer.addCell("Hello"), std::runtime_error);
}
/// Simple Html division tests
TEST(HtmlTableWriterTests, SimpleDivision) {
  HtmlDivisionWriter division_writer;
  division_writer.addHeader("Hello", 1);
  division_writer.addText("My text");
  std::cout << "Division: \n" << division_writer.getDivisionText() << std::endl;
}
///

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

#include <aerial_autonomy/common/html_utils.h>
#include <gtest/gtest.h>
#include <iostream>

/// \brief TEST
/// Simple Html table tests
TEST(HtmlTableWriterTests, SimpleTable) {
  HtmlTableWriter table_writer;
  table_writer.beginRow();
  table_writer.addHeader("Header");
  table_writer.beginRow();
  double data = 2.0;
  table_writer.addCell(data, "Hello");
  table_writer.addCell("Data");
  table_writer.addCell("Data", "Hello", Colors::white);
  ///\todo Add an automatic way of validating html string
  std::cout << "Table: \n" << table_writer.getTableString() << std::endl;
}
TEST(HtmlTableWriterTests, TableError) {
  HtmlTableWriter table_writer;
  EXPECT_THROW(table_writer.addHeader("Hello"), std::runtime_error);
  EXPECT_THROW(table_writer.addCell("Hello"), std::runtime_error);
}
/// Simple Html division tests
TEST(HtmlTableWriterTests, SimpleDivision) {
  HtmlDivisionWriter division_writer;
  division_writer.addHeader("Hello", 1);
  division_writer.addText("My text");
  std::cout << "Division: \n" << division_writer.getDivisionText() << std::endl;
}
///

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

Add todo for automatic html validation


#include "KVNetworkAccessManager.h"

#include <QDebug>

#include "KVNetworkReply.h"

KVNetworkAccessManager::KVNetworkAccessManager(QObject *parent) :
	QNetworkAccessManager(parent)
{

}

QNetworkReply *KVNetworkAccessManager::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData)
{
	QNetworkRequest request = req;
	request.setRawHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");

	if(request.url().host() != "localhost" && request.url().host() != "127.0.0.1")
	{
		if(op == QNetworkAccessManager::PostOperation)
		{
			qDebug() << "POST" << request.url().path();
			QNetworkReply *r = QNetworkAccessManager::createRequest(op, request, outgoingData);
			KVNetworkReply *reply = new KVNetworkReply(r->parent(), r, this);
			return reply;
		}
		else if(op == QNetworkAccessManager::GetOperation)
		{
			qDebug() << "GET" << request.url().path();
		}
	}

	QNetworkReply *reply = QNetworkAccessManager::createRequest(op, request, outgoingData);
	return reply;
}

#include "KVNetworkAccessManager.h"

#include <QDebug>

#include "KVNetworkReply.h"

KVNetworkAccessManager::KVNetworkAccessManager(QObject *parent) :
	QNetworkAccessManager(parent)
{

}

QNetworkReply *KVNetworkAccessManager::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData)
{
	QNetworkRequest request = req;
	request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36");

	if(request.url().host() != "localhost" && request.url().host() != "127.0.0.1")
	{
		if(op == QNetworkAccessManager::PostOperation)
		{
			qDebug() << "POST" << request.url().path();
			QNetworkReply *r = QNetworkAccessManager::createRequest(op, request, outgoingData);
			KVNetworkReply *reply = new KVNetworkReply(r->parent(), r, this);
			return reply;
		}
		else if(op == QNetworkAccessManager::GetOperation)
		{
			qDebug() << "GET" << request.url().path();
		}
	}

	QNetworkReply *reply = QNetworkAccessManager::createRequest(op, request, outgoingData);
	return reply;
}

Use the same User-Agent everywhere, just because


// Tests -fsanitize-coverage=inline-8bit-counters
//
// REQUIRES: has_sancovcc,stable-runtime
// UNSUPPORTED: i386-darwin
//
// RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1

#include <stdio.h>
#include <assert.h>

const char *first_counter;

extern "C"
void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) {
  printf("INIT: %p %p\n", start, end);
  assert(end - start > 1);
  first_counter = start;
}

int main() {
  assert(first_counter);
  assert(*first_counter == 1);
}

// Tests -fsanitize-coverage=inline-8bit-counters
//
// REQUIRES: has_sancovcc,stable-runtime
// UNSUPPORTED: i386-darwin, x86_64-darwin
//
// RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1

#include <stdio.h>
#include <assert.h>

const char *first_counter;

extern "C"
void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) {
  printf("INIT: %p %p\n", start, end);
  assert(end - start > 1);
  first_counter = start;
}

int main() {
  assert(first_counter);
  assert(*first_counter == 1);
}

Mark sancov test as unsupported on Darwin


#include <QTest>
#include "test-suite.h"
#include "custom-network-access-manager.h"
#include <iostream>

int main(int argc, char *argv[])
{
	#ifdef HEADLESS
		QCoreApplication a(argc, argv);
	#else
		QGuiApplication a(argc, argv);
	#endif

	QMap<QString,int> results;
	int failed = 0;

	CustomNetworkAccessManager::TestMode = true;

	for (QObject *suite : TestSuite::suites)
	{
		int result = QTest::qExec(suite);
		results.insert(suite->metaObject()->className(), result);
		if (result != 0)
		{
			failed++;
		}
	}

	for (auto key : results.keys())
	{
		std::cout << '[' << (results.value(key) != 0 ? "FAIL" : "OK") << "] " << key.toStdString() << std::endl;
	}

	return failed;
}

#include <QTest>
#include "test-suite.h"
#include "custom-network-access-manager.h"
#include <iostream>

int main(int argc, char *argv[])
{
	#ifdef HEADLESS
		QCoreApplication a(argc, argv);
	#else
		QGuiApplication a(argc, argv);
	#endif

	QStringList testSuites;
	for (int i = 1; i < argc; ++i)
		testSuites.append(argv[i]);

	QMap<QString,int> results;
	int failed = 0;

	CustomNetworkAccessManager::TestMode = true;

	for (QObject *suite : TestSuite::suites)
	{
		if (!testSuites.isEmpty() && !testSuites.contains(suite->metaObject()->className()))
			continue;

		int result = QTest::qExec(suite);
		results.insert(suite->metaObject()->className(), result);
		if (result != 0)
		{
			failed++;
		}
	}

	for (auto key : results.keys())
	{
		std::cout << '[' << (results.value(key) != 0 ? "FAIL" : "OK") << "] " << key.toStdString() << std::endl;
	}

	return failed;
}

Allow to only run some test suites from the test runner


// 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/ui/webui/options2/chromeos/stats_options_handler.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"

namespace chromeos {

StatsOptionsHandler::StatsOptionsHandler() {
}

// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
}

void StatsOptionsHandler::Initialize() {
}

// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
      base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
                 base::Unretained(this)));
}

void StatsOptionsHandler::HandleMetricsReportingCheckbox(
    const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
  const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
  const bool enabled = (checked_str == "true");
  UserMetrics::RecordAction(
      enabled ?
      UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
      UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}

}  // 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/ui/webui/options2/chromeos/stats_options_handler.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"

using content::UserMetricsAction;

namespace chromeos {

StatsOptionsHandler::StatsOptionsHandler() {
}

// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
}

void StatsOptionsHandler::Initialize() {
}

// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
      base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
                 base::Unretained(this)));
}

void StatsOptionsHandler::HandleMetricsReportingCheckbox(
    const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
  const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
  const bool enabled = (checked_str == "true");
  content::RecordAction(
      enabled ?
      UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
      UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}

}  // namespace chromeos

Fix CrOS Official build from options2 copy.


#include <%QAPP_INCLUDE%>
#include "%INCLUDE%"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    %CLASS% w;
#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
    w.showMaximized();
#else
    w.show();
#endif
    return a.exec();
}

#include <%QAPP_INCLUDE%>
#include "%INCLUDE%"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    %CLASS% w;
#if defined(Q_WS_S60)
    w.showMaximized();
#else
    w.show();
#endif
    return a.exec();
}

Remove special showMaximized case for Maemo 5


#include <string>
#include <ccspec/core/hooks.h>
#include <ccspec/core/example_group.h>

namespace ccspec {
namespace core {

void before(std::string scope, Hook hook) {
    ExampleGroup* parent_group = groups_being_defined.top();
    if (scope == "each" || scope == "example")
        parent_group->addBeforeEachHook(hook);
    else if (scope == "all" || scope == "context")
        parent_group->addBeforeAllHook(hook);
    else
        throw "no such before hook type";
}

void after(std::string scope, Hook hook) {
    ExampleGroup* parent_group = groups_being_defined.top();
    if (scope == "each" || scope == "example")
        parent_group->addAfterEachHook(hook);
    else if (scope == "all" || scope == "context")
        parent_group->addAfterAllHook(hook);
    else
        throw "no such before hook type";
}

} // namespace core
} // namespace ccspec

#include <string>
#include <ccspec/core/hooks.h>
#include <ccspec/core/example_group.h>

namespace ccspec {
namespace core {

void before(std::string scope, Hook hook) {
    ExampleGroup* parent_group = groups_being_defined.top();
    if (scope == "each" || scope == "example")
        parent_group->addBeforeEachHook(hook);
    else if (scope == "all" || scope == "context")
        parent_group->addBeforeAllHook(hook);
    else
        throw "no such before hook type";
}

void after(std::string scope, Hook hook) {
    ExampleGroup* parent_group = groups_being_defined.top();
    if (scope == "each" || scope == "example")
        parent_group->addAfterEachHook(hook);
    else if (scope == "all" || scope == "context")
        parent_group->addAfterAllHook(hook);
    else
        throw "no such after hook type";
}

} // namespace core
} // namespace ccspec

Correct after hook exception 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/ui/views/find_bar_host.h"

#include "base/logging.h"
#include "ui/base/events/event.h"

void FindBarHost::AudibleAlert() {
#if defined(OS_WIN)
  MessageBeep(MB_OK);
#else
  // TODO(mukai):
  NOTIMPLEMENTED();
#endif
}

bool FindBarHost::ShouldForwardKeyEventToWebpageNative(
    const ui::KeyEvent& key_event) {
  return true;
}

// 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/ui/views/find_bar_host.h"

#include "base/logging.h"
#include "ui/base/events/event.h"

void FindBarHost::AudibleAlert() {
#if defined(OS_WIN)
  MessageBeep(MB_OK);
#endif
}

bool FindBarHost::ShouldForwardKeyEventToWebpageNative(
    const ui::KeyEvent& key_event) {
  return true;
}

Remove NOTIMPLEMENTED() in FindBarHost::AudibleAlert() for ChromeOS.


//===--- UnaryStaticAssertCheck.cpp - clang-tidy---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "UnaryStaticAssertCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace modernize {

void UnaryStaticAssertCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus1z)
    return;

  Finder->addMatcher(staticAssertDecl().bind("static_assert"), this);
}

void UnaryStaticAssertCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *MatchedDecl =
      Result.Nodes.getNodeAs<StaticAssertDecl>("static_assert");
  const StringLiteral *AssertMessage = MatchedDecl->getMessage();

  SourceLocation Loc = MatchedDecl->getLocation();

  if (!AssertMessage || AssertMessage->getLength() ||
      AssertMessage->getLocStart().isMacroID() || Loc.isMacroID())
    return;

  diag(Loc,
       "use unary 'static_assert' when the string literal is an empty string")
      << FixItHint::CreateRemoval(AssertMessage->getSourceRange());
}

} // namespace modernize
} // namespace tidy
} // namespace clang

//===--- UnaryStaticAssertCheck.cpp - clang-tidy---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "UnaryStaticAssertCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace modernize {

void UnaryStaticAssertCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus17)
    return;

  Finder->addMatcher(staticAssertDecl().bind("static_assert"), this);
}

void UnaryStaticAssertCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *MatchedDecl =
      Result.Nodes.getNodeAs<StaticAssertDecl>("static_assert");
  const StringLiteral *AssertMessage = MatchedDecl->getMessage();

  SourceLocation Loc = MatchedDecl->getLocation();

  if (!AssertMessage || AssertMessage->getLength() ||
      AssertMessage->getLocStart().isMacroID() || Loc.isMacroID())
    return;

  diag(Loc,
       "use unary 'static_assert' when the string literal is an empty string")
      << FixItHint::CreateRemoval(AssertMessage->getSourceRange());
}

} // namespace modernize
} // namespace tidy
} // namespace clang

Fix build after r319688: s/CPlusPlus1z/CPlusPlus17/


// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <bcm_host.h>
#include "WindowResourceRasp.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    WindowResourceRasp::WindowResourceRasp()
    {
        bcm_host_init();
    }

    WindowResourceRasp::~WindowResourceRasp()
    {
        bcm_host_deinit();
    }

    bool WindowResourceRasp::init(const Size2& newSize,
                                  bool newResizable,
                                  bool newFullscreen,
                                  bool newExclusiveFullscreen,
                                  const std::string& newTitle,
                                  bool newHighDpi,
                                  bool depth)
    {
        if (!WindowResource::init(newSize,
                                  newResizable,
                                  newFullscreen,
                                  newExclusiveFullscreen,
                                  newTitle,
                                  newHighDpi,
                                  depth))
        {
            return false;
        }

        uint32_t screenWidth;
        uint32_t screenHeight;
        int32_t success = graphics_get_display_size(0, &screenWidth, &screenHeight);

        if (success == -1)
        {
            Log(Log::Level::ERR) << "Failed to get display size";
            return false;
        }

        size.width = static_cast<float>(screenWidth);
        size.height = static_cast<float>(screenHeight);
        resolution = size;

        return true;
    }
}

// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <bcm_host.h>
#include "WindowResourceRasp.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    WindowResourceRasp::WindowResourceRasp()
    {
        bcm_host_init();
    }

    WindowResourceRasp::~WindowResourceRasp()
    {
        bcm_host_deinit();
    }

    bool WindowResourceRasp::init(const Size2& newSize,
                                  bool newResizable,
                                  bool newFullscreen,
                                  bool newExclusiveFullscreen,
                                  const std::string& newTitle,
                                  bool newHighDpi,
                                  bool depth)
    {
        if (!WindowResource::init(newSize,
                                  newResizable,
                                  newFullscreen,
                                  newExclusiveFullscreen,
                                  newTitle,
                                  newHighDpi,
                                  depth))
        {
            return false;
        }

        uint32_t screenWidth;
        uint32_t screenHeight;
        int32_t success = graphics_get_display_size(0, &screenWidth, &screenHeight);

        if (success < 0)
        {
            Log(Log::Level::ERR) << "Failed to get display size";
            return false;
        }

        size.width = static_cast<float>(screenWidth);
        size.height = static_cast<float>(screenHeight);
        resolution = size;

        return true;
    }
}

Check if the result of graphics_get_display_size is less than 0


/*************************************************************************
> File Name: ruleOfFive.cpp
> Author: Chan-Ho Chris Ohk
> E-mail: utilForever@gmail.com, utilForever@kaist.ac.kr
> Created Time: 2015/4/26
> Personal Blog: https://github.com/utilForever
************************************************************************/
#include <utility>

class Resource
{
private:
	int x = 0;
};

class RO3
{
private:
	Resource* pResource;
};

class RO5
{
private:
	Resource* pResource;

public:
	RO5()
		: pResource{ new Resource{} }
	{ }

	RO5(const RO5& rhs)
		: pResource{ new Resource(*(rhs.pResource)) }
	{ }

	RO5(RO5&& rhs)
		: pResource{ rhs.pResource }
	{
		rhs.pResource = nullptr;
	}

	RO5& operator=(const RO5& rhs)
	{
		if (&rhs != this)
		{
			delete pResource;
			pResource = nullptr;
			pResource = new Resource(*(rhs.pResource));
		}

		return *this;
	}

	RO5& operator=(RO5&& rhs)
	{
		if (&rhs != this)
		{
			delete pResource;
			pResource = rhs.pResource;
			rhs.pResource = nullptr;
		}

		return *this;
	}

	~RO5()
	{
		delete pResource;
	}
};

Update Rule of Five Example


// Solution to problem from Crack Coding interviews. Implement an
// algorithm to determine if a string has all unique characters
#include "check_unique_char.h"

CheckUniqueChar::CheckUniqueChar() {

}

CheckUniqueChar::~CheckUniqueChar() {

}

// Takes O(n) running time
bool CheckUniqueChar::solver_boolean(std::string test_string) {

}

// Takes O(nlogn) running time
bool CheckUniqueChar::solver_sorted(std::string test_string) {

}

bool CheckUniqueChar:test_case() {

}

Add functions to new problem for CheckUniqueChar


#include <GL/gl.h>
#include <orz/exception.h>
#include "hw3d_opengl_texture.h"

namespace Hw3D
{
	Texture::Lock OpenGlTexture::LockRegion(const Geom::RectInt &region, bool readOnly)
	{
		return Texture::Lock();
	}

	void OpenGlTexture::UnlockRegion()
	{

	}

	OpenGlTexture::OpenGlTexture(Geom::SizeInt dimensions, Format fmt, Pool pool):
		Texture(dimensions, fmt),
		m_textureName(0)
	{
		glGenTextures(1, &m_textureName);
		if(m_textureName == GL_INVALID_VALUE)
		{
			m_textureName = 0;
			DO_THROW(Err::CriticalError, "Failed allocating texture");
		}
	}

	OpenGlTexture::~OpenGlTexture()
	{
		glDeleteTextures(1, &m_textureName);
	}
}

#include <GL/gl.h>
#include <orz/exception.h>
#include "hw3d_opengl_texture.h"
#include "hw3d_opengl_common.h"

namespace Hw3D
{
	Texture::Lock OpenGlTexture::LockRegion(const Geom::RectInt &region, bool readOnly)
	{
		return Texture::Lock();
	}

	void OpenGlTexture::UnlockRegion()
	{

	}

	OpenGlTexture::OpenGlTexture(Geom::SizeInt dimensions, Format fmt, Pool pool):
		Texture(dimensions, fmt),
		m_textureName(0)
	{
		glGenTextures(1, &m_textureName);
		if(m_textureName == GL_INVALID_VALUE)
		{
			m_textureName = 0;
			DO_THROW(Err::CriticalError, "Failed allocating texture");
		}
		glBindTexture(GL_TEXTURE_2D, m_textureName);
		glTexImage2D(
			GL_TEXTURE_2D,
			0,
			GetGlInternalFormat(fmt),
			dimensions.Width,
			dimensions.Height,
			0,
			GetGlFormat(fmt),
			GetGlDataType(fmt),
			nullptr
		);

		GLenum err;

		if((err = glGetError()) != GL_NO_ERROR)
		{
			DO_THROW(Err::CriticalError, "glTexImage2D failed: " + GetGlErrorString(err));
		}
	}

	OpenGlTexture::~OpenGlTexture()
	{
		glDeleteTextures(1, &m_textureName);
	}
}

Create OpenGl texture object when creating OpenGlTexture


#include "CppUTest\CommandLineTestRunner.h"
#include <stdio.h>
#include "mbed.h"
#include "testrunner.h"
#include "test_env.h"

/**
Object 'console' is used to show prints on console.
It is declared in \cpputest\src\Platforms\armcc\UtestPlatform.cpp
*/
Serial console(STDIO_UART_TX, STDIO_UART_RX);

int main(int ac, char** av)
{
    unsigned failureCount = 0;
    {
        // Some compilers may not pass ac, av so we need to supply them ourselves
        int ac = 2;
        char* av[] = {__FILE__, "-v"};
        failureCount = CommandLineTestRunner::RunAllTests(ac, av);
    }

    notify_completion(failureCount == 0);
    return failureCount;
}

#include "CommandLineTestRunner.h"
#include <stdio.h>
#include "mbed.h"
#include "testrunner.h"
#include "test_env.h"

/**
Object 'console' is used to show prints on console.
It is declared in \cpputest\src\Platforms\armcc\UtestPlatform.cpp
*/
Serial console(STDIO_UART_TX, STDIO_UART_RX);

int main(int ac, char** av)
{
    unsigned failureCount = 0;
    {
        // Some compilers may not pass ac, av so we need to supply them ourselves
        int ac = 2;
        char* av[] = {__FILE__, "-v"};
        failureCount = CommandLineTestRunner::RunAllTests(ac, av);
    }

    notify_completion(failureCount == 0);
    return failureCount;
}

Remove an include path with undefined behaviour on non-windows systems


#include <inttypes.h>
#include <stdio.h>

extern "C" bool _TSsop2leFT3lhsNSs5int643rhsS__NSs4bool(int64_t l, int64_t r) {
  return l <= r;
}

extern "C" double _TSsop1sFT1aNSs6double_S_(double x) {
    return -x;
}

extern "C" void _T3fib5printFT1iNSs5int64_T_(int64_t l) {
  printf("%lld\n", l);
}

extern "C" void _T3fib5printFT1iNS_6double_T_(double l) {
  printf("%f\n", l);
}

extern "C" void _T5nbody5printFT1iNSs6double_T_(double l) {
  printf("%f\n", l);
}

extern "C" bool _TSs19convertToLogicValueFT1vNSs4bool_i1(bool b) {
  return b;
}

extern "C"
double
_TNSs6double26convert_from_float_literalFT3valf64_S_(double x)
{
    return x;
}

#include <inttypes.h>
#include <stdio.h>

extern "C" void _T3fib5printFT1iNSs5int64_T_(int64_t l) {
  printf("%lld\n", l);
}

extern "C" void _T3fib5printFT1iNS_6double_T_(double l) {
  printf("%f\n", l);
}

extern "C" void _T5nbody5printFT1iNSs6double_T_(double l) {
  printf("%f\n", l);
}

// This cannot be implemented in swift.swift until we have pattern matching.
extern "C" bool _TSs19convertToLogicValueFT1vNSs4bool_i1(bool b) {
  return b;
}

extern "C"
double
_TNSs6double26convert_from_float_literalFT3valf64_S_(double x)
{
    return x;
}

Implement all the integer comparison operators in swift.swift. Despite the indirection, each of these compiles into nice simple IR at -O3, with: swift swift.swift -I test -emit-llvm | opt -O3 -S | less


#include <QPixmap>

#include "restdialog.h"

RestDialog::RestDialog(QWidget *parent) :
    QDialog(parent)
{
    Qt::WindowFlags flags = windowFlags();
    setWindowFlags((flags & ~Qt::WindowContextHelpButtonHint) |
                   Qt::WindowStaysOnTopHint);
    ui_restDialog = QSharedPointer<Ui::RestDialog>(new Ui::RestDialog());
    ui_restDialog->setupUi(this);

    // set message
    QString message = settings.value("message", QString()).toString();
    ui_restDialog->messageLabel->setText(message);

    // possibly set image
    bool useImage = settings.value("use_img", false).toBool();
    if (useImage)
        setImage();

    activateWindow();
}

void RestDialog::setImage()
{
    QString imagePath = settings.value("img_path", QString()).toString();
    QPixmap image(imagePath);
    if (image.isNull())
        return;
    ui_restDialog->imageLabel->setPixmap(image);
}

bool RestDialog::isPostponed() const
{
    return ui_restDialog->afterCheckBox->isChecked();
}

#include <QPixmap>
#include <QDesktopWidget>

#include "restdialog.h"

RestDialog::RestDialog(QWidget *parent) :
    QDialog(parent)
{
    Qt::WindowFlags flags = windowFlags();
    setWindowFlags((flags & ~Qt::WindowContextHelpButtonHint) |
                   Qt::WindowStaysOnTopHint);
    ui_restDialog = QSharedPointer<Ui::RestDialog>(new Ui::RestDialog());
    ui_restDialog->setupUi(this);

    // set message
    QString message = settings.value("message", QString()).toString();
    ui_restDialog->messageLabel->setText(message);

    // possibly set image
    bool useImage = settings.value("use_img", false).toBool();
    if (useImage)
        setImage();

    activateWindow();
}

void RestDialog::setImage()
{
    QString imagePath = settings.value("img_path", QString()).toString();
    QPixmap image(imagePath);
    if (image.isNull())
        return;

    // check that image is not bigger than screen resolution
    QSize imageSize = image.size();
    int screenWidth = QApplication::desktop()->width();
    int screenHeight = QApplication::desktop()->height();
    if ((imageSize.height() >= screenHeight) ||
            (imageSize.width() >= screenWidth))
    {
        // let's scale it
        image = image.scaled((screenWidth - width() - 50),
                             (screenHeight - height() - 50),
                             Qt::KeepAspectRatio);
    }

    ui_restDialog->imageLabel->setPixmap(image);
}

bool RestDialog::isPostponed() const
{
    return ui_restDialog->afterCheckBox->isChecked();
}

Check that image in message dialog is not bigger than screen


#include "behaviours/audio_voice_fade_behaviour.h"
#include "../audio_voice.h"
#include "audio_facade.h"
#include "halley/utils/utils.h"

using namespace Halley;

AudioVoiceFadeBehaviour::AudioVoiceFadeBehaviour(float fadeTime, float sourceVolume, float targetVolume, bool stopAtEnd)
	: curTime(0)
	, fadeTime(fadeTime)
	, volume0(sourceVolume)
	, volume1(targetVolume)
	, stopAtEnd(stopAtEnd)
{
}

void AudioVoiceFadeBehaviour::onAttach(AudioVoice& audioSource)
{
}

bool AudioVoiceFadeBehaviour::update(float elapsedTime, AudioVoice& audioSource)
{
	curTime += elapsedTime;
	const float t = clamp(curTime / fadeTime, 0.0f, 1.0f);
	const float volume = lerp(volume0, volume1, t);

	audioSource.getDynamicGainRef() *= gainToVolume(volume);

	if (curTime >= fadeTime) {
		if (stopAtEnd) {
			audioSource.stop();
		}
		return false;
	}
	return true;
}

#include "behaviours/audio_voice_fade_behaviour.h"
#include "../audio_voice.h"
#include "audio_facade.h"
#include "halley/utils/utils.h"

using namespace Halley;

AudioVoiceFadeBehaviour::AudioVoiceFadeBehaviour(float fadeTime, float sourceVolume, float targetVolume, bool stopAtEnd)
	: curTime(0)
	, fadeTime(fadeTime)
	, volume0(sourceVolume)
	, volume1(targetVolume)
	, stopAtEnd(stopAtEnd)
{
}

void AudioVoiceFadeBehaviour::onAttach(AudioVoice& audioSource)
{
}

bool AudioVoiceFadeBehaviour::update(float elapsedTime, AudioVoice& audioSource)
{
	curTime += elapsedTime;
	const float t = fadeTime == 0.0f ? 1.0f : clamp(curTime / fadeTime, 0.0f, 1.0f);
	const float volume = lerp(volume0, volume1, t);

	audioSource.setUserGain(audioSource.getDynamicGainRef() * gainToVolume(volume));

	if (curTime >= fadeTime) {
		if (stopAtEnd) {
			audioSource.stop();
		}
		return false;
	}
	return true;
}

Change AudioVoiceFadeBehaviour to use userGain


// RUN: %clangxx -w -fsanitize=bool %s -o %t
// RUN: %run %t 2>&1 | FileCheck %s

#include <iostream>

extern "C" {
void __ubsan_get_current_report_data(const char **OutIssueKind,
                                     const char **OutMessage,
                                     const char **OutFilename,
                                     unsigned *OutLine, unsigned *OutCol,
                                     char **OutMemoryAddr);

// Override the weak definition of __ubsan_on_report from the runtime, just
// for testing purposes.
void __ubsan_on_report(void) {
  const char *IssueKind, *Message, *Filename;
  unsigned Line, Col;
  char *Addr;
  __ubsan_get_current_report_data(&IssueKind, &Message, &Filename, &Line, &Col,
                                  &Addr);

  std::cout << "Issue: " << IssueKind << "\n"
            << "Location: " << Filename << ":" << Line << ":" << Col << "\n"
            << "Message: " << Message << std::endl;

  (void)Addr;
}
}

int main() {
  char C = 3;
  bool B = *(bool *)&C;
  // CHECK: Issue: invalid-bool-load
  // CHECK-NEXT: Location: {{.*}}monitor.cpp:[[@LINE-2]]:12
  // CHECK-NEXT: Message: Load of value 3, which is not a valid value for type 'bool'
  return 0;
}

// RUN: %clangxx -w -fsanitize=bool %s -o %t
// RUN: %run %t 2>&1 | FileCheck %s

// __ubsan_on_report is not defined as weak. Redefining it here isn't supported
// on Windows.
//
// UNSUPPORTED: win32

#include <iostream>

extern "C" {
void __ubsan_get_current_report_data(const char **OutIssueKind,
                                     const char **OutMessage,
                                     const char **OutFilename,
                                     unsigned *OutLine, unsigned *OutCol,
                                     char **OutMemoryAddr);

// Override the definition of __ubsan_on_report from the runtime, just for
// testing purposes.
void __ubsan_on_report(void) {
  const char *IssueKind, *Message, *Filename;
  unsigned Line, Col;
  char *Addr;
  __ubsan_get_current_report_data(&IssueKind, &Message, &Filename, &Line, &Col,
                                  &Addr);

  std::cout << "Issue: " << IssueKind << "\n"
            << "Location: " << Filename << ":" << Line << ":" << Col << "\n"
            << "Message: " << Message << std::endl;

  (void)Addr;
}
}

int main() {
  char C = 3;
  bool B = *(bool *)&C;
  // CHECK: Issue: invalid-bool-load
  // CHECK-NEXT: Location: {{.*}}monitor.cpp:[[@LINE-2]]:12
  // CHECK-NEXT: Message: Load of value 3, which is not a valid value for type 'bool'
  return 0;
}

Mark a test case as unsupported on Windows


// 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/renderer/extensions/api_definitions_natives.h"

#include <algorithm>

#include "chrome/common/extensions/features/base_feature_provider.h"

namespace {
const char kInvalidExtensionNamespace[] = "Invalid extension namespace";
}

namespace extensions {

ApiDefinitionsNatives::ApiDefinitionsNatives(Dispatcher* dispatcher,
                                             ChromeV8Context* context)
    : ChromeV8Extension(dispatcher, context) {
  RouteFunction("GetExtensionAPIDefinitionsForTest",
                base::Bind(
                    &ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest,
                    base::Unretained(this)));
}

void ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  std::vector<std::string> apis;
  FeatureProvider* feature_provider = BaseFeatureProvider::GetByName("api");
  const std::vector<std::string>& feature_names =
      feature_provider->GetAllFeatureNames();
  for (std::vector<std::string>::const_iterator i = feature_names.begin();
       i != feature_names.end(); ++i) {
    if (!feature_provider->GetParent(feature_provider->GetFeature(*i)) &&
        context()->GetAvailability(*i).is_available()) {
      apis.push_back(*i);
    }
  }
  args.GetReturnValue().Set(
    dispatcher()->v8_schema_registry()->GetSchemas(apis));
}

}  // 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/renderer/extensions/api_definitions_natives.h"

#include <algorithm>

#include "chrome/common/extensions/features/base_feature_provider.h"

namespace extensions {

ApiDefinitionsNatives::ApiDefinitionsNatives(Dispatcher* dispatcher,
                                             ChromeV8Context* context)
    : ChromeV8Extension(dispatcher, context) {
  RouteFunction("GetExtensionAPIDefinitionsForTest",
                base::Bind(
                    &ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest,
                    base::Unretained(this)));
}

void ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  std::vector<std::string> apis;
  FeatureProvider* feature_provider = BaseFeatureProvider::GetByName("api");
  const std::vector<std::string>& feature_names =
      feature_provider->GetAllFeatureNames();
  for (std::vector<std::string>::const_iterator i = feature_names.begin();
       i != feature_names.end(); ++i) {
    if (!feature_provider->GetParent(feature_provider->GetFeature(*i)) &&
        context()->GetAvailability(*i).is_available()) {
      apis.push_back(*i);
    }
  }
  args.GetReturnValue().Set(
    dispatcher()->v8_schema_registry()->GetSchemas(apis));
}

}  // namespace extensions

Remove an unused const kInvalidExtensionNamespace.


#include <cstdio>
#include <cstdlib>

#include "util/debug.hpp"

bool nest::mc::util::failed_assertion(const char *assertion, const char *file,
                                      int line, const char *func)
{
    std::fprintf(stderr, "%s:%d %s: Assertion `%s' failed.\n", file, line, func, assertion);
    std::abort();
    return false;
}

#include <cstdlib>
#include <iostream>

#include "util/debug.hpp"

bool nest::mc::util::failed_assertion(const char *assertion, const char *file,
                                      int line, const char *func)
{
    // Explicit flush, as we can't assume default buffering semantics on stderr/cerr,
    // and abort() mignt not flush streams.

    std::cerr << file << ':' << line << " " << func
              << ": Assertion `" << assertion << "' failed." << std::endl;
    std::abort();
    return false;
}

Use cerr in preference to stderr for assertion message.


#include "./Sphere.hpp"
#include "./misc.hpp"
#include <algorithm>
#include <cmath>

namespace yks {

	Optional<float> intersect(const vec3& origin, float radius, const Ray& r) {
		const vec3 o = r.origin - origin;
		const vec3 v = r.direction;

		float t1, t2;
		const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2);

		if (solutions == 0) {
			return Optional<float>();
		} else if (solutions == 1) {
			return make_optional<float>(t1);
		} else {
			return make_optional<float>(std::min(t1, t2));
		}
	}

	vec3 uniform_point_on_sphere(float a, float b) {
		const float y = 2.0f * a - 1.0f;
		const float latitude = std::asin(y);
		const float longitude = b * two_pi;
		const float cos_latitude = std::cos(latitude);

		return mvec3(cos_latitude * cos(longitude), y, cos_latitude * sin(longitude));
	}

}

#include "./Sphere.hpp"
#include "./misc.hpp"
#include <algorithm>
#include <cmath>

namespace yks {

	Optional<float> intersect(const vec3& origin, float radius, const Ray& r) {
		const vec3 o = r.origin - origin;
		const vec3 v = r.direction;

		float t1, t2;
		const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2);

		if (solutions == 0) {
			return Optional<float>();
		} else if (solutions == 1) {
			return make_optional<float>(t1);
		} else {
			return make_optional<float>(std::min(t1, t2));
		}
	}

	vec3 uniform_point_on_sphere(float a, float b) {
		const float y = 2.0f * a - 1.0f;
		const float longitude = b * two_pi;
		const float cos_latitude = std::sqrt(1.0f - sqr(y));

		return mvec3(cos_latitude * std::cos(longitude), y, cos_latitude * std::sin(longitude));
	}

}

Optimize sphere sampling code using trig identity


/*
 * AnimationTask.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <esp_log.h>

#include "nvs_flash.h"
#include "esp_wifi.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"

#include "AnimationTask.h"
#include "sdkconfig.h"

static char tag[] = "AnimationTask";

AnimationTask::AnimationTask(const char* taskName, I2C* i2c)
        : Esp32RtosTask(taskName),
          m_i2c(i2c) {
}

AnimationTask::~AnimationTask() {
}

void AnimationTask::run(void* data) {
    while (1) {
        ESP_LOGW(tag, "AnimationTask::run");
        delay(1000);
    }
}

/*
 * AnimationTask.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <esp_log.h>

#include "nvs_flash.h"
#include "esp_wifi.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"

#include "AnimationTask.h"
#include "sdkconfig.h"

static char tag[] = "AnimationTask";

AnimationTask::AnimationTask(const char* taskName, I2C* i2c)
        : Esp32RtosTask(taskName),
          m_i2c(i2c) {
}

AnimationTask::~AnimationTask() {
}

void AnimationTask::run(void* data) {
    m_i2c->init(I2C_NUM_1, I2C_MODE_MASTER, GPIO_NUM_18, GPIO_NUM_19, GPIO_PULLUP_DISABLE, GPIO_PULLUP_DISABLE, 100000);
    m_i2c->i2c_is31_init(I2C_NUM_1);
    while (1) {
        ESP_LOGW(tag, "AnimationTask::run");
        m_i2c->i2c_is31_pwm(I2C_NUM_1);
        m_i2c->i2c_is31_en(I2C_NUM_1);
        delay(1000);
    }
}

Initialize and enable LEDs in animation to test


/*
 * AnimationTask.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <esp_log.h>

#include "AnimationTask.h"
#include "sdkconfig.h"

static char tag[] = "AnimationTask";

AnimationTask::AnimationTask(std::string taskName) : Task(taskName) {
}

AnimationTask::~AnimationTask() {
}

void AnimationTask::run(void *data) {
    ESP_LOGW(tag, "AnimationTask::run");
}

/*
 * AnimationTask.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <esp_log.h>

#include "AnimationTask.h"
#include "sdkconfig.h"

static char tag[] = "AnimationTask";

AnimationTask::AnimationTask(std::string taskName)
        : Task(taskName) {
}

AnimationTask::~AnimationTask() {
}

void AnimationTask::run(void *data) {
    while (1) {
        ESP_LOGW(tag, "AnimationTask::run");
        delay(1000);
    }
}

Fix animation task, run should not return


#include <boost/test/unit_test.hpp>

#include "../uint256.h"

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

BOOST_AUTO_TEST_SUITE(miner_tests)

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

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

    int i;

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

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

		BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

#include <boost/test/unit_test.hpp>

#include "../uint256.h"

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

BOOST_AUTO_TEST_SUITE(miner_tests)

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

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

    int i;

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

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

    BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

Fix miner_test unit test bug


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

#include "mtac/remove_dead_basic_blocks.hpp"
#include "mtac/Function.hpp"

using namespace eddic;

bool mtac::remove_dead_basic_blocks::operator()(mtac::Function& function){
    unsigned int before = function.bb_count();

    if(before <= 2){
        return false;
    }

    auto it = iterate(function);

    //ENTRY is always accessed
    ++it;

    while(it.has_next()){
        auto& block = *it;

        if(block->predecessors.empty()){
            it.erase();
        } else {
            ++it;
        }
    }

    return function.bb_count() < before;
}

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

#include <unordered_set>

#include "mtac/remove_dead_basic_blocks.hpp"
#include "mtac/Function.hpp"

using namespace eddic;

bool mtac::remove_dead_basic_blocks::operator()(mtac::Function& function){
    bool optimized;
    bool optimized_once = false;

    do {
        optimized = false;

        unsigned int before = function.bb_count();

        if(before <= 2){
            return optimized_once;
        }

        std::unordered_set<basic_block_p> live_basic_blocks;

        for(auto& basic_block : function){
            if(basic_block->index < 0){
                live_basic_blocks.insert(basic_block);
            } else {
                for(auto& predecessor : basic_block->predecessors){
                    if(live_basic_blocks.find(predecessor) != live_basic_blocks.end()){
                        live_basic_blocks.insert(basic_block);
                        break;
                    }
                }
            }
        }

        auto it = iterate(function);

        while(it.has_next()){
            auto& block = *it;

            if(live_basic_blocks.find(block) == live_basic_blocks.end()){
                it.erase();
            } else {
                ++it;
            }
        }

        optimized = function.bb_count() < before;
        if(optimized){
            optimized_once = true;
        }
    } while(optimized);

    return optimized_once;
}

Improve removal of dead basic blocks to remove all dead basic blocks at once


#include "tags/tag-database-factory.h"
#include <QFile>
#include "tags/tag-database-in-memory.h"
#include "tags/tag-database-sqlite.h"

TagDatabase *TagDatabaseFactory::Create(QString directory)
{
	if (!directory.endsWith("/") && !directory.endsWith("\\")) {
		directory += "/";
	}

	const QString typesFile = directory + "tag-types.txt";

	if (QFile::exists(directory + "tags.db")) {
		return new TagDatabaseSqlite(typesFile, directory + "tags.db");
	}

	return new TagDatabaseInMemory(typesFile, directory + "tags.txt");
}

#include "tags/tag-database-factory.h"
#include <QFile>
#include "tags/tag-database-in-memory.h"
#include "tags/tag-database-sqlite.h"

TagDatabase *TagDatabaseFactory::Create(QString directory)
{
	if (!directory.endsWith("/") && !directory.endsWith("\\")) {
		directory += "/";
	}

	const QString typesFile = directory + "tag-types.txt";

	if (QFile::exists(directory + "tags.txt")) {
		return new TagDatabaseInMemory(typesFile, directory + "tags.txt");
	}

	return new TagDatabaseSqlite(typesFile, directory + "tags.db");
}

Switch default tag database from TXT to SQLite


// FIXME: The standalone module still seems to cause clang to want to test for
// the existence of a 'foo' directory:
// RUN: mkdir %t
// RUN: cp %s %t
// RUN: mkdir %t/foo
// RUN: cd %t
// RUN: not %clang_cc1 -fmodules -fsyntax-only %s 2>&1 | FileCheck %s

// CHECK: error: no matching function for call to 'foo'
// CHECK: note: candidate function not viable: requires 0 arguments, but 1 was provided

// FIXME: This should use -verify, but it seems it doesn't hook up the
// SourceManager correctly or something, and the foo.h note gets attributed to
// the synthetic module translation unit "foo.map Line 2:...".
// %clang_cc1 -fmodules -verify %s

#pragma clang module build foo
module foo {
  umbrella "foo"
  module * {
    export *
  }
}
#pragma clang module contents
#pragma clang module begin foo.foo
# 1 "foo.h" 1
#ifndef FOO_FOO_H
void foo();
#endif
#pragma clang module end
#pragma clang module endbuild
#pragma clang module import foo.foo
// expected-note@foo.h:2 {{candidate function not viable: requires 0 arguments, but 1 was provided}}
int main() {
  foo(1); // expected-error {{no matching function for call to 'foo'}}
}

// FIXME: The standalone module still seems to cause clang to want to test for
// the existence of a 'foo' directory:
// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: cp %s %t
// RUN: rm -rf %t/foo
// RUN: mkdir %t/foo
// RUN: cd %t
// RUN: not %clang_cc1 -fmodules -fsyntax-only %s 2>&1 | FileCheck %s

// CHECK: error: no matching function for call to 'foo'
// CHECK: note: candidate function not viable: requires 0 arguments, but 1 was provided

// FIXME: This should use -verify, but it seems it doesn't hook up the
// SourceManager correctly or something, and the foo.h note gets attributed to
// the synthetic module translation unit "foo.map Line 2:...".
// %clang_cc1 -fmodules -verify %s

#pragma clang module build foo
module foo {
  umbrella "foo"
  module * {
    export *
  }
}
#pragma clang module contents
#pragma clang module begin foo.foo
# 1 "foo.h" 1
#ifndef FOO_FOO_H
void foo();
#endif
#pragma clang module end
#pragma clang module endbuild
#pragma clang module import foo.foo
// expected-note@foo.h:2 {{candidate function not viable: requires 0 arguments, but 1 was provided}}
int main() {
  foo(1); // expected-error {{no matching function for call to 'foo'}}
}

Fix buildbot break after r360195


#include <vector>
#include <boost/any.hpp>
#include <v8.h>

#include "JSFunctionInvokable.hpp"
#include "../JSObjectScript.hpp"
#include "JSInvokableUtil.hpp"

namespace Sirikata
{
namespace JS
{

  boost::any JSFunctionInvokable::invoke(std::vector<boost::any>& params)
  {
    /* Invoke the function handle */

    int argc =
#ifdef _WIN32
               1
#else
               0
#endif
               ;
    int base_offset = argc; // need to work around windows weirdness
   argc += params.size();

   v8::HandleScope handle_scope;
   v8::Context::Scope  context_scope(script_->context());

   std::vector<v8::Handle<v8::Value> >argv(argc);

   if (base_offset) argv[0] = v8::Handle<v8::Value>();

   for(uint32 i = 0; i < params.size(); i++)
       argv[base_offset+i] = InvokableUtil::AnyToV8(script_, params[i]);

  //TryCatch try_catch;

   // We are currently executing in the global context of the entity
   // FIXME: need to take care fo the "this" pointer
   v8::Handle<v8::Value> result = script_->invokeCallback(function_, argc, &argv[0]);

   if(result.IsEmpty())
   {
     /*
     v8::String::Utf8Value error(try_catch.Exception());
     const char* cMsg = ToCString(error);
     std::cerr << cMsg << "\n";
     */
   }

   return boost::any(result) ;

  }
}
}

#include <vector>
#include <boost/any.hpp>
#include <v8.h>

#include "JSFunctionInvokable.hpp"
#include "../JSObjectScript.hpp"
#include "JSInvokableUtil.hpp"

namespace Sirikata
{
namespace JS
{

  boost::any JSFunctionInvokable::invoke(std::vector<boost::any>& params)
  {
    /* Invoke the function handle */

    int argc = params.size();

   v8::HandleScope handle_scope;
   v8::Context::Scope  context_scope(script_->context());

   std::vector<v8::Handle<v8::Value> >argv(argc);

   for(uint32 i = 0; i < params.size(); i++)
       argv[i] = InvokableUtil::AnyToV8(script_, params[i]);

  //TryCatch try_catch;

   // We are currently executing in the global context of the entity
   // FIXME: need to take care fo the "this" pointer
   v8::Handle<v8::Value> result = script_->invokeCallback(function_, argc, &argv[0]);

   if(result.IsEmpty())
   {
     /*
     v8::String::Utf8Value error(try_catch.Exception());
     const char* cMsg = ToCString(error);
     std::cerr << cMsg << "\n";
     */
   }

   return boost::any(result) ;

  }
}
}

Remove old windows workaround for V8 function invokations.


#include "TestUpdaterOptions.h"

#include "TestUtils.h"
#include "UpdaterOptions.h"

void TestUpdaterOptions::testOldFormatArgs()
{
	const int argc = 6;
	char* argv[argc];
	argv[0] = "updater";
	argv[1] = "CurrentDir=/path/to/app";
	argv[2] = "TempDir=/tmp/updater";
	argv[3] = "UpdateScriptFileName=/tmp/updater/file_list.xml";
	argv[4] = "AppFileName=/path/to/app/theapp";
	argv[5] = "PID=123456";

	UpdaterOptions options;
	options.parse(argc,argv);

	TEST_COMPARE(options.mode,UpdateInstaller::Setup);
	TEST_COMPARE(options.installDir,"/path/to/app");
	TEST_COMPARE(options.packageDir,"/tmp/updater");
	TEST_COMPARE(options.scriptPath,"/tmp/updater/file_list.xml");
	TEST_COMPARE(options.waitPid,123456);
}

int main(int,char**)
{
	TestList<TestUpdaterOptions> tests;
	tests.addTest(&TestUpdaterOptions::testOldFormatArgs);
	return TestUtils::runTest(tests);
}

#include "TestUpdaterOptions.h"

#include "TestUtils.h"
#include "UpdaterOptions.h"

void TestUpdaterOptions::testOldFormatArgs()
{
	const int argc = 6;
	char* argv[argc];
	argv[0] = strdup("updater");
	argv[1] = strdup("CurrentDir=/path/to/app");
	argv[2] = strdup("TempDir=/tmp/updater");
	argv[3] = strdup("UpdateScriptFileName=/tmp/updater/file_list.xml");
	argv[4] = strdup("AppFileName=/path/to/app/theapp");
	argv[5] = strdup("PID=123456");

	UpdaterOptions options;
	options.parse(argc,argv);

	TEST_COMPARE(options.mode,UpdateInstaller::Setup);
	TEST_COMPARE(options.installDir,"/path/to/app");
	TEST_COMPARE(options.packageDir,"/tmp/updater");
	TEST_COMPARE(options.scriptPath,"/tmp/updater/file_list.xml");
	TEST_COMPARE(options.waitPid,123456);

	for (int i=0; i < argc; i++)
	{
		free(argv[i]);
	}
}

int main(int,char**)
{
	TestList<TestUpdaterOptions> tests;
	tests.addTest(&TestUpdaterOptions::testOldFormatArgs);
	return TestUtils::runTest(tests);
}

Fix warnings about conversion from string literal to char*


#include "Item.h"

using namespace node;
using namespace v8;

namespace node_iTunes {

// Convenience function that takes an iTunesItem instance (or any subclass)
// and wraps it up into the proper JS class type, and returns it.
// TODO: Implement some kind of Object Cache, so if the same instance is
//       attempting to be wrapped again, then the same JS Object is returned.
v8::Handle<Value> Item::WrapInstance(iTunesItem* item) {
  HandleScope scope;

  //NSLog(@"%@", [item persistentID]);
  if (item == nil) {
    return scope.Close(Null());
  }

  NSString* className = NSStringFromClass([item class]);
  //NSLog(@"Class: %@", className);
  Local<Object> jsItem;
  if ([className isEqualToString:@"ITunesURLTrack" ]) {
    jsItem = url_track_constructor_template->GetFunction()->NewInstance();
  } else if ([className isEqualToString:@"ITunesFileTrack" ]) {
    jsItem = file_track_constructor_template->GetFunction()->NewInstance();
  } else if ([className isEqualToString:@"ITunesTrack" ]) {
    jsItem = track_constructor_template->GetFunction()->NewInstance();
  } else {
    jsItem = item_constructor_template->GetFunction()->NewInstance();
  }
  Item* itemWrap = ObjectWrap::Unwrap<Item>(jsItem);
  itemWrap->itemRef = item;
  return scope.Close(jsItem);
}

}

#include "Item.h"

using namespace node;
using namespace v8;

namespace node_iTunes {

// Convenience function that takes an iTunesItem instance (or any subclass)
// and wraps it up into the proper JS class type, and returns it.
// TODO: Implement some kind of Object Cache, so if the same instance is
//       attempting to be wrapped again, then the same JS Object is returned.
v8::Handle<Value> Item::WrapInstance(iTunesItem* item) {
  HandleScope scope;

  //NSLog(@"%@", [item persistentID]);
  if (item == nil) {
    return scope.Close(Null());
  }

  NSString* className = NSStringFromClass([item class]);
  //NSLog(@"Class: %@", className);
  Local<Object> jsItem;
  if ([className isEqualToString:@"ITunesURLTrack" ]) {
    jsItem = url_track_constructor_template->GetFunction()->NewInstance();
  } else if ([className isEqualToString:@"ITunesFileTrack" ]) {
    jsItem = file_track_constructor_template->GetFunction()->NewInstance();
  } else if ([className isEqualToString:@"ITunesTrack" ]) {
    jsItem = track_constructor_template->GetFunction()->NewInstance();
  } else if ([className isEqualToString:@"ITunesSource" ]) {
    jsItem = source_constructor_template->GetFunction()->NewInstance();
  } else {
    jsItem = item_constructor_template->GetFunction()->NewInstance();
  }
  Item* itemWrap = ObjectWrap::Unwrap<Item>(jsItem);
  itemWrap->itemRef = item;
  return scope.Close(jsItem);
}

}

Add support for 'Source' in Item::WrapInstance.


#include <cstdio>
#include <cstdint>
#include <string>
#include <memory>
#include <list>

#include "boost/format.hpp"

#include "packet.h"
#include "exceptions.h"
#include "parser.h"

namespace parse4880 {

PGPPacket::PGPPacket(std::string contents) : contents_(contents) {
}

std::shared_ptr<PGPPacket> PGPPacket::ParsePacket(uint8_t tag,
                                                  std::string packet) {
  switch (tag) {
    case 2:
      return std::shared_ptr<PGPPacket>(new SignaturePacket(packet));
      break;
    case 6:
      return std::shared_ptr<PGPPacket>(new PublicKeyPacket(packet));
      break;
    case 13:
      return std::shared_ptr<PGPPacket>(new UserIDPacket(packet));
      break;
    case 14:
      return std::shared_ptr<PGPPacket>(new PublicSubkeyPacket(packet));
      break;

    default:
      return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
  }
}

const std::list<std::shared_ptr<PGPPacket>>& PGPPacket::subpackets() const {
  return subpackets_;
}

const std::string& PGPPacket::contents() const {
  return contents_;
}

}

#include <cstdio>
#include <cstdint>
#include <string>
#include <memory>
#include <list>

#include "boost/format.hpp"

#include "packet.h"
#include "exceptions.h"
#include "parser.h"

namespace parse4880 {

PGPPacket::PGPPacket(std::string contents) : contents_(contents) {
}

std::shared_ptr<PGPPacket> PGPPacket::ParsePacket(uint8_t tag,
                                                  std::string packet) {
  try {
    switch (tag) {
      case 2:
        return std::shared_ptr<PGPPacket>(new SignaturePacket(packet));
        break;
      case 6:
        return std::shared_ptr<PGPPacket>(new PublicKeyPacket(packet));
        break;
      case 13:
        return std::shared_ptr<PGPPacket>(new UserIDPacket(packet));
        break;
      case 14:
        return std::shared_ptr<PGPPacket>(new PublicSubkeyPacket(packet));
        break;
      default:
        return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
    }
  } catch (unsupported_feature_error e) {
    return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
  }
}

const std::list<std::shared_ptr<PGPPacket>>& PGPPacket::subpackets() const {
  return subpackets_;
}

const std::string& PGPPacket::contents() const {
  return contents_;
}

}

Create UnknownPGPPackets in case of unsupported feature.


/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/core/platform/rocm_rocdl_path.h"

#include <stdlib.h>

#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/rocm/rocm_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

string ROCmRoot() {
  VLOG(3) << "ROCM root = " << TF_ROCM_TOOLKIT_PATH;
  return TF_ROCM_TOOLKIT_PATH;
}

}  // namespace tensorflow

/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/core/platform/rocm_rocdl_path.h"

#include <stdlib.h>

#if !defined(PLATFORM_GOOGLE) && TENSORFLOW_USE_ROCM
#include "third_party/gpus/rocm/rocm_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

string ROCmRoot() {
#if TENSORFLOW_USE_ROCM
  VLOG(3) << "ROCM root = " << TF_ROCM_TOOLKIT_PATH;
  return TF_ROCM_TOOLKIT_PATH;
#else
  return "";
#endif
}

}  // namespace tensorflow

Address potential issues encountered in non-ROCm systems.


#include "xchainer/python/error.h"

#include "xchainer/error.h"

#include "xchainer/python/common.h"

namespace xchainer {

namespace py = pybind11;  // standard convention

void InitXchainerError(pybind11::module& m) {
    py::register_exception<XchainerError>(m, "XchainerError");
    py::register_exception<DeviceError>(m, "DeviceError");
    py::register_exception<DtypeError>(m, "DtypeError");
    py::register_exception<DimensionError>(m, "DimensionError");
}

}  // namespace xchainer

#include "xchainer/python/error.h"

#include "xchainer/error.h"

#include "xchainer/python/common.h"

namespace xchainer {

namespace py = pybind11;  // standard convention

void InitXchainerError(pybind11::module& m) {
    py::register_exception<XchainerError>(m, "XchainerError");
    py::register_exception<BackendError>(m, "BackendError");
    py::register_exception<DeviceError>(m, "DeviceError");
    py::register_exception<DtypeError>(m, "DtypeError");
    py::register_exception<DimensionError>(m, "DimensionError");
}

}  // namespace xchainer

Add python binding to BackendError


#include "../include/graph/dijkstra.cpp"
#include "../include/graph/weighted_graph.cpp"
#include "../include/others/fast_cin.cpp"
#include "../include/others/fast_cout.cpp"

using Graph = WeightedGraph<long long>;

int main() {
  int n, m, s, t;
  fcin >> n >> m >> s >> t;
  Graph rg(n);
  for (int i = 0; i < m; ++i) {
    int a, b;
    long long c;
    fcin >> a >> b >> c;
    add_edge(rg, b, a, c);
  }
  std::vector<int> prev;
  auto d = dijkstra(rg, t, prev);

  if (d[s] == inf<long long>()) {
    fcout << -1 << fendl;
    return 0;
  }
  if (d[s] == 0) {
    // Hack for multiple solutions.
    fcout << 0 << " " << 1 << fendl;
    fcout << s << " " << t << fendl;
    return 0;
  }

  std::vector<int> trace;
  trace.reserve(m);
  trace.push_back(s);
  while (trace.back() != t) {
    int v = trace.back();
    trace.push_back(prev[v]);
  }
  int size = trace.size() - 1;
  fcout << d[s] << " " << size << fendl;
  for (int i = 0; i < size; ++i) {
    fcout << trace[i] << " " << trace[i + 1] << fendl;
  }
  return 0;
}

#include "../include/graph/dijkstra.cpp"
#include "../include/graph/weighted_graph.cpp"
#include "../include/others/fast_cin.cpp"
#include "../include/others/fast_cout.cpp"

using Graph = WeightedGraph<long long>;

int main() {
  int n, m, s, t;
  fcin >> n >> m >> s >> t;
  Graph rg(n);
  for (int i = 0; i < m; ++i) {
    int a, b;
    long long c;
    fcin >> a >> b >> c;
    add_edge(rg, b, a, c);
  }
  std::vector<int> prev;
  auto d = dijkstra(rg, t, prev);

  if (d[s] == inf<long long>()) {
    fcout << -1 << fendl;
    return 0;
  }

  std::vector<int> trace;
  trace.reserve(m);
  trace.push_back(s);
  while (trace.back() != t) {
    int v = trace.back();
    trace.push_back(prev[v]);
  }
  int size = trace.size() - 1;
  fcout << d[s] << " " << size << fendl;
  for (int i = 0; i < size; ++i) {
    fcout << trace[i] << " " << trace[i + 1] << fendl;
  }
  return 0;
}

Remove needless hack for the newest oj version


#include <catch.hpp>
#include <string>
#include "test_data.hpp"
#include "libslic3r.h"

using namespace Slic3r::Test;
using namespace std::literals;

SCENARIO("PrintObject: object layer heights") {
    GIVEN("20mm cube and config that has a 3mm nozzle and a 2mm requested layer height") {
        auto config {Slic3r::Config::new_from_defaults()};
        TestMesh m { TestMesh::cube_20x20x20 };
        Slic3r::Model model;
        auto event_counter {0U};
        std::string stage;
        int value {0};
        config->set("fill_density", 0);
        config->set("nozzle_diameter", "3");
        config->set("layer_height", 2.0);
        config->set("first_layer_height", 2.0);

        WHEN("generate_object_layers() is called with a starting layer of 2mm") {
            auto print {Slic3r::Test::init_print({m}, model, config)};
            const auto& object = *(print->objects.at(0));
            auto result {print->objects[0]->generate_object_layers(2.0)};
            THEN("The output vector has 10 entries") {
                REQUIRE(result.size() == 10);
            }
            AND_THEN("Each layer is approximately 2mm above the previous Z") {
                coordf_t last = 0.0;
                for (size_t i = 0; i < result.size(); i++) {
                    REQUIRE((result[i] - last) == Approx(2.0));
                    last = result[i];
                }
            }
        }
    }
}

#include <catch.hpp>
#include <string>
#include "test_data.hpp"
#include "libslic3r.h"

using namespace Slic3r::Test;
using namespace std::literals;

SCENARIO("PrintObject: object layer heights") {
    GIVEN("20mm cube and config that has a 3mm nozzle and a 2mm requested layer height") {
        auto config {Slic3r::Config::new_from_defaults()};
        TestMesh m { TestMesh::cube_20x20x20 };
        Slic3r::Model model;
        config->set("nozzle_diameter", "3");
        config->set("layer_height", 2.0);
        config->set("first_layer_height", 2.0);

        WHEN("generate_object_layers() is called with a starting layer of 2mm") {
            auto print {Slic3r::Test::init_print({m}, model, config)};
            auto result {print->objects[0]->generate_object_layers(2.0)};
            THEN("The output vector has 10 entries") {
                REQUIRE(result.size() == 10);
            }
            AND_THEN("Each layer is approximately 2mm above the previous Z") {
                coordf_t last = 0.0;
                for (size_t i = 0; i < result.size(); i++) {
                    REQUIRE((result[i] - last) == Approx(2.0));
                    last = result[i];
                }
            }
        }
    }
}

Remove some dead code in the printgcode test.


#include "log.h"
#include "ethernetutil.h"

void initializeEthernet(EthernetDevice* device, Server* server,
        uint8_t MACAddr[], uint8_t IPAddr[])
{
    debug("initializing Ethernet...");
    device->ptrServer = server;
    Ethernet.begin(MACAddr, IPAddr);
    device->ptrServer->begin();
}

// The message bytes are sequentially popped from the
// send queue to the send buffer. After the buffer is full
// or the queue is emtpy, the contents of the buffer are
// sent over the ethernet to listening clients.
void processEthernetSendQueue(EthernetDevice* device)
{
    unsigned int byteCount = 0;
    char sendBuffer[MAX_MESSAGE_SIZE];
    while(!QUEUE_EMPTY(uint8_t, &device->sendQueue) &&
            byteCount < MAX_MESSAGE_SIZE) {
        sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue);
    }

    device->ptrServer->write((uint8_t*) sendBuffer, byteCount);
}

Move braces up onto same line as conditional.


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

#include "SkFontHost.h"
#include "SkTypeface.h"
#include "SkTypeface_win.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

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

#include "SkFontHost.h"
#include "SkTypeface.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

Remove unneeded include which is breaking build.


//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Bastian Holst <bastianholst@gmx.de>
//

#include "KmlRegionTagHandler.h"

#include "MarbleDebug.h"

#include "KmlElementDictionary.h"
#include "GeoDataFeature.h"
#include "GeoParser.h"
#include "GeoDataRegion.h"

namespace Marble
{
namespace kml
{
KML_DEFINE_TAG_HANDLER( Region )

GeoNode* KmlRegionTagHandler::parse( GeoParser& parser ) const
{
    Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_Region ) );

    GeoDataRegion region;

    GeoStackItem parentItem = parser.parentElement();
#ifdef DEBUG_TAGS
    mDebug() << "Parsed <" << kmlTag_Region << ">"
             << " parent item name: " << parentItem.qualifiedName().first;
#endif

    if( parentItem.represents( kmlTag_Region ) || parentItem.represents( kmlTag_Region ) ) {
        parentItem.nodeAs<GeoDataFeature>()->setRegion( region );
        return &parentItem.nodeAs<GeoDataFeature>()->region();
    } else {
        return 0;
    }
}

}
}

//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Bastian Holst <bastianholst@gmx.de>
//

#include "KmlRegionTagHandler.h"

#include "MarbleDebug.h"

#include "KmlElementDictionary.h"
#include "GeoDataFeature.h"
#include "GeoParser.h"
#include "GeoDataRegion.h"

namespace Marble
{
namespace kml
{
KML_DEFINE_TAG_HANDLER( Region )

GeoNode* KmlRegionTagHandler::parse( GeoParser& parser ) const
{
    Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_Region ) );

    GeoDataRegion region;

    GeoStackItem parentItem = parser.parentElement();
#ifdef DEBUG_TAGS
    mDebug() << "Parsed <" << kmlTag_Region << ">"
             << " parent item name: " << parentItem.qualifiedName().first;
#endif

    if( parentItem.is<GeoDataFeature>() ) {
        parentItem.nodeAs<GeoDataFeature>()->setRegion( region );
        return &parentItem.nodeAs<GeoDataFeature>()->region();
    } else {
        return 0;
    }
}

}
}

Fix logic error in kml region parsing (region never attached to doc).


// Copyright (c) 2019 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 <core_io.h>
#include <primitives/transaction.h>
#include <test/fuzz/fuzz.h>
#include <util/strencodings.h>

#include <cassert>
#include <cstdint>
#include <string>
#include <vector>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string tx_hex = HexStr(buffer);
    CMutableTransaction mtx;
    const bool result_none = DecodeHexTx(mtx, tx_hex, false, false);
    const bool result_try_witness = DecodeHexTx(mtx, tx_hex, false, true);
    const bool result_try_witness_and_maybe_no_witness = DecodeHexTx(mtx, tx_hex, true, true);
    const bool result_try_no_witness = DecodeHexTx(mtx, tx_hex, true, false);
    assert(!result_none);
    if (result_try_witness_and_maybe_no_witness) {
        assert(result_try_no_witness || result_try_witness);
    }
    // if (result_try_no_witness) { // Uncomment when https://github.com/bitcoin/bitcoin/pull/17775 is merged
    if (result_try_witness) { // Remove stop-gap when https://github.com/bitcoin/bitcoin/pull/17775 is merged
        assert(result_try_witness_and_maybe_no_witness);
    }
}

// Copyright (c) 2019 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 <core_io.h>
#include <primitives/transaction.h>
#include <test/fuzz/fuzz.h>
#include <util/strencodings.h>

#include <cassert>
#include <cstdint>
#include <string>
#include <vector>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string tx_hex = HexStr(buffer);
    CMutableTransaction mtx;
    const bool result_none = DecodeHexTx(mtx, tx_hex, false, false);
    const bool result_try_witness = DecodeHexTx(mtx, tx_hex, false, true);
    const bool result_try_witness_and_maybe_no_witness = DecodeHexTx(mtx, tx_hex, true, true);
    const bool result_try_no_witness = DecodeHexTx(mtx, tx_hex, true, false);
    assert(!result_none);
    if (result_try_witness_and_maybe_no_witness) {
        assert(result_try_no_witness || result_try_witness);
    }
    if (result_try_no_witness) {
        assert(result_try_witness_and_maybe_no_witness);
    }
}

Fix DecodeHexTx fuzzing harness issue


#include "mem/st/visitor/DepBuilder.hpp"

namespace mem { namespace st { namespace visitor {

DepBuilder::DepBuilder ()
{
   _name = "st.DepBuilder";
}

bool
DepBuilder::visit (st::Symbol* sym)
{
   printf("Visit...\n");
   if (sym->isClassSymbol())
   {
      visitClass(static_cast<st::Class*>(sym));
   }
   return true;
}

void
DepBuilder::visitClass (st::Class* cls_sym)
{
   printf("Visiting CLS !\n");
   _dep_tree.addDependency(NULL, cls_sym);
}

} } }

#include "mem/st/visitor/DepBuilder.hpp"

namespace mem { namespace st { namespace visitor {

DepBuilder::DepBuilder ()
{
   _name = "st.DepBuilder";
}

bool
DepBuilder::visit (st::Symbol* sym)
{
   if (sym->isClassSymbol())
   {
      visitClass(static_cast<st::Class*>(sym));
   }
   return true;
}

void
DepBuilder::visitClass (st::Class* cls_sym)
{
   _dep_tree.addDependency(NULL, cls_sym);
}

} } }

Add support for basic ops in LLVM


#include <MetaEvent.h>
#include <MetaFactory.h>
#include <ratio>

namespace test {

namespace metaEventSuite {

using namespace id::attribute;
using namespace std;

	class MetaEventSuite : public ::testing::Test {
		public:
			ID posID = Position::value();
			MetaFactory& f=MetaFactory::instance();
			MetaEvent e;
			MetaEventSuite(){
				MetaAttribute position = posID;
				position.value() = f.create({{0,1}, {1,1}, {2,1}});
				position.unit()  = Meter();
				position.scale() = ratio<1, 1000>();
        e.add(position);
			}
	};

	TEST_F(MetaEventSuite, findAttributeTest) {
		MetaAttribute test = posID;
		test.value() = f.create({{0,1}, {1,1}, {2,1}});
		test.unit()  = Meter();
		test.scale() = ratio<1, 1000>();
    const MetaAttribute* posPtr = e.attribute(posID);
    ASSERT_NE(posPtr, nullptr) << "Position attribute could not be retrieved";
    const MetaAttribute& pos = *posPtr;
		EXPECT_EQ(pos, test) << "Position attribute not stored correctly";
	}
}}

#include <MetaEvent.h>
#include <MetaFactory.h>
#include <ratio>

namespace test {

namespace metaEventSuite {

using namespace id::attribute;
using namespace std;

	class MetaEventSuite : public ::testing::Test {
		public:
			ID posID = Position::value();
			MetaFactory& f=MetaFactory::instance();
			MetaEvent e;
			MetaEventSuite(){
				MetaAttribute position = posID;
				position.value() = f.create({{{0,1}, {1,1}, {2,1}}});
				position.unit()  = Meter();
				position.scale() = ratio<1, 1000>();
        e.add(position);
			}
	};

	TEST_F(MetaEventSuite, findAttributeTest) {
		MetaAttribute test = posID;
		test.value() = f.create({{0, 1, 2}});
		test.unit()  = Meter();
		test.scale() = ratio<1, 1000>();
    const MetaAttribute* posPtr = e.attribute(posID);
    ASSERT_NE(posPtr, nullptr) << "Position attribute could not be retrieved";
    const MetaAttribute& pos = *posPtr;
		EXPECT_EQ(pos, test) << "Position attribute not stored correctly";
	}

	TEST_F(MetaEventSuite, typeTest) {
		EventType eT;
		eT.add(AttributeType(posID, ValueType(id::type::Double::value(), 1, 3, true), ratio<1,1000>(), Meter()));
		EXPECT_EQ((EventType)e, eT) << "Inferred MetaEvent-Type is wrong";
	}
}}

Add MetaEvent EventType cast test


// RUN: %clang_cc1 %s -ast-print -fms-extensions | FileCheck %s

// FIXME: align attribute print

// CHECK: int x __attribute__((aligned(4, 0)));
int x __attribute__((aligned(4)));

// FIXME: Print this at a valid location for a __declspec attr.
// CHECK: int y __declspec(align(4, 1));
__declspec(align(4)) int y;

// CHECK: void foo() __attribute__((const));
void foo() __attribute__((const));

// CHECK: void bar() __attribute__((__const));
void bar() __attribute__((__const));

// FIXME: Print this with correct format and order.
// CHECK: void foo1() __attribute__((pure)) __attribute__((noinline));
void foo1() __attribute__((noinline, pure));

Add a test case for attribute print.


// This file is part of nbind, copyright (C) 2014-2015 BusFaster Ltd.
// Released under the MIT license, see LICENSE.

#include <cstdio>

#include "nbind/api.h"
#include "Coord.h"

class Nullable {

public:

	static Coord *getCoord() {
		return(new Coord(60, 25));
	}

	static Coord *getNull() {
		return(nullptr);
	}

	static void foo(Coord *coord) {
		printf("%p\n", coord);
	}

	static void bar(Coord *coord) {
		printf("%p\n", coord);
	}

};

#include "nbind/nbind.h"

#ifdef NBIND_CLASS

NBIND_CLASS(Coord) {}

NBIND_CLASS(Nullable) {
	method(getCoord);
	method(getNull);
	method(foo);
	method(bar, "bar", nbind::Nullable());
}

#endif

// This file is part of nbind, copyright (C) 2014-2015 BusFaster Ltd.
// Released under the MIT license, see LICENSE.

#include <cstdio>

#include "nbind/api.h"
#include "Coord.h"

class Nullable {

public:

	static Coord *getCoord() {
		return(new Coord(60, 25));
	}

	static Coord *getNull() {
		return(nullptr);
	}

	static void foo(Coord *coord) {
		printf("%p\n", coord);
	}

	static void bar(Coord *coord) {
		printf("%p\n", coord);
	}

};

#include "nbind/nbind.h"

#ifdef NBIND_CLASS

NBIND_CLASS(Nullable) {
	method(getCoord);
	method(getNull);
	method(foo);
	method(bar, "bar", nbind::Nullable());
}

#endif

Remove duplicate class from testbench. Otherwise wrong constructor gets run on OS X without any flaw in nbind itself.


#include "mdist.hpp"
#include "../search/idastar.hpp"
#include "../search/astar.hpp"
#include "../incl/utils.hpp"
#include <cstdio>

static void search(TilesMdist &, Search<TilesMdist> &, TilesMdist::State &);

int main(int argc, char *argv[]) {
	TilesMdist d(stdin);
//	Idastar<TilesMdist, true, true> srch;
	Astar<TilesMdist, true> srch;
	TilesMdist::State s0 = d.initstate();
	search(d, srch, s0);
	return 0;
}

static void search(TilesMdist &d, Search<TilesMdist> &srch, TilesMdist::State &s0) {
	dfheader(stdout);
	dfpair(stdout, "initial heuristic", "%d", d.h(s0));
	Result<TilesMdist> res = srch.search(d, s0);
	res.output(stdout);
	dffooter(stdout);
}

#include "mdist.hpp"
#include "../search/idastar.hpp"
#include "../search/astar.hpp"
#include "../incl/utils.hpp"
#include <cstdio>

static void search(TilesMdist&, Search<TilesMdist>&, TilesMdist::State&);
static Search<TilesMdist> *getsearch(int, char *[]);

int main(int argc, char *argv[]) {
	TilesMdist d(stdin);
	Search<TilesMdist> *srch = getsearch(argc, argv);
	TilesMdist::State s0 = d.initstate();
	search(d, *srch, s0);
	delete srch;
	return 0;
}

static void search(TilesMdist &d, Search<TilesMdist> &srch, TilesMdist::State &s0) {
	dfheader(stdout);
	dfpair(stdout, "initial heuristic", "%d", d.h(s0));
	Result<TilesMdist> res = srch.search(d, s0);
	res.output(stdout);
	dffooter(stdout);
}

static Search<TilesMdist> *getsearch(int argc, char *argv[]) {
	Search<TilesMdist> *srch = NULL;

	if (argc > 1 && strcmp(argv[1], "idastar") == 0)
		srch = new Idastar<TilesMdist, true, true>();
	else
		srch = new Astar<TilesMdist, true>();

	return srch;
}

Switch search algorithms via command-line arguments.