#include <nekit/deps/easylogging++.h>
#include <nekit/stream_coder/detail/stream_coder_manager.h>
#include <nekit/stream_coder/stream_processor.h>

namespace nekit {
namespace stream_coder {

template <class T>
ActionRequest StreamProcessor<T>::Negotiate() {
  return impl_->Negotiate();
}

template <class T>
BufferReserveSize StreamProcessor<T>::InputReserve() {
  return impl_->InputReserve();
}

template <class T>
ActionRequest StreamProcessor<T>::Input(utils::Buffer& buffer) {
  return impl_->Input(buffer);
}

template <class T>
BufferReserveSize StreamProcessor<T>::OutputReserve() {
  return impl_->OutputReserve();
}

template <class T>
ActionRequest StreamProcessor<T>::Output(utils::Buffer& buffer) {
  return impl_->Output(buffer);
}

template <class T>
utils::Error StreamProcessor<T>::GetLatestError() const {
  return impl_->GetLatestError();
}

template <class T>
bool StreamProcessor<T>::forwarding() const {
  return impl_->forwarding();
}

template <class T>
T* StreamProcessor<T>::implemention() {
  return impl_;
}

}  // namespace stream_coder
}  // namespace nekit

#include <nekit/deps/easylogging++.h>
#include <nekit/stream_coder/detail/stream_coder_manager.h>
#include <nekit/stream_coder/stream_processor.h>

namespace nekit {
namespace stream_coder {

template <class T>
StreamProcessor<T>::StreamProcessor() {
  impl_ = new T();
}

template <class T>
StreamProcessor<T>::~StreamProcessor() {
  delete impl_;
}

template <class T>
ActionRequest StreamProcessor<T>::Negotiate() {
  return impl_->Negotiate();
}

template <class T>
BufferReserveSize StreamProcessor<T>::InputReserve() {
  return impl_->InputReserve();
}

template <class T>
ActionRequest StreamProcessor<T>::Input(utils::Buffer& buffer) {
  return impl_->Input(buffer);
}

template <class T>
BufferReserveSize StreamProcessor<T>::OutputReserve() {
  return impl_->OutputReserve();
}

template <class T>
ActionRequest StreamProcessor<T>::Output(utils::Buffer& buffer) {
  return impl_->Output(buffer);
}

template <class T>
utils::Error StreamProcessor<T>::GetLatestError() const {
  return impl_->GetLatestError();
}

template <class T>
bool StreamProcessor<T>::forwarding() const {
  return impl_->forwarding();
}

template <class T>
T* StreamProcessor<T>::implemention() {
  return impl_;
}

}  // namespace stream_coder
}  // namespace nekit

Add constructor and destructor for StreamProcessor template


//===- MCFixup.cpp - Assembly Fixup Implementation ------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/MC/MCFixup.h"
using namespace llvm;

static MCSymbolRefExpr::VariantKind getAccessVariant(const MCExpr *Expr) {
  switch (Expr->getKind()) {
  case MCExpr::Unary: {
    const MCUnaryExpr *UE = cast<MCUnaryExpr>(Expr);
    assert(getAccessVariant(UE->getSubExpr()) == MCSymbolRefExpr::VK_None);
    return MCSymbolRefExpr::VK_None;
  }

  case MCExpr::Target:
    llvm_unreachable("unsupported");

  case MCExpr::Constant:
    return MCSymbolRefExpr::VK_None;

  case MCExpr::SymbolRef: {
    const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(Expr);
    return SRE->getKind();
  }
  case MCExpr::Binary: {
    const MCBinaryExpr *ABE = cast<MCBinaryExpr>(Expr);
    assert(getAccessVariant(ABE->getRHS()) == MCSymbolRefExpr::VK_None);
    return getAccessVariant(ABE->getLHS());
  }
  }
  llvm_unreachable("unknown MCExpr kind");
}

MCSymbolRefExpr::VariantKind MCFixup::getAccessVariant() const {
  return ::getAccessVariant(getValue());
}

//===- MCFixup.cpp - Assembly Fixup Implementation ------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/MC/MCFixup.h"
using namespace llvm;

static MCSymbolRefExpr::VariantKind getAccessVariant(const MCExpr *Expr) {
  switch (Expr->getKind()) {
  case MCExpr::Unary: {
    assert(getAccessVariant(cast<MCUnaryExpr>(Expr)->getSubExpr()) ==
           MCSymbolRefExpr::VK_None);
    return MCSymbolRefExpr::VK_None;
  }

  case MCExpr::Target:
    llvm_unreachable("unsupported");

  case MCExpr::Constant:
    return MCSymbolRefExpr::VK_None;

  case MCExpr::SymbolRef: {
    const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(Expr);
    return SRE->getKind();
  }
  case MCExpr::Binary: {
    const MCBinaryExpr *ABE = cast<MCBinaryExpr>(Expr);
    assert(getAccessVariant(ABE->getRHS()) == MCSymbolRefExpr::VK_None);
    return getAccessVariant(ABE->getLHS());
  }
  }
  llvm_unreachable("unknown MCExpr kind");
}

MCSymbolRefExpr::VariantKind MCFixup::getAccessVariant() const {
  return ::getAccessVariant(getValue());
}

Remove a variable from r206192 that is only used in an assert.


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

#include "chrome/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
}

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

#include "chrome/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
  // To make wcstombs/mbstowcs work in a renderer.
  const char* locale = setlocale(LC_ALL, "");
  LOG_IF(WARNING, locale == NULL) << "setlocale failed.";
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  // The sandbox is started in the zygote process: zygote_main_linux.cc
  // http://code.google.com/p/chromium/wiki/LinuxSUIDSandbox
}

Call setlocale(LC_ALL, "") in a renderer process for subsequent calls to SysNativeMBToWide and WideToSysNativeMB (that use mbstowcs and wcstombs) to work correctly.


#include "surface.h"

namespace batoid {

    #pragma omp declare target

    Surface::Surface() :
        _devPtr(nullptr)
    {}

    Surface::~Surface() {}

    bool Surface::timeToIntersect(
        double x, double y, double z,
        double vx, double vy, double vz,
        double& dt
    ) const {
        // The better the initial estimate of dt, the better this will perform
        double rPx = x+vx*dt;
        double rPy = y+vy*dt;
        double rPz = z+vz*dt;

        double sz = sag(rPx, rPy);
        // Always do exactly 10 iterations.  GPUifies better this way.
        for (int iter=0; iter<10; iter++) {
            // repeatedly intersect plane tangent to surface at (rPx, rPy, sz) with ray
            double nx, ny, nz;
            normal(rPx, rPy, nx, ny, nz);
            dt = (rPx-x)*nx + (rPy-y)*ny + (sz-z)*nz;
            dt /= (nx*vx + ny*vy + nz*vz);
            rPx = x+vx*dt;
            rPy = y+vy*dt;
            rPz = z+vz*dt;
            sz = sag(rPx, rPy);
        }
        return (std::abs(sz-rPz) < 1e-12);
    }

    #pragma omp end declare target

}

#include "surface.h"

namespace batoid {

    #pragma omp declare target

    Surface::Surface() :
        _devPtr(nullptr)
    {}

    Surface::~Surface() {}

    bool Surface::timeToIntersect(
        double x, double y, double z,
        double vx, double vy, double vz,
        double& dt
    ) const {
        // The better the initial estimate of dt, the better this will perform
        double rPx = x+vx*dt;
        double rPy = y+vy*dt;
        double rPz = z+vz*dt;

        double sz = sag(rPx, rPy);
        // Always do exactly 5 iterations.  GPUifies better this way.
        // Unit tests pass (as of 20/10/13) with just 3 iterations.
        for (int iter=0; iter<5; iter++) {
            // repeatedly intersect plane tangent to surface at (rPx, rPy, sz) with ray
            double nx, ny, nz;
            normal(rPx, rPy, nx, ny, nz);
            dt = (rPx-x)*nx + (rPy-y)*ny + (sz-z)*nz;
            dt /= (nx*vx + ny*vy + nz*vz);
            rPx = x+vx*dt;
            rPy = y+vy*dt;
            rPz = z+vz*dt;
            sz = sag(rPx, rPy);
        }
        return (std::abs(sz-rPz) < 1e-12);
    }

    #pragma omp end declare target

}

Reduce iterations in generic intersection alg


