#include "MessageBase.hpp"
#include "MessageBaseImpl.hpp"

namespace Grappa {

  /// Internal messaging functions
  namespace impl {

    /// @addtogroup Communication
    /// @{

    void Grappa::impl::MessageBase::legacy_send_message_am( char * buf, size_t size, void * payload, size_t payload_size ) {
      Grappa::impl::MessageBase::deserialize_and_call( static_cast< char * >( buf ) );
    }

    /// Block until message can be deallocated.
    void Grappa::impl::MessageBase::block_until_sent() {
      // if message has not been enqueued to be sent, do so.
      // if it has already been sent somehow, then don't worry about it.
      if( !is_sent_ && !is_enqueued_ ) {
        DVLOG(5) << this << " not sent, so enqueuing";
        enqueue();
      }
      // now block until message is sent
      while( !is_sent_ ) {
        DVLOG(5) << this << " blocking until sent";
        Grappa::wait( &cv_ );
        DVLOG(5) << this << " woken";
      }
    }

    /// @}

  }
}

#include "MessageBase.hpp"
#include "MessageBaseImpl.hpp"

namespace Grappa {

  /// Internal messaging functions
  namespace impl {

    /// @addtogroup Communication
    /// @{

    void Grappa::impl::MessageBase::legacy_send_message_am( char * buf, size_t size, void * payload, size_t payload_size ) {
      Grappa::impl::MessageBase::deserialize_and_call( static_cast< char * >( buf ) );
    }

    /// Block until message can be deallocated.
    void Grappa::impl::MessageBase::block_until_sent() {
      // if enqueued, block until message is sent
      while( is_enqueued_ && !is_sent_ ) {
        DVLOG(5) << this << " blocking until sent";
        Grappa::wait( &cv_ );
        DVLOG(5) << this << " woken";
      }
    }

    /// @}

  }
}

Disable auto-enqueue functionality in message destructor.


#include "SymbolicEngine.h"

SymbolicElement::SymbolicElement(std::stringstream &dst, std::stringstream &src, uint64_t id)
{
  //this->isTainted   = !TAINTED;
  this->source      = new std::stringstream(src.str());
  this->destination = new std::stringstream(dst.str());
  this->expression  = new std::stringstream();

  *this->expression << (*this->destination).str() << " = " << (*this->source).str();

  this->id = id;
}

SymbolicElement::~SymbolicElement()
{
  delete this->source;
  delete this->destination;
  delete this->expression;
}

/* Returns the SMT dst and src expression of the symbolic element */
std::stringstream *SymbolicElement::getExpression()
{
  return this->expression;
}

/* Returns the SMT src expression of the symbolic element */
std::stringstream *SymbolicElement::getSource()
{
  return this->source;
}

/* Returns the ID of the symbolic element */
uint64_t SymbolicElement::getID()
{
  return this->id;
}

#include "SymbolicEngine.h"

SymbolicElement::SymbolicElement(std::stringstream &dst, std::stringstream &src, uint64_t id)
{
  this->isTainted   = false;
  this->source      = new std::stringstream(src.str());
  this->destination = new std::stringstream(dst.str());
  this->expression  = new std::stringstream();

  *this->expression << (*this->destination).str() << " = " << (*this->source).str();

  this->id = id;
}

SymbolicElement::~SymbolicElement()
{
  delete this->source;
  delete this->destination;
  delete this->expression;
}

/* Returns the SMT dst and src expression of the symbolic element */
std::stringstream *SymbolicElement::getExpression()
{
  return this->expression;
}

/* Returns the SMT src expression of the symbolic element */
std::stringstream *SymbolicElement::getSource()
{
  return this->source;
}

/* Returns the ID of the symbolic element */
uint64_t SymbolicElement::getID()
{
  return this->id;
}

Fix taint attribute in sym element


/****************************************************************************
 * Copyright (c) 2012-2019 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/

#include <DTK_Search_Exception.hpp>

#include <boost/test/unit_test.hpp>

#define BOOST_TEST_MODULE DesignByContract

BOOST_AUTO_TEST_CASE( dumb )
{
    using namespace DataTransferKit;
    BOOST_CHECK_THROW( DTK_SEARCH_ASSERT( false ), SearchException );
    std::string const prefix = "DTK Search exception: ";
    std::string const message = "Keep calm and chive on!";
    BOOST_CHECK_EXCEPTION( throw SearchException( message ), SearchException,
                           [&]( SearchException const &e ) {
                               return prefix + message == e.what();
                           } );
}

/****************************************************************************
 * Copyright (c) 2012-2019 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/

#include <DTK_Search_Exception.hpp>

#include <boost/test/unit_test.hpp>

#define BOOST_TEST_MODULE DesignByContract

BOOST_AUTO_TEST_CASE( dumb )
{
    using namespace DataTransferKit;
    BOOST_CHECK_NO_THROW( DTK_SEARCH_ASSERT( true ) );
    BOOST_CHECK_THROW( DTK_SEARCH_ASSERT( false ), SearchException );
    std::string const prefix = "DTK Search exception: ";
    std::string const message = "Keep calm and chive on!";
    BOOST_CHECK_EXCEPTION( throw SearchException( message ), SearchException,
                           [&]( SearchException const &e ) {
                               return prefix + message == e.what();
                           } );
}

Check that the assertion macro does not throw when the condition is satisfied


#include "WorkerThread.h"
#include "Logger.h"
#include <sstream>

namespace comm {

WorkerThread::WorkerThread()
    : tasks(folly::MPMCQueue<std::unique_ptr<taskType>>(20)) {
  auto job = [this]() {
    while (true) {
      std::unique_ptr<taskType> lastTask;
      this->tasks.blockingRead(lastTask);
      if (lastTask == nullptr) {
        break;
      }
      (*lastTask)();
    }
  };
  this->thread = std::make_unique<std::thread>(job);
}

void WorkerThread::scheduleTask(const taskType task) {
  if (!this->tasks.write(std::make_unique<taskType>(std::move(task)))) {
    throw std::runtime_error("Error scheduling task on Database thread");
  }
}

WorkerThread::~WorkerThread() {
  this->tasks.blockingWrite(nullptr);
  try {
    this->thread->join();
  } catch (const std::system_error &error) {
    std::ostringstream stringStream;
    stringStream << "Error occurred joining the Database thread: "
                 << error.what();
    Logger::log(stringStream.str());
  }
}

} // namespace comm

#include "WorkerThread.h"
#include "Logger.h"
#include <sstream>

namespace comm {

WorkerThread::WorkerThread()
    : tasks(folly::MPMCQueue<std::unique_ptr<taskType>>(20)) {
  auto job = [this]() {
    while (true) {
      std::unique_ptr<taskType> lastTask;
      this->tasks.blockingRead(lastTask);
      if (lastTask == nullptr) {
        break;
      }
      (*lastTask)();
    }
  };
  this->thread = std::make_unique<std::thread>(job);
}

void WorkerThread::scheduleTask(const taskType task) {
  if (!this->tasks.write(std::make_unique<taskType>(std::move(task)))) {
    throw std::runtime_error("Error scheduling task on a worker thread");
  }
}

WorkerThread::~WorkerThread() {
  this->tasks.blockingWrite(nullptr);
  try {
    this->thread->join();
  } catch (const std::system_error &error) {
    std::ostringstream stringStream;
    stringStream << "Error occurred joining a worker thread: " << error.what();
    Logger::log(stringStream.str());
  }
}

} // namespace comm

Refactor error messages for worker threads


#include <string>
#include "runDiff.h"

int main(int argc, const char * argv[])
{
	if (argc != 2 )
	{
		std::cerr<<"Usage: "<<argv[0]<<" input file name"<<std::endl;
		return 1;
	}
	runFiles(string(argv[1]));
	return 0;
}

#include <string>
#include "runDiff.h"

int main(int argc, const char * argv[])
{
	if (argc != 2 )
	{
		std::cerr<<"Usage: "<<argv[0]<<" input file name"<<std::endl;
		return 1;
	}
	runFiles(std::string(argv[1]));
	return 0;
}

Use std::string instead of string (error fix, compiles now)


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

#include "parser_nn.h"

namespace ufal {
namespace parsito {

void parser_nn::parse(tree& t, configuration& c) const {
}

void parser_nn::load(binary_decoder& data) {
  // Load labels
  labels.resize(data.next_2B());
  for (auto&& label : labels)
    data.next_str(label);

  // Load transition system
  string system_name;
  data.next_str(system_name);
  system.reset(transition_system::create(system_name, labels));
}

} // namespace parsito
} // namespace ufal

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

#include "parser_nn.h"

namespace ufal {
namespace parsito {

void parser_nn::parse(tree& t, configuration& c) const {
  if (!system) return;

  // Unlink all nodes in the given tree
  t.unlink_all_nodes();

  // Create configuration
  c.init(t);

  // Compute which transitions to perform and perform them
  while (!c.final()) {
    unsigned transition = 0; // TODO: compute which transition to perform
    system->perform(c, t, transition);
  }
}

void parser_nn::load(binary_decoder& data) {
  // Load labels
  labels.resize(data.next_2B());
  for (auto&& label : labels)
    data.next_str(label);

  // Load transition system
  string system_name;
  data.next_str(system_name);
  system.reset(transition_system::create(system_name, labels));
}

} // namespace parsito
} // namespace ufal

Add skeleton of parser::parse implementation.


#include <iostream>
#include "List.h"

using namespace std;
using namespace List_h;

void foo() {
    Skip_list ll;

    for (auto i = -50; i < 50000; ++i) {
        ll.push_back(i);
    }

    ll.display();
}

int main() {
    Skip_list sl;

    sl.push_back(3);
    sl.push_back(6);
    sl.push_back(7);
    sl.push_back(9);
    sl.push_back(12);
    sl.push_back(17);
    sl.push_back(19);
    sl.push_back(25);
    sl.push_back(26);

    sl.insert(40, 40);
    sl.push_front(1);

    sl.delete_node(1);
    sl.delete_node(17);

    sl.display();

    int val;

    std::cout << "Please enter a number to search: ";
    std::cin >> val;

    if (sl.search(val)) {
        std::cout << val << " was found" << std::endl;
    }
    else {
        std::cout << val << " was not found" << std::endl;
    }

    return 0;
}

#include <vector>
#include <initializer_list>
#include <algorithm>
#include <random>
#include <iostream>
#include <ctime>
#include "List.h"

using namespace std;
using namespace List_h;

void foo() {
    Skip_list ll;

    for (auto i = -50; i < 50000; ++i) {
        ll.push_back(i);
    }

    ll.display();
}

int main() {
    constexpr int border = 8000000;
    Skip_list sl;
    Slink_list sll;

    for (auto i = 0; i < border; ++i) {
        sl.push_back(i);
        sll.push_back(i);
    }

    int val;

    std::cout << "Please enter a number to search: ";
    while (std::cin >> val) {

        clock_t t;

        t = clock();

        /*if (sl.search(val)) {
            std::cout << val << " was found" << std::endl;
        }
        else {
            std::cout << val << " was not found" << std::endl;
        }*/

        bool vt = sl.search(val);

        t = clock() - t;

        std::cout << "Search in the skip list took me " << t << " cycles (" << static_cast<float> (t) / CLOCKS_PER_SEC << " seconds).\n";

        t = clock();

        const Link *p = sll.find(val);

        t = clock() - t;

        std::cout << "Search in the singly linked list took me " << t << " cycles (" << static_cast<float> (t) / CLOCKS_PER_SEC << " seconds).\n";

        if (vt) {
            std::cout << "Value " << p->val << " was found\n";
        }
    }

    return 0;
}

