#include "hackypassabilityagent.h"

#include <QQuickItem>
#include <QQuickWindow>

#include "quickentity.h"
#include "utils.h"

HackyPassabilityAgent::HackyPassabilityAgent() :
    mGridItem(nullptr)
{
}

bool HackyPassabilityAgent::isPassable(const QPointF &pos, AbstractEntity *entity)
{
    if (!mGridItem)
        return false;

    QuickEntity *quickEntity = dynamic_cast<QuickEntity*>(entity);
    Q_ASSERT(quickEntity);

    // very basic, hacky check that doesn't take into account a radius.
    QQuickItem *child = mGridItem->childAt(pos.x(), pos.y());
    if (child->property("blocksMovement").toBool()) {
        return false;
    }

    return true;
}

QQuickItem *HackyPassabilityAgent::gridItem() const
{
    return mGridItem;
}

void HackyPassabilityAgent::setGridItem(QQuickItem *gridItem)
{
    if (gridItem == mGridItem)
        return;

    mGridItem = gridItem;
    emit gridItemChanged();
}

#include "hackypassabilityagent.h"

#include <QQuickItem>
#include <QQuickWindow>

#include "quickentity.h"
#include "utils.h"

HackyPassabilityAgent::HackyPassabilityAgent() :
    mGridItem(nullptr)
{
}

bool HackyPassabilityAgent::isPassable(const QPointF &pos, AbstractEntity *entity)
{
    if (!mGridItem)
        return false;

    QuickEntity *quickEntity = dynamic_cast<QuickEntity*>(entity);
    Q_ASSERT(quickEntity);

    // very basic, hacky check that doesn't take into account a radius.
    QQuickItem *child = mGridItem->childAt(pos.x(), pos.y());
    if (child && child->property("blocksMovement").toBool()) {
        return false;
    }

    return true;
}

QQuickItem *HackyPassabilityAgent::gridItem() const
{
    return mGridItem;
}

void HackyPassabilityAgent::setGridItem(QQuickItem *gridItem)
{
    if (gridItem == mGridItem)
        return;

    mGridItem = gridItem;
    emit gridItemChanged();
}

Fix null pointer access in HackyPassabilityAgent


#include "Client.hh"

#include <string>
#include "Socket.hh"
#include "http/Response.hh"
#include "http/Request.hh"
#include "methods/Get.hh"
#include "Config.hh"

ss::Client::Client(Socket* socket) : socket(socket)
{
	auto request = get_request();
	http::Response response;
	response.headers["protocol"] = "HTTP/1.1";

	if (request.headers["method"] == "GET")
	{
		methods::Get(request, &response);
	}

	send_response(response);
}

ss::http::Request ss::Client::get_request()
{
	std::string response;

	// An endless wait may happen if the last response is the same size as buffer.
	while (true)
	{
		char buffer[1024];
		int received;
		socket->receive(&buffer, sizeof(buffer), &received);
		response.append(buffer, received);

		if (received < sizeof(buffer))
		{
			break;
		}
	}

	return http::Request(response);
}

void ss::Client::send_response(const http::Response& response)
{
	const auto response_string = response.as_string();
	socket->send(response_string.data(), response_string.size());
	socket->disconnect();
}

#include "Client.hh"

#include <string>
#include "Socket.hh"
#include "http/Response.hh"
#include "http/Request.hh"
#include "methods/Get.hh"
#include "Config.hh"

ss::Client::Client(Socket* socket) : socket(socket)
{
	auto request = get_request();
	http::Response response;
	response.headers["protocol"] = "HTTP/1.1";

	if (request.headers["method"] == "GET")
	{
		methods::Get(request, &response);
	}

	send_response(response);
}

ss::http::Request ss::Client::get_request()
{
	std::string response;

  char buffer[1024];
	int received = sizeof(buffer);
	// An endless wait may happen if the last response is the same size as buffer.
  while (received == sizeof(buffer)) {
		socket->receive(&buffer, sizeof(buffer), &received);
		response.append(buffer, received);
	}

	return http::Request(response);
}

void ss::Client::send_response(const http::Response& response)
{
	const auto response_string = response.as_string();
	socket->send(response_string.data(), response_string.size());
	socket->disconnect();
}

Make while loop more compact


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

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

See LICENSE.txt or http://www.mitk.org for details.

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

#include "QmitkToolGUI.h"

#include <iostream>

QmitkToolGUI::~QmitkToolGUI()
{
  m_ReferenceCountLock.Lock();
  m_ReferenceCount = 0; // otherwise ITK will complain in LightObject's destructor
  m_ReferenceCountLock.Unlock();
}

void QmitkToolGUI::Register() const
{
  // empty on purpose, just don't let ITK handle calls to Register()
}

void QmitkToolGUI::UnRegister() const
{
  // empty on purpose, just don't let ITK handle calls to UnRegister()
}

void QmitkToolGUI::SetReferenceCount(int)
{
  // empty on purpose, just don't let ITK handle calls to SetReferenceCount()
}

void QmitkToolGUI::SetTool( mitk::Tool* tool )
{
  m_Tool = tool;

  emit( NewToolAssociated(tool) );
}

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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

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

See LICENSE.txt or http://www.mitk.org for details.

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

#include "QmitkToolGUI.h"

#include <iostream>

QmitkToolGUI::~QmitkToolGUI()
{
  m_ReferenceCountLock.Lock();
  m_ReferenceCount = 0; // otherwise ITK will complain in LightObject's destructor
  m_ReferenceCountLock.Unlock();
}

void QmitkToolGUI::Register() const
{
  // empty on purpose, just don't let ITK handle calls to Register()
}

void QmitkToolGUI::UnRegister() const ITK_NOEXCEPT
{
  // empty on purpose, just don't let ITK handle calls to UnRegister()
}

void QmitkToolGUI::SetReferenceCount(int)
{
  // empty on purpose, just don't let ITK handle calls to SetReferenceCount()
}

void QmitkToolGUI::SetTool( mitk::Tool* tool )
{
  m_Tool = tool;

  emit( NewToolAssociated(tool) );
}

Add missing keyword to UnRegister definition


#include <iostream>

//Thomas' Prototypes

//Hannah's Prototypes

int atomic_distance (int distance); //Kate's Prototype: defines atomic distance as integer

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

#include <iostream>

//Thomas' Prototypes

//Hannah's Prototypes

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

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

Update to Kate's First Function Prototype


// 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 "base/native_library.h"

#include <dlfcn.h>

#include "base/file_path.h"
#include "base/logging.h"

namespace base {

// static
NativeLibrary LoadNativeLibrary(const FilePath& library_path) {
  void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY);
  if (!dl)
    NOTREACHED() << "dlopen failed: " << dlerror();

  return dl;
}

// static
void UnloadNativeLibrary(NativeLibrary library) {
  int ret = dlclose(library);
  if (ret < 0)
    NOTREACHED() << "dlclose failed: " << dlerror();
}

// static
void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
                                          NativeLibraryFunctionNameType name) {
  return dlsym(library, name);
}

}  // namespace base

// 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 "base/native_library.h"

#include <dlfcn.h>

#include "base/file_path.h"
#include "base/logging.h"

namespace base {

// static
NativeLibrary LoadNativeLibrary(const FilePath& library_path) {
  void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY|RTLD_DEEPBIND);
  if (!dl)
    NOTREACHED() << "dlopen failed: " << dlerror();

  return dl;
}

// static
void UnloadNativeLibrary(NativeLibrary library) {
  int ret = dlclose(library);
  if (ret < 0)
    NOTREACHED() << "dlclose failed: " << dlerror();
}

// static
void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
                                          NativeLibraryFunctionNameType name) {
  return dlsym(library, name);
}

}  // namespace base

Use RTLD_DEEPBIND to make sure plugins don't use Chrome's symbols instead of their own


#include "KAI/Console/Console.h"

#include <iostream>

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif

using namespace std;

USING_NAMESPACE_KAI

//static Color _color;

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

	cout << "pyro v0.1" << endl;

	Console console;
	console.SetLanguage(Language::Pi);

	Process::trace = 0;
	console.GetExecutor()->SetTraceLevel(0);

	return console.Run();
}

#include <KAI/Console/Console.h>
#include <iostream>

using namespace std;

USING_NAMESPACE_KAI

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

	cout << "KAI v0.1" << endl;

	Console console;
	console.SetLanguage(Language::Pi);

	// the higher the number, the greater the verbosity of debug output
	Process::trace = 0;
	console.GetExecutor()->SetTraceLevel(0);

	// start the REPL
	return console.Run();
}

Remove explicit WIN32 references from Console app.


// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Models/Enchantment.hpp>
#include <Rosetta/Tasks/SimpleTasks/RemoveEnchantmentTask.hpp>