/*
 * 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 "JSITracing.h"

namespace facebook {
namespace jsi {
void addNativeTracingHooks(Runtime &rt) {
  assert(false && "unimplemented");
}
} // namespace jsi
} // 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 "JSITracing.h"

namespace facebook {
namespace jsi {
void addNativeTracingHooks(Runtime &rt) {
  // Unimplemented
}
} // namespace jsi
} // namespace facebook

Remove unconditional assert from addNativeTracingHooks. Do nothing instead.


//===----------------------------------------------------------------------===//
//
//                     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.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// <thread>

// class thread

// void detach();

#include <thread>
#include <new>
#include <cstdlib>
#include <cassert>

class G
{
    int alive_;
public:
    static int n_alive;
    static bool op_run;

    G() : alive_(1) {++n_alive;}
    G(const G& g) : alive_(g.alive_) {++n_alive;}
    ~G() {alive_ = 0; --n_alive;}

    void operator()()
    {
        assert(alive_ == 1);
        assert(n_alive >= 1);
        op_run = true;
    }
};

int G::n_alive = 0;
bool G::op_run = false;

int main()
{
    {
        std::thread t0((G()));
        assert(t0.joinable());
        t0.detach();
        assert(!t0.joinable());
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
        assert(G::op_run);
        assert(G::n_alive == 0);
    }
}

//===----------------------------------------------------------------------===//
//
//                     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.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads

// <thread>

// class thread

// void detach();

#include <thread>
#include <atomic>
#include <cassert>

std::atomic_bool done = ATOMIC_VAR_INIT(false);

class G
{
    int alive_;
    bool done_;
public:
    static int n_alive;
    static bool op_run;

    G() : alive_(1), done_(false)
    {
        ++n_alive;
    }

    G(const G& g) : alive_(g.alive_), done_(false)
    {
        ++n_alive;
    }
    ~G()
    {
        alive_ = 0;
        --n_alive;
        if (done_) done = true;
    }

    void operator()()
    {
        assert(alive_ == 1);
        assert(n_alive >= 1);
        op_run = true;
        done_ = true;
    }
};

int G::n_alive = 0;
bool G::op_run = false;

int main()
{
    {
        G g;
        std::thread t0(g);
        assert(t0.joinable());
        t0.detach();
        assert(!t0.joinable());
        while (!done) {}
        assert(G::op_run);
        assert(G::n_alive == 1);
    }
    assert(G::n_alive == 0);
}

Fix race condition in thread test.


#include <object/centralized-slots.hh>

namespace object
{
  CentralizedSlots::content_type*
    CentralizedSlots::content_ =
    new CentralizedSlots::content_type();

  CentralizedSlots::loc_index_type&
    CentralizedSlots::loc_index_ =
    CentralizedSlots::content_->get<0>();

  CentralizedSlots::obj_index_type&
    CentralizedSlots::obj_index_ =
    CentralizedSlots::content_->get<1>();
}

#include <object/centralized-slots.hh>

namespace object
{
  // Allocated dynamically to avoid static destruction order
  // fiasco. Some objects could indeed be destroyed after the hash
  // table is destroyed.
  CentralizedSlots::content_type*
    CentralizedSlots::content_ =
    new CentralizedSlots::content_type();

  CentralizedSlots::loc_index_type&
    CentralizedSlots::loc_index_ =
    CentralizedSlots::content_->get<0>();

  CentralizedSlots::obj_index_type&
    CentralizedSlots::obj_index_ =
    CentralizedSlots::content_->get<1>();
}

Comment why the slots table is allocated on the heap.


// $Header: /home/cvsroot/yaz++/zoom/zrs.cpp,v 1.5 2003-07-02 10:25:13 adam Exp $

// Z39.50 Result Set class

#include "zoom.h"

namespace ZOOM {
    resultSet::resultSet(connection &c, const query &q) : owner(c) {
	ZOOM_connection yazc = c._getYazConnection();
	rs = ZOOM_connection_search(yazc, q._getYazQuery());
	int errcode;
	const char *errmsg;	// unused: carries same info as `errcode'
	const char *addinfo;

	if ((errcode = ZOOM_connection_error(yazc, &errmsg, &addinfo)) != 0) {
	    throw bib1Exception(errcode, addinfo);
	}
    }

    resultSet::~resultSet() {
	ZOOM_resultset_destroy(rs);
    }

    std::string resultSet::option(const std::string &key) const {
	return ZOOM_resultset_option_get(rs, key.c_str());
    }

    bool resultSet::option(const std::string &key, const std::string &val) {
      ZOOM_resultset_option_set(rs, key.c_str(), val.c_str());
	return true;
    }

    size_t resultSet::size() const {
	return ZOOM_resultset_size(rs);
    }
}

// $Header: /home/cvsroot/yaz++/zoom/zrs.cpp,v 1.6 2003-09-22 13:04:52 mike Exp $

// Z39.50 Result Set class

#include "zoom.h"

namespace ZOOM {
    resultSet::resultSet(connection &c, const query &q) : owner(c) {
	ZOOM_connection yazc = c._getYazConnection();
	rs = ZOOM_connection_search(yazc, q._getYazQuery());
	int errcode;
	const char *errmsg;	// unused: carries same info as `errcode'
	const char *addinfo;

	if ((errcode = ZOOM_connection_error(yazc, &errmsg, &addinfo)) != 0) {
	    ZOOM_resultset_destroy(rs);
	    throw bib1Exception(errcode, addinfo);
	}
    }

    resultSet::~resultSet() {
	ZOOM_resultset_destroy(rs);
    }

    std::string resultSet::option(const std::string &key) const {
	return ZOOM_resultset_option_get(rs, key.c_str());
    }

    bool resultSet::option(const std::string &key, const std::string &val) {
      ZOOM_resultset_option_set(rs, key.c_str(), val.c_str());
	return true;
    }

    size_t resultSet::size() const {
	return ZOOM_resultset_size(rs);
    }
}

Destroy half-created ZOOM-C result-set on failure, thanks to Phil Dennis <phil@booksys.com>


Remove superfluous setName(mName) from the c'tor.


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

#include "stdafx.h"

int main()
{
	std::ifstream Input("Input.txt");

	if (!Input.is_open())
	{
		std::cout << "Error opening File!" << std::endl;
		return 0;
	}

	std::string Line;
	uint64_t WrappingPaper = 0;

	while (std::getline(Input, Line))
	{
		std::stringstream LineStream(Line);

		uint32_t l;
		uint32_t h;
		uint32_t w;

		LineStream >> l;
		LineStream.get();
		LineStream >> h;
		LineStream.get();
		LineStream >> w;

		uint32_t Side1 = l * w;
		uint32_t Side2 = h * w;
		uint32_t Side3 = l * h;

		uint32_t SmallestSide = std::min({ Side1, Side2, Side3 });

		WrappingPaper += SmallestSide + 2 * Side1 + 2 * Side2 + 2 * Side3;
	}

	Input.close();

	std::cout << "Wrapping Paper: " << WrappingPaper << std::endl;

	system("pause");

    return 0;
}

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

#include "stdafx.h"

int main()
{
	std::ifstream Input("Input.txt");

	if (!Input.is_open())
	{
		std::cout << "Error opening File!" << std::endl;
		return 0;
	}

	std::string Line;
	uint64_t WrappingPaper = 0;
	uint64_t Ribbon = 0;

	while (std::getline(Input, Line))
	{
		std::stringstream LineStream(Line);

		uint32_t l;
		uint32_t h;
		uint32_t w;

		LineStream >> l;
		LineStream.get();
		LineStream >> h;
		LineStream.get();
		LineStream >> w;

		uint32_t Side1 = l * w;
		uint32_t Side2 = h * w;
		uint32_t Side3 = l * h;

		uint32_t SmallestSide = std::min({ Side1, Side2, Side3 });
		uint32_t LargestDimension = std::max({ l, w, h });

		WrappingPaper += SmallestSide + 2 * Side1 + 2 * Side2 + 2 * Side3;
		Ribbon += l * w * h + 2 * l + 2 * w + 2 * h - 2 * LargestDimension;
	}

	Input.close();

	std::cout << "Wrapping Paper: " << WrappingPaper << std::endl;
	std::cout << "Ribbon: " << Ribbon << std::endl;

	system("pause");

    return 0;
}

Add solution for Day 2 part two


/**
 * \file
 * \brief board::lowLevelInitialization() implementation for NUCLEO-F103RB
 *
 * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/board/lowLevelInitialization.hpp"

namespace distortos
{

namespace board
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{

}

}	// namespace board

}	// namespace distortos

/**
 * \file
 * \brief board::lowLevelInitialization() implementation for NUCLEO-F103RB
 *
 * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/board/lowLevelInitialization.hpp"

#include "distortos/chip/CMSIS-proxy.h"

namespace distortos
{

namespace board
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{
	RCC->APB2ENR |=
#ifdef CONFIG_BOARD_LEDS_ENABLE
			RCC_APB2ENR_IOPAEN |
#endif	// def CONFIG_BOARD_LEDS_ENABLE
			0;
}

}	// namespace board

}	// namespace distortos

Enable GPIOA in board::lowLevelInitialization() for NUCLEO-F103RB


#include <QCoreApplication>
#include "qtyamltest.h"

#define RUN(klass) \
    do { \
        klass *obj = new klass(); \
        status |= QTest::qExec(obj, argc, argv); \
        delete obj; \
    } while(0)

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

    int status = 0;
    RUN(HighLevelTests);
    RUN(YAMLDotOrgTests);
    RUN(PracticalTests);
    return status;
}

#include <QCoreApplication>
#include "qtyamltest.h"

#define RUN(klass) \
    do { \
        klass obj; \
        status |= QTest::qExec(&obj, argc, argv); \
    } while(0)

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

    int status = 0;
    RUN(HighLevelTests);
    RUN(YAMLDotOrgTests);
    RUN(PracticalTests);
    return status;
}

Simplify test case class construction


#include <sstream>
#include <gtest/gtest.h>
#include <errors.h>
#include <iostreamsocket.h>

#define TEST_CLASS IOStreamSocketTest
#define INIT_DATA ("dat_data_tho")
#define INIT_LEN (12)

class TEST_CLASS : public testing::Test {
protected:
    TEST_CLASS() : in(INIT_DATA), sock(in, out) { }
    std::stringstream in, out;
    IOStreamSocket sock;
};

TEST_F(TEST_CLASS, TestRead) {
    int iret;
    char *buffer[INIT_LEN+1] = {0};

    iret = sock.read(0, INIT_LEN, buffer);
    ASSERT_EQ(iret, ERR_SUCCESS) << "Read failed";
    ASSERT_TRUE(!memcmp(buffer, INIT_DATA, INIT_LEN)) << "Read wrong data(" << buffer << ")";
}

TEST_F(TEST_CLASS, TestWrite) {
    int iret;

    iret = sock.write(0, INIT_LEN, INIT_DATA);
    ASSERT_EQ(iret, ERR_SUCCESS) << "Read failed";

    const char *actual = out.str().c_str();
    ASSERT_TRUE(!memcmp(actual, INIT_DATA, INIT_LEN)) << "Wrote wrong data(" << actual << ")";
}

#include <sstream>
#include <gtest/gtest.h>
#include <errors.h>
#include <iostreamsocket.h>

#define TEST_CLASS IOStreamSocketTest
#define INIT_DATA ("dat data tho")
#define INIT_LEN (12)

class TEST_CLASS : public testing::Test {
protected:
    TEST_CLASS() : in(INIT_DATA), sock(in, out) { }
    std::stringstream in, out;
    IOStreamSocket sock;
};

TEST_F(TEST_CLASS, TestRead) {
    int iret;
    char *buffer[INIT_LEN+1] = {0};

    iret = sock.read(0, INIT_LEN, buffer);
    ASSERT_EQ(iret, ERR_SUCCESS) << "Read failed";
    ASSERT_TRUE(!memcmp(buffer, INIT_DATA, INIT_LEN)) << "Read wrong data(" << buffer << ")";
}

TEST_F(TEST_CLASS, TestWrite) {
    int iret;

    iret = sock.write(0, INIT_LEN, INIT_DATA);
    ASSERT_EQ(iret, ERR_SUCCESS) << "Read failed";

    const char *actual = out.str().c_str();
    ASSERT_TRUE(!memcmp(actual, INIT_DATA, INIT_LEN)) << "Wrote wrong data(" << actual << ")";
}

Use test data with spaces


// External Depdendencies
#include "../../../lib/jnipp/jnipp.h"

// Module Dependencies
#include "../include/app.h"
#include "../include/eventqueue.h"

namespace native
{
    namespace ui
    {
        // Static Variable Initialisations
        thread_local int EventQueue::_exitCode = 0;

        bool EventQueue::handleEvent(bool block)
        {
            throw NotImplementedException();
        }

        void EventQueue::quitWithCode(int exitCode)
        {
            jni::Object* activity = (jni::Object*) App::getAppHandle();

            activity->call<void>("finish");
        }
    }
}

// External Depdendencies
#include "../../../lib/jnipp/jnipp.h"

// Module Dependencies
#include "../include/app.h"
#include "../include/eventqueue.h"

namespace native
{
    namespace ui
    {
        // Static Variable Initialisations
        thread_local int EventQueue::_exitCode = 0;

        bool EventQueue::handleEvent(bool block)
        {
            throw NotImplementedException();
        }

        void EventQueue::quitWithCode(int exitCode)
        {
            jni::Object* activity = (jni::Object*) App::getAppHandle();

            _exitCode = exitCode;
            activity->call<void>("finish");
        }
    }
}

Set exit code on quitting.


#include "gflags/gflags.h"

DEFINE_string(race_id, "", "");
DEFINE_bool(continuous_integration, true, "");
DEFINE_double(safe_angle, 60.0, "");
DEFINE_int32(handicap, 0, "");
DEFINE_bool(check_if_safe_ahead, true, "");
DEFINE_int32(answer_time, 10, "Time limit for answer in ms");

DEFINE_bool(bump_with_turbo, false, "kamikazebumps");
DEFINE_bool(defend_turbo_bump, false, "Defend against people that have bump_with_turbo");

#include "gflags/gflags.h"

DEFINE_string(race_id, "", "");
DEFINE_bool(continuous_integration, true, "");
DEFINE_double(safe_angle, 60.0, "");
DEFINE_int32(handicap, 0, "");
DEFINE_bool(check_if_safe_ahead, true, "");
DEFINE_int32(answer_time, 10, "Time limit for answer in ms");

DEFINE_bool(bump_with_turbo, true, "kamikazebumps");
DEFINE_bool(defend_turbo_bump, false, "Defend against people that have bump_with_turbo");

Enable bump with turbo by default


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

#include "base/test_file_util.h"

#include "base/logging.h"

namespace file_util {

bool EvictFileFromSystemCache(const FilePath& file) {
  // TODO(port): Implement.
  NOTIMPLEMENTED();
  return false;
}

}  // namespace file_util

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

#include "base/test_file_util.h"

#include "base/logging.h"

namespace file_util {

bool EvictFileFromSystemCache(const FilePath& file) {
  // There is no way that we can think of to dump something from the UBC.  You
  // can add something so when you open it, it doesn't go in, but that won't
  // work here.
  return true;
}

}  // namespace file_util

Change the stub for file_util::EvictFileFromSystemCache


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

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, JavaScriptURLPermissions) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_;
}

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

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

// Disabled, http://crbug.com/63589.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_JavaScriptURLPermissions) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());

  ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_;
}

Disable ExtensionApiTest.JavaScriptURLPermissions, it flakily hits an assertion.


//
//  TableLookupOsc.cpp
//  Tonic
//
//  Created by Nick Donaldson on 2/8/13.

//

#include "TableLookupOsc.h"

namespace Tonic {

  namespace Tonic_{

    TableLookupOsc_::TableLookupOsc_() :
      phase_(0.0)
    {
      modFrames_.resize(kSynthesisBlockSize, 1);
      lookupTable_ = SampleTable(kSynthesisBlockSize,1);
    }

    void TableLookupOsc_::reset(){
      phase_ = 0.0f;
    }

    void TableLookupOsc_::setLookupTable(SampleTable table){
      if (table.channels() != 1){
        error("TableLookupOsc expects lookup table with 1 channel only");
        return;
      }

      unsigned int nearestPo2;
      if (!isPowerOf2(table.size()-1, &nearestPo2)){

        warning("TableLookUpOsc lookup tables must have a (power-of-two + 1) number of samples (example 2049 or 4097). Resizing to nearest power-of-two + 1");

        // TODO: This will just lop off samples or add silence. Don't want to do that.
        table.resample(nearestPo2+1, 1);

      }

      lookupTable_ = table;
    }

  } // Namespace Tonic_

  TableLookupOsc & TableLookupOsc::setLookupTable(SampleTable lookupTable){
    gen()->setLookupTable(lookupTable);
    return *this;
  }

} // Namespace Tonic

//
//  TableLookupOsc.cpp
//  Tonic
//
//  Created by Nick Donaldson on 2/8/13.

//

#include "TableLookupOsc.h"

namespace Tonic {

  namespace Tonic_{

    TableLookupOsc_::TableLookupOsc_() :
      phase_(0.0)
    {
      modFrames_.resize(kSynthesisBlockSize, 1);
      lookupTable_ = SampleTable(kSynthesisBlockSize,1);
    }

    void TableLookupOsc_::reset(){
      phase_ = 0.0f;
    }

    void TableLookupOsc_::setLookupTable(SampleTable table){
      if (table.channels() != 1){
        error("TableLookupOsc expects lookup table with 1 channel only");
        return;
      }

      unsigned int nearestPo2;
      if (!isPowerOf2(table.size()-1, &nearestPo2)){

        warning("TableLookUpOsc lookup tables must have a (power-of-two + 1) number of samples (example 2049 or 4097). Resizing to nearest power-of-two + 1");

        table.resample(nearestPo2, 1);
        table.resize(nearestPo2+1, 1);
        table.dataPointer()[nearestPo2] = table.dataPointer()[0]; // copy first sample to last

      }

      lookupTable_ = table;
    }

  } // Namespace Tonic_

  TableLookupOsc & TableLookupOsc::setLookupTable(SampleTable lookupTable){
    gen()->setLookupTable(lookupTable);
    return *this;
  }

} // Namespace Tonic

Fix resizing for arbitrary lookup tables


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

#include "MockSocket.h"

namespace cura
{

MockSocket::MockSocket()
{
}

void MockSocket::connect(const std::string& address, int port) { /* Do nothing. */ }
void MockSocket::listen(const std::string& address, int port) { /* Do nothing. */ }
void MockSocket::close() { /* Do nothing. */ }
void MockSocket::reset() { /* Do nothing. */ }