Change example a little bit


#include "Animator.h"

namespace hm
{
	Animator::Animator()
	{

	}

	Animator::~Animator()
	{

	}

	void Animator::add(Animation a)
	{
		animations.push_back(a);
		return;
	}

	void Animator::add(AnimationQueue q)
	{
		queues.push_back(q);
		return;
	}

	void Animator::clearAnimations()
	{
		animations.clear();
		return;
	}

	void Animator::clearQueues()
	{
		queues.clear();
		return;
	}

	void Animator::clear()
	{
		animations.clear();
		queues.clear();
		return;
	}

	void Animator::animate()
	{
		// Iteratively animate all given animations.
		for(std::vector<Animation>::iterator it = animations.begin();
				it != animations.end(); it++)
		{
			it->animate();

			// Remove completed animations.
			if(it->isComplete())
			{
				it = animations.erase(it);
				it--;
			}
		}

		// Iteratively animate all given queues.
		for(std::vector<AnimationQueue>::iterator it = queues.begin();
				it != queues.end(); it++)
		{
			it->animate();

			// Remove empty queues.
			if(it->isComplete())
			{
				it = animations.erase(it);
				it--;
			}
		}

		return;
	}
}

#include "Animator.h"

namespace hm
{
	Animator::Animator()
	{

	}

	Animator::~Animator()
	{

	}

	void Animator::add(Animation a)
	{
		animations.push_back(a);
		return;
	}

	void Animator::add(AnimationQueue q)
	{
		queues.push_back(q);
		return;
	}

	void Animator::clearAnimations()
	{
		animations.clear();
		return;
	}

	void Animator::clearQueues()
	{
		queues.clear();
		return;
	}

	void Animator::clear()
	{
		animations.clear();
		queues.clear();
		return;
	}

	void Animator::animate()
	{
		// Iteratively animate all given animations.
		for(std::vector<Animation>::iterator it = animations.begin();
				it != animations.end(); it++)
		{
			it->animate();

			// Remove completed animations.
			if(it->isComplete())
			{
				it = animations.erase(it);
				it--;
			}
		}

		// Iteratively animate all given queues.
		for(std::vector<AnimationQueue>::iterator it = queues.begin();
				it != queues.end(); it++)
		{
			it->animate();

			// Remove empty queues.
			if(it->isComplete())
			{
				it = queues.erase(it);
				it--;
			}
		}

		return;
	}
}

Correct call to remove empty queues.


// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.

#include "ofp/protocoliterator.h"
#include "ofp/unittest.h"

using namespace ofp;

TEST(protocoliterator, ProtocolRangeItemCount) {
  UInt64 buffer;
  ByteRange data{&buffer, 0UL};
  const size_t unused = ~0UL;

  EXPECT_EQ(
      0, detail::ProtocolRangeItemCount(8, data, PROTOCOL_ITERATOR_SIZE_FIXED));

  for (size_t offset = 0; offset < 32; offset += 2) {
    EXPECT_EQ(0, detail::ProtocolRangeItemCount(unused, data, offset));
  }
}

TEST(protocoliterator, ProtocolRangeSplitOffset) {
  UInt64 buffer = 0;
  ByteRange data{&buffer, 0UL};
  const size_t unused = ~0UL;

  EXPECT_EQ(0, detail::ProtocolRangeSplitOffset(8, unused, data, 0));

  *Big16_cast(&buffer) = 8;
  ByteRange data8{&buffer, sizeof(buffer)};
  EXPECT_EQ(8, detail::ProtocolRangeSplitOffset(8, unused, data8, 0));
}

// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.

#include "ofp/protocoliterator.h"
#include "ofp/unittest.h"

using namespace ofp;

TEST(protocoliterator, ProtocolRangeItemCount) {
  UInt64 buffer;
  ByteRange data{&buffer, static_cast<size_t>(0)};
  const size_t unused = ~0UL;

  EXPECT_EQ(
      0, detail::ProtocolRangeItemCount(8, data, PROTOCOL_ITERATOR_SIZE_FIXED));

  for (size_t offset = 0; offset < 32; offset += 2) {
    EXPECT_EQ(0, detail::ProtocolRangeItemCount(unused, data, offset));
  }
}

TEST(protocoliterator, ProtocolRangeSplitOffset) {
  UInt64 buffer = 0;
  ByteRange data{&buffer, static_cast<size_t>(0)};
  const size_t unused = ~0UL;

  EXPECT_EQ(0, detail::ProtocolRangeSplitOffset(8, unused, data, 0));

  *Big16_cast(&buffer) = 8;
  ByteRange data8{&buffer, sizeof(buffer)};
  EXPECT_EQ(8, detail::ProtocolRangeSplitOffset(8, unused, data8, 0));
}

Fix ambiguity for 32-bit gcc.


#include "dselrig_part.h"
#include "eavesdroppermodel.h"

#include <kdemacros.h>
#include <kparts/genericfactory.h>

#include <QLabel>
#include <QTreeView>
#include <QVBoxLayout>

K_PLUGIN_FACTORY(DselRigPartFactory, registerPlugin<DselRigPart>();)  // produce a factory
K_EXPORT_PLUGIN(DselRigPartFactory("DselRig", "DselRig"))

class DselRigPart::Private
{
public:
    QWidget *mainWidget;
};

DselRigPart::DselRigPart(QWidget *parentWidget, QObject *parent, const QVariantList &)
   : KParts::ReadOnlyPart(parent),
     d(new Private)
{
    KGlobal::locale()->insertCatalog("DselRig");
    setComponentData(DselRigPartFactory::componentData());

    d->mainWidget = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout;
    d->mainWidget->setLayout(mainLayout);

    QLabel *label = new QLabel("I am DselRig");
    mainLayout->addWidget(label);

    QTreeView *messageList = new QTreeView;
    mainLayout->addWidget(messageList);
    EavesdropperModel *model = new EavesdropperModel();
    messageList->setModel(model);

    setWidget(d->mainWidget);
}

DselRigPart::~DselRigPart()
{
    delete d;
    d = 0;
}

#include "dselrig_part.h"
#include "eavesdroppermodel.h"

#include <kdemacros.h>
#include <kparts/genericfactory.h>

#include <QLabel>
#include <QTreeView>
#include <QVBoxLayout>

K_PLUGIN_FACTORY(DselRigPartFactory, registerPlugin<DselRigPart>();)  // produce a factory
K_EXPORT_PLUGIN(DselRigPartFactory("DselRig", "DselRig"))

class DselRigPart::Private
{
public:
    QWidget *mainWidget;
};

DselRigPart::DselRigPart(QWidget *parentWidget, QObject *parent, const QVariantList &)
   : KParts::ReadOnlyPart(parent),
     d(new Private)
{
    KGlobal::locale()->insertCatalog("DselRig");
    setComponentData(DselRigPartFactory::componentData());

    d->mainWidget = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout;
    d->mainWidget->setLayout(mainLayout);

    QTreeView *messageList = new QTreeView;
    mainLayout->addWidget(messageList);
    EavesdropperModel *model = new EavesdropperModel();
    messageList->setModel(model);

    setWidget(d->mainWidget);
}

DselRigPart::~DselRigPart()
{
    delete d;
    d = 0;
}

Remove the QLabel, it's a leftover from getting the KPart to work.


#include "../../base/SRC_FIRST.hpp"
#include "../../testing/testing.hpp"

#include "../writer.hpp"
#include "../../base/macros.hpp"

UNIT_TEST(MemWriterEmpty)
{
  vector<char> data;
  {
    MemWriter< vector<char> > writer(data);
  }
  TEST(data.empty(), (data));
}

UNIT_TEST(MemWriterSimple)
{
  vector<char> data;
  MemWriter< vector<char> > writer(data);
  writer.Write("Hello", 5);
  writer.Write(",", 1);
  writer.Write("world!", 6);
  char const expected_string[] = "Hello,world!";
  vector<char> expected_data(&expected_string[0], &expected_string[ARRAY_SIZE(expected_string)-1]);
  TEST_EQUAL(data, expected_data, ());
}

#include "../../base/SRC_FIRST.hpp"
#include "../../testing/testing.hpp"

#include "../writer.hpp"
#include "../file_writer.hpp"

#include "../../base/macros.hpp"

UNIT_TEST(MemWriterEmpty)
{
  vector<char> data;
  {
    MemWriter< vector<char> > writer(data);
  }
  TEST(data.empty(), (data));
}

UNIT_TEST(MemWriterSimple)
{
  vector<char> data;
  MemWriter< vector<char> > writer(data);
  writer.Write("Hello", 5);
  writer.Write(",", 1);
  writer.Write("world!", 6);

  char const expected[] = "Hello,world!";
  TEST_EQUAL(data.size(), ARRAY_SIZE(expected)-1, ());
  TEST(equal(data.begin(), data.end(), &expected[0]), (data));
}

/*
UNIT_TEST(FileWriter_NoDiskSpace)
{
  FileWriter w("/Volumes/Untitled/file.bin");

  vector<uint8_t> bytes(100000000);

  for (size_t i = 0; i < 10; ++i)
    w.Write(&bytes[0], bytes.size());
}
*/

Test for FileWriter (not enough disk space).


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

#include "base/test/launcher/unit_test_launcher.h"

namespace base {

int LaunchUnitTests(int argc,
                    char** argv,
                    const RunTestSuiteCallback& run_test_suite) {
  // Stub implementation - iOS doesn't support features we need for
  // the full test launcher (e.g. process_util).
  return run_test_suite.Run();
}

}  // namespace base

Add newline to end of file.


/*
 * Author: Laurent Goderre
 */

#include <stdio.h>
#include <Arduino.h>
#include "Target.h"

//-------------------------------------
// TODO: CALIBRATE THESE FOR SERVOS
const int servoOffPosition = 150;
const int servoOnPosition = 400;
//-------------------------------------

