#include "xchainer/python/device.h"

#include <sstream>

#include "xchainer/device.h"

namespace xchainer {

namespace py = pybind11;  // standard convention

void InitXchainerDevice(pybind11::module& m) {
    py::class_<Device>(m, "Device").def("__repr__", [](Device device) {
        std::ostringstream os;
        os << "<Device " << device.name << ">";
        return os.str();
    });

    m.def("get_current_device", []() { return GetCurrentDevice(); });
    m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); });
    m.def("set_current_device", [](const std::string& name) { SetCurrentDevice(name); });
}

}  // namespace xchainer

#include "xchainer/python/device.h"

#include <sstream>

#include "xchainer/device.h"

namespace xchainer {

namespace py = pybind11;  // standard convention

void InitXchainerDevice(pybind11::module& m) {
    py::class_<Device>(m, "Device")
        .def(py::init(&MakeDevice))
        .def("__eq__", py::overload_cast<const Device&, const Device&>(&operator==))
        .def("__ne__", py::overload_cast<const Device&, const Device&>(&operator!=))
        .def("__repr__",
             [](Device device) {
                 std::ostringstream os;
                 os << "<Device " << device.name << ">";
                 return os.str();
             });

    m.def("get_current_device", []() { return GetCurrentDevice(); });
    m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); });
    m.def("set_current_device", [](const std::string& name) { SetCurrentDevice(name); });
}

}  // namespace xchainer

Support Python-level Device ctor and comparison


// RUN: clang-cc -fsyntax-only -verify %s

struct add_pointer {
  template<typename T>
  struct apply {
    typedef T* type;
  };
};

struct add_reference {
  template<typename T>
  struct apply {
    typedef T& type; // expected-error{{cannot form a reference to 'void'}}
  };
};

template<typename MetaFun, typename T>
struct apply1 {
  typedef typename MetaFun::template apply<T>::type type; // expected-note{{in instantiation of template class 'struct add_reference::apply<void>' requested here}}
};

int i;
apply1<add_pointer, int>::type ip = &i;
apply1<add_reference, int>::type ir = i;
apply1<add_reference, float>::type fr = i; // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a value of type 'int'}}

void test() {
  apply1<add_reference, void>::type t; // expected-note{{in instantiation of template class 'struct apply1<struct add_reference, void>' requested here}} \
  // FIXME: expected-error{{unexpected type name 'type': expected expression}}
}

// RUN: clang-cc -fsyntax-only -verify %s

struct add_pointer {
  template<typename T>
  struct apply {
    typedef T* type;
  };
};

struct add_reference {
  template<typename T>
  struct apply {
    typedef T& type; // expected-error{{cannot form a reference to 'void'}}
  };
};

struct bogus {
  struct apply {
    typedef int type;
  };
};

template<typename MetaFun, typename T>
struct apply1 {
  typedef typename MetaFun::template apply<T>::type type; // expected-note{{in instantiation of template class 'struct add_reference::apply<void>' requested here}} \
  // expected-error{{'apply' following the 'template' keyword does not refer to a template}} \
  // FIXME: expected-error{{type 'MetaFun::template apply<int>' cannot be used prior to '::' because it has no members}}
};

int i;
apply1<add_pointer, int>::type ip = &i;
apply1<add_reference, int>::type ir = i;
apply1<add_reference, float>::type fr = i; // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a value of type 'int'}}

void test() {
  apply1<add_reference, void>::type t; // expected-note{{in instantiation of template class 'struct apply1<struct add_reference, void>' requested here}} \
  // FIXME: expected-error{{unexpected type name 'type': expected expression}}

  apply1<bogus, int>::type t2; // expected-note{{in instantiation of template class 'struct apply1<struct bogus, int>' requested here}} \
  // FIXME: expected-error{{unexpected type name 'type': expected expression}}
}

Improve the dependent nested-name-specifier test a bit


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/globals.h"
#if defined(TARGET_OS_FUCHSIA)

#include "bin/crypto.h"

#include <magenta/syscalls.h>

namespace dart {
namespace bin {

bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
  intptr_t read = 0;
  while (read < count) {
    const intptr_t remaining = count - read;
    const intptr_t len =
        (MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN
                                            : remaining;
    const mx_ssize_t res = mx_cprng_draw(buffer + read, len);
    if (res == ERR_INVALID_ARGS) {
      return false;
    }
    read += res;
  }
  return true;
}

}  // namespace bin
}  // namespace dart

#endif  // defined(TARGET_OS_FUCHSIA)

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/globals.h"
#if defined(TARGET_OS_FUCHSIA)

#include "bin/crypto.h"

#include <magenta/syscalls.h>

namespace dart {
namespace bin {

bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
  intptr_t read = 0;
  while (read < count) {
    const intptr_t remaining = count - read;
    const intptr_t len =
        (MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN
                                            : remaining;
    mx_size_t res = 0;
    const mx_status_t status = mx_cprng_draw(buffer + read, len, &res);
    if (status != NO_ERROR) {
      return false;
    }
    read += res;
  }
  return true;
}

}  // namespace bin
}  // namespace dart

#endif  // defined(TARGET_OS_FUCHSIA)

Use the new argument ordering for mx_cprng_draw


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

#include "SkSGDraw.h"

#include "SkSGGeometryNode.h"
#include "SkSGInvalidationController.h"
#include "SkSGPaintNode.h"

namespace sksg {

Draw::Draw(sk_sp<GeometryNode> geometry, sk_sp<PaintNode> paint)
    : fGeometry(std::move(geometry))
    , fPaint(std::move(paint)) {
    fGeometry->addInvalReceiver(this);
    fPaint->addInvalReceiver(this);
}

Draw::~Draw() {
    fGeometry->removeInvalReceiver(this);
    fPaint->removeInvalReceiver(this);
}

void Draw::onRender(SkCanvas* canvas) const {
    fGeometry->draw(canvas, fPaint->makePaint());
}

SkRect Draw::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {
    SkASSERT(this->hasInval());

    // TODO: adjust bounds for paint
    const auto bounds = fGeometry->revalidate(ic, ctm);
    fPaint->revalidate(ic, ctm);

    return bounds;
}

} // namespace sksg

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

#include "SkSGDraw.h"

#include "SkSGGeometryNode.h"
#include "SkSGInvalidationController.h"
#include "SkSGPaintNode.h"

namespace sksg {

Draw::Draw(sk_sp<GeometryNode> geometry, sk_sp<PaintNode> paint)
    : fGeometry(std::move(geometry))
    , fPaint(std::move(paint)) {
    fGeometry->addInvalReceiver(this);
    fPaint->addInvalReceiver(this);
}

Draw::~Draw() {
    fGeometry->removeInvalReceiver(this);
    fPaint->removeInvalReceiver(this);
}

void Draw::onRender(SkCanvas* canvas) const {
    fGeometry->draw(canvas, fPaint->makePaint());
}

SkRect Draw::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {
    SkASSERT(this->hasInval());

    auto bounds = fGeometry->revalidate(ic, ctm);
    fPaint->revalidate(ic, ctm);

    const auto& paint = fPaint->makePaint();
    SkASSERT(paint.canComputeFastBounds());

    return paint.computeFastBounds(bounds, &bounds);
}

} // namespace sksg

Adjust Draw node bounds for paint


// [TODO] This belongs into the cmake platform files!!
#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include <memory>

#include <gloperate/ext-includes-begin.h>
#include <widgetzeug/dark_fusion_style.hpp>
#include <gloperate/ext-includes-end.h>

#include <gloperate-qt/viewer/Viewer.h>

#include "Application.h"

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

    widgetzeug::enableDarkFusionStyle();

    gloperate_qt::Viewer viewer;
    viewer.show();

    viewer.loadPainter("Logo");

    return app.exec();
}

// [TODO] This belongs into the cmake platform files!!
#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include <memory>

#include <gloperate/ext-includes-begin.h>
#include <widgetzeug/dark_fusion_style.hpp>
#include <gloperate/ext-includes-end.h>

#include <gloperate-qt/viewer/Viewer.h>

#include "Application.h"

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

    widgetzeug::enableDarkFusionStyle();

    gloperate_qt::Viewer viewer;
    viewer.show();

    std::string painterName = (argc > 1) ? argv[1] : "Logo";
    viewer.loadPainter(painterName);

    return app.exec();
}

Allow user to specify the initial painter on the commandline for gloperate-viewer


#include "ofxShadersFX.h"

namespace ofxShadersFX {
    Shader::Shader(ShaderType p_type)
    {
        setShaderType(p_type);
    }

    void Shader::begin() {
        // The shader needs reload if not loaded
        // or if modifications in attributes occurred since last frame
        if (!m_shader.isLoaded() || m_needsReload) {
            reload();
            m_needsReload = false;
        }
        m_shader.begin();
    }

    void Shader::end() {
        m_shader.end();
    }

    ShaderType Shader::shaderType() const {
        return m_type;
    }

    void Shader::setShaderType(ShaderType p_type) {
        m_type = p_type;
    }

    void Shader::reload() {
        this->m_shader.setupShaderFromSource(GL_VERTEX_SHADER, getShader(GL_VERTEX_SHADER));
        this->m_shader.setupShaderFromSource(GL_FRAGMENT_SHADER, getShader(GL_FRAGMENT_SHADER));
        if(ofIsGLProgrammableRenderer()) {
            this->m_shader.bindDefaults();
        }
        this->m_shader.linkProgram();
    }
}

// The MIT License (MIT)
// Copyright (c) 2016 Alexandre Baron (Scylardor)

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

namespace ofxShadersFX {
    Shader::Shader(ShaderType p_type)
    {
        setShaderType(p_type);
    }

    void Shader::begin() {
        // The shader needs reload if not loaded
        // or if modifications in attributes occurred since last frame
        if (!m_shader.isLoaded() || m_needsReload) {
            reload();
            m_needsReload = false;
        }
        m_shader.begin();
    }

    void Shader::end() {
        m_shader.end();
    }

    ShaderType Shader::shaderType() const {
        return m_type;
    }

    void Shader::setShaderType(ShaderType p_type) {
        m_type = p_type;
    }

