#include "codearea.h"

#include <algorithm>

namespace openlocationcode {

const double kLatitudeMaxDegrees = 90;
const double kLongitudeMaxDegrees = 180;

CodeArea::CodeArea(double latitude_lo, double longitude_lo, double latitude_hi,
                   double longitude_hi, size_t code_length) {
  latitude_lo_ = latitude_lo;
  longitude_lo_ = longitude_lo;
  latitude_hi_ = latitude_hi;
  longitude_hi_ = longitude_hi;
  code_length_ = code_length;
}

double CodeArea::GetLatitudeLo() const{
  return latitude_lo_;
}

double CodeArea::GetLongitudeLo() const {
  return longitude_lo_;
}

double CodeArea::GetLatitudeHi() const {
  return latitude_hi_;
}

double CodeArea::GetLongitudeHi() const {
  return longitude_hi_;
}

size_t CodeArea::GetCodeLength() const { return code_length_; }

LatLng CodeArea::GetCenter() const {
  double latitude_center = std::min(latitude_lo_ + (latitude_hi_ - latitude_lo_) / 2, kLatitudeMaxDegrees);
  double longitude_center = std::min(longitude_lo_ + (longitude_hi_ - longitude_lo_) / 2, kLongitudeMaxDegrees);
  LatLng center = {latitude: latitude_center, longitude: longitude_center};
  return center;
}

} // namespace openlocationcode

#include "codearea.h"

#include <algorithm>

namespace openlocationcode {

const double kLatitudeMaxDegrees = 90;
const double kLongitudeMaxDegrees = 180;

CodeArea::CodeArea(double latitude_lo, double longitude_lo, double latitude_hi,
                   double longitude_hi, size_t code_length) {
  latitude_lo_ = latitude_lo;
  longitude_lo_ = longitude_lo;
  latitude_hi_ = latitude_hi;
  longitude_hi_ = longitude_hi;
  code_length_ = code_length;
}

double CodeArea::GetLatitudeLo() const{
  return latitude_lo_;
}

double CodeArea::GetLongitudeLo() const {
  return longitude_lo_;
}

double CodeArea::GetLatitudeHi() const {
  return latitude_hi_;
}

double CodeArea::GetLongitudeHi() const {
  return longitude_hi_;
}

size_t CodeArea::GetCodeLength() const { return code_length_; }

LatLng CodeArea::GetCenter() const {
  double latitude_center = std::min(latitude_lo_ + (latitude_hi_ - latitude_lo_) / 2, kLatitudeMaxDegrees);
  double longitude_center = std::min(longitude_lo_ + (longitude_hi_ - longitude_lo_) / 2, kLongitudeMaxDegrees);
  LatLng center{latitude_center, longitude_center};
  return center;
}

} // namespace openlocationcode

Fix warning in open location code library


#include <gmi_mesh.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfConvert.h>
#include <apf.h>
#include <PCU.h>

int main(int argc, char** argv)
{
  assert(argc==3);
  MPI_Init(&argc,&argv);
  PCU_Comm_Init();
  PCU_Protect();
  gmi_register_mesh();
  gmi_register_null();
  int* conn;
  int nelem;
  int etype;
  apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
  int dim = m->getDimension();
  destruct(m, conn, nelem, etype);
  m->destroyNative();
  apf::destroyMesh(m);
  gmi_model* model = gmi_load(".null");
  m = apf::makeEmptyMdsMesh(model, dim, false);
  apf::GlobalToVert outMap;
  apf::construct(m, conn, nelem, etype, outMap);
  outMap.clear();
  delete [] conn;
  apf::alignMdsRemotes(m);
  apf::deriveMdsModel(m);
  m->verify();
  m->destroyNative();
  apf::destroyMesh(m);
  PCU_Comm_Free();
  MPI_Finalize();
}

#include <gmi_mesh.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfConvert.h>
#include <apf.h>
#include <PCU.h>

int main(int argc, char** argv)
{
  assert(argc==3);
  MPI_Init(&argc,&argv);
  PCU_Comm_Init();
  PCU_Protect();
  gmi_register_mesh();
  gmi_register_null();
  int* conn;
  double* coords;
  int nelem;
  int etype;
  int nverts;

  apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);
  int dim = m->getDimension();
  extractCoords(m, coords, nverts);
  destruct(m, conn, nelem, etype);
  m->destroyNative();
  apf::destroyMesh(m);

  gmi_model* model = gmi_load(".null");
  m = apf::makeEmptyMdsMesh(model, dim, false);
  apf::GlobalToVert outMap;
  apf::construct(m, conn, nelem, etype, outMap);
  delete [] conn;
  apf::alignMdsRemotes(m);
  apf::deriveMdsModel(m);
  apf::setCoords(m, coords, nverts, outMap);
  delete [] coords;
  outMap.clear();
  m->verify();

  //apf::writeVtkFiles("after", m);

  m->destroyNative();
  apf::destroyMesh(m);
  PCU_Comm_Free();
  MPI_Finalize();
}

Add test for setting coordinates


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

#include "base/test_file_util.h"

#include "base/logging.h"

namespace file_util {

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

}  // namespace file_util

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

#include "base/test_file_util.h"

#include "base/logging.h"

namespace file_util {

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

}  // namespace file_util

Change the stub for file_util::EvictFileFromSystemCache


#include <gtest/gtest.h>

#include "../src/awg.hpp"

#include "../src/pulseTrain.hpp"

class AWGConstructors : public ::testing::Test {
	protected:
};

class AWGAcessors : public ::testing::Test {
	protected:
};

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

#include <gtest/gtest.h>

#include "../src/awg.hpp"

#include "../src/pulseTrain.hpp"

TEST(AwgClass, ComPort) {
	awg testAwg;

	EXPECT_EQ(std::string("COM1"),testAwg.comPort());

	testAwg.comPort(2);
	EXPECT_EQ(std::string("COM2"),testAwg.comPort());

	testAwg.comPort("com1");
	EXPECT_EQ(std::string("com1"),testAwg.comPort());
}

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

Test the COM Port assignments in the AWG class


#include <unordered_map>
#include <mutex>

#include "../os.h"
#include "test_lib.h"
#include "../../../intercom-cpp/src/cominterop.h"
#include "../../../intercom-cpp/src/activator.h"

using intercom::Activator;

void InitializeRuntime()
{
}

void UninitializeRuntime()
{
}

intercom::HRESULT CreateInstance( intercom::REFCLSID clsid, intercom::REFIID iid, void** pout )
{
    Activator activate( test_lib::Descriptor::NAME, clsid );
    activate.create( iid, pout );

    return S_OK;
}

#include <unordered_map>
#include <mutex>

#include "../os.h"
#include "test_lib.h"
#include "../../../intercom-cpp/src/cominterop.h"
#include "../../../intercom-cpp/src/activator.h"

using intercom::Activator;

void InitializeRuntime()
{
}

void UninitializeRuntime()
{
}

intercom::HRESULT CreateInstance( intercom::REFCLSID clsid, intercom::REFIID iid, void** pout )
{
    Activator activate( test_lib::Descriptor::NAME, clsid );
    return activate.create( iid, pout );
}

Fix return value in create()


//------------------------------------------------------------------------------
// rewriter.cpp
// Simple tool that parses an input file and writes it back out; used
// for verifying the round-trip nature of the parse tree.
//
// File is under the MIT license; see LICENSE for details
//------------------------------------------------------------------------------

#include <cstdio>
#if defined(_WIN32)
#    include <fcntl.h>
#    include <io.h>
#endif

#include <filesystem>

#include "slang/syntax/SyntaxPrinter.h"
#include "slang/syntax/SyntaxTree.h"

using namespace slang;

int main(int argc, char** argv) try {
    if (argc != 2) {
        fprintf(stderr, "usage: rewriter file");
        return 1;
    }

    // Make sure we reproduce newlines correctly on Windows:
#if defined(_WIN32)
    _setmode(_fileno(stdout), _O_BINARY);
#endif

    if (!std::filesystem::exists(argv[1])) {
        fprintf(stderr, "File does not exist: %s\n", argv[1]);
        return 1;
    }

    if (!std::filesystem::is_regular_file(argv[1])) {
        fprintf(stderr, "%s is not a file\n", argv[1]);
        return 1;
    }

    auto tree = SyntaxTree::fromFile(argv[1]);
    printf("%s", SyntaxPrinter::printFile(*tree).c_str());
    return 0;
}
catch (const std::exception& e) {
    printf("internal compiler error (exception): %s\n", e.what());
    return 2;
}

//------------------------------------------------------------------------------
// rewriter.cpp
// Simple tool that parses an input file and writes it back out; used
// for verifying the round-trip nature of the parse tree.
//
// File is under the MIT license; see LICENSE for details
//------------------------------------------------------------------------------

#include <cstdio>
#if defined(_WIN32)
#    include <fcntl.h>
#    include <io.h>
#endif

#include <filesystem>

#include "slang/syntax/SyntaxPrinter.h"
#include "slang/syntax/SyntaxTree.h"

using namespace slang;

int main(int argc, char** argv) try {
    if (argc != 2) {
        fprintf(stderr, "usage: rewriter file\n");
        return 1;
    }

    // Make sure we reproduce newlines correctly on Windows:
#if defined(_WIN32)
    _setmode(_fileno(stdout), _O_BINARY);
#endif

    if (!std::filesystem::exists(argv[1])) {
        fprintf(stderr, "File does not exist: %s\n", argv[1]);
        return 1;
    }

    if (!std::filesystem::is_regular_file(argv[1])) {
        fprintf(stderr, "%s is not a file\n", argv[1]);
        return 1;
    }

    auto tree = SyntaxTree::fromFile(argv[1]);
    printf("%s", SyntaxPrinter::printFile(*tree).c_str());
    return 0;
}
catch (const std::exception& e) {
    printf("internal compiler error (exception): %s\n", e.what());
    return 2;
}

Print newline in usage in rewrite