const String showingStr = "Showing target #";
const String hidingStr = "Hiding target #";

Target::Target(int targetNumber, Adafruit_PWMServoDriver pwm, int servoNumber) : number(targetNumber), pwm(pwm), servoNumber(servoNumber) {
	//Set Servo to initial position
	pwm.setPWM(servoNumber, 0, servoOffPosition);
}

Target::~Target(void){}

void Target::show()
{
	Serial.println(showingStr + (number + 1));
	for (uint16_t pulselen = servoOffPosition; pulselen < servoOnPosition; pulselen++) {
		pwm.setPWM(servoNumber, 0, pulselen);
	}
}

void Target::hide()
{
	Serial.println(hidingStr + (number + 1));
	for (uint16_t pulselen = servoOnPosition; pulselen > servoOffPosition; pulselen--) {
		pwm.setPWM(servoNumber, 0, pulselen);
	}
}

/*
 * Author: Laurent Goderre
 */

#include <stdio.h>
#include <Arduino.h>
#include "Target.h"

//-------------------------------------
// TODO: CALIBRATE THESE FOR SERVOS
const int servoOffPosition = 150;
const int servoOnPosition = 400;
//-------------------------------------

const String showingStr = "Showing target #";
const String hidingStr = "Hiding target #";

Target::Target(int targetNumber, Adafruit_PWMServoDriver pwm, int servoNumber) : number(targetNumber), pwm(pwm), servoNumber(servoNumber) {
	//Hide the target on initalization
	this->hide();
}

Target::~Target(void){}

void Target::show()
{
	Serial.println(showingStr + (number + 1));
	for (uint16_t pulselen = servoOffPosition; pulselen < servoOnPosition; pulselen++) {
		pwm.setPWM(servoNumber, 0, pulselen);
	}
}

void Target::hide()
{
	Serial.println(hidingStr + (number + 1));
	for (uint16_t pulselen = servoOnPosition; pulselen > servoOffPosition; pulselen--) {
		pwm.setPWM(servoNumber, 0, pulselen);
	}
}

Use target hide method instead of custom code on initialization


// 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/net/async_dns_field_trial.h"

#include "base/metrics/field_trial.h"
#include "build/build_config.h"
#include "chrome/common/chrome_version_info.h"

namespace chrome_browser_net {

bool ConfigureAsyncDnsFieldTrial() {
#if defined(OS_ANDROID) || defined(OS_IOS)
  // There is no DnsConfigService on those platforms so disable the field trial.
  return false;
#endif
  const base::FieldTrial::Probability kAsyncDnsDivisor = 100;
  base::FieldTrial::Probability enabled_probability = 0;

#if defined(OS_CHROMEOS)
  if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_DEV)
    enabled_probability = 50;
#endif

  scoped_refptr<base::FieldTrial> trial(
      base::FieldTrialList::FactoryGetFieldTrial(
          "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 10, 30, NULL));

  int enabled_group = trial->AppendGroup("enabled", enabled_probability);
  return trial->group() == enabled_group;
}

}  // namespace chrome_browser_net

// 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/net/async_dns_field_trial.h"

#include "base/metrics/field_trial.h"
#include "build/build_config.h"
#include "chrome/common/chrome_version_info.h"

namespace chrome_browser_net {

bool ConfigureAsyncDnsFieldTrial() {
#if defined(OS_ANDROID) || defined(OS_IOS)
  // There is no DnsConfigService on those platforms so disable the field trial.
  return false;
#endif
  const base::FieldTrial::Probability kAsyncDnsDivisor = 100;
  base::FieldTrial::Probability enabled_probability = 0;

  if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_DEV)
    enabled_probability = 50;

  scoped_refptr<base::FieldTrial> trial(
      base::FieldTrialList::FactoryGetFieldTrial(
          "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 10, 30, NULL));

  int enabled_group = trial->AppendGroup("enabled", enabled_probability);
  return trial->group() == enabled_group;
}

}  // namespace chrome_browser_net

Extend async DNS field trial to other supported platforms.


#include "common/application_info.h"

namespace brightray {

std::string GetApplicationName() {
  return std::string();
}

std::string GetApplicationVersion() {
  return std::string();
}

}

#include "common/application_info.h"

#include "base/file_version_info.h"
#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"

namespace brightray {

std::string GetApplicationName() {
  auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
  return UTF16ToUTF8(info->product_name());
}

std::string GetApplicationVersion() {
  auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
  return UTF16ToUTF8(info->file_version());
}

}

Set the user agent string correctly on Windows


#include <ncurses.h>

#include <string>

using namespace std;

void menuShow();
void menuAdd(int pos, string str);
void menuDone();

int main() {

    /*
     * init term
     */

    initscr();
    cbreak();
    noecho();
    clear();

    /*
     * init title
     */
    menuShow();

    refresh();
    while(true);

    /*
     * exit
     */

    return 0;
}

void menuShow() {

    move(5, 5); // move cursor to (x,y)

    string text = "TERMINAL QUEST";
    for (size_t i = 0; i < text.size(); i++) {
        addch(text[i]);
        addch(' ');
    }

    menuAdd(1, "start");
    menuAdd(2, "quit");
    menuDone();

    refresh();

    while(1);
}

void close() {
    endwin();
}

// Private functions

void menuAdd(int pos, string str) {
    if (pos > 0 && str.length() > 0) {
        move((pos + 6), 8);
        addstr(str.c_str());
    }
}

void menuDone() {
    move(7, 6);
}

#include <ncurses.h>

#include <string>

using namespace std;

void menuShow(string title);
void menuAdd(int pos, string str);
void menuDone();

int main() {

    /*
     * init term
     */

    initscr();
    cbreak();
    noecho();
    clear();

    /*
     * init title
     */
    menuShow("TERMINAL QUEST");

    refresh();
    while(true);

    /*
     * exit
     */

    return 0;
}

void menuShow(string title) {

    move(5, 5); // move cursor to (x,y)

    for (size_t i = 0; i < title.size(); i++) {
        addch(title[i]);
        addch(' ');
    }

    menuAdd(1, "start");
    menuAdd(2, "quit");
    menuDone();

    refresh();

    while(1);
}

void close() {
    endwin();
}

// Private functions

void menuAdd(int pos, string str) {
    if (pos > 0 && str.length() > 0) {
        move((pos + 6), 8);
        addstr(str.c_str());
    }
}

void menuDone() {
    move(7, 6);
}

Use dynamic str rather than static in priv fn


/* Copyright (c) 2010 David Bender assigned to Benegon Enterprises LLC
 * See the file LICENSE for full license information. */

#include <errno.h>
#include "posix.hh"

FD_Reader::FD_Reader(int fd) throw()
	: _fd(fd), _errno(0)
{
}

FD_Reader::~FD_Reader() throw(){
	/* Assume file is read only; don't really care about successful close. */
	if(-1 != _fd)
		close(_fd);
}

int FD_Reader::Read(uint8_t* buff, unsigned len) throw(){
	/* If file closed just return 0. */
	if(-1 == _fd)
		return 0;

	/* BLOCKING read until data comes or unrecoverable error. */
	while(true){
		int ret = read(_fd, buff, len);
		if(ret < 0){
			if(EINTR == errno)
				continue;
			_errno = errno;
			close(_fd);
			_fd = -1;
		}
		else if(0 == ret){
			close(_fd);
			_fd = -1;
		}
		return ret;
	}
}

/* Copyright (c) 2010 David Bender assigned to Benegon Enterprises LLC
 * See the file LICENSE for full license information. */

#include <errno.h>
#include <unistd.h>
#include "posix.hh"

FD_Reader::FD_Reader(int fd) throw()
	: _fd(fd), _errno(0)
{
}

FD_Reader::~FD_Reader() throw(){
	/* Assume file is read only; don't really care about successful close. */
	if(-1 != _fd)
		close(_fd);
}

int FD_Reader::Read(uint8_t* buff, unsigned len) throw(){
	/* If file closed just return 0. */
	if(-1 == _fd)
		return 0;

	/* BLOCKING read until data comes or unrecoverable error. */
	while(true){
		int ret = read(_fd, buff, len);
		if(ret < 0){
			if(EINTR == errno)
				continue;
			_errno = errno;
			close(_fd);
			_fd = -1;
		}
		else if(0 == ret){
			close(_fd);
			_fd = -1;
		}
		return ret;
	}
}

Add include line that may be required on some platforms


#include "Transform.h"

BEGIN_NAMESPACE_CA_DRAWING

Transform::Transform()
	: position(0, 0)
	, scale(1, 1)
	, angle(0)
{

}

Transform::~Transform()
{

}

//###########################################################################

void Transform::addTransform(const Transform& other)
{
	position += other.position;

	scale.x *= other.scale.x;
	scale.y *= other.scale.y;

	angle += other.angle;
	while (angle >= 360.0f) angle -= 360.0f;
	while (angle < 0.0f) angle += 360.0f;
}

END_NAMESPACE_CA_DRAWING

#include "Transform.h"

BEGIN_NAMESPACE_CA_DRAWING

Transform::Transform()
	: position(0, 0)
	, scale(1, 1)
	, angle(0)
{

}

Transform::~Transform()
{

}

//###########################################################################

void Transform::addTransform(const Transform& other)
{
	position += other.position;

	scale.x *= other.scale.x;
	scale.y *= other.scale.y;

	angle += other.angle;
}

END_NAMESPACE_CA_DRAWING

Delete unnecessary code in transform class.


/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include <QtCore/QCoreApplication>

#include "testapp.h"

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

    TestApp *test = new TestApp(0);

    app.exec();
}

/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include <QtGui/QApplication>

#include "testapp.h"

int main (int argc, char *argv[])
{
    setenv("KSCREEN_BACKEND", "XRandR", 1);
    QApplication app(argc, argv);

    TestApp *test = new TestApp(0);

    app.exec();
}

Use QApplication and set KScreen backend to XRandR


// Copyright 2014 Toggl Desktop developers.

#include <windows.h>
#include <psapi.h>
#pragma comment(lib, "psapi.lib")
#include <time.h>
#include <string>

static const int kFilenameBufferSize = 255;

template <class string_type>
inline typename string_type::value_type *WriteInto(string_type *str,
        size_t length_with_null) {
    str->reserve(length_with_null);
    str->resize(length_with_null - 1);
    return &((*str)[0]);
}

void GetFocusedWindowInfo(std::string *title, std::string *filename) {
    *title = "";
    *filename = "";

    // get window handle
    HWND window_handle = GetForegroundWindow();

    // get window title
    int length = GetWindowTextLength(window_handle) + 1;
    std::wstring title_wstring;
    GetWindowText(window_handle, WriteInto(&title_wstring, length), length);
    std::string str(title_wstring.begin(), title_wstring.end());
    *title = str;

    // get process by window handle
    DWORD process_id;
    GetWindowThreadProcessId(window_handle, &process_id);

    // get the filename of another process
    HANDLE ps = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE,
                            process_id);
    CHAR filename_buffer[kFilenameBufferSize];
    if (GetModuleFileNameExA(ps, 0, filename_buffer, kFilenameBufferSize) > 0) {
        *filename = std::string(filename_buffer);
    }
}