    void Shader::reload() {
        m_shader.setupShaderFromSource(GL_VERTEX_SHADER, getShader(GL_VERTEX_SHADER));
        m_shader.setupShaderFromSource(GL_FRAGMENT_SHADER, getShader(GL_FRAGMENT_SHADER));
        if(ofIsGLProgrammableRenderer()) {
            m_shader.bindDefaults();
        }
        m_shader.linkProgram();
    }
}

Remove unnecessary "this->" (style issue)


// @palcu
// InfoOltenia 2015, teleport, backtracking

#include <cstdio>
#include <algorithm>

using namespace std;

const int NMAX = 100000,
          PASI_INFINITI = NMAX*2;

int v[NMAX],
    nVector, sizeOfCheat;

int back(int pozitieCurenta, int cheatsAvailable) {
    if (pozitieCurenta > nVector)
        return PASI_INFINITI;

    if (pozitieCurenta == nVector)
        return 0;

    int sol = min(back(pozitieCurenta+1, cheatsAvailable) + 1,
                  back(pozitieCurenta+v[pozitieCurenta], cheatsAvailable) + 1);
    if (cheatsAvailable)
        sol = min(sol, back(pozitieCurenta+sizeOfCheat, cheatsAvailable-1) + 1);
    return sol;
}

int main() {
    freopen("teleport.in", "r", stdin);
    freopen("teleport.out", "w", stdout);

    int nCheats;
    scanf("%d%d%d", &nVector, &nCheats, &sizeOfCheat);

    for(int i=0; i<nVector; i++)
        scanf("%d", &v[i]);

    printf("%d\n", back(0, nCheats));

    return 0;
}

Add comments in the source code


// RUN: %clang_cc1 -analyze -analyzer-experimental-internal-checks -analyzer-check-objc-mem  -analyzer-experimental-checks -verify %s
struct X0 { };
bool operator==(const X0&, const X0&);

// PR7287
struct test { int a[2]; };

void t2() {
  test p = {{1,2}};
  test q;
  q = p;
}

bool PR7287(X0 a, X0 b) {
  return a == b;
}

// RUN: %clang_cc1 -analyze -analyzer-experimental-internal-checks -analyzer-check-objc-mem  -analyzer-experimental-checks -verify %s
struct X0 { };
bool operator==(const X0&, const X0&);

// PR7287
struct test { int a[2]; };

void t2() {
  test p = {{1,2}};
  test q;
  q = p;
}

bool PR7287(X0 a, X0 b) {
  return operator==(a, b);
}

Make my test case test what it meant to


/* Copyright 2012 Dietrich Epp <depp@zdome.net> */
#include "level.hpp"
#include "gamescreen.hpp"
using namespace LD24;

Level::~Level()
{ }

void Level::nextLevel()
{
    screen.nextLevel();
}

void Level::setTipFlags(unsigned flags)
{
    if (flags == m_tipflag)
        return;
    levelTips.clear();
    for (int i = 0; i < 32; ++i) {
        if (flags & (1u << i))
            levelTips.push_back(m_allTips[i]);
    }
}

void Level::addTip(int index)
{
    setTipFlags(m_tipflag | (1u << index));
}

void Level::removeTip(int index)
{
    setTipFlags(m_tipflag & ~(1u << index));
}

/* Copyright 2012 Dietrich Epp <depp@zdome.net> */
#include "level.hpp"
#include "gamescreen.hpp"
using namespace LD24;

Level::~Level()
{ }

void Level::nextLevel()
{
    screen.nextLevel();
}

void Level::setTipFlags(unsigned flags)
{
    if (flags == m_tipflag)
        return;
    levelTips.clear();
    for (int i = 0; i < 32; ++i) {
        if (flags & (1u << i))
            levelTips.push_back(m_allTips[i]);
    }
    m_tipflag = flags;
}

void Level::addTip(int index)
{
    setTipFlags(m_tipflag | (1u << index));
}

void Level::removeTip(int index)
{
    setTipFlags(m_tipflag & ~(1u << index));
}

Fix problems with multiple tips


// Rel native launcher for Linux.

#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <libgen.h>
#include <string>
#include <fstream>
#include <streambuf>

int main(int argc, char **argv)
{
  // Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found
  char *dir = dirname(argv[0]);
  chdir(dir);

  // Read the ini file
  std::string iniFileName("lib/Rel.ini");
  std::ifstream configfile(iniFileName);
  std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>());

  // Empty or no ini file?
  if (cmd.length() == 0) {
    std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl;
    return 10;
  }

  // Include command-line args.
  std::string args("");
  for (int i = 1; i < argc; i++)
  	args += std::string(" ") + std::string(argv[i]);

  setenv("SWT_GTK3", "0", 1);
  return system((cmd + args).c_str());
}

// Rel native launcher for Linux.

#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <libgen.h>
#include <string>
#include <fstream>
#include <streambuf>

int main(int argc, char **argv)
{
  // Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found
  char *dir = dirname(argv[0]);
  chdir(dir);

  // Read the ini file
  std::string iniFileName("lib/Rel.ini");
  std::ifstream configfile(iniFileName);
  std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>());

  // Empty or no ini file?
  if (cmd.length() == 0) {
    std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl;
    return 10;
  }

  // Include command-line args.
  std::string args("");
  for (int i = 1; i < argc; i++)
    args += std::string(" \"") + std::string(argv[i]) + std::string("\"");

  setenv("SWT_GTK3", "0", 1);
  return system((cmd + args).c_str());
}

Add double-quote delimiters to args.


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

#include "content/public/common/context_menu_params.h"

namespace content {

const int32 CustomContextMenuContext::kCurrentRenderWidget = kint32max;

CustomContextMenuContext::CustomContextMenuContext()
    : is_pepper_menu(false),
      request_id(0),
      render_widget_id(kCurrentRenderWidget) {
}

ContextMenuParams::ContextMenuParams()
    : media_type(blink::WebContextMenuData::MediaTypeNone),
      x(0),
      y(0),
      has_image_contents(true),
      frame_id(0),
      media_flags(0),
      misspelling_hash(0),
      speech_input_enabled(false),
      spellcheck_enabled(false),
      is_editable(false),
      writing_direction_default(
          blink::WebContextMenuData::CheckableMenuItemDisabled),
      writing_direction_left_to_right(
          blink::WebContextMenuData::CheckableMenuItemEnabled),
      writing_direction_right_to_left(
          blink::WebContextMenuData::CheckableMenuItemEnabled),
      edit_flags(0),
      referrer_policy(blink::WebReferrerPolicyDefault) {
}

ContextMenuParams::~ContextMenuParams() {
}

}  // namespace content

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

#include "content/public/common/context_menu_params.h"

namespace content {

const int32 CustomContextMenuContext::kCurrentRenderWidget = kint32max;

CustomContextMenuContext::CustomContextMenuContext()
    : is_pepper_menu(false),
      request_id(0),
      render_widget_id(kCurrentRenderWidget) {
}

ContextMenuParams::ContextMenuParams()
    : media_type(blink::WebContextMenuData::MediaTypeNone),
      x(0),
      y(0),
      has_image_contents(true),
      frame_id(0),
      media_flags(0),
      misspelling_hash(0),
      speech_input_enabled(false),
      spellcheck_enabled(false),
      is_editable(false),
      writing_direction_default(
          blink::WebContextMenuData::CheckableMenuItemDisabled),
      writing_direction_left_to_right(
          blink::WebContextMenuData::CheckableMenuItemEnabled),
      writing_direction_right_to_left(
          blink::WebContextMenuData::CheckableMenuItemEnabled),
      edit_flags(0),
      referrer_policy(blink::WebReferrerPolicyDefault),
      source_type(ui::MENU_SOURCE_NONE) {
}

ContextMenuParams::~ContextMenuParams() {
}

}  // namespace content

Initialize all members of ContextMenuParams in the ctor


// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++17

void foo(int* a, int *b) {
  a -= b; // expected-warning {{incompatible integer to pointer conversion assigning to 'int *' from 'long'}}
}

template<typename T> T declval();
struct true_type { static const bool value = true; };
struct false_type { static const bool value = false; };
template<bool, typename T, typename U> struct select { using type = T; };
template<typename T, typename U> struct select<false, T, U> { using type = U; };

template<typename T>
typename select<(sizeof(declval<T>() -= declval<T>(), 1) != 1), true_type, false_type>::type test(...);
template<typename T> false_type test(...);

template<typename T>
static const auto has_minus_assign = decltype(test<T>())::value;

static_assert(has_minus_assign<int*>, "failed"); // expected-error {{static_assert failed due to requirement 'has_minus_assign<int *>' "failed"}}

// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++17

void foo(int* a, int *b) {
  a -= b; // expected-warning {{incompatible integer to pointer conversion assigning to 'int *' from}}
}

template<typename T> T declval();
struct true_type { static const bool value = true; };
struct false_type { static const bool value = false; };
template<bool, typename T, typename U> struct select { using type = T; };
template<typename T, typename U> struct select<false, T, U> { using type = U; };

template<typename T>
typename select<(sizeof(declval<T>() -= declval<T>(), 1) != 1), true_type, false_type>::type test(...);
template<typename T> false_type test(...);

template<typename T>
static const auto has_minus_assign = decltype(test<T>())::value;

static_assert(has_minus_assign<int*>, "failed"); // expected-error {{static_assert failed due to requirement 'has_minus_assign<int *>' "failed"}}

Fix test failure from r351495


#include "variant/pwm_platform.hpp"

#include "hal.h"

static const PWMConfig motor_pwm_config = {
  500000,    // 500 kHz PWM clock frequency.
  1000,      // PWM period 2.0 ms.
  NULL,      // No callback.
  {
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL}
  },   // Channel configurations
  0,0   // HW dependent
};

PWMPlatform::PWMPlatform() {
  pwmStart(&PWMD8, &motor_pwm_config);
  palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4));
}

void PWMPlatform::set(std::uint8_t ch, float dc) {
  pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f);
  pwmEnableChannel(&PWMD8, ch, width);
}

#include "variant/pwm_platform.hpp"

#include "hal.h"

static const PWMConfig motor_pwm_config = {
  500000,    // 500 kHz PWM clock frequency.
  2000,      // PWM period 2.0 ms.
  NULL,      // No callback.
  {
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL}
  },   // Channel configurations
  0,0   // HW dependent
};

