/*
 * RandomConn.cpp
 *
 *  Created on: Apr 27, 2009
 *      Author: rasmussn
 */

#include "RandomConn.hpp"
#include <assert.h>
#include <string.h>

namespace PV {

RandomConn::RandomConn(const char * name,
      HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel)
{
   this->connId = hc->numberOfConnections();
   this->name   = strdup(name);
   this->parent = hc;

   this->numBundles = 1;

   initialize(NULL, pre, post, channel);

   hc->addConnection(this);
}

int RandomConn::initializeWeights(const char * filename)
{
   assert(filename == NULL);
   return initializeRandomWeights(0);
}

}

/*
 * RandomConn.cpp
 *
 *  Created on: Apr 27, 2009
 *      Author: rasmussn
 */

#include "RandomConn.hpp"
#include <assert.h>
#include <string.h>

namespace PV {

RandomConn::RandomConn(const char * name,
      HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel)
{
   this->connId = hc->numberOfConnections();
   this->name   = strdup(name);
   this->parent = hc;

   this->numAxonalArborLists = 1;

   initialize(NULL, pre, post, channel);

   hc->addConnection(this);
}

int RandomConn::initializeWeights(const char * filename)
{
   assert(filename == NULL);
   return initializeRandomWeights(0);
}

}

Convert to use of axonalArbor syntax.


#include "display.h"
#include "sensor.h"
#include <LiquidCrystal.h>  // Arduino LCD library
#include <Arduino.h>  // enables use of byte pics

// pin definition for LCD
#define LCD_CS   10
#define LCD_DC   9
#define LCD_RST  8

namespace LCD {
  TFT TFTscreen = TFT(LCD_CS, LCD_DC, LCD_RST);

  void setup() {
    // initialize the display
    TFTscreen.begin();
    // clear the screen with a black background
    TFTscreen.background(0, 0, 0);
    // set the font color to white
    TFTscreen.stroke(255, 255, 255);
  }

  void clearScreen() {
    // clear the screen to show refreshed data
    TFTscreen.background(0, 0, 0);
  }

  void displayTemp(int tempInt) {
    char tempChar[6];
    snprintf(tempChar, sizeof tempChar, "%d", tempInt);
    // print temp text
    TFTscreen.text(tempChar, 0, 20);
  }
}

#include "display.h"
#include "sensor.h"
#include <LiquidCrystal.h>  // Arduino LCD library
#include <Arduino.h>  // enables use of byte pics

#define DISPLAY_RS 14
#define DISPLAY_E  15
#define DISPLAY_D4 5
#define DISPLAY_D5 4
#define DISPLAY_D6 3
#define DISPLAY_D7 2

namespace LCD {
  TFT TFTscreen = TFT(LCD_CS, LCD_DC, LCD_RST);

  void setup() {
    // initialize the display
    TFTscreen.begin();
    // clear the screen with a black background
    TFTscreen.background(0, 0, 0);
    // set the font color to white
    TFTscreen.stroke(255, 255, 255);
  }

  void clearScreen() {
    // clear the screen to show refreshed data
    TFTscreen.background(0, 0, 0);
  }

  void displayTemp(int tempInt) {
    char tempChar[6];
    snprintf(tempChar, sizeof tempChar, "%d", tempInt);
    // print temp text
    TFTscreen.text(tempChar, 0, 20);
  }
}

Update pin definitions for 16x2 lcd


#include <gtest/gtest.h>
#include <system.h>
#include "mock_memorymodule.h"

class SystemTest : public testing::Test {
protected:
    System sys;
    StrictMockMemoryModule mem;
};

//Dumy test
TEST_F(SystemTest, TestMemoryAddressTranslation) {
    unsigned char dummy_buffer[10];
    sys.installMemory(mem, 10, 10);
    int iret = sys.readMemory(10, 5, dummy_buffer);
}

#include <gtest/gtest.h>
#include <errors.h>
#include <system.h>
#include "mock_memorymodule.h"

class SystemTest : public testing::Test {
protected:
    System sys;
    StrictMockMemoryModule mem;
};

//Dumy test
TEST_F(SystemTest, TestMemoryAddressTranslation) {
    unsigned char dummy_buffer[10];
    int iret;

    iret = sys.installMemory(mem, 10, 10);
    ASSERT_EQ(iret, ERR_SUCCESS) << "Module installion failed";

    iret = sys.readMemory(10, 5, dummy_buffer);
    ASSERT_EQ(iret, ERR_SUCCESS) << "Memory read failed";
}

Create example memory read test


#define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    CCoinsViewDB *pcoinsdbview;

    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        noui_connect();
        bitdb.MakeMock();
        pblocktree = new CBlockTreeDB(true);
        pcoinsdbview = new CCoinsViewDB(true);
        pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
        LoadBlockIndex();
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        delete pcoinsTip;
        delete pcoinsdbview;
        delete pblocktree;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

#define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    CCoinsViewDB *pcoinsdbview;

    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        noui_connect();
        bitdb.MakeMock();
        pblocktree = new CBlockTreeDB(1 << 20, true);
        pcoinsdbview = new CCoinsViewDB(1 << 23, true);
        pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
        LoadBlockIndex();
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        delete pcoinsTip;
        delete pcoinsdbview;
        delete pblocktree;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

Fix tests after cache tweaks


// observable-ip-address.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	return 0;
}

// observable-ip-address.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <windows.h>

#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")

int _tmain(int argc, _TCHAR* argv[])
{
	OVERLAPPED overlap;
	DWORD ret;

	HANDLE hand = NULL;
	overlap.hEvent = WSACreateEvent();

	ret = NotifyAddrChange(&hand, &overlap);

	if (ret != NO_ERROR)
	{
		if (WSAGetLastError() != WSA_IO_PENDING)
		{
			printf("NotifyAddrChange error...%d\n", WSAGetLastError());
			return 1;
		}
	}

	if (WaitForSingleObject(overlap.hEvent, INFINITE) == WAIT_OBJECT_0)
		printf("IP Address table changed..\n");

	return 0;
}

Add code that hangs until the IP address changes


// 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 "remoting/protocol/key_event_tracker.h"

#include "base/logging.h"
#include "remoting/proto/event.pb.h"

namespace remoting {
namespace protocol {

KeyEventTracker::KeyEventTracker(InputStub* input_stub)
    : input_stub_(input_stub) {
}

KeyEventTracker::~KeyEventTracker() {
  DCHECK(pressed_keys_.empty());
}

void KeyEventTracker::InjectKeyEvent(const KeyEvent& event) {
  DCHECK(event.has_pressed());
  DCHECK(event.has_keycode());
  if (event.pressed()) {
    pressed_keys_.insert(event.keycode());
  } else {
    pressed_keys_.erase(event.keycode());
  }
  input_stub_->InjectKeyEvent(event);
}

void KeyEventTracker::InjectMouseEvent(const MouseEvent& event) {
  input_stub_->InjectMouseEvent(event);
}

void KeyEventTracker::ReleaseAllKeys() {
  std::set<int>::iterator i;
  for (i = pressed_keys_.begin(); i != pressed_keys_.end(); ++i) {
    KeyEvent event;
    event.set_keycode(*i);
    event.set_pressed(false);
    input_stub_->InjectKeyEvent(event);
  }
  pressed_keys_.clear();
}

}  // namespace protocol
}  // namespace remoting

// 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 "remoting/protocol/key_event_tracker.h"

#include "base/logging.h"
#include "remoting/proto/event.pb.h"

namespace remoting {
namespace protocol {

KeyEventTracker::KeyEventTracker(InputStub* input_stub)
    : input_stub_(input_stub) {
}

KeyEventTracker::~KeyEventTracker() {
}

void KeyEventTracker::InjectKeyEvent(const KeyEvent& event) {
  DCHECK(event.has_pressed());
  DCHECK(event.has_keycode());
  if (event.pressed()) {
    pressed_keys_.insert(event.keycode());
  } else {
    pressed_keys_.erase(event.keycode());
  }
  input_stub_->InjectKeyEvent(event);
}

void KeyEventTracker::InjectMouseEvent(const MouseEvent& event) {
  input_stub_->InjectMouseEvent(event);
}

void KeyEventTracker::ReleaseAllKeys() {
  std::set<int>::iterator i;
  for (i = pressed_keys_.begin(); i != pressed_keys_.end(); ++i) {
    KeyEvent event;
    event.set_keycode(*i);
    event.set_pressed(false);
    input_stub_->InjectKeyEvent(event);
  }
  pressed_keys_.clear();
}

}  // namespace protocol
}  // namespace remoting

Remove erroneous DCHECK from KeyEventTracker


#include "advanced_assert.h"

std::function<void (const char*)> AdvancedAssert::_loggingFunc;

void AdvancedAssert::setLoggingFunc(const std::function<void (const char*)>& func)
{
	_loggingFunc = func;
}

#include "advanced_assert.h"

#if defined _DEBUG == (defined NDEBUG || NDEBUG == 1)
#error "Either _DEBUG or NDEBUG=1 must be defined"
#endif

std::function<void (const char*)> AdvancedAssert::_loggingFunc;

void AdvancedAssert::setLoggingFunc(const std::function<void (const char*)>& func)
{
	_loggingFunc = func;
}

Debug / release macros check added (required for normal assert functioning on non-Windows systems)


#include <iostream>
#include "../src/tisys.hpp"

int main(int argc, char** argv){
	cout << "Example" <<endl;
	Filesystem fs;

	if ( argc == 1 )
		fs.info(".");
	else
		fs.info( argv[1] );

	cout << fs;
	return 0;
}

#include <iostream>
#include "../src/tisys.hpp"

using namespace std;

int main(int argc, char** argv){
	cout << "Example" <<endl;
	Filesystem fs;

	if ( argc == 1 )
		fs.info(".");
	else
		fs.info( argv[1] );

	cout << fs;
	return 0;
}

Put the using namespace std in the cpp files


#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <set>
#include <string>
#include <assert.h>

using namespace std;

set<string> done;

void dump_header(string header) {
    if (done.find(header) != done.end()) return;
    done.insert(header);

    FILE *f = fopen(header.c_str(), "r");

    if (f == NULL) {
      fprintf(stderr, "Could not open header %s.\n", header.c_str());
      exit(1);
    }

    char line[1024];

    while (fgets(line, 1024, f)) {
        if (strncmp(line, "#include \"", 10) == 0) {
            char *sub_header = line + 10;
            for (int i = 0; i < 1014; i++) {
                if (sub_header[i] == '"') sub_header[i] = 0;
            }
            size_t slash_pos = header.rfind('/');
            std::string path;
            if (slash_pos != std::string::npos)
                path = header.substr(0, slash_pos + 1);
            dump_header(path + sub_header);
        } else {
            fputs(line, stdout);
        }
    }

    fclose(f);
}

int main(int argc, char **headers) {
    for (int i = 1; i < argc; i++) {
        dump_header(headers[i]);
    }

    return 0;
}

#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <set>
#include <string>
#include <assert.h>

std::set<std::string> done;