namespace RosettaStone::SimpleTasks
{
TaskID RemoveEnchantmentTask::GetTaskID() const
{
    return TaskID::REMOVE_ENCHANTMENT;
}

TaskStatus RemoveEnchantmentTask::Impl(Player&)
{
    auto enchantment = dynamic_cast<Enchantment*>(m_source);
    if (enchantment == nullptr)
    {
        return TaskStatus::STOP;
    }

    enchantment->Remove();

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Models/Enchantment.hpp>
#include <Rosetta/Tasks/SimpleTasks/RemoveEnchantmentTask.hpp>

namespace RosettaStone::SimpleTasks
{
TaskID RemoveEnchantmentTask::GetTaskID() const
{
    return TaskID::REMOVE_ENCHANTMENT;
}

TaskStatus RemoveEnchantmentTask::Impl(Player&)
{
    auto enchantment = dynamic_cast<Enchantment*>(m_source);
    if (enchantment == nullptr)
    {
        return TaskStatus::STOP;
    }

    if (enchantment->card.power.GetEnchant() != nullptr)
    {
        for (auto& effect : enchantment->card.power.GetEnchant()->effects)
        {
            effect->Remove(m_target);
        }
    }

    enchantment->Remove();

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

Add code to remove effects


#include <boost/log/trivial.hpp>
#include <boost/program_options.hpp>

#include <dsnutil/log/init.h>

namespace po = boost::program_options;

int main(int argc, char** argv)
{
    dsn::log::init();

    try {
        po::options_description descr;
        descr.add_options()("help,?", "Display list of valid arguments");

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, descr), vm);
        po::notify(vm);
    }

    catch (po::error& ex) {
        BOOST_LOG_TRIVIAL(error) << "Failed to parse command line arguments: " << ex.what();
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

#include <iostream>

#include <boost/log/trivial.hpp>
#include <boost/program_options.hpp>

#include <dsnutil/log/init.h>
#include <build-bot/bot.h>

namespace po = boost::program_options;

int main(int argc, char** argv)
{
    dsn::log::init();

    std::string configFile;
    try {
        po::options_description descr;
        descr.add_options()("help,?", "Display list of valid arguments");
        descr.add_options()("config,c", po::value<std::string>()->required()->default_value(dsn::build_bot::Bot::DEFAULT_CONFIG_FILE), "Path to configuration file");

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, descr), vm);
        po::notify(vm);

        if (vm.count("help")) {
            std::cerr << descr << std::endl;
            return EXIT_SUCCESS;
        }

        configFile = vm["config"].as<std::string>();
    }

    catch (po::error& ex) {
        BOOST_LOG_TRIVIAL(error) << "Failed to parse command line arguments: " << ex.what();
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

Add parameter for config file


/***************************************************************************
 *  @file       The code is for the exercises in C++ Primmer 5th Edition
 *  @author     @Yue Wang @gupenghu
 *  @date       29.11.2014
 *  @remark
 ***************************************************************************/

//!
//! Exercise 12.26:
//! Rewrite the program on page 481 using an allocator.
//!

#include <iostream>
#include <memory>
int main()
{
    //! create a allocator object and use it to handle string.
    //! create a movable pointer to the address p points
    std::allocator<std::string> alloc;
    std::string* const p = alloc.allocate(5);
    std::string* p_movable = p;

    //! constuct each object using copy constructor
    std::cout << "enter 4 times\n";
    for(std::string word ;std::cin >> word && p_movable != p + 3; ++p_movable)
        alloc.construct(p_movable,word);

    //! move the movable pointer back home
    p_movable = p;

    //! print the strings constructed.
    for( ;  p_movable != p + 3; ++p_movable){
        std::cout << *p_movable <<"\n";
        alloc.destroy(p_movable);
    }

    //! free the allocated memory.
    alloc.deallocate(p, 5);
    std::cout << "exit normally\n";
    return 0;
}
//! output
//!
//enter 4 times
//ss
//ss
//ss
//ss
//ss
//ss
//ss
//exit normally

/***************************************************************************
 *  @file       The code is for the exercises in C++ Primmer 5th Edition
 *  @author     @Yue Wang @gupenghu
 *  @date       29.11.2014
 *  @remark
 ***************************************************************************/

//!
//! Exercise 12.26:
//! Rewrite the program on page 481 using an allocator.
//!

#include <iostream>
#include <memory>
int main()
{
    //! create a allocator object and use it to handle string.
    //! create a movable pointer to the address p points
    std::allocator<std::string> alloc;
    std::string* const p = alloc.allocate(5);
    std::string* p_movable = p;

    //! constuct each object using copy constructor
    std::cout << "enter 4 times\n";
    for(std::string word ;std::cin >> word and p_movable != p + 3; ++p_movable)
        alloc.construct(p_movable,word);

    //! move the movable pointer back home
    p_movable = p;

    //! print the strings constructed.
    for( ;  p_movable != p + 3; ++p_movable){
        std::cout << *p_movable <<"\n";
        alloc.destroy(p_movable);
    }

    //! free the allocated memory.
    alloc.deallocate(p, 5);
    std::cout << "exit normally\n";
    return 0;
}
//! output
//!
//enter 4 times
//ss
//ss
//ss
//ss
//ss
//ss
//ss
//exit normally

Replace && with and for readability.


/*
 * Copyright 2016 - 2021 gary@drinkingtea.net
 *
 * 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 <nostalgia/core/core.hpp>

#include "app.hpp"

static ox::Error run(int argc, const char **argv) noexcept {
	ox::trace::init();
	if (argc < 2) {
		oxErr("Please provide path to project directory or OxFS file.");
		return OxError(1);
	}
	const auto path = argv[1];
	oxRequire(fs, nostalgia::core::loadRomFs(path));
	return run(fs.get());
}

int main(int argc, const char **argv) {
	const auto err = run(argc, argv);
	oxAssert(err, "Something went wrong...");
	return static_cast<int>(err);
}

/*
 * Copyright 2016 - 2021 gary@drinkingtea.net
 *
 * 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 <nostalgia/core/core.hpp>

#include "app.hpp"

static ox::Error run(int argc, const char **argv) noexcept {
	ox::trace::init();
	if (argc < 2) {
		oxErr("Please provide path to project directory or OxFS file.\n");
		return OxError(1);
	}
	const auto path = argv[1];
	oxRequire(fs, nostalgia::core::loadRomFs(path));
	return run(fs.get());
}

int main(int argc, const char **argv) {
	const auto err = run(argc, argv);
	oxAssert(err, "Something went wrong...");
	return static_cast<int>(err);
}

Add new line to oxErr output


#include <miopen/hipoc_kernel.hpp>
#include <miopen/errors.hpp>
#include <hip/hip_hcc.h>

namespace miopen {

void HIPOCKernelInvoke::run(void* args, std::size_t size) const
{
    HipEventPtr start = nullptr;
    HipEventPtr stop = nullptr;
    void *config[] = {
        HIP_LAUNCH_PARAM_BUFFER_POINTER, args,
        HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
        HIP_LAUNCH_PARAM_END
    };
    if (callback)
    {
        start = make_hip_event();
        stop = make_hip_event();

        hipEventRecord(start.get(), stream);
    }

    // std::cerr << "Launch kernel: " << name << std::endl;
    auto status = hipHccModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config);
    if(status != hipSuccess) MIOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel");

    if (callback)
    {
        hipEventRecord(stop.get(), stream);
        hipEventSynchronize(stop.get());
        callback(start.get(), stop.get());
    }
}

HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback)
{
    return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback};
}
}

#include <miopen/hipoc_kernel.hpp>
#include <miopen/errors.hpp>
#include <hip/hip_hcc.h>

namespace miopen {

void HIPOCKernelInvoke::run(void* args, std::size_t size) const
{
    HipEventPtr start = nullptr;
    HipEventPtr stop = nullptr;
    void *config[] = {
        HIP_LAUNCH_PARAM_BUFFER_POINTER, args,
        HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
        HIP_LAUNCH_PARAM_END
    };
    if (callback)
    {
        start = make_hip_event();
        stop = make_hip_event();
    }

    // std::cerr << "Launch kernel: " << name << std::endl;
    auto status = hipHccModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config, start.get(), stop.get());
    if(status != hipSuccess) MIOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel");

    if (callback)
    {
        hipEventSynchronize(stop.get());
        callback(start.get(), stop.get());
    }
}

HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback)
{
    return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback};
}
}

Use more precise kernel timers for HIP.


// RUN: %clang_cc1 -fsyntax-only -std=c++17 -pedantic -verify %s
// RUN: %clang_cc1 -fsyntax-only -std=c++2a -Wc++17-compat-pedantic -verify %s

struct A {};
int (A::*pa)() const&;
int use_pa = (A().*pa)();
#if __cplusplus <= 201703L
  // expected-warning@-2 {{invoking a pointer to a 'const &' member function on an rvalue is a C++2a extension}}
#else
  // expected-warning@-4 {{invoking a pointer to a 'const &' member function on an rvalue is incompatible with C++ standards before C++2a}}
#endif

struct B {
  void b() {
    (void) [=, this] {};
#if __cplusplus <= 201703L
    // expected-warning@-2 {{explicit capture of 'this' with a capture default of '=' is a C++2a extension}}
#else
    // expected-warning@-4 {{explicit capture of 'this' with a capture default of '=' is incompatible with C++ standards before C++2a}}
#endif
  }
};

// RUN: %clang_cc1 -fsyntax-only -std=c++17 -pedantic -verify %s
// RUN: %clang_cc1 -fsyntax-only -std=c++2a -Wc++17-compat-pedantic -verify %s

struct A {};
int (A::*pa)() const&;
int use_pa = (A().*pa)();
#if __cplusplus <= 201703L
  // expected-warning@-2 {{invoking a pointer to a 'const &' member function on an rvalue is a C++2a extension}}
#else
  // expected-warning@-4 {{invoking a pointer to a 'const &' member function on an rvalue is incompatible with C++ standards before C++2a}}
#endif

struct B {
  void b() {
    (void) [=, this] {};
#if __cplusplus <= 201703L
    // expected-warning@-2 {{explicit capture of 'this' with a capture default of '=' is a C++2a extension}}
#else
    // expected-warning@-4 {{explicit capture of 'this' with a capture default of '=' is incompatible with C++ standards before C++2a}}
#endif
  }

  int n : 5 = 0;
#if __cplusplus <= 201703L
    // expected-warning@-2 {{default member initializer for bit-field is a C++2a extension}}
#else
    // expected-warning@-4 {{default member initializer for bit-field is incompatible with C++ standards before C++2a}}
#endif
};

Add test for -Wc++17-compat warning for P0683R1.


#include "../../valhalla/mjolnir/signbuilder.h"

using namespace valhalla::baldr;

namespace valhalla {
namespace mjolnir {

// Constructor with arguments
SignBuilder::SignBuilder(const uint32_t idx,
                                 const Sign::Type& type,
                                 const uint32_t text_offset)
    : Sign(idx, type, text_offset) {
}

// Set the directed edge index.
void SignBuilder::set_edgeindex(const uint32_t idx) {
  edgeindex_ = idx;
}

}
}

#include "../../valhalla/mjolnir/signbuilder.h"

using namespace valhalla::baldr;

namespace valhalla {
namespace mjolnir {

// Constructor with arguments
SignBuilder::SignBuilder(const uint32_t idx,
                                 const Sign::Type& type,
                                 const uint32_t text_offset)
    : Sign(idx, type, text_offset) {
}

// Set the directed edge index.
void SignBuilder::set_edgeindex(const uint32_t idx) {
  data_.edgeindex = idx;
}

}
}

Update to reflect changes to signs.


// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "Bitstrip.h"

Bitstrip::Bitstrip(std::wstring bitmapName, int x, int y, int units) :
Meter(bitmapName, x, y, units) {
    _rect.Height = _bitmap->GetHeight() / _units;
}

void Bitstrip::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
    int units = CalcUnits();
    int stripY = (units - 1) * _rect.Height;

    if (units == 0) {
        /* The mute OSD should be shown here, but we'll do something sane
         * rather than go negative. */
        stripY = 0;
    }

    graphics->DrawImage(_bitmap, _rect,
        0, stripY, _rect.Width, _rect.Height, Gdiplus::UnitPixel);

    UpdateDrawnValues();
}

// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "Bitstrip.h"

Bitstrip::Bitstrip(std::wstring bitmapName, int x, int y, int units) :
Meter(bitmapName, x, y, units) {
    _rect.Height = _bitmap->GetHeight() / _units;
}

void Bitstrip::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
    int units = CalcUnits();
    int stripY = (units - 1) * _rect.Height;

    if (units == 0) {
        /* The mute OSD should be shown here, but we'll do something sane
         * rather than go negative. */
        stripY = 0;
    }

    graphics->DrawImage(_bitmap, _rect, 0, stripY, _rect.Width, _rect.Height,
        Gdiplus::UnitPixel, &_imageAttributes, NULL, NULL);

    UpdateDrawnValues();
}

Enable color transformations for bitstrips


// RUN: %clang -flimit-debug-info -emit-llvm -g -S %s -o - | FileCheck %s

// CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "A"
// CHECK-NOT:              DIFlagFwdDecl
// CHECK-SAME:             ){{$}}
class A {
public:
  int z;
};

A *foo (A* x) {
  A *a = new A(*x);
  return a;
}

// CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "B"
// CHECK-SAME:             flags: DIFlagFwdDecl

class B {
public:
  int y;
};

extern int bar(B *b);
int baz(B *b) {
  return bar(b);
}

// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "C"
// CHECK-SAME:             flags: DIFlagFwdDecl

struct C {
};

C (*x)(C);

// RUN: %clang -flimit-debug-info -emit-llvm -g -S %s -o - | FileCheck %s
// RUN: %clang -flimit-debug-info -emit-llvm -g -S %s -o - | FileCheck --check-prefix=CHECK-C %s

// CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "A"
// CHECK-NOT:              DIFlagFwdDecl
// CHECK-SAME:             ){{$}}
class A {
public:
  int z;
};

A *foo (A* x) {
  A *a = new A(*x);
  return a;
}

// CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "B"
// CHECK-SAME:             flags: DIFlagFwdDecl

class B {
public:
  int y;
};

extern int bar(B *b);
int baz(B *b) {
  return bar(b);
}

// CHECK-C: !DICompositeType(tag: DW_TAG_structure_type, name: "C"
// CHECK-C-SAME:             flags: DIFlagFwdDecl

struct C {
};

C (*x)(C);

Fix testcase for MSVC targets where the output ordering is different.


// Copyright (c) 20109 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"

// This test failed at times on the Vista dbg builder and has been marked as
// flaky for now. Bug http://code.google.com/p/chromium/issues/detail?id=28630
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_ExecuteScript) {
  // We need a.com to be a little bit slow to trigger a race condition.
  host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500);
  host_resolver()->AddRule("b.com", "127.0.0.1");
  host_resolver()->AddRule("c.com", "127.0.0.1");
  StartHTTPServer();

  ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_;
  ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_;
  ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_;
}

