//
// Created by monty on 26/09/16.
//
#include <string>
#include <cstdarg>

#ifdef __ANDROID__

#include <android/log.h>

#else
#include <cstdio>
#endif

#include "Logger.h"

namespace odb {

    void doLog(const char *format, va_list args) {
        char buffer[255];
        std::vsnprintf(buffer, 255, format, args);

#ifdef __ANDROID__
        __android_log_print(ANDROID_LOG_INFO, "Logger::log", "%s", buffer);
#else
        std::printf( "%s\n", buffer );
#endif

    }

    void Logger::log(const char *format, ...) {

        va_list args;
        va_start(args, format);

        doLog(format, args);
        va_end(args);
    }

    void Logger::log(std::string format, ...) {
        va_list args;
        va_start(args, format);
        auto fmt = format.c_str();
        doLog(fmt, args);
        va_end(args);
    }
}

//
// Created by monty on 26/09/16.
//
#include <string>
#include <cstdarg>
#include <cstring>

#ifdef __ANDROID__

#include <android/log.h>

#else
#include <cstdio>
#endif

#include "Logger.h"

namespace odb {

    void doLog(const char *format, va_list args) {
        char buffer[255];
        return;
        memset(&buffer[0], 0, 255);
        std::vsnprintf(buffer, 255, format, args);

#ifdef __ANDROID__
        __android_log_print(ANDROID_LOG_INFO, "Logger::log", "%s", buffer);
#else
        std::printf( "%s\n", buffer );
#endif

    }

    void Logger::log(const char *format, ...) {

        va_list args;
        va_start(args, format);

        doLog(format, args);
        va_end(args);
    }

    void Logger::log(std::string format, ...) {
        va_list args;
        va_start(args, format);
        auto fmt = format.c_str();
        doLog(fmt, args);
        va_end(args);
    }
}

Fix compilation error on OSX


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

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

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

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

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

// Started failing with r29947. WebKit merge 49961:49992.
IN_PROC_BROWSER_TEST_F(DISABLED_ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

Disable test failing since r29947.


// Copyright 2014 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 "components/translate/core/common/language_detection_details.h"

namespace translate {

LanguageDetectionDetails::LanguageDetectionDetails() {}

LanguageDetectionDetails::~LanguageDetectionDetails() {}

}  // namespace translate

// Copyright 2014 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 "components/translate/core/common/language_detection_details.h"

namespace translate {

LanguageDetectionDetails::LanguageDetectionDetails()
    : is_cld_reliable(false) {
}

LanguageDetectionDetails::~LanguageDetectionDetails() {}

}  // namespace translate

Fix uninit memory access in TranslateManagerRenderViewHostTests.


#include "powerdhcp.hh"

namespace PowerDHCP {
  Logging theL;

  pthread_rwlock_t Logger::d_lock = PTHREAD_RWLOCK_INITIALIZER;

  const char* Logger::LEVEL[] = {
      "DEBUG",
      "INFO",
      "NOTICE",
      "WARNING",
      "ERROR",
      "CRITICAL"
  };

  std::string stringerror() {
    std::string ret;
    char *buf = new char[1024];
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! defined(_GNU_SOURCE)
    if (strerror_r(errno, buf, 1024)==0)
      ret.assign(buf);
#elif defined(_GNU_SOURCE)
    if (strerror_r(errno, buf, 1024))
      ret.assign(buf);
#else
    #error "PowerDHCP::stringerror is not threadsafe on this system"
#endif
    delete [] buf;
    return ret;
  }
};

#include "powerdhcp.hh"

namespace PowerDHCP {
  Logger theL;

  pthread_rwlock_t Logger::d_lock = PTHREAD_RWLOCK_INITIALIZER;

  const char* Logger::LEVEL[] = {
      "DEBUG",
      "INFO",
      "NOTICE",
      "WARNING",
      "ERROR",
      "CRITICAL"
  };

  std::string stringerror() {
    std::string ret;
    char *buf = new char[1024];
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! defined(_GNU_SOURCE)
    if (strerror_r(errno, buf, 1024)==0)
      ret.assign(buf);
#elif defined(_GNU_SOURCE)
    if (strerror_r(errno, buf, 1024))
      ret.assign(buf);
#else
    #warning "PowerDHCP::stringerror might not be threadsafe on this system"
    ret.assign(strerror(errno));
#endif
    delete [] buf;
    return ret;
  }
};

Use correct name for logger. Do not fail if sterror_r is not there


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

#include "instance.h"
#include "query.h"

extern "C" {

device_instance get_device_instance(void* platform_data) {
    auto instance = query::getDeviceInstance(platform_data);

    // Reserialize the instance with the ID field.
    device_instance out;
    out.size = instance->ByteSize();
    out.data = new uint8_t[out.size];
    instance->SerializeToArray(out.data, out.size);

    delete instance;

    return out;
}

const char* get_device_instance_error() {
    return query::contextError();
}

void free_device_instance(device_instance di) {
    delete[] di.data;
}

} // extern "C"

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

#include "instance.h"
#include "query.h"

extern "C" {

device_instance get_device_instance(void* platform_data) {
    device_instance out = {};

    auto instance = query::getDeviceInstance(platform_data);
    if (!instance) {
        return out;
    }

    // Reserialize the instance with the ID field.
    out.size = instance->ByteSize();
    out.data = new uint8_t[out.size];
    instance->SerializeToArray(out.data, out.size);

    delete instance;

    return out;
}

const char* get_device_instance_error() {
    return query::contextError();
}

void free_device_instance(device_instance di) {
    delete[] di.data;
}

} // extern "C"

Fix crash in deviceinfo query.


#include "PythonModule.h"

//#include "agent_finder_api.h"

using namespace opencog;

DECLARE_MODULE(PythonModule);

PythonModule::PythonModule() : Module()
{
    logger().info("[PythonModule] constructor");
    do_load_py_register();
}

PythonModule::~PythonModule()
{
    logger().info("[PythonModule] destructor");
    do_load_py_unregister();
}

void PythonModule::init()
{
    logger().info("[PythonModule] init");
}

std::string PythonModule::do_load_py(Request *dummy, std::list<std::string> args)
{
    //AtomSpace *space = CogServer::getAtomSpace();
    if (args.size() == 0) return "Please specify Python module to load.";
    PyObject* py_module = load_module(args.front());
    // TODO save the py_module somewhere
    // ...
    // TODO register the agents
    //CogServer& cogserver = static_cast<CogServer&>(server());
    // How do we initialise a mind agent with a factory that will
    // load with given Python class
    //cogserver.registerAgent(PyMindAgent::info().id, &forgettingFactory);
    // TODO return info on what requests and mindagents were found
    return "Loaded python module";
}

#include "PythonModule.h"

#include "agent_finder_api.h"

using namespace opencog;

DECLARE_MODULE(PythonModule);

PythonModule::PythonModule() : Module()
{
    logger().info("[PythonModule] constructor");
    do_load_py_register();
}

PythonModule::~PythonModule()
{
    logger().info("[PythonModule] destructor");
    do_load_py_unregister();
}

void PythonModule::init()
{
    logger().info("[PythonModule] init");
}

std::string PythonModule::do_load_py(Request *dummy, std::list<std::string> args)
{
    //AtomSpace *space = CogServer::getAtomSpace();
    if (args.size() == 0) return "Please specify Python module to load.";
    PyObject* py_module = load_module(args.front());
    // TODO save the py_module somewhere
    // ...
    // TODO register the agents
    //CogServer& cogserver = static_cast<CogServer&>(server());
    // How do we initialise a mind agent with a factory that will
    // load with given Python class
    //cogserver.registerAgent(PyMindAgent::info().id, &forgettingFactory);
    // TODO return info on what requests and mindagents were found
    return "Loaded python module";
}

Fix things so that they don't break the compile


#include "JobTree.h"
#include "plow.h"

#include <QStringList>
#include <QString>

namespace Plow { namespace Gui {

JobTree::JobTree(QWidget *parent) : QWidget(parent)
{
    layout = new QVBoxLayout(this);

    QStringList header;
    header << "Job" << "Cores" << "Max" << "Waiting";

    treeWidget = new QTreeWidget;
    treeWidget->setHeaderLabels(header);
    treeWidget->setColumnCount(4);

    layout->addWidget(treeWidget);
}

void JobTree::updateJobs()
{
    PlowClient* client = getClient();

    std::vector<JobT> jobs;
    JobFilterT filter;

    std::vector<JobState::type> states;
    states.push_back(JobState::RUNNING);
    filter.__set_states(states);

    client->getJobs(jobs, filter);

    for (std::vector<JobT>::iterator i = jobs.begin();
                                     i != jobs.end();
                                     ++i)
    {
        QStringList data;
        data << QString::fromStdString(i->name)
             << QString::number(i->runningCoreCount)
             << QString::number(i->maxCores)
             << QString::number(i->waitingTaskCount);

        QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, data);
        treeWidget->insertTopLevelItem(0, item);
    }
}

}
}

#include "JobTree.h"
#include "plow.h"

#include <QStringList>
#include <QString>

namespace Plow { namespace Gui {

JobTree::JobTree(QWidget *parent) : QWidget(parent)
{
    layout = new QVBoxLayout(this);

    QStringList header;
    header << "Job" << "Cores" << "Max" << "Waiting";

    treeWidget = new QTreeWidget;
    treeWidget->setHeaderLabels(header);
    treeWidget->setColumnCount(4);
    treeWidget->setColumnWidth(0, 300);

    layout->addWidget(treeWidget);

}

void JobTree::updateJobs()
{
    PlowClient* client = getClient();

    std::vector<JobT> jobs;
    JobFilterT filter;

    std::vector<JobState::type> states;
    states.push_back(JobState::RUNNING);
    filter.__set_states(states);

    client->getJobs(jobs, filter);

    for (std::vector<JobT>::iterator i = jobs.begin();
                                     i != jobs.end();
                                     ++i)
    {
        QStringList data;
        data << QString::fromStdString(i->name)
             << QString::number(i->runningCoreCount)
             << QString::number(i->maxCores)
             << QString::number(i->waitingTaskCount);

        QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, data);
        treeWidget->insertTopLevelItem(0, item);
    }
}

} // Gui
} // Plow

Expand the job name column.


#include <ngraph.h>
#include <PCU.h>
#include <engpar_support.h>
#include "buildGraphs.h"
#include "../partition/Diffusive/engpar_diffusive_input.h"
#include "../partition/Diffusive/src/engpar_queue.h"
int main(int argc, char* argv[]) {
  MPI_Init(&argc,&argv);
  EnGPar_Initialize();

  agi::Ngraph* g;
  if (argc==1)
    if (PCU_Comm_Peers()==2)
      g = buildDisconnected2Graph();
    else
      g=buildHyperGraphLine();
  else {
    g = agi::createEmptyGraph();
    g->loadFromFile(argv[1]);
  }
  PCU_Barrier();

  engpar::Input* input = engpar::createDiffusiveInput(g,0);
  engpar::DiffusiveInput* inp = static_cast<engpar::DiffusiveInput*>(input);
  engpar::Queue* q = engpar::createDistanceQueue(inp);
  delete q;
  delete input;

  if (g->hasCoords()) {
    std::string filename = "graph";
    agi::writeVTK(g,filename.c_str());
  }

  agi::destroyGraph(g);

  PCU_Barrier();
  if (!PCU_Comm_Self())
    printf("All Tests Passed\n");

  EnGPar_Finalize();
  MPI_Finalize();

  return 0;
}