void dump_header(std::string header) {
    if (done.find(header) != done.end()) return;
    done.insert(header);

    FILE *f = fopen(header.c_str(), "r");

    if (f == NULL) {
      fprintf(stderr, "Could not open header %s.\n", header.c_str());
      exit(1);
    }

    char line[1024];

    while (fgets(line, 1024, f)) {
        if (strncmp(line, "#include \"", 10) == 0) {
            char *sub_header = line + 10;
            for (int i = 0; i < 1014; i++) {
                if (sub_header[i] == '"') sub_header[i] = 0;
            }
            size_t slash_pos = header.rfind('/');
            std::string path;
            if (slash_pos != std::string::npos)
                path = header.substr(0, slash_pos + 1);
            dump_header(path + sub_header);
        } else {
            fputs(line, stdout);
        }
    }

    fclose(f);
}

int main(int argc, char **headers) {
    for (int i = 1; i < argc; i++) {
        dump_header(headers[i]);
    }

    return 0;
}

Remove dependency on importing std into global namespace.


#include <ctx.hpp>
#include <cl.hpp>
#include <vector>

namespace opencl
{

using std::vector;
using cl::Platform;
using cl::Device;

void ctxCB(const char *errinfo, const void *private_info, size_t cb, void *user_data)
{
    printf("Context Error: %s\n", errinfo); fflush(stdout);
}

const cl::Context&
getCtx(unsigned char idx)
{
    static std::vector<cl::Platform> platforms(0);
    static std::vector<cl::Context> contexts(0);
    if(contexts.empty()) {
        Platform::get(&platforms);
        for(auto platform : platforms) {
            vector<cl_context_properties> prop = {CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0};
            contexts.emplace_back(CL_DEVICE_TYPE_CPU, &prop.front(), ctxCB);
        }
    }
    return contexts[idx];
}

cl::CommandQueue&
getQueue(unsigned char idx) {
    static std::vector<cl::CommandQueue> queues;
    if(queues.empty()) {
        queues.emplace_back(getCtx(0));
    }
    return queues[idx];
}

}

#include <ctx.hpp>
#include <cl.hpp>
#include <vector>

namespace opencl
{

using std::vector;
using cl::Platform;
using cl::Device;

void ctxCB(const char *errinfo, const void *private_info, size_t cb, void *user_data)
{
    printf("Context Error: %s\n", errinfo); fflush(stdout);
}

const cl::Context&
getCtx(unsigned char idx)
{
    static std::vector<cl::Platform> platforms(0);
    static std::vector<cl::Context> contexts(0);
    if(contexts.empty()) {
        Platform::get(&platforms);
        for(auto platform : platforms) {
            vector<cl_context_properties> prop = {CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0};
            contexts.emplace_back(CL_DEVICE_TYPE_DEFAULT, &prop.front(), ctxCB);
        }
    }
    return contexts[idx];
}

cl::CommandQueue&
getQueue(unsigned char idx) {
    static std::vector<cl::CommandQueue> queues;
    if(queues.empty()) {
        queues.emplace_back(getCtx(0));
    }
    return queues[idx];
}

}

Create context using DEFAULT instead of CPU for OpenCL backend


#include "SkTypeface.h"

// ===== Begin Chrome-specific definitions =====

uint32_t SkTypeface::UniqueID(const SkTypeface* face)
{
    return NULL;
}

void SkTypeface::serialize(SkWStream* stream) const {
}

SkTypeface* SkTypeface::Deserialize(SkStream* stream) {
  return NULL;
}

// ===== End Chrome-specific definitions =====

#include "SkTypeface.h"

// ===== Begin Chrome-specific definitions =====

uint32_t SkTypeface::UniqueID(const SkTypeface* face)
{
    return 0;
}

void SkTypeface::serialize(SkWStream* stream) const {
}

SkTypeface* SkTypeface::Deserialize(SkStream* stream) {
  return NULL;
}

// ===== End Chrome-specific definitions =====

Return 0 instead of NULL for a non-pointer type. Eliminates a warning in GCC.


#include "gtest/gtest.h"

#include "../include/rainy.h"
using namespace rainy;

TEST(SphereTest, InstanceTest) {
    Sphere sp(1.0, Vector3(0.0, 0.0, 0.0), Color(), Color(0.75, 0.75, 0.75), REFLECTION_DIFFUSE);

    EXPECT_EQ(0.0, sp.center().x());
    EXPECT_EQ(0.0, sp.center().y());
    EXPECT_EQ(0.0, sp.center().z());

    HitPoint hitpoint;
    sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(-1.0, 0.0, 0.0)), hitpoint);
}

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

#include "gtest/gtest.h"

#include "../include/rainy.h"
using namespace rainy;

TEST(SphereTest, InstanceTest) {
    Sphere sp(2.0, Vector3(0.0, 0.0, 0.0), Color(), Color(0.75, 0.75, 0.75), REFLECTION_DIFFUSE);

    EXPECT_EQ(0.0, sp.center().x());
    EXPECT_EQ(0.0, sp.center().y());
    EXPECT_EQ(0.0, sp.center().z());

    EXPECT_EQ(0.0, sp.emission().x());
    EXPECT_EQ(0.0, sp.emission().y());
    EXPECT_EQ(0.0, sp.emission().z());

    EXPECT_EQ(0.75, sp.color().x());
    EXPECT_EQ(0.75, sp.color().y());
    EXPECT_EQ(0.75, sp.color().z());

    EXPECT_EQ(REFLECTION_DIFFUSE, sp.reftype());

    HitPoint hitpoint;
    EXPECT_TRUE(sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(-1.0, 0.0, 0.0)), hitpoint));
    EXPECT_EQ(2.0, hitpoint.position().x());
    EXPECT_EQ(0.0, hitpoint.position().y());
    EXPECT_EQ(0.0, hitpoint.position().z());

    EXPECT_EQ(1.0, hitpoint.normal().x());
    EXPECT_EQ(0.0, hitpoint.normal().y());
    EXPECT_EQ(0.0, hitpoint.normal().z());

    EXPECT_FALSE(sp.intersect(Ray(Vector3(10.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0)), hitpoint));
}

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

Add test code for Sphere intersection.


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

#include "ipc/mojo/ipc_mojo_handle_attachment.h"

#include "ipc/ipc_message_attachment_set.h"
#include "third_party/mojo/src/mojo/edk/embedder/embedder.h"

namespace IPC {
namespace internal {

MojoHandleAttachment::MojoHandleAttachment(mojo::ScopedHandle handle)
    : handle_(handle.Pass()) {
}

MojoHandleAttachment::~MojoHandleAttachment() {
}

MessageAttachment::Type MojoHandleAttachment::GetType() const {
  return TYPE_MOJO_HANDLE;
}

#if defined(OS_POSIX)
base::PlatformFile MojoHandleAttachment::TakePlatformFile() {
  mojo::embedder::ScopedPlatformHandle platform_handle;
  MojoResult unwrap_result = mojo::embedder::PassWrappedPlatformHandle(
      handle_.release().value(), &platform_handle);
  if (unwrap_result != MOJO_RESULT_OK) {
    LOG(ERROR) << "Pipe failed to covert handles. Closing: " << unwrap_result;
    return -1;
  }

  return platform_handle.release().fd;
}
#endif  // OS_POSIX

mojo::ScopedHandle MojoHandleAttachment::TakeHandle() {
  return handle_.Pass();
}

}  // namespace internal
}  // namespace IPC

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

#include "ipc/mojo/ipc_mojo_handle_attachment.h"

#include "ipc/ipc_message_attachment_set.h"
#include "third_party/mojo/src/mojo/edk/embedder/embedder.h"

namespace IPC {
namespace internal {

MojoHandleAttachment::MojoHandleAttachment(mojo::ScopedHandle handle)
    : handle_(handle.Pass()) {
}

MojoHandleAttachment::~MojoHandleAttachment() {
}

MessageAttachment::Type MojoHandleAttachment::GetType() const {
  return TYPE_MOJO_HANDLE;
}

#if defined(OS_POSIX)
base::PlatformFile MojoHandleAttachment::TakePlatformFile() {
  mojo::embedder::ScopedPlatformHandle platform_handle;
  MojoResult unwrap_result = mojo::embedder::PassWrappedPlatformHandle(
      handle_.get().value(), &platform_handle);
  handle_.reset();
  if (unwrap_result != MOJO_RESULT_OK) {
    LOG(ERROR) << "Pipe failed to covert handles. Closing: " << unwrap_result;
    return -1;
  }

  return platform_handle.release().fd;
}
#endif  // OS_POSIX

mojo::ScopedHandle MojoHandleAttachment::TakeHandle() {
  return handle_.Pass();
}

}  // namespace internal
}  // namespace IPC

Fix leak of PlatformHandleDispatchers in Mojo IPC


#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

#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<ContextError>(m, "ContextError");
    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 ContextError


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

#include "sky/tools/sky_snapshot/vm.h"

#include "base/logging.h"
#include "sky/tools/sky_snapshot/loader.h"
#include "sky/tools/sky_snapshot/logging.h"

extern "C" {
extern void* kDartVmIsolateSnapshotBuffer;
extern void* kDartIsolateSnapshotBuffer;
}

static const char* kDartArgs[] = {
    "--enable_mirrors=false",
};

void InitDartVM() {
  CHECK(Dart_SetVMFlags(arraysize(kDartArgs), kDartArgs));
  CHECK(
      Dart_Initialize(reinterpret_cast<uint8_t*>(&kDartVmIsolateSnapshotBuffer),
                      nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
                      nullptr, nullptr, nullptr, nullptr, nullptr) == nullptr);
}

Dart_Isolate CreateDartIsolate() {
  CHECK(kDartIsolateSnapshotBuffer);
  char* error = nullptr;
  Dart_Isolate isolate = Dart_CreateIsolate(
      "dart:snapshot", "main",
      reinterpret_cast<uint8_t*>(&kDartIsolateSnapshotBuffer), nullptr, nullptr,
      &error);

  CHECK(isolate) << error;
  CHECK(!LogIfError(Dart_SetLibraryTagHandler(HandleLibraryTag)));

  Dart_ExitIsolate();
  return isolate;
}

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

#include "sky/tools/sky_snapshot/vm.h"

#include "base/logging.h"
#include "sky/tools/sky_snapshot/loader.h"
#include "sky/tools/sky_snapshot/logging.h"

extern "C" {
extern void* kDartVmIsolateSnapshotBuffer;
extern void* kDartIsolateSnapshotBuffer;
}

static const char* kDartArgs[] = {
    "--enable_mirrors=false",
    "--load_deferred_eagerly=true",
};

void InitDartVM() {
  CHECK(Dart_SetVMFlags(arraysize(kDartArgs), kDartArgs));
  CHECK(
      Dart_Initialize(reinterpret_cast<uint8_t*>(&kDartVmIsolateSnapshotBuffer),
                      nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
                      nullptr, nullptr, nullptr, nullptr, nullptr) == nullptr);
}