// Copyright (c) 20109 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"

// EXTREMELY flaky, crashy, and bad. See http://crbug.com/28630 and don't dare
// to re-enable without a real fix or at least adding more debugging info.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_ExecuteScript) {
  // We need a.com to be a little bit slow to trigger a race condition.
  host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500);
  host_resolver()->AddRule("b.com", "127.0.0.1");
  host_resolver()->AddRule("c.com", "127.0.0.1");
  StartHTTPServer();

  ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_;
  ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_;
  ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_;
}

Mark ExtensionApiTest.ExecuteScript DISABLED because it's not only flaky, but crashy and it has been ignored for weeks!


#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>

int
main (int argc, char** argv)
{
  // Load input file into a PointCloud<T> with an appropriate type
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());
  // Load bun0.pcd -- should be available with the PCL archive in test
  pcl::io::loadPCDFile ("bun0.pcd", *cloud);

  // Create a KD-Tree
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);

  // Output has the PointNormal type in order to store the normals calculated by MLS
  pcl::PointCloud<pcl::PointNormal> mls_points;

  // Init object (second point type is for the normals, even if unused)
  pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal> mls;

  mls.setComputeNormals (true);

  // Set parameters
  mls.setInputCloud (cloud);
  mls.setPolynomialFit (true);
  mls.setSearchMethod (tree);
  mls.setSearchRadius (0.03);

  // Reconstruct
  mls.process (mls_points);

  // Save output
  pcl::io::savePCDFile ("bun0-mls.pcd", mls_points);
}

#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>

int
main (int argc, char** argv)
{
  // Load input file into a PointCloud<T> with an appropriate type
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());
  // Load bun0.pcd -- should be available with the PCL archive in test
  pcl::io::loadPCDFile ("bun0.pcd", *cloud);

  // Create a KD-Tree
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);

  // Output has the PointNormal type in order to store the normals calculated by MLS
  pcl::PointCloud<pcl::PointNormal> mls_points;

  // Init object (second point type is for the normals, even if unused)
  pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal> mls;

  mls.setComputeNormals (true);

  // Set parameters
  mls.setInputCloud (cloud);
  mls.setPolynomialOrder (2);
  mls.setSearchMethod (tree);
  mls.setSearchRadius (0.03);

  // Reconstruct
  mls.process (mls_points);

  // Save output
  pcl::io::savePCDFile ("bun0-mls.pcd", mls_points);
}

Fix deprecation warning in "Resampling" tutorial


// 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-CHROMIUM file.

#include "browser/browser_main_parts.h"

#include "browser/browser_context.h"
#include "browser/web_ui_controller_factory.h"
#include "net/proxy/proxy_resolver_v8.h"

namespace brightray {

BrowserMainParts::BrowserMainParts() {
}

BrowserMainParts::~BrowserMainParts() {
}

void BrowserMainParts::PreMainMessageLoopRun() {
  browser_context_.reset(CreateBrowserContext());
  browser_context_->Initialize();

  web_ui_controller_factory_.reset(
      new WebUIControllerFactory(browser_context_.get()));
  content::WebUIControllerFactory::RegisterFactory(
      web_ui_controller_factory_.get());
}

void BrowserMainParts::PostMainMessageLoopRun() {
  browser_context_.reset();
}

int BrowserMainParts::PreCreateThreads() {
#if defined(OS_WIN)
  net::ProxyResolverV8::CreateIsolate();
#else
  net::ProxyResolverV8::RememberDefaultIsolate();
#endif
  return 0;
}

BrowserContext* BrowserMainParts::CreateBrowserContext() {
  return new BrowserContext;
}

}  // namespace brightray

// 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-CHROMIUM file.

#include "browser/browser_main_parts.h"

#include "browser/browser_context.h"
#include "browser/web_ui_controller_factory.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/gfx/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"

namespace brightray {

BrowserMainParts::BrowserMainParts() {
}

BrowserMainParts::~BrowserMainParts() {
}

void BrowserMainParts::PreMainMessageLoopRun() {
  browser_context_.reset(CreateBrowserContext());
  browser_context_->Initialize();

  web_ui_controller_factory_.reset(
      new WebUIControllerFactory(browser_context_.get()));
  content::WebUIControllerFactory::RegisterFactory(
      web_ui_controller_factory_.get());

#if defined(OS_WIN)
  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen());
#endif
}

void BrowserMainParts::PostMainMessageLoopRun() {
  browser_context_.reset();
}

int BrowserMainParts::PreCreateThreads() {
#if defined(OS_WIN)
  net::ProxyResolverV8::CreateIsolate();
#else
  net::ProxyResolverV8::RememberDefaultIsolate();
#endif
  return 0;
}

BrowserContext* BrowserMainParts::CreateBrowserContext() {
  return new BrowserContext;
}

}  // namespace brightray

Set up a native screen on Windows


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

#include <boost/test/unit_test.hpp>
#include <tinyformat.h>
#include <utilmoneystr.h>
#include "masternode-budget.h"

BOOST_AUTO_TEST_SUITE(budget_tests)

void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue)
{
    CBudgetManager budget;
    CAmount nBudget = budget.GetTotalBudget(nHeight);
    std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue));
    BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError);
}

BOOST_AUTO_TEST_CASE(budget_value)
{
    SelectParams(CBaseChainParams::MAIN);
    int nHeightTest = Params().Zerocoin_Block_V2_Start() + 1;
    CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN);

    SelectParams(CBaseChainParams::TESTNET);
    nHeightTest = Params().Zerocoin_Block_V2_Start() + 1;
    CheckBudgetValue(nHeightTest, "testnet", 7300*COIN);
}

BOOST_AUTO_TEST_SUITE_END()

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

#include "masternode-budget.h"
#include "tinyformat.h"
#include "utilmoneystr.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(budget_tests)

void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue)
{
    CBudgetManager budget;
    CAmount nBudget = budget.GetTotalBudget(nHeight);
    std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue));
    BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError);
}

BOOST_AUTO_TEST_CASE(budget_value)
{
    SelectParams(CBaseChainParams::TESTNET);
    int nHeightTest = Params().Zerocoin_Block_V2_Start() + 1;
    CheckBudgetValue(nHeightTest, "testnet", 7300*COIN);

    SelectParams(CBaseChainParams::MAIN);
    nHeightTest = Params().Zerocoin_Block_V2_Start() + 1;
    CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN);
}

BOOST_AUTO_TEST_SUITE_END()

Fix chain ordering in budget tests


//
// Created by Chris Richards on 27/04/2016.
//

#include <iomanip>
#include <sstream>
#include "DbfColumn.h"
#include "DbfUtils.h"

const int kDbfFieldDescriptorSize = 32;

DbfColumn::DbfColumn(std::istream &stream, int index)
        : index_(index) {
    read(stream);
}

void DbfColumn::read(std::istream &stream) {
    name_.clear();
    name_.resize(10);

    stream.read(&name_[0], 11);

    std::vector<char>::iterator it = std::find(name_.begin(), name_.end(), '\0');
    if (it != name_.end()) {
        name_.erase(it, name_.end());
    }

    type_ = (DbfColumnType)read_raw<uint8_t>(stream);
    uint32_t address = read_raw<uint32_t>(stream);
    length_ = read_raw<uint8_t>(stream);
    decimal_ = read_raw<uint8_t>(stream);

    // skip the next 14 bytes
    stream.seekg(14, std::ios_base::cur);
}

int DbfColumn::index() const {
    return index_;
}

std::string DbfColumn::name() const {
    return name_;
}

DbfColumn::DbfColumnType DbfColumn::type() const {
    return type_;
}

int DbfColumn::length() const {
    return length_;
}

int DbfColumn::decimal() const {
    return decimal_;
}

//
// Created by Chris Richards on 27/04/2016.
//

#include <iomanip>
#include <sstream>
#include "DbfColumn.h"
#include "DbfUtils.h"

const int kDbfFieldDescriptorSize = 32;

DbfColumn::DbfColumn(std::istream &stream, int index)
        : index_(index) {
    read(stream);
}

void DbfColumn::read(std::istream &stream) {
    name_.clear();
    name_.resize(10);

    stream.read(&name_[0], 11);

    size_t pos = name_.find('\0');
    if (pos != std::string::npos) {
        name_.erase(pos);
    }

    type_ = (DbfColumnType)read_raw<uint8_t>(stream);
    uint32_t address = read_raw<uint32_t>(stream);
    length_ = read_raw<uint8_t>(stream);
    decimal_ = read_raw<uint8_t>(stream);

    // skip the next 14 bytes
    stream.seekg(14, std::ios_base::cur);
}

int DbfColumn::index() const {
    return index_;
}

std::string DbfColumn::name() const {
    return name_;
}

DbfColumn::DbfColumnType DbfColumn::type() const {
    return type_;
}

int DbfColumn::length() const {
    return length_;
}

int DbfColumn::decimal() const {
    return decimal_;
}

Fix to removing nulls from column names