#include <ngraph.h>
#include <PCU.h>
#include <engpar_support.h>
#include "buildGraphs.h"
#include "../partition/Diffusive/engpar_diffusive_input.h"
#include "../partition/Diffusive/src/engpar_queue.h"
int main(int argc, char* argv[]) {
  MPI_Init(&argc,&argv);
  EnGPar_Initialize();

  agi::Ngraph* g;
  if (argc==1)
    if (PCU_Comm_Peers()==2)
      g = buildDisconnected2Graph();
    else
      g=buildHyperGraphLine();
  else {
    g = agi::createEmptyGraph();
    g->loadFromFile(argv[1]);
  }
  PCU_Barrier();

  engpar::Input* input = engpar::createDiffusiveInput(g,0);
  engpar::DiffusiveInput* inp = static_cast<engpar::DiffusiveInput*>(input);
  engpar::Queue* q = engpar::createDistanceQueue(inp);
  delete q;
  delete input;

  agi::destroyGraph(g);

  PCU_Barrier();
  if (!PCU_Comm_Self())
    printf("All Tests Passed\n");

  EnGPar_Finalize();
  MPI_Finalize();

  return 0;
}

Remove rendering from distance queue tests to fix aero tests


//===-- WebAssemblyTargetInfo.cpp - WebAssembly Target Implementation -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file registers the WebAssembly target.
///
//===----------------------------------------------------------------------===//

#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;

#define DEBUG_TYPE "wasm-target-info"

Target llvm::getTheWebAssemblyTarget32();
Target llvm::getTheWebAssemblyTarget64();

extern "C" void LLVMInitializeWebAssemblyTargetInfo() {
  RegisterTarget<Triple::wasm32> X(getTheWebAssemblyTarget32(), "wasm32",
                                   "WebAssembly 32-bit");
  RegisterTarget<Triple::wasm64> Y(getTheWebAssemblyTarget64(), "wasm64",
                                   "WebAssembly 64-bit");
}

//===-- WebAssemblyTargetInfo.cpp - WebAssembly Target Implementation -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file registers the WebAssembly target.
///
//===----------------------------------------------------------------------===//

#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;

#define DEBUG_TYPE "wasm-target-info"

Target &llvm::getTheWebAssemblyTarget32() {
  static Target TheWebAssemblyTarget32;
  return TheWebAssemblyTarget32;
}
Target &llvm::getTheWebAssemblyTarget64() {
  static Target TheWebAssemblyTarget64;
  return TheWebAssemblyTarget64;
}

extern "C" void LLVMInitializeWebAssemblyTargetInfo() {
  RegisterTarget<Triple::wasm32> X(getTheWebAssemblyTarget32(), "wasm32",
                                   "WebAssembly 32-bit");
  RegisterTarget<Triple::wasm64> Y(getTheWebAssemblyTarget64(), "wasm64",
                                   "WebAssembly 64-bit");
}

Fix WebAssembly build after r283702.


/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <minizinc/allocator.hh>

namespace MiniZinc {

  const size_t
  BlockAllocator::blockSize;

  void
  BlockAllocator::allocateBlock(size_t bs) {
    bs = std::max(bs,blockSize);
    MemoryBlock* newBlock = static_cast<MemoryBlock*>(::malloc(bs));
    newBlock->size = bs;
    newBlock->next = curBlock;
    curBlock = newBlock;
    curP = curBlock->data;
    endP = curBlock->data+bs;
  }

  void*
  BlockAllocator::alloc(size_t size) {
    /// Align to word boundary
    size += ((8 - (size & 7)) & 7);
    if (curP + size >= endP)
      allocateBlock(size);
    char* ret = curP;
    curP += size;
    return ret;
  }

  BlockAllocator::~BlockAllocator(void) {
    while (curBlock) {
      MemoryBlock* n = curBlock->next;
      ::free(curBlock);
      curBlock = n;
    }
  }

}

/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <minizinc/allocator.hh>

namespace MiniZinc {

  const size_t
  BlockAllocator::blockSize;

  void
  BlockAllocator::allocateBlock(size_t bs) {
    bs = std::max(bs,blockSize);
    MemoryBlock* newBlock =
      static_cast<MemoryBlock*>(::malloc(sizeof(MemoryBlock)+bs));
    newBlock->size = bs;
    newBlock->next = curBlock;
    curBlock = newBlock;
    curP = curBlock->data;
    endP = curBlock->data+bs;
  }

  void*
  BlockAllocator::alloc(size_t size) {
    /// Align to word boundary
    size += ((8 - (size & 7)) & 7);
    if (curP + size >= endP)
      allocateBlock(size);
    char* ret = curP;
    curP += size;
    return ret;
  }

  BlockAllocator::~BlockAllocator(void) {
    while (curBlock) {
      MemoryBlock* n = curBlock->next;
      ::free(curBlock);
      curBlock = n;
    }
  }

}

Fix basic allocation of memory blocks


/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
 * Implementation for OFLogHandler class.
 *
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

/* This must be included before anything else */
#if HAVE_CONFIG_H
#  include <config.h>
#endif

#include "opflex/logging/OFLogHandler.h"
#include "opflex/logging/StdOutLogHandler.h"

namespace opflex {
namespace logging {

static OFLogHandler* volatile activeHandler = NULL;

OFLogHandler::OFLogHandler(Level logLevel) : logLevel_(logLevel) { };
OFLogHandler::~OFLogHandler() { }

void OFLogHandler::registerHandler(OFLogHandler& handler) {
    activeHandler = &handler;
}

OFLogHandler* OFLogHandler::getHandler() {
    static StdOutLogHandler defaultHandler(INFO);
    if (activeHandler) return activeHandler;
    return &defaultHandler;
}

bool OFLogHandler::shouldEmit(const Level level) {
    return level >= logLevel_;
}

} /* namespace logging */
} /* namespace opflex */

/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
 * Implementation for OFLogHandler class.
 *
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

/* This must be included before anything else */
#if HAVE_CONFIG_H
#  include <config.h>
#endif

#include <boost/atomic.hpp>
#include "opflex/logging/OFLogHandler.h"
#include "opflex/logging/StdOutLogHandler.h"

namespace opflex {
namespace logging {

static boost::atomic<OFLogHandler*> activeHandler(NULL);

OFLogHandler::OFLogHandler(Level logLevel) : logLevel_(logLevel) { };
OFLogHandler::~OFLogHandler() { }

void OFLogHandler::registerHandler(OFLogHandler& handler) {
    activeHandler = &handler;
}

OFLogHandler* OFLogHandler::getHandler() {
    static StdOutLogHandler defaultHandler(INFO);
    if (activeHandler) return activeHandler;
    return &defaultHandler;
}

bool OFLogHandler::shouldEmit(const Level level) {
    return level >= logLevel_;
}

} /* namespace logging */
} /* namespace opflex */

Address last TSAN issue exposed by libopflex unit tests


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <QDebug>

#include <Qt>
#include "QZXingFilter.h"

#if defined(Q_OS_IOS)
/// Reference for iOS entry point:
/// http://stackoverflow.com/questions/25353686/you-are-creating-qapplication-before-calling-uiapplicationmain-error-on-ios
extern "C" int qtmn(int argc, char **argv)
#else
int main(int argc, char *argv[])
#endif
{
    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    qmlRegisterType<QZXingFilter>("QZXing", 2, 3, "QZXingFilter");
    qmlRegisterType<QZXing>("QZXing", 2, 3, "QZXing");

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <QDebug>

#include <Qt>
#include "QZXingFilter.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    qmlRegisterType<QZXingFilter>("QZXing", 2, 3, "QZXingFilter");
    qmlRegisterType<QZXing>("QZXing", 2, 3, "QZXing");

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}

Fix linking on recent Qt for iOS


#include "OneWire.h"

static OneWireMock* gOneWireMock = NULL;

OneWireMock* oneWireMockInstance() {
    if( !gOneWireMock ) {
        gOneWireMock = new OneWireMock();
    }

    return gOneWireMock;
}

void releaseOneWireMock() {
    if( gOneWireMock ) {
        delete gOneWireMock;
        gOneWireMock = NULL;
    }
}

bool OneWire::search( uint8_t* buf ) {
    assert( gOneWireMock != NULL );
    return gOneWireMock->search(buf);
}

void OneWire::reset_search( void ) {

}

#include "OneWire.h"

static OneWireMock* gOneWireMock = NULL;

OneWireMock* oneWireMockInstance() {
    if( !gOneWireMock ) {
        gOneWireMock = new OneWireMock();
    }

    return gOneWireMock;
}

void releaseOneWireMock() {
    if( gOneWireMock ) {
        delete gOneWireMock;
        gOneWireMock = NULL;
    }
}

bool OneWire::search( uint8_t* buf ) {
    assert( gOneWireMock != NULL );
    return gOneWireMock->search( buf );
}

void OneWire::reset_search( void ) {
    assert( gOneWireMock != NULL );
    gOneWireMock->reset_search( );
}

Fix spacing + llamada a reset_search del mock


#include "Game/CannonBall.h"

CannonBall::CannonBall(const QPixmap & pixmap, QVector2D velocity, QVector2D position, Player owner, QGraphicsItem * parent) : Entity(pixmap, owner, parent), m_initialVelocity(velocity), m_initialPosition(position), m_gravity(9.8), m_timeSinceShot(0)
{
	setScale(0.1);
	setPos(m_initialPosition.toPointF());
}

void CannonBall::updateEntity(double deltaTime)
{
	m_timeSinceShot += deltaTime/1000.0;

	double x = m_initialPosition.x() + m_initialVelocity.x() * m_timeSinceShot;
	double y = m_initialPosition.y() - m_initialVelocity.y() * m_timeSinceShot + 0.5 * m_gravity * m_timeSinceShot * m_timeSinceShot;

	setPos(x, y);
}

#include "Game/CannonBall.h"

CannonBall::CannonBall(const QPixmap & pixmap, QVector2D velocity, QVector2D position, Player owner, QGraphicsItem * parent) : Entity(pixmap, owner, parent), m_initialVelocity(velocity), m_initialPosition(position), m_gravity(9.8), m_timeSinceShot(0)
{
	setScale(0.1);
	setPos(m_initialPosition.toPointF());
}

void CannonBall::updateEntity(double deltaTime)
{
    m_timeSinceShot += deltaTime/1000.0 * 2.0;

	double x = m_initialPosition.x() + m_initialVelocity.x() * m_timeSinceShot;
	double y = m_initialPosition.y() - m_initialVelocity.y() * m_timeSinceShot + 0.5 * m_gravity * m_timeSinceShot * m_timeSinceShot;

	setPos(x, y);
}

Make the ball go faster


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

#include "clang/Analysis/Analyses/Dominators.h"

using namespace clang;

template <>
void clang::CFGDominatorTreeImpl</*IsPostDom=*/true>::anchor() {}

template <>
void clang::CFGDominatorTreeImpl</*IsPostDom=*/false>::anchor() {}

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

#include "clang/Analysis/Analyses/Dominators.h"

namespace clang {

template <>
void CFGDominatorTreeImpl</*IsPostDom=*/true>::anchor() {}

template <>
void CFGDominatorTreeImpl</*IsPostDom=*/false>::anchor() {}

} // end of namespace clang

