#define FPL_AUTO_NAMESPACE
#include <final_platform_layer.hpp>

int main(int argc, char **args) {
	Settings settings = DefaultSettings();
	CopyAnsiString("Software Rendering Example", settings.window.windowTitle, FPL_ARRAYCOUNT(settings.window.windowTitle) - 1);
	settings.video.driverType = VideoDriverType::Software;
	if (InitPlatform(InitFlags::Video, settings)) {
		VideoBackBuffer *videoContext = GetVideoBackBuffer();
		while (WindowUpdate()) {
			uint32_t *p = videoContext->pixels;
			for (uint32_t y = 0; y < videoContext->height; ++y) {
				uint32_t color = 0xFFFF0000;
				for (uint32_t x = 0; x < videoContext->width; ++x) {
					*p++ = color;
				}
			}
			WindowFlip();
		}
		ReleasePlatform();
	}
	return 0;
}

#define FPL_AUTO_NAMESPACE
#include <final_platform_layer.hpp>

struct RandomSeries {
	uint16_t index;
};

static uint16_t RandomU16(RandomSeries &series) {
	series.index ^= (series.index << 13);
    series.index ^= (series.index >> 9);
	series.index ^= (series.index << 7);
	return (series.index);
}

static uint8_t RandomByte(RandomSeries &series) {
	uint8_t result = RandomU16(series) % UINT8_MAX;
	return(result);
}

int main(int argc, char **args) {
	Settings settings = DefaultSettings();
	CopyAnsiString("Software Rendering Example", settings.window.windowTitle, FPL_ARRAYCOUNT(settings.window.windowTitle) - 1);
	settings.video.driverType = VideoDriverType::Software;
	if (InitPlatform(InitFlags::Video, settings)) {
		RandomSeries series = {1337};
		VideoBackBuffer *videoContext = GetVideoBackBuffer();
		while (WindowUpdate()) {
			uint32_t *p = videoContext->pixels;
			for (uint32_t y = 0; y < videoContext->height; ++y) {
				for (uint32_t x = 0; x < videoContext->width; ++x) {
					uint8_t r = RandomByte(series);
					uint8_t g = RandomByte(series);
					uint8_t b = RandomByte(series);
					uint32_t color = (0xFF << 24) | (r << 16) | (g << 8) | b;
					*p++ = color;
				}
			}
			WindowFlip();
		}
		ReleasePlatform();
	}
	return 0;
}

Use random for software rendering demo


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

#include "SkFontHost.h"
#include "SkTypeface.h"
#include "SkTypeface_win.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

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

#include "SkFontHost.h"
#include "SkTypeface.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

Remove unneeded include which is breaking build.


#include "side_pane.hpp"

#include <cppurses/painter/color.hpp>
#include <cppurses/painter/glyph.hpp>
#include <cppurses/widget/widgets/text_display.hpp>

using namespace cppurses;

namespace demos {
namespace glyph_paint {

Side_pane::Side_pane() {
    this->width_policy.fixed(16);

    space1.wallpaper = L'─';
    space2.wallpaper = L'─';

    glyph_select.height_policy.preferred(6);
    color_select_stack.height_policy.fixed(3);

    for (auto& child : color_select_stack.top_row.children.get()) {
        child->brush.set_background(Color::Light_gray);
        child->brush.set_foreground(Color::Black);
    }

    show_glyph.height_policy.fixed(1);
    show_glyph.set_alignment(Alignment::Center);
}
}  // namespace glyph_paint
}  // namespace demos

#include "side_pane.hpp"

#include <cppurses/painter/color.hpp>
#include <cppurses/painter/glyph.hpp>
#include <cppurses/widget/widgets/text_display.hpp>

using namespace cppurses;

namespace demos {
namespace glyph_paint {

Side_pane::Side_pane() {
    this->width_policy.fixed(16);

    space1.wallpaper = L'─';
    space2.wallpaper = L'─';

    glyph_select.height_policy.preferred(6);
    color_select_stack.height_policy.fixed(3);

    show_glyph.height_policy.fixed(1);
    show_glyph.set_alignment(Alignment::Center);
}
}  // namespace glyph_paint
}  // namespace demos

Remove duplicate brush color set in glyph paint cycle box.


// Copyright (c) 2017 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 "quic/test_tools/failing_proof_source.h"

#include "absl/strings/string_view.h"

namespace quic {
namespace test {

void FailingProofSource::GetProof(const QuicSocketAddress& /*server_address*/,
                                  const QuicSocketAddress& /*client_address*/,
                                  const std::string& /*hostname*/,
                                  const std::string& /*server_config*/,
                                  QuicTransportVersion /*transport_version*/,
                                  absl::string_view /*chlo_hash*/,
                                  std::unique_ptr<Callback> callback) {
  callback->Run(false, nullptr, QuicCryptoProof(), nullptr);
}

QuicReferenceCountedPointer<ProofSource::Chain>
FailingProofSource::GetCertChain(const QuicSocketAddress& /*server_address*/,
                                 const QuicSocketAddress& /*client_address*/,
                                 const std::string& /*hostname*/,
                                 bool* /*cert_matched_sni*/) {
  return QuicReferenceCountedPointer<Chain>();
}

void FailingProofSource::ComputeTlsSignature(
    const QuicSocketAddress& /*server_address*/,
    const QuicSocketAddress& /*client_address*/,
    const std::string& /*hostname*/,
    uint16_t /*signature_algorithm*/,
    absl::string_view /*in*/,
    std::unique_ptr<SignatureCallback> callback) {
  callback->Run(false, "", nullptr);
}

}  // namespace test
}  // namespace quic

// Copyright (c) 2017 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 "quic/test_tools/failing_proof_source.h"

#include "absl/strings/string_view.h"

namespace quic {
namespace test {

void FailingProofSource::GetProof(const QuicSocketAddress& /*server_address*/,
                                  const QuicSocketAddress& /*client_address*/,
                                  const std::string& /*hostname*/,
                                  const std::string& /*server_config*/,
                                  QuicTransportVersion /*transport_version*/,
                                  absl::string_view /*chlo_hash*/,
                                  std::unique_ptr<Callback> callback) {
  callback->Run(false, nullptr, QuicCryptoProof(), nullptr);
}

QuicReferenceCountedPointer<ProofSource::Chain>
FailingProofSource::GetCertChain(const QuicSocketAddress& /*server_address*/,
                                 const QuicSocketAddress& /*client_address*/,
                                 const std::string& /*hostname*/,
                                 bool* cert_matched_sni) {
  *cert_matched_sni = false;
  return QuicReferenceCountedPointer<Chain>();
}

void FailingProofSource::ComputeTlsSignature(
    const QuicSocketAddress& /*server_address*/,
    const QuicSocketAddress& /*client_address*/,
    const std::string& /*hostname*/,
    uint16_t /*signature_algorithm*/,
    absl::string_view /*in*/,
    std::unique_ptr<SignatureCallback> callback) {
  callback->Run(false, "", nullptr);
}

}  // namespace test
}  // namespace quic

Fix an ASAN failure in //third_party/quic/core:tls_server_handshaker_test by always setting *cert_matched_sni in GetCertChain().


#include <test/unit/math/test_ad.hpp>

TEST(MathMixMatFun, reverse) {
  auto f = [](const auto& x) { return stan::math::reverse(x); };

  // 0 x 0
  Eigen::VectorXd x0(0);
  stan::test::expect_ad(f, x0);

  // 1 x 1
  Eigen::VectorXd x1(1);
  x1 << 1;
  stan::test::expect_ad(f, x1);

  // 4 x 4
  Eigen::VectorXd x(4);
  x << 1, 3, 4, -5;
  stan::test::expect_ad(f, x);
}

#include <test/unit/math/test_ad.hpp>
#include <vector>

TEST(MathMixMatFun, reverse_vector) {
  auto f = [](const auto& x) { return stan::math::reverse(x); };

  // 0 x 0
  Eigen::VectorXd x0(0);
  stan::test::expect_ad(f, x0);

  // 1 x 1
  Eigen::VectorXd x1(1);
  x1 << 1;
  stan::test::expect_ad(f, x1);

  // 4 x 4
  Eigen::VectorXd x(4);
  x << 1, 3, 4, -5;
  stan::test::expect_ad(f, x);
}

TEST(MathMixMatFun, reverse_row_vector) {
  auto f = [](const auto& x) { return stan::math::reverse(x); };

  // 0 x 0
  Eigen::RowVectorXd x0(0);
  stan::test::expect_ad(f, x0);

  // 1 x 1
  Eigen::RowVectorXd x1(1);
  x1 << 1;
  stan::test::expect_ad(f, x1);

  // 4 x 4
  Eigen::RowVectorXd x(4);
  x << 1, 3, 4, -5;
  stan::test::expect_ad(f, x);
}

TEST(MathMixMatFun, reverse_array) {
  auto f = [](const auto& x) { return stan::math::reverse(x); };

  // 0 x 0
  std::vector<double> x0(0);
  stan::test::expect_ad(f, x0);

  // 1 x 1
  std::vector<double> x1{1};
  stan::test::expect_ad(f, x1);

  // 4 x 4
  std::vector<double> x{1, 3, 4, -5};
  stan::test::expect_ad(f, x);
}

Add tests for row vector and array


#include "stdafx.h"
#include "CppUnitTest.h"
#include "../DNAnalyzerServer/Dictionnaire.h"
#include "../DNAnalyzerServer/Mots.h"
#include <exception>
#include <unordered_set>
#include <cstring>
#include <string>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace DNAnalyzerServerTest
{
	TEST_CLASS(DictionnaireTest)
	{
	public:
		//ObtenirInstance
		TEST_METHOD(ObtenirInstance_NotNull)
		{
			// L'instance retourne ne doit pas tre null
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);
		}

		TEST_METHOD(ObtenirInstance_SameReference)
		{
			// L'instance retourne doit toujours tre la mme
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));
		}
		TEST_METHOD(ObtenirMaladie_KnownMaladie) {

		}
		TEST_METHOD(ObtenirMaladie_UnKnownMaladie) {

		}
		TEST_METHOD(ObtenirMaladies_NoMaladies) {
			char motInexistant[] = "ATCGINEXISTANT";
			unsigned int indexMotInexistant = Mots::ObtenirInstance().InsererMot(motInexistant);
			const unordered_set<const Maladie*> resutat = Dictionnaire::ObtenirInstance().ObtenirMaladies(indexMotInexistant);
			Assert::AreEqual(resutat.size, 0);
		}
		TEST_METHOD(ObtenirMaladies_OneMaladies) {

		}
		TEST_METHOD(ObtenirMaladies_TwoMaladies) {

		}
		TEST_METHOD(ObtenirNomMaladies_EmptyDictionnaire) {

		}
		TEST_METHOD(ObtenirNomMaladies_NotEmptyDictionnaire) {

		}
	};
}

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../DNAnalyzerServer/Dictionnaire.h"
#include <exception>
#include <cstring>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace DNAnalyzerServerTest
{
	TEST_CLASS(DictionnaireTest)
	{
	public:
		//ObtenirInstance
		TEST_METHOD(ObtenirInstance_NotNull)
		{
			// L'instance retourne ne doit pas tre null
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);
		}

		TEST_METHOD(ObtenirInstance_SameReference)
		{
			// L'instance retourne doit toujours tre la mme
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));
		}
	};
}