#include "myapplication.h"
#include "eventdispatcher_libevent.h"
#include "msghandler.h"

int main(int argc, char** argv)
{
#if QT_VERSION < 0x050000
	qInstallMsgHandler(messageHandler);
#else
	qInstallMessageHandler(messageHandler);
#endif

#if QT_VERSION >= 0x050000
	QCoreApplication::setEventDispatcher(new EventDispatcherLibEvent());
#else
	EventDispatcherLibEvent e;
#endif

	QCoreApplication::setApplicationName(QLatin1String("Proxy"));
	QCoreApplication::setOrganizationName(QLatin1String("Goldbar Enterprises"));
	QCoreApplication::setOrganizationDomain(QLatin1String("goldbar.net"));
#if QT_VERSION >= 0x040400
	QCoreApplication::setApplicationVersion(QLatin1String("0.0.1"));
#endif

	MyApplication app(argc, argv);
	return app.exec();
}

#include "myapplication.h"
#include "eventdispatcher_libevent.h"
#include "msghandler.h"
#include "qt4compat.h"

int main(int argc, char** argv)
{
#if QT_VERSION < 0x050000
	qInstallMsgHandler(messageHandler);
#else
	qInstallMessageHandler(messageHandler);
#endif

#if QT_VERSION >= 0x050000
	QCoreApplication::setEventDispatcher(new EventDispatcherLibEvent());
#else
	EventDispatcherLibEvent e;
#endif

	QCoreApplication::setApplicationName(QLatin1String("Proxy"));
	QCoreApplication::setOrganizationName(QLatin1String("Goldbar Enterprises"));
	QCoreApplication::setOrganizationDomain(QLatin1String("goldbar.net"));
#if QT_VERSION >= 0x040400
#if defined(REPWATCHPROXY_VERSION)
#define RPV QT_STRINGIFY(REPWATCHPROXY_VERSION)
	QCoreApplication::setApplicationVersion(QLatin1String(RPV));
#undef RPV
#else
	QCoreApplication::setApplicationVersion(QLatin1String("0.0.1"));
#endif
#endif

	MyApplication app(argc, argv);
	return app.exec();
}

Use version number from qmake if possible


#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

int main(int argc, char *argv[])
{
    // For this example, wizard-generates single line code would be good enough,
    // but very soon it won't be enough for you anyway, so use this more detailed example from start
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    Factorizer fact;

#ifdef QT_QML_DEBUG
    runUnitTests();
#endif

//    Here's how you will add QML components whenever you start using them
//    Check https://github.com/amarchen/Wikipedia for a more full example
//    view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString());
    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->setTitle("Sailfactor");

    app->setApplicationName("harbour-sailfactor");
    app->setApplicationDisplayName("Sailfactor");

    view->show();

    return app->exec();
}

#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

void loadTranslations() {
    QString langCode = QLocale::system().name().mid(0, 2);
    const QString Prefix("sailfactor_");

    if (QFile::exists(QString(":/lang/") + Prefix + langCode + ".qm")) {
        QTranslator *translator = new QTranslator(QCoreApplication::instance());
        translator->load(Prefix + langCode, ":/lang");
        QCoreApplication::installTranslator(translator);
    }
}

int main(int argc, char *argv[])
{
    // For this example, wizard-generates single line code would be good enough,
    // but very soon it won't be enough for you anyway, so use this more detailed example from start
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    loadTranslations();

    Factorizer fact;

#ifdef QT_QML_DEBUG
    runUnitTests();
#endif

//    Here's how you will add QML components whenever you start using them
//    Check https://github.com/amarchen/Wikipedia for a more full example
//    view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString());
    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->setTitle("Sailfactor");

    app->setApplicationName("harbour-sailfactor");
    app->setApplicationDisplayName("Sailfactor");

    view->show();

    return app->exec();
}

Load the appropriate translation at startup, based on current locale.


// RUN: %clang_cc1 -fsyntax-only -verify -std=c++0x %s
struct S {
  virtual void final() final;
  virtual void override() override;
  virtual void n() new;
};

// RUN: %clang_cc1 -fsyntax-only -verify -std=c++0x %s
struct S {
  virtual void final() final;
  virtual void override() override;
  virtual void n() new;
  int i : 3 new;
  int j new;
};

struct T {
  // virt-specifier-seq is only valid in member-declarators, and a function definition is not a member-declarator.
  virtual void f() const override { } // expected-error {{expected ';' at end of declaration list}}
};

Add more parser tests for the override control keywords.


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

#include <util/validation.h>

#include <consensus/validation.h>
#include <tinyformat.h>

/** Convert ValidationState to a human-readable message for logging */
std::string FormatStateMessage(const ValidationState &state)
{
    return strprintf("%s%s",
        state.GetRejectReason(),
        state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage());
}

const std::string strMessageMagic = "Bitcoin Signed Message:\n";

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

#include <util/validation.h>

#include <consensus/validation.h>
#include <tinyformat.h>

/** Convert ValidationState to a human-readable message for logging */
std::string FormatStateMessage(const ValidationState &state)
{
    if (state.IsValid()) {
        return "Valid";
    }

    return strprintf("%s%s",
        state.GetRejectReason(),
        state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage());
}

const std::string strMessageMagic = "Bitcoin Signed Message:\n";

Format CValidationState properly in all cases


//#include "InstructionParser.h"

#include <string>
#include <stdexcept>

#include "gtest/gtest.h"

class InstructionParser
{
public:
  class UnknownInstruction : public std::runtime_error
  {
  public:
    UnknownInstruction(const std::string& msg) : std::runtime_error{msg}
    {}
  };

  void parseInstructions(const std::string& instruction)
  {
    const std::vector<std::string> acceptableInstructions{"ld a,", "out (0),a"};
    if (std::find(acceptableInstructions.begin(), acceptableInstructions.end(), instruction) == acceptableInstructions.end())
    {
      throw UnknownInstruction{"Unknown instruction" + instruction};
    }
  }

};

TEST(InstructionParser, ParserShouldDeclineUnknownInstruction)
{
  InstructionParser parser;
  EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction);
}

TEST(InstructionParser, ParserShouldAcceptInstuctionLd)
{
  InstructionParser parser;
  EXPECT_NO_THROW(parser.parseInstructions("ld a,"));
}

TEST(InstructionParser, ParserShouldAcceptInstructionOut)
{
  InstructionParser parser;
  EXPECT_NO_THROW(parser.parseInstructions("out (0),a"));
}

//#include "InstructionParser.h"

#include <string>
#include <stdexcept>

#include "gtest/gtest.h"

class InstructionParser
{
public:
  class UnknownInstruction : public std::runtime_error
  {
  public:
    UnknownInstruction(const std::string& msg) : std::runtime_error{msg}
    {}
  };

  void parseInstructions(const std::string& instruction)
  {
    const std::vector<std::string> acceptableInstructions{"ld a,", "out (0),a"};
    if (std::find(acceptableInstructions.begin(), acceptableInstructions.end(), instruction) == acceptableInstructions.end())
    {
      throw UnknownInstruction{"Unknown instruction" + instruction};
    }
  }

};

using namespace ::testing;

struct InstructionParserTest : public Test
{
  InstructionParser parser;
};

TEST(InstructionParserTest, ParserShouldDeclineUnknownInstruction)
{
  EXPECT_THROW(parser.parseInstructions("Instructions"), InstructionParser::UnknownInstruction);
}

TEST(InstructionParserTest, ParserShouldAcceptInstuctionLd)
{
  EXPECT_NO_THROW(parser.parseInstructions("ld a,"));
}

TEST(InstructionParserTest, ParserShouldAcceptInstructionOut)
{
  EXPECT_NO_THROW(parser.parseInstructions("out (0),a"));
}

Use container to store acceptable instructions


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

#include "application.h"

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

	Application a(argc, argv);
	MainWindow w;

	w.show();

	QStringList args = QApplication::arguments();

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

    return a.exec();
}

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

#include "application.h"

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

	QLocale::setDefault(QLocale(QLocale::English)); // make decimal points == .

	Application a(argc, argv);
	MainWindow w;

	w.show();

	QStringList args = QApplication::arguments();

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

    return a.exec();
}

Fix to decimal point rejection in float fields


#include "bundle.h"
#include "exec.h"

int main(int argc, char *argv[])
{
    bool enable_assert = true;
    unsigned short debug_port = 0;

    run_from_bundle(argv[0], enable_assert, debug_port, argc, argv);

    return 0;
}

#include "bundle.h"
#include "exec.h"

#ifdef _WIN32
#include <windows.h>
#endif

int main(int argc, char *argv[])
{
    bool enable_assert = true;
    unsigned short debug_port = 0;

    const char *exe = argv[0];
    #ifdef _WIN32
        char buf[MAX_PATH];
        GetModuleFileName(NULL, buf, sizeof(buf));
        exe = buf;
    #endif
    run_from_bundle(exe, enable_assert, debug_port, argc, argv);

    return 0;
}

Use GetModuleFileName on win32 to get exe name


#include <iostream>
#include <yaml-cpp/yaml.h>

int main()
{
   YAML::Emitter out;
   out << "Hello, World!";

   std::cout << "Here's the output YAML:\n" << out.c_str();

   return 0;
}

#include <cassert>
#include <yaml-cpp/yaml.h>

int main()
{
    YAML::Node node = YAML::Load("[1, 2, 3]");

    assert(node.IsSequence());

    return 0;
}

Change the test application to one that works.


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

#include <iostream>

#include "AssemblyFileWriter.hpp"
#include "Functions.hpp"
#include "Utils.hpp"

using namespace eddic;

using std::endl;

void MainDeclaration::write(AssemblyFileWriter& writer){
    writer.stream() << ".text" << endl
                    << ".globl main" << endl
                    << "\t.type main, @function" << endl;
}

void FunctionCall::checkFunctions(Program& program){
    if(!program.exists(m_function)){
        throw CompilerException("The function \"" + m_function + "()\" does not exists at line " + toString<int>(token()->line()) + ":" + toString<int>(token()->col()));
    }
}

void Function::write(AssemblyFileWriter& writer){
    writer.stream() << endl << m_name << ":" << endl;

    writer.stream() << "pushl %ebp" << std::endl;
    writer.stream() << "movl %esp, %ebp" << std::endl;

    ParseNode::write(writer);

    writer.stream() << "leave" << std::endl;
    writer.stream() << "ret" << std::endl;
}

void FunctionCall::write(AssemblyFileWriter& writer){
    writer.stream() << "call " << m_function << endl;
}

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

#include <iostream>

#include "AssemblyFileWriter.hpp"
#include "Functions.hpp"
#include "Utils.hpp"

using namespace eddic;

using std::endl;

void MainDeclaration::write(AssemblyFileWriter& writer){
    writer.stream() << ".text" << endl
                    << ".globl main" << endl
                    << "\t.type main, @function" << endl;
}