Dart_Isolate CreateDartIsolate() {
  CHECK(kDartIsolateSnapshotBuffer);
  char* error = nullptr;
  Dart_Isolate isolate = Dart_CreateIsolate(
      "dart:snapshot", "main",
      reinterpret_cast<uint8_t*>(&kDartIsolateSnapshotBuffer), nullptr, nullptr,
      &error);

  CHECK(isolate) << error;
  CHECK(!LogIfError(Dart_SetLibraryTagHandler(HandleLibraryTag)));

  Dart_ExitIsolate();
  return isolate;
}

Load deferred import libraries when building the snapshot


#include <kernel/kernconf.hh>

USDK_API kernconf_type kernconf = {
  // Default is large enough until we enable a mechanism to dynamically
  // reallocate task space on demand.
  /* .default_stack_size = */         128 * 1024,
  /* .minimum_stack_size = */         4 * 1024
};

#include <kernel/config.h>
#include <kernel/kernconf.hh>

USDK_API kernconf_type kernconf = {
  // Default is large enough until we enable a mechanism to dynamically
  // reallocate task space on demand.
  /* .default_stack_size = */         URBI_KERNEL_STACK_SIZE * 1024,
  /* .minimum_stack_size = */         4 * 1024
};

Use the stack size provided by configure.


// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license

#include <iostream>
#include <set>
#include "warnings.hpp"

void warn(std::string message) {
    std::cerr << "[cfiles] " << message << std::endl;
}

void warn_once(std::string message) {
    static std::set<std::string> already_seen;
    auto seen = already_seen.insert(message).second;
    if (!seen) {
        warn(message);
    }
}

// cfiles, an analysis frontend for the Chemfiles library
// Copyright (C) Guillaume Fraux and contributors -- BSD license

#include <iostream>
#include <set>
#include "warnings.hpp"

void warn(std::string message) {
    std::cerr << "[cfiles] " << message << std::endl;
}

void warn_once(std::string message) {
    static std::set<std::string> ALREADY_SEEN;
    auto not_seen = ALREADY_SEEN.insert(message).second;
    if (not_seen) {
        warn(message);
    }
}

Fix warn_once to effectively warn once


#include "planning/simulation/interactable_geometry.hh"

namespace jcc {
namespace simulation {

std::vector<RayIntersection> InteractableGeometry::all_intersections(
    const geometry::Ray& ray) {
  std::vector<RayIntersection> intersections;
  for (const auto& bbox : aabb_) {
    const auto intersection = bbox.second.bbox.intersect(ray);
    if (intersection.intersected) {
      intersections.push_back(
          {bbox.first, intersection.distance, ray(intersection.distance)});
    }
  }
  return intersections;
}

std::vector<BoundingBoxIntersection> InteractableGeometry::all_intersections(
    const InteractableGeometry::BBox3& bbox) {
  return {};
}

}  // namespace simulation
}  // namespace jcc

#include "planning/simulation/interactable_geometry.hh"

#include <algorithm>

namespace jcc {
namespace simulation {

std::vector<RayIntersection> InteractableGeometry::all_intersections(
    const geometry::Ray& ray) {
  std::vector<RayIntersection> intersections;
  for (const auto& bbox : aabb_) {
    const auto intersection = bbox.second.bbox.intersect(ray);
    if (intersection.intersected) {
      intersections.push_back(
          {bbox.first, intersection.distance, ray(intersection.distance)});
    }
  }
  std::sort(intersections.begin(), intersections.end(),
            [](const RayIntersection& a, const RayIntersection& b) -> bool {
              return a.distance < b.distance;
            });

  return intersections;
}

std::vector<BoundingBoxIntersection> InteractableGeometry::all_intersections(
    const InteractableGeometry::BBox3& other) {
  std::vector<BoundingBoxIntersection> intersections;

  for (const auto& bbox : aabb_) {
    const auto intersection = bbox.second.bbox.intersect(other);

    if (intersection.contained) {
      intersections.push_back({bbox.first, intersection.contained});
    }
  }

  return intersections;
}

}  // namespace simulation
}  // namespace jcc

Sort ray-intersected boxes by distance


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

// <array>

// template <size_t I, class T> struct variant_alternative; // undefined
// template <size_t I, class T> struct variant_alternative<I, const T>;
// template <size_t I, class T> struct variant_alternative<I, volatile T>;
// template <size_t I, class T> struct variant_alternative<I, const volatile T>;
// template <size_t I, class T>
//   using variant_alternative_t = typename variant_alternative<I, T>::type;
//
// template <size_t I, class... Types>
//    struct variant_alternative<I, variant<Types...>>;

#include <variant>
#include <cassert>

int main()
{
    {
        typedef std::variant<int, double> T;
        std::variant_alternative<2, T>::type foo; // expected-note {{requested here}}
        // expected-error@variant:* {{static_assert failed "Index out of bounds in std::variant_alternative<>"}}
    }
}

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

// <variant>
// UNSUPPORTED: c++98, c++03, c++11, c++14

// template <size_t I, class T> struct variant_alternative; // undefined
// template <size_t I, class T> struct variant_alternative<I, const T>;
// template <size_t I, class T> struct variant_alternative<I, volatile T>;
// template <size_t I, class T> struct variant_alternative<I, const volatile T>;
// template <size_t I, class T>
//   using variant_alternative_t = typename variant_alternative<I, T>::type;
//
// template <size_t I, class... Types>
//    struct variant_alternative<I, variant<Types...>>;

#include <variant>
#include <cassert>

int main()
{
    {
        typedef std::variant<int, double> T;
        std::variant_alternative<2, T>::type foo; // expected-note {{requested here}}
        // expected-error@variant:* {{static_assert failed "Index out of bounds in std::variant_alternative<>"}}
    }
}

Mark the recent variant test as UNSUPPORTED for C++ before 17


/*
  * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
  * A copy of the License is located at
  *
  *  http://aws.amazon.com/apache2.0
  *
  * or in the "license" file accompanying this file. This file 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 <aws/external/gtest.h>
#include <aws/core/Aws.h>
#include <aws/testing/platform/PlatformTesting.h>
#include <aws/testing/MemoryTesting.h>

int main(int argc, char** argv)
{
    Aws::SDKOptions options;
    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    AWS_BEGIN_MEMORY_TEST_EX(options, 1024, 128);
    Aws::Testing::InitPlatformTest(options);

    Aws::InitAPI(options);
    ::testing::InitGoogleTest(&argc, argv);
    int exitCode = RUN_ALL_TESTS();
    Aws::ShutdownAPI(options);

    AWS_END_MEMORY_TEST_EX;
    Aws::Testing::ShutdownPlatformTest(options);
    return exitCode;
}

/*
  * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
  * A copy of the License is located at
  *
  *  http://aws.amazon.com/apache2.0
  *
  * or in the "license" file accompanying this file. This file 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 <aws/external/gtest.h>
#include <aws/core/Aws.h>
#include <aws/testing/platform/PlatformTesting.h>
//#include <aws/testing/MemoryTesting.h>

int main(int argc, char** argv)
{
    Aws::SDKOptions options;
    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    //AWS_BEGIN_MEMORY_TEST_EX(options, 1024, 128);
    Aws::Testing::InitPlatformTest(options);

    Aws::InitAPI(options);
    ::testing::InitGoogleTest(&argc, argv);
    int exitCode = RUN_ALL_TESTS();
    Aws::ShutdownAPI(options);

    ///AWS_END_MEMORY_TEST_EX;
    Aws::Testing::ShutdownPlatformTest(options);
    return exitCode;
}

Revert text-to-speech-test from using exact memory manager


// Copyright (c) 2022 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.

#include "utils/IntPoint.h"
#include <gtest/gtest.h>

// NOLINTBEGIN(*-magic-numbers)
namespace cura
{
TEST(IntPointTest, TestRotationMatrix)
{
    PointMatrix rot2d(90);
    Point3Matrix rot_homogeneous(rot2d);
    Point a(20, 10);
    Point b(30, 20);
    Point translated = Point3Matrix::translate(-a).apply(b);
    Point rotated = rot_homogeneous.apply(translated);
    Point rotated_in_place = Point3Matrix::translate(a).apply(rotated);

    Point3Matrix all_in_one = Point3Matrix::translate(a).compose(rot_homogeneous).compose(Point3Matrix::translate(-a));
    Point rotated_in_place_2 = all_in_one.apply(b);

    ASSERT_EQ(rotated_in_place, rotated_in_place_2) << "Matrix composition with translate and rotate failed.";
}
} // namespace cura
// NOLINTEND(*-magic-numbers)

// Copyright (c) 2022 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.

#include "utils/IntPoint.h"
#include <gtest/gtest.h>

// NOLINTBEGIN(*-magic-numbers)
namespace cura
{
TEST(IntPointTest, TestRotationMatrix)
{
    PointMatrix rot2d(90);
    Point3Matrix rot_homogeneous(rot2d);
    Point a(20, 10);
    Point b(30, 20);
    Point translated = Point3Matrix::translate(-a).apply(b);
    Point rotated = rot_homogeneous.apply(translated);
    Point rotated_in_place = Point3Matrix::translate(a).apply(rotated);

    Point3Matrix all_in_one = Point3Matrix::translate(a).compose(rot_homogeneous).compose(Point3Matrix::translate(-a));
    Point rotated_in_place_2 = all_in_one.apply(b);

    ASSERT_EQ(rotated_in_place, rotated_in_place_2) << "Matrix composition with translate and rotate failed.";
}

TEST(IntPointTest, TestSize)
{
    ASSERT_EQ(sizeof(Point::X), sizeof(coord_t));
    ASSERT_LE(sizeof(coord_t), sizeof(int64_t));
}

} // namespace cura
// NOLINTEND(*-magic-numbers)

Make sure Point is made of right-sized coord's.


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

#include "views/controls/menu/menu_config.h"

#include "grit/app_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/resource/resource_bundle.h"

namespace views {

// static
MenuConfig* MenuConfig::Create() {
  MenuConfig* config = new MenuConfig();
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  config->font = rb.GetFont(ResourceBundle::BaseFont);
  config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width();
  // Add 4 to force some padding between check and label.
  config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4;
  config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height();
  return config;
}

}  // namespace views

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

#include "views/controls/menu/menu_config.h"

#include "grit/app_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/resource/resource_bundle.h"

namespace views {

// static
MenuConfig* MenuConfig::Create() {
  MenuConfig* config = new MenuConfig();
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
#if defined(TOUCH_UI)
  config->font = rb.GetFont(ResourceBundle::LargeFont);
#else
  config->font = rb.GetFont(ResourceBundle::BaseFont);
#endif
  config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width();
  // Add 4 to force some padding between check and label.
  config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4;
  config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height();
  return config;
}

}  // namespace views

Increase the base font size for touch ui


#include "logger.h"

namespace lightstep {
//------------------------------------------------------------------------------
// LogDefault
//------------------------------------------------------------------------------
static void LogDefault(LogLevel log_level,
                       opentracing::string_view message) noexcept try {
  std::ostringstream oss;
  switch (log_level) {
    case LogLevel::debug:
      oss << "Debug: ";
      break;
    case LogLevel::info:
      oss << "Info: ";
      break;
    case LogLevel::warn:
      oss << "Warn: ";
      break;
    case LogLevel::error:
      oss << "Error: ";
      break;
    case LogLevel::off:
      /* This should never be reached. */
      return;
  }
  oss << message << '\n';
  std::cerr << oss.str();
} catch (const std::exception& /*e*/) {
  // Ignore errors.
}