Revert "Ajout de methode de test (incomplete) de Dictionnaire"


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

  Library:   CTK

  Copyright (c) 2010  Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.commontk.org/LICENSE

  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.

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

// Qt includes
#include <QApplication>

// CTK includes
#include "ctkDateRangeWidget.h"

// STD includes
#include <cstdlib>
#include <iostream>

//-----------------------------------------------------------------------------
int ctkDateRangeWidgetTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);

  ctkDateRangeWidget dateRange;

  dateRange.show();
  return EXIT_SUCCESS;
}

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

  Library:   CTK

  Copyright (c) 2010  Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.commontk.org/LICENSE

  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.

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

// Qt includes
#include <QApplication>
#include <QTimer>

// CTK includes
#include "ctkDateRangeWidget.h"

// STD includes
#include <cstdlib>
#include <iostream>

//-----------------------------------------------------------------------------
int ctkDateRangeWidgetTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);

  ctkDateRangeWidget dateRange;
  dateRange.show();
  dateRange.onToday();
  dateRange.onYesterday();
  dateRange.onAnyDate();
  dateRange.onLastMonth();
  dateRange.onLastWeek();
  dateRange.onSelectRange();

  return EXIT_SUCCESS;
}

Add extra date range widget tests


#include <iostream>
#include "Crown.h"
#include "lua.hpp"
#include <unistd.h>

using namespace crown;

static void report_errors(lua_State* state, const int status)
{
  if (status != 0)
  {
    std::cerr << "-- " << lua_tostring(state, -1) << std::endl;

    lua_pop(state, 1);
  }
}

int main(int argc, char** argv)
{
  lua_State* lua_state;

  Filesystem fs("/home/mikymod/test/res_compiled");

  FileResourceArchive archive(fs);

  MallocAllocator allocator;

  ResourceManager res_manager(archive, allocator);

  ResourceId script = res_manager.load("lua/hello.lua");

  res_manager.flush();

  while (1)
  {
    if (res_manager.is_loaded(script))
    {

      lua_state = luaL_newstate();
      luaL_openlibs(lua_state);

      ScriptResource* resource = (ScriptResource*)res_manager.data(script);

      int s = luaL_loadbuffer(lua_state, (char*)resource->data(), 47, "");

      if (s == 0)
      {
        s = lua_pcall(lua_state, 0, LUA_MULTRET, 0);
      }

      report_errors(lua_state, s);

      break;
    }
  }

  lua_close(lua_state);

  return 0;
}

#include <iostream>
#include "Crown.h"
#include "lua.hpp"
#include <unistd.h>

using namespace crown;

static void report_errors(lua_State* state, const int status)
{
  if (status != 0)
  {
    std::cerr << "-- " << lua_tostring(state, -1) << std::endl;

    lua_pop(state, 1);
  }
}

int main(int argc, char** argv)
{
  lua_State* lua_state;

  Filesystem fs("/home/mikymod/test/res_compiled");

  FileResourceArchive archive(fs);

  ResourceManager res_manager(archive);

  ResourceId script = res_manager.load("lua/hello.lua");

  res_manager.flush();

  while (1)
  {
    if (res_manager.is_loaded(script))
    {

      lua_state = luaL_newstate();
      luaL_openlibs(lua_state);

      ScriptResource* resource = (ScriptResource*)res_manager.data(script);

      int s = luaL_loadbuffer(lua_state, (char*)resource->data(), 47, "");

      if (s == 0)
      {
        s = lua_pcall(lua_state, 0, LUA_MULTRET, 0);
      }

      report_errors(lua_state, s);

      break;
    }
  }

  lua_close(lua_state);

  return 0;
}

Fix building of the engine


#include <Magick++/Functions.h>
#include <Magick++/ResourceLimits.h>
#include <Magick++/SecurityPolicy.h>

#ifndef FUZZ_MAX_SIZE
#define FUZZ_MAX_SIZE 2048
#endif