void FunctionCall::checkFunctions(Program& program){
    if(!program.exists(m_function)){
        throw CompilerException("The function \"" + m_function + "()\" does not exists", token());
    }
}

void Function::write(AssemblyFileWriter& writer){
    writer.stream() << endl << m_name << ":" << endl;

    writer.stream() << "pushl %ebp" << std::endl;
    writer.stream() << "movl %esp, %ebp" << std::endl;

    ParseNode::write(writer);

    writer.stream() << "leave" << std::endl;
    writer.stream() << "ret" << std::endl;
}

void FunctionCall::write(AssemblyFileWriter& writer){
    writer.stream() << "call " << m_function << endl;
}

Use the next exception for functions error reporting


#include <stdio.h>

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

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

    {
    }

    return 0;
}

#include <stdio.h>

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

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

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

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

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

    free_random_data(data);
    return 0;
}

Add body of solution of prob 3


#include "ext_mongo.h"

namespace HPHP {

// PHP Exceptions and Classes
HPHP::Class* MongoException::cls = nullptr;
HPHP::Class* MongoConnectionException::cls = nullptr;
HPHP::Class* MongoCursorTimeoutException::cls = nullptr;
HPHP::Class* MongoDuplicateKeyException::cls = nullptr;
HPHP::Class* MongoExecutionTimeoutException::cls = nullptr;
HPHP::Class* MongoGridFSException::cls = nullptr;
HPHP::Class* MongoProtocolException::cls = nullptr;
HPHP::Class* MongoResultException::cls = nullptr;
HPHP::Class* MongoWriteConcernException::cls = nullptr;

mongoExtension s_mongo_extension;
HHVM_GET_MODULE(mongo);

} // namespace HPHP

#include "ext_mongo.h"

namespace HPHP {

// PHP Exceptions and Classes
HPHP::Class* MongoException::cls = nullptr;
HPHP::Class* MongoConnectionException::cls = nullptr;
HPHP::Class* MongoCursorException::cls = nullptr;
HPHP::Class* MongoCursorTimeoutException::cls = nullptr;
HPHP::Class* MongoDuplicateKeyException::cls = nullptr;
HPHP::Class* MongoExecutionTimeoutException::cls = nullptr;
HPHP::Class* MongoGridFSException::cls = nullptr;
HPHP::Class* MongoProtocolException::cls = nullptr;
HPHP::Class* MongoResultException::cls = nullptr;
HPHP::Class* MongoWriteConcernException::cls = nullptr;

mongoExtension s_mongo_extension;
HHVM_GET_MODULE(mongo);

} // namespace HPHP

Define class pointer for MongoCursorException


#include <stdio.h>

int main(void)
{
    return 0;
}

#include <stdio.h>

#define MAX_LOOP    10000

double formula(const double x, const double k)
{
    return (x * x) / ((2 * k - 1) * (2 * k));
}

int main(void)
{
    double x;
    printf("Enter x= ");
    scanf("%lf", &x);

    double cosx = 1,
           sinx = x;

    int k = 2;
    while(k < MAX_LOOP)
    {
        cosx = cosx - cosx * formula(x, k++);
        sinx = sinx - sinx * formula(x, k++);
        cosx = cosx + cosx * formula(x, k++);
        sinx = sinx + sinx * formula(x, k++);
    }

    printf("Result is: cosx=%f sinx=%f\n", cosx, sinx);

    return 0;
}

Add a body of prob 6


#include <type/class.hh>

namespace type
{
    Class::Class(const std::string& name)
        : name_(name)
    {}

    Class::~Class()
    {}

    const std::string& Class::name_get() const
    {
        return name_;
    }

    ast::Ast* Class::component_get(const std::string& name)
    {
        return content_[name];
    }

    bool Class::component_add(const std::string& name, ast::Ast* dec)
    {
        // Component already exists
        if (!content_[name])
            return false;

        content_[name] = dec;

        return true;
    }

    std::ostream& Class::dump(std::ostream& o) const
    {
        o << "Class (" << name_ << ")";

        return o;
    }

    std::string Class::cpp_type() const
    {
        return name_ + "*";
    }
} // namespace type

#include <type/class.hh>

namespace type
{
    Class::Class(const std::string& name)
        : name_(name)
    {}

    Class::~Class()
    {}

    const std::string& Class::name_get() const
    {
        return name_;
    }

    ast::Ast* Class::component_get(const std::string& name)
    {
        return content_[name];
    }

    bool Class::component_add(const std::string& name, ast::Ast* dec)
    {
        // Component already exists
        if (content_[name])
            return false;

        content_[name] = dec;

        return true;
    }

    std::ostream& Class::dump(std::ostream& o) const
    {
        o << "Class (" << name_ << ")";

        return o;
    }

    std::string Class::cpp_type() const
    {
        return name_ + "*";
    }
} // namespace type

Fix bug with component_add() on Class type


#include "parserPrivate.h"

complexType getNumber(std::string string, bool negative, bool &a)
{
	complexType complex;
	char haveI = 0;

	size_t size = string.size();
	double value;

	if(string.at(0) == 'i')
	{
		haveI++;
		string.erase(0, 1);
		size--;
	}

	if(string.at(size-1) == 'i')
	{
		haveI++;
		string.erase(size-1, 1);
		size--;
	}

	if(string.at(0) == '[')
	{
		value = 0;
	}
	else
		value = atof(string.c_str());

	if(haveI == 1)
		complex.isComplex = true;
	else
	{
		complex.isComplex = false;
		if(haveI == 2)
			value *= -1;
	}

	if(negative)
		value *= -1;

	complex.coefficient = value;
	return complex;
}

#include "parserPrivate.h"

complexType getNumber(std::string string, bool negative, bool &a)
{
	complexType complex;
	size_t size = string.size();
	double value;
	char haveI = 0;
	bool isComplex;

	if(string.at(0) == 'i')
	{
		haveI++;
		string.erase(0, 1);
		size--;
	}

	if(string.at(size-1) == 'i')
	{
		haveI++;
		string.erase(size-1, 1);
		size--;
	}

	if(string.at(0) == '[')
	{
		value = 0;
	}
	else
		value = atof(string.c_str());

	if(negative)
		value *= -1;

	if(haveI == 1)
		isComplex = true;
	else
	{
		isComplex = false;
		if(haveI == 2)
			value *= -1;
	}

	if(isComplex)
		complex.coefComplex = value;
	else
		complex.coefReal = value;

	return complex;
}

bool isOperator

Use more powerfull complex type


#include <iostream>
#include <gtest/gtest.h>

TEST(sizeof, test1) {
    char str1[10];
    char str2[] = "Hello World!";

    EXPECT_EQ(10, sizeof(str1));
    EXPECT_EQ(13, sizeof(str2));
}

TEST(memcpy, test1) {
    int a[] = {1, 2, 3};
    int b[3];

    memcpy(b, a, sizeof(int) * 3);

    EXPECT_EQ(1, b[0]);
    EXPECT_EQ(2, b[1]);
    EXPECT_EQ(3, b[2]);
}

TEST(swap, test1) {
    int a = 1;
    int b = 2;

    std::swap(a, b);

    EXPECT_EQ(2, a);
    EXPECT_EQ(1, b);
}

TEST(array, test1) {
    int foo[2] = {1};

    EXPECT_EQ(1, foo[0]);
    EXPECT_EQ(0, foo[1]);
}

Add a test of array initialization


//
#include <stdio.h>

int main() {
  int n;
  scanf("%d", &n);

  int *A = new int[n];
  for (int i = 0; i < n; ++i) {
    scanf("%d", &A[i]);
  }

  int sum = 0;
  int i = 0;
L0:
  if (A[i] % 2 == 0) {
  left0:
    sum += A[i];
  } else {
  right0:
    sum -= A[i];
  }
  printf("%d", sum);
  if (A[i] % 2 == 0) {
    sum += A[i];
    if (++i < n) {
      goto left0;
    }
  } else {
    sum -= A[i];
    if (++i < n) {
      goto right0;
    }
  }

  printf("%d\n", sum);
  delete[] A;
}

// Let's call this CFG the 'butterfly'.
// It looks like this:
//
//     A
// ,. / \,-,
// | B1 B2 |
// |  \ /  |
// |   C   |
// |  / \  |
// | D1 D2 |
// `-`\ /`-`
//     E
//
// Where the edges between B1-D1 and B2-D2 are actually 'back-edges' which is to
// say the direction is from D1 to B1 and from D2 to B2 (illustrated by edges
// always leaving from the bottom of a node and entering through the top).
#include <stdio.h>

int main() {
  int n;
  scanf("%d", &n);

  int *A = new int[n];
  for (int i = 0; i < n; ++i) {
    scanf("%d", &A[i]);
  }

  int sum = 0;
  int i = 0;
A:
  if (A[i] % 2 == 0) {
  B1:
    sum += A[i];
  } else {
  B2:
    sum -= A[i];
  }
C:
  if (A[i] % 2 == 0) {
  D1:
    sum += A[i];
    if (++i < n) {
      goto B1;
    }
  } else {
  D2:
    sum -= A[i];
    if (++i < n) {
      goto B2;
    }
  }
E:

  printf("%d\n", sum);
  delete[] A;
}

Add descriptory comment to specimen4 example


#include <map>

int main()
{
  typedef std::map<int, int> ContainerType;
  typedef std::pair<bool, ContainerType::iterator> EmplaceReturnType;

  ContainerType m;

  // pair move constructor
  EmplaceReturnType aResult = m.emplace(std::make_pair(int(1), int(2)));
  bool aValid = (aResult.first) && ((*(aResult.second)).second == 2);

  // pair converting move constructor
  EmplaceReturnType bResult = m.emplace(std::make_pair(2, 4));
  bool bValid = (bResult.first) && ((*(bResult.second)).second == 4);

  // pair template constructor
  EmplaceReturnType cResult = m.emplace(3, 6);
  bool cValid = (cResult.first) && ((*(cResult.second)).second == 6);

  return (aValid && bValid && cValid) ? 0 : 1;
}

#include <map>

#include <iostream>
int main()
{
  typedef std::map<int, int> ContainerType;
  typedef std::pair<ContainerType::iterator, bool> EmplaceReturnType;

  ContainerType m;

  // pair move constructor
  EmplaceReturnType aResult = m.emplace(std::make_pair(int(1), int(2)));
  bool aValid = (aResult.second) && ((*(aResult.first)).second == 2);

  // pair converting move constructor
  EmplaceReturnType bResult = m.emplace(std::make_pair(2, 4));
  bool bValid = (bResult.second) && ((*(bResult.first)).second == 4);

  // pair template constructor
  EmplaceReturnType cResult = m.emplace(3, 6);
  bool cValid = (cResult.second) && ((*(cResult.first)).second == 6);

  return (aValid && bValid && cValid) ? 0 : 1;
}

Use correct pair type order in map::emplace 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 "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.0;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.15;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

Revert 163344 - [Sync] Disable unrecoverable error uploading.


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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.15;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.0;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