void MockSocket::sendMessage(Arcus::MessagePtr message)
{
    sent_messages.push_back(message);
}

Arcus::MessagePtr MockSocket::takeNextMessage()
{
    Arcus::MessagePtr result = received_messages.front();
    received_messages.pop_front();
    return result;
}

void MockSocket::pushMessageToReceivedQueue(Arcus::MessagePtr message)
{
    received_messages.push_back(message);
}

Arcus::MessagePtr MockSocket::popMessageFromSendQueue()
{
    Arcus::MessagePtr result = sent_messages.front();
    sent_messages.pop_front();
    return result;
}

} //namespace cura

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

#include "MockSocket.h"

namespace cura
{

MockSocket::MockSocket()
{
}

void MockSocket::connect(const std::string&, int) { /* Do nothing. */ }
void MockSocket::listen(const std::string&, int) { /* Do nothing. */ }
void MockSocket::close() { /* Do nothing. */ }
void MockSocket::reset() { /* Do nothing. */ }

void MockSocket::sendMessage(Arcus::MessagePtr message)
{
    sent_messages.push_back(message);
}

Arcus::MessagePtr MockSocket::takeNextMessage()
{
    Arcus::MessagePtr result = received_messages.front();
    received_messages.pop_front();
    return result;
}

void MockSocket::pushMessageToReceivedQueue(Arcus::MessagePtr message)
{
    received_messages.push_back(message);
}

Arcus::MessagePtr MockSocket::popMessageFromSendQueue()
{
    Arcus::MessagePtr result = sent_messages.front();
    sent_messages.pop_front();
    return result;
}

} //namespace cura

Remove names of unused variables


#include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"

#include "krs_servo_driver.hpp"

class KrsServoNode {
public:
  KrsServoNode();
  explicit KrsServoNode(ros::NodeHandle& nh);

private:
  void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);

  ros::Subscriber sub;
  KrsServoDriver krs;
};

KrsServoNode::KrsServoNode()
  : krs()
{}

KrsServoNode::KrsServoNode(ros::NodeHandle& nh)
  : krs()
{
  sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}

inline void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
  krs.sendAngle(msg->id, msg->angle);
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "krs_servo_node");
  ros::NodeHandle nh;

  KrsServoNode ksn(nh);

  ros::spin();
  return 0;
}

#include "ros/ros.h"
#include "servo_msgs/KrsServoDegree.h"

#include "krs_servo_driver.hpp"

class KrsServoNode {
public:
  KrsServoNode();
  explicit KrsServoNode(ros::NodeHandle& nh);

private:
  void krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg);

  ros::Subscriber sub;
  KrsServoDriver krs;
};

KrsServoNode::KrsServoNode()
  : krs()
{}

KrsServoNode::KrsServoNode(ros::NodeHandle& nh)
  : krs()
{
  sub = nh.subscribe("cmd_krs", 16, &KrsServoNode::krsServoDegreeCallback, this);
}

void KrsServoNode::krsServoDegreeCallback(const servo_msgs::KrsServoDegree::ConstPtr& msg) {
  krs.sendAngle(msg->id, msg->angle);
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "krs_servo_node");
  ros::NodeHandle nh;

  KrsServoNode ksn(nh);

  ros::spin();
  return 0;
}

Fix invalid inline because get pointer


// 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 <agency/new_executor_traits.hpp>
#include <cassert>
#include <iostream>

#include "test_executors.hpp"

template<class Executor>
void test()
{
  using executor_type = Executor;

  {
    // returning void

    executor_type exec;

    int set_me_to_thirteen = 0;

    auto f = agency::new_executor_traits<executor_type>::async_execute(exec, [&]
    {
      set_me_to_thirteen = 13;
    });

    f.wait();

    assert(set_me_to_thirteen == 13);
  }

  {
    // returning int

    executor_type exec;

    auto f = agency::new_executor_traits<executor_type>::async_execute(exec, []
    {
      return 13;
    });

    assert(f.get() == 13);
  }
}