// Copyright 2014 Toggl Desktop developers.

#include <windows.h>
#include <psapi.h>
#pragma comment(lib, "psapi.lib")
#include <time.h>

static const int kFilenameBufferSize = 255;

template <class string_type>
inline typename string_type::value_type *WriteInto(string_type *str,
        size_t length_with_null) {
    str->reserve(length_with_null);
    str->resize(length_with_null - 1);
    return &((*str)[0]);
}

void GetFocusedWindowInfo(std::string *title, std::string *filename) {
    *title = "";
    *filename = "";

    // get window handle
    HWND window_handle = GetForegroundWindow();

    // get window title
    int length = GetWindowTextLength(window_handle) + 1;
    std::wstring title_wstring;
    GetWindowText(window_handle, WriteInto(&title_wstring, length), length);
    std::string str(title_wstring.begin(), title_wstring.end());
    *title = str;

    // get process by window handle
    DWORD process_id;
    GetWindowThreadProcessId(window_handle, &process_id);

    // get the filename of another process
    HANDLE ps = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE,
                            process_id);
    CHAR filename_buffer[kFilenameBufferSize];
    if (GetModuleFileNameExA(ps, 0, filename_buffer, kFilenameBufferSize) > 0) {
        *filename = std::string(filename_buffer);
    }
}

Add missing string include for win32


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

#include "chrome/common/net/test_url_fetcher_factory.h"

TestURLFetcher::TestURLFetcher(int id,
                               const GURL& url,
                               URLFetcher::RequestType request_type,
                               URLFetcher::Delegate* d)
    : URLFetcher(url, request_type, d),
      id_(id),
      original_url_(url) {
}

URLFetcher* TestURLFetcherFactory::CreateURLFetcher(
    int id,
    const GURL& url,
    URLFetcher::RequestType request_type,
    URLFetcher::Delegate* d) {
  TestURLFetcher* fetcher = new TestURLFetcher(id, url, request_type, d);
  fetchers_[id] = fetcher;
  return fetcher;
}

TestURLFetcher* TestURLFetcherFactory::GetFetcherByID(int id) const {
  Fetchers::const_iterator i = fetchers_.find(id);
  return i == fetchers_.end() ? NULL : i->second;
}

void TestURLFetcherFactory::RemoveFetcherFromMap(int id) {
  Fetchers::const_iterator i = fetchers_.find(id);
  DCHECK(i != fetchers_.end());
  fetchers_.erase(i);
}

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

#include "chrome/common/net/test_url_fetcher_factory.h"

TestURLFetcher::TestURLFetcher(int id,
                               const GURL& url,
                               URLFetcher::RequestType request_type,
                               URLFetcher::Delegate* d)
    : URLFetcher(url, request_type, d),
      id_(id),
      original_url_(url) {
}

URLFetcher* TestURLFetcherFactory::CreateURLFetcher(
    int id,
    const GURL& url,
    URLFetcher::RequestType request_type,
    URLFetcher::Delegate* d) {
  TestURLFetcher* fetcher = new TestURLFetcher(id, url, request_type, d);
  fetchers_[id] = fetcher;
  return fetcher;
}

TestURLFetcher* TestURLFetcherFactory::GetFetcherByID(int id) const {
  Fetchers::const_iterator i = fetchers_.find(id);
  return i == fetchers_.end() ? NULL : i->second;
}

void TestURLFetcherFactory::RemoveFetcherFromMap(int id) {
  Fetchers::iterator i = fetchers_.find(id);
  DCHECK(i != fetchers_.end());
  fetchers_.erase(i);
}

Fix compile failure on GCC


//===-- Passes.cpp - Target independent code generation passes ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//

#include "llvm/CodeGen/Passes.h"
#include "Support/CommandLine.h"
#include <iostream>
using namespace llvm;

namespace {
  enum RegAllocName { simple, local, linearscan, iterativescan };

  cl::opt<RegAllocName RegAlloc(
    "regalloc",
    cl::desc("Register allocator to use: (default = simple)"),
    cl::Prefix,
    cl::values(
       clEnumVal(simple,        "  simple register allocator"),
       clEnumVal(local,         "  local register allocator"),
       clEnumVal(linearscan,    "  linear scan register allocator"),
       clEnumVal(iterativescan, "  iterative scan register allocator"),
       clEnumValEnd),
    cl::init(local));
}

FunctionPass *llvm::createRegisterAllocator() {
  switch (RegAlloc) {
  default:
    std::cerr << "no register allocator selected";
    abort();
  case simple:
    return createSimpleRegisterAllocator();
  case local:
    return createLocalRegisterAllocator();
  case linearscan:
    return createLinearScanRegisterAllocator();
  case iterativescan:
    return createIterativeScanRegisterAllocator();
  }
}

//===-- Passes.cpp - Target independent code generation passes ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//

#include "llvm/CodeGen/Passes.h"
#include "Support/CommandLine.h"
#include <iostream>
using namespace llvm;

namespace {
  enum RegAllocName { simple, local, linearscan, iterativescan };

  cl::opt<RegAllocName>
  RegAlloc(
    "regalloc",
    cl::desc("Register allocator to use: (default = simple)"),
    cl::Prefix,
    cl::values(
       clEnumVal(simple,        "  simple register allocator"),
       clEnumVal(local,         "  local register allocator"),
       clEnumVal(linearscan,    "  linear scan register allocator"),
       clEnumVal(iterativescan, "  iterative scan register allocator"),
       clEnumValEnd),
    cl::init(local));
}

FunctionPass *llvm::createRegisterAllocator() {
  switch (RegAlloc) {
  default:
    std::cerr << "no register allocator selected";
    abort();
  case simple:
    return createSimpleRegisterAllocator();
  case local:
    return createLocalRegisterAllocator();
  case linearscan:
    return createLinearScanRegisterAllocator();
  case iterativescan:
    return createIterativeScanRegisterAllocator();
  }
}

Put variable name to a separate line.


// csamisc_anonymousnamespaceinheader.t.cpp                           -*-C++-*-
// -----------------------------------------------------------------------------
// Copyright 2011 Dietmar Kuehl http://www.dietmar-kuehl.de
// Distributed under the Boost Software License, Version 1.0. (See file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
// -----------------------------------------------------------------------------

#include <csabase_analyser.h>
#include <csabase_location.h>
#include <csabase_registercheck.h>
#ident "$Id$"

// -----------------------------------------------------------------------------

static std::string const check_name("anon-namespace");

static void
anonymous_namespace_in_header(cool::csabase::Analyser& analyser, clang::NamespaceDecl const* decl)
{
    if (decl->isAnonymousNamespace()
        && analyser.get_location(decl).file() != analyser.toplevel())
    {
        analyser.report(decl, check_name, "ANS01",
                "Anonymous namespace in header");
    }
}

// -----------------------------------------------------------------------------

static cool::csabase::RegisterCheck check(check_name, &anonymous_namespace_in_header);

// csamisc_anonymousnamespaceinheader.t.cpp                           -*-C++-*-
// -----------------------------------------------------------------------------
// Copyright 2011 Dietmar Kuehl http://www.dietmar-kuehl.de
// Distributed under the Boost Software License, Version 1.0. (See file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
// -----------------------------------------------------------------------------

#include <csabase_analyser.h>
#include <csabase_debug.h>
#include <csabase_location.h>
#include <csabase_registercheck.h>
#ident "$Id$"

// -----------------------------------------------------------------------------

static std::string const check_name("anon-namespace");

static void anonymous_namespace_in_header(cool::csabase::Analyser& analyser,
                                          clang::NamespaceDecl const* decl)
{
    if (decl->isAnonymousNamespace() && analyser.is_component_header(decl)) {
        analyser.report(decl, check_name, "ANS01",
                "Anonymous namespace in header", true);
    }
}

// -----------------------------------------------------------------------------

static cool::csabase::RegisterCheck check(check_name, &anonymous_namespace_in_header);

Check should be for component header, not not toplevel.


#include "omnicore/version.h"

#include "config/bitcoin-config.h"

#include <string>

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(omnicore_version_tests)

BOOST_AUTO_TEST_CASE(version_comparison)
{
    BOOST_CHECK(OMNICORE_VERSION > 900300); // Master Core v0.0.9.3
}

/**
 * The following tests are very unhandy, because any version bump
 * breaks the tests.
 *
 * TODO: might be removed completely.
 */

BOOST_AUTO_TEST_CASE(version_string)
{
    BOOST_CHECK_EQUAL(OmniCoreVersion(), "0.0.10-rc2");
}

BOOST_AUTO_TEST_CASE(version_number)
{
    BOOST_CHECK_EQUAL(OMNICORE_VERSION, 1000000);
}

BOOST_AUTO_TEST_CASE(config_package_version)
{
    // the package version is used in the file names:
    BOOST_CHECK_EQUAL(PACKAGE_VERSION, "0.0.10.0-rc2");
}

BOOST_AUTO_TEST_SUITE_END()

#include "omnicore/version.h"

#include "config/bitcoin-config.h"

#include <string>

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(omnicore_version_tests)

BOOST_AUTO_TEST_CASE(version_comparison)
{
    BOOST_CHECK(OMNICORE_VERSION > 900300); // Master Core v0.0.9.3
}

/**
 * The following tests are very unhandy, because any version bump
 * breaks the tests.
 *
 * TODO: might be removed completely.
 */

BOOST_AUTO_TEST_CASE(version_string)
{
    BOOST_CHECK_EQUAL(OmniCoreVersion(), "0.0.10-rc3");
}

BOOST_AUTO_TEST_CASE(version_number)
{
    BOOST_CHECK_EQUAL(OMNICORE_VERSION, 1000000);
}

BOOST_AUTO_TEST_CASE(config_package_version)
{
    // the package version is used in the file names:
    BOOST_CHECK_EQUAL(PACKAGE_VERSION, "0.0.10.0-rc3");
}

BOOST_AUTO_TEST_SUITE_END()

Update unit tests for rc3


#include <memory>

#include "view.h"
#include "dummyfrequencyprovider.h"
#include "frequencyprovider.h"

#include <emscripten.h>

#include <SDL/SDL.h>

extern "C" {
    EMSCRIPTEN_KEEPALIVE
    int run_fmv_with_frequency_provider(int width, int height) {
        std::shared_ptr<FMV::FrequencyProvider> provider(FMV::createDummyFrequencyProvider());
        return FMV::runViewLoop(0, nullptr, {width, height}, *provider);
    }
}