class FuzzingInitializer {
public:
  FuzzingInitializer() {
    Magick::InitializeMagick((const char *) NULL);
    Magick::SecurityPolicy::maxMemoryRequest(256000000);
    Magick::ResourceLimits::memory(1000000000);
    Magick::ResourceLimits::map(500000000);
    Magick::ResourceLimits::width(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::height(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::listLength(32);
  }
};

FuzzingInitializer fuzzingInitializer;

#if BUILD_MAIN
#include "encoder_format.h"

EncoderFormat encoderFormat;

#define FUZZ_ENCODER encoderFormat.get()
#endif // BUILD_MAIN

#include <Magick++/Functions.h>
#include <Magick++/ResourceLimits.h>
#include <Magick++/SecurityPolicy.h>

#ifndef FUZZ_MAX_SIZE
#define FUZZ_MAX_SIZE 2048
#endif

class FuzzingInitializer {
public:
  FuzzingInitializer() {

    // Disable SIMD in jpeg turbo.
    (void) putenv(const_cast<char *>("JSIMD_FORCENONE=1"));

    Magick::InitializeMagick((const char *) NULL);
    Magick::SecurityPolicy::maxMemoryRequest(256000000);
    Magick::ResourceLimits::memory(1000000000);
    Magick::ResourceLimits::map(500000000);
    Magick::ResourceLimits::width(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::height(FUZZ_MAX_SIZE);
    Magick::ResourceLimits::listLength(32);
  }
};

FuzzingInitializer fuzzingInitializer;

#if BUILD_MAIN
#include "encoder_format.h"

EncoderFormat encoderFormat;

#define FUZZ_ENCODER encoderFormat.get()
#endif // BUILD_MAIN

Disable SIMD in jpeg turbo as suggested to check if that fixes the uninitialised memory issue.


#include "main_window.hpp"
#include <QVBoxLayout>
#include <QMessageBox>
#include "executable_viewer.hpp"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    setWindowTitle(QString("Interactive Executable Mangler"));

    mdiArea = new QMdiArea();

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(mdiArea);

    QMenu *file = menuBar()->addMenu(QString("File"));
    QWidget *central = new QWidget(this);
    central->setLayout(layout);
    setCentralWidget(central);

    createActions();

    file->addAction(newAction);
    file->addAction(aboutAction);
}

void MainWindow::createActions()
{
    newAction = new QAction(QString("New"), this);
    aboutAction = new QAction(QString("About"), this);
    connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
}

void MainWindow::newFile()
{
    QString filename("hacker.out");
    ExecutableViewer *viewer = new ExecutableViewer(filename, mdiArea);
    mdiArea->addSubWindow(viewer);
    viewer->show();
    mdiArea->tileSubWindows();
}

void MainWindow::about()
{
    QMessageBox::about(this, QString("About"),
        QString("
Ștefan Mirea & Adrian Dobrică 2016.

Click!
"));
}

#include "main_window.hpp"
#include <QMessageBox>
#include "executable_viewer.hpp"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    setWindowTitle(QString("Interactive Executable Mangler"));

    mdiArea = new QMdiArea();

    QMenu *file = menuBar()->addMenu(QString("File"));
    setCentralWidget(mdiArea);

    createActions();

    file->addAction(newAction);
    file->addAction(aboutAction);
}

void MainWindow::createActions()
{
    newAction = new QAction(QString("New"), this);
    aboutAction = new QAction(QString("About"), this);
    connect(newAction, SIGNAL(triggered()), this, SLOT(newFile()));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
}

void MainWindow::newFile()
{
    QString filename("hacker.out");
    ExecutableViewer *viewer = new ExecutableViewer(filename, mdiArea);
    mdiArea->addSubWindow(viewer);
    viewer->show();
    mdiArea->tileSubWindows();
}

void MainWindow::about()
{
    QMessageBox::about(this, QString("About"),
        QString("
Ștefan Mirea & Adrian Dobrică 2016.

Click!
"));
}

Use mdiArea directly as the window's central widget


#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    pushall(h,i)

    i <- d == 0
    jnzrel(i, L_done)

L_top:
    h <- d & 1
    i <- h <> 0
    i <- c & i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

L_done:
    popall(h,i)
    ret

#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    pushall(h,i,j,k)

    i <- d == 0
    jnzrel(i, L_done)
    h <- 1
    b <- 0

    j <- c >> 31    // save sign bit in j
    j <- -j         // convert sign to flag
    c <- c ^ j      // adjust multiplicand
    c <- c - j

    k <- d >> 31    // save sign bit in k
    k <- -k         // convert sign to flag
    d <- d ^ k      // adjust multiplier
    d <- d - k

    j <- j ^ k      // final flip flag is in j

L_top:
    // use constant 1 in h to combine instructions
    i <- d & h - 1
    i <- c &~ i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

L_done:
    b <- b ^ j      // adjust product for signed math
    b <- b - j

    popall(h,i,j,k)
    ret

Support signed numbers in imul


#include "UnitTest++/UnitTest++.h"

#include <fstream>
#include <cereal/archives/binary.hpp>

SUITE( CerealTest )
{
    TEST( basicSaveAndLoad )
    {
        const std::string saveFileName = "CerealTest";
        const int expectedData = 42;
        int actualData = 666;

        {
            std::ofstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryOutputArchive archive( file );
            archive( expectedData );
        }

        {
            std::ifstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryInputArchive archive( file );
            archive( actualData );
        }

        CHECK_EQUAL( expectedData, actualData );

        // Delete save file
        CHECK( !remove( saveFileName.data() ) ) ;
    }
}

#include "UnitTest++/UnitTest++.h"

#include <fstream>
#include <cereal/archives/binary.hpp>

class Base
{
    public:
        Base() : someConstant(1)
        {
        }

    private:
        const int someConstant;

        friend cereal::access;
        template < class Archive >
        void serialize( Archive & ar )
        {
            ar( const_cast< int & >( someConstant ) );
        }
};

SUITE( CerealTest )
{
    TEST( basicSaveAndLoad )
    {
        const std::string saveFileName = "CerealTest";
        const int expectedData = 42;
        int actualData = 666;

        {
            std::ofstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryOutputArchive archive( file );
            archive( expectedData );
        }

        {
            std::ifstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryInputArchive archive( file );
            archive( actualData );
        }

        CHECK_EQUAL( expectedData, actualData );

        // Delete save file
        CHECK( !remove( saveFileName.data() ) ) ;
    }

    TEST( loadConstantVariable )
    {
        const std::string saveFileName = "CerealTest";
        const int expectedData = 42;
        const int actualData = 666;

        {
            std::ofstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryOutputArchive archive( file );
            archive( expectedData );
        }

        {
            std::ifstream file( saveFileName, std::ios::binary );
            CHECK( !file.fail() );

            cereal::BinaryInputArchive archive( file );
            archive( const_cast< int & >( actualData ) );
        }

        CHECK_EQUAL( expectedData, actualData );

        // Delete save file
        CHECK( !remove( saveFileName.data() ) ) ;
    }
}

Test cereal for loading a constant variable (using a const_cast)


#include "variables.hpp"

#ifdef _VARS
std::ostream& var_defs_stream = cerr;
#endif

#include "variables.hpp"

#ifdef _VARS
std::ostream& var_defs_stream = cout;
#endif

Print variable debug output to stdout


/* This file is part of the KDE libraries
   Copyright (C) 2003 Hamish Rodda <rodda@kde.org>
   Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

#include "editinterfaceext.h"
#include "document.h"

using namespace KTextEditor;

uint EditInterfaceExt::globalEditInterfaceExtNumber = 0;

EditInterfaceExt::EditInterfaceExt()
	: d(0L)
{
  globalEditInterfaceExtNumber++;
  myEditInterfaceExtNumber = globalEditInterfaceExtNumber;
}

EditInterfaceExt::~EditInterfaceExt()
{
}

uint EditInterfaceExt::editInterfaceExtNumber() const
{
  return myEditInterfaceExtNumber;
}

EditInterfaceExt *KTextEditor::editInterfaceExt (Document *doc)
{
  if (!doc)
    return 0;

  return static_cast<EditInterfaceExt*>(doc->qt_cast("KTextEditor::EditInterfaceExt"));
}

Add licence (yes, this means that editinterface.cpp has no licence)


#include "NMakefile.hpp"

#include <configure/Build.hpp>
#include <configure/Filesystem.hpp>
#include <configure/quote.hpp>

namespace configure { namespace generators {

	std::string NMakefile::name() const
	{ return "NMakefile"; }

	bool NMakefile::is_available(Build& build) const
	{
		return build.fs().which("nmake") != boost::none;
	}

	void NMakefile::dump_command(
		    std::ostream& out,
		    std::vector<std::string> const& cmd) const
	{
		out << quote<CommandParser::nmake>(cmd);
	}

	std::vector<std::string>
	NMakefile::build_command(Build& build, std::string const& target) const
	{
		return {
			"nmake", "-f", (build.directory() / "Makefile").string(),
			target.empty() ? "all" : target
		};
	}

}}

#include "NMakefile.hpp"

#include <configure/Build.hpp>
#include <configure/Filesystem.hpp>
#include <configure/quote.hpp>

namespace configure { namespace generators {

	std::string NMakefile::name() const
	{ return "NMakefile"; }

	bool NMakefile::is_available(Build& build) const
	{
		return build.fs().which("nmake") != boost::none;
	}

	void NMakefile::dump_command(
		    std::ostream& out,
		    std::vector<std::string> const& cmd) const
	{
		out << quote<CommandParser::nmake>(cmd);
	}

	std::vector<std::string>
	NMakefile::build_command(Build& build, std::string const& target) const
	{
		return {
			"nmake", "-nologo", "-f", (build.directory() / "Makefile").string(),
			target.empty() ? "all" : target
		};
	}

}}

Add -nologo in nmake command lines.


#include "analyzer.h"

#include "dal.h"

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

namespace holmes {

kj::Promise<bool> Analyzer::run(DAL *dal) {
  std::vector<Holmes::Fact::Reader> searchedFacts;
  auto ctxs = dal->getFacts(premises);
  kj::Array<kj::Promise<bool>> analResults =
    KJ_MAP(ctx, ctxs) {
      if (cache.miss(ctx)) {
        auto req = analysis.analyzeRequest();
        auto ctxBuilder = req.initContext(ctx.size());
        auto dex = 0;
        for (auto&& val : ctx) {
          ctxBuilder.setWithCaveats(dex++, val);
        }
        return req.send().then([this, dal, ctx = kj::mv(ctx)](Holmes::Analysis::AnalyzeResults::Reader res){
          auto dfs = res.getDerived();
          bool dirty = false;
          if (dal->setFacts(dfs) != 0) {
            dirty = true;
          }
          cache.add(ctx);
          return dirty;
        });
      }
      return kj::Promise<bool>(false);
    };
  return kj::joinPromises(kj::mv(analResults)).then([this](kj::Array<bool> x){
    bool dirty = false;
    for (auto v : x) {
      dirty |= v;
    }
    return dirty;
  });
}

}

#include "analyzer.h"

#include "dal.h"

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

namespace holmes {

kj::Promise<bool> Analyzer::run(DAL *dal) {
  std::vector<Holmes::Fact::Reader> searchedFacts;
  DLOG(INFO) << "Starting analysis " << name;
  DLOG(INFO) << "Getting facts for " << name;
  auto ctxs = dal->getFacts(premises);
  DLOG(INFO) << "Got facts for " << name;
  kj::Array<kj::Promise<bool>> analResults =
    KJ_MAP(ctx, ctxs) {
      if (cache.miss(ctx)) {
        auto req = analysis.analyzeRequest();
        auto ctxBuilder = req.initContext(ctx.size());
        auto dex = 0;
        for (auto&& val : ctx) {
          ctxBuilder.setWithCaveats(dex++, val);
        }
        return req.send().then([this, dal, ctx = kj::mv(ctx)](Holmes::Analysis::AnalyzeResults::Reader res){
          auto dfs = res.getDerived();
          bool dirty = false;
          if (dal->setFacts(dfs) != 0) {
            dirty = true;
          }
          cache.add(ctx);
          return dirty;
        });
      }
      return kj::Promise<bool>(false);
    };
  return kj::joinPromises(kj::mv(analResults)).then([this](kj::Array<bool> x){
    bool dirty = false;
    for (auto v : x) {
      dirty |= v;
    }
    DLOG(INFO) << "Finished analysis " << name;
    return dirty;
  });
}

}

Add logging to analysis for profiling


#include <PIDController.h>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
	PIDController* pid = new PIDController(1,0,0,-100,100);

    pid->on();
    pid->targetSetpoint(100);
    pid->off();

    cout << "Hello World!" << endl;

	return 0;
}

#include <PIDController.h>
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
	PIDController* pid = new PIDController(5,0.5,0.25,-100,100);

    pid->on(); // Turn PID controller on
    pid->targetSetpoint(10); // Change desired setpoint to 10

    double t = 0; // Init with time t=0
    double controlVariable = 0; // Init with zero actuation
    double processVariable = 0; // Init with zero position

    while(1) {
        controlVariable = pid->calc(processVariable); // Calculate next controlVariable
        processVariable += controlVariable/(20 + ((rand() % 11) - 5)); // Arbitrary function to simulate a plant

        cout << "Time: " << t << ", Setpoint: " << pid->getSetpoint() << ", PV: " << processVariable << endl;

        usleep(100000); // 100ms delay to simulate actuation time
        t += 0.1; // Increment time variable by 100ms
    }

	return 0;
}

Update example to be actually somewhat useful


#include "gtest/gtest.h"

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

#include "gtest/gtest.h"
#include "sodium.h"

int main(int argc, char **argv) {
  assert(sodium_init() != -1);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Initialize libsodium in the gtest suite.


#include "../../include/core/StateCell.hpp"
#include "../../include/core/Cell.hpp"

bool StateCell::isState(StateCell* state) const
{
  return state == this; //All state are singletons, so if state has the same class as this, it is the same instance
}

EmptyCell::EmptyCell()
{}

EmptyCell* EmptyCell::instance = new EmptyCell();

EmptyCell* EmptyCell::emptyCell()
{
  return instance;
}

std::string EmptyCell::toString() const
{
  return "EmptyCell";
}

StateCell* EmptyCell::iterate(Cell const* cell)
{
  return AliveCell::aliveCell();
}

AliveCell::AliveCell()
{}

AliveCell* AliveCell::instance = new AliveCell();

AliveCell* AliveCell::aliveCell()
{
  return instance;
}

std::string AliveCell::toString() const
{
  return "AliveCell";
}

StateCell* AliveCell::iterate(Cell const* cell)
{
  return EmptyCell::emptyCell();
}

#include "../../include/core/StateCell.hpp"
#include "../../include/core/Cell.hpp"

bool StateCell::isState(StateCell* state) const
{
  return state == this; //All state are singletons, so if state has the same class as this, it is the same instance
}

EmptyCell::EmptyCell()
{}

EmptyCell* EmptyCell::instance = new EmptyCell();

EmptyCell* EmptyCell::emptyCell()
{
  return instance;
}

std::string EmptyCell::toString() const
{
  return "EmptyCell";
}

StateCell* EmptyCell::iterate(Cell const* cell)
{
  int nbAliveNeighbors(0);
  std::vector<Cell const*> neighbors = cell->getNeighbors();

  for(int i = 0; i < neighbors.size(); i++)
  {
    if(neighbors[i]->isState(AliveCell::aliveCell()))
    {
      nbAliveNeighbors++;
    }
  }

  if(nbAliveNeighbors > 2)
    return AliveCell::aliveCell();
  else
    return EmptyCell::emptyCell();
}

AliveCell::AliveCell()
{}

AliveCell* AliveCell::instance = new AliveCell();

AliveCell* AliveCell::aliveCell()
{
  return instance;
}

std::string AliveCell::toString() const
{
  return "AliveCell";
}

StateCell* AliveCell::iterate(Cell const* cell)
{
  int nbAliveNeighbors(0);
  std::vector<Cell const*> neighbors = cell->getNeighbors();

  for(int i = 0; i < neighbors.size(); i++)
  {
    if(neighbors[i]->isState(AliveCell::aliveCell()))
    {
      nbAliveNeighbors ++;
    }
  }

  if(nbAliveNeighbors < 2) //Solitude
    return EmptyCell::emptyCell();
  else if(nbAliveNeighbors > 3) //Surpopulation
    return EmptyCell::emptyCell();
  else
    return AliveCell::aliveCell();
}

Modify states methods to implement the game of life


#include <QtCore/QList>

struct SmallType {
    char a[8];
};

struct BigType {
    char a[9];
};

void foo()
{
    QList<BigType> bigT; // Warning
    QList<SmallType> smallT; // OK
}

class A {
public:
    void foo()
    {
        m_big.clear();
    }

    QList<BigType> m_big; // Warning
};

void foo1(QList<BigType> big2)
{
    QList<BigType> bigt; // Warning
    bigt = big2;
}

void test_bug358740()
{
    QList<int> list; // OK
    int a, b;
}

Add test-case for a bug report


// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "commctrl.h"
#include "accctrl.h"

BOOL APIENTRY DllMain(
    HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
    }

    return TRUE;
}

// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "commctrl.h"
#include "accctrl.h"
#include "shellapi.h"
#include "shlobj.h"

BOOL APIENTRY DllMain(
    HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
            break;
    }

    return TRUE;
}

Add shell includes to test project for searching purposes


#include "test.h"

// When defining a facility, it has to occur before including the logger.
#define VAST_LOG_FACILITY "test"
#include "vast/logger.h"

#if VAST_LOG_LEVEL >= 5

using namespace vast;

int foo()
{
  VAST_ENTER();
  VAST_RETURN(-1);
  return -1;
};

void bar(int i, std::string s, char c)
{
  VAST_ENTER(VAST_ARG(i, s, c));
  VAST_MSG("about to call foo");
  foo();
  VAST_LEAVE("leaving with a message");
};

BOOST_AUTO_TEST_CASE(logging_test)
{
  foo();
  bar(42, "***", 'A');
}

#endif

#include "test.h"

// When defining a facility, it has to occur before including the logger.
#define VAST_LOG_FACILITY "test"
#include "vast/logger.h"

#if VAST_LOG_LEVEL > 5

using namespace vast;

int foo()
{
  VAST_ENTER();
  VAST_RETURN(-1);
  return -1;
};

void bar(int i, std::string s, char c)
{
  VAST_ENTER(VAST_ARG(i, s, c));
  VAST_MSG("about to call foo");
  foo();
  VAST_LEAVE("leaving with a message");
};

BOOST_AUTO_TEST_CASE(logging_test)
{
  foo();
  bar(42, "***", 'A');
}

#endif

Define tracing unit tests with proper log level.


// FIXME: Same as test/asan/TestCases/Linux/odr-violation.cc ?
// XFAIL: android

// RUN: %clangxx_asan -fno-rtti -DBUILD_SO1 -fPIC -shared %s -o %t1.so
// RUN: %clangxx_asan -fno-rtti -DBUILD_SO2 -fPIC -shared %s -o %t2.so
// RUN: %clangxx_asan -fno-rtti %t1.so %t2.so %s -Wl,-R. -o %t
// RUN: %env_asan_opts=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t 2>&1 | FileCheck %s

struct XYZ {
  virtual void foo();
};

#if defined(BUILD_SO1)

void XYZ::foo() {}

#elif defined(BUILD_SO2)

void XYZ::foo() {}

#else

int main() {}

#endif

// CHECK: AddressSanitizer: odr-violation
// CHECK-NEXT: 'vtable for XYZ'
// CHECK-NEXT: 'vtable for XYZ'

Disable ODR test on Android


#include "PolarisBlock.h"

#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketAcceptor.h"
#include "PolarisConnection.h"

using Poco::Net::ServerSocket;
using Poco::Net::SocketReactor;
using Poco::Net::SocketAcceptor;
using Poco::Thread;

int main(int argc, char** argv) {
    return PolarisBlockApp().run(argc, argv);
}

int PolarisBlockApp::main(const std::vector<std::string> &args) {
    // Create + Bind socket
    ServerSocket blockSocket(12201); // TODO Config file / Argument / Whatever

    // Make the reactor
    SocketReactor reactor;

    // Assign the Connector
    SocketAcceptor<PolarisConnection> acceptor(blockSocket, reactor);

    Thread thread;
    logger().information("Starting reactor...");
    thread.start(reactor);

    waitForTerminationRequest();

    reactor.stop();
    thread.join();

    return Application::EXIT_OK;
}

#include "PolarisBlock.h"

#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketAcceptor.h"
#include "Poco/Thread.h"
#include "PolarisConnection.h"

using Poco::Net::ServerSocket;
using Poco::Net::SocketReactor;
using Poco::Net::SocketAcceptor;
using Poco::Thread;

int main(int argc, char** argv) {
    return PolarisBlockApp().run(argc, argv);
}

int PolarisBlockApp::main(const std::vector<std::string> &args) {
    // Create + Bind socket
    ServerSocket blockSocket(12201); // TODO Config file / Argument / Whatever

    // Make the reactor
    SocketReactor reactor;

    // Assign the Connector
    SocketAcceptor<PolarisConnection> acceptor(blockSocket, reactor);

    Thread thread;
    logger().information("Starting reactor...");
    thread.start(reactor);

    waitForTerminationRequest();

    reactor.stop();
    thread.join();

    return Application::EXIT_OK;
}

Add thread to fix gcc


#include "quasigame.h"
#include "gamescene.h"

QuasiGame::QuasiGame(QQuickItem *parent)
    : QQuickItem(parent)
    , m_currentScene(0)
    , m_fps(DEFAULT_FPS)
{
    connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(onUpdate()));
    m_gameTime.start();
    m_updateTimer.start(1000 / m_fps);
}

GameScene *QuasiGame::currentScene() const {
    return m_currentScene;
}

void QuasiGame::setCurrentScene(GameScene *currentScene) {
    if (m_currentScene)
        disconnect(SIGNAL(update(long)));

    m_currentScene = currentScene;

    if (m_currentScene)
        connect(this, SIGNAL(update(long)), m_currentScene, SLOT(update(long)));

    emit currentSceneChanged();
}

int QuasiGame::fps() const
{
    return m_fps;
}

void QuasiGame::setFps(int fps)
{
    m_fps = fps;

    emit fpsChanged();
}

void QuasiGame::onUpdate()
{
    long elapsedTime = m_gameTime.restart();
    emit update(elapsedTime);
}

#include "quasigame.h"
#include "gamescene.h"

QuasiGame::QuasiGame(QQuickItem *parent)
    : QQuickItem(parent)
    , m_currentScene(0)
    , m_fps(DEFAULT_FPS)
{
    connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(onUpdate()));
    m_gameTime.start();
    m_updateTimer.start(1000 / m_fps);
}

GameScene *QuasiGame::currentScene() const {
    return m_currentScene;
}

void QuasiGame::setCurrentScene(GameScene *currentScene) {
    if (m_currentScene != currentScene) {
        if (m_currentScene)
            disconnect(SIGNAL(update(long)));

        m_currentScene = currentScene;

        if (m_currentScene)
            connect(this, SIGNAL(update(long)), m_currentScene, SLOT(update(long)));

        emit currentSceneChanged();
    }
}

int QuasiGame::fps() const
{
    return m_fps;
}

void QuasiGame::setFps(int fps)
{
    if (m_fps != fps) {
        m_fps = fps;

        emit fpsChanged();
    }
}

void QuasiGame::onUpdate()
{
    long elapsedTime = m_gameTime.restart();
    emit update(elapsedTime);
}

Check properties changes before emitting notify signal


#include "JNIRhodes.h"

#include "gapikey.h"

#include <common/rhoparams.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"

RHO_GLOBAL void mapview_create(rho_param *p)
{
#ifdef GOOGLE_API_KEY
    jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
    if (!clsMapView) return;
    jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V");
    if (!midCreate) return;

    if (p->type != RHO_PARAM_HASH) {
        RAWLOG_ERROR("create: wrong input parameter (expect Hash)");
        return;
    }

    JNIEnv *env = jnienv();
    jobject paramsObj = RhoValueConverter(env).createObject(p);
    env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj);
#else
    RHO_NOT_IMPLEMENTED;
#endif
}

#include "JNIRhodes.h"

#include "gapikey.h"

#include <common/rhoparams.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"

extern "C" void alert_show_popup(char *);

RHO_GLOBAL void mapview_create(rho_param *p)
{
#ifdef GOOGLE_API_KEY
    jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
    if (!clsMapView) return;
    jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V");
    if (!midCreate) return;

    if (p->type != RHO_PARAM_HASH) {
        RAWLOG_ERROR("create: wrong input parameter (expect Hash)");
        return;
    }

    JNIEnv *env = jnienv();
    jobject paramsObj = RhoValueConverter(env).createObject(p);
    env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj);
#else
    alert_show_popup("Google API key problem");
#endif
}

Add alert when Google API key was not specified


/* Copyright 2015 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/core/kernels/cwise_ops_common.h"

namespace tensorflow {

REGISTER6(UnaryOp, CPU, "Sinh", functor::sinh, float, double, bfloat16,
          Eigen::half, complex64, complex128);

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Sinh", functor::sinh, float, double);
#endif
REGISTER(UnaryOp, GPU, "Sinh", functor::sinh, bfloat16)
#endif

}  // namespace tensorflow

/* Copyright 2015 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/core/kernels/cwise_ops_common.h"

namespace tensorflow {

REGISTER6(UnaryOp, CPU, "Sinh", functor::sinh, float, double, bfloat16,
          Eigen::half, complex64, complex128);

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Sinh", functor::sinh, Eigen::half, float, double);
#endif
REGISTER(UnaryOp, GPU, "Sinh", functor::sinh, bfloat16)
#endif

}  // namespace tensorflow

Fix registration of Sinh GPU Eigen kernel


/* Include the SDL main definition header */
#include "SDL_main.h"

/*******************************************************************************
                 Functions called by JNI
*******************************************************************************/
#include <jni.h>

// Called before SDL_main() to initialize JNI bindings in SDL library
extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls);

// Library init
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    return JNI_VERSION_1_4;
}

// Start up the SDL app
extern "C" void Java_org_libsdl_app_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobject obj)
{
    /* This interface could expand with ABI negotiation, calbacks, etc. */
    SDL_Android_Init(env, cls);

    /* Run the application code! */
    char *argv[2];
    argv[0] = strdup("SDL_app");
    argv[1] = NULL;
    SDL_main(1, argv);
}

/* Include the SDL main definition header */
#include "SDL_main.h"

/*******************************************************************************
                 Functions called by JNI
*******************************************************************************/
#include <jni.h>

// Called before SDL_main() to initialize JNI bindings in SDL library
extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls);

// Library init
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    return JNI_VERSION_1_4;
}