/*
    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) 2013  David Edmundson <D.Edmundson@lboro.ac.uk>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "person-plugin-manager.h"

#include <QAction>

#include "abstract-person-plugin.h"

PersonPluginManager::PersonPluginManager(QObject* parent): QObject(parent)
{

}

PersonPluginManager::~PersonPluginManager()
{
    qDeleteAll(m_plugins);
}

QList<QAction*> PersonPluginManager::actionsForPerson(PersonData* person, QObject* parent)
{
    QList<QAction*> actions;
    Q_FOREACH(AbstractPersonPlugin *plugin, m_plugins) {
        actions << plugin->actionsForPerson(person, parent);
    }
    return actions;
}

/*
    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) 2013  David Edmundson <D.Edmundson@lboro.ac.uk>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "person-plugin-manager.h"

#include <QAction>

#include "abstract-person-plugin.h"

#include "plugins/im-plugin.h"
#include "plugins/email-plugin.h"

PersonPluginManager::PersonPluginManager(QObject* parent): QObject(parent)
{
    m_plugins << new IMPlugin(this);
    m_plugins << new EmailPlugin(this);
}

PersonPluginManager::~PersonPluginManager()
{
    qDeleteAll(m_plugins);
}

QList<QAction*> PersonPluginManager::actionsForPerson(PersonData* person, QObject* parent)
{
    QList<QAction*> actions;
    Q_FOREACH(AbstractPersonPlugin *plugin, m_plugins) {
        actions << plugin->actionsForPerson(person, parent);
    }
    return actions;
}

Use the new actions plugins


#define CATCH_CONFIG_MAIN
#include "./catch.hpp"

#define CATCH_CONFIG_RUNNER
#include "./catch.hpp"
#include "./ReQL.hpp"

int
main(int argc, char **argv) {
  int result = Catch::Session().run(argc, argv);

  ReQL::Connection conn;

  ReQL::wait({})
  .funcall({
    ReQL::func({
      1.0,
      ReQL::db({std::string("rethinkdb")})
      .table({std::string("db_config")})
      .delete_({})
    })
  }).run(conn).toVector().clear();

  conn.close();

  return result;
}

Add cleanup to the entire database on test exit.


#include "FortWrap.h"
#include <algorithm> 		// For count
#include <iostream>

int main(void)
{

  // Set up v = [1,2,3,4]
  std::vector<int> v(4);
  for (int i=0; i<v.size(); i++)
    v[i] = i+1;

  if (FortFuncs::array_in(&v)  != 10)
    return 1;

  std::vector<int> v2(10);
  FortFuncs::array_out(&v,&v2);
  if ((int) count(v.begin(), v.end(), 20) != v.size())
    return 2;
  else if ((int) count(v2.begin(), v2.end(), 30) != v2.size())
    return 3;

  std::vector<int> a(3), b(3);
  for (int i=0; i<a.size(); i++)
    {
      a[i] = i;
      b[i] = i+1;
    }
  if (FortFuncs::inner_prod(&a,&b) != 8)
    return 4;

  // Test assumed size
  if (FortFuncs::inner_prod(&a,&b) != 8)
    return 5;

  return 0;
}

#include "FortWrap.h"
#include <algorithm> 		// For count
#include <iostream>

int main(void)
{

  // Set up v = [1,2,3,4]
  std::vector<int> v(4);
  for (int i=0; i<v.size(); i++)
    v[i] = i+1;

  if (FortFuncs::array_in(&v)  != 10)
    return 1;

  std::vector<int> v2(10);
  FortFuncs::array_out(&v,&v2);
  if ((int) count(v.begin(), v.end(), 20) != v.size())
    return 2;
  else if ((int) count(v2.begin(), v2.end(), 30) != v2.size())
    return 3;

  std::vector<int> a(3), b(3);
  for (int i=0; i<a.size(); i++)
    {
      a[i] = i;
      b[i] = i+1;
    }
  if (FortFuncs::inner_prod(&a,&b) != 8)
    return 4;

  // Test assumed size
  if (FortFuncs::inner_prod_2(3,&a,&b) != 8)
    return 5;

  return 0;
}

Test wasn't referring to the correct routine.


#include "MessageBuilder.hpp"

#include "common/LinkParser.hpp"
#include "singletons/Emotes.hpp"
#include "singletons/Resources.hpp"
#include "singletons/Theme.hpp"

#include <QDateTime>

namespace chatterino {

MessageBuilder::MessageBuilder()
    : message(new Message)
{
}

MessagePtr MessageBuilder::getMessage()
{
    return this->message;
}

void MessageBuilder::append(MessageElement *element)
{
    this->message->addElement(element);
}

void MessageBuilder::appendTimestamp()
{
    this->appendTimestamp(QTime::currentTime());
}

void MessageBuilder::setHighlight(bool value)
{
    if (value) {
        this->message->flags |= Message::Highlighted;
    } else {
        this->message->flags &= ~Message::Highlighted;
    }
}

void MessageBuilder::appendTimestamp(const QTime &time)
{
    this->append(new TimestampElement(time));
}

QString MessageBuilder::matchLink(const QString &string)
{
    LinkParser linkParser(string);

    static QRegularExpression httpRegex("\\bhttps?://");
    static QRegularExpression ftpRegex("\\bftps?://");

    if (!linkParser.hasMatch()) {
        return QString();
    }

    QString captured = linkParser.getCaptured();

    if (!captured.contains(httpRegex)) {
        if (!captured.contains(ftpRegex)) {
            captured.insert(0, "http://");
        }
    }

    return captured;
}

}  // namespace chatterino

#include "MessageBuilder.hpp"

#include "common/LinkParser.hpp"
#include "singletons/Emotes.hpp"
#include "singletons/Resources.hpp"
#include "singletons/Theme.hpp"

#include <QDateTime>

namespace chatterino {

MessageBuilder::MessageBuilder()
    : message(new Message)
{
}

MessagePtr MessageBuilder::getMessage()
{
    return this->message;
}

void MessageBuilder::append(MessageElement *element)
{
    this->message->addElement(element);
}

void MessageBuilder::appendTimestamp()
{
    this->appendTimestamp(QTime::currentTime());
}

void MessageBuilder::setHighlight(bool value)
{
    if (value) {
        this->message->flags |= Message::Highlighted;
    } else {
        this->message->flags &= ~Message::Highlighted;
    }
}

void MessageBuilder::appendTimestamp(const QTime &time)
{
    this->append(new TimestampElement(time));
}

QString MessageBuilder::matchLink(const QString &string)
{
    LinkParser linkParser(string);

    static QRegularExpression httpRegex("\\bhttps?://", QRegularExpression::CaseInsensitiveOption);
    static QRegularExpression ftpRegex("\\bftps?://", QRegularExpression::CaseInsensitiveOption);

    if (!linkParser.hasMatch()) {
        return QString();
    }

    QString captured = linkParser.getCaptured();

    if (!captured.contains(httpRegex)) {
        if (!captured.contains(ftpRegex)) {
            captured.insert(0, "http://");
        }
    }

    return captured;
}

}  // namespace chatterino

Make protocol regexes case insensitive


#include "stdafx.h"
#include <dukat/animationmanager.h>

namespace dukat
{
	Animation* AnimationManager::add(std::unique_ptr<Animation> animation)
	{
		auto anim = animation.get();
		animations.push_back(std::move(animation));
		if (!anim->is_running())
		{
			anim->start();
		}
		return anim;
	}

	void AnimationManager::cancel(Animation* animation)
	{
		auto it = std::find_if(animations.begin(), animations.end(), [animation](const std::unique_ptr<Animation>& anim) {
			return animation == anim.get();
		});
		if (it != animations.end())
			(*it)->stop(); // don't erase here - update will take care of that
	}

	void AnimationManager::update(float delta)
	{
		for (auto it = animations.begin(); it != animations.end(); )
		{
			(*it)->step(delta);
			if ((*it)->is_done())
			{
				it = animations.erase(it);
			}
			else
			{
				++it;
			}
		}
	}
}

#include "stdafx.h"
#include <dukat/animationmanager.h>

namespace dukat
{
	Animation* AnimationManager::add(std::unique_ptr<Animation> animation)
	{
		auto anim = animation.get();
		animations.push_back(std::move(animation));
		if (!anim->is_running())
		{
			anim->start();
		}
		return anim;
	}

	void AnimationManager::cancel(Animation* animation)
	{
		auto it = std::find_if(animations.begin(), animations.end(), [animation](const std::unique_ptr<Animation>& anim) {
			return animation == anim.get();
		});
		if (it != animations.end())
			(*it)->stop(); // don't erase here - update will take care of that
	}

	void AnimationManager::update(float delta)
	{
		for (auto it = animations.begin(); it != animations.end(); )
		{
			if ((*it)->is_done())
			{
				it = animations.erase(it);
			}
			else
			{
				(*it)->step(delta);
				++it;
			}
		}
	}
}

Fix order of animation update


#include "game.h"

#include "button.h"
#include "screen.h"
#include "led.h"
#include "timer.h"
#include "const.h"
#include "logger.h"
#include "helper.h"
#include "controller.h"

namespace game {
  namespace {
    const unsigned long GAME_TIME = 3000;

    unsigned long endTime;

    unsigned int buttonsPressed = 0;

    void countDown() {
      screen::display("3");
      helper::waitTime(1000);
      screen::display("2");
      helper::waitTime(1000);
      screen::display("1");
      helper::waitTime(1000);
    }

    void runMain() {
      while (millis() < endTime) {

        //Generate random button
        int buttonNumber = random(0, constants::NUMBER_OF_LEDS - 1);

        //Turn on led and wait for button press
        led::turnOn(buttonNumber);

        while(not button::isPressed(buttonNumber)){
          controller::run();
        }

        led::turnOff(buttonNumber);

        //Increment counter
        buttonsPressed ++;
      }
    }
  }

  unsigned long getRemainingTime() {
    unsigned long remainingTime = endTime - millis();

    if (remainingTime > 0) {
      return remainingTime;
    }

    return 0;
  }

  void start() {
    countDown();

    endTime = GAME_TIME + millis();

    timer::start();
    runMain();
    timer::stop();

    screen::display(String(buttonsPressed) + " buttons pressed");
  }
}

#include "game.h"

#include "button.h"
#include "screen.h"
#include "led.h"
#include "timer.h"
#include "const.h"
#include "logger.h"
#include "helper.h"
#include "controller.h"

namespace game {
  namespace {
    const unsigned long GAME_TIME = 3000;

    unsigned long endTime;

    unsigned int buttonsPressed = 0;

    void countDown() {
      screen::display("3");
      helper::waitTime(1000);
      screen::display("2");
      helper::waitTime(1000);
      screen::display("1");
      helper::waitTime(1000);
    }

    void runMain() {
      while (millis() < endTime) {

        //Generate random button
        int buttonNumber = random(0, constants::NUMBER_OF_LEDS - 1);

        //Turn on led and wait for button press
        led::turnOn(buttonNumber);

        while(not button::isPressed(buttonNumber) and millis() < endTime){
          controller::run();
        }

        if (millis() < endTime){
          buttonsPressed ++; //Increment counter
        }

        led::turnOff(buttonNumber);
      }
    }
  }

  unsigned long getRemainingTime() {
    unsigned long remainingTime = endTime - millis();

    if (remainingTime > 0) {
      return remainingTime;
    }

    return 0;
  }

  void start() {
    countDown();

    endTime = GAME_TIME + millis();

    timer::start();
    runMain();
    timer::stop();

    screen::display(String(buttonsPressed) + " buttons pressed");
  }
}

Make button turn off after time ends


#include "YarpStateDirector.hpp"

const int rd::YarpStateDirector::DEFAULT_RATE_MS = 100;

rd::YarpStateDirector::YarpStateDirector(rd::State *state) : StateDirector(state), RateThread(DEFAULT_RATE_MS)
{

}

bool rd::YarpStateDirector::Start()
{
    RD_DEBUG("Starting StateDirector for id %s\n", state->getStateId().c_str());
    active = true;
    state->setup();

    return yarp::os::RateThread::start();
}

bool rd::YarpStateDirector::Stop()
{
    RD_DEBUG("Stopping StateDirector for id %s\n", state->getStateId().c_str());

    active = false;

    yarp::os::RateThread::askToStop();
    yarp::os::RateThread::stop();

    state->cleanup();

    return true;
}

void rd::YarpStateDirector::run()
{
    //RD_DEBUG("Entering loop in StateDirector with id %s\n", state->getStateId().c_str());
    if ( !state->loop() )
    {
        RD_ERROR("Error in loop. Stopping this state...\n");
        this->Stop();
    }
    int condition = state->evaluateConditions();

    if (nextStates.find(condition) != nextStates.end())
    {
        this->Stop();
        nextStates.find(condition)->second->Start();
    }

}

#include "YarpStateDirector.hpp"

const int rd::YarpStateDirector::DEFAULT_RATE_MS = 100;

rd::YarpStateDirector::YarpStateDirector(rd::State *state) : StateDirector(state), RateThread(DEFAULT_RATE_MS)
{

}

bool rd::YarpStateDirector::Start()
{
    RD_DEBUG("Starting StateDirector for id %s\n", state->getStateId().c_str());
    active = true;
    if (!state->setup())
    {
        RD_ERROR("Error in state setup for id %s\n", state->getStateId.c_str());
        return false;
    }

    return yarp::os::RateThread::start();
}

bool rd::YarpStateDirector::Stop()
{
    RD_DEBUG("Stopping StateDirector for id %s\n", state->getStateId().c_str());

    active = false;

    yarp::os::RateThread::askToStop();
    yarp::os::RateThread::stop();

    state->cleanup();

    return true;
}

void rd::YarpStateDirector::run()
{
    //RD_DEBUG("Entering loop in StateDirector with id %s\n", state->getStateId().c_str());
    if ( !state->loop() )
    {
        RD_ERROR("Error in loop. Stopping this state...\n");
        this->Stop();
    }
    int condition = state->evaluateConditions();

    if (nextStates.find(condition) != nextStates.end())
    {
        this->Stop();
        nextStates.find(condition)->second->Start();
    }

}

Check setup return value to stop the FSM if false


/*
 */