Make a buildbot using a buggy gcc happy


#include "mbed.h"
#include "test_env.h"

int main() {
    MBED_HOSTTEST_TIMEOUT(20);
    MBED_HOSTTEST_SELECT(serial_nc_rx_auto);
    MBED_HOSTTEST_DESCRIPTION(Serial NC RX);
    MBED_HOSTTEST_START("MBED_37");

    Serial *pc = new Serial(USBTX, USBRX);

    char c = pc->getc();

    delete pc;

    // This should be true
    if (c == 'E') {
      Serial *pc = new Serial(USBTX, NC);

      pc->printf("RX OK - Expected\r\n");

      c = pc->getc();

      // This should be false/not get here
      if (c == 'U') {
        pc->printf("RX OK - Unexpected\r\n");
      }

      delete pc;
    }

    while (1) {
    }
}

#include "mbed.h"
#include "test_env.h"

int main() {
    MBED_HOSTTEST_TIMEOUT(20);
    MBED_HOSTTEST_SELECT(serial_nc_rx_auto);
    MBED_HOSTTEST_DESCRIPTION(Serial NC RX);
    MBED_HOSTTEST_START("MBED_37");

    Serial *pc = new Serial(NC, USBRX);

    char c = pc->getc();

    delete pc;

    // This should be true
    if (c == 'E') {
      Serial *pc = new Serial(USBTX, NC);

      pc->printf("RX OK - Expected\r\n");

      c = pc->getc();

      // This should be false/not get here
      if (c == 'U') {
        pc->printf("RX OK - Unexpected\r\n");
      }

      delete pc;
    }

    while (1) {
    }
}

Revert "corrected serial port definition of rx test"


#include <linux/limits.h>
#include <stdlib.h>
#include <sys/stat.h>

#include "MagpieString.h"
#include "Path.h"

namespace magpie
{
  namespace path
  {
    char separator() { return '/'; }

    gc<String> real(gc<String> path)
    {
      char absolute[PATH_MAX];
      realpath(path->cString(), absolute);
      return String::create(absolute);
    }

    bool fileExists(gc<String> path)
    {
      // If we can stat it, it exists.
      struct stat dummy;
      return stat(path->cString(), &dummy) == 0;
    }
  }
}

// TODO(bob): PATH_MAX isn't actually part of POSIX. Need to do something
// smarter here.
#ifdef __linux__
  #include <linux/limits.h>
#else
#include <limits.h>
#endif
#include <stdlib.h>
#include <sys/stat.h>

#include "MagpieString.h"
#include "Path.h"

namespace magpie
{
  namespace path
  {
    char separator() { return '/'; }

    gc<String> real(gc<String> path)
    {
      char absolute[PATH_MAX];
      realpath(path->cString(), absolute);
      return String::create(absolute);
    }

    bool fileExists(gc<String> path)
    {
      // If we can stat it, it exists.
      struct stat dummy;
      return stat(path->cString(), &dummy) == 0;
    }
  }
}

Use correct header to get PATH_MAX on linux/mac.


#include "filesystem.h"

#include "remotefileops.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>

#define DEBUG_FILESYSTEM 0

struct FileSystemPrivate
{
    FileSystemPrivate(FileOps* ops)
    {
        m_fileOps = ops;
    }

    FileOps* m_fileOps;
};

FileSystem::FileSystem(FileOps* ops)
    : QThread(0)
    , d(new FileSystemPrivate(ops))
{
}

FileSystem::~FileSystem()
{
    delete d;
}

void FileSystem::stop()
{
    QThread::exit(0);
}

void FileSystem::run()
{
    exec();
}

#include "filesystem.h"

#include "remotefileops.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>

#define DEBUG_FILESYSTEM 0

struct FileSystemPrivate
{
    FileSystemPrivate(FileOps* ops)
    {
        m_fileOps = ops;
    }

    FileOps* m_fileOps;
};

FileSystem::FileSystem(FileOps* ops)
    : QThread(0)
    , d(new FileSystemPrivate(ops))
{
}

FileSystem::~FileSystem()
{
    stop();
    delete d;
}

void FileSystem::stop()
{
    exit(0);
    if (!wait(5000)) {
        terminate();
        wait();
    }
}

void FileSystem::run()
{
    exec();
}

Exit properly from the dokan filesystem thread.


#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QQmlFileSelector>

#include "screenvalues.h"

static QObject *screen_values_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine)
    Q_UNUSED(scriptEngine)

    return new ScreenValues();
}

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

    QQmlApplicationEngine engine;

    QQmlFileSelector* selector = new QQmlFileSelector(&engine);

    Q_UNUSED(selector)

    engine.addImportPath("qrc:/");

    qmlRegisterSingletonType<ScreenValues>("QtWorldSummit", 1, 5, "ScreenValues", screen_values_provider);

    engine.load(QUrl("qrc:/qml/qml/main.qml"));

    return app.exec();
}

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QQmlFileSelector>

#include "screenvalues.h"

static QObject *screen_values_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine)
    Q_UNUSED(scriptEngine)

    return new ScreenValues();
}

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

    QQmlApplicationEngine engine;

    QQmlFileSelector* selector = new QQmlFileSelector(&engine);

    QStringList extraSelectors;

#ifdef Q_OS_ANDROID
    ScreenValues *sv = new ScreenValues();

    if (sv->isTablet())
        extraSelectors << "android_tablet";

    delete sv;
#endif

    if (!extraSelectors.isEmpty())
        selector->setExtraSelectors(extraSelectors);

    engine.addImportPath("qrc:/");

    qmlRegisterSingletonType<ScreenValues>("QtWorldSummit", 1, 5, "ScreenValues", screen_values_provider);

    engine.load(QUrl("qrc:/qml/qml/main.qml"));

    return app.exec();
}

Add selector for Android tablet


// Copyright (c) 2016-2019 The Gulden developers
// Authored by: Willem de Jonge (willem@isnapp.nl)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING

#include "extendwitnessdialog.h"
#include <qt/_Gulden/forms/ui_extendwitnessdialog.h>

#include "wallet/wallet.h"
#include "GuldenGUI.h"

#define LOG_QT_METHOD LogPrint(BCLog::QT, "%s\n", __PRETTY_FUNCTION__)

ExtendWitnessDialog::ExtendWitnessDialog(const QStyle *_platformStyle, QWidget *parent)
: QFrame( parent )
, ui( new Ui::ExtendWitnessDialog )
, platformStyle( _platformStyle )
{
    ui->setupUi(this);

    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancelClicked()));
    connect(ui->extendButton, SIGNAL(clicked()), this, SLOT(extendClicked()));
}

ExtendWitnessDialog::~ExtendWitnessDialog()
{
    delete ui;
}

void ExtendWitnessDialog::cancelClicked()
{
    LOG_QT_METHOD;

    Q_EMIT dismiss(this);
}

void ExtendWitnessDialog::extendClicked()
{
    LOG_QT_METHOD;

    Q_EMIT dismiss(this);
}

// Copyright (c) 2016-2019 The Gulden developers
// Authored by: Willem de Jonge (willem@isnapp.nl)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING

#include "extendwitnessdialog.h"
#include <qt/_Gulden/forms/ui_extendwitnessdialog.h>

#include "wallet/wallet.h"
#include "gui.h"

#define LOG_QT_METHOD LogPrint(BCLog::QT, "%s\n", __PRETTY_FUNCTION__)

ExtendWitnessDialog::ExtendWitnessDialog(const QStyle *_platformStyle, QWidget *parent)
: QFrame( parent )
, ui( new Ui::ExtendWitnessDialog )
, platformStyle( _platformStyle )
{
    ui->setupUi(this);

    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(cancelClicked()));
    connect(ui->extendButton, SIGNAL(clicked()), this, SLOT(extendClicked()));
}

ExtendWitnessDialog::~ExtendWitnessDialog()
{
    delete ui;
}

void ExtendWitnessDialog::cancelClicked()
{
    LOG_QT_METHOD;

    Q_EMIT dismiss(this);
}

void ExtendWitnessDialog::extendClicked()
{
    LOG_QT_METHOD;

    if(QDialog::Accepted == GUI::createDialog(this, "Confirm extending", tr("Extend"), tr("Cancel"), 600, 360, "ExtendWitnessConfirmationDialog")->exec())
    {
        // TODO: execute extend and dismiss dialog on succes, or alert user on failure
        Q_EMIT dismiss(this);
    }
}

Extend witness ask user confirmation


#include "app.hpp"
#include "gui.hpp"

namespace rack {

void RackScrollWidget::step() {
	Vec pos = gRackWidget->lastMousePos;
	// Scroll rack if dragging cable near the edge of the screen
	if (gRackWidget->wireContainer->activeWire) {
		float margin = 20.0;
		float speed = 15.0;
		if (pos.x <= margin)
			offset.x -= speed;
		if (pos.x >= box.size.x - margin)
			offset.x += speed;
		if (pos.y <= margin)
			offset.y -= speed;
		if (pos.y >= box.size.y - margin)
			offset.y += speed;
	}
	ScrollWidget::step();
}

} // namespace rack

#include "app.hpp"
#include "gui.hpp"

namespace rack {

void RackScrollWidget::step() {
	Vec pos = gMousePos;
	Rect viewport = getViewport(box.zeroPos());
	// Scroll rack if dragging cable near the edge of the screen
	if (gRackWidget->wireContainer->activeWire) {
		float margin = 20.0;
		float speed = 15.0;
		if (pos.x <= viewport.pos.x + margin)
			offset.x -= speed;
		if (pos.x >= viewport.pos.x + viewport.size.x - margin)
			offset.x += speed;
		if (pos.y <= viewport.pos.y + margin)
			offset.y -= speed;
		if (pos.y >= viewport.pos.y + viewport.size.y - margin)
			offset.y += speed;
	}
	ScrollWidget::step();
}

} // namespace rack

Fix autoscrolling when dragging near edge of rack


#include "SavePreferences.h"

SavePreferences::SavePreferences()
{
}

// Called just before this Command runs the first time
void SavePreferences::Initialize()
{
	Preferences::GetInstance()->Save();
}

// Called repeatedly when this Command is scheduled to run
void SavePreferences::Execute()
{
}

// Make this return true when this Command no longer needs to run execute()
bool SavePreferences::IsFinished()
{
	return true;
}

// Called once after isFinished returns true
void SavePreferences::End()
{
}

// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void SavePreferences::Interrupted()
{
	End();
}

#include "SavePreferences.h"

SavePreferences::SavePreferences()
{
	this->SetRunWhenDisabled(true);
}

// Called just before this Command runs the first time
void SavePreferences::Initialize()
{
	Preferences::GetInstance()->Save();
}

// Called repeatedly when this Command is scheduled to run
void SavePreferences::Execute()
{
}

// Make this return true when this Command no longer needs to run execute()
bool SavePreferences::IsFinished()
{
	return true;
}

// Called once after isFinished returns true
void SavePreferences::End()
{
}

// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void SavePreferences::Interrupted()
{
	End();
}

Save Prefs can run when disabled


#include "SVGImage.h"