PWMPlatform::PWMPlatform() {
  pwmStart(&PWMD8, &motor_pwm_config);
  palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4));
}

void PWMPlatform::set(std::uint8_t ch, float dc) {
  pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f);
  pwmEnableChannel(&PWMD8, ch, width);
}

Fix PWM period on F3.


#include "yebash.hpp"
#include "History.hpp"

#include "catch.hpp"
#include <sstream>

using namespace yb;

TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]"  ) {
    std::stringstream ss;
    History history;
    history.read(ss);
    HistorySuggestion suggestion(history);

    auto c = yebash(suggestion, 'a');
    REQUIRE(c == 'a');
}

#include "yebash.hpp"
#include "History.hpp"

#include "catch.hpp"
#include <sstream>

using namespace yb;

TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]"  ) {
    std::stringstream ss;
    std::stringstream output;
    History history;
    history.read(ss);
    HistorySuggestion suggestion(history);
    Printer printer(output);

    auto c = yebash(suggestion, printer, 'a');
    std::string result{output.str()};

    REQUIRE(c == 'a');
    REQUIRE(output.str() == "");
}

Update tests - allow checking the output


#include <QTest>
#include "mainwindow.h"
#include "test-suite.h"

QMap<QDateTime, QString> _log;
QMap<QString, QString> _md5;
mainWindow *_mainwindow;

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

    int failed = 0;
    for (QObject *suite : TestSuite::suites)
    {
        int result = QTest::qExec(suite);
        if (result != 0)
        {
            failed++;
        }
    }

    return failed;
}

#include <QTest>
#include "mainwindow.h"
#include "test-suite.h"

QMap<QDateTime, QString> _log;
QMap<QString, QString> _md5;
mainWindow *_mainwindow;

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

    int failed = 0;
    for (QObject *suite : TestSuite::suites)
    {
        int result = QTest::qExec(suite);
        if (result != 0)
        {
            failed++;
        }
    }

    return failed;
}

Replace gui application by core app to run in cli


#include "Thread/Unix/ThreadImpl.hh"
#include "Thread/ThreadException.hh"

namespace LilWrapper
{
  ThreadImpl::ThreadImpl(Thread *thread)
  {
    this->_isActive = pthread_create(&this->_thread, NULL,
	&ThreadImpl::entryPoint, thread) == 0;
    if (!this->_isActive)
      throw ThreadException("Thread Exception: "
	  "Error while creating the Thread.");
  }

  ThreadImpl::~ThreadImpl()
  {
    if (this->_isActive)
      terminate();
  }

  void ThreadImpl::wait()
  {
    if (this->_isActive)
    {
      if (pthread_equal(pthread_self(), this->_thread) != 0)
	throw ThreadException("Thread Exception: "
	    "A thread cannot wait for itself.");
      pthread_join(this->_thread, NULL);
    }
  }

  void ThreadImpl::terminate()
  {
    if (this->_isActive)
      pthread_cancel(this->_thread);
  }

  void *ThreadImpl::entryPoint(void *data)
  {
    Thread *self = static_cast<Thread *>(data);

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    self->run();
    return (NULL);
  }
}

#include "Thread/Unix/ThreadImpl.hh"
#include "Thread/ThreadException.hh"

namespace LilWrapper
{
  ThreadImpl::ThreadImpl(Thread *thread)
  {
    this->_isActive = pthread_create(&this->_thread, NULL,
        &ThreadImpl::entryPoint, thread) == 0;
    if (!this->_isActive)
      throw ThreadException("Thread Exception: "
          "Error while creating the Thread.");
  }

  ThreadImpl::~ThreadImpl()
  {
    if (this->_isActive)
      terminate();
  }

  void ThreadImpl::wait()
  {
    if (this->_isActive)
    {
      if (pthread_equal(pthread_self(), this->_thread) != 0)
        throw ThreadException("Thread Exception: "
            "A thread cannot wait for itself.");
      pthread_join(this->_thread, NULL);
    }
  }

  void ThreadImpl::terminate()
  {
    if (this->_isActive)
      pthread_cancel(this->_thread);
    this->_isActive = false;
  }

  void *ThreadImpl::entryPoint(void *data)
  {
    Thread *self = static_cast<Thread *>(data);

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    self->run();
    return (NULL);
  }
}

Set the Thread as inactive when terminating it.


/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkTypes.h"

static const size_t kBufferSize = 256;

#define LOG_TAG "skia"
#include <android/log.h>

void SkDebugf(const char format[], ...) {
    va_list args;
    va_start(args, format);
    __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
    va_end(args);
}

/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkTypes.h"

static const size_t kBufferSize = 256;

#define LOG_TAG "skia"
#include <android/log.h>

static bool gSkDebugToStdOut = false;

extern "C" void AndroidSkDebugToStdOut(bool debugToStdOut) {
    gSkDebugToStdOut = debugToStdOut;
}

void SkDebugf(const char format[], ...) {
    va_list args;
    va_start(args, format);
    __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);

    // Print debug output to stdout as well.  This is useful for command
    // line applications (e.g. skia_launcher)
    if (gSkDebugToStdOut) {
        vprintf(format, args);
    }

    va_end(args);
}

Enable Android executables (like skia_launcher) to redirect SkDebugf output to stdout as well as the system logs.


/*
 * Copyright (c) 2016 Lech Kulina
 *
 * This file is part of the Realms Of Steel.
 * For conditions of distribution and use, see copyright details in the LICENSE file.
 */
#include <cstdlib>
#include <boost/property_tree/info_parser.hpp>
#include <application/Logger.h>
#include <application/Application.h>
#include <resources/ResourceCache.h>

int main() {
    int exitCode = EXIT_FAILURE;

    ros::PropertyTree config;
    boost::property_tree::read_info("Config.info", config);

    if (!ros::Logger::initInstance(config.get_child("Logger")) ||
        !ros::Application::initInstance(config.get_child("application")) ||
        !ros::ResourceCache::initInstance(config.get_child("resources"))) {
        return exitCode;
    }

    ros::ApplicationPtr application = ros::Application::getInstance();
    if (application) {
        exitCode = application->run();
        application->uninit();
    }

    return exitCode;
}

/*
 * Copyright (c) 2016 Lech Kulina
 *
 * This file is part of the Realms Of Steel.
 * For conditions of distribution and use, see copyright details in the LICENSE file.
 */
#include <cstdlib>
#include <boost/property_tree/info_parser.hpp>
#include <application/Logger.h>
#include <application/Application.h>
#include <resources/FileSystem.h>
#include <resources/ResourcesCache.h>

int main() {
    int exitCode = EXIT_FAILURE;

    ros::PropertyTree config;
    boost::property_tree::read_info("Config.info", config);

    if (!ros::Logger::initInstance(config.get_child("Logger")) ||
        !ros::Application::initInstance(config.get_child("application")) ||
        !ros::FileSystem::initInstance(config.get_child("file-system")) ||
        !ros::ResourcesCache::initInstance(config.get_child("resources-cache"))) {
        return exitCode;
    }

    ros::ApplicationPtr application = ros::Application::getInstance();
    if (application) {
        exitCode = application->run();
        application->uninit();
    }

    return exitCode;
}

Initialize FileSystem and ResourcesCache from config file


#include <iostream>
#include <cstlib>
#include <vector>

#include <iostream>
#include <cstdlib>
#include <vector>
#include <bitset>
#include <cstring>
#include <string>
#include <fstream>
#include <cstdio>

#include "rand.h"

using namespace std;

class individual {
public:
  int key[26];
  float fit;

};

// user functions go here

int main() {

  // get cipher from cin
  string cipher, tmp;
  while( getline( cin, tmp ) ) {
    cipher.append( tmp );
  }

  // read in freq.txt
  FILE *freq = fopen( "freq.txt", "r" );
  char eng1[488], eng2[488];
  float engnum[488];

  // check if file is open
  if( freq != NULL ) {
    for( int i = 0; i < 488; i++ ) {
      fscanf( freq, "%c%c %f ", &eng1[i], &eng2[i], &engnum[i] );
      //      eng1[i] = fgetc( freq );
      //eng2[i] = fgetc( freq );

      cout << eng1[i] << eng2[i] << " " << engnum[i] <<endl;
    }
  }

  // create cipher count tables
  char cipher1[488], cipher2[488];
  float ciphernum[488];

  for( int i = 0; i < cipher.size(); i++ ){

  }

} // end main

Use fscanf to read in file.


#include <stdexcept>
#include "Person.h"

Person::Person(std::string name) {
	if(name.empty()){
		throw std::invalid_argument("Name can not be empty.");
	}
	this->name = name;
};

#include <stdexcept>
#include "Person.h"

Person::Person(std::string name) {
	if(name.empty()){
		throw std::invalid_argument("Name cannot be empty.");
	}
	this->name = name;
};

Add verification to Person constructor


#include "gtest/gtest.h"

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

#include "gtest/gtest.h"

class ThrowListener : public testing::EmptyTestEventListener
{
  void OnTestPartResult(const testing::TestPartResult& result) override
  {
    if (result.type() == testing::TestPartResult::kFatalFailure)
    {
      throw testing::AssertionException(result);
    }
  }
};

int main(int argc, char *argv[])
{
  ::testing::InitGoogleTest(&argc, argv);
  ::testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener);
  return RUN_ALL_TESTS();
}

Make ASSERTs in helper functions fail the parent testcase


#include "BoardMarker.hpp"

BoardMarker::BoardMarker (void) : m(NONE), c(' ') {}

bool BoardMarker::apply_modifier(Modifier& m) {
  if (this->m != NONE) {
    return false;
  }
  this->m = m;
  return true;
}

bool BoardMarker::set_char(char& c) {
  if (this->c != ' ') {
    return false;
  }
  this->c = toupper(c);
  return true;
}

void BoardMarker::print_marker(void) {
  string pre = " ";
  string col = "";
  string post = " ";
  if (this->m != NONE) {
    pre = " \033[";
    post = "\033[0m ";
    switch (this->m) {
      case DOUBLE_L:
        col = "1;43;37m";
        break;
      case DOUBLE_W:
        col = "1;42;37m";
        break;
      case TRIPLE_L:
        col = "1;44;37m";
        break;
      case TRIPLE_W:
        col = "1;41;37m";
        break;
      case NONE:
        cout << "Shouldn't reach this line!" << endl;
    }
  }

  cout << pre << col << this->c << post;
}