#include <array>

#include <memory>

#include "view.h"
#include "frequencyprovider.h"

#include <emscripten.h>

#include <SDL/SDL.h>

namespace {
    class ModifiableFrequencyProvider :
        public FMV::FrequencyProvider
    {
        public:
            static std::array<float, 255> frequencyData;

        public:
            void workWithCurrentFrequencies(Callback const &cb) override {
                cb(ModifiableFrequencyProvider::frequencyData.data());
            }
    };
}

extern "C" {
    EMSCRIPTEN_KEEPALIVE
    int run_fmv_with_frequency_provider(int width, int height) {
        ModifiableFrequencyProvider::frequencyData.fill(0.0);
        ModifiableFrequencyProvider provider;
        return FMV::runViewLoop(0, nullptr, {width, height}, provider);
    }

    EMSCRIPTEN_KEEPALIVE
    void set_frequencies(float *frequencies, size_t length) {
        for (size_t i = 0; i < length; ++i) {
            ModifiableFrequencyProvider::frequencyData[i] = frequencies[i];
        }
    }
}

Allow for frequencies to be modified


// 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/glue/resource_loader_bridge.h"

#include "net/http/http_response_headers.h"

namespace webkit_glue {

ResourceLoaderBridge::ResponseInfo::ResponseInfo() {
  content_length = -1;
#if defined(OS_WIN)
  response_data_file = base::kInvalidPlatformFileValue;
#elif defined(OS_POSIX)
  response_data_file.fd = base::kInvalidPlatformFileValue;
  response_data_file.auto_close = false;
#endif
}

ResourceLoaderBridge::ResponseInfo::~ResponseInfo() {
}

ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() {
}

ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() {
}

ResourceLoaderBridge::ResourceLoaderBridge() {
}

ResourceLoaderBridge::~ResourceLoaderBridge() {
}

}  // namespace webkit_glue

// 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/glue/resource_loader_bridge.h"
#include "webkit/glue/webappcachecontext.h"

#include "net/http/http_response_headers.h"

namespace webkit_glue {

ResourceLoaderBridge::ResponseInfo::ResponseInfo() {
  content_length = -1;
  app_cache_id = WebAppCacheContext::kNoAppCacheId;
#if defined(OS_WIN)
  response_data_file = base::kInvalidPlatformFileValue;
#elif defined(OS_POSIX)
  response_data_file.fd = base::kInvalidPlatformFileValue;
  response_data_file.auto_close = false;
#endif
}

ResourceLoaderBridge::ResponseInfo::~ResponseInfo() {
}

ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() {
}

ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() {
}

ResourceLoaderBridge::ResourceLoaderBridge() {
}

ResourceLoaderBridge::~ResourceLoaderBridge() {
}

}  // namespace webkit_glue

Fix an issue found by purify with my previous submission.


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

// Portable interface for browser interaction - API invariant portions.

#include "base/rand_util_c.h"

#include "native_client/src/include/nacl_string.h"
#include "native_client/src/include/nacl_elf.h"
#include "native_client/src/include/portability_io.h"
#include "native_client/src/trusted/plugin/nacl_entry_points.h"

extern "C" {
  int GetUrandomFD(void) {
    return get_urandom_fd();
  }
}

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

// Portable interface for browser interaction - API invariant portions.

#include "base/rand_util_c.h"

#include "native_client/src/trusted/plugin/nacl_entry_points.h"

extern "C" {
  int GetUrandomFD(void) {
    return get_urandom_fd();
  }
}

Fix Chromium build breakage introduced by r6280


// Copyright 2016 The PDFium 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 <memory>

#include "core/fxcrt/cfx_retain_ptr.h"
#include "core/fxcrt/fx_string.h"
#include "xfa/fde/css/cfde_csssyntaxparser.h"
#include "xfa/fde/css/fde_css.h"
#include "xfa/fgas/crt/fgas_stream.h"
#include "xfa/fxfa/parser/cxfa_widetextread.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  CFX_WideString input = CFX_WideString::FromUTF8(
      CFX_ByteStringC(data, static_cast<FX_STRSIZE>(size)));

  CFDE_CSSSyntaxParser parser;
  parser.Init(input.c_str(), size);

  FDE_CSSSyntaxStatus status;
  do {
    status = parser.DoSyntaxParse();
  } while (status != FDE_CSSSyntaxStatus::Error &&
           status != FDE_CSSSyntaxStatus::EOS);
  return 0;
}

// Copyright 2016 The PDFium 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 <memory>

#include "core/fxcrt/cfx_retain_ptr.h"
#include "core/fxcrt/fx_string.h"
#include "xfa/fde/css/cfde_csssyntaxparser.h"
#include "xfa/fde/css/fde_css.h"
#include "xfa/fgas/crt/fgas_stream.h"
#include "xfa/fxfa/parser/cxfa_widetextread.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  CFX_WideString input = CFX_WideString::FromUTF8(
      CFX_ByteStringC(data, static_cast<FX_STRSIZE>(size)));

  // If we convert the input into an empty string bail out.
  if (input.GetLength() == 0)
    return 0;

  CFDE_CSSSyntaxParser parser;
  parser.Init(input.c_str(), input.GetLength());

  FDE_CSSSyntaxStatus status;
  do {
    status = parser.DoSyntaxParse();
  } while (status != FDE_CSSSyntaxStatus::Error &&
           status != FDE_CSSSyntaxStatus::EOS);
  return 0;
}

Fix CSS fuzzer input size


// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Enchants/Power.hpp>

namespace RosettaStone
{
std::optional<Aura>& Power::GetAura()
{
    return m_aura;
}

Enchant& Power::GetEnchant()
{
    return m_enchant;
}

std::vector<ITask*>& Power::GetPowerTask()
{
    return m_powerTask;
}

std::vector<ITask*>& Power::GetDeathrattleTask()
{
    return m_deathrattleTask;
}

void Power::ClearData()
{
    m_powerTask.clear();
    m_deathrattleTask.clear();
}

void Power::AddAura(Aura&& aura)
{
    m_aura = std::move(aura);
}

void Power::AddEnchant(Enchant&& enchant)
{
    m_enchant = std::move(enchant);
}

void Power::AddPowerTask(ITask* task)
{
    m_powerTask.emplace_back(task);
}

void Power::AddDeathrattleTask(ITask* task)
{
    m_deathrattleTask.emplace_back(task);
}
}  // namespace RosettaStone

// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Enchants/Power.hpp>

namespace RosettaStone
{
std::optional<Aura>& Power::GetAura()
{
    return m_aura;
}

Enchant& Power::GetEnchant()
{
    return m_enchant;
}

std::vector<ITask*>& Power::GetPowerTask()
{
    return m_powerTask;
}

std::vector<ITask*>& Power::GetDeathrattleTask()
{
    return m_deathrattleTask;
}

void Power::ClearData()
{
    m_aura.reset();
    m_powerTask.clear();
    m_deathrattleTask.clear();
}

void Power::AddAura(Aura&& aura)
{
    m_aura = std::move(aura);
}

void Power::AddEnchant(Enchant&& enchant)
{
    m_enchant = std::move(enchant);
}

void Power::AddPowerTask(ITask* task)
{
    m_powerTask.emplace_back(task);
}

void Power::AddDeathrattleTask(ITask* task)
{
    m_deathrattleTask.emplace_back(task);
}
}  // namespace RosettaStone

Add code to reset 'm_aura' in ClearData() method


#include "mjolnir/directededgebuilder.h"

namespace valhalla {
namespace mjolnir {

// Default constructor
DirectedEdgeBuilder::DirectedEdgeBuilder()
    : speed_(0),
      length_(0) {
}

// Sets the length of the edge in kilometers.
void DirectedEdgeBuilder::length(const float length) {
  length_ = length;
}

// Sets the end node of this directed edge.
void DirectedEdgeBuilder::endnode(const GraphId& endnode) {
  endnode_ = endnode;
}

// TODO - methods for access

// Sets the speed in KPH.
void DirectedEdgeBuilder::speed(const float speed) const {
  // TODO - protect against exceeding max speed
  speed_ = static_cast<unsigned char>(speed + 0.5f);
}

}
}

#include "mjolnir/directededgebuilder.h"

namespace valhalla {
namespace mjolnir {

// Default constructor
DirectedEdgeBuilder::DirectedEdgeBuilder()
  : DirectedEdge() {
}

// Sets the length of the edge in kilometers.
void DirectedEdgeBuilder::length(const float length) {
  length_ = length;
}

// Sets the end node of this directed edge.
void DirectedEdgeBuilder::endnode(const GraphId& endnode) {
  endnode_ = endnode;
}

// TODO - methods for access

// Sets the speed in KPH.
void DirectedEdgeBuilder::speed(const float speed) const {
  // TODO - protect against exceeding max speed
  speed_ = static_cast<unsigned char>(speed + 0.5f);
}

}
}

Fix derived constructor to call base class constructor


#include "Genes/Pawn_Advancement_Gene.h"

#include <string>

#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Utility.h"

Pawn_Advancement_Gene::Pawn_Advancement_Gene() : Gene(0.0)
{
}

Pawn_Advancement_Gene::~Pawn_Advancement_Gene()
{
}

double Pawn_Advancement_Gene::score_board(const Board& board, Color perspective) const
{
    double score = 0.0;
    int home_rank = (perspective == WHITE ? 2 : 7);

    for(char file = 'a'; file <= 'h'; ++file)
    {
        for(int rank = 1; rank <= 8; ++rank)
        {
            auto piece = board.piece_on_square(file, rank);
            if(piece && piece->color() == perspective && toupper(piece->fen_symbol()) == 'P')
            {
                // 1 point per pawn + 1 point per move towards promotion
                score += std::abs(home_rank - rank);
            }
        }
    }

    return score/(8.*5.); // normalize to 8 pawns 5 ranks from home (just before promotion)
}

Pawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const
{
    return new Pawn_Advancement_Gene(*this);
}

std::string Pawn_Advancement_Gene::name() const
{
    return "Pawn Advancement Gene";
}

#include "Genes/Pawn_Advancement_Gene.h"

#include <string>

#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Utility.h"

Pawn_Advancement_Gene::Pawn_Advancement_Gene() : Gene(0.0)
{
}

Pawn_Advancement_Gene::~Pawn_Advancement_Gene()
{
}

double Pawn_Advancement_Gene::score_board(const Board& board, Color perspective) const
{
    double score = 0.0;
    int home_rank = (perspective == WHITE ? 2 : 7);

    for(char file = 'a'; file <= 'h'; ++file)
    {
        for(int rank = 1; rank <= 8; ++rank)
        {
            auto piece = board.piece_on_square(file, rank);
            if(piece && piece->color() == perspective && toupper(piece->fen_symbol()) == 'P')
            {
                // 1 point per move towards promotion
                score += std::abs(home_rank - rank);
            }
        }
    }

    return score/(8.*5.); // normalize to 8 pawns 5 ranks from home (just before promotion)
}

Pawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const
{
    return new Pawn_Advancement_Gene(*this);
}

std::string Pawn_Advancement_Gene::name() const
{
    return "Pawn Advancement Gene";
}

Fix incorrect comment in Pawn Advancement Gene


/*
 * glc_declarativeview.cpp
 *
 *  Created on: 22/04/2013
 *      Author: laumaya
 */

#include <QGLWidget>

#include <GLC_Context>

#include "glc_declarativeview.h"

GLC_DeclarativeView::GLC_DeclarativeView(QWidget *pParent)
    : QDeclarativeView(pParent)
{
    QDeclarativeView::setViewport(new QGLWidget(new GLC_Context(QGLFormat(QGL::SampleBuffers))));
    QDeclarativeView::setRenderHint(QPainter::SmoothPixmapTransform);
    QDeclarativeView::setRenderHint(QPainter::Antialiasing);
    QDeclarativeView::setResizeMode(QDeclarativeView::SizeViewToRootObject);
}

/*
 * glc_declarativeview.cpp
 *
 *  Created on: 22/04/2013
 *      Author: laumaya
 */

#include <QGLWidget>

#include <GLC_Context>

#include "glc_declarativeview.h"

GLC_DeclarativeView::GLC_DeclarativeView(QWidget *pParent)
    : QDeclarativeView(pParent)
{
    QDeclarativeView::setViewport(new QGLWidget(new GLC_Context(QGLFormat(QGL::SampleBuffers)), this));
    QDeclarativeView::setRenderHint(QPainter::SmoothPixmapTransform);
    QDeclarativeView::setRenderHint(QPainter::Antialiasing);
    QDeclarativeView::setResizeMode(QDeclarativeView::SizeViewToRootObject);
}

Fix a bug on Windows which cause a crash.


#include <iostream>

#include <Python.h>

#include "character.h"

using namespace std;

static int error(const std::string & message){
    std::cout << message << std::endl;
    //PyErr_Print();
    return -1;
}