Set error upload rate to 0.


#ifndef _WIN32
#include <specs/specs.h>

go_bandit([]() {
  describe("colorizer: ", [&]() {
    describe("colors enabled", [&]() {
      bandit::detail::colorizer colorizer;

      it("can set color to green", [&]() {
        AssertThat(colorizer.green(), Equals("\033[1;32m"));
      });

      it("set color to red", [&]() {
        AssertThat(colorizer.red(), Equals("\033[1;31m"));
      });
      it("resets color", [&]() {
        AssertThat(colorizer.reset(), Equals("\033[0m"));
      });
    });

    describe("colors disabled", [&]() {
      bandit::detail::colorizer colorizer(false);

      it("ignores setting color to green", [&]() {
        AssertThat(colorizer.green(), Equals(""));
      });

      it("ignores setting color to red", [&]() {
        AssertThat(colorizer.red(), Equals(""));
      });

      it("ignores resetting colors", [&]() {
        AssertThat(colorizer.reset(), Equals(""));
      });
    });
  });
});
#endif

#include <specs/specs.h>

go_bandit([]() {
  describe("colorizer: ", [&]() {
#if !defined(_WIN32) || defined(BANDIT_CONFIG_COLOR_ANSI)
    describe("colors enabled", [&]() {
      bandit::detail::colorizer colorizer;

      it("can set color to green", [&]() {
        AssertThat(colorizer.green(), Equals("\033[1;32m"));
      });

      it("set color to red", [&]() {
        AssertThat(colorizer.red(), Equals("\033[1;31m"));
      });
      it("resets color", [&]() {
        AssertThat(colorizer.reset(), Equals("\033[0m"));
      });
    });
#endif

    describe("colors disabled", [&]() {
      bandit::detail::colorizer colorizer(false);

      it("ignores setting color to green", [&]() {
        AssertThat(colorizer.green(), Equals(""));
      });

      it("ignores setting color to red", [&]() {
        AssertThat(colorizer.red(), Equals(""));
      });

      it("ignores resetting colors", [&]() {
        AssertThat(colorizer.reset(), Equals(""));
      });
    });
  });
});

Test disabled colorizer on Windows


#include <common/buffer.h>

#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>

#include <io/pipe.h>

#include <xcodec/xcodec.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_encoder_pipe.h>

XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec)
: PipeSimple("/xcodec/encoder/pipe"),
  encoder_(codec)
{
	encoder_.set_pipe(this);
}

XCodecEncoderPipe::~XCodecEncoderPipe()
{
	encoder_.set_pipe(NULL);
}

void
XCodecEncoderPipe::output_ready(void)
{
	PipeSimple::output_spontaneous();
}

bool
XCodecEncoderPipe::process(Buffer *out, Buffer *in)
{
	encoder_.encode(out, in);
	return (true);
}

#include <common/buffer.h>

#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>

#include <io/pipe.h>

#include <xcodec/xcodec.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_encoder_pipe.h>

XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec)
: PipeSimple("/xcodec/encoder/pipe"),
  encoder_(codec)
{
	encoder_.set_pipe(this);
}

XCodecEncoderPipe::~XCodecEncoderPipe()
{
	encoder_.set_pipe(NULL);
}

void
XCodecEncoderPipe::output_ready(void)
{
}

bool
XCodecEncoderPipe::process(Buffer *out, Buffer *in)
{
	encoder_.encode(out, in);
	return (true);
}

Remove output_spontaneous use for now.


#include <chrono>
#include <iostream>
#include <thread>

#include "AHRS.h"
#include "WPILib.h"

/*
 * This program is used to measure the frequency of NavX errors.
 *
 * It prints a stream of millisecond timestamps corresponding to the last good
 * sensor read. Any errors noted by the NavX library are printed to standard
 * output and are interleaved with the timestamps.
 *
 * Excessive SPI errors have been noted while running this when
 * /etc/init.d/nilvrt is running so run `/etc/init.d/nilvrt stop` first.
 *
 * TIMESTAMP_PERIOD_MS = how often a timestamp is printed to standard output
 * LOOP_SLEEP_MS = run loop wait period
 */

static constexpr double TIMESTAMP_PERIOD_MS = 10 / 1000;
static constexpr auto LOOP_SLEEP_MS = std::chrono::milliseconds(1);

class Robot : public SampleRobot {
 public:
  void OperatorControl() {
    AHRS gyro{SPI::Port::kMXP};
    frc::Timer timer;
    timer.Start();
    while (IsEnabled()) {
      if (timer.HasPeriodPassed(TIMESTAMP_PERIOD_MS)) {
        std::cout << gyro.GetLastSensorTimestamp() << std::endl;
      }
      std::this_thread::sleep_for(LOOP_SLEEP_MS);
    }
  }

  void RobotInit() {}

  void Disabled() {
    while (IsDisabled()) {
      std::this_thread::sleep_for(LOOP_SLEEP_MS);
    }
  }
};

START_ROBOT_CLASS(Robot)

#include <chrono>
#include <iostream>
#include <thread>

#include "AHRS.h"
#include "WPILib.h"

/*
 * This program is used to measure the frequency of NavX errors.
 *
 * It prints a stream of millisecond timestamps corresponding to the last good
 * sensor read. Any errors noted by the NavX library are printed to standard
 * output and are interleaved with the timestamps.
 *
 * Excessive SPI errors have been noted while running this when
 * /etc/init.d/nilvrt is running so run `/etc/init.d/nilvrt stop` first.
 *
 * TIMESTAMP_PERIOD_MS = how often a timestamp is printed to standard output
 * LOOP_SLEEP_MS = run loop wait period
 */

static constexpr double TIMESTAMP_PERIOD_MS = 10 / 1000;
static constexpr auto LOOP_SLEEP_MS = std::chrono::milliseconds(1);

class Robot : public SampleRobot {
 public:
  AHRS gyro{SPI::Port::kMXP};

  void OperatorControl() {
    frc::Timer timer;
    timer.Start();
    while (IsEnabled()) {
      if (timer.HasPeriodPassed(TIMESTAMP_PERIOD_MS)) {
        std::cout << gyro.GetLastSensorTimestamp() << std::endl;
      }
      std::this_thread::sleep_for(LOOP_SLEEP_MS);
    }
  }

  void RobotInit() {}

  void Disabled() {
    while (IsDisabled()) {
      std::this_thread::sleep_for(LOOP_SLEEP_MS);
    }
  }
};

START_ROBOT_CLASS(Robot)

Move gyro to class scope.


#include "views.h"

using namespace std;

namespace rviews {

void login(JsonValue * message, ServerHandler * handler) {
    JsonDict * dictMessage = JDICT(message);

    if (dictMessage == NULL) {
        throw BadRequest("Malformatted request. Need a JSON dict");
    }

    bool success = getBool(dictMessage, "success");
    if(success){
        emit handler->getWindow()->loginSuccess();
    }
    else {
        emit handler->getWindow()->loginFailure(getInt(dictMessage, "code"));
    }
}

void signup(JsonValue * message, ServerHandler * handler) {
    JsonDict * dictMessage = JDICT(message);

    if (dictMessage == NULL) {
        throw BadRequest("Malformatted request. Need a JSON dict");
    }

    bool success = getBool(dictMessage, "success");
    if(success){
        emit handler->getWindow()->registerSuccess();
    }
    else {
        emit handler->getWindow()->registerFailure(getInt(dictMessage, "code"));
    }
}

void userlist(JsonValue * message, ServerHandler * handler) {
    JsonDict * listMessage = JLIST(message);

    if (listMessage == NULL) {
        throw BadRequest("Malformatted request. Need a JSON list");
    }

    JsonList * jlist = getList(dictMessage, "userlist");
    vector<string> ulist;
    for(int i = 0; i < jlist->size(); i++){
        ulist.push_back(getString(jlist, i));
    }
    emit handler->getWindow()->refreshRegisterList(ulist);
}

#include "views.h"

using namespace std;

namespace rviews {

void login(JsonValue * message, ServerHandler * handler) {
    JsonDict * dictMessage = JDICT(message);

    if (dictMessage == NULL) {
        throw BadRequest("Malformatted request. Need a JSON dict");
    }

    bool success = getBool(dictMessage, "success");
    if(success){
        emit handler->getWindow()->loginSuccess();
    }
    else {
        emit handler->getWindow()->loginFailure(getInt(dictMessage, "code"));
    }
}

void signup(JsonValue * message, ServerHandler * handler) {
    JsonDict * dictMessage = JDICT(message);

    if (dictMessage == NULL) {
        throw BadRequest("Malformatted request. Need a JSON dict");
    }

    bool success = getBool(dictMessage, "success");
    if(success){
        emit handler->getWindow()->registerSuccess();
    }
    else {
        emit handler->getWindow()->registerFailure(getInt(dictMessage, "code"));
    }
}

void userlist(JsonValue * message, ServerHandler * handler) {
    JsonDict * dictMessage = JDICT(message);

    if (dictMessage == NULL) {
        throw BadRequest("Malformatted request. Need a JSON list");
    }

    JsonList * jlist = getList(dictMessage, "userlist");
    vector<string> ulist;
    for(int i = 0; i < jlist->size(); i++){
        ulist.push_back(getString(jlist, i));
    }
    emit handler->getWindow()->userList(ulist);
}
}

Use new signals (again) + fix list/dict


// RUN: %clang_cc1 %s -triple i386-pc-windows-msvc19.0.0 -emit-obj \
// RUN:     -debug-info-kind=line-tables-only -fms-extensions
class __declspec(dllexport) A {
  A(int * = new int) {}
};
// CHECK: define {{.*}}void @"\01??_FA@@AAEXXZ"
// CHECK-SAME: !dbg ![[SP:[0-9]+]]
// CHECK-NOT: {{ret }}
// CHECK: call x86_thiscallcc %class.A* @"\01??0A@@AAE@PAH@Z"(%class.A* %this1, i32* %0)
// CHECK-SAME: !dbg ![[DBG:[0-9]+]]
// CHECK: ret void, !dbg ![[DBG]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(
// CHECK-SAME:          line: 3
// CHECK-SAME:          isDefinition: true
// CHECK-SAME:          DIFlagArtificial
// CHECK-SAME:          ){{$}}
//
// CHECK: ![[DBG]] = !DILocation(line: 0

// RUN: %clang_cc1 %s -triple i386-pc-windows-msvc19.0.0 -emit-llvm \
// RUN:     -debug-info-kind=line-tables-only -fms-extensions -o - | FileCheck %s
class __declspec(dllexport) A {
  A(int * = new int) {}
};
// CHECK: define {{.*}}void @"\01??_FA@@AAEXXZ"
// CHECK-SAME: !dbg ![[SP:[0-9]+]]
// CHECK-NOT: {{ret }}
// CHECK: call x86_thiscallcc %class.A* @"\01??0A@@AAE@PAH@Z"(%class.A* %this1, i32* %0)
// CHECK-SAME: !dbg ![[DBG:[0-9]+]]
// CHECK: ret void, !dbg ![[DBG1:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(
// CHECK-SAME:          line: 4
// CHECK-SAME:          isDefinition: true
// CHECK-SAME:          DIFlagArtificial
// CHECK-SAME:          ){{$}}
//
// CHECK: ![[DBG1]] = !DILocation(line: 0
// CHECK: ![[DBG]] = !DILocation(line: 0

Add the missing FileCheck invocation to this testcase.


// RUN: rm -rf %t
// RUN: %clang -Wunused-local-typedef -c -x objective-c++ -fcxx-modules -fmodules -fmodules-cache-path=%t -I %S/Inputs %s 2>&1 | FileCheck %s -check-prefix=CHECK_1
// RUN: %clang -Wunused-local-typedef -c -x objective-c++ -fcxx-modules -fmodules -fmodules-cache-path=%t -I %S/Inputs %s 2>&1 | FileCheck %s -check-prefix=CHECK_2 -allow-empty

// For modules, the warning should only fire the first time, when the module is
// built.
// CHECK_1: warning: unused typedef
// CHECK_2-NOT: warning: unused typedef
@import warn_unused_local_typedef;

// RUN: rm -rf %t
// RUN: %clang -Wunused-local-typedef -c -x objective-c++ -fcxx-modules -fmodules -fmodules-cache-path=%t -I %S/Inputs %s -o /dev/null 2>&1 | FileCheck %s -check-prefix=CHECK_1
// RUN: %clang -Wunused-local-typedef -c -x objective-c++ -fcxx-modules -fmodules -fmodules-cache-path=%t -I %S/Inputs %s -o /dev/null 2>&1 | FileCheck %s -check-prefix=CHECK_2 -allow-empty

// For modules, the warning should only fire the first time, when the module is
// built.
// CHECK_1: warning: unused typedef
// CHECK_2-NOT: warning: unused typedef
@import warn_unused_local_typedef;

Fix test to not write output to the test directory, as it may not be writable.


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

#include <cstddef>

#ifndef offsetof
#error offsetof not defined
#endif

int main()
{
}

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

#include <cstddef>

#ifndef offsetof
#error offsetof not defined
#endif

struct A
{
    int x;
};

int main()
{
#if (__has_feature(cxx_noexcept))
    static_assert(noexcept(offsetof(A, x)), "");
#endif
}

Add noexcept test for offsetof macro per [support.types]/p4.


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

#include "config.h"
#include "webkit/extensions/v8/playback_extension.h"

namespace extensions_v8 {

const char* kPlaybackExtensionName = "v8/PlaybackMode";

v8::Extension* PlaybackExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kPlaybackExtensionName,
      "(function () {"
      "  var orig_date = Date;"
      "  Math.random = function() {"
      "    return 0.5;"
      "  };"
      "  Date.__proto__.now = function() {"
      "    return new orig_date(1204251968254);"
      "  };"
      "  Date = function() {"
      "    return Date.now();"
      "  };"
      "})()");
    return extension;
}

}  // namespace extensions_v8

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