#define NANOSVG_IMPLEMENTATION
#include <nanosvg.h>
#include <nanovg.h>
// XXX This is bad, but easy.
#define NANOVG_GL_IMPLEMENTATION
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2platform.h>
#include <nanovg_gl.h>
#include <nanovg.c>

SVGImage::SVGImage() : _nanoSvgImage(nullptr) {
}

SVGImage::SVGImage(const boost::filesystem::path &path) : SVGImage() {
    open(path);
}

SVGImage::~SVGImage() {
    if (_nanoSvgImage) {
	::nsvgDelete(_nanoSvgImage);
    }
    _nanoSvgImage = nullptr;
}

bool SVGImage::open(const boost::filesystem::path &path) {
    _nanoSvgImage = ::nsvgParseFromFile(path.string().c_str(), "", 72.f);
    return (_nanoSvgImage->width > 0.0f && _nanoSvgImage->height > 0.0 && _nanoSvgImage->shapes);
}

void SVGImage::draw() {
}

#include "SVGImage.h"

#define NANOSVG_IMPLEMENTATION
#include <nanosvg.h>
#include <nanovg.h>
// XXX This is bad, but easy.
#define NANOVG_GL_IMPLEMENTATION
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2platform.h>
#include <nanovg_gl.h>
#include <nanovg.c>

SVGImage::SVGImage() : _nanoSvgImage(nullptr) {
}

SVGImage::SVGImage(const boost::filesystem::path &path) : SVGImage() {
    open(path);
}

SVGImage::~SVGImage() {
    if (_nanoSvgImage) {
	::nsvgDelete(_nanoSvgImage);
    }
    _nanoSvgImage = nullptr;
}

bool SVGImage::open(const boost::filesystem::path &path) {
    _nanoSvgImage = ::nsvgParseFromFile(path.string().c_str(), "", 72.f);
    return (_nanoSvgImage->width > 0.0f && _nanoSvgImage->height > 0.0 && _nanoSvgImage->shapes);
}

void SVGImage::draw() {
    if (!_nanoSvgImage)
	return;
}

Check to see if there's an image before drawing starts.


//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield
// Distributed under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation.
//
// All software using osgSim must be GPL'd or excempted via the
// purchase of the Open Scene Graph Professional License (OSGPL)
// for further information contact robert@openscenegraph.com.

#include <osgSim/BlinkSequence>

#include <stdlib.h>

using namespace osgSim;

BlinkSequence::BlinkSequence():
    Referenced(),
    _pulsePeriod(0.0),
    _phaseShift(0.0),
    _pulseData(),
    _sequenceGroup(0) {}

BlinkSequence::BlinkSequence(const BlinkSequence& bs):
    Referenced(),
    _pulsePeriod(bs._pulsePeriod),
    _phaseShift(bs._phaseShift),
    _pulseData(bs._pulseData),
    _sequenceGroup(bs._sequenceGroup) {}

BlinkSequence::SequenceGroup::SequenceGroup():
    Referenced()
{
    // set a random base time between 0 and 1000.0
    _baseTime = ((double)rand()/(double)RAND_MAX)*1000.0;
}

BlinkSequence::SequenceGroup::SequenceGroup(double baseTime):
    Referenced(),
    _baseTime(baseTime) {}

//C++ header - Open Scene Graph Simulation - Copyright (C) 1998-2002 Robert Osfield
// Distributed under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation.
//
// All software using osgSim must be GPL'd or excempted via the
// purchase of the Open Scene Graph Professional License (OSGPL)
// for further information contact robert@openscenegraph.com.

#include <osgSim/BlinkSequence>

#include <stdlib.h>

using namespace osgSim;

BlinkSequence::BlinkSequence():
    _pulsePeriod(0.0),
    _phaseShift(0.0),
    _pulseData(),
    _sequenceGroup(0)
{
}

BlinkSequence::BlinkSequence(const BlinkSequence& bs):
    _pulsePeriod(bs._pulsePeriod),
    _phaseShift(bs._phaseShift),
    _pulseData(bs._pulseData),
    _sequenceGroup(bs._sequenceGroup)
{
}

BlinkSequence::SequenceGroup::SequenceGroup()
{
    // set a random base time between 0 and 1000.0
    _baseTime = ((double)rand()/(double)RAND_MAX)*1000.0;
}

BlinkSequence::SequenceGroup::SequenceGroup(double baseTime):
    _baseTime(baseTime)
{
}

Fix for compile problems under IRIX.


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

// <functional>

// See https://llvm.org/bugs/show_bug.cgi?id=20002

#include <functional>
#include <type_traits>

using Fn = std::function<void()>;
struct S : Fn { using function::function; };

int main() {
    S f1( Fn{} );
    S f2(std::allocator_arg, std::allocator<void>{}, Fn{});
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

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

// <functional>

// See https://llvm.org/bugs/show_bug.cgi?id=20002

#include <functional>
#include <type_traits>

using Fn = std::function<void()>;
struct S : public std::function<void()> { using function::function; };

int main() {
    S s( [](){} );
    S f1( s );
    S f2(std::allocator_arg, std::allocator<int>{}, s);
}

Fix inheriting constructor test for std::function.


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

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QApplication::setApplicationName("ofProjectGenerator");
    QApplication::setApplicationVersion("0.5.1");
    QApplication::setOrganizationName("Furkanzmc");

    MainWindow w;
    w.show();

    return a.exec();
}

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

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QApplication::setApplicationName("ofProjectGenerator");
    QApplication::setApplicationVersion("0.5.2");
    QApplication::setOrganizationName("Furkanzmc");

    MainWindow w;
    w.show();

    return a.exec();
}

Increase version for the VS support


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

#include "ui/gfx/linux_util.h"

#include "base/basictypes.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace gfx {

TEST(LinuxUtilTest, ConvertAcceleratorsFromWindowsStyle) {
  static const struct {
    const char* input;
    const char* output;
  } cases[] = {
    { "", "" },
    { "nothing", "nothing" },
    { "foo &bar", "foo _bar" },
    { "foo &&bar", "foo &bar" },
    { "foo &&&bar", "foo &_bar" },
    { "&foo &&bar", "_foo &bar" },
    { "&foo &bar", "_foo _bar" },
  };
  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
    std::string result = ConvertAcceleratorsFromWindowsStyle(cases[i].input);
    EXPECT_EQ(cases[i].output, result);
  }
}

}  // namespace gfx

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

#include "ui/gfx/linux_util.h"

#include "base/basictypes.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace gfx {

TEST(LinuxUtilTest, ConvertAcceleratorsFromWindowsStyle) {
  static const struct {
    const char* input;
    const char* output;
  } cases[] = {
    { "", "" },
    { "nothing", "nothing" },
    { "foo &bar", "foo _bar" },
    { "foo &&bar", "foo &bar" },
    { "foo &&&bar", "foo &_bar" },
    { "&foo &&bar", "_foo &bar" },
    { "&foo &bar", "_foo _bar" },
  };
  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
    std::string result = ConvertAcceleratorsFromWindowsStyle(cases[i].input);
    EXPECT_EQ(cases[i].output, result);
  }
}

TEST(LinuxUtilTest, RemoveWindowsStyleAccelerators) {
  static const struct {
    const char* input;
    const char* output;
  } cases[] = {
    { "", "" },
    { "nothing", "nothing" },
    { "foo &bar", "foo bar" },
    { "foo &&bar", "foo &bar" },
    { "foo &&&bar", "foo &bar" },
    { "&foo &&bar", "foo &bar" },
    { "&foo &bar", "foo bar" },
  };
  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
    std::string result = RemoveWindowsStyleAccelerators(cases[i].input);
    EXPECT_EQ(cases[i].output, result);
  }
}

}  // namespace gfx

Add unittests for RemoveWindowsStyleAccelerators() function.


#include "variantmap.h"

namespace MolCore {

// === VariantMap ========================================================== //
/// \class VariantMap
/// \brief The VariantMap class provides a map between string keys
///        and variant values.

// --- Construction and Destruction ---------------------------------------- //
/// Creates a new variant map object.
VariantMap::VariantMap()
{
}

/// Destroys the variant map.
VariantMap::~VariantMap()
{
}

// --- Properties ---------------------------------------------------------- //
/// Returns the size of the variant map.
size_t VariantMap::size() const
{
  return m_map.size();
}

/// Returns \c true if the variant map is empty (i.e. size() ==
/// \c 0).
bool VariantMap::isEmpty() const
{
  return m_map.empty();
}

// --- Values -------------------------------------------------------------- //
/// Sets the value of \p name to \p value.
void VariantMap::setValue(const std::string &name, const Variant &value)
{
  m_map[name] = value;
}

/// Returns the value for \p name.
Variant VariantMap::value(const std::string &name) const
{
  return m_map.at(name);
}

} // end MolCore namespace

#include "variantmap.h"

namespace MolCore {

// === VariantMap ========================================================== //
/// \class VariantMap
/// \brief The VariantMap class provides a map between string keys
///        and variant values.

// --- Construction and Destruction ---------------------------------------- //
/// Creates a new variant map object.
VariantMap::VariantMap()
{
}

/// Destroys the variant map.
VariantMap::~VariantMap()
{
}

// --- Properties ---------------------------------------------------------- //
/// Returns the size of the variant map.
size_t VariantMap::size() const
{
  return m_map.size();
}

/// Returns \c true if the variant map is empty (i.e. size() ==
/// \c 0).
bool VariantMap::isEmpty() const
{
  return m_map.empty();
}

// --- Values -------------------------------------------------------------- //
/// Sets the value of \p name to \p value.
void VariantMap::setValue(const std::string &name, const Variant &value)
{
  m_map[name] = value;
}

/// Returns the value for \p name. If \p name is not found a null
/// variant is returned.
Variant VariantMap::value(const std::string &name) const
{
  std::map<std::string, Variant>::const_iterator iter = m_map.find(name);
  if(iter == m_map.end())
    return Variant();

  return iter->second;
}

} // end MolCore namespace

Remove the usage of non-portable std::map::at() from VariantMap


#include <iostream>
#include <array>
#include <asio/steady_timer.hpp>
#include <asio.hpp>
#include <thread>
#include "node/raft_node.h"

using namespace std;

std::vector<raft_node_endpoint_t> peers{
        {1ul, "localhost", 12345, 13001},
        {2ul, "localhost", 12346, 13002},
        {3ul, "localhost", 12347, 13003}
};