#include "BoardMarker.hpp"

BoardMarker::BoardMarker (void) : m(NONE), c(' ') {}

bool BoardMarker::apply_modifier(Modifier& m) {
  if (this->m != NONE) {
    return false;
  }
  this->m = m;
  return true;
}

bool BoardMarker::set_char(char& c) {
  if (this->c != ' ') {
    return this->c == c;
  }
  this->c = toupper(c);
  return true;
}

void BoardMarker::print_marker(void) {
  string pre = " ";
  string col = "";
  string post = " ";
  if (this->m != NONE) {
    pre = " \033[";
    post = "\033[0m ";
    switch (this->m) {
      case DOUBLE_L:
        col = "1;43;37m";
        break;
      case DOUBLE_W:
        col = "1;42;37m";
        break;
      case TRIPLE_L:
        col = "1;44;37m";
        break;
      case TRIPLE_W:
        col = "1;41;37m";
        break;
      case NONE:
        cout << "Shouldn't reach this line!" << endl;
    }
  }

  cout << pre << col << this->c << post;
}

Allow set_char when char is the same - updating words


// 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/ui/tabs/dock_info.h"

#include "chrome/browser/ui/views/tabs/tab.h"
#include "build/build_config.h"

#if !defined(OS_WIN)
// static
int DockInfo::GetHotSpotDeltaY() {
  return Tab::GetMinimumUnselectedSize().height() - 1;
}
#endif

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

#include "chrome/browser/ui/tabs/dock_info.h"

#include "chrome/browser/ui/views/tabs/tab.h"
#include "build/build_config.h"

#if defined(USE_AURA) || defined(USE_ASH) || defined(OS_CHROMEOS)
// static
int DockInfo::GetHotSpotDeltaY() {
  return Tab::GetMinimumUnselectedSize().height() - 1;
}
#endif

Fix win_aura build enabling GetHotSpotDeltaY() in aura too.


#include "messagedirector.h"
#include "../core/config.h"
ConfigVariable<std::string> bind_addr("messagedirector/bind", "unspecified");

MessageDirector MessageDirector::singleton;

void MessageDirector::InitializeMD()
{
	if(!m_initialized)
	{
		if(bind_addr.get_val() != "unspecified")
		{
		}
	}
}

MessageDirector::MessageDirector() : m_acceptor(NULL), m_initialized(false)
{
}

#include "../core/global.h"
#include "messagedirector.h"
#include "../core/config.h"
using boost::asio::ip::tcp; // I don't want to type all of that god damned shit
ConfigVariable<std::string> bind_addr("messagedirector/bind", "unspecified");

MessageDirector MessageDirector::singleton;

void MessageDirector::InitializeMD()
{
	if(!m_initialized)
	{
		if(bind_addr.get_val() != "unspecified")
		{
			std::string str_ip = bind_addr.get_val();
			std::string str_port = str_ip.substr(str_ip.find(':', 0)+1, std::string::npos);
			str_ip = str_ip.substr(0, str_ip.find(':', 0));
			tcp::resolver resolver(io_service);
			tcp::resolver::query query(str_ip, str_port);
			tcp::resolver::iterator it = resolver.resolve(query);
			m_acceptor = new tcp::acceptor(io_service, *it, true);
			tcp::socket socket(io_service);
			tcp::endpoint peerEndpoint;
			m_acceptor->accept(socket);
		}
	}
}

MessageDirector::MessageDirector() : m_acceptor(NULL), m_initialized(false)
{
}

Put in some placeholder synhronous accept code


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

// <future>

// template <class F, class... Args>
//     future<typename result_of<F(Args...)>::type>
//     async(F&& f, Args&&... args);

// template <class F, class... Args>
//     future<typename result_of<F(Args...)>::type>
//     async(launch policy, F&& f, Args&&... args);

#include <future>
#include <atomic>
#include <memory>
#include <cassert>

#include "test_macros.h"

int foo (int x) { return x; }

int main ()
{
	std::async(                    foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}}
	std::async(std::launch::async, foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}}
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03, c++11, c++14, c++17
// UNSUPPORTED: clang-3.3, clang-3.4, clang-3.5, clang-3.6, clang-3.7, clang-3.8

// <future>

// template <class F, class... Args>
//     future<typename result_of<F(Args...)>::type>
//     async(F&& f, Args&&... args);

// template <class F, class... Args>
//     future<typename result_of<F(Args...)>::type>
//     async(launch policy, F&& f, Args&&... args);

#include <future>
#include <atomic>
#include <memory>
#include <cassert>

#include "test_macros.h"

int foo (int x) { return x; }

int main ()
{
	std::async(                    foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}}
	std::async(std::launch::async, foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}}
}

Add additional 'UNSUPPORTED' to the test case.


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

// TAG_member is used to encode debug info for 'z' in A.
// CHECK: TAG_member
class A {
public:
  int z;
};

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

// Verify that we're not emitting a full definition of B in limit debug mode.
// RUN: %clang -emit-llvm -g -flimit-debug-info -S %s -o - | FileCheck %s
// CHECK-NOT: TAG_member

class B {
public:
  int y;
};

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

Add a test to verify that -flimit-debug-info is working in some way.


#include <opencv2/opencv.hpp>
#include <unistd.h>
int main(int argc, char** argv){
  if(argc!=2){
    std::cout << "Nope.\n";
    return -1;
  }
  cv::VideoCapture _capture(CV_CAP_OPENNI);
  std::cout << "Started streaming data to main system..\n";
  int c=0;
  while(1){
    cv::Mat depthMap, rgb;
    usleep(500000);
    _capture.grab();
    _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP);
    _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE);
    imwrite(std::string(argv[1])+"/rgb.png", rgb);
    imwrite(std::string(argv[1])+"/depth.png", depthMap);
    std::cout << ++c << "\n";
  }
  return 0;
}

#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <unistd.h>
int main(int argc, char** argv){
  if(argc!=2){
    std::cout << "Nope.\n";
    return -1;
  }
  cv::VideoCapture _capture(CV_CAP_OPENNI);
  std::cout << "Started streaming data to main system..\n";
  int c=0;
  cv::namedWindow("DEPTH");
  while(1){
    cv::Mat depthMap, rgb;
    usleep(500000);
    _capture.grab();
    _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP);
    cv::imshow("DEPTH", depthMap);
    cv::waitKey(1);
    _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE);
    cv::imshow("RGB", rgb);
    cv::waitKey(1);
    std::string name=std::string(argv[1])+"/";
    imwrite(name+"/rgb1.png", rgb);
    imwrite(name+"/depth1.png", depthMap);
    system(("mv "+name+"rgb1.png "+name+"rgb.png ; mv "+name+"depth1.png "+name+"depth.png").c_str());
    std::cout << ++c << "\n";
  }
  return 0;
}

Make a more robust streamer