//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
Logger::Logger() : logger_sink_{LogDefault} {}

Logger::Logger(
    std::function<void(LogLevel, opentracing::string_view)>&& logger_sink) {
  if (logger_sink) {
    logger_sink_ = std::move(logger_sink);
  } else {
    logger_sink_ = LogDefault;
  }
}

//------------------------------------------------------------------------------
// Log
//------------------------------------------------------------------------------
void Logger::Log(LogLevel level,
                 opentracing::string_view message) noexcept try {
  if (static_cast<int>(level) <= static_cast<int>(level_)) {
    logger_sink_(level, message);
  }
} catch (const std::exception& /*e*/) {
  // Ignore exceptions.
}
}  // namespace lightstep

#include "logger.h"

namespace lightstep {
//------------------------------------------------------------------------------
// LogDefault
//------------------------------------------------------------------------------
static void LogDefault(LogLevel log_level,
                       opentracing::string_view message) noexcept try {
  std::ostringstream oss;
  switch (log_level) {
    case LogLevel::debug:
      oss << "Debug: ";
      break;
    case LogLevel::info:
      oss << "Info: ";
      break;
    case LogLevel::warn:
      oss << "Warn: ";
      break;
    case LogLevel::error:
      oss << "Error: ";
      break;
    case LogLevel::off:
      /* This should never be reached. */
      return;
  }
  oss << message << '\n';
  std::cerr << oss.str();
} catch (const std::exception& /*e*/) {
  // Ignore errors.
}

//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
Logger::Logger() : logger_sink_{LogDefault} {}

Logger::Logger(
    std::function<void(LogLevel, opentracing::string_view)>&& logger_sink) {
  if (logger_sink) {
    logger_sink_ = std::move(logger_sink);
  } else {
    logger_sink_ = LogDefault;
  }
}

//------------------------------------------------------------------------------
// Log
//------------------------------------------------------------------------------
void Logger::Log(LogLevel level,
                 opentracing::string_view message) noexcept try {
  if (static_cast<int>(level) >= static_cast<int>(level_)) {
    logger_sink_(level, message);
  }
} catch (const std::exception& /*e*/) {
  // Ignore exceptions.
}
}  // namespace lightstep

Fix bug when checking log level.


// RUN: %clangxx_msan -O0 %s -c -o %t
// RUN: %clangxx_msan -O3 %s -c -o %t

// Regression test for MemorySanitizer instrumentation of a select instruction
// with vector arguments.

#if defined(__x86_64__)
#include <emmintrin.h>

__m128d select(bool b, __m128d c, __m128d d)
{
  return b ? c : d;
}
#elif defined (__mips64)
typedef double __w64d __attribute__ ((vector_size(16)));

__w64d select(bool b, __w64d c, __w64d d)
{
  return b ? c : d;
}
#endif

// RUN: %clangxx_msan -O0 %s -c -o %t
// RUN: %clangxx_msan -O3 %s -c -o %t

// Regression test for MemorySanitizer instrumentation of a select instruction
// with vector arguments.

#if defined(__x86_64__)
#include <emmintrin.h>

__m128d select(bool b, __m128d c, __m128d d)
{
  return b ? c : d;
}
#elif defined (__mips64) || defined (__powerpc64__)
typedef double __w64d __attribute__ ((vector_size(16)));

__w64d select(bool b, __w64d c, __w64d d)
{
  return b ? c : d;
}
#endif

Enable this test for PPC64.


#include "entity.h"

using namespace sf;

Entity::Entity(EntityShape shape0, Engine *engine0) {
	shape = shape0;
	position.x = 0; position.y = 0;
	isKilledFlag = false;
	engine = engine0;
	UID = ++globalUID;
}
Entity::~Entity() {
	engine = NULL;
}

Uint32 Entity::globalUID = 0;
Uint32 Entity::getUID(void) const {return UID;}
void Entity::setUID(Uint32 uid) {UID = uid;}
void Entity::useUpperUID(void) {
	globalUID |= 0x80000000;
}

#include "entity.h"

using namespace sf;

Entity::Entity(EntityShape shape0, Engine *engine0) {
	shape = shape0;
	position.x = 0; position.y = 0;
	isKilledFlag = false;
	engine = engine0;
	if (globalUID & 0x80000000) {
		globalUID = (globalUID+1) | 0x80000000;
	} else {
		globalUID = (globalUID+1) & (~0x80000000);
	}
	UID = globalUID;
}
Entity::~Entity() {
	engine = NULL;
}

Uint32 Entity::globalUID = 0;
Uint32 Entity::getUID(void) const {return UID;}
void Entity::setUID(Uint32 uid) {UID = uid;}
void Entity::useUpperUID(void) {
	globalUID |= 0x80000000;
}

Make sure entities UID space don't clash between server & client.


// a wrapper to load netgen-dll into python

#include <iostream>

#ifdef NG_PYTHON
#include <boost/python.hpp>
#endif

#ifdef WIN32
#define DLL_HEADER __declspec(dllimport)
#else
#define DLL_HEADER
#endif

void DLL_HEADER ExportNetgenMeshing();
void DLL_HEADER ExportMeshVis();
void DLL_HEADER ExportCSG();
void DLL_HEADER ExportCSGVis();
void DLL_HEADER ExportGeom2d();

#ifdef NG_PYTHON
BOOST_PYTHON_MODULE(libngpy)
{
    ExportCSG();
    ExportCSGVis();
    ExportNetgenMeshing();
    ExportMeshVis();
    ExportGeom2d();
}
#endif

// a wrapper to load netgen-dll into python

#include <iostream>
#include <boost/python.hpp>

#ifdef WIN32
#define DLL_HEADER __declspec(dllimport)
#else
#define DLL_HEADER
#endif

void DLL_HEADER ExportNetgenMeshing();
void DLL_HEADER ExportMeshVis();
void DLL_HEADER ExportCSG();
void DLL_HEADER ExportCSGVis();
void DLL_HEADER ExportGeom2d();

BOOST_PYTHON_MODULE(libngpy)
{
    ExportCSG();
    ExportCSGVis();
    ExportNetgenMeshing();
    ExportMeshVis();
    ExportGeom2d();
}

Revert "Guard inclusion of boost/python.hpp"


#include <QtWidgets/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

Remove trailing whitespace from example source code


#include "engineBootstrap.hpp"
#include <catch/catch.hpp>

TEST_CASE("Test glTF Loading")
{
	auto GameEngine = Annwvyn::bootstrapTestEngine("GlTF Test");

	auto object = Annwvyn::AnnGetGameObjectManager()->createGameObject("Avocado.glb");
	object->setPosition(0, 1.6, 9);

	REQUIRE(object != nullptr);
	GameEngine->initPlayerRoomscalePhysics();
	Annwvyn::AnnGetEventManager()->useDefaultEventListener();

	const auto counter = 60*5;
	auto frame		   = 0;
	while(frame < counter && !GameEngine->checkNeedToQuit())
	{
		object->setOrientation(Annwvyn::AnnQuaternion(Annwvyn::AnnDegree(frame * 5), Annwvyn::AnnVect3::UNIT_Y));
		frame++;
		GameEngine->refresh();
	}

}

#include "engineBootstrap.hpp"
#include <catch/catch.hpp>

namespace Annwvyn
{
TEST_CASE("Test glTF Loading")
{
	auto GameEngine = Annwvyn::bootstrapTestEngine("GlTF Test");

	auto object = Annwvyn::AnnGetGameObjectManager()->createGameObject("Avocado.glb");
	object->setPosition(0, 1.6, 9);
	object->setScale(3, 3, 3);

	REQUIRE(object != nullptr);
	GameEngine->initPlayerRoomscalePhysics();
	Annwvyn::AnnGetEventManager()->useDefaultEventListener();

	const auto counter = 60 * 5;
	auto frame		   = 0;
	while(frame < counter && !GameEngine->checkNeedToQuit())
	{
		object->setOrientation(Annwvyn::AnnQuaternion(Annwvyn::AnnDegree(frame * 5), Annwvyn::AnnVect3::UNIT_Y));
		frame++;
		GameEngine->refresh();
	}
}
}

Put test in Annwvyn namespace


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

#include "LegacyViewManagerInteropViewProps.h"

namespace facebook {
namespace react {

LegacyViewManagerInteropViewProps::LegacyViewManagerInteropViewProps(
    const LegacyViewManagerInteropViewProps &sourceProps,
    const RawProps &rawProps)
    : ViewProps(sourceProps, rawProps), otherProps((folly::dynamic)rawProps) {}

} // namespace react
} // namespace facebook

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

#include "LegacyViewManagerInteropViewProps.h"

namespace facebook {
namespace react {

static folly::dynamic recursiveMerge(
    folly::dynamic const &lhs,
    folly::dynamic const &rhs) {
  auto copy = lhs;
  copy.merge_patch(rhs);
  return copy;
}

LegacyViewManagerInteropViewProps::LegacyViewManagerInteropViewProps(
    const LegacyViewManagerInteropViewProps &sourceProps,
    const RawProps &rawProps)
    : ViewProps(sourceProps, rawProps),
      otherProps(
          recursiveMerge(sourceProps.otherProps, (folly::dynamic)rawProps)) {}

} // namespace react
} // namespace facebook

Fix clone of props for legacy interop component


// Copyright 2012, Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: tomasz.kaftal@gmail.com (Tomasz Kaftal)
//
// This file contains a custom googletest main method to launch tests.
// It launches the Supersonic initialisation routine.

#include <iostream>

#include "supersonic/base/infrastructure/init.h"
#include "gtest/gtest.h"