// Start up the SDL app
extern "C" void Java_org_libsdl_app_SDLActivity_nativeInit(JNIEnv* env, jclass cls, jobject obj)
{
    /* This interface could expand with ABI negotiation, calbacks, etc. */
    SDL_Android_Init(env, cls);

    /* Run the application code! */
    int status;
    char *argv[2];
    argv[0] = strdup("SDL_app");
    argv[1] = NULL;
    status = SDL_main(1, argv);

    /* We exit here for consistency with other platforms. */
    exit(status);
}

/* vi: set ts=4 sw=4 expandtab: */

Make sure we shut down the app if SDL_main() returns instead of exiting.


/* $Id$ */

#include <grid/geometry_info.h>

// enable these lines for gcc2.95
//
//const unsigned int GeometryInfo<deal_II_dimension>::vertices_per_cell;
//const unsigned int GeometryInfo<deal_II_dimension>::lines_per_cell;
//const unsigned int GeometryInfo<deal_II_dimension>::quads_per_cell;
//const unsigned int GeometryInfo<deal_II_dimension>::hexes_per_cell;
//const unsigned int GeometryInfo<deal_II_dimension>::children_per_cell;

template <>
const unsigned int GeometryInfo<1>::opposite_face[GeometryInfo<1>::faces_per_cell]
= { 0, 1 };

template <>
const unsigned int GeometryInfo<2>::opposite_face[GeometryInfo<2>::faces_per_cell]
= { 2, 3, 0, 1 };

template <>
const unsigned int GeometryInfo<3>::opposite_face[GeometryInfo<3>::faces_per_cell]
= { 1, 0, 4, 5, 2, 3 };

/* $Id$ */

#include <grid/geometry_info.h>

const unsigned int GeometryInfo<deal_II_dimension>::vertices_per_cell;
const unsigned int GeometryInfo<deal_II_dimension>::lines_per_cell;
const unsigned int GeometryInfo<deal_II_dimension>::quads_per_cell;
const unsigned int GeometryInfo<deal_II_dimension>::hexes_per_cell;
const unsigned int GeometryInfo<deal_II_dimension>::children_per_cell;

template <>
const unsigned int GeometryInfo<1>::opposite_face[GeometryInfo<1>::faces_per_cell]
= { 0, 1 };

template <>
const unsigned int GeometryInfo<2>::opposite_face[GeometryInfo<2>::faces_per_cell]
= { 2, 3, 0, 1 };

template <>
const unsigned int GeometryInfo<3>::opposite_face[GeometryInfo<3>::faces_per_cell]
= { 1, 0, 4, 5, 2, 3 };

Use actual definitions of static variables.


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

#include "SkFontHost.h"
#include "SkTypeface.h"
#include "SkTypeface_win.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

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

#include "SkFontHost.h"
#include "SkTypeface.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

Remove unneeded include which is breaking build.


#include "Example1.h"

#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <shader_program.h>

using namespace std;

bool
Example1::Init() {
}

void
Example1::onDraw() {
}

void
Example1::onShutdown() {
}

std::shared_ptr<Example1> application;

void applicationMain(FWPlatformBase * platform) {
	application = std::make_shared<Example1>(platform);
	platform->setApplication(application.get());
}

#include "Example1.h"

#include <string.h>
#include <GLES3/gl3.h>
#include <jni.h>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <shader_program.h>
#include <Context.h>
#include <AndroidPlatform.h>
#include <ContextAndroid.h>

using namespace std;

bool
Example1::Init() {
}