/*  This file is part of Fabula.
    Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>

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

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

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

#include "MainWindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);
    application.setApplicationName(QString::fromAscii("Fabula"));
    application.setApplicationVersion(QString::fromAscii(PROJECT_VERSION));
    application.setOrganizationDomain(QString::fromAscii("mikemcquaid.com"));
    application.setOrganizationName(QString::fromAscii("Mike McQuaid"));

#ifdef Q_WS_MAC
    application.setAttribute(Qt::AA_DontShowIconsInMenus);
#else
    application.setWindowIcon(":/icons/audio-input-microphone.png");
#endif

    MainWindow mainWindow;
    mainWindow.show();
    return application.exec();
}

/*  This file is part of Fabula.
    Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>

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

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

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

#include "MainWindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);
    application.setApplicationName(QString::fromAscii("Fabula"));
    application.setApplicationVersion(QString::fromAscii(PROJECT_VERSION));
    application.setOrganizationDomain(QString::fromAscii("mikemcquaid.com"));
    application.setOrganizationName(QString::fromAscii("Mike McQuaid"));

#ifdef Q_WS_MAC
    application.setAttribute(Qt::AA_DontShowIconsInMenus);
#else
    application.setWindowIcon(QIcon(":/icons/audio-input-microphone.png"));
#endif

    MainWindow mainWindow;
    mainWindow.show();
    return application.exec();
}

Fix Windows window icon failure.


#include "imageviewer.h"
#include "ui_imageviewer.h"

ImageViewer::ImageViewer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ImageViewer)
{
    ui->setupUi(this);

    QImage image("/Users/Wojtek/Pictures/Three-eyed_crow.jpg");
    ui->imageLabel->setPixmap(QPixmap::fromImage(image));
}

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

#include "imageviewer.h"
#include "ui_imageviewer.h"

ImageViewer::ImageViewer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ImageViewer)
{
    ui->setupUi(this);

    ui->imageLabel->setBackgroundRole(QPalette::Base);
    ui->imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    ui->imageLabel->setScaledContents(true);

    ui->scrollArea->setBackgroundRole(QPalette::Dark);

    QImage image("/Users/Wojtek/Pictures/Three-eyed_crow.jpg");
    ui->imageLabel->setPixmap(QPixmap::fromImage(image));

    setWindowTitle(tr("Image Viewer"));
}

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

Set imageLabel and scrollArea properties


#include <stdio.h>
#include <stdarg.h>
#include <iostream>
#include <fstream>
#include <string>

#include "platform.h"

void logMsg(const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
}

std::string stringFromResource(const char* _path) {
    std::string into;

    std::ifstream file;
    std::string buffer;

    file.open(_path);
    if(!file.is_open()) {
        return std::string();
    }

    while(!file.eof()) {
        getline(file, buffer);
        into += buffer + "\n";
    }

    file.close();
    return into;
}

unsigned char* bytesFromResource(const char* _path, unsigned int* _size) {
    std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);

    if(!resource.is_open()) {
        logMsg("Failed to read file at path: %s\n", _path);
        *_size = 0;
        return nullptr;
    }

    *_size = resource.tellg();

    resource.seekg(std::ifstream::beg);

    char* cdata = (char*) malloc(sizeof(char) * (*_size));

    resource.read(cdata, *_size);
    resource.close();

    return reinterpret_cast<unsigned char *>(cdata);
}

#include <stdio.h>
#include <stdarg.h>
#include <iostream>
#include <fstream>
#include <string>

#include "platform.h"

void logMsg(const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
}

void requestRender() {
    // TODO: implement non-continuous rendering on RPi
}

void setContinuousRendering(bool _isContinuous) {
    // TODO: implement non-continuous rendering on RPi
}

bool isContinuousRendering() {
    // TODO: implement non-continuous rendering on RPi
}

std::string stringFromResource(const char* _path) {
    std::string into;

    std::ifstream file;
    std::string buffer;

    file.open(_path);
    if(!file.is_open()) {
        return std::string();
    }

    while(!file.eof()) {
        getline(file, buffer);
        into += buffer + "\n";
    }

    file.close();
    return into;
}

unsigned char* bytesFromResource(const char* _path, unsigned int* _size) {
    std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);

    if(!resource.is_open()) {
        logMsg("Failed to read file at path: %s\n", _path);
        *_size = 0;
        return nullptr;
    }

    *_size = resource.tellg();

    resource.seekg(std::ifstream::beg);

    char* cdata = (char*) malloc(sizeof(char) * (*_size));

    resource.read(cdata, *_size);
    resource.close();

    return reinterpret_cast<unsigned char *>(cdata);
}

Fix missing symbols for RPi


// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
// DSIM
#include <dsim/DSIM_Service.hpp>
#include <dsim/config/dsim-paths.hpp>

// ///////// M A I N ////////////
int main (int argc, char* argv[]) {

  try {

    // Output log File
    std::string lLogFilename ("simulate.log");

    // Set the log parameters
    std::ofstream logOutputFile;
    // Open and clean the log outputfile
    logOutputFile.open (lLogFilename.c_str());
    logOutputFile.clear();

    // Initialise the list of classes/buckets
    DSIM::DSIM_Service dsimService (logOutputFile);

    // Perform a simulation
    dsimService.simulate();

  } catch (const std::exception& stde) {
    std::cerr << "Standard exception: " << stde.what() << std::endl;
    return -1;

  } catch (...) {
    return -1;
  }

  return 0;
}

// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
// DSIM
#include <dsim/DSIM_Service.hpp>
#include <dsim/config/dsim-paths.hpp>

// ///////// M A I N ////////////
int main (int argc, char* argv[]) {

  try {

    // Schedule input file name
    std::string lScheduleInputFilename ("../samples/schedule01.csv");

    // Output log File
    std::string lLogFilename ("simulate.log");

    // Set the log parameters
    std::ofstream logOutputFile;
    // Open and clean the log outputfile
    logOutputFile.open (lLogFilename.c_str());
    logOutputFile.clear();

    // Initialise the list of classes/buckets
    DSIM::DSIM_Service dsimService (lScheduleInputFilename, logOutputFile);

    // Perform a simulation
    dsimService.simulate();

  } catch (const std::exception& stde) {
    std::cerr << "Standard exception: " << stde.what() << std::endl;
    return -1;

  } catch (...) {
    return -1;
  }

  return 0;
}

Update the test with the schedule input filename.


// Copyright (c) 2018 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 <hspp/Tasks/SimpleTasks/IncludeTask.hpp>

namespace Hearthstonepp::SimpleTasks
{
TaskID IncludeTask::GetTaskID() const
{
    return TaskID::INCLUDE;
}

std::vector<Entity*> IncludeTask::GetEntities(EntityType entityType,
                                              Player& player)
{
    std::vector<Entity*> entities;

    switch (entityType)
    {
        case EntityType::HERO:
            entities.emplace_back(player.GetHero());
            break;
        case EntityType::FRIENDS:
            for (auto& minion : player.GetField())
            {
                entities.emplace_back(minion);
            }
            entities.emplace_back(player.GetHero());
            break;
        case EntityType::ENEMIES:
            for (auto& minion : player.GetOpponent().GetField())
            {
                entities.emplace_back(minion);
            }
            entities.emplace_back(player.GetOpponent().GetHero());
            break;
        default:
            throw std::exception("Not implemented");
    }

    return entities;
}

MetaData IncludeTask::Impl(Player&)
{
    return MetaData::INCLUDE_SUCCESS;
}
}  // namespace Hearthstonepp::SimpleTasks

// Copyright (c) 2018 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 <hspp/Tasks/SimpleTasks/IncludeTask.hpp>

#include <stdexcept>

namespace Hearthstonepp::SimpleTasks
{
TaskID IncludeTask::GetTaskID() const
{
    return TaskID::INCLUDE;
}

std::vector<Entity*> IncludeTask::GetEntities(EntityType entityType,
                                              Player& player)
{
    std::vector<Entity*> entities;

    switch (entityType)
    {
        case EntityType::HERO:
            entities.emplace_back(player.GetHero());
            break;
        case EntityType::FRIENDS:
            for (auto& minion : player.GetField())
            {
                entities.emplace_back(minion);
            }
            entities.emplace_back(player.GetHero());
            break;
        case EntityType::ENEMIES:
            for (auto& minion : player.GetOpponent().GetField())
            {
                entities.emplace_back(minion);
            }
            entities.emplace_back(player.GetOpponent().GetHero());
            break;
        default:
            throw std::domain_error("Invalid entity type");
    }

    return entities;
}

MetaData IncludeTask::Impl(Player&)
{
    return MetaData::INCLUDE_SUCCESS;
}
}  // namespace Hearthstonepp::SimpleTasks

Correct compile error on Linux and macOS


#include <test.hpp>

TEST_CASE("basic") {

    SECTION("default constructed pbf message is okay") {
        mapbox::util::pbf item;
        REQUIRE(!item.next());
    }

    SECTION("empty buffer is okay") {
        std::string buffer;
        mapbox::util::pbf item(buffer.data(), 0);
        REQUIRE(!item.next());
    }

    SECTION("check every possible value for single byte in buffer") {
        char buffer[1];
        for (int i = 0; i <= 255; ++i) {
            *buffer = static_cast<char>(i);
            mapbox::util::pbf item(buffer, 1);

            REQUIRE_THROWS({
                item.next();
                item.skip();
            });
        }
    }

}

#include <test.hpp>

TEST_CASE("basic") {

    SECTION("default constructed pbf message is okay") {
        mapbox::util::pbf item;
        REQUIRE(!item.next());
    }

    SECTION("empty buffer is okay") {
        std::string buffer;
        mapbox::util::pbf item(buffer.data(), 0);
        REQUIRE(!item); // test operator bool()
        REQUIRE(!item.next());
    }

    SECTION("check every possible value for single byte in buffer") {
        char buffer[1];
        for (int i = 0; i <= 255; ++i) {
            *buffer = static_cast<char>(i);
            mapbox::util::pbf item(buffer, 1);

            REQUIRE(!!item); // test operator bool()
            REQUIRE_THROWS({
                item.next();
                item.skip();
            });
        }
    }

}

Add tests for operator bool().


#include "Rainback.hpp"

#include <lua-cxx/LuaEnvironment.hpp>
#include <lua-cxx/LuaValue.hpp>
#include <QFile>

int main(int argc, char* argv[])
{
    Lua lua;
    rainback::Rainback rainback(lua);

    std::string srcdir(getenv("srcdir"));
    QFile testRunner(QString(srcdir.c_str()) + "/test_lua.lua");
    return (bool)lua(testRunner) ? 0 : 1;
}

#include "Rainback.hpp"

#include <lua-cxx/LuaEnvironment.hpp>
#include <lua-cxx/LuaValue.hpp>
#include <QFile>
#include <QCoreApplication>

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

    Lua lua;
    rainback::Rainback rainback(lua);

    std::string srcdir(getenv("srcdir"));
    QFile testRunner(QString(srcdir.c_str()) + "/test_lua.lua");
    return (bool)lua(testRunner) ? 0 : 1;
}

Create a QCoreApplication when testing Lua


// 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 "content/renderer/scheduler/renderer_scheduler.h"

#include "content/renderer/scheduler/null_renderer_scheduler.h"

namespace content {

RendererScheduler::RendererScheduler() {
}

RendererScheduler::~RendererScheduler() {
}

// static
scoped_ptr<RendererScheduler> RendererScheduler::Create() {
  // TODO(rmcilroy): Use the RendererSchedulerImpl when the scheduler is enabled
  return make_scoped_ptr(new NullRendererScheduler());
}

}  // namespace content

// 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 "content/renderer/scheduler/renderer_scheduler.h"

#include "base/command_line.h"
#include "base/message_loop/message_loop_proxy.h"
#include "content/public/common/content_switches.h"
#include "content/renderer/scheduler/null_renderer_scheduler.h"
#include "content/renderer/scheduler/renderer_scheduler_impl.h"

namespace content {

RendererScheduler::RendererScheduler() {
}

RendererScheduler::~RendererScheduler() {
}

// static
scoped_ptr<RendererScheduler> RendererScheduler::Create() {
  CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableBlinkScheduler)) {
    return make_scoped_ptr(new NullRendererScheduler());
  } else {
    return make_scoped_ptr(
        new RendererSchedulerImpl(base::MessageLoopProxy::current()));
  }
}

}  // namespace content

Enable the RendererScheduler by default.


#include "gns/test_util/random_number.h"

namespace gns {
namespace test_util {
  RandomNumber::RandomNumber(const size_t seed)
  : engine_(), distribution_()
  {
  }

  double RandomNumber::operator()()
  {
    return distribution_(engine_);
  }

  double RandomNumber::operator()(const double min, const double max)
  {
    const int diff = max - min;
    return (*this)() * diff + min;
  }
} // namespace test_util
} // namespace gns

#include "gns/test_util/random_number.h"

namespace gns {
namespace test_util {
  RandomNumber::RandomNumber(const size_t seed)
  : engine_(), distribution_()
  {
    engine_.seed(seed);
  }

  double RandomNumber::operator()()
  {
    return distribution_(engine_);
  }

  double RandomNumber::operator()(const double min, const double max)
  {
    const int diff = max - min;
    return (*this)() * diff + min;
  }
} // namespace test_util
} // namespace gns

Fix error in Travic CI


/** @example user_touche.cpp
 Touche example.
 */