#include <synext.hpp>
#include "../parse/common.hpp"

class CExpanderFile:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
    {
        return box$( TTStreamO(TokenTree(Token(TOK_STRING, sp.filename.c_str()))) );
    }
};

class CExpanderLine:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
    {
        return box$( TTStreamO(TokenTree(Token((uint64_t)sp.start_line, CORETYPE_U32))) );
    }
};

STATIC_MACRO("file", CExpanderFile);
STATIC_MACRO("line", CExpanderLine);

/*
 */
#include <synext.hpp>
#include "../parse/common.hpp"

class CExpanderFile:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
    {
        return box$( TTStreamO(TokenTree(Token(TOK_STRING, sp.filename.c_str()))) );
    }
};

class CExpanderLine:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
    {
        return box$( TTStreamO(TokenTree(Token((uint64_t)sp.start_line, CORETYPE_U32))) );
    }
};

class CExpanderModulePath:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
    {
        ::std::string   path_str;
        for(const auto& comp : mod.path().nodes()) {
            if( &comp != &mod.path().nodes().front() )
                path_str += "::";
            path_str += comp.name();
        }
        return box$( TTStreamO(TokenTree( Token(TOK_STRING, mv$(path_str)) )) );
    }
};

STATIC_MACRO("file", CExpanderFile);
STATIC_MACRO("line", CExpanderLine);
STATIC_MACRO("module_path", CExpanderModulePath);

Expand - Implement module_path! macro


#include <cstddef>
#include <string>

// Emulates the standard std::string literal ("..."s) from C++14. Since 's' is
// reserved by the standard, we have to use '_s' instead of 's'.
std::string operator "" _s(const char *str, std::size_t length) {
    return std::string(str, length);
}

int main() {
    std::string s1 = "abc\x00xyz";   // s1 contains "abc"
    std::string s2 = "abc\x00xyz"_s; // s1 contains "abc\x00xyz"
}

#include <cstddef>
#include <string>

// Emulates the standard std::string literal ("..."s) from C++14. Since 's' is
// reserved by the standard, we have to use '_s' instead of 's'.
std::string operator "" _s(const char *str, std::size_t length) {
    return std::string(str, length);
}

int main() {
    std::string s1 = "abc\x00xyz";   // s1 contains "abc"
    std::string s2 = "abc\x00xyz"_s; // s2 contains "abc\x00xyz"
}

Fix a typo in a comment.


// 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/in_process_webkit/webkit_thread.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(WebKitThreadTest, ExposedInChromeThread) {
  int* null = NULL;  // Help the template system out.
  EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null));
  {
    WebKitThread thread;
    EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                          FROM_HERE, null));
    thread.Initialize();
    EXPECT_TRUE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                         FROM_HERE, null));
  }
  EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                        FROM_HERE, null));
}

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

#include "chrome/browser/in_process_webkit/webkit_thread.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(WebKitThreadTest, DISABLED_ExposedInChromeThread) {
  int* null = NULL;  // Help the template system out.
  EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT, FROM_HERE, null));
  {
    WebKitThread thread;
    EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                          FROM_HERE, null));
    thread.Initialize();
    EXPECT_TRUE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                         FROM_HERE, null));
  }
  EXPECT_FALSE(ChromeThread::DeleteSoon(ChromeThread::WEBKIT,
                                        FROM_HERE, null));
}

Disable WebKitThreadTest.ExposedInChromeThread, due to subsequent assert.


#include <stdlib.h>

#include <cppfs/system.h>

namespace cppfs
{
namespace system
{

std::string homeDir()
{
    return std::string(getenv("HOME"));
}

std::string configDir(const std::string & application)
{
#if defined(SYSTEM_WINDOWS)
    return std::string(getenv("APPDATA")) + "\\" + application;
#elif defined(SYSTEM_DARWIN)
    return std::string(getenv("HOME")) + "/Library/Preferences/" + application;
#else
    return std::string(getenv("HOME")) + "/.config/" + application;
#endif
}

} // namespace system
} // namespace cppfs

#include <stdlib.h>

#include <cppfs/system.h>

namespace cppfs
{
namespace system
{

std::string homeDir()
{
#if defined(SYSTEM_WINDOWS)
	return std::string(getenv("HOMEPATH"));
#else
	return std::string(getenv("HOME"));
#endif
}

std::string configDir(const std::string & application)
{
#if defined(SYSTEM_WINDOWS)
    return std::string(getenv("APPDATA")) + "\\" + application;
#elif defined(SYSTEM_DARWIN)
    return std::string(getenv("HOME")) + "/Library/Preferences/" + application;
#else
    return std::string(getenv("HOME")) + "/.config/" + application;
#endif
}

} // namespace system
} // namespace cppfs

Fix runtime error on Windows


#include "Queue.h"
#include "gtest/gtest.h"
/* The Queue data structure
 * Public interface:
 * enqueue()
 * dequeue()
 * size()
 * clear()
 * begin()
 * end() : one pass the last item
 * empty()
 */

class QueueTest : public testing::Test {
 protected:
  // SetUp() & TearDown() are virtual functions from testting::Test,
  // so we just signify that we override them here
  virtual void SetUp() {
    q1_.enqueue(1);
    q1_.enqueue(2);
    q2_.enqueue(1);
    q2_.enqueue(3);
  }

  virtual void TearDown() {
  }

  // setup fixtures
  Queue<int> q0_;
  Queue<int> q1_;
  Queue<int> q2_;
};

// Use TEST_F to test with fixtures.
TEST_F(QueueTest, DefaultConstructor) {
  EXPECT_EQ(0u, q0_.size());
}

TEST_F(QueueTest, Enqueue){
  EXPECT_EQ(2u, q1_.size());
  EXPECT_EQ(2u, q2_.size());
  q2_.enqueue(100);
  EXPECT_EQ(3u, q2_.size());
}

#include "Queue.h"
#include "gtest/gtest.h"
/* The Queue data structure
 * Public interface:
 * enqueue()
 * dequeue()
 * size()
 * clear()
 * begin()
 * end() : one pass the last item
 * empty()
 */

class QueueTest : public testing::Test {
 protected:
  // SetUp() & TearDown() are virtual functions from testting::Test,
  // so we just signify that we override them here
  virtual void SetUp() {
    q1_.enqueue(1);
    q1_.enqueue(2);
    q2_.enqueue(1);
    q2_.enqueue(3);
  }

  virtual void TearDown() {
  }

  // setup fixtures
  Queue<int> q0_;
  Queue<int> q1_;
  Queue<int> q2_;
};

// Use TEST_F to test with fixtures.
TEST_F(QueueTest, DefaultConstructor) {
  EXPECT_EQ(0u, q0_.size());
}

TEST_F(QueueTest, enqueue){
  EXPECT_EQ(2u, q1_.size());
  EXPECT_EQ(2u, q2_.size());
  q2_.enqueue(100);
  EXPECT_EQ(3u, q2_.size());
}

TEST_F(QueueTest, clear) {
  q2_.clear();
  EXPECT_TRUE(q2_.empty());
}

TEST_F(QueueTest, dequeue) {
  int* pop_item = q1_.dequeue();
  EXPECT_EQ(*pop_item, 1);
  EXPECT_EQ(q1_.size(), 1);
  delete pop_item;
  pop_item = q1_.dequeue();
  EXPECT_EQ(*pop_item, 2);
  EXPECT_TRUE(q1_.empty());
  // q1_ should be empty now. check it:
  delete pop_item;
  pop_item = q1_.dequeue();
  EXPECT_EQ(nullptr, pop_item);
}

Add tests for the clear() and dequeue() methods.


#include "configuration.hh"

namespace vick {

char QUIT_KEY = 0;
int TAB_SIZE = 1;
void (*PUSH_BACK_CHANGE)(contents&, std::shared_ptr<change>) = 0;
std::string DELIMINATORS = "";

bool use_colors() {return true;}
void init_conf() {}
void add_listeners() {}
void add_commands(
    std::map<std::string,
             std::function<boost::optional<std::shared_ptr<change> >(
                 contents&, boost::optional<int>)> >&) {}

}

#include "configuration.hh"

namespace vick {

char QUIT_KEY = 0;
int TAB_SIZE = 1;
void (*PUSH_BACK_CHANGE)(contents&, std::shared_ptr<change>) = nullptr;
std::string DELIMINATORS = "";

bool use_colors() {return true;}
void init_conf() {}
void add_listeners() {}
void add_commands(
    std::map<std::string,
             std::function<boost::optional<std::shared_ptr<change> >(
                 contents&, boost::optional<int>)> >&) {}

}

Use ``nullptr`` instead of ``0`` or ``NULL``