int main()
{
  using namespace test_executors;

  test<empty_executor>();
  test<single_agent_when_all_execute_and_select_executor>();
  test<multi_agent_when_all_execute_and_select_executor>();
  test<single_agent_then_execute_executor>();
  test<multi_agent_execute_returning_user_defined_container_executor>();
  test<multi_agent_execute_returning_default_container_executor>();
  test<multi_agent_execute_returning_void_executor>();

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

  return 0;
}

#include <agency/new_executor_traits.hpp>
#include <cassert>
#include <iostream>

#include "test_executors.hpp"

template<class Executor>
void test()
{
  using executor_type = Executor;

  {
    // returning void

    executor_type exec;

    int set_me_to_thirteen = 0;

    auto f = agency::new_executor_traits<executor_type>::async_execute(exec, [&]
    {
      set_me_to_thirteen = 13;
    });

    f.wait();

    assert(set_me_to_thirteen == 13);
    assert(exec.valid());
  }

  {
    // returning int

    executor_type exec;

    auto f = agency::new_executor_traits<executor_type>::async_execute(exec, []
    {
      return 13;
    });

    assert(f.get() == 13);
    assert(exec.valid());
  }
}

int main()
{
  using namespace test_executors;

  test<empty_executor>();
  test<single_agent_when_all_execute_and_select_executor>();
  test<multi_agent_when_all_execute_and_select_executor>();
  test<single_agent_then_execute_executor>();
  test<multi_agent_execute_returning_user_defined_container_executor>();
  test<multi_agent_execute_returning_default_container_executor>();
  test<multi_agent_execute_returning_void_executor>();

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

  return 0;
}

Validate the executor as part of the test


// 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 "base/basictypes.h"
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"

namespace nacl {

void CopyNaClCommandLineArguments(CommandLine* cmd_line) {
  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();

  // Propagate the following switches to the NaCl loader command line (along
  // with any associated values) if present in the browser command line.
  // TODO(gregoryd): check which flags of those below can be supported.
  static const char* const kSwitchNames[] = {
    switches::kNoSandbox,
    switches::kTestNaClSandbox,
    switches::kDisableBreakpad,
    switches::kFullMemoryCrashReport,
    switches::kEnableLogging,
    switches::kDisableLogging,
    switches::kLoggingLevel,
    switches::kEnableDCHECK,
    switches::kSilentDumpOnDCHECK,
    switches::kMemoryProfiling,
    switches::kNoErrorDialogs,
#if defined(OS_MACOSX)
    switches::kEnableSandboxLogging,
#endif
  };
  cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
                             arraysize(kSwitchNames));
}

}  // namespace nacl

// 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 "base/basictypes.h"
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"

namespace nacl {

void CopyNaClCommandLineArguments(CommandLine* cmd_line) {
  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();

  // Propagate the following switches to the NaCl loader command line (along
  // with any associated values) if present in the browser command line.
  // TODO(gregoryd): check which flags of those below can be supported.
  static const char* const kSwitchNames[] = {
    switches::kNoSandbox,
    switches::kTestNaClSandbox,
    switches::kDisableBreakpad,
    switches::kFullMemoryCrashReport,
    switches::kEnableLogging,
    switches::kDisableLogging,
    switches::kLoggingLevel,
    switches::kEnableDCHECK,
    switches::kNoErrorDialogs,
#if defined(OS_MACOSX)
    switches::kEnableSandboxLogging,
#endif
  };
  cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
                             arraysize(kSwitchNames));
}

}  // namespace nacl

Remove the switches kSilentDumpOnDCHECK and kMemoryProfiling from NaCl and broker processes.


// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t
// RUN: %clangxx_msan -DPOSITIVE -m64 -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s

#include <emmintrin.h>

int to_int(double v) {
  __m128d t = _mm_set_sd(v);
  int x = _mm_cvtsd_si32(t);
  return x;
  // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
  // CHECK: #{{.*}} in to_int{{.*}}vector_cvt.cc:[[@LINE-4]]
}

int main() {
#ifdef POSITIVE
  double v;
#else
  double v = 1.1;
#endif
  double* volatile p = &v;
  int x = to_int(*p);
  return !x;
}

// RUN: %clangxx_msan -m64 -O0 %s -o %t && %run %t
// RUN: %clangxx_msan -DPOSITIVE -m64 -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s

#include <emmintrin.h>

int to_int(double v) {
  __m128d t = _mm_set_sd(v);
  int x = _mm_cvtsd_si32(t);
  return x;
  // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
  // CHECK: #{{.*}} in to_int{{.*}}vector_cvt.cc:[[@LINE-3]]
}

int main() {
#ifdef POSITIVE
  double v;
#else
  double v = 1.1;
#endif
  double* volatile p = &v;
  int x = to_int(*p);
  return !x;
}

Fix line numbers for code inlined from __nodebug__ functions.


// 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

class WindowOpenPanelTest : public ExtensionApiTest {
  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnablePanels);
  }
};

// http://crbug.com/253417 for NDEBUG
#if defined(OS_WIN) || (defined(OS_MACOSX) && defined(NDEBUG))
// Focus test fails if there is no window manager on Linux.
IN_PROC_BROWSER_TEST_F(WindowOpenPanelTest, WindowOpenFocus) {
  ASSERT_TRUE(RunExtensionTest("window_open/focus")) << message_;
}
#endif

// 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

class WindowOpenPanelTest : public ExtensionApiTest {
  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnablePanels);
  }
};

// http://crbug.com/253417 for NDEBUG
#if (defined(OS_WIN) || defined(OS_MACOSX)) && defined(NDEBUG)
// Focus test fails if there is no window manager on Linux.
IN_PROC_BROWSER_TEST_F(WindowOpenPanelTest, WindowOpenFocus) {
  ASSERT_TRUE(RunExtensionTest("window_open/focus")) << message_;
}
#endif

Disable WindowOpenPanelTest.WindowOpenFocus on Windows debug builds.


#include <sol.hpp>
#include <string>
#include <iostream>

/// this example shows how to read data in from a lua table
using namespace std;

//compiles on linux with: g++ -std=c++11 -I.. table.cpp -o tables -llua

int main(int argc, char * argv[])
{
  sol::state lua;
  //table used as an array
  lua.script("table1 = {\"hello\", \"table\"}");
  //table with a nested table and the key value syntax
  lua.script("table2 = {[\"nestedTable\"]={[\"key1\"]=\"value1\", [\"key2\"]=\"value2\"},"
    " [\"name\"]=\"table2\"}");

  //using the values stored in table1
  cout << lua.get<sol::table>("table1").get<string>(1)<< " " <<
    lua.get<sol::table>("table1").get<string>(2) << endl;

  auto t2 = lua.get<sol::table>("table2");
  auto nestedTable = t2.get<sol::table>("nestedTable");
  //some retrival of values from the nested table
  //the cleaner way of doing things
  cout << "nested table: key1 : " << nestedTable.get<string>("key1") << ", key2: "
    //yes you can chain the get<>() results
    << lua.get<sol::table>("table2").get<sol::table>("nestedTable").get<string>("key2")
    << endl;

  cout << "name of t2: " << t2.get<string>("name") << endl;

  return 0;
}

#include <sol.hpp>
#include <string>
#include <iostream>

// this example shows how to read data in from a lua table

int main() {
    sol::state lua;
    // table used as an array
    lua.script("table1 = {\"hello\", \"table\"}");
    // table with a nested table and the key value syntax
    lua.script("table2 = {"
                  "[\"nestedTable\"] = {"
                       "[\"key1\"] = \"value1\","
                       "[\"key2\"]= \"value2\""
                   "},"
                  "[\"name\"]= \"table2\""
                "}");

    // using the values stored in table1
    std::cout << lua.get<sol::table>("table1").get<std::string>(1) << " "
              << lua.get<sol::table>("table1").get<std::string>(2) << '\n';

    auto t2 = lua.get<sol::table>("table2");
    auto nestedTable = t2.get<sol::table>("nestedTable");

    // some retrieval of values from the nested table
    // the cleaner way of doing things
    std::cout << "nested table: key1 : " << nestedTable.get<std::string>("key1") << ", key2: "
    // yes you can chain the get<>() results
              << lua.get<sol::table>("table2").get<sol::table>("nestedTable").get<std::string>("key2")
              << '\n';

    std::cout << "name of t2: " << t2.get<std::string>("name") << '\n';
}

Improve formatting of table example


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

QString _defaultPathAudio = "";
QString _defaultPathProjects = "";
QString _defaultPathOutput = "";

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

    return a.exec();
}

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

QString _defaultPathAudio = "";
QString _defaultPathProjects = "";
QString _defaultPathOutput = "";

int main(int argc, char *argv[])
{
    QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::Round);
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

Support high-dpi screens in Windows


//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// <ios>

// class ios_base

// static int xalloc();

#include <ios>
#include <cassert>

int main(int, char**)
{
    assert(std::ios_base::xalloc() == 0);
    assert(std::ios_base::xalloc() == 1);
    assert(std::ios_base::xalloc() == 2);
    assert(std::ios_base::xalloc() == 3);
    assert(std::ios_base::xalloc() == 4);

  return 0;
}

//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// <ios>

// class ios_base

// static int xalloc();

#include <ios>
#include <cassert>

int main(int, char**)
{
    int index = std::ios_base::xalloc();
    for (int i = 0; i < 10000; ++i)
        assert(std::ios_base::xalloc() == ++index);

  return 0;
}

Increase portability of xalloc test


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

// <memory>

// template <class T>
//   pair<T*, ptrdiff_t>
//   get_temporary_buffer(ptrdiff_t n);
//
// template <class T>
//   void
//   return_temporary_buffer(T* p);

#include <memory>
#include <cassert>

struct alignas(32) A {
    int field;
};

int main()
{
    std::pair<A*, std::ptrdiff_t> ip = std::get_temporary_buffer<A>(5);
    assert(!(ip.first == nullptr) ^ (ip.second == 0));
    assert(reinterpret_cast<uintptr_t>(ip.first) % alignof(A) == 0);
    std::return_temporary_buffer(ip.first);
}

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

// UNSUPPORTED: c++98, c++03

// <memory>