int main(int argc, char* argv[]) {
    try {
        // Start raft_nodes
        std::vector<std::thread> workers;
        for (auto &peer : peers) {
            workers.push_back(std::thread([&peer]() {
                auto node = raft_node(peer.uuid, std::make_shared<raft::config>(peers));
                node.run();
            }));
        }

        // Wait for raft_nodes to finish
        std::for_each(workers.begin(), workers.end(), [](std::thread &t){
            t.join();
        });
    }
    catch(std::exception& e) {
        std::cerr << "Error" << std::endl;
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

#include <iostream>
#include <array>
#include <asio/steady_timer.hpp>
#include <asio.hpp>
#include <thread>
#include "node/raft_node.h"

using namespace std;

std::vector<raft_node_endpoint_t> peers{
        {1ul, "localhost", 12345, 13001},
        {2ul, "localhost", 12346, 13002},
        {3ul, "localhost", 12347, 13003}
};

int main(int argc, char* argv[]) {
    try {
        // Start raft_nodes
        std::vector<std::thread> workers;
        for (auto &peer : peers) {
            workers.push_back(std::thread([&peer]() {
                raft_node node(peer.uuid, std::make_shared<raft::config>(peers));
                node.run();
            }));
        }

        // Wait for raft_nodes to finish
        std::for_each(workers.begin(), workers.end(), [](std::thread &t){
            t.join();
        });
    }
    catch(std::exception& e) {
        std::cerr << "Error" << std::endl;
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

Fix constructor usage (copy constructor deleted)


/// \file    main.cpp

#include "HelloTriangleApplication.hpp"

#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"

#include <cstdlib>
#include <ostream>
#include <stdexcept>

int main(int argc, char* argv[]) // NOLINT(bugprone-exception-escape)
{
  ////////////////////////////// Testing Stuff ////
  doctest::Context context;                      //
  context.setOption("no-breaks", true);          //
  context.setOption("no-run", true);             //
  context.applyCommandLine(argc, argv);          //
  auto test_results = context.run();             //
  if (context.shouldExit()) return test_results; //
  /////////////////////////////////////////////////

  HelloTriangleApplication app;

  try {
    app.run();
  }
  catch (const std::exception& e) {
    std::cerr << e.what() << "\n";
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS + test_results;
}

// vim:set et ts=2 sw=0 sts=0:

/// \file    main.cpp

#include "HelloTriangleApplication.hpp"

#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"

#include <cstdlib>
#include <ostream>
#include <stdexcept>

int main(int argc, char* argv[])
{
  /////////////////////////////////////////////////////////////// Testing Stuff
  doctest::Context context;
  context.setOption("no-breaks", true);
  context.setOption("no-run", true);
  context.applyCommandLine(argc, argv);
  auto test_results = context.run();
  if (context.shouldExit()) return test_results;
  /////////////////////////////////////////////////////////////////////////////

  HelloTriangleApplication app;

  try {
    app.run();
  }
  catch (const std::exception& e) {
    std::cerr << e.what() << "\n";
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS + test_results;
}

// vim:set et ts=2 sw=0 sts=0:

Remove linter concerns which no longer trigger


// Copyright 2015 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

#include "bindings/script_prologue.h"

namespace bindings {

// NOTE: Line breaks will be removed from these scripts before their execution in the
//       JavaScript virtual machine. Therefore you must NOT use line-level comments in this code,
//       as that will cause the first line of the user script to be ignored.

// Define the require() function on the global object, available to all.
const char kScriptPrologue[] = R"(
Object.defineProperty(self, 'require', {
  enumerable: true,
  configurable: false,
  writable: false,
  value: (() => {
    let _script_cache = {};

    /** require(script) **/
    let _function = (script) => {
      if (!_script_cache.hasOwnProperty(script))
        _script_cache[script] = requireImpl(script);
      return _script_cache[script];
    }

    return _function;
  })()
});
)";

const char kModulePrologue[] = R"(
(function() {
  let exports = {};
  let module = {};

  return (function(require, exports, module, global) {
)";

const char kModuleEpilogue[] = R"(
    ; return exports;
  })(require, exports, module, self);
})();
)";

}  // namespace bindings

// Copyright 2015 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

#include "bindings/script_prologue.h"

namespace bindings {

// NOTE: Line breaks will be removed from these scripts before their execution in the
//       JavaScript virtual machine. Therefore you must NOT use line-level comments in this code,
//       as that will cause the first line of the user script to be ignored.

// Define the require() function on the global object, available to all.
const char kScriptPrologue[] = R"(
Object.defineProperty(self, 'require', {
  enumerable: true,
  configurable: false,
  writable: false,
  value: (() => {
    let _script_cache = {};

    /** require(script) **/
    let _function = script => {
      if (!_script_cache.hasOwnProperty(script))
        _script_cache[script] = requireImpl(script);
      return _script_cache[script];
    };

    /** require.clear(prefix) **/
    _function.clear = prefix => {
      Object.keys(_script_cache).forEach(script => {
        if (script.startsWith(prefix))
          delete _script_cache[script];
      });
    };

    return _function;
  })()
});
)";

const char kModulePrologue[] = R"(
(function() {
  let exports = {};
  let module = {};

  return (function(require, exports, module, global) {
)";

const char kModuleEpilogue[] = R"(
    ; return exports;
  })(require, exports, module, self);
})();
)";

}  // namespace bindings

Add a require.clear() function to PlaygroundJS


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

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

#include "base/logging.h"

// static
void RenderWidgetHostView::GetDefaultScreenInfo(
    WebKit::WebScreenInfo* results) {
  NOTIMPLEMENTED();
}

////////////////////////////////////////////////////////////////////////////////
// RenderWidgetHostView, public:

// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
    RenderWidgetHost* widget) {
  NOTIMPLEMENTED();
  return NULL;
}

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

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

#include "base/logging.h"

// static
void RenderWidgetHostViewBase::GetDefaultScreenInfo(
    WebKit::WebScreenInfo* results) {
  NOTIMPLEMENTED();
}

////////////////////////////////////////////////////////////////////////////////
// RenderWidgetHostView, public:

// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
    RenderWidgetHost* widget) {
  NOTIMPLEMENTED();
  return NULL;
}

Fix compile error when building content_unittests for android.


#include "stdafx.h"
#include "ScriptLoader.h"
#include <boost\filesystem.hpp>
#include <sstream>

namespace fs = boost::filesystem;
using namespace fs;

ScriptLoader::ScriptLoader(JsContextRef* context)
{
	this->context = *context;
}

ScriptLoader::~ScriptLoader()
{
}

void ScriptLoader::LoadScripts()
{
	path js(L"js");
	if (is_directory(js))
	{
		for (directory_entry& entry : directory_iterator(js))
		{
			path file = entry.path();
			if (is_regular_file(file) && file.has_extension() && file.extension() == ".js")
			{
				fs::ifstream fileStream(file);
				ostringstream stringStream;
				stringStream << fileStream.rdbuf();
				fileStream.close();
				string script = stringStream.str();
				LoadScript(script);
			}
		}
	}
	else
	{
		create_directory(js);
	}
}

void ScriptLoader::LoadScript(string script)
{
}

#include "stdafx.h"
#include "ScriptLoader.h"
#include <boost\filesystem.hpp>
#include <sstream>

namespace fs = boost::filesystem;
using namespace fs;

ScriptLoader::ScriptLoader(JsContextRef* context)
{
	this->context = *context;
}

ScriptLoader::~ScriptLoader()
{
}

void ScriptLoader::LoadScripts()
{
	path js(L"js");
	if (is_directory(js))
	{
		for (directory_entry& entry : directory_iterator(js))
		{
			path file = entry.path();
			if (is_regular_file(file) && file.has_extension() && file.extension() == ".js")
			{
				fs::wifstream fileStream(file);
				wostringstream stringStream;
				stringStream << fileStream.rdbuf();;
				fileStream.close();
				wstring script = stringStream.str();
				LoadScript(script);
			}
		}
	}
	else
	{
		create_directory(js);
	}
}

void ScriptLoader::LoadScript(wstring script)
{
}

Convert string back to wstring


#include "greentea-client/greentea_serial.h"

SingletonPtr<GreenteaSerial> greentea_serial;

GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX, MBED_CONF_PLATFORM_STDIO_BAUD_RATE) {};

#include "greentea-client/greentea_serial.h"

/**
 * Macros for setting console flow control.
 */
#define CONSOLE_FLOWCONTROL_RTS     1
#define CONSOLE_FLOWCONTROL_CTS     2
#define CONSOLE_FLOWCONTROL_RTSCTS  3
#define mbed_console_concat_(x) CONSOLE_FLOWCONTROL_##x
#define mbed_console_concat(x) mbed_console_concat_(x)
#define CONSOLE_FLOWCONTROL mbed_console_concat(MBED_CONF_TARGET_CONSOLE_UART_FLOW_CONTROL)

SingletonPtr<GreenteaSerial> greentea_serial;

GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX, MBED_CONF_PLATFORM_STDIO_BAUD_RATE) {
#if   CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_RTS
    set_flow_control(SerialBase::RTS, STDIO_UART_RTS, NC);
#elif CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_CTS
    set_flow_control(SerialBase::CTS, NC, STDIO_UART_CTS);
#elif CONSOLE_FLOWCONTROL == CONSOLE_FLOWCONTROL_RTSCTS
    set_flow_control(SerialBase::RTSCTS, STDIO_UART_RTS, STDIO_UART_CTS);
#endif
}

Enable flow control in Greentea


//===----------------------- cxa_bad_cast.pass.cpp ------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

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

#include <cxxabi.h>
#include <cassert>
#include <stdlib.h>
#include <exception>
#include <typeinfo>

class Base {
  virtual void foo() {};
};

class Derived : public Base {};

Derived &test_bad_cast(Base b) {
  return dynamic_cast<Derived&>(b);
}

Base gB;

void my_terminate() { exit(0); }

int main ()
{
    // swap-out the terminate handler
    void (*default_handler)() = std::get_terminate();
    std::set_terminate(my_terminate);

#ifndef LIBCXXABI_HAS_NO_EXCEPTIONS
    try {
#endif
        Derived &d = test_bad_cast(gB);
        assert(false);
        ((void)d);
#ifndef LIBCXXABI_HAS_NO_EXCEPTIONS
    } catch (std::bad_cast) {
        // success
        return 0;
    } catch (...) {
        assert(false);
    }
#endif

    // failure, restore the default terminate handler and fire
    std::set_terminate(default_handler);
    std::terminate();
}

//===----------------------- cxa_bad_cast.pass.cpp ------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

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

#include <cxxabi.h>
#include <cassert>
#include <stdlib.h>
#include <exception>
#include <typeinfo>

class Base {
  virtual void foo() {};
};

class Derived : public Base {};

Derived &test_bad_cast(Base& b) {
  return dynamic_cast<Derived&>(b);
}

Base gB;

void my_terminate() { exit(0); }

int main ()
{
    // swap-out the terminate handler
    void (*default_handler)() = std::get_terminate();
    std::set_terminate(my_terminate);

#ifndef LIBCXXABI_HAS_NO_EXCEPTIONS
    try {
#endif
        Derived &d = test_bad_cast(gB);
        assert(false);
        ((void)d);
#ifndef LIBCXXABI_HAS_NO_EXCEPTIONS
    } catch (std::bad_cast) {
        // success
        return 0;
    } catch (...) {
        assert(false);
    }
#endif

    // failure, restore the default terminate handler and fire
    std::set_terminate(default_handler);
    std::terminate();
}

Fix dangling reference in test


#include "CacheJsonToArticleConverter.h"

#include <json/json.h>

#include "WalkerException.h"
#include "Article.h"

ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache)
{
    Json::Reader reader;
    Json::Value document;
    bool success = reader.parse(json, document, false);

    if(!success) {
        throw WalkerException("Error parsing JSON");
    }

    // get all "main" articles first
    for(auto &titleElement : document.getMemberNames()) {
        std::string title = titleElement;

        Article *a = articleCache.get(title);

        if(a == nullptr) {
            a = new Article(title);
            articleCache.add(a);
        }

        for(auto linkedArticle :
                document.get(title, Json::Value::nullSingleton())
                        .get("forward_links", Json::Value::nullSingleton())) {
            std::string linkedTitle = linkedArticle.asString();
            Article *la = articleCache.get(linkedTitle);

            if(la == nullptr) {
                la = new Article(linkedTitle);
                articleCache.add(la);
            }

            a->addLink(la);
        }
    }

    return articleCache;
    /*
        a->setAnalyzed(true); ?
    */
}