#include <ESP.h>

BinaryIntArraySerialStream stream(0, 115200, 160);
GestureRecognitionPipeline pipeline;

void setup()
{
    useInputStream(stream);

    pipeline.addFeatureExtractionModule(TimeseriesBuffer(1, 160));
    pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2));
    usePipeline(pipeline);
}

/** @example user_touche.cpp
 Touche example.
 */

#include <ESP.h>

BinaryIntArraySerialStream stream(0, 115200, 160);
GestureRecognitionPipeline pipeline;

void setup()
{
    useInputStream(stream);

    pipeline.setClassifier(SVM(SVM::POLY_KERNEL, SVM::C_SVC, false, true, true, 0.1, 1.0, 0, 0.5, 2));
    usePipeline(pipeline);
}

Remove Touche feature extraction module.


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

//
// (plesslie)
// posix_time_zone is just parsing the "-XX" portion and subtracting that from UTC meaning
// that it isn't adjusting for daylight savings time.  not sure how to fix that, and I don't
// really care for now.
//
Logger::Logger() : ss_(), tz_(new boost::local_time::posix_time_zone("CST-05")), output_facet_(new boost::local_time::local_time_facet()), input_facet_(new boost::local_time::local_time_input_facet())  {
	ss_.imbue(std::locale(std::locale::classic(), output_facet_));
	ss_.imbue(std::locale(ss_.getloc(), input_facet_));
	output_facet_->format(boost::local_time::local_time_facet::iso_time_format_extended_specifier);
}

Logger::~Logger() {
	delete output_facet_;
	delete input_facet_;
}

Logger& Logger::instance() {
	static Logger logger;
	return logger;
}

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

//
// (plesslie)
// posix_time_zone is just parsing the "-XX" portion and subtracting that from UTC meaning
// that it isn't adjusting for daylight savings time.  not sure how to fix that, and I don't
// really care for now.
//
Logger::Logger() : ss_(), tz_(new boost::local_time::posix_time_zone("CST-05")), output_facet_(new boost::local_time::local_time_facet()), input_facet_(new boost::local_time::local_time_input_facet())  {
	ss_.imbue(std::locale(std::locale::classic(), output_facet_));
	ss_.imbue(std::locale(ss_.getloc(), input_facet_));
	output_facet_->format(boost::local_time::local_time_facet::iso_time_format_extended_specifier);
}

Logger::~Logger() {
	delete input_facet_;
	delete output_facet_;
}

Logger& Logger::instance() {
	static Logger logger;
	return logger;
}

Fix delete ordering for input/output facets


// PluginHelpers.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "pluginhelpers.h"

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

using namespace Abstractspoon::Tdl::PluginHelpers;

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

MarshalledString::MarshalledString(String^ str) : m_wszGlobal(NULL)
{
	m_wszGlobal = (LPCWSTR)Marshal::StringToHGlobalUni(str).ToPointer();
}

MarshalledString::~MarshalledString()
{
	Marshal::FreeHGlobal((IntPtr)(void*)m_wszGlobal);
}

MarshalledString::operator LPCWSTR()
{
	return m_wszGlobal;
}

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

void DialogUtils::SetFont(System::Windows::Forms::Control^ ctrl, System::Drawing::Font^ font)
{
	ctrl->Font = font;

	SetFont(ctrl->Controls, font);
}

void DialogUtils::SetFont(System::Windows::Forms::Control::ControlCollection^ ctrls, System::Drawing::Font^ font)
{
	int nCtrl = ctrls->Count;

	while (nCtrl--)
		SetFont(ctrls[nCtrl], font); // RECURSIVE CALL
}

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

// PluginHelpers.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "pluginhelpers.h"

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

using namespace Abstractspoon::Tdl::PluginHelpers;

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

class ModuleInitialiser
{
public:
	ModuleInitialiser()
	{
		System::Windows::Forms::Application::SetCompatibleTextRenderingDefault(false);
	}
};

static ModuleInitialiser* _init = new ModuleInitialiser();

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

MarshalledString::MarshalledString(String^ str) : m_wszGlobal(NULL)
{
	m_wszGlobal = (LPCWSTR)Marshal::StringToHGlobalUni(str).ToPointer();
}

MarshalledString::~MarshalledString()
{
	Marshal::FreeHGlobal((IntPtr)(void*)m_wszGlobal);
}

MarshalledString::operator LPCWSTR()
{
	return m_wszGlobal;
}

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

void DialogUtils::SetFont(System::Windows::Forms::Control^ ctrl, System::Drawing::Font^ font)
{
	ctrl->Font = font;

	SetFont(ctrl->Controls, font);
}

void DialogUtils::SetFont(System::Windows::Forms::Control::ControlCollection^ ctrls, System::Drawing::Font^ font)
{
	int nCtrl = ctrls->Count;

	while (nCtrl--)
		SetFont(ctrls[nCtrl], font); // RECURSIVE CALL
}

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

Use legacy font rendering for consistency


/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow_lite_support/cc/task/core/error_reporter.h"

#include <cstdarg>
#include <cstdio>
#include <cstring>

#include "tensorflow/lite/minimal_logging.h"

namespace tflite {
namespace task {
namespace core {

int ErrorReporter::Report(const char* format, va_list args) {
  last_message_[0] = '\0';
  int num_characters = vsnprintf(last_message_, kBufferSize, format, args);
  // To mimic tflite::StderrReporter.
  tflite::logging_internal::MinimalLogger::Log(TFLITE_LOG_ERROR, last_message_);
  return num_characters;
}

std::string ErrorReporter::message() { return last_message_; }

}  // namespace core
}  // namespace task
}  // namespace tflite

/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow_lite_support/cc/task/core/error_reporter.h"

#include <cstdarg>
#include <cstdio>
#include <cstring>

#include "tensorflow/lite/minimal_logging.h"

namespace tflite {
namespace task {
namespace core {

int ErrorReporter::Report(const char* format, va_list args) {
  last_message_[0] = '\0';
  int num_characters = vsnprintf(last_message_, kBufferSize, format, args);
  // To mimic tflite::StderrReporter.
  tflite::logging_internal::MinimalLogger::Log(TFLITE_LOG_ERROR, "%s",
                                               last_message_);
  return num_characters;
}

std::string ErrorReporter::message() { return last_message_; }

}  // namespace core
}  // namespace task
}  // namespace tflite

Fix bug where it was assuming that error messages won't contain format strings.


#include <stdlib.h>
#include <string>

// include the sql parser
#include "SQLParser.h"

// contains printing utilities
#include "sqlhelper.h"

int main(int argc, char *argv[]) {
    if (argc <= 1) {
        fprintf(stderr, "Usage: ./example \"SELECT * FROM test;\"\n");
        return -1;
    }
    std::string query = argv[1];

    // parse a given query
    hsql::SQLParserResult* result = hsql::SQLParser::parseSQLString(query);

    // check whether the parsing was successful
    if (result->isValid()) {
        printf("Parsed successfully!\n");
        printf("Number of statements: %lu\n", result->size());

        for (uint i = 0; i < result->size(); ++i) {
            // Print a statement summary.
            hsql::printStatementInfo(result->getStatement(i));
        }

        delete result;
        return 0;
    } else {
        fprintf(stderr, "Given string is not a valid SQL query.\n");
        fprintf(stderr, "%s (L%d:%d)\n",
                result->errorMsg(),
                result->errorLine(),
                result->errorColumn());
        delete result;
        return -1;
    }
}

#include <stdlib.h>
#include <string>

// include the sql parser
#include "SQLParser.h"

// contains printing utilities
#include "sqlhelper.h"

int main(int argc, char *argv[]) {
    if (argc <= 1) {
        fprintf(stderr, "Usage: ./example \"SELECT * FROM test;\"\n");
        return -1;
    }
    std::string query = argv[1];

    // parse a given query
    hsql::SQLParserResult* result = hsql::SQLParser::parseSQLString(query);

    // check whether the parsing was successful
    if (!result) {
        return -1;
    }

    if (result->isValid()) {
        printf("Parsed successfully!\n");
        printf("Number of statements: %lu\n", result->size());

        for (uint i = 0; i < result->size(); ++i) {
            // Print a statement summary.
            hsql::printStatementInfo(result->getStatement(i));
        }

        delete result;
        return 0;
    } else {
        fprintf(stderr, "Given string is not a valid SQL query.\n");
        fprintf(stderr, "%s (L%d:%d)\n",
                result->errorMsg(),
                result->errorLine(),
                result->errorColumn());
        delete result;
        return -1;
    }
}

Check NULL value of result.


// 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 "../client/gles2_lib.h"
#include "../common/thread_local.h"

namespace gles2 {
namespace {
gpu::ThreadLocalKey g_gl_context_key;
}  // namespace anonymous

void Initialize() {
  g_gl_context_key = gpu::ThreadLocalAlloc();
}

void Terminate() {
  gpu::ThreadLocalFree(g_gl_context_key);
  g_gl_context_key = 0;
}

gpu::gles2::GLES2Implementation* GetGLContext() {
  return static_cast<gpu::gles2::GLES2Implementation*>(
    gpu::ThreadLocalGetValue(g_gl_context_key));
}

void SetGLContext(gpu::gles2::GLES2Implementation* context) {
  gpu::ThreadLocalSetValue(g_gl_context_key, context);
}
}  // namespace gles2

// 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 "../client/gles2_lib.h"
#include "../common/thread_local.h"

namespace gles2 {
// TODO(kbr): the use of this anonymous namespace core dumps the
// linker on Mac OS X 10.6 when the symbol ordering file is used
// namespace {
static gpu::ThreadLocalKey g_gl_context_key;
// }  // namespace anonymous

void Initialize() {
  g_gl_context_key = gpu::ThreadLocalAlloc();
}

void Terminate() {
  gpu::ThreadLocalFree(g_gl_context_key);
  g_gl_context_key = 0;
}

gpu::gles2::GLES2Implementation* GetGLContext() {
  return static_cast<gpu::gles2::GLES2Implementation*>(
    gpu::ThreadLocalGetValue(g_gl_context_key));
}

void SetGLContext(gpu::gles2::GLES2Implementation* context) {
  gpu::ThreadLocalSetValue(g_gl_context_key, context);
}
}  // namespace gles2