GTEST_API_ int main(int argc, char** argv) {
  std::cout << "Running main() from supersonic_test_main.cc\n";

  supersonic::SupersonicInit(&argc, &argv);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

// Copyright 2012, Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: tomasz.kaftal@gmail.com (Tomasz Kaftal)
//
// This file contains a custom googletest main method to launch tests.
// It launches the Supersonic initialisation routine.

#include <iostream>

#include "supersonic/base/infrastructure/init.h"
#include "gtest/gtest.h"

GTEST_API_ int main(int argc, char** argv) {
  std::cout << "Running main() from supersonic_test_main.cc\n";

  // Make sure to parse gtest_* flags before parsing other flags.
  testing::InitGoogleTest(&argc, argv);
  supersonic::SupersonicInit(&argc, &argv);
  return RUN_ALL_TESTS();
}

Make sure to parse gtest_* flags before other flags when running tests.


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

// <fstream>

// template <class charT, class traits = char_traits<charT> >
// class basic_fstream

// The char type of the stream and the char_type of the traits have to match

#include <fstream>

int main()
{
	std::basic_fstream<char, std::char_traits<wchar_t> > f;
//  expected-error-re@ios:* {{static_assert failed{{.*}} "traits_type::char_type must be the same type as CharT"}}
//  expected-error-re@streambuf:* {{static_assert failed{{.*}} "traits_type::char_type must be the same type as CharT"}}
}

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

// <fstream>

// template <class charT, class traits = char_traits<charT> >
// class basic_fstream

// The char type of the stream and the char_type of the traits have to match

#include <fstream>

int main()
{
	std::basic_fstream<char, std::char_traits<wchar_t> > f;
//  expected-error-re@ios:* {{static_assert failed{{.*}} "traits_type::char_type must be the same type as CharT"}}
//  expected-error-re@streambuf:* {{static_assert failed{{.*}} "traits_type::char_type must be the same type as CharT"}}

// FIXME: As of commit r324062 Clang incorrectly generates a diagnostic about mismatching
// exception specifications for types which are already invalid for one reason or another.
// For now we tolerate this diagnostic.
// expected-error@ostream:* 0-1 {{exception specification of overriding function is more lax than base version}}
}

Work around Clang bug introduced in r324062


#include "main.hpp"

int main()
{
	DEV::KeepConsoleOpen keepConsoleOpen;
	keepConsoleOpen.setKeyRequirement(DEV::KeepConsoleOpen::Escape);

	try
	{
		Game game;
		game.run();
	}
	catch (int e)
	{
		DEV::printLine("Exception caught:\n\"" + pl::stringFrom(e) + "\"");
		return EXIT_FAILURE;
	}
	catch (char* e)
	{
		DEV::printLine("Exception caught:\n\"" + std::string(e) + "\"");
		return EXIT_FAILURE;
	}
	catch (...)
	{
		DEV::printLine("Unknown exception caught!");
		return EXIT_FAILURE;
	}

	keepConsoleOpen.allowToClose();
	return EXIT_SUCCESS;
}

#include "main.hpp"

int main()
{
	DEV::KeepConsoleOpen keepConsoleOpen;
	keepConsoleOpen.setKeyRequirement(DEV::KeepConsoleOpen::Escape);

	try
	{
		Game game;
		game.run();
	}
	catch (int e)
	{
		DEV::printLine("Exception caught: " + pl::stringFrom(e));
		return EXIT_FAILURE;
	}
	catch (char* e)
	{
		DEV::printLine("Exception caught:\n\"" + std::string(e) + "\"");
		return EXIT_FAILURE;
	}
	catch (...)
	{
		DEV::printLine("Unknown exception caught!");
		return EXIT_FAILURE;
	}

	keepConsoleOpen.allowToClose();
	return EXIT_SUCCESS;
}

Change display of int exception


#include "misc_util.h"

namespace dlib {

    void string_fmt_time(std::string& ret) {
        time_t now = time(NULL);
        struct tm *t = localtime(&now);
        while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t))
            ret.reserve(ret.size() << 1);
    }

}

#include "misc_util.h"

namespace dlib {

    void string_fmt_time(std::string& ret) {
        time_t now = time(NULL);
        struct tm *t = localtime(&now);
        while(!strftime((char *)ret.data(), ret.capacity(), "%Y:%m:%d %H:%M", t))
            ret.reserve(ret.capacity() ? ret.capacity() << 1: 16);
    }

}

Fix mistake of using size instead of capacity.


/* -*- mode:linux -*- */
/**
 * \file timeout.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-12-16
 */

#include <iostream>

#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

void alarm_action(int sig)
{
	cout << "No Solution" << endl
	     << "cost: infinity" << endl
	     << "length: infinity" << endl
	     << "wall_time: infinity" << endl
	     << "CPU_time: infinity" << endl
	     << "generated: infinity" << endl
	     << "expanded: infinity" << endl;

	exit(EXIT_SUCCESS);
}

void timeout(unsigned int sec)
{
	struct sigaction sa;

	sa.sa_handler = alarm_action;
	sigaction(SIGALRM, &sa, NULL);

	alarm(sec);
}

/* -*- mode:linux -*- */
/**
 * \file timeout.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-12-16
 */

#include <iostream>

#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

void alarm_action(int sig)
{
	cout << "No Solution" << endl
	     << "cost: infinity" << endl
	     << "length: infinity" << endl
	     << "wall_time: infinity" << endl
	     << "CPU_time: infinity" << endl
	     << "generated: infinity" << endl
	     << "expanded: infinity" << endl;

	exit(EXIT_SUCCESS);
}

void timeout(unsigned int sec)
{
	struct sigaction sa;

	sa.sa_flags = 0;
	sa.sa_sigaction = NULL;
	sa.sa_restorer = NULL;
	sa.sa_handler = alarm_action;
	sigfillset(&sa.sa_mask);
	sigaction(SIGALRM, &sa, NULL);

	alarm(sec);
}

Initialize the fields of the sigaction structure.


// https://github.com/KubaO/stackoverflown/tree/master/questions/styledbutton-20642553
#include <QPushButton>
#include <QHBoxLayout>
#include <QApplication>

int main(int argc, char *argv[])
{
   QApplication a{argc, argv};
   QWidget w;
   QHBoxLayout layout{&w};
   QPushButton button1{"Default"};
   button1.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
   layout.addWidget(&button1);
   QPushButton button2{"Styled"};
   button2.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
   button2.setStyleSheet(
            "* { border: 2px solid #8f8f91; border-radius: 12px; background-color: #d02020; }"
            "*:pressed { background-color: #f6f7fa; }");
   layout.addWidget(&button2);
   auto pal = w.palette();
   pal.setBrush(QPalette::Background, Qt::darkBlue);
   w.setPalette(pal);
   w.show();
   return a.exec();
}

Add github link, make code narrower.


#include "Arduboy.h"
#include "audio.h"

bool ArduboyAudio::audio_enabled = false;

void ArduboyAudio::on()
{
  audio_enabled = true;
}

bool ArduboyAudio::enabled()
{
  return audio_enabled;
}

void ArduboyAudio::off()
{
  audio_enabled = false;
}

void ArduboyAudio::saveOnOff()
{
  EEPROM.write(EEPROM_AUDIO_ON_OFF, audio_enabled);
}

void ArduboyAudio::begin()
{
  if (EEPROM.read(EEPROM_AUDIO_ON_OFF))
    on();
}

#include "Arduboy.h"
#include "audio.h"

bool ArduboyAudio::audio_enabled = false;

void ArduboyAudio::on()
{
  audio_enabled = true;
}

bool ArduboyAudio::enabled()
{
  return audio_enabled;
}

void ArduboyAudio::off()
{
  audio_enabled = false;
}

void ArduboyAudio::saveOnOff()
{
  EEPROM.update(EEPROM_AUDIO_ON_OFF, audio_enabled);
}

void ArduboyAudio::begin()
{
  if (EEPROM.read(EEPROM_AUDIO_ON_OFF))
    on();
}

Change EEPROM write() to update()


// Copyright 2015 Matt Heard
// http://mattheard.net
// matt@mattheard.net
// @mattheard

#include <iostream>
#include <string>

int main(int argc, char **argv) {
    const int expectedNumArgs = 2;
    if (argc != expectedNumArgs) {
        using std::string;
        const string cmdName = "DisplayImage";
        const string argsDesc = " <Image_Path>";
        std::cout << "Usage: " << cmdName << argsDesc << std::endl;
        return -1;
    }
    return 0;
}

// Copyright 2015 Matt Heard
// http://mattheard.net
// matt@mattheard.net
// @mattheard

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

int main(int argc, char **argv) {
    using std::string;
    const int expectedNumArgs = 2;
    if (argc != expectedNumArgs) {
        const string cmdName = "DisplayImage";
        const string argsDesc = " <Image_Path>";
        std::cout << "Usage: " << cmdName << argsDesc << std::endl;
        return -1;
    }
    const string filename = argv[1];
    const cv::Mat img = cv::imread(filename);
    if (!img.data) {
        const string err = "No image data";
        std::cerr << err << std::cout;
        return -1;
    }

    // The tutorial calls `namedWindow` and `imshow` to display the input image
    // in a GUI window, but as I'm currently running these tutorials on a
    // headless Raspberry Pi, I will not do that. Where future tutorials show
    // modified images, I will write them to files instead with `imwrite`, and
    // view them on a browser across my local network.

    return 0;
}

Read file and finish tutorial


/*
 * Behavior.cpp
 *
 *  Created on: Mar 25, 2014
 *      Author: user
 */

#include "Behavior.h"

Behavior::Behavior(Robot* robot)
{
	// TODO Auto-generated constructor stub
	_robot = robot;
}

Behavior* Behavior::addNextBehavior(Behavior* behavior)
{
	this->_nextBehaviors.push_back(behavior);
}

Behavior* Behavior::getNextBehavior()
{
	for (vector<Behavior*>::const_iterator iter = _nextBehaviors.begin(); iter != _nextBehaviors.end(); iter++)
	{
		Behavior* currentBehavior = *iter;
		if (currentBehavior->startCondition())
		{
			return currentBehavior;
		}
	}

	return NULL;
}

Behavior::~Behavior()
{
	for (vector<Behavior*>::const_iterator iter = _nextBehaviors.begin(); iter != _nextBehaviors.end(); iter++)
	{
		Behavior* currentBehavior = *iter;
		delete currentBehavior;
	}
}

/*
 * Behavior.cpp
 *
 *  Created on: Mar 25, 2014
 *      Author: user
 */

#include "Behavior.h"

Behavior::Behavior(Robot* robot)
{
	_robot = robot;
}

Behavior* Behavior::addNextBehavior(Behavior* behavior)
{
	this->_nextBehaviors.push_back(behavior);
}

Behavior* Behavior::getNextBehavior()
{
	for (vector<Behavior*>::const_iterator iter = _nextBehaviors.begin(); iter != _nextBehaviors.end(); iter++)
	{
		Behavior* currentBehavior = *iter;
		if (currentBehavior->startCondition())
		{
			return currentBehavior;
		}
	}

	return NULL;
}

Behavior::~Behavior()
{
}

Remove the free of behaviors to the plans


#include <agency/execution_policy.hpp>
#include <vector>

int sum(const std::vector<int>& data)
{
  using namespace agency;

  return bulk_invoke(con(data.size()),
    [&](concurrent_agent& self, std::vector<int>& scratch) -> single_result<int>
    {
      auto i = self.index();
      auto n = scratch.size();

      while(n > 1)
      {
        if(i < n/2)
        {
          scratch[i] += scratch[n - i - 1];
        }

        // wait for every agent in the group to reach this point
        self.wait();

        // cut the number of active agents in half
        n -= n/2;
      }

      // the first agent returns the result
      if(i == 0)
      {
        return scratch[0];
      }

      // all other agents return an ignored value
      return std::ignore;
    },
    share<0>(data)
  );
}

int main()
{
  size_t n = 10;

  std::vector<int> data(n, 1);

  auto result = sum(data);

  std::cout << "sum is " << result << std::endl;

  assert(result == n);

  std::cout << "OK" << std::endl;

  return 0;
}

#include <agency/execution_policy.hpp>
#include <vector>