void
Example1::onDraw() {
}

void
Example1::onShutdown() {
}

std::shared_ptr<Example1> application;

void applicationMain(FWPlatformBase * platform) {
	application = std::make_shared<Example1>(platform);
	platform->setApplication(application.get());
}

Add includes to use debugging showCanvas


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

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

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  auto degree = ics::Angle::newDegree(msg->angle);
  auto nowpos = driver->move(msg->id, degree);
  servo_msgs::IdBased result;
  result.id = msg->id;
  result.angle = nowpos;
  pub.publish(result);
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle n {};
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  try {
    ics::ICS3 ics {path.c_str()};
    driver = &ics;
  } catch (std::runtime_error e) {
    ROS_INFO("Error: Cannot make ICS3 instance [%s]", e.what());
    ROS_INFO("I tried open [%s]", path.c_str());
    return -1;
  }
  ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

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

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

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

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle n {};
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  try {
    ics::ICS3 ics {path.c_str()};
    driver = &ics;
  } catch (std::runtime_error e) {
    ROS_INFO("Error: Cannot make ICS3 instance [%s]", e.what());
    ROS_INFO("I tried open [%s]", path.c_str());
    return -1;
  }
  ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Add try block for receive error on connection


//
// Created by dar on 1/25/16.
//

#include "GuiButton.h"

GuiButton::GuiButton(int x, int y, int width, int height) {
    this->x = x;
    this->y = y;
    this->width = width;
    this->height = height;
}

bool virtual GuiButton::onClick(int action, float x, float y) {
    if (onClickListener == NULL) return false;
    return onClickListener(action, x, y);
}

void virtual GuiButton::setOnClickListener(std::function<bool(int, float, float)> onClickListener) {
    this->onClickListener = onClickListener;
}

//
// Created by dar on 1/25/16.
//

#include "GuiButton.h"

GuiButton::GuiButton(int x, int y, int width, int height) {
    this->x = x;
    this->y = y;
    this->width = width;
    this->height = height;
}

bool GuiButton::onClick(int action, float x, float y) {
    if (onClickListener == NULL) return false;
    return onClickListener(action, x, y);
}

void GuiButton::setOnClickListener(std::function<bool(int, float, float)> onClickListener) {
    this->onClickListener = onClickListener;
}

Fix 'virtual out of class' error


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

namespace [[deprecated]] {}  // expected-warning {{'deprecated' attribute on anonymous namespace ignored}}

namespace [[deprecated]] N { // expected-note 4{{'N' has been explicitly marked deprecated here}}
  int X;
  int Y = X; // Ok
  int f();
}

int N::f() { // Ok
  return Y; // Ok
}

void f() {
  int Y = N::f(); // expected-warning {{'N' is deprecated}}
  using N::X; // expected-warning {{'N' is deprecated}}
  int Z = X; //Ok
}

void g() {
  using namespace N; // expected-warning {{'N' is deprecated}}
  int Z = Y; // Ok
}

namespace M = N; // expected-warning {{'N' is deprecated}}

// Shouldn't diag:
[[nodiscard, deprecated("")]] int PR37935();

Add regression test for PR37935.


#include "object/object.h"
#include "object/jsobject.h"
#include "object/function.h"
#include "parser/functionstatement.h"
#include "vm/instruction-builder.h"
#include "vm/instruction.h"
#include "vm/context.h"
#include "vm/vm.h"

namespace grok {
namespace parser {

using namespace grok::vm;
using namespace grok::obj;

/// emits code for function definition
/// We don't generate the code for the body now but defer it until
/// it is required i.e. when a call is placed to this function during
/// execution
void FunctionStatement::emit(std::shared_ptr<InstructionBuilder>)
{
    std::string Name = proto_->GetName();
    auto F = std::make_shared<Function>(std::move(body_), std::move(proto_));
    auto VS = GetVStore(GetGlobalVMContext());
    auto V = Value{};
    V.O = std::make_shared<Object>(F);
    VS->StoreValue(Name, V);
}

void FunctionPrototype::emit(std::shared_ptr<InstructionBuilder>)
{
    // do nothing
}

} // parser
} // grok

#include "object/object.h"
#include "object/jsobject.h"
#include "object/function.h"
#include "parser/functionstatement.h"
#include "vm/instruction-builder.h"
#include "vm/instruction.h"
#include "vm/context.h"
#include "vm/vm.h"

namespace grok {
namespace parser {

using namespace grok::vm;
using namespace grok::obj;

/// emits code for function definition
/// We don't generate the code for the body now but defer it until
/// it is required i.e. when a call is placed to this function during
/// execution
void FunctionStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
    std::string Name = proto_->GetName();
    auto F = std::make_shared<Function>(std::move(body_), std::move(proto_));
    auto VS = GetVStore(GetGlobalVMContext());

    if (Name.length()) {
        auto V = Value{};
        V.O = std::make_shared<Object>(F);
        VS->StoreValue(Name, V);
    }

    auto instr = InstructionBuilder::Create<Instructions::push>();
    instr->data_type_ = d_obj;
    instr->data_ = std::make_shared<Object>(F);

    builder->AddInstruction(std::move(instr));
}

void FunctionPrototype::emit(std::shared_ptr<InstructionBuilder>)
{
    // do nothing
}

} // parser
} // grok

Allow unnamed function and their assigning to other values


//@author A0097630B
#include "stdafx.h"
#include "query_executor.h"

namespace You {
namespace Controller {
namespace Internal {

QueryExecutor::QueryExecutor(std::unique_ptr<You::QueryEngine::Query>&& query) {
}

Result QueryExecutor::execute() {
	QueryEngine::Response response = QueryEngine::executeQuery(
		std::move(query));
	return processResponse(response);
}

}  // namespace Internal
}  // namespace Controller
}  // namespace You

//@author A0097630B
#include "stdafx.h"
#include "query_executor.h"

namespace You {
namespace Controller {
namespace Internal {

QueryExecutor::QueryExecutor(std::unique_ptr<You::QueryEngine::Query>&& query)
: query(std::move(query)) {
}

Result QueryExecutor::execute() {
	QueryEngine::Response response = QueryEngine::executeQuery(
		std::move(query));
	return processResponse(response);
}

}  // namespace Internal
}  // namespace Controller
}  // namespace You

Store the query that is to be executed later.


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WindowsInitialExperienceModule.h"
#include "WindowsInitialExperiencePreLoadModel.h"
#include "InitialExperienceIntroStep.h"
//#include "InitialExperienceSearchResultAttractModeModel.h"

namespace ExampleApp
{
    namespace InitialExperience
    {
        namespace SdkModel
        {
            WindowsInitialExperienceModule::WindowsInitialExperienceModule(
                WindowsNativeState& nativeState,
                PersistentSettings::IPersistentSettingsModel& persistentSettings,
                ExampleAppMessaging::TMessageBus& messageBus
            )
                : InitialExperienceModuleBase(persistentSettings)
                , m_nativeState(nativeState)
                , m_messageBus(messageBus)
                //, m_pInitialExperienceSearchResultAttractModeModule(NULL)
            {

            }

            WindowsInitialExperienceModule::~WindowsInitialExperienceModule()
            {
                //Eegeo_DELETE m_pInitialExperienceSearchResultAttractModeModule;
            }