/*
 * Copyright (C) 2016 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 <cutils/log.h>

#include <stdio.h>
#include <sys/stat.h>

#include <string>
#include <vector>

std::vector<uint8_t> readWholeFile(const std::string& filePath) {
    FILE* fp = fopen(filePath.c_str(), "r");
    LOG_ALWAYS_FATAL_IF(fp == nullptr);
    struct stat st;
    LOG_ALWAYS_FATAL_IF(fstat(fileno(fp), &st) != 0);

    std::vector<uint8_t> result(st.st_size);
    LOG_ALWAYS_FATAL_IF(fread(result.data(), 1, st.st_size, fp) != st.st_size);
    fclose(fp);
    return result;
}

/*
 * Copyright (C) 2016 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 <cutils/log.h>

#include <stdio.h>
#include <sys/stat.h>

#include <string>
#include <vector>

std::vector<uint8_t> readWholeFile(const std::string& filePath) {
    FILE* fp = fopen(filePath.c_str(), "r");
    LOG_ALWAYS_FATAL_IF(fp == nullptr);
    struct stat st;
    LOG_ALWAYS_FATAL_IF(fstat(fileno(fp), &st) != 0);

    std::vector<uint8_t> result(st.st_size);
    LOG_ALWAYS_FATAL_IF(fread(result.data(), 1, st.st_size, fp) != static_cast<size_t>(st.st_size));
    fclose(fp);
    return result;
}

Fix build failure of minikin_perftest


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

// ShaderExecutable9.cpp: Implements a D3D9-specific class to contain shader
// executable implementation details.

#include "libANGLE/renderer/d3d/d3d9/ShaderExecutable9.h"

#include "common/debug.h"

namespace rx
{

ShaderExecutable9::ShaderExecutable9(const void *function, size_t length, IDirect3DPixelShader9 *executable)
    : ShaderExecutableD3D(function, length)
{
    mPixelExecutable = executable;
    mVertexExecutable = NULL;
}

ShaderExecutable9::ShaderExecutable9(const void *function, size_t length, IDirect3DVertexShader9 *executable)
    : ShaderExecutableD3D(function, length)
{
    mVertexExecutable = executable;
    mPixelExecutable = NULL;
}

ShaderExecutable9::~ShaderExecutable9()
{
    SafeRelease(mVertexExecutable);
    SafeRelease(mPixelExecutable);
}

IDirect3DVertexShader9 *ShaderExecutable9::getVertexShader() const
{
    return mVertexExecutable;
}

IDirect3DPixelShader9 *ShaderExecutable9::getPixelShader() const
{
    return mPixelExecutable;
}

}

Add a few missing newlines at eof.


#include "buffers.h"
#include "strutil.h"
#include "log.h"

void processQueue(ByteQueue* queue, bool (*callback)(uint8_t*)) {
    uint8_t snapshot[QUEUE_MAX_LENGTH(uint8_t)];
    queue_snapshot(queue, snapshot);
    if(callback == NULL) {
        debug("Callback is NULL (%p) -- unable to handle queue at %p\r\n",
                callback, queue);
        return;
    }

    if(callback(snapshot)) {
        queue_init(queue);
    } else if(queue_full(queue)) {
        debug("Incoming write is too long");
        queue_init(queue);
    } else if(strnchr((char*)snapshot, queue_length(queue), '\0') != NULL) {
        debug("Incoming buffered write corrupted -- clearing buffer");
        queue_init(queue);
    }
}

#include "buffers.h"
#include "strutil.h"
#include "log.h"

void processQueue(ByteQueue* queue, bool (*callback)(uint8_t*)) {
    uint8_t snapshot[QUEUE_MAX_LENGTH(uint8_t)];
    queue_snapshot(queue, snapshot);
    if(callback == NULL) {
        debug("Callback is NULL (%p) -- unable to handle queue at %p\r\n",
                callback, queue);
        return;
    }

    if(callback(snapshot)) {
        queue_init(queue);
    } else if(queue_full(queue)) {
        debug("Incoming write is too long\r\n");
        queue_init(queue);
    } else if(strnchr((char*)snapshot, queue_length(queue), '\0') != NULL) {
        debug("Incoming buffered write corrupted -- clearing buffer\r\n");
        queue_init(queue);
    }
}

Put newlines after more debug messages.


#include <optimisationProblem/benchmark/sphereFunction.hpp>

#include <cmath>
using std::sqrt;
using std::pow;

#include <armadillo>
using arma::norm;

namespace hop {
  SphereFunction::SphereFunction(const unsigned int &numberOfDimensions) : BenchmarkProblem(numberOfDimensions) {

  }

  double SphereFunction::getObjectiveValueImplementation(const Col<double> &parameter) {
    return pow(norm(getRandomParameterTranslation(parameter)), 2);
  }
}

#include <optimisationProblem/benchmark/sphereFunction.hpp>

#include <cmath>
using std::sqrt;
using std::pow;

#include <armadillo>
using arma::norm;

namespace hop {
  SphereFunction::SphereFunction(const unsigned int &numberOfDimensions) : BenchmarkProblem(numberOfDimensions) {

  }

  double SphereFunction::getObjectiveValueImplementation(const Col<double> &parameter) const {
    return pow(norm(getRandomParameterTranslation(parameter)), 2);
  }
}

Set sphere function's objective value method to be const (missed this one)


#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"

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

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	DataStore sut;

	TEST_METHOD(DataStore_Post_Basic_Test) {
		bool result = sut.post(0, DataStore::STask());
		Assert::IsTrue(result);
	}

	TEST_METHOD(DataStore_Post_DuplicateId_Test) {
		sut.post(0, DataStore::STask());
		bool result = sut.post(0, DataStore::STask());
		Assert::IsFalse(result);
	}

	TEST_METHOD(DataStore_Put_Basic_Test) {
		sut.post(0, DataStore::STask());
		bool result = sut.put(0, DataStore::STask());
		Assert::IsTrue(result);
	}
};
}  // namespace YouDataStoreTests

#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"

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

namespace YouDataStoreTests {

const std::wstring TASK_ID = L"id";
const std::wstring DESCRIPTION = L"desc";
const std::wstring DEADLINE = L"deadl";
const std::wstring PRIORITY = L"pri";
const std::wstring DEPENDENCIES = L"depend";
const DataStore::STask stask = {
		{ TASK_ID, L"0" },
		{ DESCRIPTION, L"bla bla" },
		{ DEADLINE, L"xxxxxx" },
		{ PRIORITY, L"urgent" },
		{ DEPENDENCIES, L"12345" }
};

TEST_CLASS(DataStoreApiTest) {
public:
	DataStore sut;

	TEST_METHOD(DataStore_Post_Basic_Test) {
		bool result = sut.post(0, DataStore::STask());
		Assert::IsTrue(result);
	}

	TEST_METHOD(DataStore_Post_DuplicateId_Test) {
		sut.post(0, DataStore::STask());
		bool result = sut.post(0, DataStore::STask());
		Assert::IsFalse(result);
	}

	TEST_METHOD(DataStore_Put_Basic_Test) {
		sut.post(0, DataStore::STask());
		bool result = sut.put(0, DataStore::STask());
		Assert::IsTrue(result);
	}
};
}  // namespace YouDataStoreTests

Add constants for unit test


// RUN: %clangxx_asan -O0 %s -Fe%t 2>&1
// 'cat' is used below to work around FileCheck buffering bug which makes this
// test flaky.  FIXME: file an issue.
// RUN: not %run %t 2>&1 | cat | FileCheck %s --check-prefix=CHECK

#include <windows.h>

DWORD WINAPI thread_proc(void *context) {
  int subscript = -1;
  volatile char stack_buffer[42];
  stack_buffer[subscript] = 42;
// CHECK: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]]
// CHECK: WRITE of size 1 at [[ADDR]] thread T1
// CHECK:   {{#0 .* thread_proc .*thread_stack_array_left_oob.cc}}:[[@LINE-3]]
// CHECK: Address [[ADDR]] is located in stack of thread T1 at offset {{.*}} in frame
// CHECK:   thread_proc
  return 0;
}

int main(void) {
  HANDLE thr = CreateThread(NULL, 0, thread_proc, NULL, 0, NULL);
// CHECK: Thread T1 created by T0 here:
// CHECK:   {{#[01] .* main .*thread_stack_array_left_oob.cc}}:[[@LINE-2]]
  WaitForSingleObject(thr, INFINITE);
  return 0;
}

// RUN: %clangxx_asan -O0 %s -Fe%t 2>&1
// 'cat' is used below to work around FileCheck buffering bug which makes this
// test flaky.  FIXME: file an issue.
// RUN: not %run %t 2>&1 | cat | FileCheck %s

#include <windows.h>

DWORD WINAPI thread_proc(void *context) {
  int subscript = -1;
  volatile char stack_buffer[42];
  stack_buffer[subscript] = 42;
// CHECK: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]]
// CHECK: WRITE of size 1 at [[ADDR]] thread T1
// CHECK:   {{#0 .* thread_proc .*thread_stack_array_left_oob.cc}}:[[@LINE-3]]
// CHECK: Address [[ADDR]] is located in stack of thread T1 at offset {{.*}} in frame
// CHECK:   thread_proc
  return 0;
}

int main(void) {
  HANDLE thr = CreateThread(NULL, 0, thread_proc, NULL, 0, NULL);
// CHECK: Thread T1 created by T0 here:
// CHECK:   {{#[01] .* main .*thread_stack_array_left_oob.cc}}:[[@LINE-2]]
  WaitForSingleObject(thr, INFINITE);
  return 0;
}

Remove --check-prefix=CHECK as it's useless


{{{header}}}
{{#includes}}
#include <{{{.}}}>
{{/includes}}
{{{precontent}}}
#include <boost/python.hpp>
#include <cmath>

/* postinclude */