int sum(const std::vector<int>& data)
{
  using namespace agency;

  return bulk_invoke(con(data.size()),
    [&](concurrent_agent& self, std::vector<int>& scratch) -> single_result<int>
    {
      auto i = self.index();
      auto n = scratch.size();

      while(n > 1)
      {
        if(i < n/2)
        {
          scratch[i] += scratch[n - i - 1];
        }

        // wait for every agent in the group to reach this point
        self.wait();

        // cut the number of active agents in half
        n -= n/2;
      }

      // the first agent returns the result
      if(i == 0)
      {
        return scratch[0];
      }

      // all other agents return an ignored value
      return std::ignore;
    },
    share(data)
  );
}

int main()
{
  size_t n = 10;

  std::vector<int> data(n, 1);

  auto result = sum(data);

  std::cout << "sum is " << result << std::endl;

  assert(result == n);

  std::cout << "OK" << std::endl;

  return 0;
}

Replace use of share<0>() with share()


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

#include "controls_plugin.h"
#include <QFontDatabase>
#include <QGuiApplication>
#include <QtQml>
#include "application_p.h"
#include "flatmesh.h"
#include "icon.h"

ControlsPlugin::ControlsPlugin(QObject *parent) : QQmlExtensionPlugin(parent)
{
}

void ControlsPlugin::registerTypes(const char *uri)
{
    Q_ASSERT(uri == QLatin1String("org.asteroid.controls"));

    QGuiApplication::setFont(QFont("Open Sans"));

    qmlRegisterType<Application_p>(uri, 1, 0, "Application_p");
    qmlRegisterType<FlatMesh>(uri, 1, 0, "FlatMesh");
    qmlRegisterType<Icon>(uri, 1, 0, "Icon");
}

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

#include "controls_plugin.h"
#include <QFontDatabase>
#include <QGuiApplication>
#include <QtQml>
#include "application_p.h"
#include "flatmesh.h"
#include "icon.h"

ControlsPlugin::ControlsPlugin(QObject *parent) : QQmlExtensionPlugin(parent)
{
}

void ControlsPlugin::registerTypes(const char *uri)
{
    Q_ASSERT(uri == QLatin1String("org.asteroid.controls"));

    QGuiApplication::setFont(QFont("Noto Sans"));

    qmlRegisterType<Application_p>(uri, 1, 0, "Application_p");
    qmlRegisterType<FlatMesh>(uri, 1, 0, "FlatMesh");
    qmlRegisterType<Icon>(uri, 1, 0, "Icon");
}

Change system font to Noto Sans.


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

alignas(double) void f(); // expected-error {{'alignas' attribute only applies to variables, data members and tag types}}
alignas(double) unsigned char c[sizeof(double)]; // expected-note {{previous}}
extern unsigned char c[sizeof(double)];
alignas(float) extern unsigned char c[sizeof(double)]; // expected-error {{different alignment}}

// RUN: %clang_cc1 -std=c++11 -verify %s -triple x86_64-linux-gnu

alignas(double) void f(); // expected-error {{'alignas' attribute only applies to variables, data members and tag types}}
alignas(double) unsigned char c[sizeof(double)]; // expected-note {{previous}}
extern unsigned char c[sizeof(double)];
alignas(float) extern unsigned char c[sizeof(double)]; // expected-error {{different alignment}}

Add a triple to this test so it passes for targets where alignof(double) really should be equal to alignof(float).


#include <iostream>

//Thomas' Prototypes

//Hannah's Prototypes

int atomic_distance (int x, int y, int z); //Kate's Prototype: defines atomic distance as combination of x, y, z coordinates

int (main)
{
using nedit file...
create new input "hannah's test changes"
}

#include <iostream>

//Thomas' Prototypes

//Hannah's Prototypes

int atomic_distance (int atom_dist_x, int atom_dist_y, int atom_dist_z); //Kate's Prototype: defines atomic distance as combination of x, y, z coordinates

int (main)
{
using nedit file...
create new input "hannah's test changes"
}

Update to Kate's First Prototype


//
// C++ Implementation: mailvieweventfilter
//
// Description:
//
//
// Author: Aron Boström <aron dot bostrom at gmail dot com>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include <QtDebug>

#include <QResizeEvent>
#include <QWidget>

#include "mailvieweventfilter.h"

MailViewEventFilter::MailViewEventFilter(QWidget *textedit, QWidget *viewport, QObject *parent) : QObject(parent), m_viewport(viewport), m_textedit(textedit)
{
}

MailViewEventFilter::~MailViewEventFilter()
{
}

bool MailViewEventFilter::eventFilter(QObject *obj, QEvent *event)
{
  if (event->type() == QEvent::Resize) {
    QResizeEvent *resizeEvent = static_cast<QResizeEvent *>(event);
    m_viewport->resize(resizeEvent->size());
    m_textedit->resize(resizeEvent->size());
    qDebug() << "TEST";
  }
  return QObject::eventFilter(obj, event);
}

#include "mailvieweventfilter.moc"

//
// C++ Implementation: mailvieweventfilter
//
// Description:
//
//
// Author: Aron Boström <aron dot bostrom at gmail dot com>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include <QtDebug>

#include <QResizeEvent>
#include <QWidget>

#include "mailvieweventfilter.h"

MailViewEventFilter::MailViewEventFilter(QWidget *textedit, QWidget *viewport, QObject *parent) : QObject(parent), m_viewport(viewport), m_textedit(textedit)
{
}

MailViewEventFilter::~MailViewEventFilter()
{
}

bool MailViewEventFilter::eventFilter(QObject *obj, QEvent *event)
{
  if (event->type() == QEvent::Resize) {
    QResizeEvent *resizeEvent = static_cast<QResizeEvent *>(event);
    m_viewport->resize(resizeEvent->size());
    m_textedit->resize(resizeEvent->size());
    qDebug() << "TEST";
    return true;
  }
  return QObject::eventFilter(obj, event);
}

#include "mailvieweventfilter.moc"

Return true if the event was handled.


// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t >%t.out 2>&1
// RUN: %clangxx_msan -m64 -O1 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

// Test that (no_sanitize_memory) functions propagate shadow.

// Note that at -O0 there is no report, because 'x' in 'f' is spilled to the
// stack, and then loaded back as a fully initialiazed value (due to
// no_sanitize_memory attribute).

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

__attribute__((noinline))
__attribute__((no_sanitize_memory))
int f(int x) {
  return x;
}

int main(void) {
  int x;
  int * volatile p = &x;
  int y = f(*p);
  // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
  // CHECK: {{#0 0x.* in main .*no_sanitize_memory_prop.cc:}}[[@LINE+1]]
  if (y)
    exit(0);
  return 0;
}

// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t >%t.out 2>&1
// RUN: %clangxx_msan -m64 -O1 %s -o %t && %run %t >%t.out 2>&1
// RUN: %clangxx_msan -m64 -O2 %s -o %t && %run %t >%t.out 2>&1
// RUN: %clangxx_msan -m64 -O3 %s -o %t && %run %t >%t.out 2>&1

// Test that (no_sanitize_memory) functions DO NOT propagate shadow.

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

__attribute__((noinline))
__attribute__((no_sanitize_memory))
int f(int x) {
  return x;
}

int main(void) {
  int x;
  int * volatile p = &x;
  int y = f(*p);
  if (y)
    exit(0);
  return 0;
}

Stop propagating shadow in blacklisted functions.


//===-- CPlusPlusLanguage.cpp --------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "CPlusPlusLanguage.h"

#include "lldb/Core/ConstString.h"
#include "lldb/Core/PluginManager.h"

using namespace lldb;
using namespace lldb_private;

void
CPlusPlusLanguage::Initialize()
{
    PluginManager::RegisterPlugin (GetPluginNameStatic(),
                                   "C++ Language",
                                   CreateInstance);
}

void
CPlusPlusLanguage::Terminate()
{
    PluginManager::UnregisterPlugin (CreateInstance);
}

lldb_private::ConstString
CPlusPlusLanguage::GetPluginNameStatic()
{
    static ConstString g_name("cplusplus");
    return g_name;
}

//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
lldb_private::ConstString
CPlusPlusLanguage::GetPluginName()
{
    return GetPluginNameStatic();
}

uint32_t
CPlusPlusLanguage::GetPluginVersion()
{
    return 1;
}

//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
Language *
CPlusPlusLanguage::CreateInstance (lldb::LanguageType language)
{
    switch (language)
    {
        case lldb::eLanguageTypeC_plus_plus:
        case lldb::eLanguageTypeC_plus_plus_03:
        case lldb::eLanguageTypeC_plus_plus_11:
        case lldb::eLanguageTypeC_plus_plus_14:
            return new CPlusPlusLanguage();
        default:
            return nullptr;
    }
}

//===-- CPlusPlusLanguage.cpp --------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "CPlusPlusLanguage.h"

#include "lldb/Core/ConstString.h"
#include "lldb/Core/PluginManager.h"

using namespace lldb;
using namespace lldb_private;

void
CPlusPlusLanguage::Initialize()
{
    PluginManager::RegisterPlugin (GetPluginNameStatic(),
                                   "C++ Language",
                                   CreateInstance);
}

void
CPlusPlusLanguage::Terminate()
{
    PluginManager::UnregisterPlugin (CreateInstance);
}

lldb_private::ConstString
CPlusPlusLanguage::GetPluginNameStatic()
{
    static ConstString g_name("cplusplus");
    return g_name;
}

//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
lldb_private::ConstString
CPlusPlusLanguage::GetPluginName()
{
    return GetPluginNameStatic();
}

uint32_t
CPlusPlusLanguage::GetPluginVersion()
{
    return 1;
}

//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
Language *
CPlusPlusLanguage::CreateInstance (lldb::LanguageType language)
{
    if (Language::LanguageIsCPlusPlus(language))
        return new CPlusPlusLanguage();
    return nullptr;
}

Use Language::LanguageIsCPlusPlus instead of doing the same switch over language


#include "environment.h"
#include <webdriverxx/client.h>
#include <gtest/gtest.h>

namespace test {

using namespace webdriverxx;

class TestClient : public ::testing::Test {
protected:
	static void SetUpTestCase() {
		client = new Client(GetWebDriverUrl());
	}

	static void TearDownTestCase() {
		delete client;
		client = 0;
	}

	static Client* client;
};

Client* TestClient::client = 0;

TEST_F(TestClient, GetsStatus) {
	picojson::object status = client->GetStatus();
	ASSERT_TRUE(status["build"].is<picojson::object>());
	ASSERT_TRUE(status["os"].is<picojson::object>());
}

TEST_F(TestClient, GetsSessions) {
	client->GetSessions();
}

TEST_F(TestClient, CreatesSession) {
 	Parameters params = GetParameters();
	client->CreateSession(params.required, params.desired);
}

} // namespace test

#include "environment.h"
#include <webdriverxx/client.h>
#include <gtest/gtest.h>

namespace test {

using namespace webdriverxx;

class TestClient : public ::testing::Test {
protected:
	static void SetUpTestCase() {
		client = new Client(GetWebDriverUrl());
	}