#include "CacheJsonToArticleConverter.h"

#include <json/json.h>

#include "WalkerException.h"
#include "Article.h"

ArticleCollection& CacheJsonToArticleConverter::convertToArticle(std::string json, ArticleCollection& articleCache)
{
    Json::Reader reader;
    Json::Value document;
    bool success = reader.parse(json, document, false);

    if(!success) {
        throw WalkerException("Error parsing JSON");
    }

    // get all "main" articles first
    for(auto &titleElement : document.getMemberNames()) {
        std::string title = titleElement;

        Article *a = articleCache.get(title);

        if(a == nullptr) {
            a = new Article(title);
            articleCache.add(a);
        }

        auto links = document
                        .get(title, Json::Value::nullSingleton())
                        .get("forward_links", Json::Value::nullSingleton());

        if(links.isNull()) {
            /* don't need to set article analyzed to false,
             * since that's the default */
            continue;
        }

        a->setAnalyzed(true);

        for(auto linkedArticle : links) {
            std::string linkedTitle = linkedArticle.asString();
            Article *la = articleCache.get(linkedTitle);

            if(la == nullptr) {
                la = new Article(linkedTitle);
                articleCache.add(la);
            }

            a->addLink(la);
        }
    }

    return articleCache;
    /*
        a->setAnalyzed(true); ?
    */
}

Modify json cache implementation to match null/empty array behavior


/*
 * Copyright (c) 2015 Daniel Kirchner
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#include "glutil.h"
#include <oglp/oglp.cxx>

namespace glutil {

void Init (oglp::GetProcAddressCallback getprocaddress) {
    oglp::Init (getprocaddress);
}

} /* namespace glutil */

/*
 * Copyright (c) 2015 Daniel Kirchner
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#include "glutil.h"

namespace glutil {

void Init (oglp::GetProcAddressCallback getprocaddress) {
    oglp::Init (getprocaddress);
}

} /* namespace glutil */

Remove obsolete oglp code include.


#include "TextureHolder.hpp"

TextureHolder::TextureHolder()
{

}

void TextureHolder::load(Textures id, const std::string &fileName)
{
    std::unique_ptr<sf::Texture> texture(new sf::Texture);
    texture->loadFromFile(fileName);

    m_textureMap.insert(std::make_pair(id, std::move(texture)));
}

sf::Texture& TextureHolder::get(Textures id)
{
    auto found = m_textureMap.find(id);
    return *found->second;
}

const sf::Texture& TextureHolder::get(Textures id) const
{
    auto found = m_textureMap.find(id);
    return *found->second;
}

#include "TextureHolder.hpp"

TextureHolder::TextureHolder()
{

}

void TextureHolder::load(Textures id, const std::string &fileName)
{
    std::unique_ptr<sf::Texture> texture(new sf::Texture);
    if (!texture->loadFromFile(fileName))
    {
        throw std::runtime_error("TextureHolder::load - Failed to load " + fileName);
    }
    auto inserted = m_textureMap.insert(std::make_pair(id, std::move(texture)));
    // Stop execute in debug mode when there was an error by inserting the resource(e.g try to add the same id twice)
    // Trying to load the same resource twice with the same id is a logical error so the progtam should stop immediately in debug mode
    assert(inserted.second);
}

sf::Texture& TextureHolder::get(Textures id)
{
    auto found = m_textureMap.find(id);
    // Stop programm in debug mode, when trying to get a resource which is not loaded
    assert(found != m_textureMap.end());
    return *found->second;
}

const sf::Texture& TextureHolder::get(Textures id) const
{
    auto found = m_textureMap.find(id);
    return *found->second;
}

Add Error handling to textureholder


///
//
// LibSourcey
// Copyright (c) 2005, Sourcey <https://sourcey.com>
//
// SPDX-License-Identifier: LGPL-2.1+
//
/// @addtogroup base
/// @{

#include "scy/pipe.h"

using std::endl;

namespace scy {

Pipe::Pipe(uv::Loop* loop)
    : Stream(loop, new uv_pipe_t)
{
}

Pipe::~Pipe()
{
}

void Pipe::init(bool ipc)
{
    uv_pipe_init(loop(), ptr<uv_pipe_t>(), ipc ? 1 : 0);
    //Stream::readStart();
}

bool Pipe::readStart()
{
    return Stream::readStart();
}

//
//bool Pipe::readStop()
//{
//    return Stream::readStop();
//}

} // namespace scy

/// @\}

///
//
// LibSourcey
// Copyright (c) 2005, Sourcey <https://sourcey.com>
//
// SPDX-License-Identifier: LGPL-2.1+
//
/// @addtogroup base
/// @{

#include "scy/pipe.h"

using std::endl;

namespace scy {

Pipe::Pipe(uv::Loop* loop)
    : Stream(loop, new uv_pipe_t)
{
}

Pipe::~Pipe()
{
}

void Pipe::init(bool ipc)
{
    uv_pipe_init(loop(), ptr<uv_pipe_t>(), ipc ? 1 : 0);
    Stream::init();
}

bool Pipe::readStart()
{
    return Stream::readStart();
}

// bool Pipe::readStop()
// {
//     return Stream::readStop();
// }

} // namespace scy

/// @\}

Fix missing call to Pipe::init


#include <gloperate/stages/ColorGradientPreparationStage.h>

#include <gloperate/base/ColorGradientList.h>
#include <gloperate/tools/ColorGradientPreparation.h>

namespace gloperate
{

ColorGradientPreparationStage::ColorGradientPreparationStage()
{
    addInput("gradients", gradients);
    addInput("pixmapSize", pixmapSize);

    addOutput("names", names);
    addOutput("pixmaps", pixmaps);
}

ColorGradientPreparationStage::~ColorGradientPreparationStage()
{
}

void ColorGradientPreparationStage::process()
{
    ColorGradientPreparation preparation(gradients.data(), pixmapSize.data());

    names.data() = preparation.names();
    pixmaps.data() = preparation.pixmaps();

    invalidateOutputs();
}

} // namespace gloperate

#include <gloperate/stages/ColorGradientPreparationStage.h>

#include <gloperate/base/ColorGradientList.h>
#include <gloperate/tools/ColorGradientPreparation.h>

namespace gloperate
{

ColorGradientPreparationStage::ColorGradientPreparationStage()
{
    addInput("gradients", gradients);
    addInput("pixmapSize", pixmapSize);

    addOutput("names", names);
    addOutput("pixmaps", pixmaps);
}

ColorGradientPreparationStage::~ColorGradientPreparationStage()
{
}

void ColorGradientPreparationStage::process()
{
    ColorGradientPreparation preparation(gradients.data(), pixmapSize.data());

    preparation.fillNames(names.data());
    preparation.fillPixmaps(pixmaps.data());

    invalidateOutputs();
}

} // namespace gloperate

Use designated interface of the color gradient preparation tool in the color gradient preparation stage


#include "network_config.hpp"
#include <fstream>
#include <string>

namespace phosphor
{
namespace network
{

namespace bmc
{
    void writeDHCPDefault(const std::string& filename,
            const std::string& interface)
    {
        std::ofstream filestream;

        filestream.open(filename);
        filestream << "[Match]\nName=" << interface <<
                "\n[Network]\nDHCP=true\nLinkLocalAddressing=yes\n"
                "[DHCP]\nClientIdentifier=mac\n";
        filestream.close();
    }
}

}//namespace network
}//namespace phosphor

#include "network_config.hpp"
#include <fstream>
#include <string>

namespace phosphor
{
namespace network
{

namespace bmc
{
    void writeDHCPDefault(const std::string& filename,
            const std::string& interface)
    {
        std::ofstream filestream;

        filestream.open(filename);
        filestream << "[Match]\nName=" << interface <<
                "\n[Network]\nDHCP=true\n"
                "[DHCP]\nClientIdentifier=mac\n";
        filestream.close();
    }
}

}//namespace network
}//namespace phosphor

Disable zeroconf in factory reset mode


//
// 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 2013      Mayank Madan <maddiemadan@gmail.com>
//
#include "KmlDurationTagHandler.h"

#include "MarbleDebug.h"

#include "KmlElementDictionary.h"

#include "MarbleGlobal.h"
#include "GeoDataFlyTo.h"
#include "GeoParser.h"

namespace Marble
{
namespace kml
{
KML_DEFINE_TAG_HANDLER( duration )
    GeoNode *KmldurationTagHandler::parse(GeoParser & parser) const
    {
        Q_ASSERT ( parser.isStartElement()
                   && parser.isValidElement( kmlTag_duration ) );

        GeoStackItem parentItem = parser.parentElement();

        qreal const duration = parser.readElementText().trimmed().toDouble();
        if ( parentItem.is<GeoDataFlyTo>() ){
            parentItem.nodeAs<GeoDataFlyTo>()->setDuration( duration );
        }
        return 0;
}
}
}

//
// 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 2013      Mayank Madan <maddiemadan@gmail.com>
//
#include "KmlDurationTagHandler.h"

#include "MarbleDebug.h"

#include "KmlElementDictionary.h"

#include "MarbleGlobal.h"
#include "GeoDataFlyTo.h"
#include "GeoParser.h"

namespace Marble
{
namespace kml
{

KML_DEFINE_TAG_HANDLER_GX22( duration )

GeoNode *KmldurationTagHandler::parse(GeoParser & parser) const
{
    Q_ASSERT ( parser.isStartElement()
               && parser.isValidElement( kmlTag_duration ) );

    GeoStackItem parentItem = parser.parentElement();

    qreal const duration = parser.readElementText().trimmed().toDouble();
    if ( parentItem.is<GeoDataFlyTo>() ){
        parentItem.nodeAs<GeoDataFlyTo>()->setDuration( duration );
    }
    return 0;
}

}
}

Fix namespace. It is <gx:duration>.


#include "SkTypeface.h"

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

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

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

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

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

#include "SkTypeface.h"

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

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

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

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

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

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


#include <qpiekey.h>
#include <QSizePolicy>
#include <QPainter>
#include <QPaintEvent>

QPieKey::QPieKey(QWidget *parent) : QWidget(parent)
{
    bitmap = new QBitmap(40,40);
    QPainter painter(bitmap);

    bitmap->clear();
    painter.drawEllipse(0, 0, 40, 40);
    setFixedSize(40, 40);
    setMask(*bitmap);
}

QPieKey::~QPieKey()
{
}

void QPieKey::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    painter.setBrush(QColor(128, 128, 128));
    painter.drawRect(event->rect());
}

#include <qpiekey.h>
#include <QSizePolicy>
#include <QPainter>
#include <QPaintEvent>

#define SIZE 60

QPieKey::QPieKey(QWidget *parent) : QWidget(parent)
{
    bitmap = new QBitmap(SIZE*2,SIZE*2);
    QPainter painter(bitmap);

    setFixedSize(SIZE*2, SIZE*2);

    bitmap->clear();
    painter.setBrush(Qt::color1);
    painter.drawEllipse(1, 1, SIZE*2-2, SIZE*2-2);
    painter.setBrush(Qt::color0);
    painter.drawEllipse(SIZE/2, SIZE/2, SIZE, SIZE);
    setMask(*bitmap);
    hide();
}