// template <class T>
//   pair<T*, ptrdiff_t>
//   get_temporary_buffer(ptrdiff_t n);
//
// template <class T>
//   void
//   return_temporary_buffer(T* p);

#include <memory>
#include <cassert>

struct alignas(32) A {
    int field;
};

int main()
{
    std::pair<A*, std::ptrdiff_t> ip = std::get_temporary_buffer<A>(5);
    assert(!(ip.first == nullptr) ^ (ip.second == 0));
    assert(reinterpret_cast<uintptr_t>(ip.first) % alignof(A) == 0);
    std::return_temporary_buffer(ip.first);
}

Disable test in C++<11 mode due to use of alignas.


/** @file.cc
 * π approximation
 */
#include <iostream>
#include <random>

/** Approximate π in a number of runs.
 * @param N the number of runs
 * @param rng the random number generator used
 * @return an approximation of π
 */
double ApproximatePi(const size_t N, std::mt19937 &rng) {
  static std::uniform_real_distribution<double> dist(0.0, 1.0);
  size_t i,
         n = 0;
  double x,
         y;
  for (i = 0; i < N; i++) {
    x = dist(rng);
    y = dist(rng);
    if (x * x + y * y <= 1) {
      ++n;
    }
  }
  return 4.0 * n / N;
}

/** Main. */
int main(int argc, char *argv[]) {
  std::random_device rd;
  std::mt19937 rng(rd());
  std::cout << "π = " << ApproximatePi(10000000, rng) << std::endl;
}

/** @file.cc
 * π approximation
 */

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

/** Approximate π in a number of runs.
 * @param N the number of runs
 * @param rng the random number generator used
 * @return an approximation of π
 */
double ApproximatePi(const size_t N, std::mt19937 &rng) {
  static std::uniform_real_distribution<double> dist(0.0, 1.0);
  size_t i,
         n = 0;
  double x,
         y;
  for (i = 0; i < N; i++) {
    x = dist(rng);
    y = dist(rng);
    if (x * x + y * y <= 1) {
      ++n;
    }
  }
  return 4.0 * n / N;
}

/** Main. */
int main(int argc, char *argv[]) {
  std::random_device rd;
  std::mt19937 rng(rd());
  double pi = ApproximatePi(10000000, rng);
  std::cout << std::setprecision(20)
            << "    π = " << pi << std::endl
            << "π - π = " << pi - M_PI << std::endl;
}

Add comparison to "real" value.


/**
 * Tower Defence Pro #005
 * (C) 2010 - Samuel Andersson, Björn Ekberg
 */

#ifdef _WIN32
#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>
#endif

#include <Core/Game.h>
#include <Core/GameEngine.h>
#include <ctime>
#include <memory>
#include <Utils/Log.h>

int main(int argc, char *argv[])
{
	/** Seed srand() */
	time_t t;
	time(&t);
	srand((unsigned int) t);

	Log::reportingLevel() = logDEBUG;
	FILE* logFd;
	fopen_s(&logFd, "output.log", "w");
	Output2FILE::stream() = logFd;

	int ret = 0;
	Game* game = new Game();
	{
		GameSettings settings;
		settings.WindowWidth = WWIDTH;
		settings.WindowHeight = WHEIGHT;
		settings.WindowTitle = "Tower Defence Pro " + std::string(VERSION) + " © 2010 - 2016 A15 Entertainment";

		GameEngine engine(settings);
		ret = engine.run(game);
	}
	delete game;

#ifdef _WIN32
	_CrtDumpMemoryLeaks();
#endif
	return ret;
}

/**
 * Tower Defence Pro #005
 * (C) 2010 - Samuel Andersson, Björn Ekberg
 */

#if defined(_WIN32) && (_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>
#endif

#include <Core/Game.h>
#include <Core/GameEngine.h>
#include <ctime>
#include <memory>
#include <Utils/Log.h>

int main(int argc, char *argv[])
{
	/** Seed srand() */
	time_t t;
	time(&t);
	srand((unsigned int) t);

#ifdef _DEBUG
	Log::reportingLevel() = logDEBUG;
#else
	Log::reportingLevel() = logWARNING;
#endif
	FILE* logFd;
	fopen_s(&logFd, "log.txt", "w");
	Output2FILE::stream() = logFd;

	int ret = 0;
	Game* game = new Game();
	{
		GameSettings settings;
		settings.WindowWidth = WWIDTH;
		settings.WindowHeight = WHEIGHT;
		settings.WindowTitle = "Tower Defence Pro " + std::string(VERSION) + " © 2010 - 2016 A15 Entertainment";

		GameEngine engine(settings);
		ret = engine.run(game);
	}
	delete game;

#if defined(_WIN32) && defined (_DEBUG)
	_CrtDumpMemoryLeaks();
#endif
	return ret;
}

Set logging level based on build