	static void TearDownTestCase() {
		delete client;
		client = 0;
	}

	static Client* client;
};

Client* TestClient::client = 0;

TEST_F(TestClient, GetsStatus) {
	picojson::object status = client->GetStatus();
	ASSERT_TRUE(status["build"].is<picojson::object>());
	ASSERT_TRUE(status["os"].is<picojson::object>());
}

TEST_F(TestClient, GetsSessions) {
	client->GetSessions();
}

TEST_F(TestClient, CreatesSession) {
 	Parameters params = GetParameters();
	client->CreateSession(params.desired, params.required);
}

} // namespace test

Fix wrong parameters order in client test


/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2013 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include <libcouchbase/debug.h>

/**
 * This is just an example program intended to show you how to use
 * the debug functionalities of libcouchbase
 */

static void dumpHttpCommand(void) {
    lcb_http_cmd_t http_cmd("/foo/bar", 8, NULL, 0, LCB_HTTP_METHOD_POST,
                            1, "applicaiton/json");
    std::cout << http_cmd << std::endl;
}

int main(void)
{
    dumpHttpCommand();
    exit(EXIT_SUCCESS);
}

/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2013 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include <libcouchbase/debug.h>
#include <cstdlib>

using namespace std;

/**
 * This is just an example program intended to show you how to use
 * the debug functionalities of libcouchbase
 */

static void dumpHttpCommand(void) {
    lcb_http_cmd_t http_cmd("/foo/bar", 8, NULL, 0, LCB_HTTP_METHOD_POST,
                            1, "applicaiton/json");
    cout << http_cmd << endl;
}

int main(void)
{
    dumpHttpCommand();
    exit(EXIT_SUCCESS);
}

Fix buildbreak for missing error code from cstdlib


#include "string_split.h"

namespace psz {

std::vector<std::string> SplitString(const std::string& str,
                                     const std::string& sep) {
  std::vector<std::string> results;
  size_t prev = 0;
  size_t pos = str.find(sep);
  while (pos != std::string::npos) {
    results.push_back(str.substr(prev, pos - prev));
    prev = pos + 1;
    pos = str.find(sep, prev);
  }
  results.push_back(str.substr(prev, str.length() - prev));
  return results;
}

std::vector<unsigned int> SplitStringAndParse(const std::string& str,
                                              const std::string& sep,
                                              int shift) {
  std::vector<unsigned int> result;
  for (const auto& val : SplitString(str, sep)) {
    if (val.empty()) {
      continue;
    }
    unsigned int val_u = std::stoul(val);
    // CHECK_LE(-shift, val_u);
    result.push_back(val_u + shift);
  }
  return result;
}

}  // namespace psz

#include "string_split.h"

namespace psz {

std::vector<std::string> SplitString(const std::string& str,
                                     const std::string& sep) {
  std::vector<std::string> results;
  size_t prev = 0;
  size_t pos = str.find(sep);
  while (pos != std::string::npos) {
    // TODO optimize!
    auto s = str.substr(prev, pos - prev);
    if (!s.empty()) {
      results.push_back(s);
    }
    prev = pos + 1;
    pos = str.find(sep, prev);
  }
  results.push_back(str.substr(prev, str.length() - prev));
  return results;
}

std::vector<unsigned int> SplitStringAndParse(const std::string& str,
                                              const std::string& sep,
                                              int shift) {
  std::vector<unsigned int> result;
  for (const auto& val : SplitString(str, sep)) {
    if (val.empty()) {
      continue;
    }
    unsigned int val_u = std::stoul(val);
    // CHECK_LE(-shift, val_u);
    result.push_back(val_u + shift);
  }
  return result;
}

}  // namespace psz

Fix empty string being added to string vector.


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

#include <Windows.h>
#include "Application.h"

int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	ouzel::Application* application = new ouzel::Application();
	//TODO: create main window
	//TODO: attach Renderer's view to this window
	//TODO: run main loop

	return 0;
}

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

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

int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	ouzel::Application* application = new ouzel::Application();
	//TODO: create main window
	//TODO: attach Renderer's view to this window
	//TODO: run main loop

	return 0;
}

Fix the case of windows.h for consistency


#include "../src/logger.h"

#define CATCH_CONFIG_MAIN
#include <lightstep/catch/catch.hpp>

using namespace lightstep;

TEST_CASE("logger") {
  LogLevel logged_level = LogLevel::off;
  std::string logged_message;
  Logger logger{[&](LogLevel level, opentracing::string_view message) {
    logged_level = level;
    logged_message = message;
  }};
  logger.set_level(LogLevel::warn);

  SECTION(
      "If log level is less than the logger's level, the message is ignored") {
    logger.Info("t");
    CHECK(logged_message.empty());
  }

  SECTION(
      "If log level is greater than or equal to the logger's message, the "
      "logger sink receive's the message") {
    logger.Warn("t1");
    CHECK(logged_level == LogLevel::warn);
    CHECK(logged_message == "t1");

    logger.Error("t2");
    CHECK(logged_level == LogLevel::error);
    CHECK(logged_message == "t2");
  }
}

#include "../src/logger.h"

#define CATCH_CONFIG_MAIN
#include <lightstep/catch/catch.hpp>

using namespace lightstep;

TEST_CASE("logger") {
  LogLevel logged_level = LogLevel::off;
  std::string logged_message;
  Logger logger{[&](LogLevel level, opentracing::string_view message) {
    logged_level = level;
    logged_message = message;
  }};
  logger.set_level(LogLevel::warn);

  SECTION(
      "If log level is less than the logger's level, the message is ignored") {
    logger.Info("t");
    CHECK(logged_message.empty());
  }

  SECTION(
      "If log level is greater than or equal to the logger's message, the "
      "logger sink receive's the message") {
    logger.Warn("t1");
    CHECK(logged_level == LogLevel::warn);
    CHECK(logged_message == "t1");

    logger.Error("t2");
    CHECK(logged_level == LogLevel::error);
    CHECK(logged_message == "t2");
  }

  SECTION("Multiple arguments are concatenated together") {
    logger.Warn("a", "bc");
    CHECK(logged_message == "abc");

    logger.Warn("a", "bc", 123);
    CHECK(logged_message == "abc123");
  }
}

Add concatenation test to logger.


//===--- ArgumentsAdjusters.cpp - Command line arguments adjuster ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains definitions of classes which implement ArgumentsAdjuster
// interface.
//
//===----------------------------------------------------------------------===//

#include "clang/Tooling/ArgumentsAdjusters.h"

namespace clang {
namespace tooling {

void ArgumentsAdjuster::anchor() {
}

/// Add -fsyntax-only option to the commnand line arguments.
CommandLineArguments
ClangSyntaxOnlyAdjuster::Adjust(const CommandLineArguments &Args) {
  CommandLineArguments AdjustedArgs = Args;
  // FIXME: Remove options that generate output.
  AdjustedArgs.push_back("-fsyntax-only");
  return AdjustedArgs;
}

} // end namespace tooling
} // end namespace clang

//===--- ArgumentsAdjusters.cpp - Command line arguments adjuster ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains definitions of classes which implement ArgumentsAdjuster
// interface.
//
//===----------------------------------------------------------------------===//

#include "clang/Tooling/ArgumentsAdjusters.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/StringRef.h"

namespace clang {
namespace tooling {

void ArgumentsAdjuster::anchor() {
}

/// Add -fsyntax-only option to the commnand line arguments.
CommandLineArguments
ClangSyntaxOnlyAdjuster::Adjust(const CommandLineArguments &Args) {
  CommandLineArguments AdjustedArgs;
  for (size_t i = 0, e = Args.size(); i != e; ++i) {
    StringRef Arg = Args[i];
    // FIXME: Remove options that generate output.
    if (!Arg.startswith("-fcolor-diagnostics") &&
        !Arg.startswith("-fdiagnostics-color"))
      AdjustedArgs.push_back(Args[i]);
  }
  AdjustedArgs.push_back("-fsyntax-only");
  return AdjustedArgs;
}

} // end namespace tooling
} // end namespace clang

Make clang tools ignore -fcolor-diagnostics and -fdiagnostics-color retrieved from the compilation database.


#include "ui/region_picker.hpp"

int main()
{
	EasyGIF::UI::RegionPicker picker(false);
	picker.Activate();
	while(picker.IsRunning())
	{
		picker.UpdateEvents();
		picker.ProcessInput();
		picker.Draw();
	}

	return 0;
}

#include "img/image_frame.hpp"
#include "img/image_grabber.hpp"
#include "img/image_saver.hpp"
#include "ui/region_picker.hpp"
#include <unistd.h>

int main()
{
	EasyGIF::UI::RegionPicker picker(false);
	EasyGIF::ImageFrame frame;
	EasyGIF::ImageGrabber grabber;
	EasyGIF::ImageSaver saver;
	picker.Activate();
	while(picker.IsRunning())
	{
		picker.UpdateEvents();
		if(picker.IsConfirmed())
		{
			::EasyGIF::Utility::Rectangle rect = picker.GetRect();
			picker.Shutdown();
			sleep(5); // let X close the window
			frame = grabber.Grab(rect);
			saver.LoadData(frame);
			saver.Save("./test_picker.png");
		}
		else
		{
			picker.ProcessInput();
			picker.Draw();
		}
	}

	return 0;
}

Test for saving a selected region to a file


#include <cassert>
#include <iostream>

#include "ColorFinder.hpp"

int main() {
  constexpr ColorFinder::Color c{0x82, 0x12, 0x18};
  constexpr auto name = getClosestColorName(c);
  std::cout << name << std::endl;
  return 0;
}

#include <cassert>
#include <iostream>

#include "ColorFinder.hpp"

int main() {
  constexpr ColorFinder::Color c{0x82, 0x12, 0x18};
  constexpr auto name = getClosestColorName(c);
  static_assert(name == "Falu Red", "Something went wrong");
  std::cout << name << std::endl;
  return 0;
}

Add static_assert to check evaluated value


#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>

#include <evm2wasm.h>

using namespace std;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " <EVM file>" << endl;
        return 1;
    }

    ifstream input(argv[1]);
    if (!input.is_open()) {
        cerr << "File not found: " << argv[1] << endl;
        return 1;
    }

    string str(
        (std::istreambuf_iterator<char>(input)),
        std::istreambuf_iterator<char>()
    );

    cout << evm2wasm::evm2wasm(str) << endl;

    return 0;
}

#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>

#include <evm2wasm.h>

using namespace std;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
        return 1;
    }

    bool wast = false;
    if (argc == 3) {
        wast = (string(argv[2]) == "--wast");
        if (!wast) {
            cerr << "Usage: " << argv[0] << " <EVM file> [--wast]" << endl;
            return 1;
        }
    }

    ifstream input(argv[1]);
    if (!input.is_open()) {
        cerr << "File not found: " << argv[1] << endl;
        return 1;
    }

    string str(
        (std::istreambuf_iterator<char>(input)),
        std::istreambuf_iterator<char>()
    );

    if (wast) {
        cout << evm2wasm::evm2wast(str) << endl;
    } else {
        cout << evm2wasm::evm2wasm(str) << endl;
    }

    return 0;
}