QPieKey::~QPieKey()
{
}

void QPieKey::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    painter.setBrush(QColor(128, 128, 128));
    painter.drawRect(event->rect());
}

Set the transparent region appropriately


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

int main(int argc, char* argv[])
try
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
catch (...)
{
    std::cout << "Exception during testing. Exiting...\n";
    return 1;
}

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

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

Remove exception handler - this was not needed


#include "models/bucket.h"
#include "views/session_view.h"

SessionView::SessionView(Session* session, QWidget* parent)
	: QWidget(parent),
	  m_session(session)
{
	m_hostFileSystem = new QFileSystemModel(this);
	m_hostFileSystem->setRootPath(QDir::rootPath());

	m_hostBrowser = new QTreeView;
	m_hostBrowser->setModel(m_hostFileSystem);
	m_hostBrowser->setRootIndex(m_hostFileSystem->index(QDir::rootPath()));
	// Remove the focus rectangle around the tree view on OSX.
	m_hostBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0);

	m_remoteBrowser = new QTreeView;
	// Remove the focus rectangle around the tree view on OSX.
	m_remoteBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0);

	m_splitter = new QSplitter;
	m_splitter->addWidget(m_hostBrowser);
	m_splitter->addWidget(m_remoteBrowser);

	m_topLayout = new QVBoxLayout(this);
	m_topLayout->addWidget(m_splitter);

	setLayout(m_topLayout);

	m_client = new Client(m_session->GetHost(),
			      m_session->GetPort(),
			      m_session->GetAccessId(),
			      m_session->GetSecretKey());

	ds3_get_service_response* response = m_client->GetService();
	Bucket* bucket = new Bucket(response);
	m_remoteBrowser->setModel(bucket);
}

SessionView::~SessionView()
{
	delete m_client;
}

#include "models/bucket.h"
#include "views/session_view.h"

SessionView::SessionView(Session* session, QWidget* parent)
	: QWidget(parent),
	  m_session(session)
{
	m_hostFileSystem = new QFileSystemModel(this);
	QString rootPath = m_hostFileSystem->myComputer().toString();
	m_hostFileSystem->setRootPath(rootPath);

	m_hostBrowser = new QTreeView;
	m_hostBrowser->setModel(m_hostFileSystem);
	// Remove the focus rectangle around the tree view on OSX.
	m_hostBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0);

	m_remoteBrowser = new QTreeView;
	// Remove the focus rectangle around the tree view on OSX.
	m_remoteBrowser->setAttribute(Qt::WA_MacShowFocusRect, 0);

	m_splitter = new QSplitter;
	m_splitter->addWidget(m_hostBrowser);
	m_splitter->addWidget(m_remoteBrowser);

	m_topLayout = new QVBoxLayout(this);
	m_topLayout->addWidget(m_splitter);

	setLayout(m_topLayout);

	m_client = new Client(m_session->GetHost(),
			      m_session->GetPort(),
			      m_session->GetAccessId(),
			      m_session->GetSecretKey());

	ds3_get_service_response* response = m_client->GetService();
	Bucket* bucket = new Bucket(response);
	m_remoteBrowser->setModel(bucket);
}

SessionView::~SessionView()
{
	delete m_client;
}

Set the host file system model's root path to "myComputer" so the host browser will show all drives.


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "transport_latch.h"
#include <vespa/vespalib/util/stringfmt.h>

using vespalib::make_string;
using storage::spi::Result;

namespace proton {

TransportLatch::TransportLatch(uint32_t cnt)
    : _latch(cnt),
      _lock(),
      _result()
{}

TransportLatch::~TransportLatch() = default;

void
TransportLatch::send(ResultUP result, bool documentWasFound)
{
    {
        std::lock_guard<std::mutex> guard(_lock);
        if (!_result) {
            _result = std::move(result);
        } else if (result->hasError()) {
            _result.reset(new Result(mergeErrorResults(*_result, *result)));
        } else if (documentWasFound) {
            _result = std::move(result);
        }
    }
    _latch.countDown();
}

Result
TransportLatch::mergeErrorResults(const Result &lhs, const Result &rhs)
{
    Result::ErrorType error = (lhs.getErrorCode() > rhs.getErrorCode() ? lhs : rhs).getErrorCode();
    return Result(error, make_string("%s, %s", lhs.getErrorMessage().c_str(), rhs.getErrorMessage().c_str()));
}

} // proton

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "transport_latch.h"
#include <vespa/vespalib/util/stringfmt.h>

using vespalib::make_string;
using storage::spi::Result;

namespace proton {

TransportLatch::TransportLatch(uint32_t cnt)
    : _latch(cnt),
      _lock(),
      _result()
{
    if (cnt == 0u) {
        _result = std::make_unique<Result>();
    }
}

TransportLatch::~TransportLatch() = default;

void
TransportLatch::send(ResultUP result, bool documentWasFound)
{
    {
        std::lock_guard<std::mutex> guard(_lock);
        if (!_result) {
            _result = std::move(result);
        } else if (result->hasError()) {
            _result.reset(new Result(mergeErrorResults(*_result, *result)));
        } else if (documentWasFound) {
            _result = std::move(result);
        }
    }
    _latch.countDown();
}

Result
TransportLatch::mergeErrorResults(const Result &lhs, const Result &rhs)
{
    Result::ErrorType error = (lhs.getErrorCode() > rhs.getErrorCode() ? lhs : rhs).getErrorCode();
    return Result(error, make_string("%s, %s", lhs.getErrorMessage().c_str(), rhs.getErrorMessage().c_str()));
}

} // proton

Handle count being zero in transport latch.


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

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

#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Enchants/Effects.hpp>
#include <Rosetta/Enchants/Enchants.hpp>

#include <regex>

namespace RosettaStone
{
Enchant Enchants::GetEnchantFromText(const std::string& cardID)
{
    std::vector<Effect> effects;

    static std::regex attackHealthRegex("\\+([[:digit:]]+)/\\+([[:digit:]]+)");
    static std::regex attackRegex("\\+([[:digit:]]+) Attack");

    const std::string text = Cards::FindCardByID(cardID).text;
    std::smatch values;

    if (std::regex_search(text, values, attackHealthRegex))
    {
        effects.emplace_back(Effects::AttackN(std::stoi(values[1].str())));
        effects.emplace_back(Effects::HealthN(std::stoi(values[2].str())));
    }
    else if (std::regex_search(text, values, attackRegex))
    {
        effects.emplace_back(Effects::AttackN(std::stoi(values[1].str())));
    }

    return Enchant(effects);
}
}  // namespace RosettaStone

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

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

#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Enchants/Effects.hpp>
#include <Rosetta/Enchants/Enchants.hpp>

#include <regex>

namespace RosettaStone
{
Enchant Enchants::GetEnchantFromText(const std::string& cardID)
{
    std::vector<Effect> effects;
    bool isOneTurn = false;

    static std::regex attackHealthRegex("\\+([[:digit:]]+)/\\+([[:digit:]]+)");
    static std::regex attackRegex("\\+([[:digit:]]+) Attack");

    const std::string text = Cards::FindCardByID(cardID).text;
    std::smatch values;

    if (std::regex_search(text, values, attackHealthRegex))
    {
        effects.emplace_back(Effects::AttackN(std::stoi(values[1].str())));
        effects.emplace_back(Effects::HealthN(std::stoi(values[2].str())));
    }
    else if (std::regex_search(text, values, attackRegex))
    {
        effects.emplace_back(Effects::AttackN(std::stoi(values[1].str())));
    }

    if (text.find("this turn") != std::string::npos)
    {
        isOneTurn = true;
    }

    return Enchant(effects, isOneTurn);
}
}  // namespace RosettaStone

Add code to find text "this turn" and set flag


#include "test_env.h"

#if defined(TARGET_K64F)
AnalogIn in(A0);
AnalogOut out(A5);

#elif defined(TARGET_KL25Z)
AnalogIn in(PTC2);
AnalogOut out(PTE30);

#elif defined(TARGET_KL05Z)
AnalogIn in(PTB11);  // D9
AnalogOut out(PTB1); // D1

#elif defined(TARGET_KL46Z)
AnalogIn in(PTB0);
AnalogOut out(PTE30);

#else
AnalogIn in(p17);
AnalogOut out(p18);

#endif

#define ERROR_TOLLERANCE    0.05

int main() {
    bool check = true;

    for (float out_value=0.0; out_value<1.1; out_value+=0.1) {
        out.write(out_value);
        wait(0.1);

        float in_value = in.read();
        float diff = fabs(out_value - in_value);
        if (diff > ERROR_TOLLERANCE) {
            check = false;
            printf("ERROR (out:%.4f) - (in:%.4f) = (%.4f)"NL, out_value, in_value, diff);
        } else {
            printf("OK    (out:%.4f) - (in:%.4f) = (%.4f)"NL, out_value, in_value, diff);
        }
    }

    notify_completion(check);
}

#include "test_env.h"

#if defined(TARGET_K64F)
AnalogIn in(A0);
AnalogOut out(DAC0_OUT);

#elif defined(TARGET_KL25Z)
AnalogIn in(PTC2);
AnalogOut out(PTE30);

#elif defined(TARGET_KL05Z)
AnalogIn in(PTB11);  // D9
AnalogOut out(PTB1); // D1

#elif defined(TARGET_KL46Z)
AnalogIn in(PTB0);
AnalogOut out(PTE30);

#else
AnalogIn in(p17);
AnalogOut out(p18);

#endif

#define ERROR_TOLLERANCE    0.05

int main() {
    bool check = true;

    for (float out_value=0.0; out_value<1.1; out_value+=0.1) {
        out.write(out_value);
        wait(0.1);

        float in_value = in.read();
        float diff = fabs(out_value - in_value);
        if (diff > ERROR_TOLLERANCE) {
            check = false;
            printf("ERROR (out:%.4f) - (in:%.4f) = (%.4f)"NL, out_value, in_value, diff);
        } else {
            printf("OK    (out:%.4f) - (in:%.4f) = (%.4f)"NL, out_value, in_value, diff);
        }
    }

    notify_completion(check);
}

Update AnalogOut pinname in the test


#include <tgmath.h>

typedef struct {
    float f;
    int i;
} my_untagged_struct;

double multiply(my_untagged_struct *s)
{
    return s->f * s->i;
}

double multiply(my_untagged_struct *s, int x)
{
    return multiply(s) * x;
}

int main(int argc, char **argv)
{
    my_untagged_struct s = {
        .f = (float)argc,
        .i = argc,
    };
    // lldb testsuite break
    return !(multiply(&s, argc) == pow(argc, 3));
}

#include <cmath>

typedef struct {
    float f;
    int i;
} my_untagged_struct;

double multiply(my_untagged_struct *s)
{
    return s->f * s->i;
}

double multiply(my_untagged_struct *s, int x)
{
    return multiply(s) * x;
}

int main(int argc, char **argv)
{
    my_untagged_struct s = {
        .f = (float)argc,
        .i = argc,
    };
    // lldb testsuite break
    return !(multiply(&s, argc) == pow(argc, 3));
}

Fix compilation error caused by tgmath.h.


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

#include "Camera.h"

namespace ouzel
{
    Camera::Camera()
    {

    }