int main(int argc, char ** argv){
    if (argc > 1){
        Py_Initialize();

        /* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('./')");

        try {
            Character * character = new Character(argv[1]);
            character->addAttribute("name", Character::String);
            std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
            delete character;
        } catch (const PyException & ex){
            error("Problem loading module! Reason: " + ex.getReason());
        }

        Py_Finalize();

        return 0;
    }

    std::cout << "Usage: ./test character.py" << std::endl;

    return 0;

}

#include <iostream>

#include <Python.h>

#include "character.h"

using namespace std;

static int error(const std::string & message){
    std::cout << message << std::endl;
    //PyErr_Print();
    return -1;
}

int main(int argc, char ** argv){
    if (argc > 1){
        Py_Initialize();

        /* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('./')");

        try {
            Character * character = new Character(argv[1]);
            character->addAttribute("name", Character::String);
            std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
            delete character;
        } catch (const PyException & ex){
            error("Problem loading module! Reason: " + ex.getReason());
        }

        Py_Finalize();

        return 0;
    }

    std::cout << "Usage: ./test character_module_name" << std::endl;

    return 0;

}

Correct usage line, no need to include .py in module name.


// Copyright (c) 2012 Cloudera, Inc. All rights reserved.
//
// This file contains the main() function for the state store process,
// which exports the Thrift service StateStoreService.

#include <glog/logging.h>
#include <gflags/gflags.h>

#include "sparrow/state-store-service.h"
#include "util/cpu-info.h"

DEFINE_int32(state_store_port, 24000, "port where StateStoreService is exported");

int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);
  impala::CpuInfo::Init();

  boost::shared_ptr<sparrow::StateStore> state_store(new sparrow::StateStore());
  state_store->Start(FLAGS_state_store_port);
  state_store->WaitForServerToStop();
}

// Copyright (c) 2012 Cloudera, Inc. All rights reserved.
//
// This file contains the main() function for the state store process,
// which exports the Thrift service StateStoreService.

#include <glog/logging.h>
#include <gflags/gflags.h>
#include <iostream>

#include "common/status.h"
#include "sparrow/state-store-service.h"
#include "util/cpu-info.h"
#include "util/webserver.h"
#include "util/logging.h"
#include "util/default-path-handlers.h"

DECLARE_int32(state_store_port);
DECLARE_int32(webserver_port);
DECLARE_bool(enable_webserver);

using impala::Webserver;
using impala::Status;
using namespace std;

int main(int argc, char** argv) {
  // Override default for webserver port
  FLAGS_webserver_port = 9190;
  google::ParseCommandLineFlags(&argc, &argv, true);
  impala::InitGoogleLoggingSafe(argv[0]);
  impala::CpuInfo::Init();

  boost::shared_ptr<sparrow::StateStore> state_store(new sparrow::StateStore());

  boost::scoped_ptr<Webserver> webserver(new Webserver());

  if (FLAGS_enable_webserver) {
    impala::AddDefaultPathHandlers(webserver.get());
    EXIT_IF_ERROR(webserver->Start());
  } else {
    LOG(INFO) << "Not starting webserver";
  }

  state_store->Start(FLAGS_state_store_port);
  state_store->WaitForServerToStop();
}

Allow configuraiton of state-store log dir / name. Also add debug webserver to state-store.


// Copyright 2014-present Bill Fisher. All rights reserved.

#include "ofp/mptablestats.h"
#include "ofp/writable.h"
#include "ofp/constants.h"
#include "ofp/log.h"
#include "ofp/validation.h"

using namespace ofp;

void MPTableStatsBuilder::write(Writable *channel) {
  UInt8 version = channel->version();

  if (version == OFP_VERSION_4) {
    channel->write(&msg_, 4);
    channel->write(&msg_.activeCount_, 20);
    channel->flush();

  } else if (version == OFP_VERSION_1) {
    channel->write(&msg_, sizeof(msg_));
    channel->flush();

  } else {
    log::debug("MPTableStatsBuilder not implemented for version:", version);
  }
}

// Copyright 2014-present Bill Fisher. All rights reserved.

#include "ofp/mptablestats.h"
#include "ofp/writable.h"
#include "ofp/constants.h"
#include "ofp/log.h"
#include "ofp/validation.h"

using namespace ofp;

void MPTableStatsBuilder::write(Writable *channel) {
  UInt8 version = channel->version();

  if (version >= OFP_VERSION_4) {
    channel->write(&msg_, 4);
    channel->write(&msg_.activeCount_, 20);
    channel->flush();

  } else if (version == OFP_VERSION_1) {
    channel->write(&msg_, sizeof(msg_));
    channel->flush();

  } else {
    log::debug("MPTableStatsBuilder not implemented for version:", version);
  }
}

Fix writing of v5 REPLY.TABLE.


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

#include "logging.h"

#include <iostream>
#include <unistd.h>

#include "cutils/log.h"

static const int kLogSeverityToAndroidLogPriority[] = {
  ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL
};

LogMessage::LogMessage(const char* file, int line, LogSeverity severity, int error)
: file_(file), line_number_(line), severity_(severity), errno_(error)
{
}

void LogMessage::LogLine(const char* line) {
  int priority = kLogSeverityToAndroidLogPriority[severity_];
  LOG_PRI(priority, LOG_TAG, "%s", line);
}

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

#include "logging.h"

#include <iostream>
#include <unistd.h>

#include "cutils/log.h"

static const int kLogSeverityToAndroidLogPriority[] = {
  ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL
};

LogMessage::LogMessage(const char* file, int line, LogSeverity severity, int error)
: file_(file), line_number_(line), severity_(severity), errno_(error)
{
  const char* last_slash = strrchr(file, '/');
  file_ = (last_slash == NULL) ? file : last_slash + 1;
}

void LogMessage::LogLine(const char* line) {
  int priority = kLogSeverityToAndroidLogPriority[severity_];
  LOG_PRI(priority, LOG_TAG, "%s:%d] %s", file_, line_number_, line);
}

Make our CHECK logging more useful on the target...


/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include <QtGui/QApplication>

#include "loop.h"

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

    setenv("KSCREEN_BACKEND", "XRandR", 1);

    Loop *loop = new Loop(0);
    loop->printConfig();
    app.exec();
}

/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include <stdlib.h>

#include <QtGui/QApplication>

#include "loop.h"

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

    setenv("KSCREEN_BACKEND", "XRandR", 1);

    Loop *loop = new Loop(0);
    loop->printConfig();
    app.exec();
}

Include stdlib (getenv and setenv)


#include "sampling.h"

namespace {

static constexpr float M_2PI = 2.f * M_PI;

}

namespace sampling {

__thread static xorshift64star<float> uniform{4};

std::pair<Vec, float> hemisphere() {
    // draw coordinates
    float u1 = uniform();
    float u2 = uniform();

    // u1 is cos(theta)
    auto z = u1;
    auto r = sqrtf(fmax(0.f, 1.f - z*z));
    auto phi = M_2PI * u2;
    auto x = r * cosf(phi);
    auto y = r * sinf(phi);
    return std::make_pair(Vec{x, y, z}, u1);
}

/**
 * Sample a point on the triangle.
 *
 * return point in world space.
 */
Vec triangle(const Triangle& triangle) {
    while(true) {
        float r1 = uniform();
        float r2 = uniform();

        if ((r1 + r2) <= 1.f) {
            return triangle.vertices[0] + r1 * triangle.u + r2 * triangle.v;
        }
    }
}

}

#include "sampling.h"

namespace {

static constexpr float M_2PI = 2.f * M_PI;

__thread static xorshift64star<float> uniform{4};
}

namespace sampling {

std::pair<Vec, float> hemisphere() {
    // draw coordinates
    float u1 = uniform();
    float u2 = uniform();

    // u1 is cos(theta)
    auto z = u1;
    auto r = sqrtf(fmax(0.f, 1.f - z*z));
    auto phi = M_2PI * u2;
    auto x = r * cosf(phi);
    auto y = r * sinf(phi);
    return std::make_pair(Vec{x, y, z}, u1);
}

/**
 * Sample a point on the triangle.
 *
 * return point in world space.
 */
Vec triangle(const Triangle& triangle) {
    while(true) {
        float r1 = uniform();
        float r2 = uniform();

        if ((r1 + r2) <= 1.f) {
            return triangle.vertices[0] + r1 * triangle.u + r2 * triangle.v;
        }
    }
}

}

Move RNG to anonymous namespace.


#include <cppcutter.h>
#include "tuishogi.cpp"

namespace tuishogi {

void
test_isMated(void)
{
  using namespace osl;
  NumEffectState state((SimpleState(HIRATE)));
  bool mated = isMated(state);
  cut_assert_false(mated);
}

}  // namespace tuishogi

#include <cppcutter.h>
#include "tuishogi.cpp"

namespace tuishogi {

void
test_showState(void)
{
  // Arrange
  using namespace osl;
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  const char* expected = "\
P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\
P2 * -HI *  *  *  *  * -KA * \n\
P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\
P4 *  *  *  *  *  *  *  *  * \n\
P5 *  *  *  *  *  *  *  *  * \n\
P6 *  *  *  *  *  *  *  *  * \n\
P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\
P8 * +KA *  *  *  *  * +HI * \n\
P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\
+\n\
\n";

  // Act
  showState(state);

  std::cout << std::flush;
  std::cout.rdbuf(std_out);

  // TODO assert it as a std::string
  std::string str = string_out.str();
  int len = str.length();
  char* actual = new char[len+1];
  memcpy(actual, str.c_str(), len+1);

  // Assert
  cut_assert_equal_string(expected, actual);
}

void
test_isMated(void)
{
  using namespace osl;
  NumEffectState state((SimpleState(HIRATE)));
  bool mated = isMated(state);
  cut_assert_false(mated);
}

}  // namespace tuishogi

Add a test of "showState()"


// RUN: %llvmgxx -S %s -o -

struct QChar {unsigned short X; QChar(unsigned short); } ;

struct Command {
        Command(QChar c) : c(c) {}
        unsigned int type : 4;
        QChar c;
    };

Command X(QChar('c'));

void Foo(QChar );
void bar() { Foo(X.c); }

Make this testcase harder, to test the read case as well.


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

#include "ModelData.hpp"
#include "core/Engine.hpp"
#include "utils/Utils.hpp"

namespace ouzel
{
    namespace scene
    {
        bool ModelData::init(Box3 newBoundingBox,
                             const std::vector<uint32_t> indices,
                             const std::vector<graphics::Vertex>& vertices,
                             const std::shared_ptr<graphics::Material>& newMaterial)
        {
            boundingBox = newBoundingBox;

            indexCount = static_cast<uint32_t>(indices.size());
            indexSize = sizeof(uint32_t);

            indexBuffer = std::make_shared<graphics::Buffer>();
            indexBuffer->init(graphics::Buffer::Usage::INDEX, 0, indices.data(), static_cast<uint32_t>(getVectorSize(indices)));

            vertexBuffer = std::make_shared<graphics::Buffer>();
            vertexBuffer->init(graphics::Buffer::Usage::VERTEX, 0, vertices.data(), static_cast<uint32_t>(getVectorSize(vertices)));

            material = newMaterial;

            return true;
        }
    } // namespace scene
} // namespace ouzel

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

#include "ModelData.hpp"
#include "core/Engine.hpp"
#include "utils/Utils.hpp"

namespace ouzel
{
    namespace scene
    {
        bool ModelData::init(Box3 newBoundingBox,
                             const std::vector<uint32_t> indices,
                             const std::vector<graphics::Vertex>& vertices,
                             const std::shared_ptr<graphics::Material>& newMaterial)
        {
            boundingBox = newBoundingBox;

            indexCount = static_cast<uint32_t>(indices.size());
            indexSize = sizeof(uint32_t);

            indexBuffer = std::make_shared<graphics::Buffer>();
            if (!indexBuffer->init(graphics::Buffer::Usage::INDEX, 0, indices.data(), static_cast<uint32_t>(getVectorSize(indices))))
                return false;

            vertexBuffer = std::make_shared<graphics::Buffer>();
            if (!vertexBuffer->init(graphics::Buffer::Usage::VERTEX, 0, vertices.data(), static_cast<uint32_t>(getVectorSize(vertices))))
                return false;

            material = newMaterial;

            return true;
        }
    } // namespace scene
} // namespace ouzel

Check the result of the init methods


// RUN: %clang_cc1 %s -emit-llvm-only -o -

// https://bugs.llvm.org/show_bug.cgi?id=38356
// We only check that we do not crash.

// ASAN increases stack usage, so we are hitting stack overflow before reaching
// recursive template instantiation limit.
// XFAIL: darwin && asan

template <typename a, a b(unsigned), int c, unsigned...>
struct d : d<a, b, c - 1> {};
template <typename a, a b(unsigned), unsigned... e>
struct d<a, b, 0, e...> {
  a f[0];
};
struct g {
  static g h(unsigned);
};
struct i {
  void j() const;
  // Current maximum depth of recursive template instantiation is 1024,
  // thus, this \/ threshold value is used here. BasePathSize in CastExpr might
  // not fit it, so we are testing that we do fit it.
  // If -ftemplate-depth= is provided, larger values (4096 and up) cause crashes
  // elsewhere.
  d<g, g::h, (1U << 10U) - 2U> f;
};
void i::j() const {
  const void *k{f.f};
  (void)k;
}

// RUN: %clang_cc1 %s -emit-llvm-only -o -

// https://bugs.llvm.org/show_bug.cgi?id=38356
// We only check that we do not crash.

// This test can exceed stack usage in some configurations, so unless we can
// properly handle that don't run it.
// REQUIRES: thread_support

template <typename a, a b(unsigned), int c, unsigned...>
struct d : d<a, b, c - 1> {};
template <typename a, a b(unsigned), unsigned... e>
struct d<a, b, 0, e...> {
  a f[0];
};
struct g {
  static g h(unsigned);
};
struct i {
  void j() const;
  // Current maximum depth of recursive template instantiation is 1024,
  // thus, this \/ threshold value is used here. BasePathSize in CastExpr might
  // not fit it, so we are testing that we do fit it.
  // If -ftemplate-depth= is provided, larger values (4096 and up) cause crashes
  // elsewhere.
  d<g, g::h, (1U << 10U) - 2U> f;
};
void i::j() const {
  const void *k{f.f};
  (void)k;
}

Fix a passing XFAIL test


#include "server.h"

using namespace std;

void thread_loop(UserHandler * handler) {
    while (!handler->isReady()) {
        usleep(10000);
    }
    try {
        handler->loop();
    }
    catch (...) {
        try {
            JsonDict answer;

            JsonString s = JsonString("Unknown error");
            JsonInt i = JsonInt(500);
            answer.add("Error", &s);
            answer.add("code", &i);
            handler->writeToClient("error", &answer);
        }
        catch (...) {}
        cout << "Uncought exception, this is bad !" << endl;
    }
    delete handler;
    cout << "Client disconnected." << endl;
}

#include "server.h"

using namespace std;

void thread_loop(UserHandler * handler) {
    while (!handler->isReady()) {
        usleep(10000);
    }
    try {
        handler->loop();
    }
    catch (...) {
        try {
            JsonDict answer;

            answer.add("Error", new JsonString("Unknown error"));
            answer.add("code", new JsonInt(500));
            handler->writeToClient("error", &answer);
        }
        catch (...) {}
        cout << "Uncought exception, this is bad !" << endl;
    }
    delete handler;
    cout << "Client disconnected." << endl;
}

Fix non head json allocation


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

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

A::A() {}

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

B::B() {}

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

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

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

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

A::A() {}

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

B::B() {}

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

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

Test case B: fixed check rule


/* 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 <csignal>
#include <ncurses.h>
#include <cstdlib>

#include "signals.hh"

extern "C" void myexit(int i) {
    endwin();
    SIG_DFL(i);
}

namespace vick {

void setup_signal_handling() {
    signal(SIGABRT, myexit);
    signal(SIGFPE, myexit);
    signal(SIGILL, myexit);
    signal(SIGINT, myexit);
    signal(SIGSEGV, myexit);
    signal(SIGTERM, myexit);
}
}

/* 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 <csignal>
#include <ncurses.h>
#include <cstdlib>

#include "signals.hh"

extern "C" {
static void myexit(int i) {
    endwin();
    SIG_DFL(i);
}
}

namespace vick {

void setup_signal_handling() {
    signal(SIGABRT, myexit);
    signal(SIGFPE, myexit);
    signal(SIGILL, myexit);
    signal(SIGINT, myexit);
    signal(SIGSEGV, myexit);
    signal(SIGTERM, myexit);
}
}

Use block `extern "C"` so can make function `static`


// RUN: CINDEXTEST_EDITING=1 LIBCLANG_DISABLE_CRASH_RECOVERY=1 c-index-test -test-load-source-reparse 2 none -remap-file-0=%S/Inputs/reparse-issue.h,%S/Inputs/reparse-issue.h-0 -remap-file-1=%S/Inputs/reparse-issue.h,%S/Inputs/reparse-issue.h-1 -- %s 2>&1 | FileCheck %s
#include "Inputs/reparse-issue.h"

// CHECK: reparse-issue.h:4:1:{1:1-1:1}: error: C++ requires a type specifier for all declarations

// RUN: env CINDEXTEST_EDITING=1 LIBCLANG_DISABLE_CRASH_RECOVERY=1 c-index-test -test-load-source-reparse 2 none -remap-file-0=%S/Inputs/reparse-issue.h,%S/Inputs/reparse-issue.h-0 -remap-file-1=%S/Inputs/reparse-issue.h,%S/Inputs/reparse-issue.h-1 -- %s 2>&1 | FileCheck %s
#include "Inputs/reparse-issue.h"

// CHECK: reparse-issue.h:4:1:{1:1-1:1}: error: C++ requires a type specifier for all declarations

Add missing "env" so that test added in r327322 passes on Windows bots.


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

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

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

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

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

// This test is disabled. See bug 25746
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

Disable ExtensionApiTest.Storage because it crashes the browser_tests too.


#include <stdio.h>
#include <string.h> /* memcpy() */
#include <stdlib.h> /* rand() */

#include "quick.hpp"
#include "swap.hpp"

void quick(int *data, const int size_of_data)
{
    return quick(data, 0, size_of_data - 1);
}

void quick(int *data, const int start, const int end)
{
    int size = end - start + 1;
    if(size <= 1) return; /* Base case */

    /* Conquer */
    int pivot = end; /* Set pivot */

    int ps = start, pe = end - 1;
    while(ps < pe)
    {
        while(ps < pe && data[ps] < data[pivot]) ++ps;
        while(ps < pe && data[pe] >= data[pivot]) --pe;

        if(ps < pe) swap(data[ps], data[pe]);
    }

    if(data[pe] > data[pivot]) swap(data[pe], data[pivot]);

    /* Divide */
    quick(data, start, pe);
    quick(data, pe + 1, end);
}

#include <stdio.h>
#include <string.h> /* memcpy() */
#include <stdlib.h> /* rand() */

#include "quick.hpp"
#include "swap.hpp"

void quick(int *data, const int size_of_data)
{
    return quick(data, 0, size_of_data - 1);
}

void quick(int *data, const int start, const int end)
{
    if(start >= end) return; /* Base case */

    /* Conquer */
    int pivot = end; /* Set pivot */

    int ps = start, pe = end - 1;
    while(ps < pe)
    {
        while(ps < pe && data[ps] < data[pivot]) ++ps;
        while(ps < pe && data[pe] >= data[pivot]) --pe;

        if(ps < pe) swap(data[ps], data[pe]);
    }

    if(data[pe] > data[pivot]) swap(data[pe], data[pivot]);

    /* Divide */
    quick(data, start, pe);
    quick(data, pe + 1, end);
}

Remove variable 'size' (not used)


#include <botan/botan.h>
#include <botan/ecdsa.h>

#include <memory>
#include <iostream>

using namespace Botan;

int main()
   {
   try
      {
      std::auto_ptr<RandomNumberGenerator> rng(
         RandomNumberGenerator::make_rng());

      EC_Domain_Params params = get_EC_Dom_Pars_by_oid("1.3.132.8");

      std::cout << params.get_curve().get_p() << "\n";
      std::cout << params.get_order() << "\n";

      ECDSA_PrivateKey ecdsa(*rng, params);
      }
   catch(std::exception& e)
      {
      std::cout << e.what() << "\n";
      }
   }

#include <botan/botan.h>
#include <botan/ecdsa.h>

#include <memory>
#include <iostream>

using namespace Botan;

int main()
   {
   try
      {
      std::auto_ptr<RandomNumberGenerator> rng(
         RandomNumberGenerator::make_rng());

      EC_Domain_Params params = get_EC_Dom_Pars_by_oid("1.3.132.0.8");

      std::cout << params.get_curve().get_p() << "\n";
      std::cout << params.get_order() << "\n";

      ECDSA_PrivateKey ecdsa(*rng, params);
      }
   catch(std::exception& e)
      {
      std::cout << e.what() << "\n";
      }
   }

Correct OID for ECDSA param


Add more hardcoded puzzles and a TODO.


// Copyright (c) 2016 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 "wallet/test/wallet_test_fixture.h"

#include "rpc/server.h"
#include "wallet/db.h"
#include "wallet/wallet.h"

WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
    TestingSetup(chainName)
{
    bitdb.MakeMock();

    bool fFirstRun;
    pwalletMain = new CWallet("wallet_test.dat");
    pwalletMain->LoadWallet(fFirstRun);
    RegisterValidationInterface(pwalletMain);

    RegisterWalletRPCCommands(tableRPC);
}

WalletTestingSetup::~WalletTestingSetup()
{
    UnregisterValidationInterface(pwalletMain);
    delete pwalletMain;
    pwalletMain = NULL;

    bitdb.Flush(true);
    bitdb.Reset();
}

Add copyright header to wallet_text_fixture.cpp


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

#include <folly/executors/GlobalExecutor.h>

#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include <folly/portability/GTest.h>
#include <folly/synchronization/Baton.h>
#include <folly/system/HardwareConcurrency.h>

using namespace folly;

DECLARE_uint32(folly_global_cpu_executor_threads);

TEST(GlobalCPUExecutorTest, CPUThreadCountFlagSet) {
  gflags::FlagSaver flagsaver;

  FLAGS_folly_global_cpu_executor_threads = 100;
  auto cpu_threadpool = dynamic_cast<folly::CPUThreadPoolExecutor*>(
      folly::getGlobalCPUExecutor().get());

  EXPECT_EQ(cpu_threadpool->numThreads(), 100);
}

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

#include <folly/executors/GlobalExecutor.h>

#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include <folly/portability/GTest.h>
#include <folly/synchronization/Baton.h>

DECLARE_uint32(folly_global_cpu_executor_threads);

TEST(GlobalCPUExecutorTest, CPUThreadCountFlagSet) {
  gflags::FlagSaver flagsaver;

  FLAGS_folly_global_cpu_executor_threads = 100;
  auto cpu_threadpool = dynamic_cast<folly::CPUThreadPoolExecutor*>(
      folly::getGlobalCPUExecutor().get());

  EXPECT_EQ(cpu_threadpool->numThreads(), 100);
}

Remove dead includes in folly/executors


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

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

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) {
  ASSERT_TRUE(RunExtensionTest("cookies")) << message_;
}

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

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