Add --wast option to evm2wasm CLI


#include "Genes/Freedom_To_Move_Gene.h"

#include <string>

#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"

double Freedom_To_Move_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept
{
    static auto initial_score = double(Board().legal_moves().size());
    if(perspective == board.whose_turn())
    {
        return board.legal_moves().size()/initial_score;
    }
    else
    {
        return board.previous_moves_count()/initial_score;
    }
}

std::string Freedom_To_Move_Gene::name() const noexcept
{
    return "Freedom to Move Gene";
}

#include "Genes/Freedom_To_Move_Gene.h"

#include <string>

#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"

double Freedom_To_Move_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept
{
    static const auto initial_score = double(Board().legal_moves().size());
    if(perspective == board.whose_turn())
    {
        return board.legal_moves().size()/initial_score;
    }
    else
    {
        return board.previous_moves_count()/initial_score;
    }
}

std::string Freedom_To_Move_Gene::name() const noexcept
{
    return "Freedom to Move Gene";
}

Add const to constant value


#include "mainwindow.h"
#include <QApplication>
#include <QDialog>
#include <QGridLayout>
#include <QLayout>
#include <QDebug>

#include "application.h"

int main(int argc, char *argv[])
{
	QCoreApplication::setOrganizationName("JASP");
	QCoreApplication::setOrganizationDomain("jasp-stats.org");
	QCoreApplication::setApplicationName("JASP");

	Application a(argc, argv);
	MainWindow w;

    w.show();

	if (argc > 1)
		w.open(QString(argv[1]));

    return a.exec();
}

#include "mainwindow.h"
#include <QApplication>
#include <QDialog>
#include <QGridLayout>
#include <QLayout>
#include <QDebug>

#include "application.h"

int main(int argc, char *argv[])
{
	QCoreApplication::setOrganizationName("JASP");
	QCoreApplication::setOrganizationDomain("jasp-stats.org");
	QCoreApplication::setApplicationName("JASP");

	Application a(argc, argv);
	MainWindow w;

	w.show();

	QStringList args = QApplication::arguments();

	if (args.length() > 1)
		w.open(args.at(1));

    return a.exec();
}

Fix to unicode cmd line argument handling


/*
  Copyright (c) 2014 DataStax

  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 "logger.hpp"

namespace cass {

void default_log_callback(cass_uint64_t time_ms, CassLogLevel severity,
                          CassString message, void* data) {
  // TODO(mpenick): Format time
  fprintf(stderr, "%llu [%s]: %.*s\n", time_ms, cass_log_level_string(severity),
          static_cast<int>(message.length), message.data);
}
}

/*
  Copyright (c) 2014 DataStax

  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 "logger.hpp"

namespace cass {

void default_log_callback(cass_uint64_t time_ms, CassLogLevel severity,
                          CassString message, void* data) {
  fprintf(stderr, "%u.%03u [%s]: %.*s\n",
          (unsigned int)(time_ms/1000), (unsigned int)(time_ms % 1000),
          cass_log_level_string(severity),
          static_cast<int>(message.length), message.data);
}
}

Fix to work with different definitions of cass_uint64_t


#include "PrimaryTreeIndex.h"

void PrimaryTreeIndex::buildIndex(Table & table, int column) {
    int rowno = 0;
    for(auto &currentRow : table) {
        index.emplace(currentRow[column], rowno++);
    }
}

int PrimaryTreeIndex::size() const {
    return index.size();
}

int PrimaryTreeIndex::exactMatch(const std::string& key) const {
    auto it = index.find(key);
    return it == index.end() ? -1 : it->second;
}

int PrimaryTreeIndex::bestMatch(const std::string& key) const {
    auto bounds = index.equal_range(key);
    auto lower_bound = bounds.first;
    auto upper_bound = bounds.second;

    if(lower_bound != index.end() && lower_bound->first == key) {
        return lower_bound->second;
    } else {
        std::map<std::string,int>::const_reverse_iterator rbegin(upper_bound);
        std::map<std::string,int>::const_reverse_iterator rend(index.begin());
        for(auto it = rbegin; it!=rend; it++) {
            auto idx = key.find(it->first);
            if(idx != std::string::npos) {
                return it->second;
            }
        }
    }

    return -1;
}

#include "PrimaryTreeIndex.h"

void PrimaryTreeIndex::buildIndex(Table & table, int column) {
    int rowno = 0;
    for(auto &currentRow : table) {
        index.emplace(currentRow[column], rowno++);
    }
}

int PrimaryTreeIndex::size() const {
    return index.size();
}

int PrimaryTreeIndex::exactMatch(const std::string& key) const {
    auto it = index.find(key);
    return it == index.end() ? -1 : it->second;
}

int PrimaryTreeIndex::bestMatch(const std::string& key) const {
    auto lower_bound = index.lower_bound(key);
    if(lower_bound != index.end() && lower_bound->first == key) {
        return lower_bound->second;
    } else {
        std::map<std::string,int>::const_reverse_iterator rbegin(lower_bound);
        std::map<std::string,int>::const_reverse_iterator rend(index.begin());
        for(auto it = rbegin; it!=rend; it++) {
            auto idx = key.find(it->first);
            if(idx != std::string::npos) {
                return it->second;
            }
        }
    }

    return -1;
}

Simplify bestMatch code as lower_bound = upper_bound when no exact match found


#include <iostream>
#include <memory>

#include <windows.h>

#include <chewingwrapper.hpp>

int main()
{
    SetEnvironmentVariable("CHEWING_PATH", CHEWING_PATH);
    SetEnvironmentVariable("CHEWING_USER_PATH", CHEWING_USER_PATH);

    const wchar_t EXPECT[] = { 0x6e2c, 0x8a66, 0 /* 測試 */ };

    ChewingWrapper ctx;

    ctx.handle_default('h');
    ctx.handle_default('k');
    ctx.handle_default('4');
    ctx.handle_default('g');
    ctx.handle_default('4');
    ctx.handle_enter();

    if (!ctx.has_commit()) {
        std::cerr << "has_commit shall return true" << std::endl;
        return -1;
    }

    std::unique_ptr<wchar_t> commit_string(ctx.get_commit());
    if (wcscmp(commit_string.get(), EXPECT)) {
        std::cerr << "commit_string shall return " << EXPECT << std::endl;
        return -1;
    }

    return 0;
}

#include <iostream>
#include <memory>

#include <windows.h>

#include <chewingwrapper.hpp>

int main()
{
    // XXX: Use SetEnvironmentVariableA here will cause crash in Visual Studio.
    _putenv("CHEWING_PATH="CHEWING_PATH);
    _putenv("CHEWING_USER_PATH="CHEWING_USER_PATH);

    const wchar_t EXPECT[] = { 0x6e2c, 0x8a66, 0 /* 測試 */ };

    ChewingWrapper ctx;

    ctx.handle_default('h');
    ctx.handle_default('k');
    ctx.handle_default('4');
    ctx.handle_default('g');
    ctx.handle_default('4');
    ctx.handle_enter();

    if (!ctx.has_commit()) {
        std::cerr << "has_commit shall return true" << std::endl;
        return -1;
    }

    std::unique_ptr<wchar_t> commit_string(ctx.get_commit());
    if (wcscmp(commit_string.get(), EXPECT)) {
        std::cerr << "commit_string shall return " << EXPECT << std::endl;
        return -1;
    }

    return 0;
}

Use _putenv instead of SetEnvironmentVariable


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

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

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

namespace mate {

namespace internal {

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

}  // namespace internal

}  // namespace mate

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

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

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

namespace mate {

namespace internal {

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

}  // namespace internal

}  // namespace mate

Fix crash when emitting unhandled error on native EventEmitter


// RUN: %clang_cc1 -std=c++17 -emit-llvm -fchar8_t -triple x86_64-linux %s -o - | FileCheck %s

// CHECK: define void @_Z1fDu(
void f(char8_t c) {}

// CHECK: define void @_Z1gIiEvDTplplcvT__ELA4_KDuELDu114EE
template<typename T> void g(decltype(T() + u8"foo" + u8'r')) {}
template void g<int>(const char8_t*);

// RUN: %clang_cc1 -std=c++17 -emit-llvm -fchar8_t -triple x86_64-linux %s -o - | FileCheck %s

// CHECK: define void @_Z1fDu(
void f(char8_t c) {}

// CHECK: define weak_odr void @_Z1gIiEvDTplplcvT__ELA4_KDuELDu114EE
template<typename T> void g(decltype(T() + u8"foo" + u8'r')) {}
template void g<int>(const char8_t*);

Fix up r331244 - the emitted definition is weak_odr linkage. Should get the build bots to healthy again without a full revert. As the functionality added has nothing to do with linkage this seems unlikely to represent a deep or interesting bug in the patch.


#include <util/maker.hpp>
#include <iostream>
#include <iomanip>

void show_help() noexcept {
    std::cout << "usage: shinobi [options]\n\n";
    std::cout << std::left << '\t' << std::setw(25) << "-h, --help" << "show this message and exit" << '\n';
    std::cout << std::left << '\t' << std::setw(25) << "-d, --debug" << "create debug ninja file" << '\n';
    std::cout << std::left << '\t' << std::setw(25) << "-r, --release" << "create release ninja file (default)" << '\n';
}

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

    std::ofstream out("build.ninja");
    util::maker creator{out};

    std::set<std::string> args{argv, argv + argc};

    if(args.count("-h") || args.count("--help")) {
        show_help();
        return 0;
    }

    if(args.count("-d") || args.count("--debug")) {
        creator.debug(true);
    }

    if(args.count("-r") || args.count("--release")) {
        creator.debug(false);
    }

    creator.regular_parse();
}

#include <util/maker.hpp>
#include <iostream>
#include <iomanip>
#include <map>

void show_help() noexcept {
    std::cout << "usage: shinobi [options] [--] [filename]\n\n";
    std::cout << std::left << '\t' << std::setw(25) << "-h, --help" << "show this message and exit" << '\n';
    std::cout << std::left << '\t' << std::setw(25) << "-d, --debug" << "create debug ninja file" << '\n';
    std::cout << std::left << '\t' << std::setw(25) << "-r, --release" << "create release ninja file (default)" << '\n';
}

int main(int argc, char* argv[]) {
    std::string filename("build.ninja");
    std::map<std::string, int> args;
    for(int i = 0; i < argc; ++i) {
        args.emplace(argv[i], i);
    }

    if(args.count("-h") || args.count("--help")) {
        show_help();
        return 0;
    }

    auto it = args.find("--");

    if(it != args.end()) {
        if(argv[it->second + 1] != nullptr) {
            filename = std::string(argv[it->second + 1]) + ".ninja";
        }
    }

    std::ofstream out(filename);
    util::maker creator{out};

    if(args.count("-d") || args.count("--debug")) {
        creator.debug(true);
    }

    if(args.count("-r") || args.count("--release")) {
        creator.debug(false);
    }

    creator.regular_parse();
}

Add support for custom filenames with the command line