Work around bug in gcc's name mangling causing linker to crash on Mac OS X.


// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <service>

extern "C" __attribute__((noreturn))
void panic(const char* reason);

__attribute__((noreturn))
extern "C" void abort(){
  panic("Abort called");
}

const char* service_name__ = SERVICE_NAME;
const char* service_binary_name__ = SERVICE;

// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <service>

extern "C" __attribute__((noreturn))
void panic(const char* reason);

extern "C" __attribute__((noreturn))
void abort(){
  panic("Abort called");
}

const char* service_name__ = SERVICE_NAME;
const char* service_binary_name__ = SERVICE;

Fix compile error when using test_ukvm.sh


Return update ever 50 ms (if idle)


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


#include "runtime_internal.h"

#ifdef BITS_64
#define WIN32API
#else
#define WIN32API __stdcall
#endif

extern "C" {

WIN32API void *LoadLibrary(const char *);
WIN32API void *GetProcAddress(void *, const char *);

WEAK void *halide_get_symbol(const char *name) {
    return GetProcAddress(NULL, name);
}

WEAK void *halide_load_library(const char *name) {
    return LoadLibrary(name);
}

WEAK void *halide_get_library_symbol(void *lib, const char *name) {
    return GetProcAddress(lib, name);
}

}

#include "runtime_internal.h"

#ifdef BITS_64
#define WIN32API
#else
#define WIN32API __stdcall
#endif

extern "C" {

WIN32API void *LoadLibraryA(const char *);
WIN32API void *GetProcAddress(void *, const char *);

WEAK void *halide_get_symbol(const char *name) {
    return GetProcAddress(NULL, name);
}

WEAK void *halide_load_library(const char *name) {
    return LoadLibraryA(name);
}

WEAK void *halide_get_library_symbol(void *lib, const char *name) {
    return GetProcAddress(lib, name);
}

}

Fix missing LoadLibrary symbol on windows.


#include "FileOperations.h"
#include <QFile>
#include <QtGlobal>

template <class InputIterator1, class InputIterator2>
bool FileOperations::equal(InputIterator1 first1, InputIterator1 last1,
                           InputIterator2 first2, InputIterator2 last2) {
  while ((first1 != last1) && (first2 != last2)) {
    if (*first1 != *first2) {
      return false;
    }

    ++first1;
    ++first2;
  }

  return (first1 == last1) && (first2 == last2);
}

bool FileOperations::filesEqual(const QString& filePath1,
                                const QString& filePath2) {
  bool equivalent = false;

  QFile file1(filePath1);
  QFile file2(filePath2);

  if (file1.exists() && file2.exists()) {
    file1.open(QFile::ReadOnly);
    uchar* fileMemory1 = file1.map(0, file1.size());

    file2.open(QFile::ReadOnly);
    uchar* fileMemory2 = file2.map(0, file2.size());

    equivalent = equal(fileMemory1, fileMemory1 + file1.size(),
                       fileMemory2, fileMemory2 + file2.size());
  }

  return equivalent;
}

#include "FileOperations.h"
#include <QFile>
#include <QtGlobal>

bool FileOperations::filesEqual(const QString& filePath1,
                                const QString& filePath2) {
  bool equivalent = false;

  QFile file1(filePath1);
  QFile file2(filePath2);

  if (file1.exists() && file2.exists()) {
    file1.open(QFile::ReadOnly);
    file2.open(QFile::ReadOnly);

    while (!file1.atEnd()) {
      QByteArray file1Buffer;

      const qint64 file1BytesRead = file1.read(file1Buffer.data(), 16384);

      if (-1 == file1BytesRead) {
        break;
      }

      QByteArray file2Buffer;

      const qint64 file2BytesRead = file2.read(file2Buffer.data(), 16384);

      if (-1 == file1BytesRead) {
        break;
      }

      if (file1Buffer != file2Buffer) {
        break;
      }

      if (file1.atEnd() && !file2.atEnd()) {
        break;
      }

      if (file1.atEnd() && file2.atEnd()) {
        equivalent = true;
      }
    }
  }

  return equivalent;
}

Use QFile to do file comparison


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_GetViews GetViews
#else
#define MAYBE_GetViews DISABLED_GetViews
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViews) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("get_views")) << message_;
}

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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViews) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("get_views")) << message_;
}

Enable ExtensionApiTest.GetViews on all platforms.


/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file libuco/urbi-main.cc

#include <libport/cli.hh>
#include <libport/containers.hh>
#include <urbi/umain.hh>

extern "C"
{
  int urbi_main(int argc, const char* argv[],
                bool block, bool errors)
  {
    return urbi::main(argc, argv, block, errors);
  }

  int urbi_main_args(const libport::cli_args_type& args,
                     bool block, bool errors)
  {
    return urbi::main(args, block, errors);
  }
}

namespace urbi
{

  int
  main(int argc, const char* argv[], bool block, bool errors)
  {
    libport::cli_args_type args;
    // For some reason, I failed to use std::copy here.
    for (int i = 0; i < argc; ++i)
      args << std::string(argv[i]);
    return main(args, block, errors);
  }

}

/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file libuco/urbi-main.cc

#include <libport/cli.hh>
#include <libport/containers.hh>
#include <urbi/umain.hh>

extern "C"
{
  int urbi_main(int argc, const char* argv[],
                bool block, bool errors)
  {
    libport::program_initialize(argc, const_cast<char**>(argv));

    return urbi::main(argc, argv, block, errors);
  }

  int urbi_main_args(const libport::cli_args_type& args,
                     bool block, bool errors)
  {
    libport::program_initialize(args);

    return urbi::main(args, block, errors);
  }
}

namespace urbi
{

  int
  main(int argc, const char* argv[], bool block, bool errors)
  {
    libport::program_initialize(argc, const_cast<char**>(argv));

    libport::cli_args_type args;
    // For some reason, I failed to use std::copy here.
    for (int i = 0; i < argc; ++i)
      args << std::string(argv[i]);
    return main(args, block, errors);
  }

}

Call libport::program_initialize in every entry point.


#include "gpio.h"
#include "nvic.h"
#include "driver/timer.hpp"

extern "C" void __cxa_pure_virtual() {
    while (1);
}

namespace {

int counter = 0;

void toggle_leds() {
    ++counter;

    auto gpio_n = 17 + (counter & 3);
    gpio_toggle(0, (1 << gpio_n));
}

}

int main(void) {
    nvic_init();

    auto* rtc = driver::Timer::get_by_id(driver::Timer::ID::RTC0);

    rtc->set_prescaler(0xfff - 1);
    rtc->set_irq_handler(toggle_leds);
    rtc->enable_tick_interrupt();
    rtc->start();

    while (1);
}

#include "gpio.h"
#include "nvic.h"
#include "driver/timer.hpp"

#include "memio.h"

namespace {

int counter = 0;

void toggle_leds(int) {
    auto gpio_n = 17 + (counter++ & 3);
    gpio_toggle(0, (1 << gpio_n));
}

}

int main(void) {
    nvic_init();

    gpio_set_option(0, (1 << 17) | (1 << 18) | (1 << 19) | (1 << 20), GPIO_OPT_OUTPUT);

    auto* rtc = driver::Timer::get_by_id(driver::Timer::ID::RTC0);

    rtc->stop();
    rtc->set_prescaler(0xffd);
    rtc->add_event_handler(0, toggle_leds);
    rtc->enable_tick_interrupt();
    rtc->start();

    while (1);
}

Use new API in rtc-blinker app


// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s

template<typename... Types> struct Tuple;

// FIXME: Many more bullets to go

// In a template-argument-list (14.3); the pattern is a template-argument.
template<typename ...Types>
struct tuple_of_refs {
  typedef Tuple<Types& ...> types;
};

Tuple<int&, float&> *t_int_ref_float_ref;
tuple_of_refs<int&, float&>::types *t_int_ref_float_ref_2 =  t_int_ref_float_ref;

// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s

template<typename... Types> struct tuple;

// FIXME: Many more bullets to go

// In a template-argument-list (14.3); the pattern is a template-argument.
template<typename ...Types>
struct tuple_of_refs {
  typedef tuple<Types& ...> types;
};

tuple<int&, float&> *t_int_ref_float_ref;
tuple_of_refs<int&, float&>::types *t_int_ref_float_ref_2 =  t_int_ref_float_ref;

template<typename ...Types>
struct extract_nested_types {
  typedef tuple<typename Types::type...> types;
};

template<typename T>
struct identity {
  typedef T type;
};

tuple<int, float> *t_int_float;
extract_nested_types<identity<int>, identity<float> >::types *t_int_float_2
  = t_int_float;

Test template instantiation of pack expansions where the parameter pack is in a nested-name-specifier


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

int main() {
    char name[_POSIX_HOST_NAME_MAX + 1];
    gethostname(name, sizeof(name));
    std::cout << "Host name: " << name << std::endl;

    unsigned int cores = std::thread::hardware_concurrency();
    std::cout << "Total cores: " << cores << std::endl;

    return 0;
}

#include <iostream>
#include <limits.h>
#include <thread>

int main() {
    unsigned int cores = std::thread::hardware_concurrency();
    std::cout << "Total cores: " << cores << std::endl;

    return 0;
}

Fix Windows build issues by removing posix only code.


#include "Uniforms.h"

namespace ion
{
	namespace Graphics
	{

		template <>
		EValueType IUniformTyped<float>::GetType() const
		{
			return EValueType::Float;
		}

		template <>
		EValueType IUniformTyped<vec2f>::GetType() const
		{
			return EValueType::Float2;
		}

		template <>
		EValueType IUniformTyped<vec3f>::GetType() const
		{
			return EValueType::Float3;
		}

		template <>
		EValueType IUniformTyped<vec4f>::GetType() const
		{
			return EValueType::Float4;
		}

		template <>
		EValueType IUniformTyped<color3f>::GetType() const
		{
			return EValueType::Float3;
		}

		template <>
		EValueType IUniformTyped<color4f>::GetType() const
		{
			return EValueType::Float4;
		}