#include "config.h"
#include "webkit/extensions/v8/playback_extension.h"

namespace extensions_v8 {

const char* kPlaybackExtensionName = "v8/PlaybackMode";

v8::Extension* PlaybackExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kPlaybackExtensionName,
      "(function () {"
      "  var orig_date = Date;"
      "  var x = 0;"
      "  var time_seed = 1204251968254;"
      "  Math.random = function() {"
      "    x += .1;"
      "    return (x % 1);"
      "  };"
      "  Date.__proto__.now = function() {"
      "    time_seed += 50;"
      "    return new orig_date(time_seed);"
      "  };"
      "  Date = function() {"
      "    return Date.now();"
      "  };"
      "})()");
    return extension;
}

}  // namespace extensions_v8

Update playback extension so that javascript functions return consistent (but not constant) values in an attempt to preserve the functionality but improve compatibility of the extension.


#include "ics3/parameter.hpp"

ics::Parameter ics::Parameter::stretch() noexcept {
  static const Parameter STRETCH(0x01, 1, 127);
  return STRETCH;
}

ics::Parameter ics::Parameter::speed() noexcept {
  static const Parameter SPEED(0x02, 1, 127);
  return SPEED;
}

ics::Parameter ics::Parameter::current() noexcept {
  static const Parameter CURRENT(0x03, 0, 63);
  return CURRENT;
}

ics::Parameter ics::Parameter::temperature() noexcept {
  static const Parameter TEMPERATURE(0x04, 1, 127);
  return TEMPERATURE;
}

unsigned char ics::Parameter::get() const noexcept {
  return data;
}

void ics::Parameter::set(unsigned char input) throw(std::invalid_argument) {
  if (input < min) throw std::invalid_argument("Too small value");
  if (max < input) throw std::invalid_argument("Too big value");
  data = input;
}

ics::parameter::Parameter(unsigned char sc, unsigned char min, unsigned char max)
: sc(sc),
  min(min),
  max(max)
{}

#include "ics3/parameter.hpp"

ics::Parameter ics::Parameter::stretch() noexcept {
  static const Parameter STRETCH(0x01, 1, 127);
  return STRETCH;
}

ics::Parameter ics::Parameter::speed() noexcept {
  static const Parameter SPEED(0x02, 1, 127);
  return SPEED;
}

ics::Parameter ics::Parameter::current() noexcept {
  static const Parameter CURRENT(0x03, 0, 63);
  return CURRENT;
}

ics::Parameter ics::Parameter::temperature() noexcept {
  static const Parameter TEMPERATURE(0x04, 1, 127);
  return TEMPERATURE;
}

unsigned char ics::Parameter::get() const noexcept {
  return data;
}

void ics::Parameter::set(unsigned char input) throw(std::invalid_argument) {
  if (input < min) throw std::invalid_argument("Too small value");
  if (max < input) throw std::invalid_argument("Too big value");
  data = input;
}

ics::Parameter::Parameter(unsigned char sc, unsigned char min, unsigned char max) noexcept
: sc(sc),
  min(min),
  max(max)
{}

Fix constructor with noexcept of Parameter class


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

#define MEM_SIZE (1<<20)
#define CACHE_SIZE (1<<8)
#define DATA_SIZE (1<<8)

using namespace std;

int main() {
	// Variables used
	int dir, cmd, op;
	unsigned char dat, wait;

	// Plant the seed
	srand(time(0));

	// Infinit Loop
	while(true){
		// Each command is 32 bits,
		// 19...0 bits for dir,
		// 27...20 bits for data
		// 28 bit indicates operation type 1:read 0:write
		cmd = rand();
		dir = cmd & 0xFFFFF;
		dat = (cmd & 0xF00000)>>20;
		op = (cmd>>28)&1;
		printf("op=%c on dir(0x%x) data:%d\n","wr"[op],dir,dat);
		wait = getchar();
	}
	return 0;
}

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <bitset>
#include <deque>

#define MEM_SIZE (1<<20)
#define CACHE_SIZE (1<<8)

using namespace std;

enum{
	read,
	write
};

int main() {
	// Variables used
	int dir, cmd, op;
	unsigned char dat, wait;

	// Memory simulated
	unsigned char rawMemory[MEM_SIZE];
	int cacheDirection[CACHE_SIZE];
	unsigned char cacheData[CACHE_SIZE];

	// To simulate the circular queue
	int front = 0, tail = 0;

	// Initialize the cached Directions
	memset(cacheDirection, -1, sizeof cacheDirection);

	// Plant the seed
	srand(time(0));

	// Infinit Loop
	while(true){
		// Each command is 32 bits,
		cmd = rand();
		// 19...0 bits for dir
		dir = ((cmd)&(0xFFFFF));
		// 27...20 bits for data
		dat = (((cmd)&(0xF00000))>>20);
		// 28 bit indicates operation type 0:read 1:write
		op  = ((cmd>>28)&(1));

		//Perform operation according
		if(op == read) {

		} else { // write

		}

		wait = getchar();
	}
	return 0;
}

Add memory declaration, and refactor comments


// RUN: cat %s > %t.cpp
// RUN: clang-rename -offset=170 -new-name=hector %t.cpp -i --
// RUN: sed 's,//.*,,' %t.cpp | FileCheck %s
// REQUIRES: shell
namespace A {
int foo;  // CHECK: int hector;
}
int foo;  // CHECK: int foo;
int bar = foo; // CHECK: bar = foo;
int baz = A::foo; // CHECK: baz = A::hector;
void fun1() {
  struct {
    int foo; // CHECK: int foo;
  } b = { 100 };
  int foo = 100; // CHECK: int foo
  baz = foo; // CHECK: baz = foo;
  {
    extern int foo; // CHECK: int foo;
    baz = foo; // CHECK: baz = foo;
    foo = A::foo + baz; // CHECK: foo = A::hector + baz;
    A::foo = b.foo; // CHECK: A::hector = b.foo;
  }
  foo = b.foo; // CHECK: foo = b.foo;
}
// Use grep -FUbo 'foo;' <file> to get the correct offset of foo when changing
// this file.

namespace A { int foo;  // CHECK: int hector;
}
// RUN: cat %s > %t.cpp
// RUN: clang-rename -offset=18 -new-name=hector %t.cpp -i --
// RUN: sed 's,//.*,,' %t.cpp | FileCheck %s
int foo;  // CHECK: int foo;
int bar = foo; // CHECK: bar = foo;
int baz = A::foo; // CHECK: baz = A::hector;
void fun1() {
  struct {
    int foo; // CHECK: int foo;
  } b = { 100 };
  int foo = 100; // CHECK: int foo
  baz = foo; // CHECK: baz = foo;
  {
    extern int foo; // CHECK: int foo;
    baz = foo; // CHECK: baz = foo;
    foo = A::foo + baz; // CHECK: foo = A::hector + baz;
    A::foo = b.foo; // CHECK: A::hector = b.foo;
  }
  foo = b.foo; // CHECK: foo = b.foo;
}
// Use grep -FUbo 'foo;' <file> to get the correct offset of foo when changing
// this file.

Make test EOL tolerant by moving the symbol ot the first line before any EOL changes the byte offset count and enable it on Windows.


//===-- SparcMCAsmInfo.cpp - Sparc asm properties -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the SparcMCAsmInfo properties.
//
//===----------------------------------------------------------------------===//

#include "SparcMCAsmInfo.h"
#include "llvm/ADT/Triple.h"

using namespace llvm;

void SparcELFMCAsmInfo::anchor() { }