#if defined(OS_LINUX)
// See http://crbug.com/42943.
#define MAYBE_Storage FLAKY_Storage
#else
#define MAYBE_Storage Storage
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) {
  ASSERT_TRUE(RunExtensionTest("cookies")) << message_;
}

Mark ExtensionApiTest.Storage as flaky. BUG=42943 TEST=none TBR=rafaelw


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

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

#if defined(OS_WIN)
// Always fails on Windows after r110181: http://crbug.com/104419.
#define MAYBE_Storage FAILS_Storage
#else
#define MAYBE_Storage Storage
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

Mark ExtensionApiTest.Storage as failing, it always fails on Windows after r110181.


/*
 * Copyright Regents of the University of Minnesota, 2016.  This software is released under the following license: http://opensource.org/licenses/
 * Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
 *
 * Code author(s):
 * 		Dan Orban (dtorban)
 */

#include <display/graphics/VRGraphicsWindowNode.h>

namespace MinVR {

VRGraphicsWindowNode::~VRGraphicsWindowNode() {
}

void VRGraphicsWindowNode::render() {
	startRender();
	waitForRenderComplete();
	synchronize();
}

void VRGraphicsWindowNode::startRender() {
	setCurrentContext();
	//TODO: load data
	VRDisplayNode::render();
	flush();
}

void VRGraphicsWindowNode::waitForRenderComplete() {
	finish();
}

void VRGraphicsWindowNode::synchronize() {
	swapBuffers();
}

void VRGraphicsWindowNode::addChild(VRGraphicsWindowChild* child) {
	VRDisplayNode::addChild(child);
}

} /* namespace MinVR */

/*
 * Copyright Regents of the University of Minnesota, 2016.  This software is released under the following license: http://opensource.org/licenses/
 * Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
 *
 * Code author(s):
 * 		Dan Orban (dtorban)
 */

#include <display/graphics/VRGraphicsWindowNode.h>

namespace MinVR {

VRGraphicsWindowNode::~VRGraphicsWindowNode() {
}

void VRGraphicsWindowNode::render() {
	startRender();
	waitForRenderComplete();
	synchronize();
}

void VRGraphicsWindowNode::startRender() {
	setCurrentContext();
	//TODO: load data
	VRDisplayNode::render();
	flush();
}

void VRGraphicsWindowNode::waitForRenderComplete() {
	finish();
}

void VRGraphicsWindowNode::synchronize() {
	swapBuffers();
	clearCurrentContext();
}

void VRGraphicsWindowNode::addChild(VRGraphicsWindowChild* child) {
	VRDisplayNode::addChild(child);
}

} /* namespace MinVR */

Clear current context for window.


#include <iostream>
using namespace std;
struct node {
  int val = 0;
  node * l = nullptr;
  node * r = nullptr;
};
inline node* build(node *head, int value){
  node *son = new node;
  son->val = value;
  if (head == nullptr) return son;
  node * aux = head, * nxt = head;
  while(nxt != nullptr){
    aux = nxt;
    if (value > nxt->val) nxt = nxt->r;
      else nxt = nxt->l;
  }
  if(value > aux-> val) aux->r = son;
  else aux->l = son;
  return head;
}
inline void show(node* head){
  if (head==nullptr) return;
  show(head->l);
  cout << head->val << endl;
  show(head->r);
}
int main(){
  node *head = new node;
  head->val = 5;
  head = build(head, 45);
  head = build(head, 20);
  show(head);
  return 0;
}

#include <bits/stdc++.h>
using namespace std;
struct node{
	int val;
	node *left;
	node *right;
	node( int v ){
		val = v;
		left = nullptr;
		right = nullptr;
	}
	node* insert(node *n, int val){
		if(n == nullptr ) return new node(val);
		if(n->val > val) n->left = insert(n->left, val);
		else n->right = insert(n->right, val);
	}
	void show(node *n){
		if(n!=nullptr){
			show(n->left);
			cout << n->val << " ";
			show(n->right);
		}
	}
	string gHash(node *n) {
	 	string hash="";
	 	if(n->right!=nullptr)
	 		hash += "R"+gHash(n->right);
		if(n->left!=nullptr)
	 		hash += "L"+gHash(n->left);
		return hash+"!";
	 }
};

int main(){
	node * root = new node(7);
	root->insert(root,1);
	root->insert(root,-1);
	root->show(root);

	cout << endl<<root->gHash(root) <<endl;
	return 0;
}

Create useful binary tree, add some assets.


#include <gloperate/input/AbstractEventProvider.h>

#include <gloperate/input/AbstractEvent.h>
#include <gloperate/navigation/AbstractMapping.h>

namespace gloperate
{

AbstractEventProvider::AbstractEventProvider()
{
}

AbstractEventProvider::~AbstractEventProvider()
{
    for (AbstractMapping * mapping : m_mappings)
    {
        mapping->removeProvider(this);
    }
}

void AbstractEventProvider::registerMapping(AbstractMapping * mapping)
{
    m_mappings.push_back(mapping);
}

void AbstractEventProvider::deregisterMapping(AbstractMapping * mapping)
{
    m_mappings.remove(mapping);
}

void AbstractEventProvider::passEvent(AbstractEvent * event)
{
    for (AbstractMapping * mapping : m_mappings)
    {
        mapping->processEvent(event);
    }
}

} // namespace gloperate

#include <gloperate/input/AbstractEventProvider.h>

#include <gloperate/input/AbstractEvent.h>
#include <gloperate/navigation/AbstractMapping.h>

namespace gloperate
{

AbstractEventProvider::AbstractEventProvider()
{
}

AbstractEventProvider::~AbstractEventProvider()
{
    // Unregister from mappings

    // Note: removeProvider calls registerMapping in turn, which removes the mapping
    // from m_mappings. Therefore, a for-loop would get into trouble, so we iterate
    // like this until the list is empty.

    while (!m_mappings.empty()) {
        AbstractMapping * mapping = m_mappings.front();
        mapping->removeProvider(this);
    }
}

void AbstractEventProvider::registerMapping(AbstractMapping * mapping)
{
    m_mappings.push_back(mapping);
}

void AbstractEventProvider::deregisterMapping(AbstractMapping * mapping)
{
    m_mappings.remove(mapping);
}

void AbstractEventProvider::passEvent(AbstractEvent * event)
{
    for (AbstractMapping * mapping : m_mappings)
    {
        mapping->processEvent(event);
    }
}

} // namespace gloperate

Fix crash on shutdown caused by a dependency loop