    Camera::~Camera()
    {

    }

    void Camera::setZoom(float zoom)
    {
        _zoom = zoom;

        if (_zoom < 0.1f)
        {
            _zoom = 0.1f;
        }

        _transformDirty = _inverseTransformDirty = true;
    }

    void Camera::calculateLocalTransform() const
    {
        Matrix4 translation;
        translation.translate(-_position.x, -_position.y, 0.0f);

        Matrix4 rotation;
        rotation.rotate(Vector3(0.0f, 0.0f, -1.0f), -_rotation);

        Matrix4 scale;
        scale.scale(_zoom);

        _localTransform = scale * rotation * translation;

        _localTransformDirty = false;
    }

    void Camera::calculateTransform() const
    {
        if (_localTransformDirty)
        {
            calculateLocalTransform();
        }

        _transform = _parentTransform * _localTransform;
        _transformDirty = false;

        for (NodePtr child : _children)
        {
            child->updateTransform(_transform);
        }
    }
}

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

#include "Camera.h"

namespace ouzel
{
    Camera::Camera()
    {

    }

    Camera::~Camera()
    {

    }

    void Camera::setZoom(float zoom)
    {
        _zoom = zoom;

        if (_zoom < 0.1f)
        {
            _zoom = 0.1f;
        }

        _localTransformDirty = _transformDirty = _inverseTransformDirty = true;
    }

    void Camera::calculateLocalTransform() const
    {
        Matrix4 translation;
        translation.translate(-_position.x, -_position.y, 0.0f);

        Matrix4 rotation;
        rotation.rotate(Vector3(0.0f, 0.0f, -1.0f), -_rotation);

        Matrix4 scale;
        scale.scale(_zoom);

        _localTransform = scale * rotation * translation;

        _localTransformDirty = false;
    }

    void Camera::calculateTransform() const
    {
        if (_localTransformDirty)
        {
            calculateLocalTransform();
        }

        _transform = _parentTransform * _localTransform;
        _transformDirty = false;

        for (NodePtr child : _children)
        {
            child->updateTransform(_transform);
        }
    }
}

Mark local transform dirty when camera zoom changes


#include "LanguageTranslator.h"

#include "Logger.h"
#include "StringUtils.h"

LanguageTranslator::LanguageTranslator(std::wstring langFileName) {
    CLOG(L"Loading skin XML: %s", langFileName.c_str());
    std::string u8FileName = StringUtils::Narrow(langFileName);
    tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());
    if (result != tinyxml2::XMLError::XML_SUCCESS) {
        if (result == tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND) {
            //Error::ErrorMessageDie(SKINERR_INVALID_SKIN);
        }
        throw std::logic_error("Failed to read XML file!");
    }

    _root = _xml.GetDocument()->FirstChildElement("translation");
    if (_root == NULL) {
        throw std::runtime_error("Could not find root XML element");
    }
}

std::wstring LanguageTranslator::Translate(std::wstring str) {
    return str;
}

#include "LanguageTranslator.h"

#include "Logger.h"
#include "StringUtils.h"

LanguageTranslator::LanguageTranslator() {

}

LanguageTranslator::LanguageTranslator(std::wstring langFileName) {
    CLOG(L"Loading language XML: %s", langFileName.c_str());
    std::string u8FileName = StringUtils::Narrow(langFileName);
    tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());
    if (result != tinyxml2::XMLError::XML_SUCCESS) {
        if (result == tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND) {
            //Error::ErrorMessageDie(SKINERR_INVALID_SKIN);
        }
        throw std::logic_error("Failed to read XML file!");
    }

    _root = _xml.GetDocument()->FirstChildElement("translation");
    if (_root == NULL) {
        throw std::runtime_error("Could not find root XML element");
    }
}

std::wstring LanguageTranslator::Translate(std::wstring str) {
    return str;
}

Update log message; skin -> language


#include <stdbool.h>

bool is_triangle(const int side_a, const int side_b, const int side_c)
{
    /* Get the triangular inequality state from length of the sides */
    if(side_a + side_b > side_c && side_b + side_c > side_a && side_c + side_a > side_b) return true; /* This is a triangle */
    return false; /* Not a triangle */
}

#include <stdbool.h>

bool triangular_inequality(const int a, const int b, const int c)
{
    if(a + b > c && b + c > a && c + a > b) return true;
    return false;
}

Revert "Name of the function has been changed."


// RUN: clang-cc %s

template <typename T> struct Num {
  T value_;

public:
  Num(T value) : value_(value) {}
  T get() const { return value_; }

  template <typename U> struct Rep {
    U count_;
    Rep(U count) : count_(count) {}

    friend Num operator*(const Num &a, const Rep &n) {
      Num x = 0;
      for (U count = n.count_; count; --count)
        x += a;
      return x;
    }
  };

  friend Num operator+(const Num &a, const Num &b) {
    return a.value_ + b.value_;
  }

  Num& operator+=(const Num& b) {
    value_ += b.value_;
    return *this;
  }
};

int calc1() {
  Num<int> left = -1;
  Num<int> right = 1;
  Num<int> result = left + right;
  return result.get();
}

int calc2() {
  Num<int> x = 3;
  Num<int>::Rep<char> n = (cast) 10;
  Num<int> result = x * n;
  return result.get();
}

// RUN: clang-cc -emit-llvm-only %s

template <typename T> struct Num {
  T value_;

public:
  Num(T value) : value_(value) {}
  T get() const { return value_; }

  template <typename U> struct Rep {
    U count_;
    Rep(U count) : count_(count) {}

    friend Num operator*(const Num &a, const Rep &n) {
      Num x = 0;
      for (U count = n.count_; count; --count)
        x += a;
      return x;
    }
  };

  friend Num operator+(const Num &a, const Num &b) {
    return a.value_ + b.value_;
  }

  Num& operator+=(const Num& b) {
    value_ += b.value_;
    return *this;
  }
};

int calc1() {
  Num<int> left = -1;
  Num<int> right = 1;
  Num<int> result = left + right;
  return result.get();
}

int calc2() {
  Num<int> x = 3;
  Num<int>::Rep<char> n = (char) 10;
  Num<int> result = x * n;
  return result.get();
}

Fix a last-minute typo and make the test not emit temporaries.


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

#include "chrome/browser/extensions/api/system_info_cpu/cpu_info_provider.h"

namespace extensions {

bool CpuInfoProvider::QueryCpuTimePerProcessor(std::vector<CpuTime>* times) {
  // TODO(hongbo): Query the cpu time from /proc/stat.
  return false;
}

}  // namespace extensions

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

#include "chrome/browser/extensions/api/system_info_cpu/cpu_info_provider.h"

#include <cstdio>
#include <iostream>

#include "base/file_util.h"
#include "base/format_macros.h"

namespace extensions {

namespace {

const char kProcStat[] = "/proc/stat";

}  // namespace

bool CpuInfoProvider::QueryCpuTimePerProcessor(std::vector<CpuTime>* times) {
  DCHECK(times);

  std::string contents;
  if (!file_util::ReadFileToString(FilePath(kProcStat), &contents))
     return false;

  std::istringstream iss(contents);
  uint64 user = 0, nice = 0, sys = 0, idle = 0;
  std::string line;

  // Skip the first line because it is just an aggregated number of
  // all cpuN lines.
  std::getline(iss, line);
  std::vector<CpuTime> results;
  while (std::getline(iss, line)) {
    if (line.compare(0, 3, "cpu") != 0)
      continue;

    sscanf(line.c_str(), "%*s %"PRIu64" %"PRIu64" %"PRIu64" %"PRIu64,
           &user, &nice, &sys, &idle);

    CpuTime time;
    time.kernel = sys;
    time.user = user + nice;
    time.idle = idle;
    results.push_back(time);
  }
  times->swap(results);
  return true;
}

}  // namespace extensions

Implement querying CPU time from /proc/stat on Linux for systemInfo.cpu API


#include <iostream>
#include <thread>

void call_from_thread() {
    std::cout << "Hello, World" << std::endl;
}

int main() {
    //Launch a thread
    std::thread t[5];

    for(int i = 0; i < 5; i++){
      t[i] = std::thread(call_from_thread);
    }

    for(int i = 0; i < 5; i++){
      t[i].join();
    }

    return 0;
}

#include <thread>
#include <iostream>
#include <vector>

void hello(){
    std::cout << "Hello, world" << std::endl;
}

int main(){
    std::vector<std::thread> threads;

    for(int i = 0; i < 5; ++i){
        threads.push_back(std::thread(hello));
    }

    for(auto& thread : threads){
        thread.join();
    }

    return 0;
}

Make c++11 example more realistic


// Copyright 2021 The Pigweed Authors
//
// 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
//
//     https://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 "pw_transfer/internal/chunk_data_buffer.h"

#include <cstring>

#include "pw_assert/assert.h"

namespace pw::transfer::internal {

void ChunkDataBuffer::Write(ConstByteSpan data, bool last_chunk) {
  PW_DASSERT(data.size() <= buffer_.size());

  std::memcpy(buffer_.data(), data.data(), data.size());
  size_ = data.size();

  last_chunk_ = last_chunk;
}

}  // namespace pw::transfer::internal

// Copyright 2021 The Pigweed Authors
//
// 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
//
//     https://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 "pw_transfer/internal/chunk_data_buffer.h"

#include <algorithm>
#include <cstring>

#include "pw_assert/assert.h"

namespace pw::transfer::internal {

void ChunkDataBuffer::Write(ConstByteSpan data, bool last_chunk) {
  PW_DASSERT(data.size() <= buffer_.size());

  std::copy(data.begin(), data.end(), buffer_.begin());
  size_ = data.size();

  last_chunk_ = last_chunk;
}

}  // namespace pw::transfer::internal

Fix undefined behavior in memcpy


#include <gtest/gtest.h>
#include <teraranger_hub/teraranger_one.h>

class HubParserTest : public ::testing::Test{
protected:
  uint8_t input_buffer[BUFFER_SIZE] = {0x54,0x48,0x08,0xa7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0b};//expected result is one 2.22 meter measurement
};

TEST_F(HubParserTest, crc8Test){
  int16_t crc = teraranger_hub::crc8(input_buffer, 18);
  EXPECT_EQ(crc, input_buffer[18]);
}

TEST_F(HubParserTest, parsingTest){
  float result = teraranger_hub::two_chars_to_float(input_buffer[2],input_buffer[3]);
  ASSERT_FLOAT_EQ(result, 2215);
}

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

  return RUN_ALL_TESTS();
}

#include <gtest/gtest.h>
#include <teraranger_hub/teraranger_one.h>
#include <teraranger_hub/helper_lib.h>

class HubParserTest : public ::testing::Test{
protected:
  uint8_t input_buffer[BUFFER_SIZE] = {0x54,0x48,0x08,0xa7,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0b};//expected result is one 2.22 meter measurement
};

TEST_F(HubParserTest, crc8Test){
  int16_t crc = teraranger_hub::HelperLib::crc8(input_buffer, 18);
  EXPECT_EQ(crc, input_buffer[18]);
}

TEST_F(HubParserTest, parsingTest){
  float result = teraranger_hub::two_chars_to_float(input_buffer[2],input_buffer[3]);
  ASSERT_FLOAT_EQ(result, 2215);
}

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

  return RUN_ALL_TESTS();
}

Fix unit crc8 unit test