void {{function.mangled_name}}()
{
::boost::python::object parent_object(::boost::python::scope(){{!
    }}{{#function.scope}}{{#name}}.attr("{{name}}"){{/name}}{{/function.scope}});
::boost::python::scope parent_scope(parent_object);

boost::python::def("{{function.name}}", {{!
    }}static_cast<{{{function.type}}}>(&{{{function.qualified_name}}}){{!
    }}{{#function.params?}}, ({{#function.params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/function.params}}){{/function.params?}})
;}
{{{postcontent}}}
{{{footer}}}

{{{header}}}
{{#includes}}
#include <{{{.}}}>
{{/includes}}
{{{precontent}}}
#include <boost/python.hpp>
#include <cmath>

/* postinclude */

void {{function.mangled_name}}()
{
::boost::python::object parent_object(::boost::python::scope(){{!
    }}{{#function.scope}}{{#name}}.attr("{{name}}"){{/name}}{{/function.scope}});
::boost::python::scope parent_scope(parent_object);

{{#function.overloads}}{{!
    }}::boost::python::def("{{name}}", []({{#params}}{{{type}}} {{name}}{{^last}}, {{/last}}{{/params}}) -> {{{return_type}}} { {{!
    }}return {{{qualified_name}}}({{#params}}{{name}}{{^last}}, {{/last}}{{/params}}); }{{!
    }}{{#return_value_policy}}, ::boost::python::return_value_policy<{{{.}}} >(){{/return_value_policy}}{{!
    }}{{#params?}}, ({{#params}}::boost::python::arg("{{name}}"){{^last}}, {{/last}}{{/params}}){{/params?}});
{{/function.overloads}}

}
{{{postcontent}}}
{{{footer}}}

Support for overloads on free functions.


#include "removeNamedParameters.h"
#include "expr.h"
#include "stmt.h"

void RemoveNamedParameters::postProcessExpr(Expr* expr) {
  if (NamedExpr* named_expr = dynamic_cast<NamedExpr*>(expr)) {
    named_expr->replace(named_expr->actual->copy());
  }

  if (VarInitExpr* var_init = dynamic_cast<VarInitExpr*>(expr)) {
    if (dynamic_cast<ArrayType*>(var_init->symbol->type) ||
        dynamic_cast<DomainType*>(var_init->symbol->type)) {
      // No Default Initialization for Arrays/Domains
      var_init->parentStmt->replace(new NoOpStmt());
    } else {
      if (var_init->symbol->type->defaultVal) {
        var_init->replace(var_init->symbol->type->defaultVal->copy());
      } else {
        var_init->replace(new FnCall(new Variable(var_init->symbol->type->defaultConstructor), NULL));
      }
    }
  }
}

#include "removeNamedParameters.h"
#include "expr.h"
#include "stmt.h"

void RemoveNamedParameters::postProcessExpr(Expr* expr) {
  if (NamedExpr* named_expr = dynamic_cast<NamedExpr*>(expr)) {
    named_expr->replace(named_expr->actual->copy());
  }

  if (VarInitExpr* var_init = dynamic_cast<VarInitExpr*>(expr)) {
    if (dynamic_cast<ArrayType*>(var_init->symbol->type) ||
        dynamic_cast<DomainType*>(var_init->symbol->type)) {
      // No Default Initialization for Arrays/Domains
      var_init->parentStmt->replace(new NoOpStmt());
    } else {
      if (var_init->symbol->type->defaultVal) {
        var_init->replace(var_init->symbol->type->defaultVal->copy());
      } else {
        assert(var_init->symbol->type->defaultConstructor);
        var_init->replace(new FnCall(new Variable(var_init->symbol->type->defaultConstructor), NULL));
      }
    }
  }
}

Insert an assert to catch a bad VarInit variable type.


#include "details.hpp"
#include "json/json.h"

dota2::DetailsRequest &dota2::DetailsRequest::id(MatchID id)
{
    query.insert({"match_id", std::to_string(id)});
    return *this;
}

dota2::Details::Details(const Json::Value &json)
{
    const auto& result = json["result"];

    matchID = result["match_id"].asInt();
    startTime = timePoint(result["start_time"].asInt64());
    firstBloodTime = timePoint(result["first_blood_time"].asInt64());
    if(result["radiant_win"].asBool())
    {
        winningTeam = Team::RADIANT;
    }
    else
    {
        winningTeam = Team::DIRE;
    }
}

dota2::MatchID dota2::Details::getMatchID() const
{
    return matchID;
}

dota2::Team dota2::Details::getWinningTeam() const
{
    return winningTeam;
}

dota2::Details::timePoint dota2::Details::getStartTime() const
{
    return startTime;
}

dota2::Details::timePoint dota2::Details::getFirstBloodTime() const
{
    return firstBloodTime;
}

#include "details.hpp"
#include "json/json.h"

dota2::DetailsRequest &dota2::DetailsRequest::id(MatchID id)
{
    query.insert({"match_id", std::to_string(id)});
    return *this;
}

dota2::Details::Details(const Json::Value &json)
{
    const auto& result = json["result"];

    matchID = result["match_id"].asInt();
    startTime = timePoint(result["start_time"].asInt64());
    firstBloodTime = timePoint(result["first_blood_time"].asInt64());
    winningTeam = result["radiant_win"].asBool() ?
        Team::RADIANT : Team::DIRE;
}

dota2::MatchID dota2::Details::getMatchID() const
{
    return matchID;
}

dota2::Team dota2::Details::getWinningTeam() const
{
    return winningTeam;
}

dota2::Details::timePoint dota2::Details::getStartTime() const
{
    return startTime;
}

dota2::Details::timePoint dota2::Details::getFirstBloodTime() const
{
    return firstBloodTime;
}

Change if/else to ternary if


#include "Button.hpp"

#include <Engine/Geometry/Rectangle.hpp>
#include <Engine/Util/Input.hpp>

using namespace GUI;

Button::Button(Widget* parent) : Widget(parent) {
    mouseHover = false;
    hasClickedCallback = false;
    size = glm::vec2(64.f, 64.f);
}

Button::~Button() {

}

void Button::Update() {
    double xpos = Input()->CursorX();
    double ypos = Input()->CursorY();

    mouseHover = xpos >= GetPosition().x && xpos < GetPosition().x + size.x && ypos >= GetPosition().y && ypos < GetPosition().y + size.y;

    if (mouseHover && Input()->MousePressed(GLFW_MOUSE_BUTTON_LEFT) && hasClickedCallback) {
        clickedCallback();
    }
}

glm::vec2 Button::GetSize() const {
    return size;
}

void Button::SetSize(const glm::vec2& size) {
    this->size = size;
}

void Button::SetClickedCallback(std::function<void()> callback) {
    clickedCallback = callback;
    hasClickedCallback = true;
}

bool Button::GetMouseHover() const {
    return mouseHover;
}

#include "Button.hpp"

#include <Engine/Geometry/Rectangle.hpp>
#include <Engine/Util/Input.hpp>
#include <Engine/Physics/Rectangle.hpp>

using namespace GUI;

Button::Button(Widget* parent) : Widget(parent) {
    mouseHover = false;
    hasClickedCallback = false;
    size = glm::vec2(64.f, 64.f);
}

Button::~Button() {

}

void Button::Update() {
    glm::vec2 mousePosition(Input()->CursorX(), Input()->CursorY());
    Physics::Rectangle rect(GetPosition(), size);
    mouseHover = rect.Collide(mousePosition);

    if (mouseHover && Input()->MousePressed(GLFW_MOUSE_BUTTON_LEFT) && hasClickedCallback) {
        clickedCallback();
    }
}

glm::vec2 Button::GetSize() const {
    return size;
}

void Button::SetSize(const glm::vec2& size) {
    this->size = size;
}

void Button::SetClickedCallback(std::function<void()> callback) {
    clickedCallback = callback;
    hasClickedCallback = true;
}

bool Button::GetMouseHover() const {
    return mouseHover;
}

Use rectangle-point collision in button.


#include "StorageDeleteFileChunkJob.h"
#include "System/Stopwatch.h"
#include "System/FileSystem.h"
#include "StorageFileChunk.h"

StorageDeleteFileChunkJob::StorageDeleteFileChunkJob(StorageFileChunk* chunk_)
{
    chunk = chunk_;
}

void StorageDeleteFileChunkJob::Execute()
{
    Stopwatch   sw;
    Buffer      filename;

    Log_Debug("Deleting file chunk %U from disk, starting", chunk->GetChunkID());
    sw.Start();

    filename.Write(chunk->GetFilename());
    delete chunk;
    FS_Delete(filename.GetBuffer());

    sw.Stop();
    Log_Debug("Deleted, elapsed: %U", (uint64_t) sw.Elapsed());
}

void StorageDeleteFileChunkJob::OnComplete()
{
    delete this;
}

#include "StorageDeleteFileChunkJob.h"
#include "System/Stopwatch.h"
#include "System/FileSystem.h"
#include "StorageFileChunk.h"

StorageDeleteFileChunkJob::StorageDeleteFileChunkJob(StorageFileChunk* chunk_)
{
    chunk = chunk_;
}

void StorageDeleteFileChunkJob::Execute()
{
    Stopwatch   sw;
    Buffer      filename;

    Log_Debug("Deleting file chunk %U from disk, starting", chunk->GetChunkID());
    sw.Start();

    filename.Write(chunk->GetFilename());
    delete chunk;

    // EXPERIMENTAL: remove from production!
    //FS_Delete(filename.GetBuffer());

    sw.Stop();
    Log_Debug("Deleted, elapsed: %U", (uint64_t) sw.Elapsed());
}

void StorageDeleteFileChunkJob::OnComplete()
{
    delete this;
}

Test commit for testing EXPERIMENTAL code trigger.


#include <miniMAT/ast/WhoStmt.hpp>

#include <iostream>

namespace miniMAT {
    namespace ast {
        std::string WhoStmt::GetClassName() const {
            return "WhoStmt";
        }

        void WhoStmt::VisitDisplay(const std::string& prefix) const {
            using namespace miniMAT::visit::display;

            Show(prefix, *this);
        }

        Matrix WhoStmt::VisitEvaluate(std::shared_ptr<std::map<std::string, Matrix>> vars) {
            if (vars->size() != 0) {
                std::cout  << std::endl;
                for (auto var : *vars)
                    std::cout << var.first << std::endl;
                std::cout  << std::endl;
            }

            return Matrix::Zero(0,0);
        }

        void WhoStmt::VisitCheck(std::shared_ptr<std::map<std::string, Matrix>> vars,
                                 std::shared_ptr<reporter::ErrorReporter> reporter) const {

        }
    }
}

#include <miniMAT/ast/WhoStmt.hpp>

#include <iostream>

namespace miniMAT {
    namespace ast {
        std::string WhoStmt::GetClassName() const {
            return "WhoStmt";
        }

        void WhoStmt::VisitDisplay(const std::string& prefix) const {
            using namespace miniMAT::visit::display;

            Show(prefix, *this);
        }

        Matrix WhoStmt::VisitEvaluate(std::shared_ptr<std::map<std::string, Matrix>> vars) {
            if (vars->size() != 0) {
                std::cout << std::endl << "Your variables are:" << std::endl << std::endl;
                for (auto var : *vars)
                    std::cout << var.first << "  ";
                std::cout << std::endl << std::endl;
            }

            return Matrix::Zero(0,0);
        }

        void WhoStmt::VisitCheck(std::shared_ptr<std::map<std::string, Matrix>> vars,
                                 std::shared_ptr<reporter::ErrorReporter> reporter) const {

        }
    }
}

Fix formatting in 'who' command


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

#include "net/ftp/ftp_network_layer.h"

#include "net/ftp/ftp_network_session.h"
#include "net/ftp/ftp_network_transaction.h"
#include "net/socket/client_socket_factory.h"

namespace net {

FtpNetworkLayer::FtpNetworkLayer(HostResolver* host_resolver)
    : session_(new FtpNetworkSession(host_resolver)),
      suspended_(false) {
}

FtpNetworkLayer::~FtpNetworkLayer() {
}

// static
FtpTransactionFactory* FtpNetworkLayer::CreateFactory(
    HostResolver* host_resolver) {
  return new FtpNetworkLayer(host_resolver);
}

FtpTransaction* FtpNetworkLayer::CreateTransaction() {
  if (suspended_)
    return NULL;

  return new FtpNetworkTransaction(session_->host_resolver(),
                                   ClientSocketFactory::GetDefaultFactory());
}

void FtpNetworkLayer::Suspend(bool suspend) {
  suspended_ = suspend;

  /* TODO(darin): We'll need this code once we have a connection manager.
  if (suspend)
    session_->connection_manager()->CloseIdleSockets();
  */
}

}  // namespace net

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

#include "net/ftp/ftp_network_layer.h"

#include "net/ftp/ftp_network_session.h"
#include "net/ftp/ftp_network_transaction.h"
#include "net/socket/client_socket_factory.h"

namespace net {

FtpNetworkLayer::FtpNetworkLayer(HostResolver* host_resolver)
    : session_(new FtpNetworkSession(host_resolver)),
      suspended_(false) {
}

FtpNetworkLayer::~FtpNetworkLayer() {
}

// static
FtpTransactionFactory* FtpNetworkLayer::CreateFactory(
    HostResolver* host_resolver) {
  return new FtpNetworkLayer(host_resolver);
}

FtpTransaction* FtpNetworkLayer::CreateTransaction() {
  if (suspended_)
    return NULL;

  return new FtpNetworkTransaction(session_->host_resolver(),
                                   ClientSocketFactory::GetDefaultFactory());
}

void FtpNetworkLayer::Suspend(bool suspend) {
  suspended_ = suspend;
}

}  // namespace net

Remove dead code in FtpNetworkLayer


#include <catch.hpp>

#include "WordDecoder.hpp"

namespace {

using namespace Core8;

TEST_CASE("Decode X from pattern vXvv", "[decoder]") {
  REQUIRE(WordDecoder::readX(0x0F00) == 0XF);
  REQUIRE(WordDecoder::readX(0xF0FF) == 0X0);
}

TEST_CASE("Decode Y from pattern vvYv", "[decoder]") {
  REQUIRE(WordDecoder::readY(0x00F0) == 0XF);
  REQUIRE(WordDecoder::readY(0xFF0F) == 0X0);
}

TEST_CASE("Decode N from pattern vvvN", "[decoder]") {
  REQUIRE(WordDecoder::readN(0x000F) == 0XF);
  REQUIRE(WordDecoder::readN(0xFFF0) == 0X0);
}

TEST_CASE("Decode NN from pattern vvNN", "[decoder]") {
  REQUIRE(WordDecoder::readNN(0x00FF) == 0XFF);
  REQUIRE(WordDecoder::readNN(0xFF11) == 0X11);
}

TEST_CASE("Decode NNN from pattern vNNN", "[decoder]") {
  REQUIRE(WordDecoder::readNN(0x0FFF) == 0XFFF);
  REQUIRE(WordDecoder::readNN(0xF111) == 0X111);
}

} // unnamed namespace

#include <catch.hpp>

#include "WordDecoder.hpp"

namespace {

using namespace Core8;

TEST_CASE("Decode X from pattern vXvv", "[decoder]") {
  REQUIRE(WordDecoder::readX(0x0F00) == 0XF);
  REQUIRE(WordDecoder::readX(0xF0FF) == 0X0);
}

TEST_CASE("Decode Y from pattern vvYv", "[decoder]") {
  REQUIRE(WordDecoder::readY(0x00F0) == 0XF);
  REQUIRE(WordDecoder::readY(0xFF0F) == 0X0);
}

TEST_CASE("Decode N from pattern vvvN", "[decoder]") {
  REQUIRE(WordDecoder::readN(0x000F) == 0XF);
  REQUIRE(WordDecoder::readN(0xFFF0) == 0X0);
}

TEST_CASE("Decode NN from pattern vvNN", "[decoder]") {
  REQUIRE(WordDecoder::readNN(0x00FF) == 0XFF);
  REQUIRE(WordDecoder::readNN(0xFF11) == 0X11);
}

TEST_CASE("Decode NNN from pattern vNNN", "[decoder]") {
  REQUIRE(WordDecoder::readNNN(0x0FFF) == 0XFFF);
  REQUIRE(WordDecoder::readNNN(0xF111) == 0X111);
}

} // unnamed namespace

Fix test with wrong function call


//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011      Daniel Marth <danielmarth@gmx.at>
//

#include "RelatedActivities.h"

namespace Marble
{

namespace Declarative
{

RelatedActivities::RelatedActivities()
{
}

RelatedActivities::RelatedActivities( const QMap<QString, QVariant>& relatedActivities ) : m_relatedActivities( relatedActivities )
{
}

QStringList RelatedActivities::get( const QString& name ) const
{
    return m_relatedActivities[name].toStringList();
}

void RelatedActivities::setRelatedActivities( const QMap<QString, QVariant>& relatedActivities )
{
    m_relatedActivities = relatedActivities;
}

QMap<QString, QVariant> RelatedActivities::relatedActivities() const
{
    return m_relatedActivities;
}

}

}

#include "RelatedActivities.moc"

Fix build failure due to missing newline Patch by tropikhajma, thanks! CCBUG: 291907


#include "../kontsevich_graph_series.hpp"
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << " [order]\n";
        return 1;
    }
    size_t order = stoi(argv[1]);
    set<KontsevichGraph> relevants = KontsevichGraph::graphs(order, 2, true, true,
                    [](KontsevichGraph g) -> bool
                    {
                        return g.positive_differential_order() && g.is_prime() && !g.is_zero();
                    });
    size_t counter = 0;
    for (KontsevichGraph const& g : relevants)
        cout << g.encoding() << "    w_" << order << "_" << (++counter) << "\n";
}

#include "../kontsevich_graph_series.hpp"
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        cout << "Usage: " << argv[0] << " [order]\n";
        return 1;
    }
    size_t order = stoi(argv[1]);
    set<KontsevichGraph> relevants = KontsevichGraph::graphs(order, 2, true, true,
                    [](KontsevichGraph g) -> bool
                    {
                        return g.positive_differential_order() && g.is_prime();
                    });
    size_t counter = 0;
    for (KontsevichGraph const& g : relevants)
    {
        cout << g.encoding() << "    ";
        if (g.is_zero())
            cout << "0\n";
        else
            cout << "w_" << order << "_" << (++counter) << "\n";
    }
}

Declare zero graphs also to be relevant (may yield non-trivial cyclic weight relations).


#include "compiler/build_tables/item_set_closure.h"
#include <algorithm>
#include <set>
#include "tree_sitter/compiler.h"
#include "compiler/build_tables/follow_sets.h"
#include "compiler/build_tables/item.h"
#include "compiler/prepared_grammar.h"

namespace tree_sitter {
    using std::set;
    using rules::Symbol;

    namespace build_tables {
        static bool contains(const ParseItemSet *items, const ParseItem &item) {
            if (items->empty()) return false;
            return (std::find(items->begin(), items->end(), item) != items->end());
        }

        static void add_item(ParseItemSet *item_set,
                             const ParseItem &item,
                             const PreparedGrammar &grammar) {
            if (!contains(item_set, item)) {
                item_set->insert(item);
                for (auto &pair : follow_sets(item, grammar)) {
                    Symbol non_terminal = pair.first;
                    set<Symbol> terminals = pair.second;
                    for (auto &terminal : terminals) {
                        ParseItem next_item(non_terminal, grammar.rule(non_terminal), 0, terminal);
                        add_item(item_set, next_item, grammar);
                    }
                }
            }
        }

        const ParseItemSet item_set_closure(const ParseItemSet &item_set,
                                            const PreparedGrammar &grammar) {
            ParseItemSet result;
            for (ParseItem item : item_set)
                add_item(&result, item, grammar);
            return result;
        }
    }
}

#include "compiler/build_tables/item_set_closure.h"
#include <algorithm>
#include <set>
#include "tree_sitter/compiler.h"
#include "compiler/build_tables/follow_sets.h"
#include "compiler/build_tables/item.h"
#include "compiler/prepared_grammar.h"

namespace tree_sitter {
    using std::set;
    using rules::Symbol;

    namespace build_tables {
        static bool contains(const ParseItemSet *items, const ParseItem &item) {
            if (items->empty()) return false;
            return (std::find(items->begin(), items->end(), item) != items->end());
        }

        static void add_item(ParseItemSet *item_set,
                             const ParseItem &item,
                             const PreparedGrammar &grammar) {
            if (!contains(item_set, item)) {
                item_set->insert(item);
                for (const auto &pair : follow_sets(item, grammar)) {
                    const Symbol &non_terminal = pair.first;
                    const set<Symbol> &terminals = pair.second;
                    for (const auto &terminal : terminals) {
                        ParseItem next_item(non_terminal, grammar.rule(non_terminal), 0, terminal);
                        add_item(item_set, next_item, grammar);
                    }
                }
            }
        }

        const ParseItemSet item_set_closure(const ParseItemSet &item_set,
                                            const PreparedGrammar &grammar) {
            ParseItemSet result;
            for (const ParseItem &item : item_set)
                add_item(&result, item, grammar);
            return result;
        }
    }
}

Use const references in a few more places


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <atomic>

// constexpr atomic<T>::atomic(T value)

#include <atomic>
#include <type_traits>
#include <cassert>

struct UserType {
    int i;

    UserType() noexcept {}
    constexpr explicit UserType(int d) noexcept : i(d) {}

    friend bool operator==(const UserType& x, const UserType& y) {
        return x.i == y.i;
    }
};

template <class Tp>
void test() {
    typedef std::atomic<Tp> Atomic;
    static_assert(std::is_literal_type<Atomic>::value, "");
    constexpr Tp t(42);
    {
        constexpr Atomic a(t);
        assert(a == t);
    }
    {
        constexpr Atomic a{t};
        assert(a == t);
    }
    {
        constexpr Atomic a = ATOMIC_VAR_INIT(t);
        assert(a == t);
    }
}

int main()
{
    test<int>();
    test<UserType>();
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// NOTE: atomic<> of a TriviallyCopyable class is wrongly rejected by older
// clang versions. It was fixed right before the llvm 3.5 release. See PR18097.
// XFAIL: apple-clang-6.0, clang-3.4, clang-3.3

// <atomic>

// constexpr atomic<T>::atomic(T value)

#include <atomic>
#include <type_traits>
#include <cassert>

struct UserType {
    int i;

    UserType() noexcept {}
    constexpr explicit UserType(int d) noexcept : i(d) {}

    friend bool operator==(const UserType& x, const UserType& y) {
        return x.i == y.i;
    }
};

template <class Tp>
void test() {
    typedef std::atomic<Tp> Atomic;
    static_assert(std::is_literal_type<Atomic>::value, "");
    constexpr Tp t(42);
    {
        constexpr Atomic a(t);
        assert(a == t);
    }
    {
        constexpr Atomic a{t};
        assert(a == t);
    }
    {
        constexpr Atomic a = ATOMIC_VAR_INIT(t);
        assert(a == t);
    }
}

int main()
{
    test<int>();
    test<UserType>();
}

Mark this test as XFAIL with older compilers, since they hit PR18097


// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | grep -c {handle\\|_Unwind_Resume} | grep {\[14\]}

struct One { };
struct Two { };

void handle_unexpected () {
  try
  {
    throw;
  }
  catch (One &)
  {
    throw Two ();
  }
}

// RUN: %llvmgxx %s -S -emit-llvm -O2 -o - | ignore grep _Unwind_Resume | \
// RUN:   wc -l | grep {\[03\]}

struct One { };
struct Two { };

void handle_unexpected () {
  try
  {
    throw;
  }
  catch (One &)
  {
    throw Two ();
  }
}

Use "ignore" rather than grep tricks.


/******************************************************************************
 *   Copyright (C) 2011 Frank Osterfeld <frank.osterfeld@gmail.com>           *
 *                                                                            *
 * 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. For licensing and distribution        *
 * details, check the accompanying file 'COPYING'.                            *
 *****************************************************************************/
#include "keychain_p.h"

#include <QSettings>

using namespace QKeychain;

QKeychain::Error Keychain::Private::readEntryImpl( QByteArray* pw,
                                                  const QString& key,
                                                  QString* err ) {
    Q_UNUSED( key )
    Q_ASSERT( pw );
    Q_ASSERT( err );
    return NotImplemented;
}

QKeychain::Error Keychain::Private::writeEntryImpl( const QString& key,
                                                   const QByteArray& data_,
                                                   QString* err ) {
    Q_ASSERT( err );
    return NotImplemented;
}

QKeychain::Error Keychain::Private::deleteEntryImpl( const QString& key,
                                                    QString* err ) {
    Q_ASSERT( err );
    err->clear();
    return NotImplemented;
}

QKeychain::Error Keychain::Private::entryExistsImpl( bool* exists,
                                                    const QString& key,
                                                    QString* err ) {
    Q_ASSERT( exists );
    Q_ASSERT( err );
    err->clear();
    *exists = false;
    return NotImplemented;
}

/******************************************************************************
 *   Copyright (C) 2011 Frank Osterfeld <frank.osterfeld@gmail.com>           *
 *                                                                            *
 * 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. For licensing and distribution        *
 * details, check the accompanying file 'COPYING'.                            *
 *****************************************************************************/
#include "keychain_p.h"

#include <QSettings>

using namespace QKeychain;

void ReadPasswordJob::Private::doStart() {
    q->emitFinishedWithError( NotImplemented, QString() );
}

void WritePasswordJob::Private::doStart() {
    q->emitFinishedWithError( NotImplemented, QString() );
}

Implement dbus stub for async API.


// RUN: %clangxx_asan -O0 %s -o %t && %t

// Regression test for PR17138.

#include <assert.h>
#include <string.h>

int main() {
  char buf[1024];
  char *res = (char *)strerror_r(300, buf, sizeof(buf));
  assert(res != 0);
  return 0;
}

// RUN: %clangxx_asan -O0 %s -o %t && %t

// Regression test for PR17138.

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

int main() {
  char buf[1024];
  char *res = (char *)strerror_r(300, buf, sizeof(buf));
  printf("%p\n", res);
  return 0;
}

Remove a check from strerror_r test.


//===- MRegisterInfo.cpp - Target Register Information Implementation -----===//
//
// This file implements the MRegisterInfo interface.
//
//===----------------------------------------------------------------------===//

#include "llvm/Target/MRegisterInfo.h"

MRegisterInfo::MRegisterInfo(const MRegisterDesc *D, unsigned NR,
                             regclass_iterator RCB, regclass_iterator RCE,
			     int CFSO, int CFDO)
  : Desc(D), NumRegs(NR), RegClassBegin(RCB), RegClassEnd(RCE) {
  assert(NumRegs < FirstVirtualRegister &&
         "Target has too many physical registers!");

  PhysRegClasses = new const TargetRegisterClass*[NumRegs];
  for (unsigned i = 0; i != NumRegs; ++i)
    PhysRegClasses[i] = 0;

  // Fill in the PhysRegClasses map
  for (MRegisterInfo::regclass_iterator I = regclass_begin(),
         E = regclass_end(); I != E; ++I)
    for (unsigned i=0; i < (*I)->getNumRegs(); ++i) {
      assert(PhysRegClasses[(*I)->getRegister(i)] == 0 &&
             "Register in more than one class?");
      PhysRegClasses[(*I)->getRegister(i)] = *I;
    }

  CallFrameSetupOpcode   = CFSO;
  CallFrameDestroyOpcode = CFDO;
}

MRegisterInfo::~MRegisterInfo() {
  delete[] PhysRegClasses;
}

//===- MRegisterInfo.cpp - Target Register Information Implementation -----===//
//
// This file implements the MRegisterInfo interface.
//
//===----------------------------------------------------------------------===//

#include "llvm/Target/MRegisterInfo.h"

MRegisterInfo::MRegisterInfo(const MRegisterDesc *D, unsigned NR,
                             regclass_iterator RCB, regclass_iterator RCE,
			     int CFSO, int CFDO)
  : Desc(D), NumRegs(NR), RegClassBegin(RCB), RegClassEnd(RCE) {
  assert(NumRegs < FirstVirtualRegister &&
         "Target has too many physical registers!");

  PhysRegClasses = new const TargetRegisterClass*[NumRegs];
  for (unsigned i = 0; i != NumRegs; ++i)
    PhysRegClasses[i] = 0;

  // Fill in the PhysRegClasses map
  for (MRegisterInfo::regclass_iterator I = regclass_begin(),
         E = regclass_end(); I != E; ++I)
    for (unsigned i = 0, e = (*I)->getNumRegs(); i != e; ++i) {
      unsigned Reg = (*I)->getRegister(i);
      assert(PhysRegClasses[Reg] == 0 && "Register in more than one class?");
      PhysRegClasses[Reg] = *I;
    }

  CallFrameSetupOpcode   = CFSO;
  CallFrameDestroyOpcode = CFDO;
}

MRegisterInfo::~MRegisterInfo() {
  delete[] PhysRegClasses;
}

Make it easier to debug by exposing a temporary


#include "FileSystem.h"
#include "android/AndroidServices.h"

#include <stdexcept>
#include <fstream>
#include <sstream>

#include <android/log.h>

namespace yarrar {
namespace filesystem {

void readFile(const std::string& relativePath, std::string& toBuffer)
{
    auto assetManager = yarrar::android::getAssetManager();
    AAsset* file = AAssetManager_open(assetManager, relativePath.c_str(), AASSET_MODE_BUFFER);
    if(!file)
    {
        throw std::runtime_error(std::string("failed to open file: ") + relativePath);
    }

    size_t len = AAsset_getLength(file);
    toBuffer.clear();
    toBuffer.resize(len);

    int ret = AAsset_read(file, &toBuffer.front(), len);
    if(ret <= 0)
    {
        throw std::runtime_error(std::string("failed to open file: ") + relativePath);
    }

    AAsset_close(file);
}

}
}

#include "FileSystem.h"
#include "android/AndroidServices.h"

#include <stdexcept>
#include <fstream>
#include <sstream>

namespace {

class AndroidFile
{
public:

    AndroidFile(const std::string& path):
        m_path(path),
        m_file(nullptr)
    {
        m_file = AAssetManager_open(yarrar::android::getAssetManager(), m_path.c_str(), AASSET_MODE_BUFFER);
        if(!m_file)
        {
            throw std::runtime_error(std::string("failed to open file: ") + m_path);
        }
    }

    ~AndroidFile()
    {
        AAsset_close(m_file);
    }

    void read(std::string& toBuffer)
    {
        if(!m_file)
        {
            throw std::runtime_error(std::string("file not opened: ") + m_path);
        }

        size_t len = AAsset_getLength(m_file);
        toBuffer.clear();
        toBuffer.resize(len);

        int ret = AAsset_read(m_file, &toBuffer.front(), len);
        if(ret <= 0)
        {
            throw std::runtime_error(std::string("read error in file: ") + m_path);
        }
    }

private:
    std::string m_path;
    AAsset* m_file;
};

}

namespace yarrar {
namespace filesystem {

void readFile(const std::string& relativePath, std::string& toBuffer)
{
    yarrar::android::log(std::string("Opening file: ") + relativePath);
    AndroidFile f(relativePath);
    f.read(toBuffer);
}

}
}

Change Android file reading to RAII.


#include "pch.h"
#include "MidiNrpnParameterValueChangeMessage.h"

using namespace PeteBrown::Devices::Midi;

MidiNrpnParameterValueChangeMessage::MidiNrpnParameterValueChangeMessage()
{
	_rawData = ref new Windows::Storage::Streams::Buffer(TOTAL_BYTES_IN_MESSAGE);
	_rawData->Length = TOTAL_BYTES_IN_MESSAGE;

	_rawBytes = MidiMessageHelper::GetRawDataBytesFromBuffer(_rawData);

//	_type = Windows::Devices::Midi::MidiMessageType::None;
	_type = Windows::Devices::Midi::MidiMessageType::ControlChange;

	BuildBaseMessages();
}

//
//unsigned short MidiNrpnParameterValueChangeMessage::ParameterNumber::get()
//{
//
//}
//
//void MidiNrpnParameterValueChangeMessage::ParameterNumber::set(unsigned short value)
//{
//	// TODO: Set msb and lsb as well as backing store
//}
//
//
//
//unsigned short MidiNrpnParameterValueChangeMessage::Value::get()
//{
//
//}
//
//void MidiNrpnParameterValueChangeMessage::Value::set(unsigned short value)
//{
//	// TODO: Set msb and lsb as well as backing store
//}

#include "pch.h"
#include "MidiNrpnParameterValueChangeMessage.h"

using namespace PeteBrown::Devices::Midi;

MidiNrpnParameterValueChangeMessage::MidiNrpnParameterValueChangeMessage()
{
	_rawData = ref new Windows::Storage::Streams::Buffer(TOTAL_BYTES_IN_MESSAGE);
	_rawData->Length = TOTAL_BYTES_IN_MESSAGE;

	_rawBytes = MidiMessageHelper::GetRawDataBytesFromBuffer(_rawData);

	_type = Windows::Devices::Midi::MidiMessageType::None;
//	_type = Windows::Devices::Midi::MidiMessageType::ControlChange;

	BuildBaseMessages();
}

//
//unsigned short MidiNrpnParameterValueChangeMessage::ParameterNumber::get()
//{
//
//}
//
//void MidiNrpnParameterValueChangeMessage::ParameterNumber::set(unsigned short value)
//{
//	// TODO: Set msb and lsb as well as backing store
//}
//
//
//
//unsigned short MidiNrpnParameterValueChangeMessage::Value::get()
//{
//
//}
//
//void MidiNrpnParameterValueChangeMessage::Value::set(unsigned short value)
//{
//	// TODO: Set msb and lsb as well as backing store
//}

Change message type to None


#include "robot_name.h"
#include <sstream>
#include <stdexcept>

using namespace std;

namespace robot_name
{

namespace
{

string next_prefix(string prefix)
{
    string next{prefix};
    const string letters{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"};
    if (prefix[1] == letters.back()) {
        if (prefix[0] == letters.back()) {
            throw range_error("prefix combinations exhausted");
        }
        next[1] = letters[0];
        next[0] = letters[letters.find(next[0]) + 1];
    } else {
        next[1] = letters[letters.find(next[1]) + 1];
    }
    return next;
}

string generate_name()
{
    static string prefix = "AA";
    static int unit_number = 100;
    ostringstream buff;
    if (unit_number > 999) {
        prefix = next_prefix(prefix);
        unit_number = 100;
    }
    buff << prefix << unit_number++;
    return buff.str();
}

}

robot::robot()
    : name_(generate_name())
{
}

void robot::reset()
{
    name_ = generate_name();
}

}

#include "robot_name.h"
#include <iomanip>
#include <sstream>
#include <stdexcept>

using namespace std;

namespace robot_name
{

namespace
{

string next_prefix(string prefix)
{
    string next{prefix};
    const string letters{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"};
    if (prefix[1] == letters.back()) {
        if (prefix[0] == letters.back()) {
            throw range_error("prefix combinations exhausted");
        }
        next[1] = letters[0];
        next[0] = letters[letters.find(next[0]) + 1];
    } else {
        next[1] = letters[letters.find(next[1]) + 1];
    }
    return next;
}

string generate_name()
{
    static string prefix = "AA";
    static int unit_number = 0;
    ostringstream buff;
    if (unit_number > 999) {
        prefix = next_prefix(prefix);
        unit_number = 0;
    }
    buff << prefix << setw(3) << setfill('0') << unit_number++;
    return buff.str();
}

}

robot::robot()
    : name_(generate_name())
{
}

void robot::reset()
{
    name_ = generate_name();
}

}

Increase number of robot names that can be generated.


#define __STDC_CONSTANT_MACROS

#include <stdlib.h>

extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}

#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )

static void test()
{
  AVFormatContext* c = 0;
  AVCodec* avcodec = 0;
  AVFrame* frame = 0;

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
  int err = avformat_open_input(&c, "", NULL, NULL);
#else
  int err = av_open_input_file(&c, "", NULL, 0, NULL);
#endif
}

int main() { test(); return 0; }

#define __STDC_CONSTANT_MACROS

#include <stdlib.h>

extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}

#define CALC_FFMPEG_VERSION(a,b,c) ( a<<16 | b<<8 | c )

static void test()
{
  AVFormatContext* c = 0;
  AVCodec* avcodec = 0;
  AVFrame* frame = 0;
  (void)avcodec;
  (void)frame;

#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
  int err = avformat_open_input(&c, "", NULL, NULL);
#else
  int err = av_open_input_file(&c, "", NULL, 0, NULL);
#endif
  (void)err;
}

int main() { test(); return 0; }

Fix ffmpeg detection with -D OPENCV_WARNINGS_ARE_ERRORS=ON option.


#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;

int main()
{
    string str("a simple string");

    // while
    decltype(str.size()) i = 0;
    while (i < str.size()) str[i++] = 'X';
    cout << str << endl;

    // for
    for (i = 0; i<str.size(); ++i) str[i] = 'Y';
    cout << str << endl;

    // I like range for.
    return 0;
}

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;

int main()
{
    string str("a simple string");

    // while
    decltype(str.size()) i = 0;
    while (i < str.size()) str[i++] = 'X';
    cout << str << endl;

    // for
    for (i = 0; i < str.size(); str[i++] = 'Y');
    cout << str << endl;

    // I like range for.
    return 0;
}

Add the statement to expression in the FOR loop


//
//  shaderImageMask.cpp
//  shaderExample
//
//  Created by Alex Olivier on 6/6/14.
//
//  This example shows how to pass multiple textures
//  to a shader.  It uses one texture as a mask.

// Based on openFrameworks shader tutorials

#include "shaderImageMask.h"

shaderImageMask::shaderImageMask(string iFilename1, string iFilename2){

  // Create 2 image objects
  image1 = new ofxImageObject(iFilename1);
  image2 = new ofxImageObject(iFilename2);

  addChild(image1);
  addChild(image2);
}

// Destroy objects
shaderImageMask::~shaderImageMask(){

  removeChild(image1);
  removeChild(image2);

  delete image1;
  delete image2;

}

void shaderImageMask::idle(float iTime){

}

//  Override default method to set shader parameters
//  Pass 2 textures to our shaders
void shaderImageMask::setShaderParams(){

  // Pass one texture in as "tex0"
  // Pass second texture in as "mask"
  shader->setUniformTexture("tex0", *image1->tex, 1);
  shader->setUniformTexture("mask", *image2->tex, 2);

}

//
//  shaderImageMask.cpp
//  shaderExample
//
//  Created by Alex Olivier on 6/6/14.
//
//  This example shows how to pass multiple textures
//  to a shader.  It uses one texture as a mask.

// Based on openFrameworks shader tutorials

#include "shaderImageMask.h"

shaderImageMask::shaderImageMask(string iFilename1, string iFilename2){

  // Create 2 image objects
  image1 = new ofxImageObject(iFilename1);
  image2 = new ofxImageObject(iFilename2);

  addChild(image1);
  addChild(image2);
}

// Destroy objects
shaderImageMask::~shaderImageMask(){

  removeChild(image1);
  removeChild(image2);

  delete image1;
  delete image2;

}

void shaderImageMask::idle(float iTime){

}

//  Override default method to set shader parameters
//  Pass 2 textures to our shaders
void shaderImageMask::setShaderParams(){

  // Pass one texture in as "tex0"
  // Pass second texture in as "mask"
  shader->setUniformTexture("tex0", *image1->getTexture(), 1);
  shader->setUniformTexture("mask", *image2->getTexture(), 2);

}

Use getTexture method to access image tex


#include <thread>
#include <renderer.hpp>
#include <fensterchen.hpp>

int main(int argc, char* argv[])
{
  unsigned const width = 800;
  unsigned const height = 600;
  std::string const filename = "./checkerboard.ppm";

  Renderer app(width, height, filename);

  std::thread thr([&app]() { app.render(); });

  Window win(glm::ivec2(width,height));

  while (!win.shouldClose()) {
    if (win.isKeyPressed(GLFW_KEY_ESCAPE)) {
      win.stop();
    }

    glDrawPixels( width, height, GL_RGB, GL_FLOAT
                , app.colorbuffer().data());

    win.update();
  }

  thr.join();

  return 0;
}

#include <thread>
#include <renderer.hpp>
#include <fensterchen.hpp>

int main(int argc, char* argv[])
{
  unsigned const width = 600;
  unsigned const height = 600;
  std::string const filename = "./checkerboard.ppm";

  Renderer app(width, height, filename);

  std::thread thr([&app]() { app.render(); });

  Window win(glm::ivec2(width,height));

  while (!win.shouldClose()) {
    if (win.isKeyPressed(GLFW_KEY_ESCAPE)) {
      win.stop();
    }

    glDrawPixels( width, height, GL_RGB, GL_FLOAT
                , app.colorbuffer().data());

    win.update();
  }

  thr.join();

  return 0;
}

Set window size to 600x600.


// ThermoFun includes
#include <Thermofun/ThermoFun.hpp>
using namespace ThermoFun;

int main()
{
    Database db("aq17.json");
}

// ThermoFun includes
#include <ThermoFun/ThermoFun.hpp>
using namespace ThermoFun;

int main()
{
    Database db("aq17.json");
}

Fix include header statement of test


/* Copyright 2014 Dietrich Epp.
   This file is part of Oubliette.  Oubliette is licensed under the terms
   of the 2-clause BSD license.  For more information, see LICENSE.txt. */
#include "stats.hpp"
namespace game {

const walking_stats stats::player = {
    600.0f,
    // Walking
    1200.0f, 120.0f, 300.0f, 150.0f, 3,
    // Jumping
    25, 200.0f, 250.0f, true
};

}

/* Copyright 2014 Dietrich Epp.
   This file is part of Oubliette.  Oubliette is licensed under the terms
   of the 2-clause BSD license.  For more information, see LICENSE.txt. */
#include "stats.hpp"
namespace game {

const walking_stats stats::player = {
    600.0f,
    // Walking
    1200.0f, 120.0f, 300.0f, 150.0f, 3,
    // Jumping
    25, 400.0f, 180.0f, true
};

}

Improve ability to make small jumps


//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>

class Point {
public:
    int x;
    int y;
    Point(int a, int b):
        x(a),
        y(b)
    {}
};

class Data {
public:
    int id;
    Point point;
    Data(int i):
        id(i),
        point(0, 0)
    {}
};

int main(int argc, char const *argv[]) {
    Data *data[1000];
    Data **ptr = data;
    for (int i = 0; i < 1000; ++i) {
        ptr[i] = new Data(i);
        ptr[i]->point.x = i;
        ptr[i]->point.y = i+1;
    }

    printf("Finished populating data.\n");
    for (int i = 0; i < 1000; ++i) {
        bool dump = argc > 1; // Set breakpoint here.
                              // Evaluate a couple of expressions (2*1000 = 2000 exprs):
                              // expr ptr[i]->point.x
                              // expr ptr[i]->point.y
        if (dump) {
            printf("data[%d] = %d (%d, %d)\n", i, ptr[i]->id, ptr[i]->point.x, ptr[i]->point.y);
        }
    }
    return 0;
}

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

class Point {
public:
    int x;
    int y;
    Point(int a, int b):
        x(a),
        y(b)
    {}
};

class Data {
public:
    int id;
    Point point;
    Data(int i):
        id(i),
        point(0, 0)
    {}
};

int main(int argc, char const *argv[]) {
    Data *data[1000];
    Data **ptr = data;
    for (int i = 0; i < 1000; ++i) {
        ptr[i] = new Data(i);
        ptr[i]->point.x = i;
        ptr[i]->point.y = i+1;
    }

    for (int i = 0; i < 1000; ++i) {
        bool dump = argc > 1; // Set breakpoint here.
                              // Evaluate a couple of expressions (2*1000 = 2000 exprs):
                              // expr ptr[i]->point.x
                              // expr ptr[i]->point.y
    }
    return 0;
}

Fix a test that never compiled under -fmodules


#include <iostream>
#include "../../rltk/rltk.hpp"
#include <sstream>

bool tick(double duration_ms) {
	auto res = rltk::get_screen_size_px();
	std::stringstream ss;
	ss << "Frame duration: " << duration_ms << " ms. Resolution: " << res.first << "x" << res.second;
	rltk::cls_root();
	rltk::print_to_root(1, 1, ss.str());
	return false;
}

int main() {
	rltk::init(tick);
	rltk::run();
}

#include <iostream>
#include "../../rltk/rltk.hpp"
#include <sstream>

bool tick(double duration_ms) {
	auto res = rltk::get_screen_size_px();
	std::stringstream ss;
	ss << "Frame duration: " << duration_ms << " ms (" << (1000.0/duration_ms) << " FPS). Resolution: " << res.first << "x" << res.second;
	rltk::cls_root();
	rltk::print_to_root(1, 1, ss.str());
	return false;
}

int main() {
	rltk::init(tick);
	rltk::run();
}

Add simple FPS display to example.


#include <boost/optional.hpp>

#include "move.hh"
#include "../../../src/contents.hh"

namespace vick {
namespace move {

boost::optional< std::shared_ptr<change> > mvsot(contents& contents, boost::optional<int>) {
    contents.waiting_for_desired = false;
    contents.x = 0;
    for(auto x : contents.cont[contents.y]) {
        if(x == ' ' || x == '\t') contents.x++;
        else break;
    }
    return boost::none;
}

}
}

#include <boost/optional.hpp>

#include "move.hh"
#include "../../../src/contents.hh"

namespace vick {
namespace move {

boost::optional< std::shared_ptr<change> > mvsot(contents& contents, boost::optional<int>) {
    contents.waiting_for_desired = false;
    contents.x = 0;
    for(auto c : contents.cont[contents.y]) {
        if(c == ' ' || c == '\t') contents.x++;
        else break;
    }
    return boost::none;
}

}
}

Use iterator var for character as `c` instead of confusing `x` (using `contents.x` as well)


#include "nslog.h"

#include <node.h>
using namespace v8;

namespace {

Handle<Value> Log(const Arguments& args) {
  String::Utf8Value utf8_string(Local<String>::Cast(args[0]));
  nslog::Log(*utf8_string);
  return Undefined();
}

void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "log", Log);
}

}  // namespace

NODE_MODULE(nslog, Init)

#include "nslog.h"

#include "nan.h"
using namespace v8;

namespace {

NAN_METHOD(Log) {
  NanScope();

  String::Utf8Value utf8_string(Local<String>::Cast(args[0]));
  nslog::Log(*utf8_string);

  NanReturnUndefined();
}

void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "log", Log);
}

}  // namespace

NODE_MODULE(nslog, Init)

Use nan to wrap around V8 functions.


#include "logger.h"

Logger g_logger;

//------------------------------------------------------------------------------
LogViewer::LogViewer(QWidget* parent)
    : QPlainTextEdit(parent)
{ }

void LogViewer::connectLogger(Logger* logger)
{
    connect(logger, SIGNAL(logMessage(int, QString)),
            this, SLOT(appendLogMessage(int, QString)),
            Qt::QueuedConnection);
}

void LogViewer::appendLogMessage(int logLevel, QString msg)
{
    switch (logLevel)
    {
        case Logger::Warning:
            appendHtml("WARNING: " + msg);
            break;
        case Logger::Error:
            appendHtml("ERROR: " + msg);
            break;
        case Logger::Info:
            appendPlainText(msg);
            break;
    }
    ensureCursorVisible();
}

//------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, const QByteArray& s)
{
    out.write(s.constData(), s.size());
    return out;
}

std::ostream& operator<<(std::ostream& out, const QString& s)
{
    out << s.toUtf8();
    return out;
}

#include "logger.h"

Logger g_logger;

//------------------------------------------------------------------------------
LogViewer::LogViewer(QWidget* parent)
    : QPlainTextEdit(parent)
{ }

void LogViewer::connectLogger(Logger* logger)
{
    connect(logger, SIGNAL(logMessage(int, QString)),
            this, SLOT(appendLogMessage(int, QString)),
            Qt::QueuedConnection);
}

void LogViewer::appendLogMessage(int logLevel, QString msg)
{
    moveCursor(QTextCursor::End);
    switch (logLevel)
    {
        case Logger::Warning:
            appendHtml("WARNING: ");
            insertPlainText(msg);
            break;
        case Logger::Error:
            appendHtml("ERROR: ");
            insertPlainText(msg);
            break;
        case Logger::Info:
            appendPlainText(msg);
            break;
    }
    ensureCursorVisible();
}

//------------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& out, const QByteArray& s)
{
    out.write(s.constData(), s.size());
    return out;
}

std::ostream& operator<<(std::ostream& out, const QString& s)
{
    out << s.toUtf8();
    return out;
}

Fix logging highlighting, visibility, and newlines


#include "game/state/rules/city/vammotype.h"
#include "game/state/gamestate.h"

namespace OpenApoc
{

const UString &VAmmoType::getPrefix()
{
	static UString prefix = "VAMMOTYPE_";
	return prefix;
}

const UString &VAmmoType::getTypeName()
{
	static UString name = "VAmmoType";
	return name;
}

sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id)
{
	auto it = state.vehicle_ammo.find(id);
	if (it == state.vehicle_ammo.end())
	{
		LogError("No vammo type matching ID \"%s\"", id);
		return nullptr;
	}
	return it->second;
}
}

#include "game/state/rules/city/vammotype.h"
#include "game/state/gamestate.h"

namespace OpenApoc
{

const UString &VAmmoType::getPrefix()
{
	static UString prefix = "VEQUIPMENTAMMOTYPE_";
	return prefix;
}

const UString &VAmmoType::getTypeName()
{
	static UString name = "VAmmoType";
	return name;
}

sp<VAmmoType> VAmmoType::get(const GameState &state, const UString &id)
{
	auto it = state.vehicle_ammo.find(id);
	if (it == state.vehicle_ammo.end())
	{
		LogError("No vammo type matching ID \"%s\"", id);
		return nullptr;
	}
	return it->second;
}
}

Revert "Revert "Vehicle ammo prefix VAMMOTYPE_ to VEQUIPMENTAMMOTYPE_""


#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    auto&& now_pos = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.angle = std::move(now_pos); // now_pos is universal reference, but now use after code it. use move
    result.id = msg->id;
    pub.publish(std::move(result));
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    auto now_pos = driver->move(msg->id, ics::Angle::newRadian(msg->angle));
    result.angle = std::move(now_pos);
    result.id = msg->id;
    pub.publish(std::move(result));
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Update with convert unit to radian


#include "nodes/ui/float_info.h"

#include "elements/ui/float_info.h"

#include <QTableWidget>
#include <QGraphicsSimpleTextItem>

namespace nodes::ui {

FloatInfo::FloatInfo()
{
  QFont font{};
  font.setPixelSize(32);
  auto widget = new QGraphicsSimpleTextItem("0.0");
  widget->setFont(font);
  QPointF widgetPosition{};
  widgetPosition.rx() = -(widget->boundingRect().width() / 2.0);
  widgetPosition.ry() = -(widget->boundingRect().height() / 2.0);
  widget->setPos(widgetPosition);
  setCentralWidget(widget);

  m_info = widget;
}

void FloatInfo::refreshCentralWidget()
{
  if (!m_element || !m_element->inputs()[0].value) return;
  float const value{ std::get<float>(*m_element->inputs()[0].value) };
  m_info->setText(QString::number(value, 'f', 6));
}

void FloatInfo::showProperties()
{
  showCommonProperties();
  showInputsProperties();
  showOutputsProperties();
}

} // namespace nodes::ui

#include "nodes/ui/float_info.h"

#include "elements/ui/float_info.h"

#include <QTableWidget>
#include <QGraphicsSimpleTextItem>

namespace nodes::ui {

FloatInfo::FloatInfo()
{
  QFont font{};
  font.setPixelSize(32);
  auto widget = new QGraphicsSimpleTextItem("0.0");
  widget->setFont(font);
  QPointF widgetPosition{};
  widgetPosition.rx() = -(widget->boundingRect().width() / 2.0);
  widgetPosition.ry() = -(widget->boundingRect().height() / 2.0);
  widget->setPos(widgetPosition);
  setCentralWidget(widget);

  m_info = widget;
}

void FloatInfo::refreshCentralWidget()
{
  if (!m_element || !m_element->inputs()[0].value) return;
  float const value{ std::get<float>(*m_element->inputs()[0].value) };
  m_info->setText(QString::number(value, 'f', 2));
}

void FloatInfo::showProperties()
{
  showCommonProperties();
  showInputsProperties();
  showOutputsProperties();
}

} // namespace nodes::ui

Set float precision to 2 in FloatInfo