/*****************************************************************************
 *
 * utouch-frame - Touch Frame Library
 *
 * Copyright (C) 2011 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * 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 "xorg/gtest/test.h"

#include <X11/Xlib.h>

struct xorg::testing::Test::Private {
  ::Display* display;
};

xorg::testing::Test::Test() : d_(new Private) {
  d_->display = NULL;
}

void xorg::testing::Test::SetUp() {
  d_->display = XOpenDisplay(NULL);
  ASSERT_TRUE(d_->display != NULL) << "Failed to open connection to display";
}

void xorg::testing::Test::TearDown() {
  XCloseDisplay(d_->display);
  d_->display = NULL;
}

::Display* xorg::testing::Test::Display() const {
  return d_->display;
}

/*****************************************************************************
 *
 * utouch-frame - Touch Frame Library
 *
 * Copyright (C) 2011 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * 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 "xorg/gtest/test.h"

#include <stdexcept>

#include <X11/Xlib.h>

struct xorg::testing::Test::Private {
  ::Display* display;
};

xorg::testing::Test::Test() : d_(new Private) {
  d_->display = NULL;
}

void xorg::testing::Test::SetUp() {
  d_->display = XOpenDisplay(NULL);
  if (!d_->display)
    throw std::runtime_error("Failed to open connection to display");
}

void xorg::testing::Test::TearDown() {
  XCloseDisplay(d_->display);
  d_->display = NULL;
}

::Display* xorg::testing::Test::Display() const {
  return d_->display;
}

Throw runtime_error if Test::SetUp fails to open connection to server


#include "module.hh"
#include "module.hpp"
#include "logging.hpp"

using Wintermute::Module;
using Wintermute::Module;
using Wintermute::ModulePrivate;

Module::Module(const Designation& designation) : d_ptr(new ModulePrivate)
{
  W_PRV(Module);
  d->designation = designation;
  wtrace("Module " + static_cast<string>(designation()) + " started.");
}

Module::Designation Module::designation() const
{
  W_PRV(Module);
  return d->designation;
}

bool Module::sendMessage(const Message& message) const
{
  wtrace("Module " + static_cast<string>(designation()) + " sending a message.");
  return true;
}

bool Module::receiveMessage(const Message& message) const
{
  wtrace("Module " + static_cast<string>(designation()) + " receiving a message.");
  return true;
}

Module::~Module()
{
}

#include "module.hh"
#include "module.hpp"
#include "logging.hpp"

using Wintermute::Module;
using Wintermute::Module;
using Wintermute::ModulePrivate;

Module::Module(const Designation& designation) : d_ptr(new ModulePrivate)
{
  W_PRV(Module);
  d->designation = designation;
  wtrace("Module " + static_cast<string>(designation) + " started.");
}

Module::Designation Module::designation() const
{
  W_PRV(Module);
  return d->designation;
}

bool Module::sendMessage(const Message& message) const
{
  wtrace("Module " + static_cast<string>(designation()) + " sending a message.");
  // TODO Send a message using the MessageTunnel.
  return true;
}

bool Module::receiveMessage(const Message& message) const
{
  wtrace("Module " + static_cast<string>(designation()) + " receiving a message.");
  // TODO a message using the MessageTunnel.
  return true;
}

Module::~Module()
{
}

Use argument instead of method for designation.


// RUN: %clangxx_asan -fno-rtti -DBUILD_SO1 -fPIC -shared %s -o %dynamiclib1
// RUN: %clangxx_asan -fno-rtti -DBUILD_SO2 -fPIC -shared %s -o %dynamiclib2
// RUN: %clangxx_asan -fno-rtti %s %ld_flags_rpath_exe1 %ld_flags_rpath_exe2 -o %t
// RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t 2>&1 | FileCheck %s

// FIXME: Somehow does not detect ODR on powerpc64be
// XFAIL: powerpc64

struct XYZ {
  virtual void foo();
};

#if defined(BUILD_SO1)

void XYZ::foo() {}

#elif defined(BUILD_SO2)

void XYZ::foo() {}

#else

int main() {}

#endif

// CHECK: AddressSanitizer: odr-violation
// CHECK-NEXT: 'vtable for XYZ'
// CHECK-NEXT: 'vtable for XYZ'

// RUN: %clangxx_asan -fno-rtti -DBUILD_SO1 -fPIC -shared %s -o %dynamiclib1
// RUN: %clangxx_asan -fno-rtti -DBUILD_SO2 -fPIC -shared %s -o %dynamiclib2
// RUN: %clangxx_asan -fno-rtti %s %ld_flags_rpath_exe1 %ld_flags_rpath_exe2 -o %t
// RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t 2>&1 | FileCheck %s

struct XYZ {
  virtual void foo();
};

#if defined(BUILD_SO1)

void XYZ::foo() {}

#elif defined(BUILD_SO2)

void XYZ::foo() {}

#else

int main() {}

#endif

// CHECK: AddressSanitizer: odr-violation
// CHECK-NEXT: 'vtable for XYZ'
// CHECK-NEXT: 'vtable for XYZ'

Revert "[asan] Disable test on powerpc64be"


/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <iostream>
#include <qimessaging/qisession.h>

#include <qimessaging/session.hpp>

class QiSessionPrivate {
public:
  qi::Session session;
};

QiSession::QiSession()
  : _p(new QiSessionPrivate)
{
}

QiSession::~QiSession()
{
  delete _p;
}

void QiSession::connect(const QString &masterAddress)
{
  _p.session.connect(masterAddress::toUtf8());
}

bool QiSession::waitForConnected(int msecs)
{
  _p.session.connect(masterAddress::toUtf8());
}

bool QiSession::waitForDisconnected(int msecs)
{
  _p.session.connect(masterAddress::toUtf8());
}

QObject *QiSession::service(const QString &name, const QString &type)
{

}

QiTransportSocket *QiSession::serviceSocket(const QString &name, const QString &type)
{
}

QVector<QString> services()
{
    return QVector<QString>::fromStdVector(_p.session.services());
}

/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <iostream>
#include <qimessaging/qisession.h>

#include <qimessaging/session.hpp>

class QiSessionPrivate {
public:
  qi::Session session;
};

QiSession::QiSession()
  : _p(new QiSessionPrivate)
{
}

QiSession::~QiSession()
{
  delete _p;
}

void QiSession::connect(const QString &masterAddress)
{
  _p.session.connect(masterAddress::toUtf8());
}

bool QiSession::waitForConnected(int msecs)
{
  return _p.session.connect(masterAddress::toUtf8());
}

bool QiSession::waitForDisconnected(int msecs)
{
  return _p.session.connect(masterAddress::toUtf8());
}

QObject *QiSession::service(const QString &name, const QString &type)
{

}

QiTransportSocket *QiSession::serviceSocket(const QString &name, const QString &type)
{
}

QVector<QString> services()
{
  return QVector<QString>::fromStdVector(_p.session.services());
}

Add return statements in non-void functions.


#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "edges.hpp"
#include "sharpen.hpp"

int main() {
	cv::Mat image(cv::imread("swiss.jpg"));
	cv::Mat edges;

	//std::cout << image.channels() << std::endl;
	findEdges(image, edges);

	cv::imshow("nyc.jpg", image);
	cv::imshow("Edges of nyc.jpg", edges);
	cv::waitKey(0);

	return 0;
}

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "edges.hpp"
#include "sharpen.hpp"

int main(int argc, char* argv[]) {
	if(argc < 2) {
		std::cerr << "Please enter the name of the image file in which to find edges." << std::endl;
		return 0;
	}

	std::string imageFile(argv[1]);
	cv::Mat image(cv::imread(imageFile));

	if(image.rows == 0 || image.cols == 0) {
		std::cerr << "Please enter a valid image file." << std::endl;
		return 0;
	}

	cv::Mat edges; // blank image
	findEdges(image, edges);

	// show before & after
	cv::imshow(imageFile, image);
	cv::imshow("Edges of " + imageFile, edges);

	// convert & save image to file
	edges.convertTo(edges, CV_8UC1, 255.0);
	cv::imwrite("edges." + imageFile, edges);

	// wait
	cv::waitKey(0);

	return 0;
}

Enable image input from console


#include <iostream>

#include "CmdMessenger.h"

using namespace std;

enum
{
  ksetled
};

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

    char op;
    cmd::CmdMessenger arduino(argv[1], 9600);
    cmd::Cmd led(ksetled);

    cmd::Timeout timeout = cmd::Timeout::simpleTimeout(1000);
    arduino.setTimeout(timeout);

    while(true)
    {
      cout << "'1' turns on, '0' turns off, 'q' quits: ";
      cin >> op;
      cout << endl;

      switch(op)
      {
        case '1':
          led << true << CmdEnd();
          arduino.send(led);

          cout << led.getNumArgs() << endl;
          led.clear();
          break;

        case '0':
          led << false << CmdEnd();
          arduino.send(led);
          led.clear();
          break;

        case 'q':
          break;
      }

      if(op == 'q') break;

      cout << "feeding in serial data\n";

      arduino.feedInSerialData();

    }

  }
  else
  {
    cout << "Usage: led 'port_name'\n";
  }

  return 0;
}

#include <iostream>

#include "CmdMessenger.h"

using namespace std;

enum
{
  ksetled
};

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

    char op;
    cmd::CmdMessenger arduino(argv[1], 115200);
    cmd::Cmd led(ksetled);

    cmd::Timeout timeout = cmd::Timeout::simpleTimeout(1000);
    arduino.setTimeout(timeout);

    while(true)
    {
      cout << "'1' turns on, '0' turns off, 'q' quits: ";
      cin >> op;
      cout << endl;

      switch(op)
      {
        case '1':
          led << true << CmdEnd();
          arduino.send(led);

          cout << led.getNumArgs() << endl;
          led.clear();
          break;

        case '0':
          led << false << CmdEnd();
          arduino.send(led);
          led.clear();
          break;

        case 'q':
          break;
      }

      if(op == 'q') break;

      cout << "feeding in serial data\n";

      arduino.feedInSerialData();

    }

  }
  else
  {
    cout << "Usage: led 'port_name'\n";
  }

  return 0;
}

Change the baudrate according to the CmdMessenger Receive example


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

#include "chrome/browser/icon_loader.h"

#include "base/message_loop.h"
#include "base/mime_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "third_party/skia/include/core/SkBitmap.h"

IconLoader::IconLoader(const IconGroupID& group, IconSize size,
                       Delegate* delegate)
    : group_(group),
      icon_size_(size),
      bitmap_(NULL),
      delegate_(delegate) {
}

IconLoader::~IconLoader() {
  delete bitmap_;
}

void IconLoader::Start() {
  target_message_loop_ = MessageLoop::current();

#if defined(OS_LINUX)
  // This call must happen on the UI thread before we can start loading icons.
  mime_util::DetectGtkTheme();
#endif

  g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(this, &IconLoader::ReadIcon));
}

void IconLoader::NotifyDelegate() {
  if (delegate_->OnBitmapLoaded(this, bitmap_))
    bitmap_ = NULL;
}

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

#include "chrome/browser/icon_loader.h"

#include "base/message_loop.h"
#include "base/mime_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "third_party/skia/include/core/SkBitmap.h"

IconLoader::IconLoader(const IconGroupID& group, IconSize size,
                       Delegate* delegate)
    : target_message_loop_(NULL),
      group_(group),
      icon_size_(size),
      bitmap_(NULL),
      delegate_(delegate) {
}

IconLoader::~IconLoader() {
  delete bitmap_;
}

void IconLoader::Start() {
  target_message_loop_ = MessageLoop::current();

#if defined(OS_LINUX)
  // This call must happen on the UI thread before we can start loading icons.
  mime_util::DetectGtkTheme();
#endif

  g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(this, &IconLoader::ReadIcon));
}

void IconLoader::NotifyDelegate() {
  if (delegate_->OnBitmapLoaded(this, bitmap_))
    bitmap_ = NULL;
}

Initialize target_message_loop_ in the constructor.


#include <sensormanagerinterface.h>
#include <datatypes/magneticfield.h>

int main()
{
    SensorManagerInterface* m_remoteSensorManager;
    m_remoteSensorManager = &SensorManagerInterface::instance();
    return 0;
}

#include <sensormanagerinterface.h>
#include <datatypes/magneticfield.h>
#include <abstractsensor.h>
#include <abstractsensor_i.h>

int main()
{
    SensorManagerInterface* m_remoteSensorManager;
    m_remoteSensorManager = &SensorManagerInterface::instance();
    QList<DataRange> (AbstractSensorChannelInterface::*func)() = &AbstractSensorChannelInterface::getAvailableIntervals;
    return 0;
}

Update the sensord config test


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

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

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

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

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

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

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

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

  return render_view_host_->Send(message);
}

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

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

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

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

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

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

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

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

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

  return render_view_host_->Send(message);
}

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

Fix invalid write in RenderViewHostObserver.


Update SHA1_IA32 to use compress_n


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

#include "chrome/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  NOTIMPLEMENTED();
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  NOTIMPLEMENTED();
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  NOTIMPLEMENTED();
}

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

#include "chrome/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  // We have no sandbox.
  // http://code.google.com/p/chromium/issues/detail?id=8081
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  // We have no sandbox.
  // http://code.google.com/p/chromium/issues/detail?id=8081
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  // We have no sandbox.
  // http://code.google.com/p/chromium/issues/detail?id=8081
}

Convert sandbox NOTIMPLEMENTED()s into a bug.


// RUN: %clang_cc1 -emit-llvm -o - -triple x86_64-apple-darwin %s | FileCheck %s
// <rdar://problem/11043589>

struct Length {
  Length(double v) {
    m_floatValue = static_cast<float>(v);
  }

  bool operator==(const Length& o) const {
    return getFloatValue() == o.getFloatValue();
  }
  bool operator!=(const Length& o) const { return !(*this == o); }
private:
  float getFloatValue() const {
    return m_floatValue;
  }
  float m_floatValue;
};

struct Foo {
  static Length inchLength(double inch);
  static bool getPageSizeFromName(const Length &A) {
    static const Length legalWidth = inchLength(8.5);
    if (A != legalWidth) return true;
    return false;
  }
};

// CHECK: @_ZZN3Foo19getPageSizeFromNameERK6LengthE10legalWidth = linkonce_odr global %struct.Length zeroinitializer, align 4
// CHECK: store float %call, float* getelementptr inbounds (%struct.Length* @_ZZN3Foo19getPageSizeFromNameERK6LengthE10legalWidth, i32 0, i32 0), align 1

bool bar(Length &b) {
  Foo f;
  return f.getPageSizeFromName(b);
}

// RUN: %clang_cc1 -emit-llvm -o - -triple x86_64-apple-darwin %s | FileCheck %s
// <rdar://problem/11043589>

struct Length {
  Length(double v) {
    m_floatValue = static_cast<float>(v);
  }

  bool operator==(const Length& o) const {
    return getFloatValue() == o.getFloatValue();
  }
  bool operator!=(const Length& o) const { return !(*this == o); }
private:
  float getFloatValue() const {
    return m_floatValue;
  }
  float m_floatValue;
};

struct Foo {
  static Length inchLength(double inch);
  static bool getPageSizeFromName(const Length &A) {
    static const Length legalWidth = inchLength(8.5);
    if (A != legalWidth) return true;
    return false;
  }
};

// CHECK: @_ZZN3Foo19getPageSizeFromNameERK6LengthE10legalWidth = linkonce_odr global %struct.Length zeroinitializer, align 4
// CHECK: store float %{{.*}}, float* getelementptr inbounds (%struct.Length* @_ZZN3Foo19getPageSizeFromNameERK6LengthE10legalWidth, i32 0, i32 0), align 1

bool bar(Length &b) {
  Foo f;
  return f.getPageSizeFromName(b);
}

Make the storing variable's name generic.


#include "vast/sink/json.h"
#include "vast/util/json.h"

namespace vast {
namespace sink {

json::json(path p)
  : stream_{std::move(p)}
{
}

bool json::process(event const& e)
{
  auto j = to<util::json>(e);
  if (! j)
    return false;

  auto str = to_string(*j);
  str += '\n';

  return stream_.write(str.begin(), str.end());
}

std::string json::describe() const
{
  return "json-sink";
}

} // namespace sink
} // namespace vast

#include "vast/sink/json.h"
#include "vast/util/json.h"

namespace vast {
namespace sink {

json::json(path p)
  : stream_{std::move(p)}
{
}

bool json::process(event const& e)
{
  auto j = to<util::json>(e);
  if (! j)
    return false;

  auto str = to_string(*j, true);
  str += '\n';

  return stream_.write(str.begin(), str.end());
}

std::string json::describe() const
{
  return "json-sink";
}

} // namespace sink
} // namespace vast

Print JSON in tree format.


#include <gtest/gtest.h>

#include <chrono>
#include <iostream>
#include <random>
#include <string>
#include <thread>

#include "priority.pb.h"
#include "prioritybuffer.h"

#define NUM_ITEMS 1000

unsigned long long get_priority(const PriorityMessage& message) {
    return message.priority();
}

TEST(PriorityProtobufTests, RandomPriorityTest) {
    PriorityBuffer<PriorityMessage> buffer{get_priority};
    std::default_random_engine generator;
    std::uniform_int_distribution<unsigned long long> distribution(0, 100LL);
    for (int i = 0; i < NUM_ITEMS; ++i) {
        PriorityMessage message;
        auto priority = distribution(generator);
        message.set_priority(priority);
        EXPECT_EQ(priority, message.priority());
        message.CheckInitialized();
        buffer.Push(message);
    }
    unsigned long long priority = 100LL;
    for (int i = 0; i < NUM_ITEMS; ++i) {
        auto message = buffer.Pop();
        message.CheckInitialized();
        EXPECT_GE(priority, message.priority());
        priority = message.priority();
    }
}

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

#include <gtest/gtest.h>

#include <chrono>
#include <iostream>
#include <random>
#include <string>
#include <thread>

#include "priority.pb.h"
#include "prioritybuffer.h"

#define NUM_ITEMS 1000

unsigned long long get_priority(const PriorityMessage& message) {
    return message.priority();
}

TEST(PriorityProtobufTests, RandomPriorityTest) {
    PriorityBuffer<PriorityMessage> buffer{get_priority};
    std::random_device generator;
    std::uniform_int_distribution<unsigned long long> distribution(0, 100LL);
    for (int i = 0; i < NUM_ITEMS; ++i) {
        PriorityMessage message;
        auto priority = distribution(generator);
        message.set_priority(priority);
        EXPECT_EQ(priority, message.priority());
        message.CheckInitialized();
        buffer.Push(message);
    }
    unsigned long long priority = 100LL;
    for (int i = 0; i < NUM_ITEMS; ++i) {
        auto message = buffer.Pop();
        message.CheckInitialized();
        EXPECT_GE(priority, message.priority());
        priority = message.priority();
    }
}

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

Use a true random number generator in the priority protobuf test


// This file is part of MicroRestD <http://github.com/ufal/microrestd/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <cstdio>

#include "microrestd.h"

using namespace ufal::microrestd;

int main(void) {
  xml_builder xml;

  xml.element("nazdar");
  xml.indent().text("text-<nazdar");
  xml.indent().element("test").attribute("test", "value");
  xml.indent().text("text->test");
  xml.indent().close();
  xml.indent().text("text-&nazdar");
  xml.indent().element("pokus").attribute("attr", nullptr).close();
  xml.indent().close();

  auto data = xml.current();
  printf("%*s", int(data.len), data.str);

  return 0;
}

// This file is part of MicroRestD <http://github.com/ufal/microrestd/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <cstdio>

#include "microrestd.h"

using namespace ufal::microrestd;

int main(void) {
  xml_builder xml;

  xml.element("nazdar");
  xml.indent().text("text-<nazdar");
  xml.indent().element("test").attribute("test", "value");
  xml.indent().text("text->test");
  xml.indent().close();
  xml.indent().text("text-&nazdar");
  xml.indent().element("pokus").attribute("attr", nullptr).close();
  xml.indent().close();

  auto data = xml.current();
  printf("%*s\n", int(data.len), data.str);

  return 0;
}

Write newline after serialized XML.


#include "dashboardcontroller.h"
#include "serialization/result.h"
#include "infrastructure/contentservice.h"
#include <fstream>

ApiMock::DashboardController::DashboardController(ContentService* content)
	: _content(content) {}

ApiMock::ResponseData ApiMock::DashboardController::get(RequestData request) {
	auto content = _content->getContent("www/app/index.html");
	RawResult c(content.content, content.mimeType);
	return createResponse(HTTP_OK, &c);
}

#include "dashboardcontroller.h"
#include "serialization/result.h"
#include "infrastructure/contentservice.h"
#include <fstream>
#include <infrastructure/exceptions.h>

ApiMock::DashboardController::DashboardController(ContentService* content)
	: _content(content) {}

ApiMock::ResponseData ApiMock::DashboardController::get(RequestData request) {
	try {
		auto content = _content->getContent("www/app/index.html");
		RawResult c(content.content, content.mimeType);
		return createResponse(HTTP_OK, &c);
	}
	catch (FileNotFoundException e) {
		return createResponse(HTTP_NOT_FOUND);
	}
}

Return 404's when expected dashboard file missing


// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "PlatformNix.h"
#include "Framework.h"

#if !defined(_WINDOWS)

namespace Foundation
{
    std::string PlatformNix::GetApplicationDataDirectory()
    {
        char *ppath = NULL;
        ppath = getenv("HOME");
        if (ppath == NULL)
            throw Core::Exception("Failed to get HOME environment variable.");

        std::string path(ppath);
        return path + "/." + framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name");
    }

    std::wstring PlatformNix::GetApplicationDataDirectoryW()
    {
        // Unicode not supported on Unix-based platforms

        std::string path = GetApplicationDataDirectory();

        return (Core::ToWString(path));
    }

    std::string PlatformNix::GetUserDocumentsDirectory()
    {
        return GetApplicationDataDirectory();
    }

    std::wstring PlatformNix::GetUserDocumentsDirectoryW()
    {
        return GetApplicationDataDirectoryW();
    }
}

#endif

// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "PlatformNix.h"
#include "Framework.h"

#if !defined(_WINDOWS)

namespace Foundation
{
    std::string PlatformNix::GetApplicationDataDirectory()
    {
        char *ppath = NULL;
        ppath = getenv("HOME");
        if (ppath == NULL)
            throw Core::Exception("Failed to get HOME environment variable.");

        std::string path(ppath);
        return path + "/." + framework_->GetDefaultConfig().GetSetting<std::string>(Framework::ConfigurationGroup(), "application_name");
    }

    std::wstring PlatformNix::GetApplicationDataDirectoryW()
    {
        // Unicode not supported on Unix-based platforms

        std::string path = GetApplicationDataDirectory();

        return (Core::ToWString(path));
    }

    std::string PlatformNix::GetUserDocumentsDirectory()
    {
        return GetApplicationDataDirectory();
    }

    std::wstring PlatformNix::GetUserDocumentsDirectoryW()
    {
        return GetApplicationDataDirectoryW();
    }
}

#endif

Fix getting application name config string on non-windows systems.


/// Project-level integration tests
#include "stdafx.h"
#include <CppUnitTest.h>

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace NLP {
namespace Tests {

TEST_CLASS(NlpTests) {
public:
};

}  // namespace Tests
}  // namespace NLP
}  // namespace You

/// Project-level integration tests
#include "stdafx.h"
#include <CppUnitTest.h>

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace NLP {
namespace UnitTests {

TEST_CLASS(NlpTests) {
public:
};

}  // namespace UnitTests
}  // namespace NLP
}  // namespace You

Exclude the NLP Tests class also.


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "SearchMenuPerformedSearchMessageHandler.h"

namespace ExampleApp
{
    namespace SearchMenu
    {
        namespace SdkModel
        {
            SearchMenuPerformedSearchMessageHandler::SearchMenuPerformedSearchMessageHandler(Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer,
                                                                                ExampleAppMessaging::TMessageBus& messageBus,
                                                                                Metrics::IMetricsService& metricsService)
            : m_searchQueryPerformer(searchQueryPerformer)
            , m_messageBus(messageBus)
            , m_metricsService(metricsService)
            , m_handlePerformedSearchMessageBinding(this, &SearchMenuPerformedSearchMessageHandler::OnPerformedSearchMessage)
            {
                m_messageBus.SubscribeNative(m_handlePerformedSearchMessageBinding);
            }

            SearchMenuPerformedSearchMessageHandler::~SearchMenuPerformedSearchMessageHandler()
            {
                m_messageBus.UnsubscribeNative(m_handlePerformedSearchMessageBinding);
            }

            void SearchMenuPerformedSearchMessageHandler::OnPerformedSearchMessage(const SearchMenuPerformedSearchMessage& message)
            {
                m_metricsService.SetEvent("Search", "Search string", message.SearchQuery().c_str());
                m_searchQueryPerformer.PerformSearchQuery(message.SearchQuery(), message.IsTag(), message.IsInterior());
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "SearchMenuPerformedSearchMessageHandler.h"

namespace ExampleApp
{
    namespace SearchMenu
    {
        namespace SdkModel
        {
            SearchMenuPerformedSearchMessageHandler::SearchMenuPerformedSearchMessageHandler(Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer,
                                                                                ExampleAppMessaging::TMessageBus& messageBus,
                                                                                Metrics::IMetricsService& metricsService)
            : m_searchQueryPerformer(searchQueryPerformer)
            , m_messageBus(messageBus)
            , m_metricsService(metricsService)
            , m_handlePerformedSearchMessageBinding(this, &SearchMenuPerformedSearchMessageHandler::OnPerformedSearchMessage)
            {
                m_messageBus.SubscribeNative(m_handlePerformedSearchMessageBinding);
            }

            SearchMenuPerformedSearchMessageHandler::~SearchMenuPerformedSearchMessageHandler()
            {
                m_messageBus.UnsubscribeNative(m_handlePerformedSearchMessageBinding);
            }

            void SearchMenuPerformedSearchMessageHandler::OnPerformedSearchMessage(const SearchMenuPerformedSearchMessage& message)
            {
                m_searchQueryPerformer.RemoveSearchQueryResults();
                m_metricsService.SetEvent("Search", "Search string", message.SearchQuery().c_str());
                m_searchQueryPerformer.PerformSearchQuery(message.SearchQuery(), message.IsTag(), message.IsInterior());
            }
        }
    }
}

Fix MPLY-9622 - Re-running search using Search button after selecting a result will not show all rooms as highlighted Buddy:Jordan.Brown


/*
*
Just playing around with binary and linear search. No idea.
*/