            std::vector<IInitialExperienceStep*> WindowsInitialExperienceModule::CreateSteps(WorldAreaLoader::SdkModel::IWorldAreaLoaderModel &worldAreaLoaderModel)
            {
                std::vector<IInitialExperienceStep*> steps;

				// TODO: Recreate MEA initial experience steps for windows...

                return steps;
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WindowsInitialExperienceModule.h"
#include "WindowsInitialExperiencePreLoadModel.h"
#include "InitialExperienceIntroStep.h"
//#include "InitialExperienceSearchResultAttractModeModel.h"
#include "WorldPinVisibility.h"

namespace ExampleApp
{
    namespace InitialExperience
    {
        namespace SdkModel
        {
            WindowsInitialExperienceModule::WindowsInitialExperienceModule(
                WindowsNativeState& nativeState,
                PersistentSettings::IPersistentSettingsModel& persistentSettings,
                ExampleAppMessaging::TMessageBus& messageBus
            )
                : InitialExperienceModuleBase(persistentSettings)
                , m_nativeState(nativeState)
                , m_messageBus(messageBus)
                //, m_pInitialExperienceSearchResultAttractModeModule(NULL)
            {

            }

            WindowsInitialExperienceModule::~WindowsInitialExperienceModule()
            {
                //Eegeo_DELETE m_pInitialExperienceSearchResultAttractModeModule;
            }

            std::vector<IInitialExperienceStep*> WindowsInitialExperienceModule::CreateSteps(WorldAreaLoader::SdkModel::IWorldAreaLoaderModel &worldAreaLoaderModel)
            {
                std::vector<IInitialExperienceStep*> steps;

				// TODO: Recreate MEA initial experience steps for windows...

				m_messageBus.Publish(WorldPins::WorldPinsVisibilityMessage(WorldPins::SdkModel::WorldPinVisibility::All));

                return steps;
            }
        }
    }
}

Fix for missing Hovercards in Windows. Buddy: Mark


#include "aboutwindow.h"
#include "ui_aboutwindow.h"

aboutWindow::aboutWindow(QString version, QWidget *parent) : QDialog(parent), ui(new Ui::aboutWindow)
{
    ui->setupUi(this);

	ui->labelCurrent->setText(version);
	m_version = version.replace(".", "").toInt();

	QNetworkAccessManager *m = new QNetworkAccessManager();
	connect(m, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
	m->get(QNetworkRequest(QUrl("http://imgbrd-grabber.googlecode.com/svn/trunk/VERSION")));

	setFixedSize(400, 170);
}

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

void aboutWindow::finished(QNetworkReply *r)
{
	QString l = r->readAll();
	int latest = l.replace(".", "").toInt();
	if (latest <= m_version)
	{ ui->labelMessage->setText("
"+tr("Grabber est  jour")+"
"); }
	else
	{ ui->labelMessage->setText("
"+tr("Une nouvelle version est disponible : %1").arg(l)+"
"); }
}

#include "aboutwindow.h"
#include "ui_aboutwindow.h"

aboutWindow::aboutWindow(QString version, QWidget *parent) : QDialog(parent), ui(new Ui::aboutWindow)
{
    ui->setupUi(this);

	ui->labelCurrent->setText(version);
	m_version = version.replace(".", "").toInt();

	QNetworkAccessManager *m = new QNetworkAccessManager();
	connect(m, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
	m->get(QNetworkRequest(QUrl("http://imgbrd-grabber.googlecode.com/svn/trunk/VERSION")));

	setFixedSize(400, 170);
}

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

void aboutWindow::finished(QNetworkReply *r)
{
	QString l = r->readAll(), last = l;
	int latest = last.replace(".", "").toInt();
	if (latest <= m_version)
	{ ui->labelMessage->setText("
"+tr("Grabber est  jour")+"
"); }
	else
	{ ui->labelMessage->setText("
"+tr("Une nouvelle version est disponible : %1").arg(l)+"
"); }
}

Fix last version writing in aboutWindow


#include "enfa.h"

#include <string>

namespace tinygrep {

namespace enfa {

std::string EpsilonNFA::to_graph() const {
  return "";
}

}  // namespace enfa

}  // namespace tinygrep

#include "enfa.h"

#include <string>
#include <sstream>

namespace tinygrep {

namespace enfa {

// The default scale of a generated graph.
const unsigned int DEFAULT_PNG_SIZE = 10;
const std::string LABEL_BEGIN   = " [label=\"",
                  LABEL_END     = "\"]",
                  EDGE_ARROW    = " -> ",
                  STATE_PREFIX  = "q",
                  ENDLINE       = ";\n";

std::string EpsilonNFA::to_graph() const {
  const unsigned int png_size = DEFAULT_PNG_SIZE;
  std::stringstream output;
  output << "digraph epsilon_nfa {\n"
         << "rankdir=LR; size=\""
         << png_size << "," << png_size << "\""
         << ENDLINE;
  // add start state
  output << "foo [style = invis]"
         << ENDLINE;
  output << "node [shape = circle]; "
         << STATE_PREFIX << start_state_
         << ENDLINE;
  output << "foo" << EDGE_ARROW
         << STATE_PREFIX << start_state_
         << LABEL_BEGIN << "start" << LABEL_END
         << ENDLINE;
  // add accepting state
  output << "node [shape = doublecircle]; "
         << STATE_PREFIX << accept_state_
         << ENDLINE;
  // add remaining states
  output << "node [shape = circle]"
         << ENDLINE;
  // add transitions
  for (state_type from = 0; from < state_count_; from++) {
    // epsilon-transitions
    for (state_type to : epsilon_transitions_[from]) {
      output << STATE_PREFIX << from
             << EDGE_ARROW
             << STATE_PREFIX << to
             << LABEL_BEGIN << LABEL_END
             << ENDLINE;
    }
    // literal-transitions
    for (Transition transition : literal_transitions_[from]) {
      output << STATE_PREFIX << from
             << EDGE_ARROW
             << STATE_PREFIX << transition.target
             << LABEL_BEGIN << transition.literal << LABEL_END
             << ENDLINE;
    }
  }
  output << "}\n";
  return output.str();
}

}  // namespace enfa

}  // namespace tinygrep

Complete function for parsing epsilon-NFA -> .gv file.


#include <gtest/gtest.h>
#include <rapidxml_utils.hpp>

#include "llvm/compiler.hpp"
#include "parser/xmlParser.hpp"

class LLVMCompilerTest: public ::testing::Test {
protected:
  XMLParser xpx = XMLParser();

  inline rapidxml::file<> xmlFile(std::string path) {
    #define Q(x) #x
    #define QUOTE(x) Q(x)
    path = QUOTE(DATA_PARENT_DIR) + ("/" + path);
    #undef QUOTE
    #undef Q
    return rapidxml::file<>(path.c_str());
  }

  inline void noThrowOnCompile(std::string xmlFilePath) {
    xpx.parse(xmlFile(xmlFilePath));
    CompileVisitor::Link visitor = CompileVisitor::create(globalContext, xmlFilePath, xpx.getTree());
    try {
      visitor->visit();
    } catch (InternalError& err) {
      EXPECT_NO_THROW(throw InternalError(err));
      println(err.what());
    }
    visitor->getModule()->dump();
  }
};

TEST_F(LLVMCompilerTest, ExitCodes) {
  noThrowOnCompile("data/llvm/exit_code.xml");
  noThrowOnCompile("data/llvm/stored_return.xml");
}

TEST_F(LLVMCompilerTest, Declarations) {
  noThrowOnCompile("data/llvm/primitive.xml");
}

TEST_F(LLVMCompilerTest, Branches) {
  noThrowOnCompile("data/llvm/if.xml");
  noThrowOnCompile("data/llvm/if-else.xml");
  noThrowOnCompile("data/llvm/else-if.xml");
}

#include <gtest/gtest.h>
#include <rapidxml_utils.hpp>

#include "llvm/compiler.hpp"
#include "parser/xmlParser.hpp"

class LLVMCompilerTest: public ::testing::Test {
protected:
  XMLParser xpx = XMLParser();

  inline rapidxml::file<> xmlFile(std::string path) {
    path = DATA_PARENT_DIR + ("/" + path);
    return rapidxml::file<>(path.c_str());
  }

  inline void noThrowOnCompile(std::string xmlFilePath) {
    xpx.parse(xmlFile(xmlFilePath));
    CompileVisitor::Link visitor = CompileVisitor::create(globalContext, xmlFilePath, xpx.getTree());
    try {
      visitor->visit();
    } catch (InternalError& err) {
      EXPECT_NO_THROW(throw InternalError(err));
      println(err.what());
    }
    visitor->getModule()->dump();
  }
};

TEST_F(LLVMCompilerTest, ExitCodes) {
  noThrowOnCompile("data/llvm/exit_code.xml");
  noThrowOnCompile("data/llvm/stored_return.xml");
}

TEST_F(LLVMCompilerTest, Declarations) {
  noThrowOnCompile("data/llvm/primitive.xml");
}

TEST_F(LLVMCompilerTest, Branches) {
  noThrowOnCompile("data/llvm/if.xml");
  noThrowOnCompile("data/llvm/if-else.xml");
  noThrowOnCompile("data/llvm/else-if.xml");
}

Revert "Fixed command line macro's missing quotes"


#include "Timer.hpp"

using namespace HomieInternals;

Timer::Timer()
: _initialTime(0)
, _interval(0)
, _tickAtBeginning(false) {
}

void Timer::setInterval(uint32_t interval, bool tickAtBeginning) {
  _interval = interval;
  _tickAtBeginning = tickAtBeginning;

  this->reset();
}

bool Timer::check() const {
  if (_tickAtBeginning && _initialTime == 0) return true;
  if (millis() - _initialTime >= _interval) return true;

  return false;
}

void Timer::reset() {
  if (tickAtBeginning) {
    _initialTime = 0;
  } else {
    this->tick();
  }
}

void Timer::tick() {
  _initialTime = millis();
}

#include "Timer.hpp"

using namespace HomieInternals;

Timer::Timer()
: _initialTime(0)
, _interval(0)
, _tickAtBeginning(false) {
}

void Timer::setInterval(uint32_t interval, bool tickAtBeginning) {
  _interval = interval;
  _tickAtBeginning = tickAtBeginning;

  this->reset();
}

bool Timer::check() const {
  if (_tickAtBeginning && _initialTime == 0) return true;
  if (millis() - _initialTime >= _interval) return true;

  return false;
}

void Timer::reset() {
  if (_tickAtBeginning) {
    _initialTime = 0;
  } else {
    this->tick();
  }
}

void Timer::tick() {
  _initialTime = millis();
}

Add missing underscore - fix last commit


// Copyright (c) 2007-2009 Paul Hodge. All rights reserved.

#include "circa.h"

namespace circa {
namespace range_function {

    void evaluate(Term* caller)
    {
        unsigned int max = as_int(caller->input(0));

        Branch& branch = as_branch(caller);

        resize_list(branch, max, INT_TYPE);

        for (unsigned int i=0; i < max; i++)
            as_int(branch[i]) = i;
    }

    void setup(Branch& kernel)
    {
        import_function(kernel, evaluate, "range(int) : List");
    }
}
} // namespace circa

// Copyright (c) 2007-2009 Paul Hodge. All rights reserved.

#include "circa.h"

namespace circa {
namespace range_function {

    void evaluate(Term* caller)
    {
        int max = as_int(caller->input(0));

        Branch& branch = as_branch(caller);

        resize_list(branch, max, INT_TYPE);

        for (int i=0; i < max; i++)
            as_int(branch[i]) = i;
    }

    void setup(Branch& kernel)
    {
        import_function(kernel, evaluate, "range(int) : List");
    }
}
} // namespace circa

Fix a compile error on msvc7


#include "box2dbaseitem.h"

#include <Box2D/Box2D.h>

float Box2DBaseItem::m_scaleRatio = 32.0f;

Box2DBaseItem::Box2DBaseItem(GameScene *parent )
    : GameItem(parent)
    , m_initialized(false)
    , m_synchronizing(false)
    , m_synchronize(true)
{
}

bool Box2DBaseItem::initialized() const
{
    return m_initialized;
}

/*
 * Shamelessly stolen from qml-box2d project at gitorious
 *
 * https://gitorious.org/qml-box2d/qml-box2d
 */
void Box2DBaseItem::synchronize()
{
    if (m_synchronize && m_initialized) {
        m_synchronizing = true;

        const b2Vec2 position = b2TransformOrigin();
        const float32 angle = b2Angle();

        const qreal newX = position.x * m_scaleRatio - width() / 2.0;
        const qreal newY = -position.y * m_scaleRatio - height() / 2.0;
        const qreal newRotation = -(angle * 360.0) / (2 * b2_pi);

        if (!qFuzzyCompare(x(), newX) || !qFuzzyCompare(y(), newY))
            setPos(QPointF(newX, newY));
        if (!qFuzzyCompare(rotation(), newRotation))
            setRotation(newRotation);

        m_synchronizing = false;
    }
}

#include "box2dbaseitem.h"

#include "util.h"

#include <Box2D/Box2D.h>

float Box2DBaseItem::m_scaleRatio = 32.0f;

Box2DBaseItem::Box2DBaseItem(GameScene *parent )
    : GameItem(parent)
    , m_initialized(false)
    , m_synchronizing(false)
    , m_synchronize(true)
{
}

bool Box2DBaseItem::initialized() const
{
    return m_initialized;
}

/*
 * Shamelessly stolen from qml-box2d project at gitorious
 *
 * https://gitorious.org/qml-box2d/qml-box2d
 */
void Box2DBaseItem::synchronize()
{
    if (m_synchronize && m_initialized) {
        m_synchronizing = true;

        const QPointF newPoint = b2Util::qTopLeft(b2TransformOrigin(), boundingRect(), m_scaleRatio);
        const float32 angle = b2Angle();
        const qreal newRotation = -(angle * 360.0) / (2 * b2_pi);

        if (!qFuzzyCompare(x(), newPoint.x()) || !qFuzzyCompare(y(), newPoint.y()))
            setPos(newPoint);
        if (!qFuzzyCompare(rotation(), newRotation))
            setRotation(newRotation);

        m_synchronizing = false;
    }
}

Use helper function to get top left coordinates


#include "MediaSessionManager.h"

using namespace ::com::kurento::kms;
using namespace ::com::kurento::kms::api;

void task() {
}

MediaSessionManager::MediaSessionManager() {
}

MediaSessionManager::~MediaSessionManager() {
}

MediaSessionManager *MediaSessionManager::getInstance() {
	static shared_ptr<MediaSessionManager> instance(new MediaSessionManager());
	return instance.get();
}

void MediaSessionManager::releaseInstance(MediaSessionManager* manager) {
	// As instance is a singleton no action is needed
}

MediaSession& MediaSessionManager::createMediaSession() {
	MediaServerException exception;
	exception.__set_description("Not implemented");
	exception.__set_code(ErrorCode::UNEXPECTED);
	throw exception;
}

void MediaSessionManager::deleteMediaSession(const MediaSession& session) {
	MediaServerException exception;
	exception.__set_description("Not implemented");
	exception.__set_code(ErrorCode::UNEXPECTED);
	throw exception;
}

#include "MediaSessionManager.h"

using namespace ::com::kurento::kms;
using namespace ::com::kurento::kms::api;

void task() {
}

MediaSessionManager::MediaSessionManager() {
}

MediaSessionManager::~MediaSessionManager() {
}

MediaSessionManager *MediaSessionManager::getInstance() {
	static MediaSessionManager *instance = new MediaSessionManager();
	return instance;
}

void MediaSessionManager::releaseInstance(MediaSessionManager* manager) {
	// As instance is a singleton no action is needed
}

MediaSession& MediaSessionManager::createMediaSession() {
	MediaServerException exception;
	exception.__set_description("Not implemented");
	exception.__set_code(ErrorCode::UNEXPECTED);
	throw exception;
}

void MediaSessionManager::deleteMediaSession(const MediaSession& session) {
	MediaServerException exception;
	exception.__set_description("Not implemented");
	exception.__set_code(ErrorCode::UNEXPECTED);
	throw exception;
}

Use a pointer in getInstance instead of shared_ptr


// 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 "ppapi/tests/test_case.h"

#include <sstream>

std::string TestCase::MakeFailureMessage(const char* file,
                                         int line,
                                         const char* cmd) {
  std::ostringstream output;
  output << "Failure in " << file << "(" << line << "): " << cmd;
  return output.str();
}

// 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 "ppapi/tests/test_case.h"

#include <sstream>

std::string TestCase::MakeFailureMessage(const char* file,
                                         int line,
                                         const char* cmd) {
  // The mere presence of this local variable works around a gcc-4.2.4
  // compiler bug in official Chrome Linux builds.  If you remove it,
  // confirm this compile command still works:
  // GYP_DEFINES='branding=Chrome buildtype=Official target_arch=x64'
  //     gclient runhooks
  // make -k -j4 BUILDTYPE=Release ppapi_tests
  std::string s;

  std::ostringstream output;
  output << "Failure in " << file << "(" << line << "): " << cmd;
  return output.str();
}

Fix the Chrome Linux build by working around a compiler bug.


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

#include "strops.hpp"

int ox_strcmp(const char *str1, const char *str2) {
	auto retval = 0;
	auto i = 0;
	do {
		if (str1[i] < str2[i]) {
			retval = -1;
			break;
		} else if (str1[i] > str2[i]) {
			retval = 1;
			break;
		}
		i++;
	} while (str1[i] == str2[i] && str1[i]);
	return retval;
}

size_t ox_strlen(const char *str1) {
	int len;
	for (len = 0; str1[len]; len++);
	return len;
}

int ox_atoi(const char *str) {
	int total = 0;
	int multiplier = 1;

	for (size_t i = ox_strlen(str) - 1; i >= 0; i--) {
		total += (str[i] - '0') * multiplier;
		multiplier *= 10;
	}

	return total;
}

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

#include "strops.hpp"

int ox_strcmp(const char *str1, const char *str2) {
	auto retval = 0;
	auto i = 0;
	do {
		if (str1[i] < str2[i]) {
			retval = -1;
			break;
		} else if (str1[i] > str2[i]) {
			retval = 1;
			break;
		}
		i++;
	} while (str1[i] == str2[i] && str1[i]);
	return retval;
}

size_t ox_strlen(const char *str1) {
	int len;
	for (len = 0; str1[len]; len++);
	return len;
}

int ox_atoi(const char *str) {
	int total = 0;
	int multiplier = 1;

	for (auto i = ox_strlen(str) - 1; i != 0; i--) {
		total += (str[i] - '0') * multiplier;
		multiplier *= 10;
	}

	return total;
}

Fix warning concering always true check


/* Copyright © 2001-2018, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

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

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "osm2ed.h"

int main(int argc, const char** argv) {
    return ed::connectors::osm2ed(argc, argv);
}

Add new line at the end of file


#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
int main(int argc, char *argv[])
{
    //TODO: Run this on Qt versions which support it...
    //QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QApplication app(argc, argv);
    QQmlApplicationEngine engine;
    setenv("PYTHONDONTWRITEBYTECODE", "1", 1);
    QString frameworks = app.applicationDirPath() + "/../Frameworks";
    setenv("DYLD_LIBRARY_PATH", frameworks.toUtf8().data(), 1);

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

    return app.exec();
}

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
int main(int argc, char *argv[])
{
    //TODO: Run this on Qt versions which support it...
    //QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QApplication app(argc, argv);
    QQmlApplicationEngine engine;
    QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
    putenv(pythonNoBytecode.toUtf8().data());
    QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
    putenv(frameworks.toUtf8().data());

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

    return app.exec();
}

Use putenv for env variables


#include "zg01_fsm.h"

// max time between ZG01 bits, until a new frame is assumed to have started
#define ZG01_MAX_MS  3

// all of the state of the FSM
typedef struct {
    uint8_t *buffer;
    int num_bits;
    unsigned long prev_ms;
} fsm_t;

static fsm_t fsm;
static fsm_t *s = &fsm;

// resets the FSM
static void fsm_reset(void)
{
    s->num_bits = 0;
}

void zg01_init(uint8_t buffer[5])
{
    s->buffer = buffer;
    fsm_reset();
}

bool zg01_process(unsigned long ms, bool data)
{
    // check if a new message has started, based on time since previous bit
    if ((ms - s->prev_ms) > ZG01_MAX_MS) {
        fsm_reset();
    }
    s->prev_ms = ms;

    // number of bits received is basically the "state"
    if (s->num_bits < 40) {
        // store it while it fits
        int idx = s->num_bits / 8;
        s->buffer[idx] = (s->buffer[idx] << 1) | (data ? 1 : 0);
        // are we done yet?
        s->num_bits++;
        if (s->num_bits == 40) {
            return true;
        }
    }
    // else do nothing, wait until fsm is reset

    return false;
}

#include "zg01_fsm.h"

// max time between ZG01 bits, until a new frame is assumed to have started
#define ZG01_MAX_MS  2

// all of the state of the FSM
typedef struct {
    uint8_t *buffer;
    int num_bits;
    unsigned long prev_ms;
} fsm_t;

static fsm_t fsm;
static fsm_t *s = &fsm;

// resets the FSM
static void fsm_reset(void)
{
    s->num_bits = 0;
}

void zg01_init(uint8_t buffer[5])
{
    s->buffer = buffer;
    fsm_reset();
}

bool zg01_process(unsigned long ms, bool data)
{
    // check if a new message has started, based on time since previous bit
    if ((ms - s->prev_ms) > ZG01_MAX_MS) {
        fsm_reset();
    }
    s->prev_ms = ms;

    // number of bits received is basically the "state"
    if (s->num_bits < 40) {
        // store it while it fits
        int idx = s->num_bits / 8;
        s->buffer[idx] = (s->buffer[idx] << 1) | (data ? 1 : 0);
        // are we done yet?
        s->num_bits++;
        if (s->num_bits == 40) {
            return true;
        }
    }
    // else do nothing, wait until fsm is reset

    return false;
}

Set new frame timeout to 2 milliseconds (was 3 milliseconds)


#include "locale.hpp"
#include <cstring>
#include <clocale>
#include <algorithm>

#undef min
#undef max

namespace locale {

std::vector<std::pair<std::string_view, std::string_view>> ListLocales() {
  std::vector<std::pair<std::string_view, std::string_view>> ret;
  ret.reserve(std::size_t(ELocale::MAXLocale));
  for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1))
    ret.emplace_back(GetName(l), GetFullName(l));
  return ret;
}

ELocale LookupLocale(std::string_view name) {
  for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1))
    if (!name.compare(GetName(l)))
      return l;
  return ELocale::Invalid;
}

ELocale SystemLocaleOrEnglish() {
  const char* sysLocale = std::setlocale(LC_ALL, nullptr);
  size_t sysLocaleLen = std::strlen(sysLocale);
  for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) {
    auto name = GetName(l);
    if (!name.compare(0, std::min(name.size(), sysLocaleLen), sysLocale))
      return l;
  }
  return ELocale::en_US;
}

} // namespace locale

#include "locale.hpp"
#include <cstring>
#include <clocale>
#include <algorithm>

#undef min
#undef max

namespace locale {

std::vector<std::pair<std::string_view, std::string_view>> ListLocales() {
  std::vector<std::pair<std::string_view, std::string_view>> ret;
  ret.reserve(std::size_t(ELocale::MAXLocale));
  for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1))
    ret.emplace_back(GetName(l), GetFullName(l));
  return ret;
}

ELocale LookupLocale(std::string_view name) {
  for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1))
    if (name == GetName(l))
      return l;
  return ELocale::Invalid;
}

ELocale SystemLocaleOrEnglish() {
  const char* sysLocale = std::setlocale(LC_ALL, nullptr);
  size_t sysLocaleLen = std::strlen(sysLocale);
  for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) {
    auto name = GetName(l);
    if (!name.compare(0, std::min(name.size(), sysLocaleLen), sysLocale))
      return l;
  }
  return ELocale::en_US;
}

} // namespace locale

Switch to string compare operator


#include "AssetLoader.h"

namespace fse
{
	AssetLoader::AssetLoader() {

	}

	AssetLoader::~AssetLoader()
	{
	}

	sf::Texture& AssetLoader::getTexture(std::string path)
	{
		if (textureMap.count(path)) //Texture is already loaded
		{
			textureCounter[path]++;
		}
		else
		{
			loadTexture(path);
		}
		return textureMap[path];
	}

	void AssetLoader::releaseTexture(std::string path)
	{
		if (!textureCounter.count(path)) //Texture is not in memory
			return;
		if (textureCounter[path] == 1)
		{
			textureCounter.erase(path);
			textureMap.erase(path);
			return;
		}

		textureCounter[path]--;
	}

	void AssetLoader::loadTexture(std::string path)
	{
		sf::Texture texture;
		std::string realPath = "data/" + path;
		texture.loadFromFile(realPath.c_str());

		textureMap[path] = texture;
		textureCounter[path] = 0;
	}
}

#include "AssetLoader.h"

namespace fse
{
	AssetLoader::AssetLoader() {

	}

	AssetLoader::~AssetLoader()
	{
	}

	sf::Texture& AssetLoader::getTexture(std::string path)
	{
		if (textureMap.count(path)) //Texture is already loaded
		{
			textureCounter[path]++;
		}
		else
		{
			loadTexture(path);
		}
		return textureMap[path];
	}

	void AssetLoader::releaseTexture(std::string path)
	{
		if (textureCounter.size() == 0)
			return;
		if (!textureCounter.count(path)) //Texture is not in memory
			return;
		if (textureCounter[path] == 1)
		{
			textureCounter.erase(path);
			textureMap.erase(path);
			return;
		}

		textureCounter[path]--;
	}

	void AssetLoader::loadTexture(std::string path)
	{
		std::string realPath = "data/" + path;
		textureMap[path].loadFromFile(realPath.c_str());
		textureCounter[path] = 1;
	}
}

Fix Assetloader not cleaning up properly


// 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 "base/test/test_suite.h"
#include "media/base/media.h"

class TestSuiteNoAtExit : public base::TestSuite {
 public:
  TestSuiteNoAtExit(int argc, char** argv) : TestSuite(argc, argv) {}
  virtual ~TestSuiteNoAtExit() {}
 protected:
  virtual void Initialize();
};

void TestSuiteNoAtExit::Initialize() {
  // Run TestSuite::Initialize first so that logging is initialized.
  base::TestSuite::Initialize();
  // Run this here instead of main() to ensure an AtExitManager is already
  // present.
  media::InitializeMediaLibraryForTesting();
}

int main(int argc, char** argv) {
  return TestSuiteNoAtExit(argc, argv).Run();
}

// 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 "base/test/main_hook.h"
#include "base/test/test_suite.h"
#include "media/base/media.h"

class TestSuiteNoAtExit : public base::TestSuite {
 public:
  TestSuiteNoAtExit(int argc, char** argv) : TestSuite(argc, argv) {}
  virtual ~TestSuiteNoAtExit() {}
 protected:
  virtual void Initialize();
};

void TestSuiteNoAtExit::Initialize() {
  // Run TestSuite::Initialize first so that logging is initialized.
  base::TestSuite::Initialize();
  // Run this here instead of main() to ensure an AtExitManager is already
  // present.
  media::InitializeMediaLibraryForTesting();
}

int main(int argc, char** argv) {
  MainHook hook(main, argc, argv);
  return TestSuiteNoAtExit(argc, argv).Run();
}

Add MainHook to media unittests.


// RUN: %clangxx_asan %s -o %t
// RUN: %t 2>&1 | FileCheck %s
#include <sanitizer/common_interface_defs.h>

#include <stdio.h>

char *sink[1000];

int main() {
  int idx = 0;
  for (int i = 0; i < 17; i++)
    sink[idx++] = new char[131];
  for (int i = 0; i < 42; i++)
    sink[idx++] = new char[24];

  __sanitizer_print_memory_profile(100);
  __sanitizer_print_memory_profile(50);
}

// CHECK: Live Heap Allocations: {{.*}}; showing top 100%
// CHECK: 2227 byte(s) ({{.*}}%) in 17 allocation(s)
// CHECK: 1008 byte(s) ({{.*}}%) in 42 allocation(s)
// CHECK: Live Heap Allocations: {{.*}}; showing top 50%
// CHECK: 2227 byte(s) ({{.*}}%) in 17 allocation(s)
// CHECK-NOT: 1008 byte

// Printing memory profiling only works in the configuration where we can
// detect leaks.
// REQUIRES: leak-detection
//
// RUN: %clangxx_asan %s -o %t
// RUN: %run %t 2>&1 | FileCheck %s
#include <sanitizer/common_interface_defs.h>

#include <stdio.h>

char *sink[1000];

int main() {
  int idx = 0;
  for (int i = 0; i < 17; i++)
    sink[idx++] = new char[131];
  for (int i = 0; i < 42; i++)
    sink[idx++] = new char[24];

  __sanitizer_print_memory_profile(100);
  __sanitizer_print_memory_profile(50);
}

// CHECK: Live Heap Allocations: {{.*}}; showing top 100%
// CHECK: 2227 byte(s) ({{.*}}%) in 17 allocation(s)
// CHECK: 1008 byte(s) ({{.*}}%) in 42 allocation(s)
// CHECK: Live Heap Allocations: {{.*}}; showing top 50%
// CHECK: 2227 byte(s) ({{.*}}%) in 17 allocation(s)
// CHECK-NOT: 1008 byte

Fix the test for printing the memory profile. This fuctionality is only available along side the leak checking, so use the REQUIRES for that.


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

struct One { };
struct Two { };

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

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

struct One { };
struct Two { };

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

Fix this test for gcc-4.2.


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * 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 "transfersaction.h"

QString TransfersAction::name() const
{
    return "transfers";
}

bool TransfersAction::ui() const
{
    return true;
}

QString TransfersAction::title() const
{
    return tr("View Transfers...");
}

QVariant TransfersAction::invoke(const QVariantMap &)
{
    mTransferWindow.show();
}

/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * 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 "transfersaction.h"

QString TransfersAction::name() const
{
    return "transfers";
}

bool TransfersAction::ui() const
{
    return true;
}

QString TransfersAction::title() const
{
    return tr("View Transfers...");
}

QVariant TransfersAction::invoke(const QVariantMap &)
{
    mTransferWindow.show();
    return true;
}

Fix (another) compilation bug on MSVC.


#include "rapidcheck/detail/FrequencyMap.h"

namespace rc {
namespace detail {

FrequencyMap::FrequencyMap(const std::vector<std::size_t> &frequencies)
    : m_sum(0) {
  m_table.reserve(frequencies.size());
  for (auto x : frequencies) {
    m_sum += x;
    m_table.push_back(m_sum);
  }
}

std::size_t FrequencyMap::lookup(std::size_t x) const {
  return std::upper_bound(begin(m_table), end(m_table), x) - begin(m_table);
}

std::size_t FrequencyMap::sum() const { return m_sum; }

} // namespace detail
} // namespace rc

#include "rapidcheck/detail/FrequencyMap.h"

#include <algorithm>

namespace rc {
namespace detail {

FrequencyMap::FrequencyMap(const std::vector<std::size_t> &frequencies)
    : m_sum(0) {
  m_table.reserve(frequencies.size());
  for (auto x : frequencies) {
    m_sum += x;
    m_table.push_back(m_sum);
  }
}

std::size_t FrequencyMap::lookup(std::size_t x) const {
  return std::upper_bound(begin(m_table), end(m_table), x) - begin(m_table);
}

std::size_t FrequencyMap::sum() const { return m_sum; }

} // namespace detail
} // namespace rc

Add missing include in FrequencyMao


#include "Fido/GeneticAlgo.h"
#include <math.h>

std::vector<double> getPopulationFitness(const std::vector<net::NeuralNet> &population) {
  std::vector<double> fitnesses;

  for(net::NeuralNet network : population) {
    double totalError = 0;
    for(double input = 1; input < 4; input++) {
      totalError += pow(input*2 - network.getOutput({input})[0], 2);
    }
		fitnesses.push_back(1/totalError);
  }

  return fitnesses;
}

int main() {
	srand(time(NULL));
  gen::GeneticAlgo geneticAlgo = gen::GeneticAlgo(20, 0.4, 0.5, 10, getPopulationFitness);
	net::NeuralNet modelNetwork = net::NeuralNet(1, 1, 1, 4, "simpleLinear");
}

#include "Fido/GeneticAlgo.h"
#include <math.h>

std::vector<double> getPopulationFitness(const std::vector<net::NeuralNet> &population) {
  std::vector<double> fitnesses;

  for(net::NeuralNet network : population) {
    double totalError = 0;
    for(double input = 1; input < 4; input++) {
      totalError += pow(input*2 - network.getOutput({input})[0], 2);
    }
    fitnesses.push_back(1/totalError);
  }

  return fitnesses;
}

int main() {
  srand(time(NULL));
  gen::GeneticAlgo geneticAlgo = gen::GeneticAlgo(20, 0.4, 0.5, 10, getPopulationFitness);
  net::NeuralNet modelNetwork = net::NeuralNet(1, 1, 1, 4, "simpleLinear");
  net::NeuralNet bestNetwork = geneticAlgo.getBestNeuralNetwork(600, modelNetwork);
}

Add getting of best network to GA example


#include <fstream>
#include <iostream>
#include <utility>
#include <map>
#include <set>
#include <queue>
#include <bitset>
#include <algorithm>

using namespace std;

int main() {
	ifstream fin("bcount.in");
	ofstream fout("bcount.out");

	int num_cows, num_queries;
	fin >> num_cows >> num_queries;

	vector<array<int, 3>> totals(num_cows + 1);
	for (int i = 0; i < num_cows; i++) {
		int cow;
		fin >> cow;

		totals[i + 1] = totals[i];
		totals[i + 1][cow - 1]++;
	}

	for (int i = 0; i < num_queries; i++) {
		int a, b;
		fin >> a >> b;

		fout << (totals[b][0] - totals[a - 1][0]) << ' '
			<< (totals[b][1] - totals[a - 1][1]) << ' '
			<< (totals[b][2] - totals[a - 1][2]) << endl;
	}
}

#include <fstream>
#include <array>
#include <vector>

using namespace std;

int main() {
	ifstream fin("bcount.in");
	ofstream fout("bcount.out");

	int num_cows, num_queries;
	fin >> num_cows >> num_queries;

	vector<array<int, 3>> totals(num_cows + 1);
	for (int i = 0; i < num_cows; i++) {
		int cow;
		fin >> cow;

		totals[i + 1] = totals[i];
		totals[i + 1][cow - 1]++;
	}

	for (int i = 0; i < num_queries; i++) {
		int a, b;
		fin >> a >> b;

		fout << (totals[b][0] - totals[a - 1][0]) << ' '
			<< (totals[b][1] - totals[a - 1][1]) << ' '
			<< (totals[b][2] - totals[a - 1][2]) << endl;
	}
}

Remove debug and unused headers


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

#include <folly/ExceptionString.h>

namespace folly {

/**
 * Debug string for an exception: include type and what(), if
 * defined.
 */
fbstring exceptionStr(const std::exception& e) {
#if FOLLY_HAS_RTTI
  fbstring rv(demangle(typeid(e)));
  rv += ": ";
#else
  fbstring rv("Exception (no RTTI available): ");
#endif
  rv += e.what();
  return rv;
}

fbstring exceptionStr(std::exception_ptr ep) {
  if (!kHasExceptions) {
    return "Exception (catch unavailable)";
  }
  return catch_exception(
      [&]() -> fbstring {
        return catch_exception<std::exception const&>(
            [&]() -> fbstring { std::rethrow_exception(ep); },
            [](auto&& e) { return exceptionStr(e); });
      },
      []() -> fbstring { return "<unknown exception>"; });
}

} // namespace folly

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

#include <folly/ExceptionString.h>

#include <utility>

namespace folly {

/**
 * Debug string for an exception: include type and what(), if
 * defined.
 */
fbstring exceptionStr(const std::exception& e) {
#if FOLLY_HAS_RTTI
  fbstring rv(demangle(typeid(e)));
  rv += ": ";
#else
  fbstring rv("Exception (no RTTI available): ");
#endif
  rv += e.what();
  return rv;
}

fbstring exceptionStr(std::exception_ptr ep) {
  if (!kHasExceptions) {
    return "Exception (catch unavailable)";
  }
  return catch_exception(
      [&]() -> fbstring {
        return catch_exception<std::exception const&>(
            [&]() -> fbstring { std::rethrow_exception(std::move(ep)); },
            [](auto&& e) { return exceptionStr(e); });
      },
      []() -> fbstring { return "<unknown exception>"; });
}

} // namespace folly

Move an exception_ptr in exceptionStr


// RUN: %clang_cc1 -verify -std=c++11 %s

// Unlike in C++98, C++11 allows unions to have static data members.

union U1 {
  static constexpr int k1 = 0;
  static const int k2 = k1;
  static int k3 = k2; // expected-error {{non-const static data member must be initialized out of line}}
  static constexpr double k4 = k2;
  static const double k5 = k4; // expected-warning {{GNU extension}} expected-note {{use 'constexpr'}}
  int n[k1 + 3];
};

constexpr int U1::k1;
constexpr int U1::k2;
int U1::k3;

const double U1::k4;
const double U1::k5;

template<typename T>
union U2 {
  static const int k1;
  static double k2;
  T t;
};
template<typename T> constexpr int U2<T>::k1 = sizeof(U2<T>);
template<typename T> double U2<T>::k2 = 5.3;

static_assert(U2<int>::k1 == sizeof(int), "");
static_assert(U2<char>::k1 == sizeof(char), "");

union U3 {
  static const int k;
  U3() : k(0) {} // expected-error {{does not name a non-static data member}}
};

struct S {
  union {
    static const int n; // expected-error {{static members cannot be declared in an anonymous union}}
    int a;
    int b;
  };
};
static union {
  static const int k; // expected-error {{static members cannot be declared in an anonymous union}}
  int n;
};

Make sure we still reject static data members in anonymous unions in C++11.