SparcELFMCAsmInfo::SparcELFMCAsmInfo(StringRef TT) {
  IsLittleEndian = false;
  Triple TheTriple(TT);
  if (TheTriple.getArch() == Triple::sparcv9) {
    PointerSize = CalleeSaveStackSlotSize = 8;
  }

  Data16bitsDirective = "\t.half\t";
  Data32bitsDirective = "\t.word\t";
  Data64bitsDirective = 0;  // .xword is only supported by V9.
  ZeroDirective = "\t.skip\t";
  CommentString = "!";
  HasLEB128 = true;
  SupportsDebugInformation = true;

  SunStyleELFSectionSwitchSyntax = true;
  UsesELFSectionDirectiveForBSS = true;

  WeakRefDirective = "\t.weak\t";

  PrivateGlobalPrefix = ".L";
}

//===-- SparcMCAsmInfo.cpp - Sparc asm properties -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the SparcMCAsmInfo properties.
//
//===----------------------------------------------------------------------===//

#include "SparcMCAsmInfo.h"
#include "llvm/ADT/Triple.h"

using namespace llvm;

void SparcELFMCAsmInfo::anchor() { }

SparcELFMCAsmInfo::SparcELFMCAsmInfo(StringRef TT) {
  IsLittleEndian = false;
  Triple TheTriple(TT);
  bool isV9 = (TheTriple.getArch() == Triple::sparcv9);

  if (isV9) {
    PointerSize = CalleeSaveStackSlotSize = 8;
  }

  Data16bitsDirective = "\t.half\t";
  Data32bitsDirective = "\t.word\t";
  // .xword is only supported by V9.
  Data64bitsDirective = (isV9) ? "\t.xword\t" : 0;
  ZeroDirective = "\t.skip\t";
  CommentString = "!";
  HasLEB128 = true;
  SupportsDebugInformation = true;

  SunStyleELFSectionSwitchSyntax = true;
  UsesELFSectionDirectiveForBSS = true;

  WeakRefDirective = "\t.weak\t";

  PrivateGlobalPrefix = ".L";
}

Enable xword directive in sparcv9.


#include <gtest/gtest.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "Integrator.h"
#include "StateVector.h"

TEST(StateTest, Instantiation) {
    using MyStateVector = UKF::StateVector<
        IntegratorRK4,
        UKF::Field<1, Eigen::Vector2f>,
        UKF::Field<2, Eigen::Vector3f>,
        UKF::Field<3, Eigen::Quaternionf>,
        UKF::Field<4, float>
    >;

    MyStateVector test_state;

    EXPECT_EQ(10, MyStateVector::MaxRowsAtCompileTime);
    EXPECT_EQ(10, test_state.size());
}

#include <gtest/gtest.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "Integrator.h"
#include "StateVector.h"

TEST(StateTest, Instantiation) {
	enum MyFields {
		LatLon,
		Altitude,
		Velocity,
		Attitude
	};

    using MyStateVector = UKF::StateVector<
        IntegratorRK4,
        UKF::Field<LatLon, Eigen::Vector2f>,
        UKF::Field<Altitude, Eigen::Vector3f>,
        UKF::Field<Velocity, Eigen::Quaternionf>,
        UKF::Field<Attitude, float>
    >;

    MyStateVector test_state;

    EXPECT_EQ(10, MyStateVector::MaxRowsAtCompileTime);
    EXPECT_EQ(10, test_state.size());
}

Use enums for keys in test


#include "DSTemperature.h"

DSTemperature::DSTemperature(byte pin) {
  _wire = new OneWire(pin);
  _addresses = (DSAddress*)malloc(sizeof(DSAddress));
}

void DSTemperature::begin(void) {

  DSAddress addr;

  while (_wire->search(addr.value)) {
    if (OneWire::crc8(addr.value, 7) == addr.value[7]) {
      resizeAddresses();
      _addresses[_nSensors++] = addr;
    }
  }

  _wire->reset_search();
  delay(250);
  return;

}

void DSTemperature::resizeAddresses() {

  if (_nSensors == 0)
    return;

  DSAddress* new_addresses = (DSAddress*)malloc(sizeof(DSAddress) * _nSensors);
  for (byte i = 0 ; i < _nSensors ; i++)
    new_addresses[i] = _addresses[i];
  free(_addresses);
  _addresses = new_addresses;

}

float DSTemperature::getCelsius(byte ds) {
  return CELSIUS(getRawTemperature(ds));
}

float DSTemperature::getFahrenheit(byte ds) {
  return FAHRENHEIT(getRawTemperature(ds));
}

#include "DSTemperature.h"

DSTemperature::DSTemperature(byte pin) {
  _wire = new OneWire(pin);
  _addresses = (DSAddress*)malloc(sizeof(DSAddress));
}

void DSTemperature::begin(void) {

  DSAddress addr;

  while (_wire->search(addr.value)) {
    if (OneWire::crc8(addr.value, 7) == addr.value[7]) {
      if (_nSensors != 0)
        resizeAddresses();
      _addresses[_nSensors++] = addr;
    }
  }

  _wire->reset_search();
  delay(250);
  return;

}

void DSTemperature::resizeAddresses() {

  DSAddress* new_addresses = (DSAddress*)malloc(sizeof(DSAddress) * _nSensors);
  for (byte i = 0 ; i < _nSensors ; i++)
    new_addresses[i] = _addresses[i];
  free(_addresses);
  _addresses = new_addresses;

}

float DSTemperature::getCelsius(byte ds) {
  return CELSIUS(getRawTemperature(ds));
}

float DSTemperature::getFahrenheit(byte ds) {
  return FAHRENHEIT(getRawTemperature(ds));
}

Call resizeAddresses only if you manage more than one sensor


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

#include "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", GR_GL_GET_ERROR(gl));
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

///////////////////////////////////////////////////////////////////////////////

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

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

#include "GrGLConfig.h"
#include "GrGLInterface.h"

void GrGLClearErr(const GrGLInterface* gl) {
    while (GR_GL_NO_ERROR != gl->fGetError()) {}
}

void GrGLCheckErr(const GrGLInterface* gl,
                  const char* location,
                  const char* call) {
    uint32_t err = GR_GL_GET_ERROR(gl);
    if (GR_GL_NO_ERROR != err) {
        GrPrintf("---- glGetError %x", err);
        if (NULL != location) {
            GrPrintf(" at\n\t%s", location);
        }
        if (NULL != call) {
            GrPrintf("\n\t\t%s", call);
        }
        GrPrintf("\n");
    }
}

void GrGLResetRowLength(const GrGLInterface* gl) {
    if (gl->supportsDesktop()) {
        GR_GL_CALL(gl, PixelStorei(GR_GL_UNPACK_ROW_LENGTH, 0));
    }
}

///////////////////////////////////////////////////////////////////////////////

#if GR_GL_LOG_CALLS
    bool gLogCallsGL = !!(GR_GL_LOG_CALLS_START);
#endif

#if GR_GL_CHECK_ERROR
    bool gCheckErrorGL = !!(GR_GL_CHECK_ERROR_START);
#endif

Fix gl error debug print.


#include <iostream>
#include <vector>

#include <adios2.h>
#ifdef ADIOS2_HAVE_MPI
#include <mpi.h>
#endif

int main(int argc, char *argv[])
{
    int rank = 0;
    int size = 1;
#ifdef ADIOS2_HAVE_MPI
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
#endif
    adios2::ADIOS ad;
    try
    {
#ifdef ADIOS2_HAVE_MPI
        ad = adios2::ADIOS("does_not_exist.xml", MPI_COMM_WORLD,
                           adios2::DebugON);
#else
        ad = adios2::ADIOS("does_not_exist.xml", adios2::DebugON);
#endif
    }
    catch (std::exception &e)
    {
        if (rank == 0)
        {
            std::cout << e.what() << "\n";
        }
#ifdef ADIOS2_HAVE_MPI
        ad = adios2::ADIOS(MPI_COMM_WORLD, adios2::DebugON);
#else
        ad = adios2::ADIOS(adios2::DebugON);
#endif
    }

#ifdef ADIOS2_HAVE_MPI
    return MPI_Finalize();
#endif
}

#include <iostream>
#include <vector>

#include <adios2.h>
#ifdef ADIOS2_HAVE_MPI
#include <mpi.h>
#endif

int main(int argc, char *argv[])
{
    int rank = 0;
#ifdef ADIOS2_HAVE_MPI
    int size = 1;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
#endif
    adios2::ADIOS ad;
    try
    {
#ifdef ADIOS2_HAVE_MPI
        ad = adios2::ADIOS("does_not_exist.xml", MPI_COMM_WORLD,
                           adios2::DebugON);
#else
        ad = adios2::ADIOS("does_not_exist.xml", adios2::DebugON);
#endif
    }
    catch (std::exception &e)
    {
        if (rank == 0)
        {
            std::cout << e.what() << "\n";
        }
#ifdef ADIOS2_HAVE_MPI
        ad = adios2::ADIOS(MPI_COMM_WORLD, adios2::DebugON);
#else
        ad = adios2::ADIOS(adios2::DebugON);
#endif
    }

#ifdef ADIOS2_HAVE_MPI
    return MPI_Finalize();
#endif
}

Remove unused variable warning when MPI is disabled.


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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  const double kErrorUploadRatio = 0.15;

  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/dump_without_crashing.h"

namespace browser_sync {

void ChromeReportUnrecoverableError() {
  // Only upload on canary/dev builds to avoid overwhelming crash server.
  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  if (channel != chrome::VersionInfo::CHANNEL_CANARY &&
      channel != chrome::VersionInfo::CHANNEL_DEV) {
    return;
  }

  // We only want to upload |kErrorUploadRatio| ratio of errors.
  const double kErrorUploadRatio = 0.15;
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  logging::DumpWithoutCrashing();
}

}  // namespace browser_sync

Support unrecoverable error uploading on non-win platforms


// 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 "base/native_library.h"

#include <dlfcn.h>

#include "base/file_path.h"
#include "base/logging.h"

namespace base {

// static
NativeLibrary LoadNativeLibrary(const FilePath& library_path) {
  void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY);
  if (!dl)
    NOTREACHED() << "dlopen failed: " << dlerror();

  return dl;
}

// static
void UnloadNativeLibrary(NativeLibrary library) {
  int ret = dlclose(library);
  if (ret < 0)
    NOTREACHED() << "dlclose failed: " << dlerror();
}

// static
void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
                                          NativeLibraryFunctionNameType name) {
  return dlsym(library, name);
}

}  // namespace base

// 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 "base/native_library.h"

#include <dlfcn.h>

#include "base/file_path.h"
#include "base/logging.h"

namespace base {

// static
NativeLibrary LoadNativeLibrary(const FilePath& library_path) {
  void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY|RTLD_DEEPBIND);
  if (!dl)
    NOTREACHED() << "dlopen failed: " << dlerror();

  return dl;
}

// static
void UnloadNativeLibrary(NativeLibrary library) {
  int ret = dlclose(library);
  if (ret < 0)
    NOTREACHED() << "dlclose failed: " << dlerror();
}

// static
void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
                                          NativeLibraryFunctionNameType name) {
  return dlsym(library, name);
}

}  // namespace base

Use RTLD_DEEPBIND to make sure plugins don't use Chrome's symbols instead of their own