#include <iostream>
using namespace std;

int foo[10] = { 2, 16, 40, 77, 88, 99, 105, 120, 150 };
int n, result = 0;
int length = 10;

int sillySearch(int element) {

	//Figure out array length and make first split
	length = length / 2;
	result = foo[length];

		if (result < element)
		{
			while (length<10) {
				result = foo[(length)];
				length++;
				if (result == element) {
					return result;
				}
			}
		}
		else
		{
			while (length>0) {
				result = foo[(length)];
				length--;
				if (result == element) {
					return result;
				}
			}
		}

	return -1;
}

int main(int argc, char argv[])
{
	//first sort the array ascenging order
	int tell = sillySearch(40);
	cout << tell;
	cout << "Hello\n";
}

/*
*
Implementing binary search
*/

#include <iostream>
using namespace std;

//get rid of fixed array
int foo[10] = { 2, 16, 40, 77, 88, 99, 105, 120, 150 };

int sillySearch(int element) {

	int minIndex = 0;
	int maxIndex = 10 - 1; //array.length here plz
	int curElement, curIndex;

	while (minIndex < maxIndex) {

		curIndex = (minIndex + maxIndex) / 2 | 0;
		curElement = foo[curIndex];
		//curElement = foo[(minIndex + maxIndex) / 2 | 0];

		if (curElement < element)
		{
			minIndex = curIndex + 1;
		}
		else if (curElement > element)
		{
			maxIndex = curIndex + 1;
		}
		else {
			return curIndex;
		}
	}

	return -1;
}