		template <>
		EValueType IUniformTyped<glm::mat4>::GetType() const
		{
			return EValueType::Matrix4x4;
		}

		template <>
		EValueType IUniformTyped<int>::GetType() const
		{
			return EValueType::SignedInt32;
		}

	}
}

#include "Uniforms.h"

namespace ion
{
	namespace Graphics
	{

		template <>
		EValueType IUniformTyped<float>::GetType() const
		{
			return EValueType::Float;
		}

		template <>
		EValueType IUniformTyped<vec2f>::GetType() const
		{
			return EValueType::Float2;
		}

		template <>
		EValueType IUniformTyped<vec3f>::GetType() const
		{
			return EValueType::Float3;
		}

		template <>
		EValueType IUniformTyped<vec4f>::GetType() const
		{
			return EValueType::Float4;
		}

		template <>
		EValueType IUniformTyped<color3f>::GetType() const
		{
			return EValueType::Float3;
		}

		template <>
		EValueType IUniformTyped<color4f>::GetType() const
		{
			return EValueType::Float4;
		}

		template <>
		EValueType IUniformTyped<glm::mat4>::GetType() const
		{
			return EValueType::Matrix4x4;
		}

		template <>
		EValueType IUniformTyped<int>::GetType() const
		{
			return EValueType::SignedInt32;
		}

		template <>
		EValueType IUniformTyped<uint>::GetType() const
		{
			return EValueType::UnsignedInt32;
		}

	}
}

Add support for uint uniforms


#include <legato.h>
#include <thread>
#include <string>
#include <list>
#include <iostream>

#ifndef MUST_BE_DEFINED
#error MUST_BE_DEFINED was not defined.
#endif

COMPONENT_INIT
{
    LE_INFO("Hello world, from thread 1.");

    std::thread newThread([]()
        {
            le_thread_InitLegatoThreadData("thread 2");

            // This will crash if the Legato thread-specific data has not been initialized.
            le_thread_GetCurrent();

            LE_INFO("Hello world, from %s.", le_thread_GetMyName());

            le_thread_CleanupLegatoThreadData();
        });

    LE_INFO("Thead 2 stared, and waiting for it to complete.");
    newThread.join();

    LE_INFO("Thead 2 ended, all done with init.");

    std::list<std::string> stuff;

    // C++ 11
    for (auto s : stuff)
    {
        std::cout << "stuff: " << s << std::endl;
    }

    exit(EXIT_SUCCESS);
}

#include <legato.h>
#include <thread>
#include <string>
#include <list>
#include <iostream>

#ifndef MUST_BE_DEFINED
#error MUST_BE_DEFINED was not defined.
#endif

COMPONENT_INIT
{
    LE_INFO("Hello world, from thread 1.");

    std::thread newThread([]()
        {
            le_thread_InitLegatoThreadData("thread 2");

            // This will crash if the Legato thread-specific data has not been initialized.
            le_thread_GetCurrent();

            LE_INFO("Hello world, from %s.", le_thread_GetMyName());

            le_thread_CleanupLegatoThreadData();
        });

    LE_INFO("Thead 2 stared, and waiting for it to complete.");
    newThread.join();

    LE_INFO("Thead 2 ended, all done with init.");

    std::list<std::string> stuff;

    // C++ 11
    for (auto const &s : stuff)
    {
        std::cout << "stuff: " << s << std::endl;
    }

    exit(EXIT_SUCCESS);
}

Fix klocwork issues with uninitialized variables in the "apps" module.


#include "HM3Pointers.h"

HM3Pointers::HM3Pointers(HM3Version version)
{
	Setup(version);
}

HM3Pointers::~HM3Pointers()
{

}

void HM3Pointers::Setup(HM3Version version)
{
	uint8_t** difficultyPtr = nullptr;
	uint8_t** timePtr = nullptr;
	switch (version)
	{
	case HM3_GOG:
		m_Stats = (HM3Stats*)0x009B3B38;
		difficultyPtr = (uint8_t**)0x0082083C;
		timePtr = (uint8_t**)0x00820820;
		break;
	case HM3_STEAM:
		m_Stats = (HM3Stats*)0x009B2538;
		difficultyPtr = (uint8_t**)0x0081F83C;
		timePtr = (uint8_t**)0x0081F820;
		break;
	case HM3_UNKNOWN:
		m_Stats = nullptr;
		break;
	}

	m_Difficulty = difficultyPtr != nullptr ? *difficultyPtr + 0x6664 : nullptr;
	m_Time = timePtr != nullptr ? *timePtr + 0x48 : nullptr;
}

#include "HM3Pointers.h"

struct DataAddresses
{
	uint32_t Stats;
	uint32_t DifficultyPtr;
	uint32_t TimePtr;
};

static const DataAddresses DataVersions[]
{
	{ 0x00000000, 0x00000000, 0x00000000 }, // Unknown version
	{ 0x009B2538, 0x0081F83C, 0x0081F820 }, // Steam
	{ 0x009B3B38, 0x0082083C, 0x00820820 }  // GOG
};

HM3Pointers::HM3Pointers(HM3Version version)
{
	Setup(version);
}

HM3Pointers::~HM3Pointers()
{

}

void HM3Pointers::Setup(HM3Version version)
{
	const DataAddresses& addresses(DataVersions[version]);

	m_Stats = (HM3Stats*)addresses.Stats;
	uint8_t** difficultyPtr = (uint8_t**)addresses.DifficultyPtr;
	uint8_t** timePtr = (uint8_t**)addresses.TimePtr;

	m_Difficulty = difficultyPtr != nullptr ? *difficultyPtr + 0x6664 : nullptr;
	m_Time = timePtr != nullptr ? *timePtr + 0x48 : nullptr;
}

Improve structure of encoding different version addresses


//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_networking_sntp.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp =
{
    "nanoFramework.Networking.Sntp",
    0x733B4551,
    method_lookup,
    { 1, 0, 2, 48 }
};

//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_networking_sntp.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp =
{
    "nanoFramework.Networking.Sntp",
    0x733B4551,
    method_lookup,
    { 1, 0, 2, 49 }
};

Update nanoFramework.Networking.Sntp version to 1.0.2-preview-049 ***NO_CI***


#include "Script.hpp"

using namespace Component;

Script::Script(Entity* entity) : SuperComponent(entity) {

}

Json::Value Script::Save() const {
    Json::Value component;
    return component;
}

void Script::Load(const Json::Value& node) {

}

#include "Script.hpp"

using namespace Component;

Script::Script(Entity* entity) : SuperComponent(entity) {

}

Json::Value Script::Save() const {
    Json::Value component;
    component["placeholderValue"] = "";
    return component;
}

void Script::Load(const Json::Value& node) {

}

Add placeholder value to script component


#include "Isosurface.h"

Vector3D Isosurface::gradientAt(float x, float y, float z) const
{
    const float epsilon = 0.0001;

    float dx = valueAt(x + epsilon, y, z) - valueAt(x - epsilon, y, z);
    float dy = valueAt(x, y + epsilon, z) - valueAt(x, y - epsilon, z);
    float dz = valueAt(x, y, z + epsilon) - valueAt(x, y, z - epsilon);

    Vector3D result = { dx, dy, dz };
    normalize(result);
    return result;
}

Isosurface::~Isosurface() {
}

Fix a brace style inconsistency


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents1) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}

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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}

// Disabled, flakily exceeds timeout, http://crbug.com/72165.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebNavigationEvents1) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}

Disable ExtensionApiTest.WebNavigationEvents1, flakily exceeds test timeout


#include "mettle.hpp"
using namespace mettle;

suite<suites_list> test_suite("test suite", [](auto &_) {

  _.test("create a test suite", [](suites_list &suites) {
    suite<> inner("inner test suite", [](auto &_){
      _.test("inner test", []() {});
    }, suites);

    expect(suites, array(&inner));
  });

  _.test("create a test suite with fixture", [](suites_list &suites) {
    suite<int> inner("inner test suite", [](auto &_){
      _.test("inner test", [](int &) {});
    }, suites);

    expect(suites, array(&inner));
  });

});

#include "mettle.hpp"
using namespace mettle;

suite<suites_list> test_suite("test suite", [](auto &_) {

  _.test("create a test suite", [](suites_list &suites) {
    suite<> inner("inner test suite", [](auto &_){
      _.test("inner test", []() {});
    }, suites);

    expect(suites, array(&inner));
  });

  _.test("create a test suite with fixture", [](suites_list &suites) {
    suite<int> inner("inner test suite", [](auto &_){
      _.test("inner test", [](int &) {});
    }, suites);

    expect(suites, array(&inner));
  });

  _.test("create a test suite that throws", [](suites_list &suites) {
    try {
      suite<int> inner("broken test suite", [](auto &){
        throw "bad";
      }, suites);
    } catch(...) {}

    expect(suites, array());
  });

});

Test that test suites with broken initializers don't get added to the list of suites


// 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 "content/renderer/scheduler/renderer_scheduler.h"

#include "base/command_line.h"
#include "base/message_loop/message_loop_proxy.h"
#include "content/public/common/content_switches.h"
#include "content/renderer/scheduler/null_renderer_scheduler.h"
#include "content/renderer/scheduler/renderer_scheduler_impl.h"

namespace content {

RendererScheduler::RendererScheduler() {
}

RendererScheduler::~RendererScheduler() {
}

// static
scoped_ptr<RendererScheduler> RendererScheduler::Create() {
  CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableBlinkScheduler)) {
    return make_scoped_ptr(new NullRendererScheduler());
  } else {
    return make_scoped_ptr(
        new RendererSchedulerImpl(base::MessageLoopProxy::current()));
  }
}

}  // namespace content

// 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 "content/renderer/scheduler/renderer_scheduler.h"

#include "content/renderer/scheduler/null_renderer_scheduler.h"

namespace content {

RendererScheduler::RendererScheduler() {
}

RendererScheduler::~RendererScheduler() {
}

// static
scoped_ptr<RendererScheduler> RendererScheduler::Create() {
  // TODO(rmcilroy): Use the RendererSchedulerImpl when the scheduler is enabled
  return make_scoped_ptr(new NullRendererScheduler());
}

}  // namespace content

Revert "content: Enable the RendererScheduler by default."