int main(int argc, char argv[])
{
	//first sort the array ascenging order
	int tell = sillySearch(40);
	cout << tell;
	cout << "Hello World Once Again!\n";
}

Add more proper pure BinarySearch algorithm removing linear search


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

#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <util/error.h>

#include <cstdint>
#include <vector>

// The fuzzing kitchen sink: Fuzzing harness for functions that need to be
// fuzzed but a.) don't belong in any existing fuzzing harness file, and
// b.) are not important enough to warrant their own fuzzing harness file.
void test_one_input(const std::vector<uint8_t>& buffer)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());

    const TransactionError transaction_error = fuzzed_data_provider.PickValueInArray<TransactionError>({TransactionError::OK, TransactionError::MISSING_INPUTS, TransactionError::ALREADY_IN_CHAIN, TransactionError::P2P_DISABLED, TransactionError::MEMPOOL_REJECTED, TransactionError::MEMPOOL_ERROR, TransactionError::INVALID_PSBT, TransactionError::PSBT_MISMATCH, TransactionError::SIGHASH_MISMATCH, TransactionError::MAX_FEE_EXCEEDED});
    (void)TransactionErrorString(transaction_error);
}

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

#include <rpc/util.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <util/error.h>

#include <cstdint>
#include <vector>

// The fuzzing kitchen sink: Fuzzing harness for functions that need to be
// fuzzed but a.) don't belong in any existing fuzzing harness file, and
// b.) are not important enough to warrant their own fuzzing harness file.
void test_one_input(const std::vector<uint8_t>& buffer)
{
    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());

    const TransactionError transaction_error = fuzzed_data_provider.PickValueInArray<TransactionError>({TransactionError::OK, TransactionError::MISSING_INPUTS, TransactionError::ALREADY_IN_CHAIN, TransactionError::P2P_DISABLED, TransactionError::MEMPOOL_REJECTED, TransactionError::MEMPOOL_ERROR, TransactionError::INVALID_PSBT, TransactionError::PSBT_MISMATCH, TransactionError::SIGHASH_MISMATCH, TransactionError::MAX_FEE_EXCEEDED});
    (void)JSONRPCTransactionError(transaction_error);
    (void)RPCErrorFromTransactionError(transaction_error);
    (void)TransactionErrorString(transaction_error);
}

Add fuzzing coverage for JSONRPCTransactionError(...) and RPCErrorFromTransactionError(...)


#include "PermuteTestResult.h"

namespace fs_testing {

using std::ostream;
using std::string;
using std::to_string;

ostream& PermuteTestResult::PrintCrashState(ostream& os) const {
  for (unsigned int i = 0; i < crash_state.size() - 1; ++i) {
    os << to_string(crash_state.at(i)) << ", ";
  }
  os << to_string(crash_state.back());
  return os;
}

}  // namespace fs_testing

#include "PermuteTestResult.h"

namespace fs_testing {

using std::ostream;
using std::string;
using std::to_string;

ostream& PermuteTestResult::PrintCrashState(ostream& os) const {
  if (crash_state.size() == 0) {
    return os;
  }
  for (unsigned int i = 0; i < crash_state.size() - 1; ++i) {
    os << to_string(crash_state.at(i)) << ", ";
  }
  os << to_string(crash_state.back());
  return os;
}

}  // namespace fs_testing

Fix out of bounds exception when printing crash states.


#include <string>

#include <libport/pthread.h>
#include <libport/unit-test.hh>

using libport::test_suite;

std::string truth("vim is future");

void* thread1(void* data)
{
  std::string del((char *) data);
  size_t pos = truth.find(del);
  truth.erase(pos, pos + del.size());
  return 0;
}

void* thread2(void* data)
{
  pthread_join(*(pthread_t *)data, 0);
  truth.insert(0, "emacs");
  return (void*)0xdeadbeef;
}

void test_pthread()
{
  pthread_t my_thread[2];
  char* vim = "vim";
  void* ret;

  BOOST_CHECK(!pthread_create(my_thread, 0, &thread1, vim));
  BOOST_CHECK(!pthread_create(my_thread + 1, 0, &thread2, my_thread));
  pthread_join(my_thread[1], &ret);
  BOOST_CHECK_EQUAL(ret, (void*)0xdeadbeef);
  BOOST_CHECK_EQUAL(truth, "emacs is future");
}

test_suite*
init_test_suite()
{
  test_suite* suite = BOOST_TEST_SUITE("libport::semaphore");
  suite->add(BOOST_TEST_CASE(test_pthread));
  return suite;
}

#include <string>

#include <libport/pthread.h>
#include <libport/unit-test.hh>

using libport::test_suite;

std::string truth("vim is future");

void* thread1(void* data)
{
  std::string del((char *) data);
  size_t pos = truth.find(del);
  truth.erase(pos, pos + del.size());
  return 0;
}

void* thread2(void* data)
{
  pthread_join(*(pthread_t *)data, 0);
  truth.insert(0, "emacs");
  return (void*)0xdeadbeef;
}

void test_pthread()
{
  pthread_t my_thread[2];
  const char* vim = "vim";
  void* ret;

  BOOST_CHECK(!pthread_create(my_thread, 0, &thread1, (char*)vim));
  BOOST_CHECK(!pthread_create(my_thread + 1, 0, &thread2, my_thread));
  pthread_join(my_thread[1], &ret);
  BOOST_CHECK_EQUAL(ret, (void*)0xdeadbeef);
  BOOST_CHECK_EQUAL(truth, "emacs is future");
}

test_suite*
init_test_suite()
{
  test_suite* suite = BOOST_TEST_SUITE("libport::semaphore");
  suite->add(BOOST_TEST_CASE(test_pthread));
  return suite;
}

Fix non-const literal string warning with g++ 4.3.


//
// Aspia Project
// Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// 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 <https://www.gnu.org/licenses/>.
//

#include "host/desktop_agent_main.h"

#include <Windows.h>

int WINAPI wWinMain(HINSTANCE /* hInstance */,
                    HINSTANCE /* hPrevInstance */,
                    LPWSTR /* lpCmdLine */,
                    int /* nCmdShow */)
{
    desktopAgentMain(0, nullptr); // On Windows ignores arguments.
    return 0;
}

//
// Aspia Project
// Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// 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 <https://www.gnu.org/licenses/>.
//

#include "build/build_config.h"
#include "host/desktop_agent_main.h"

#if defined(OS_WIN)
#include <Windows.h>

int WINAPI wWinMain(HINSTANCE /* hInstance */,
                    HINSTANCE /* hPrevInstance */,
                    LPWSTR /* lpCmdLine */,
                    int /* nCmdShow */)
{
    desktopAgentMain(0, nullptr); // On Windows ignores arguments.
    return 0;
}

#else

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

#endif

Fix host building in Linux (part 15/x).


// RUN: %clang_cc1 -fsyntax-only -verify %s -Wmissing-noreturn
void f() __attribute__((noreturn));

template<typename T> void g(T) { // expected-warning {{function could be attribute 'noreturn'}}
  f();
}

template void g<int>(int); // expected-note {{in instantiation of function template specialization 'g<int>' requested here}}

template<typename T> struct A {
  void g() { // expected-warning {{function could be attribute 'noreturn'}}
    f();
  }
};

template struct A<int>; // expected-note {{in instantiation of member function 'A<int>::g' requested here}}

struct B {
  template<typename T> void g(T) { // expected-warning {{function could be attribute 'noreturn'}}
    f();
  }
};

template void B::g<int>(int); // expected-note {{in instantiation of function template specialization 'B::g<int>' requested here}}

// We don't want a warning here.
struct X {
  virtual void g() { f(); }
};

namespace test1 {
  bool condition();

  // We don't want a warning here.
  void foo() {
    while (condition()) {}
  }
}

// <rdar://problem/7880658> - This test case previously had a false "missing return"
// warning.
struct R7880658 {
  R7880658 &operator++();
  bool operator==(const R7880658 &) const;
  bool operator!=(const R7880658 &) const;
};

void f_R7880658(R7880658 f, R7880658 l) {  // no-warning
  for (; f != l; ++f) {
  }
}

Add test case for <rdar://problem/7880658>.