/*
    Copyright Sven Bergström 2014
    created for snow https://github.com/underscorediscovery/snow
    MIT license
*/

#ifdef HX_WINDOWS

#include <windows.h>
#include "SDL.h"
#include "SDL_syswm.h"

namespace snow {
    namespace platform {
        namespace window {

            void load_icon(SDL_Window* _window) {

                SDL_SysWMinfo wminfo;
                SDL_VERSION(&wminfo.version)
                if (SDL_GetWindowWMInfo(_window,&wminfo)) {

                	HINSTANCE handle = ::GetModuleHandle(NULL);
                	HWND hwnd = wminfo.info.win.window;
                	HICON icon = ::LoadIcon(handle, "IDI_MAIN_ICON");

                	::SetClassLong(hwnd, GCL_HICON, (LONG) icon);
                }

            } //load_icon

        } //window
    } //platform namespace
} //snow namespace

#endif //HX_WINDOWS

/*
    Copyright Sven Bergström 2014
    created for snow https://github.com/underscorediscovery/snow
    MIT license
*/

#ifdef HX_WINDOWS

#include <windows.h>
#include "SDL.h"
#include "SDL_syswm.h"

namespace snow {
    namespace platform {
        namespace window {

            void load_icon(SDL_Window* _window) {

                SDL_SysWMinfo wminfo;
                SDL_VERSION(&wminfo.version)
                if (SDL_GetWindowWMInfo(_window,&wminfo)) {

                	HINSTANCE handle = ::GetModuleHandle(NULL);
                	HWND hwnd = wminfo.info.win.window;
                	HICON icon = ::LoadIcon(handle, "IDI_MAIN_ICON");

                	::SetClassLong(hwnd, GCLP_HICON, (LONG) icon);
                }

            } //load_icon

        } //window
    } //platform namespace
} //snow namespace

#endif //HX_WINDOWS

Fix msvc windows 64 build; Add windows 64 bit prebuilt lib


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

#include "marl/blockingcall.h"

#include "marl/defer.h"

#include "marl_test.h"

#include <mutex>

TEST_P(WithBoundScheduler, BlockingCall) {
  auto mutex = std::make_shared<std::mutex>();
  mutex->lock();

  marl::WaitGroup wg(100);
  for (int i = 0; i < 100; i++) {
    marl::schedule([=] {
      defer(wg.done());
      marl::blocking_call([=] {
        mutex->lock();
        defer(mutex->unlock());
      });
    });
  }

  marl::schedule([=] { mutex->unlock(); });
  wg.wait();
}

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

#include "marl/blockingcall.h"

#include "marl/defer.h"

#include "marl_test.h"

#include <mutex>

TEST_P(WithBoundScheduler, BlockingCall) {
  auto mutex = std::make_shared<std::mutex>();
  mutex->lock();

  marl::WaitGroup wg(100);
  for (int i = 0; i < 100; i++) {
    marl::schedule([=] {
      defer(wg.done());
      marl::blocking_call([=] {
        mutex->lock();
        defer(mutex->unlock());
      });
    });
  }

  mutex->unlock();
  wg.wait();
}

Fix TSAN issue with BlockingCall test.


//============================================================================
// Name        : TimeSeriesStatisticsDemo.cpp
// Author      : Dominik Skoda <skoda@d3s.mff.cuni.cz>
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <cstdlib>
#include "TimeSeries.h"
#include "StudentsDistribution.h"

using namespace std;

int main() {
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!

	TimeSeries<10000,1000> s;
	for(size_t i = 0; i < 20; ++i){
		s.addSample(i%5, i*300);
	}
	StudentsDistribution d = s.getMean();

	cout << d.isLessThan(2, 0.95) << endl;

	return 0;
}

//============================================================================
// Name        : TimeSeriesStatisticsDemo.cpp
// Author      : Dominik Skoda <skoda@d3s.mff.cuni.cz>
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <cstdlib>
#include "TimeSeries.h"
#include "StudentsDistribution.h"
#include "TDistribution.h"

using namespace std;

int main() {
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!

	TimeSeries<10000,1000> s;
	for(size_t i = 0; i < 20; ++i){
		s.addSample(i%5, i*300);
	}
	StudentsDistribution d = s.getMean();

	cout << d.isLessThan(2, 0.95) << endl;

	TDistribution td;
	int err;
	for(size_t i = 0; i < 100; ++i){
		double t = td.tnc(0.975, i, 0, &err);
		if(err){
			cout << "err " << err << endl;
		}
		cout << t << endl;
	}

	return 0;
}

Test of the tnc function.


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

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

// aligned allocation functions are not provided prior to macosx10.13
// XFAIL: macosx10.12
// XFAIL: macosx10.11
// XFAIL: macosx10.10
// XFAIL: macosx10.9
// XFAIL: macosx10.8
// XFAIL: macosx10.7

#include <new>

#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
#   error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it"
#endif

int main() { }

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

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

// aligned allocation functions are not provided prior to macosx10.13
// UNSUPPORTED: macosx10.12
// UNSUPPORTED: macosx10.11
// UNSUPPORTED: macosx10.10
// UNSUPPORTED: macosx10.9
// UNSUPPORTED: macosx10.8
// UNSUPPORTED: macosx10.7

#include <new>

#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
#   error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it"
#endif

int main() { }

Disable the aligned allocation test on old mac versions instead of XFAILing it


#include "application.h"
#include "mainwindow.h"

#include <QApplication>
#include <QMainWindow>

int main(int argc, char *argv[])
{
//    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);
    app.setOrganizationName("lpd8-editor");
    app.setApplicationName("lpd8-editor");
    app.setApplicationVersion("0.0.0");

    Application application;

    MainWindow win(&application);
    win.show();

//    Application app;

    return app.exec();
}

#include "application.h"
#include "mainwindow.h"

#include <QApplication>
#include <QMainWindow>

int main(int argc, char *argv[])
{
#if QT_VERSION >= 0x050600
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QApplication app(argc, argv);
    app.setOrganizationName("lpd8-editor");
    app.setApplicationName("lpd8-editor");
    app.setApplicationVersion("0.0.0");

    Application application;

    MainWindow win(&application);
    win.show();

    return app.exec();
}

Enable HiDPI rendering if supported


/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

#include "../lib.hh"
#include "catch.hpp"

using namespace vick;
using vick::move::mvcol;

TEST_CASE("mvcol", "[mvcol]") {
    contents contents({"asert"});

    visual_setup _;
    mvcol(contents, 3);
    CHECK(contents.y == 0);
    CHECK(contents.x == 3);

    mvcol(contents, 10); // doesn't do anything
    CHECK(contents.y == 0);
    CHECK(contents.y == 0);

    mvcol(contents, 0);
    CHECK(contents.y == 0);
    CHECK(contents.x == 0);
}

/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

#include "../lib.hh"
#include "catch.hpp"

using namespace vick;
using vick::move::mvcol;

TEST_CASE("mvcol", "[mvcol]") {
    contents contents({"asert"});

    visual_setup _;
    mvcol(contents, 3);
    CHECK(contents.y == 0);
    CHECK(contents.x == 3);

    mvcol(contents, 10); // doesn't do anything
    CHECK(contents.y == 0);
    CHECK(contents.x == 3);

    mvcol(contents, 0);
    CHECK(contents.y == 0);
    CHECK(contents.x == 0);
}

Fix testing same condition twice (copy paste)


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

namespace ExplicitConv {
  struct X { }; // expected-note 2{{candidate constructor}}

  struct Y {
    explicit operator X() const;
  };

  void test(const Y& y) {
    X x(static_cast<X>(y));
    X x2((X)y);
    X x3 = y; // expected-error{{no viable conversion from 'const ExplicitConv::Y' to 'ExplicitConv::X'}}
  }
}

namespace DR899 {
  struct C { }; // expected-note 2 {{candidate constructor}}

  struct A {
    explicit operator int() const;
    explicit operator C() const;
  };

  struct B {
    int i;
    B(const A& a): i(a) { }
  };

  int main() {
    A a;
    int i = a; // expected-error{{no viable conversion}}
    int j(a);
    C c = a; // expected-error{{no viable conversion}}
    C c2(a);
  }
}

Add test for C++ DR899.


#include <fstream>

#include <VBE/system/sdl2/StorageImpl.hpp>

// static
std::unique_ptr<std::istream> StorageImpl::openAsset(const std::string& filename) {
	// Open in binary mode so Windows doesn't change LF to CRLF,
	// which will corrupt binary files such as images.
	return std::unique_ptr<std::istream>(new std::ifstream("assets/"+filename, std::ios::binary));
}

#include <fstream>

#include <VBE/system/sdl2/StorageImpl.hpp>
#include <VBE/system/Log.hpp>

// static
std::unique_ptr<std::istream> StorageImpl::openAsset(const std::string& filename) {
	// Open in binary mode so Windows doesn't change LF to CRLF,
	// which will corrupt binary files such as images.
	std::ifstream* stream = new std::ifstream("assets/"+filename, std::ios::binary);

	VBE_ASSERT(stream->good(), "Could not open asset: "+filename);
	return std::unique_ptr<std::istream>(stream);
}

Check that assets are opened properly.


#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
#if IMUL_EARLY_EXITS
    b <- c == 0
    d <- d &~ b     // d = (c == 0) ? 0 : d
    b <- d == 0
    p <- @+L_done & b + p
#endif

    o <- o - 3
    h -> [o + (3 - 0)]
    i -> [o + (3 - 1)]
    j -> [o + (3 - 2)]

    b <- 0
    h <- 1

    j <- d >> 31    // save sign bit in j
    d <- d ^ j      // adjust multiplier
    d <- d - 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
    p <- @+L_top &~ i + p

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

    o <- o + 3
    j <- [o - 2]
    i <- [o - 1]
    h <- [o - 0]
L_done:
    o <- o + 1
    p <- [o]

#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    o <- o - 3
    h -> [o + (3 - 0)]
    i -> [o + (3 - 1)]
    j -> [o + (3 - 2)]

    b <- 0
    h <- 1

    j <- d >> 31    // save sign bit in j
    d <- d ^ j      // adjust multiplier
    d <- d - 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
    p <- @+L_top &~ i + p

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

    o <- o + 3
    j <- [o - 2]
    i <- [o - 1]
    h <- [o - 0]
L_done:
    o <- o + 1
    p <- [o]

Remove optimization dependent on cpp


#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
#if IMUL_EARLY_EXITS
    b <- c == 0
    d <- d &~ b     // d = (c == 0) ? 0 : d
    b <- d <> 0
    jzrel(b, L_done)
#endif

    pushall(h,i,j)

    b <- 0
    h <- 1

    j <- d >> 31    // save sign bit in j
    j <- -j         // convert sign to flag
    d <- d ^ j      // adjust multiplier
    d <- d - 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)

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

    popall(h,i,j)
L_done:
    ret

#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
#if IMUL_EARLY_EXITS
    b <- c == 0
    d <- d &~ b     // d = (c == 0) ? 0 : d
    b <- d <> 0
    jzrel(b, L_done)
#endif

    pushall(h,i,j)

    b <- 0
    h <- 1

    j <- d >>> 31   // save sign bit in j
    d <- d ^ j      // adjust multiplier
    d <- d - 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)

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

    popall(h,i,j)
L_done:
    ret

Use arithmetic right-shift in imul


#include "gmock/gmock.h"

#include "tcframe/experimental/runner.hpp"

using ::testing::Test;

namespace tcframe {

class FakeProblem : public BaseProblem {
protected:
    void InputFormat() {}
};

class FakeGenerator : public BaseGenerator<FakeProblem> {};

class RunnerTests : public Test {
protected:
    int argc = 1;
    char* argv[1] = {const_cast<char*>("./runner")};

    Runner<FakeProblem> runner = Runner<FakeProblem>(argc, argv);
};

TEST_F(RunnerTests, CompilationSuccessful) {
    runner.setGenerator(new FakeGenerator());
}

}

#include "gmock/gmock.h"

#include "tcframe/experimental/runner.hpp"

using ::testing::Test;

namespace tcframe {

class FakeProblem : public BaseProblem {
protected:
    void InputFormat() {}
};

class FakeGenerator : public BaseGenerator<FakeProblem> {};

class RunnerTests : public Test {
protected:
    int argc = 1;
    char* argv[1] = {toChar("./runner")};

    Runner<FakeProblem> runner = Runner<FakeProblem>(argc, argv);

private:
    static char* toChar(const string& str) {
        char* cstr = new char[str.length() + 1];
        strcpy(cstr, str.c_str());
        return cstr;
    }
};

TEST_F(RunnerTests, CompilationSuccessful) {
    runner.setGenerator(new FakeGenerator());
}

}

Use safer cast from const char* literal to char*


/*
 * Copyright 2004-2014 Cray Inc.
 * Other additional copyright holders may be indicated within.
 *
 * The entirety of this work is 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 <cstdio>
#include "driver.h"
#include "version.h"
#include "version_num.h"

void
get_version(char *v) {
  v += sprintf(v, "%d.%s.%s", MAJOR_VERSION, MINOR_VERSION, UPDATE_VERSION);
  if (strcmp(BUILD_VERSION, "") || developer)
    sprintf(v, ".%s", BUILD_VERSION);
}

/*
 * Copyright 2004-2014 Cray Inc.
 * Other additional copyright holders may be indicated within.
 *
 * The entirety of this work is 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 <cstdio>
#include "driver.h"
#include "version.h"
#include "version_num.h"

void
get_version(char *v) {
  v += sprintf(v, "%d.%s.%s", MAJOR_VERSION, MINOR_VERSION, UPDATE_VERSION);
  if (!strcmp(BUILD_VERSION, "") || developer)
    sprintf(v, ".%s", BUILD_VERSION);
}

Fix boolean expectation from strcmp.


// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <test/fuzz/fuzz.h>
#include <util/bip32.h>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string keypath_str(buffer.begin(), buffer.end());
    std::vector<uint32_t> keypath;
    (void)ParseHDKeypath(keypath_str, keypath);
}

// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <util/bip32.h>

#include <cstdint>
#include <vector>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string keypath_str(buffer.begin(), buffer.end());
    std::vector<uint32_t> keypath;
    (void)ParseHDKeypath(keypath_str, keypath);

    FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
    const std::vector<uint32_t> random_keypath = ConsumeRandomLengthIntegralVector<uint32_t>(fuzzed_data_provider);
    (void)FormatHDKeypath(random_keypath);
    (void)WriteHDKeypath(random_keypath);
}

Add fuzzing coverage for FormatHDKeypath(...) and WriteHDKeypath(...)


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

#include "base/cancellation_flag.h"

#include "base/logging.h"

namespace base {

void CancellationFlag::Set() {
#if !defined(NDEBUG)
  DCHECK(set_on_ == PlatformThread::CurrentId());
#endif
  base::subtle::Release_Store(&flag_, 1);
}

bool CancellationFlag::IsSet() const {
  return base::subtle::Acquire_Load(&flag_) != 0;
}

}  // namespace base

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

#include "base/cancellation_flag.h"

#include "base/logging.h"

namespace base {

void CancellationFlag::Set() {
#if !defined(NDEBUG)
  DCHECK_EQ(set_on_, PlatformThread::CurrentId());
#endif
  base::subtle::Release_Store(&flag_, 1);
}

bool CancellationFlag::IsSet() const {
  return base::subtle::Acquire_Load(&flag_) != 0;
}

}  // namespace base

Replace a DCHECK with DCHECK_EQ.


//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/Support/TimeValue.h"
#include <time.h>

using namespace llvm;
namespace {

TEST(TimeValue, time_t) {
  sys::TimeValue now = sys::TimeValue::now();
  time_t now_t = time(NULL);
  EXPECT_TRUE(abs(static_cast<long>(now_t - now.toEpochTime())) < 2);
}

TEST(TimeValue, Win32FILETIME) {
  uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL;
  uint32_t ns = 765432100;
  sys::TimeValue epoch;

  // FILETIME has 100ns of intervals.
  uint64_t ft1970 = epoch_as_filetime + ns / 100;
  epoch.fromWin32Time(ft1970);

  // The "seconds" part in Posix time may be expected as zero.
  EXPECT_EQ(0u, epoch.toEpochTime());
  EXPECT_EQ(ns, static_cast<uint32_t>(epoch.nanoseconds()));

  // Confirm it reversible.
  EXPECT_EQ(ft1970, epoch.toWin32Time());
}

}

//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/Support/TimeValue.h"
#include <time.h>

using namespace llvm;
namespace {

TEST(TimeValue, time_t) {
  sys::TimeValue now = sys::TimeValue::now();
  time_t now_t = time(NULL);
  EXPECT_TRUE(std::abs(static_cast<long>(now_t - now.toEpochTime())) < 2);
}

TEST(TimeValue, Win32FILETIME) {
  uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL;
  uint32_t ns = 765432100;
  sys::TimeValue epoch;

  // FILETIME has 100ns of intervals.
  uint64_t ft1970 = epoch_as_filetime + ns / 100;
  epoch.fromWin32Time(ft1970);

  // The "seconds" part in Posix time may be expected as zero.
  EXPECT_EQ(0u, epoch.toEpochTime());
  EXPECT_EQ(ns, static_cast<uint32_t>(epoch.nanoseconds()));

  // Confirm it reversible.
  EXPECT_EQ(ft1970, epoch.toWin32Time());
}

}

Use the overloaded std::abs rather than C's abs(int) to address Clang's -Wabsolute-value


/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/

// This file is auto-generated by CMake at build time
#include "nomlib/version.hpp"

const std::string NOMLIB_INSTALL_PREFIX = "/Users/jeff/Library/Frameworks";
const std::string NOMLIB_BUNDLE_IDENTIFIER = "org.i8degrees.nomlib";

/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/

// This file is auto-generated by CMake at build time
#include "nomlib/version.hpp"

#if defined (NOM_PLATFORM_WINDOWS)
  const std::string NOMLIB_INSTALL_PREFIX = "C:/";
#endif

const std::string NOMLIB_BUNDLE_IDENTIFIER = "org.i8degrees.nomlib";

Add conditional preprocessor for nomlib's install prefix under Windows


/*
Copyright 2017 Google Inc. 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 "ofMain.h"
#include "ofApp.h"

//========================================================================
int main(){
	ofSetupOpenGL(1024, 768, OF_WINDOW);
	ofRunApp(new ofApp());
}

/*
Copyright 2017 Google Inc. 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 "ofMain.h"
#include "ofApp.h"

//========================================================================
int main(){
	ofSetupOpenGL(126, 64, OF_WINDOW);
	ofRunApp(new ofApp());
}

Decrease window size to use less screen space


// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Generic.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/ReturnHandTask.hpp>

namespace RosettaStone::SimpleTasks
{
ReturnHandTask::ReturnHandTask(EntityType entityType) : ITask(entityType)
{
    // Do nothing
}

TaskID ReturnHandTask::GetTaskID() const
{
    return TaskID::RETURN_HAND;
}

TaskStatus ReturnHandTask::Impl(Player& player)
{
    auto entities =
        IncludeTask::GetEntities(m_entityType, player, m_source, m_target);

    for (auto& entity : entities)
    {
        Generic::RemoveMinionFromField(m_target->GetOwner(),
                                       dynamic_cast<Minion*>(entity));
        entity->Reset();
        Generic::AddCardToHand(m_target->GetOwner(), entity);
    }

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Actions/Generic.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/ReturnHandTask.hpp>

namespace RosettaStone::SimpleTasks
{
ReturnHandTask::ReturnHandTask(EntityType entityType) : ITask(entityType)
{
    // Do nothing
}

TaskID ReturnHandTask::GetTaskID() const
{
    return TaskID::RETURN_HAND;
}

TaskStatus ReturnHandTask::Impl(Player& player)
{
    auto entities =
        IncludeTask::GetEntities(m_entityType, player, m_source, m_target);

    for (auto& entity : entities)
    {
        Generic::RemoveMinionFromField(entity->GetOwner(),
                                       dynamic_cast<Minion*>(entity));
        entity->Reset();
        Generic::AddCardToHand(entity->GetOwner(), entity);
    }

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

Correct nullptr problem (change 'm_target' to 'entity')


/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include "utils.h"

#include <cstdio>

namespace UTILS_NS
{
namespace PlatformUtils
{
	std::string GetFirstMACAddress()
	{
		MACAddress address;
		memset(&address, 0, sizeof(MACAddress));

		try
		{
			PlatformUtils::GetFirstMACAddressImpl(address);
		}
		catch(...)
		{
			// Just return zeros.
		}

		char result[18];
		std::sprintf(result, "%02x:%02x:%02x:%02x:%02x:%02x",
			address[0], address[1], address[2], address[3],
			address[4], address[5]);
		return std::string(result);
	}

	std::string GetMachineId()
	{
        static std::string machineID;
        if (machineID.empty())
            machineID = DataUtils::HexMD5(GetFirstMACAddress());
        return machineID;
	}
}
}

/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include "utils.h"

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

namespace UTILS_NS
{
namespace PlatformUtils
{
	std::string GetFirstMACAddress()
	{
		MACAddress address;
		memset(&address, 0, sizeof(MACAddress));

		try
		{
			PlatformUtils::GetFirstMACAddressImpl(address);
		}
		catch(...)
		{
			// Just return zeros.
		}

		char result[18];
		std::sprintf(result, "%02x:%02x:%02x:%02x:%02x:%02x",
			address[0], address[1], address[2], address[3],
			address[4], address[5]);
		return std::string(result);
	}

	std::string GetMachineId()
	{
        static std::string machineID;
        if (machineID.empty())
            machineID = DataUtils::HexMD5(GetFirstMACAddress());
        return machineID;
	}
}
}

Fix build error on Linux.


#include "fnv_param.hpp"
#include "fnv_algo.hpp"
#include "constraint.hpp"
#include "fnv_solver.hpp"
#include <vector>
#include <iostream>
#include <boost/foreach.hpp>

int main(int argc, char** argv)
{
  const std::vector<FNVParam> fnvParams = FNVParam::getAll();
  const std::vector<FNVAlgo> fnvAlgos = FNVAlgo::getAll();
  const std::vector<Constraint> constraints = Constraint::getAll();

  BOOST_FOREACH(const FNVParam& fnvParam, fnvParams)
  {
    std::cout << "Problem size: " << fnvParam.getWidth() << std::endl;

    BOOST_FOREACH(const FNVAlgo& fnvAlgo, fnvAlgos)
    {
      std::cout << "Algorithm: FNV-" << fnvAlgo.getName() << std::endl;

      const Constraint nullConstraint = Constraint::getNull();
      std::cout << "Constraint: " << nullConstraint.getName() << std::endl;
      FNVSolver solver(fnvParam, fnvAlgo, nullConstraint);
      solver.solve();
      const int solutionLength = solver.getSolutionLength();

      BOOST_FOREACH(const Constraint& constraint, constraints)
      {
        std::cout << "Constraint: " << constraint.getName() << std::endl;
        FNVSolver solver(fnvParam, fnvAlgo, constraint, solutionLength);
        solver.solve();
      }
    }
  }
}

#include "fnv_param.hpp"
#include "fnv_algo.hpp"
#include "constraint.hpp"
#include "fnv_solver.hpp"
#include <vector>
#include <iostream>
#include <boost/foreach.hpp>

int main(int argc, char** argv)
{
  const std::vector<FNVParam> fnvParams = FNVParam::getAll();
  const std::vector<FNVAlgo> fnvAlgos = FNVAlgo::getAll();
  const std::vector<Constraint> constraints = Constraint::getAll();

  BOOST_FOREACH(const FNVParam& fnvParam, fnvParams)
  {
    std::cout << "Problem size: " << fnvParam.getWidth() << std::endl;

    BOOST_FOREACH(const FNVAlgo& fnvAlgo, fnvAlgos)
    {
      std::cout << "Algorithm: FNV-" << fnvAlgo.getName() << std::endl;

      const Constraint nullConstraint = Constraint::getNull();
      std::cout << "Constraint: " << nullConstraint.getName() << std::endl;
      FNVSolver solver(fnvParam, fnvAlgo, nullConstraint);
      solver.solve();
      const int solutionLength = solver.getSolutionLength();

      BOOST_FOREACH(const Constraint& constraint, constraints)
      {
        std::cout << "Constraint: " << constraint.getName() << std::endl;
        FNVSolver solver(fnvParam, fnvAlgo, constraint, solutionLength);
        solver.solve();
      }
    }

    std::cout << std::endl;
  }
}

Add slightly more spacing in output.


/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
#include "webrtc/base/checks.h"
#include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h"
#include "webrtc/system_wrappers/include/clock.h"

namespace webrtc {

void FuzzOneInput(const uint8_t* data, size_t size) {
  RTCPUtility::RTCPParserV2 rtcp_parser(data, size, true);
  if (!rtcp_parser.IsValid())
    return;

  webrtc::SimulatedClock clock(1234);
  RTCPReceiver receiver(&clock, false, nullptr, nullptr, nullptr, nullptr,
                        nullptr);

  RTCPHelp::RTCPPacketInformation rtcp_packet_information;
  receiver.IncomingRTCPPacket(rtcp_packet_information, &rtcp_parser);
}
}  // namespace webrtc

/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
#include "webrtc/base/checks.h"
#include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h"
#include "webrtc/system_wrappers/include/clock.h"

namespace webrtc {
namespace {

class NullModuleRtpRtcp : public RTCPReceiver::ModuleRtpRtcp {
 public:
  void SetTmmbn(std::vector<rtcp::TmmbItem>) override {}
  void OnRequestSendReport() override {}
  void OnReceivedNack(const std::vector<uint16_t>&) override {};
  void OnReceivedRtcpReportBlocks(const ReportBlockList&) override {};
};

}

void FuzzOneInput(const uint8_t* data, size_t size) {
  NullModuleRtpRtcp rtp_rtcp_module;
  SimulatedClock clock(1234);

  RTCPReceiver receiver(&clock, false, nullptr, nullptr, nullptr, nullptr,
                        &rtp_rtcp_module);

  receiver.IncomingPacket(data, size);
}
}  // namespace webrtc

Update rtcp receiver fuzzer to use generic function IncomingPacket(const uint8_t* packet, size_t size) instead of implementation specific IncomingRTCPPacket(PacketInfo* out, Parser* in) This would allow switch parse implementation


// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s -triple x86_64-apple-darwin10 | FileCheck %s
// RUN: %clang_cc1 -S -emit-llvm -o %t.ll %s -triple x86_64-apple-darwin10
// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o %t-c++11.ll %s -triple x86_64-apple-darwin10
// RUN: diff %t.ll  %t-c++11.ll

// rdar://12897704

struct sAFSearchPos {
    unsigned char *pos;
    unsigned char count;
};

static volatile struct sAFSearchPos testPositions;
// CHECK: @_ZL13testPositions = internal global %struct.sAFSearchPos zeroinitializer

static volatile struct sAFSearchPos arrayPositions[100][10][5];
// CHECK: @_ZL14arrayPositions = internal global [100 x [10 x [5 x %struct.sAFSearchPos]]] zeroinitializer

int main() {
  return testPositions.count + arrayPositions[10][4][3].count;
}

// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o %t-c++11.ll %s -triple x86_64-apple-darwin10
// RUN: FileCheck %s < %t-c++11.ll
// RUN: %clang_cc1  -std=c++98 -S -emit-llvm -o %t.ll %s -triple x86_64-apple-darwin10
// RUN: diff %t.ll  %t-c++11.ll

// rdar://12897704

struct sAFSearchPos {
    unsigned char *pos;
    unsigned char count;
};

static volatile struct sAFSearchPos testPositions;
// CHECK: @_ZL13testPositions = internal global %struct.sAFSearchPos zeroinitializer

static volatile struct sAFSearchPos arrayPositions[100][10][5];
// CHECK: @_ZL14arrayPositions = internal global [100 x [10 x [5 x %struct.sAFSearchPos]]] zeroinitializer

int main() {
  return testPositions.count + arrayPositions[10][4][3].count;
}

Add -std=c++98 to the test and minor improvment in addition.


#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <string>

int main(int argc, char ** argv)
{
    std::ifstream input{argv[1]};
    std::string line;

    std::getline(input, line);
    while(input)
    {
        std::for_each(std::begin(line), std::end(line), [](char c) {
            std::cout << static_cast<char>(std::tolower(c));
        });
        std::cout << '\n';
        std::getline(input, line);
    }
    return 0;
}

#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <string>

int main(int argc, char ** argv)
{
    std::ifstream input{argv[1]};
    std::string line;

    std::getline(input, line);
    while(input)
    {
        std::transform(std::begin(line), std::end(line), std::begin(line), [](char c) {
            return static_cast<char>(std::tolower(c));
        });
        std::cout << line << '\n';
        std::getline(input, line);
    }
    return 0;
}

Use transform instead of for_each


/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <ogvr/ClientKit/ContextC.h>

// Library/third-party includes
// - none

// Standard includes
#include <iostream>

int main() {
    OGVR_ClientContext ctx =
        ogvrClientInit("org.opengoggles.exampleclients.MinimalInit");
    std::cout << "OK, library initialized, now going to shut it down."
              << std::endl;
    ogvrClientShutdown(ctx);
    std::cout << "Library shut down, exiting." << std::endl;
    return 0;
}

/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <ogvr/ClientKit/ContextC.h>

// Library/third-party includes
// - none

// Standard includes
#include <iostream>

int main() {
    OGVR_ClientContext ctx =
        ogvrClientInit("org.opengoggles.exampleclients.MinimalInit");
    std::cout << "OK, library initialized." << std::endl;

    // Pretend that this is your application's mainloop.
    for (int i = 0; i < 1000000; ++i) {
        ogvrClientUpdate(ctx);
    }

    ogvrClientShutdown(ctx);

    std::cout << "Library shut down, exiting." << std::endl;
    return 0;
}

Add mainloop to minimal init


/*
 * Copyright (C) 2016 Luke San Antonio
 * All rights reserved.
 */

// Include the implementation first so that it actually works. We have to do
// this because our header file includes the header as well, we might as well
// put the implementation here.
#define TINYGLTF_LOADER_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "../../gltf/tiny_gltf_loader.h"

#include "minigltf.h"

#include <cstdio>
#include "../common/log.h"

namespace redc
{
  boost::optional<tinygltf::Scene> load_gltf_file(std::string name)
  {
    std::string err;
    tinygltf::Scene scene;

    tinygltf::TinyGLTFLoader loader;

    if(!loader.LoadASCIIFromFile(&scene, &err, name))
    {
      log_e("Error in '%': %", name, err);
      return boost::none;
    }

    return std::move(scene);
  }
}

/*
 * Copyright (C) 2016 Luke San Antonio
 * All rights reserved.
 */

// Include the implementation first so that it actually works. We have to do
// this because our header file includes the header as well, we might as well
// put the implementation here.
#define TINYGLTF_LOADER_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#include "../../gltf/tiny_gltf_loader.h"

#include "minigltf.h"

#include <cstdio>
#include "../common/log.h"

namespace redc
{
  boost::optional<tinygltf::Scene> load_gltf_file(std::string name)
  {
    std::string err;
    tinygltf::Scene scene;

    tinygltf::TinyGLTFLoader loader;

    if(!loader.LoadASCIIFromFile(&scene, &err, name))
    {
      log_e("Error in '%': %", name, err);
      return boost::none;
    }
    else
    {
      log_i("Information loading '%': %", name, err);
    }

    return std::move(scene);
  }
}

Print debugging information from tinygltfloader


//
// Created by monty on 08/12/16.
//
#include <string>
#include <iostream>
#include <fstream>

#include "IFileLoaderDelegate.h"
#include "CPlainFileLoader.h"

namespace Knights {
	std::string CPlainFileLoader::loadFileFromPath( const std::string& path ) {
		std::string entry;
		std::ifstream fileToLoad(path);

		char buffer;

		while (!fileToLoad.eof()) {
			fileToLoad >> buffer;
			entry += buffer;
		}

		return entry;
	}

	std::string CPlainFileLoader::getFilePathPrefix() {
		return "res/";
	}
}

//
// Created by monty on 08/12/16.
//
#include <string>
#include <iostream>
#include <fstream>

#include "IFileLoaderDelegate.h"
#include "CPlainFileLoader.h"

namespace Knights {
	std::string CPlainFileLoader::loadFileFromPath( const std::string& path ) {
		std::string entry;
		std::ifstream fileToLoad(path);

		char buffer;

		while (!fileToLoad.eof()) {
			fileToLoad >> buffer;
			entry.push_back(buffer);
		}

		return entry;
	}

	std::string CPlainFileLoader::getFilePathPrefix() {
		return "res/";
	}
}

Replace the += operator with push_back on file loading operations


#include "picturemodel.h"

#include <QFile>

PictureModel::PictureModel(QObject *parent)
    : MediaModel(MediaModel::Picture, parent)
{
    QHash<int, QByteArray> roleNames = MediaModel::roleNames();
    setRoleNames(roleNames);
}

PictureModel::~PictureModel()
{
}

QVariant PictureModel::data(MediaInfo *mediaInfo, int role) const
{
    if (role == Qt::DisplayRole)
        return mediaInfo->name;
    return QVariant();
}

QImage PictureModel::decoration(MediaInfo *info) const
{
    QImage thumbnail = (static_cast<PictureInfo *>(info))->thumbnail;
    if (thumbnail.isNull())
        return QImage(themeResourcePath() + "/media/Fanart_Fallback_Picture_Small.jpg"); // FIXME: Make this configurable
    return thumbnail;
}

MediaInfo *PictureModel::readMediaInfo(const QString &filePath)
{
    QImage image(filePath);

    PictureInfo *info = new PictureInfo;
    info->thumbnail = image;

    return info;
}

#include "picturemodel.h"

#include <QFile>
#include <QImageReader>

PictureModel::PictureModel(QObject *parent)
    : MediaModel(MediaModel::Picture, parent)
{
    QHash<int, QByteArray> roleNames = MediaModel::roleNames();
    setRoleNames(roleNames);
}

PictureModel::~PictureModel()
{
}

QVariant PictureModel::data(MediaInfo *mediaInfo, int role) const
{
    if (role == Qt::DisplayRole)
        return mediaInfo->name;
    return QVariant();
}

QImage PictureModel::decoration(MediaInfo *info) const
{
    return (static_cast<PictureInfo *>(info))->thumbnail;
}

MediaInfo *PictureModel::readMediaInfo(const QString &filePath)
{
    QImageReader imageReader(filePath);
    if (!imageReader.canRead())
        return 0;

    QImage image = imageReader.read();
    if (image.isNull())
        return 0;

    PictureInfo *info = new PictureInfo;
    info->thumbnail = image;

    return info;
}

Use ImageReader to read the images


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

#include <ESP.h>

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

void setup()
{
    useInputStream(stream);

    pipeline.addFeatureExtractionModule(TimeseriesBuffer(1, 160));
    usePipeline(pipeline);
}

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

#include <ESP.h>

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

void setup()
{
    useInputStream(stream);

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

Add SVM classifier to Touche example.


/**
 * Unit tests for base kernel class
 * @author Vyacheslav Kompan kompan.vo@phystech.edu
 * Copyright 2018 MIPT-MIPS
 */

#include "../kernel.h"
// Catch2
#include <catch.hpp>

TEST_CASE( "Kernel: Execute nothing")
{
    CHECK( Kernel::create_dummy_kernel()->execute() == Trap::SYSCALL);
    CHECK( Kernel::create_configured_kernel()->execute() == Trap::SYSCALL);
}

/**
 * Unit tests for base kernel class
 * @author Vyacheslav Kompan kompan.vo@phystech.edu
 * Copyright 2018 MIPT-MIPS
 */

#include "../kernel.h"
#include <catch.hpp>

TEST_CASE( "Kernel: Execute nothing")
{
    CHECK( Kernel::create_dummy_kernel()->execute() == Trap::SYSCALL);
    CHECK( Kernel::create_configured_kernel()->execute() == Trap::SYSCALL);
    CHECK_NOTHROW( Kernel::create_dummy_kernel()->set_simulator( nullptr));
    CHECK_NOTHROW( Kernel::create_dummy_kernel()->connect_memory( nullptr));
    CHECK_NOTHROW( Kernel::create_dummy_kernel()->add_replica_simulator( nullptr));
    CHECK_NOTHROW( Kernel::create_dummy_kernel()->add_replica_memory( nullptr));
}

Add unit tests for dummy kernel


// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#include <string>
#include <iostream>

#include <pegtl.hh>

namespace hello
{
   struct prefix : pegtl::string< 'H', 'e', 'l', 'l', 'o', ',', ' ' > {};
   struct name : pegtl::plus< pegtl::alpha > {};
   struct grammar : pegtl::seq< prefix, name, pegtl::one< '!' >, pegtl::eof > {};

   template< typename Rule >
   struct action
         : pegtl::nothing< Rule > {};

   template<> struct action< name >
   {
      static void apply( const pegtl::input & in, std::string & name )
      {
         name = in.string();
      }
   };
}

int main( int argc, char * argv[] )
{
   if ( argc > 1 ) {
      std::string name;
      pegtl::parse< hello::grammar, hello::action >( 1, argv, name );
      std::cout << "Good bye, " << name << "!" << std::endl;
   }
}

// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#include <string>
#include <iostream>

#include <pegtl.hh>

namespace hello
{
   struct prefix : pegtl::string< 'H', 'e', 'l', 'l', 'o', ',', ' ' > {};
   struct name : pegtl::plus< pegtl::alpha > {};
   struct grammar : pegtl::must< prefix,
                                 name,
                                 pegtl::one< '!' >,
                                 pegtl::eof > {};

   template< typename Rule >
   struct action
         : pegtl::nothing< Rule > {};

   template<> struct action< name >
   {
      static void apply( const pegtl::input & in,
                         std::string & name )
      {
         name = in.string();
      }
   };
}

int main( int argc, char * argv[] )
{
   if ( argc > 1 ) {
      std::string name;
      pegtl::parse< hello::grammar, hello::action >( 1,
                                                     argv,
                                                     name );
      std::cout << "Good bye, " << name << "!" << std::endl;
   }
}

Use top-level must<> instead of seq<>


#include "helper.h"
#include "../lib/triangle.h"

#include <catch.hpp>

TEST_CASE("Test Triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = random_triangle();

        Vec normal = triangle.normal;

        // Verify unit lenght of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));

        // Verify normal is perpendicular to edges of triangle.
        float cos_u = normal * triangle.u.Normalize();
        float cos_v = normal * triangle.v.Normalize();
        REQUIRE(cos_u == Approx(0.f));
        REQUIRE(cos_v == Approx(0.f));
    }
}

#include "helper.h"
#include "../lib/triangle.h"

#include <catch.hpp>

TEST_CASE("Test Triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = random_triangle();

        Vec normal = triangle.normal;

        // Verify unit length of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));

        // Verify normal is perpendicular to edges of triangle.
        float cos_u = normal * triangle.u.Normalize();
        float cos_v = normal * triangle.v.Normalize();
        REQUIRE(cos_u == Approx(0.f));
        REQUIRE(cos_v == Approx(0.f));
    }
}

TEST_CASE("Test interpolate triangle normal", "[triangle]")
{
    static constexpr int NUM_SAMPLES = 100;

    for (int j = 0; j < NUM_SAMPLES; ++j) {
        Triangle triangle = test_triangle( random_vec(), random_vec(),
            random_vec(), random_vec().Normalize(), random_vec().Normalize(),
            random_vec().Normalize());

        float r = uniform();
        float s = uniform();
        float t = uniform();
        while( r+s+t > 1.0f) {
          r = uniform();
          s = uniform();
          t = uniform();
        }
        Vec normal = triangle.interpolate_normal(r, s, t);

        // Verify unit length of normal.
        float length = normal.Length();
        REQUIRE(length == Approx(1.f));
    }
}

Test normal interpolation for triangle.


#include "xchainer/device.h"

#include <future>

#include <gtest/gtest.h>
#include "xchainer/error.h"

namespace xchainer {

TEST(DeviceTest, SetCurrentDevice) {
    Device cpu = {"cpu"};
    Device cuda = {"cuda"};
    auto device = GetCurrentDevice();

    SetCurrentDevice("cpu");
    ASSERT_EQ(cpu, GetCurrentDevice());

    SetCurrentDevice(cuda);
    ASSERT_EQ(cuda, GetCurrentDevice());

    ASSERT_THROW(SetCurrentDevice("invalid_device"), DeviceError);

    SetCurrentDevice(device);
}

TEST(DeviceTest, ThreadLocal) {
    auto device = GetCurrentDevice();

    SetCurrentDevice("cpu");
    auto future = std::async(std::launch::async, [] {
        SetCurrentDevice("cuda");
        return GetCurrentDevice();
    });
    ASSERT_NE(GetCurrentDevice(), future.get());

    SetCurrentDevice(device);
}

}  // namespace

#include "xchainer/device.h"

#include <future>

#include <gtest/gtest.h>
#include "xchainer/error.h"

namespace xchainer {

// Device must be POD (plain old data) to be used as a thread local variable safely.
// ref. https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
static_assert(std::is_pod<Device>::value, "Device must be POD");

TEST(DeviceTest, SetCurrentDevice) {
    Device cpu = {"cpu"};
    Device cuda = {"cuda"};
    auto device = GetCurrentDevice();

    SetCurrentDevice("cpu");
    ASSERT_EQ(cpu, GetCurrentDevice());

    SetCurrentDevice(cuda);
    ASSERT_EQ(cuda, GetCurrentDevice());

    ASSERT_THROW(SetCurrentDevice("invalid_device"), DeviceError);

    SetCurrentDevice(device);
}

TEST(DeviceTest, ThreadLocal) {
    auto device = GetCurrentDevice();

    SetCurrentDevice("cpu");
    auto future = std::async(std::launch::async, [] {
        SetCurrentDevice("cuda");
        return GetCurrentDevice();
    });
    ASSERT_NE(GetCurrentDevice(), future.get());

    SetCurrentDevice(device);
}

}  // namespace

Add tests to check Device is POD


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

namespace A {
#line 1 "foo.cpp"
namespace B {
int i;
}
}

// CHECK: [[FILE:![0-9]*]] {{.*}}debug-info-namespace.cpp"
// CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i]
// CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], null, metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1]
// CHECK: [[CTXT]] = {{.*}}, metadata [[FILE]], null, null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3]
// CHECK: {i32 {{[0-9]+}}, metadata [[FILE2]]{{.*}} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp]

// FIXME: It is confused on win32 to generate file entry when dosish filename is given.
// REQUIRES: shell

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

namespace A {
#line 1 "foo.cpp"
namespace B {
int i;
}
}

// CHECK: [[FILE:![0-9]*]] {{.*}}debug-info-namespace.cpp"
// CHECK: [[VAR:![0-9]*]] = {{.*}}, metadata [[NS:![0-9]*]], metadata !"i", {{.*}} ; [ DW_TAG_variable ] [i]
// CHECK: [[NS]] = {{.*}}, metadata [[FILE2:![0-9]*]], metadata [[CTXT:![0-9]*]], {{.*}} ; [ DW_TAG_namespace ] [B] [line 1]
// CHECK: [[CTXT]] = {{.*}}, metadata [[FILE]], null, {{.*}} ; [ DW_TAG_namespace ] [A] [line 3]
// CHECK: [[FILE2]]} ; [ DW_TAG_file_type ] [{{.*}}foo.cpp]

// FIXME: It is confused on win32 to generate file entry when dosish filename is given.
// REQUIRES: shell

Revert "Update debug info test for schema change made to LLVM."


//
//  kern_start.cpp
//  CPUFriend
//
//  Copyright © 2017 Vanilla. All rights reserved.
//

#include <Headers/plugin_start.hpp>
#include <Headers/kern_api.hpp>

#include "kern_cpuf.hpp"

static CPUFriendPlugin cpuf;

static const char *bootargOff[] {
  "-cpufoff"
};

static const char *bootargDebug[] {
  "-cpufdbg"
};

static const char *bootargBeta[] {
  "-cpufbeta"
};

PluginConfiguration ADDPR(config) {
  xStringify(PRODUCT_NAME),
  parseModuleVersion(xStringify(MODULE_VERSION)),
  bootargOff,
  arrsize(bootargOff),
  bootargDebug,
  arrsize(bootargDebug),
  bootargBeta,
  arrsize(bootargBeta),
  KernelVersion::MountainLion,
  KernelVersion::HighSierra,
  []() {
    cpuf.init();
  }
};

//
//  kern_start.cpp
//  CPUFriend
//
//  Copyright © 2017 Vanilla. All rights reserved.
//

#include <Headers/plugin_start.hpp>
#include <Headers/kern_api.hpp>

#include "kern_cpuf.hpp"

static CPUFriendPlugin cpuf;

static const char *bootargOff[] {
  "-cpufoff"
};

static const char *bootargDebug[] {
  "-cpufdbg"
};

static const char *bootargBeta[] {
  "-cpufbeta"
};

PluginConfiguration ADDPR(config) {
  xStringify(PRODUCT_NAME),
  parseModuleVersion(xStringify(MODULE_VERSION)),
  LiluAPI::AllowNormal | LiluAPI::AllowInstallerRecovery | LiluAPI::AllowSafeMode,
  bootargOff,
  arrsize(bootargOff),
  bootargDebug,
  arrsize(bootargDebug),
  bootargBeta,
  arrsize(bootargBeta),
  KernelVersion::MountainLion,
  KernelVersion::HighSierra,
  []() {
    cpuf.init();
  }
};

Update plugin requirements for 1.2.0


// 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 "remoting/host/capturer.h"

namespace remoting {

Capturer::Capturer()
    : width_(0),
      height_(0),
      pixel_format_(PixelFormatInvalid),
      bytes_per_pixel_(0),
      bytes_per_row_(0),
      current_buffer_(0) {
}

Capturer::~Capturer() {
}

void Capturer::GetDirtyRects(DirtyRects* rects) const {
  *rects = dirty_rects_;
}

int Capturer::GetWidth() const {
  return width_;
}

int Capturer::GetHeight() const {
  return height_;
}

PixelFormat Capturer::GetPixelFormat() const {
  return pixel_format_;
}

void Capturer::InvalidateRect(gfx::Rect dirty_rect) {
  inval_rects_.push_back(dirty_rect);
}

void Capturer::FinishCapture(Task* done_task) {
  done_task->Run();
  delete done_task;

  // Select the next buffer to be the current buffer.
  current_buffer_ = ++current_buffer_ % kNumBuffers;
}

}  // namespace remoting

// 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 "remoting/host/capturer.h"

namespace remoting {

Capturer::Capturer()
    : width_(0),
      height_(0),
      pixel_format_(PixelFormatInvalid),
      bytes_per_pixel_(0),
      bytes_per_row_(0),
      current_buffer_(0) {
}

Capturer::~Capturer() {
}

void Capturer::GetDirtyRects(DirtyRects* rects) const {
  *rects = dirty_rects_;
}

int Capturer::GetWidth() const {
  return width_;
}

int Capturer::GetHeight() const {
  return height_;
}

PixelFormat Capturer::GetPixelFormat() const {
  return pixel_format_;
}

void Capturer::InvalidateRect(gfx::Rect dirty_rect) {
  inval_rects_.push_back(dirty_rect);
}

void Capturer::FinishCapture(Task* done_task) {
  done_task->Run();
  delete done_task;

  // Select the next buffer to be the current buffer.
  current_buffer_ = (current_buffer_ + 1) % kNumBuffers;
}

}  // namespace remoting

Fix undefined assignment evaluation order in remoting::Capturer::FinishCapture.


#include <avr/io.h>
#include <avr/interrupt.h>
#include "AnalogAccel.h"

volatile Axis currentAxis = X;

ISR(ANALOG_COMP_vect) //To be executed once analog compare is completed
{
	//Do stuff...
}

AnalogAccel::AnalogAccel()
{
}

AnalogAccel::~AnalogAccel()
{
}

volatile Axis& AnalogAccel::currentAxis_ = currentAxis;

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include "AnalogAccel.h"

volatile Axis currentAxis = X;

ISR(ANALOG_COMP_vect) //To be executed once analog compare is completed
{
	//Do stuff...
}

AnalogAccel::AnalogAccel()
{
	//Prescaler of 64 (12MHz / 64 == 187.5 kHz),
	//recommended value is 50-200kHz. Also: Enable interrupt,
	//enable auto-triggering, start conversion and turn the ADC on.
	ADCSRA |= _BV(ADPS1) | _BV(ADPS2) | _BV(ADIE) | _BV(ADATE) \
		| _BV(ADSC) | _BV(ADEN);

	//Free-running mode: takes measurements as long as the ADC is enabled
	ADCSRB = 0;

	//Disable digital input buffers for those pins (saves power)
	DIDR0 |= _BV(ADC0D) | _BV(ADC1D) | _BV(ADC2D);
}

AnalogAccel::~AnalogAccel()
{
	ADCSRA &= ~_BV(ADEN); //Disable the ADC (also disables the interrupt)
}

volatile Axis& AnalogAccel::currentAxis_ = currentAxis;

Set ADC control registers in constructor


/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <cstring>

#include <qitype/signature.hpp>

namespace qi {

bool qi::Signature::isConvertibleTo(const qi::Signature& b) const
{
  if (size() != b.size())
    return false;
  static const char numeric[] = "bcCwWiIlLfd";
  static const char container[] = "[{";
  Signature::iterator s = begin();
  Signature::iterator d = b.begin();
  for (;s!=end() && d!= b.end(); ++s,++d)
  {
    if (d.type() == Type_Dynamic)
      continue; // Dynamic can convert to whatever
    // Main switch on source sig
    if (strchr(numeric, s.type()))
    { // Numeric
      if (!strchr(numeric, d.type()))
        return false;
    }
    else if (strchr(container, s.type()))
    { // Container, list or map
      if (d.type() != s.type())
        return false; // Must be same container
      if (!s.children().isConvertibleTo(d.children()))
        return false; // Just check subtype compatibility
    }
    else
      if (d.type() != s.type())
        return false;
  }
  assert(s==end() && d==b.end()); // we allready exited on size mismatch
  return true;
}

Signature Signature::fromType(Signature::Type t)
{
  char res[2] = { (char)t, 0};
  return Signature(res);
}

}

/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <cstring>

#include <qitype/signature.hpp>

namespace qi {

bool qi::Signature::isConvertibleTo(const qi::Signature& b) const
{
  if (size() != b.size())
    return false;
  static const char numeric[] = "bcCwWiIlLfd";
  static const char container[] = "[{(";
  Signature::iterator s = begin();
  Signature::iterator d = b.begin();
  for (;s!=end() && d!= b.end(); ++s,++d)
  {
    if (d.type() == Type_Dynamic)
      continue; // Dynamic can convert to whatever
    // Main switch on source sig
    if (strchr(numeric, s.type()))
    { // Numeric
      if (!strchr(numeric, d.type()))
        return false;
    }
    else if (strchr(container, s.type()))
    { // Container, list or map
      if (d.type() != s.type())
        return false; // Must be same container
      if (!s.children().isConvertibleTo(d.children()))
        return false; // Just check subtype compatibility
    }
    else
      if (d.type() != s.type())
        return false;
  }
  assert(s==end() && d==b.end()); // we allready exited on size mismatch
  return true;
}

Signature Signature::fromType(Signature::Type t)
{
  char res[2] = { (char)t, 0};
  return Signature(res);
}

}

Fix a lolbug, it never worked and returned true always.


#include "modem/commands.h"

namespace firebase {
namespace modem {

bool StreamCommand::execute(const String& command,
                            InputStream* in, OutputStream* out) {
  if (in == nullptr || out == nullptr) {
    return false;
  }

  if (command != "BEGIN_STREAM") {
    return false;
  }

  std::string path = in->readLine().c_str();
  std::unique_ptr<FirebaseStream> stream(fbase().streamPtr(path));

  if (stream->error()) {
    out->print("-FAIL ");
    out->println(stream->error().message().c_str());
    return false;
  }

  bool running = true;
  while(running) {
    if (stream->available()) {
      std::string json;
      FirebaseStream::Event event = stream->read(json);
      out->print("+");
      out->print(FirebaseStream::EventToName(event).c_str());
      out->print(" ");
      // TODO(edcoyne): add json parsing and get real path.
      out->println("/dummy/path");
      out->println(json.length());
      out->println(json.c_str());
    } else if (in->available()) {
      String command = in->readLine();
      if (command == "END_STREAM") {
        out->println("+OK");
        running = false;
      } else {
        out->println("-FAIL Cannot call any command but END_STREAM.");
      }
    }
  }

  return true;
}

}  // modem
}  // firebase

#include "modem/commands.h"

namespace firebase {
namespace modem {

bool StreamCommand::execute(const String& command,
                            InputStream* in, OutputStream* out) {
  if (in == nullptr || out == nullptr) {
    return false;
  }

  if (command != "BEGIN_STREAM") {
    return false;
  }

  std::string path = in->readLine().c_str();
  std::unique_ptr<FirebaseStream> stream(fbase().streamPtr(path));

  if (stream->error()) {
    out->print("-FAIL ");
    out->println(stream->error().message().c_str());
    return false;
  }

  bool running = true;
  DynamicJsonBuffer buffer;
  while(running) {
    if (stream->available()) {
      std::string json;
      FirebaseStream::Event event = stream->read(json);
      out->print("+");
      out->print(FirebaseStream::EventToName(event).c_str());
      out->print(" ");
      const auto& object = buffer.parseObject(json.c_str());
      String data = object["data"];
      out->println(object["path"].asString());
      out->println(data.length());
      out->println(data);
    } else if (in->available()) {
      String command = in->readLine();
      if (command == "END_STREAM") {
        out->println("+OK");
        running = false;
      } else {
        out->println("-FAIL Cannot call any command but END_STREAM.");
      }
    }
  }

  return true;
}

}  // modem
}  // firebase

Add json parsing to modem streaming


#include "helpers.h"

using namespace std;

void sendFail(UserHandler * handler, int errorcode, string topic, string message){
    JsonDict answer;

    JsonBool b = JsonBool(false);
    JsonString s = JsonString(message);
    answer.add("success", &b);
    answer.add("reason", &s);
    handler->writeToClient(topic, &answer);
}

#include "helpers.h"

using namespace std;

void sendFail(UserHandler * handler, int errorcode, string topic, string message){
    JsonDict answer;

    JsonBool b = JsonBool(false);
    JsonString s = JsonString(message);
    JsonInt i = JsonInt(errorcode);
    answer.add("success", &b);
    answer.add("reason", &s);
    answer.add("code", &i);
    handler->writeToClient(topic, &answer);
}

Add an error code with sendFail


#include "python_script.h"

#include <cstdio>
#include <fstream>
#include <iterator>

#include <boost/log/trivial.hpp>

#include <boost/python.hpp>
#include <Python.h>

using namespace boost::python;
using namespace std;
using namespace swganh::scripting;

PythonScript::PythonScript(const string& filename)
        : filename_(filename)
{
    ReadFileContents();

    Py_Initialize();

	try
    {
		boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed(
			PyImport_AddModule("__main__")
		)));

        globals_ = main.attr("__dict__");
        globals_["swganh"] = boost::python::import("py_swganh");
		globals_["context"] = dict();
    }
    catch (error_already_set &)
    {
        PyErr_Print();
    }
}

void PythonScript::Run()
{
	try
    {
#ifdef _DEBUG
        ReadFileContents();
#endif
		file_object_ = exec(filecontents_.c_str(), globals_, globals_);
    }
    catch (error_already_set &)
    {
        PyErr_Print();
    }
}

void PythonScript::ReadFileContents()
{
    ifstream filestream(filename_);
    filestream >> noskipws;

    filecontents_ = string(
        (istreambuf_iterator<char>(filestream)),
        istreambuf_iterator<char>());
}

#include "python_script.h"

#include <cstdio>
#include <fstream>
#include <iterator>

#include <boost/log/trivial.hpp>

#include <boost/python.hpp>
#include <Python.h>

using namespace boost::python;
using namespace std;
using namespace swganh::scripting;

PythonScript::PythonScript(const string& filename)
        : filename_(filename)
{
    ReadFileContents();

    Py_Initialize();

	try
    {
        PyRun_SimpleString("import sys; sys.path.append('.');");

		boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed(
			PyImport_AddModule("__main__")
		)));

        globals_ = main.attr("__dict__");
        globals_["swganh"] = boost::python::import("py_swganh");
		globals_["context"] = dict();
    }
    catch (error_already_set &)
    {
        PyErr_Print();
    }
}

void PythonScript::Run()
{
	try
    {
#ifdef _DEBUG
        ReadFileContents();
#endif
        BOOST_LOG_TRIVIAL(info) << "Executing script: " << filename_;
		file_object_ = exec(filecontents_.c_str(), globals_, globals_);
    }
    catch (error_already_set &)
    {
        PyErr_Print();
    }
}

void PythonScript::ReadFileContents()
{
    ifstream filestream(filename_);
    filestream >> noskipws;

    filecontents_ = string(
        (istreambuf_iterator<char>(filestream)),
        istreambuf_iterator<char>());
}

Add the current directory to the path.


#include "UIUtils.h"

#include <sstream>

#include "Settings.h"

std::vector<CPropertyPage *> UIUtils::pages = { };

CString UIUtils::Capitalize(std::wstring in) {
    CString cstr(in.c_str());
    return UIUtils::Capitalize(cstr);
}

CString UIUtils::Capitalize(CString in) {
    CString newString(in);
    CString firstLetter = newString.Left(1).MakeUpper();
    newString = firstLetter + newString.Mid(1);
    return newString;
}

int UIUtils::TextToInt(CWnd &wnd) {
    int num;
    CString text;
    wnd.GetWindowTextW(text);
    std::wistringstream wistr((LPCWSTR) text);
    wistr >> num;
    return num;
}

void UIUtils::SaveSettings(CPropertyPage &page) {
    HWND hWnd = NULL;
    for (CPropertyPage *page : pages) {
        HWND test = page->m_hWnd;
        if (IsWindow(test)) {
            hWnd = test;
        }
    }

    if (hWnd == page.m_hWnd) {
        OutputDebugString(L"Saving Settings XML\n");
        Settings::Instance()->Save();
    }
}

Add method to determine if the given prop page should save the settings


/* For symbol_thingey */
#define BOOST_CHRONO_VERSION 2
#include <boost/chrono/chrono.hpp>
#include <boost/chrono/chrono_io.hpp>

#define FUTURE_TRACE 0

#include <cps/future.h>
#include <iostream>

using namespace cps;

int
main(void)
{
	auto start = boost::chrono::high_resolution_clock::now();
	const int count = 100000;
	for(int i = 0; i < count; ++i) {
		auto f = future<std::string>::create_shared();
		auto expected = "happy";
		f->on_done([expected](const std::string &v) {
			// return future<std::string>::create_shared()->done("very happy");
		})->done(expected);
		// BOOST_CHECK(seq->as<std::string>()->get() == "very happy");
	}
	auto elapsed = boost::chrono::high_resolution_clock::now() - start;
	std::cout << "Average iteration: " << boost::chrono::symbol_format << (elapsed / (float)count) << std::endl;
	return 0;
}

/* For symbol_thingey */
#include <chrono>

#define FUTURE_TRACE 0
#include <cps/future.h>
#include <iostream>

using namespace cps;

int
main(void)
{
	auto start = std::chrono::high_resolution_clock::now();
	const int count = 100000;
	for(int i = 0; i < count; ++i) {
		auto f = future<std::string>::create_shared();
		auto expected = "happy";
		f->on_done([expected](const std::string &v) {
			// return future<std::string>::create_shared()->done("very happy");
		})->done(expected);
		// BOOST_CHECK(seq->as<std::string>()->get() == "very happy");
	}
	auto elapsed = std::chrono::high_resolution_clock::now() - start;
	std::cout
		<< "Average iteration: "
		<< (std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count() / (float)count)
		<< " ns"
		<< std::endl;
	return 0;
}

Use std::chrono, to cleanse last vestiges of boost


//===- llvm/System/AIX/Path.cpp - AIX Path Implementation -------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides the AIX specific implementation of the Path class.
//
//===----------------------------------------------------------------------===//

//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only AIX specific code
//===          and must not be generic UNIX code (see ../Unix/Path.cpp)
//===----------------------------------------------------------------------===//

// Include the generic unix implementation
#include "../Unix/Path.cpp"

namespace llvm {
using namespace sys;

bool
Path::is_valid() const {
  if (path.empty())
    return false;
  if (path.length() >= MAXPATHLEN)
    return false;
  return true;
}

}

// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab

//===- llvm/System/AIX/Path.cpp - AIX Path Implementation -------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides the AIX specific implementation of the Path class.
//
//===----------------------------------------------------------------------===//

// Include the generic unix implementation
#include "../Unix/Path.cpp"

namespace llvm {
using namespace sys;

//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only AIX specific code
//===          and must not be generic UNIX code (see ../Unix/Path.cpp)
//===----------------------------------------------------------------------===//

bool
Path::is_valid() const {
  if (path.empty())
    return false;
  if (path.length() >= MAXPATHLEN)
    return false;
  return true;
}

}

// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab

Move a warning comment to where it should have been in the first place.


#include "s3d/cv/image_operation/input_output_adapter.h"

#include "s3d/cv/image_operation/image_operations.h"

namespace s3d {
namespace image_operation {

InputOutputAdapter::InputOutputAdapter(gsl::not_null<ImageOperations*> imageOperations)
  : operations_{imageOperations} {}

void InputOutputAdapter::setInputImages(const cv::Mat& leftImage, const cv::Mat& rightImage) {
  inputLeftImage = leftImage.clone();
  inputRightImage = rightImage.clone();
}

std::tuple<cv::Mat&, cv::Mat&> InputOutputAdapter::getOutputImages() {
  return { outputLeftImage, outputRightImage };
};

bool InputOutputAdapter::applyAllOperations() {
  copyInputToOutputs();
  if (!canApplyOperations()) {
    return false;
  }
  return operations_->applyAll(&outputLeftImage, &outputRightImage);
}

void InputOutputAdapter::copyInputToOutputs() {
  outputLeftImage = inputLeftImage.clone();
  outputRightImage = inputRightImage.clone();
}

bool InputOutputAdapter::canApplyOperations() {
  return !inputLeftImage.empty() && !inputRightImage.empty();
}

} // namespace s3d
} // namespace image_operation

#include "s3d/cv/image_operation/input_output_adapter.h"

#include "s3d/cv/image_operation/image_operations.h"

namespace s3d {
namespace image_operation {

InputOutputAdapter::InputOutputAdapter(gsl::not_null<ImageOperations*> imageOperations)
  : operations_{imageOperations} {}

void InputOutputAdapter::setInputImages(const cv::Mat& leftImage, const cv::Mat& rightImage) {
  inputLeftImage = leftImage.clone();
  inputRightImage = rightImage.clone();
}

std::tuple<cv::Mat&, cv::Mat&> InputOutputAdapter::getOutputImages() {
  return std::tuple<cv::Mat&, cv::Mat&>(outputLeftImage, outputRightImage);
};

bool InputOutputAdapter::applyAllOperations() {
  copyInputToOutputs();
  if (!canApplyOperations()) {
    return false;
  }
  return operations_->applyAll(&outputLeftImage, &outputRightImage);
}

void InputOutputAdapter::copyInputToOutputs() {
  outputLeftImage = inputLeftImage.clone();
  outputRightImage = inputRightImage.clone();
}

bool InputOutputAdapter::canApplyOperations() {
  return !inputLeftImage.empty() && !inputRightImage.empty();
}

} // namespace s3d
} // namespace image_operation

Fix ubuntu build fail tuple init list


#ifdef HAVE_XIMGPROC

#include "ximgproc.h"
#include "SuperpixelSEEDS.h"
#include "SuperpixelSLIC.h"
#include "SuperpixelLSC.h"

NAN_MODULE_INIT(XImgproc::Init) {
	SuperpixelSEEDS::Init(target);
	SuperpixelSLIC::Init(target);
	SuperpixelLSC::Init(target);
}

#endif // HAVE_XIMGPROC

#ifdef HAVE_XIMGPROC

#include "ximgproc.h"
#include "SuperpixelSEEDS.h"
#include "SuperpixelSLIC.h"
#include "SuperpixelLSC.h"

NAN_MODULE_INIT(XImgproc::Init) {
	SuperpixelSEEDS::Init(target);
#if OPENCV_MINOR_VERSION > 0
	SuperpixelSLIC::Init(target);
	SuperpixelLSC::Init(target);
#endif
}

#endif // HAVE_XIMGPROC

Check for opencv version before using SuperpixelLSC/SLIC


// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.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 "input_sanitizer.h"

#include <regex>

namespace influxdb {
    namespace utility {
        constexpr const char* regex = R"((^[a-zA-Z0-9_\-]+$|"(?:[^\\"]|\\.)+"))";

        const std::regex check_identifier(regex);

        bool valid_identifier(std::string const & input)
        {
            return std::regex_match(input, check_identifier);
        }

        void throw_on_invalid_identifier(std::string const & input)
        {
            if (!valid_identifier(input))
                throw std::runtime_error(std::string("Invalid identifier: ") + input);
        }
    }

}

// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.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 "input_sanitizer.h"

#include <regex>

namespace influxdb {
    namespace utility {
        constexpr const char* regex = R"((^[a-zA-Z0-9_/\\.\-]+$|"(?:[^\\"]|\\.)+"))";

        const std::regex check_identifier(regex);

        bool valid_identifier(std::string const & input)
        {
            return std::regex_match(input, check_identifier);
        }

        void throw_on_invalid_identifier(std::string const & input)
        {
            if (!valid_identifier(input))
                throw std::runtime_error(std::string("Invalid identifier: ") + input);
        }
    }

}

Allow dot and slash as message identifier


#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/Twist.h"

int main(int argc, char **argv)
{

  ros::init(argc, argv, "publish_fromfile");

  ros::NodeHandle pubFromFileHandle;

  ros::Publisher pubFromFileObj = pubFromFileHandle.advertise<geometry_msgs::Twist>("publish_fromfile",100);

  /*!
   * TODO: make this configurable by command line arg
   */
  ros::Rate sendRate(10);

  while(ros::ok())
  {
    geometry_msgs::Twist currentOutputMsg;
    currentOutputMsg.linear.x=0.0;
    currentOutputMsg.angular.z=0.0;

    pubFromFileObj.publish(currentOutputMsg);

    ros::spinOnce();
    sendRate.sleep();
  }

  return 0;
}

// ROS includes
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "ros/console.h"
#include "std_msgs/String.h"

// misc includes
#include "yaml-cpp/yaml.h"

int main(int argc, char **argv)
{

  // local variables for configurable params
  double rate_param;
  int msg_buffer_len=100;
  std::string topic_name("publish_fromfile");
  std::string input_file; // TODO: implement
  // local variables for local scope use
  const std::string node_name("publish_fromfile");

  // initialize ROS
  ros::init(argc, argv, node_name);
  // make sure to create the node handle with the node_name used to initialize
  // (so that param relative scope works)
  ros::NodeHandle pubFromFileHandle(node_name);
  pubFromFileHandle.param("rate",rate_param,1.0);
  ROS_INFO_STREAM("/" << node_name << "/rate value set " << rate_param);
  pubFromFileHandle.param<std::string>("topic_name",topic_name,"publish_fromfile");
  ROS_INFO_STREAM("/" << node_name << "/topic_name value set " << topic_name);
  pubFromFileHandle.param("msg_buffer_len",msg_buffer_len,msg_buffer_len);
  ROS_INFO_STREAM("/" << node_name << "/msg_buffer_len value set " << msg_buffer_len);

  ros::Publisher pubFromFileObj = pubFromFileHandle.advertise<geometry_msgs::Twist>(topic_name,msg_buffer_len);

  ros::Rate sendRate(rate_param);

  while(ros::ok())
  {
    geometry_msgs::Twist currentOutputMsg;
    currentOutputMsg.linear.x=0.0;
    currentOutputMsg.angular.z=0.0;

    pubFromFileObj.publish(currentOutputMsg);

    ros::spinOnce();
    sendRate.sleep();
  }

  return 0;
}

Add ros console logging, implement params for ROS properties


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 "Version.hpp"

#include "CacheImpl.hpp"

namespace apache {
namespace geode {
namespace client {

int8_t Version::m_ordinal = 90;  // Geode 1.7.0

}  // namespace client
}  // namespace geode
}  // namespace apache

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 "Version.hpp"

#include "CacheImpl.hpp"

namespace apache {
namespace geode {
namespace client {

int8_t Version::m_ordinal = 45;  // Geode 1.0.0

}  // namespace client
}  // namespace geode
}  // namespace apache

Revert "GEODE-5968: move protocol to the last release of Geode"


/**
	Responsible for creating and destroying the mentat reference

*/
#include "d2tmh.h"

cMentatFactory::cMentatFactory() {
	type = -1;
}

void cMentatFactory::deleteCurrent() {
	switch (type) {
		case ATREIDES:
			delete (cAtreidesMentat *)Mentat;
			break;
		case HARKONNEN:
			delete (cAtreidesMentat *)Mentat;
			break;
		case ORDOS:
			delete (cAtreidesMentat *)Mentat;
			break;
		case BENEGES:
			delete (cAtreidesMentat *)Mentat;
			break;
	}
}

void cMentatFactory::create(int mentatType) {
	if (type > -1) {
		if (mentatType != type) {
			deleteCurrent();
		}
	}
	/** It is safe to create a new Mentat now **/
	switch (mentatType) {
		case ATREIDES:
			Mentat = new cAtreidesMentat;
			break;
		case HARKONNEN:
			Mentat = new cHarkonnenMentat;
			break;
		case ORDOS:
			Mentat = new cOrdosMentat;
			break;
		case BENEGES:
			Mentat = new cBenegesMentat;
			break;
	}
	type = mentatType;
}

/**
	Responsible for creating and destroying the mentat reference

*/
#include "d2tmh.h"

cMentatFactory::cMentatFactory() {
	type = -1;
}

void cMentatFactory::deleteCurrent() {
	switch (type) {
		case ATREIDES:
			delete (cAtreidesMentat *)Mentat;
			break;
		case HARKONNEN:
			delete (cHarkonnenMentat *)Mentat;
			break;
		case ORDOS:
			delete (cOrdosMentat *)Mentat;
			break;
		case BENEGES:
			delete (cBenegesMentat *)Mentat;
			break;
	}
}

void cMentatFactory::create(int mentatType) {
	if (type > -1) {
		if (mentatType != type) {
			deleteCurrent();
		}
	}
	/** It is safe to create a new Mentat now **/
	switch (mentatType) {
		case ATREIDES:
			Mentat = new cAtreidesMentat;
			break;
		case HARKONNEN:
			Mentat = new cHarkonnenMentat;
			break;
		case ORDOS:
			Mentat = new cOrdosMentat;
			break;
		case BENEGES:
			Mentat = new cBenegesMentat;
			break;
	}
	type = mentatType;
}

Fix deletion of Mentats in MentatFactory


#include "ShaderProgram.hpp"

#include "Shader.hpp"

ShaderProgram::ShaderProgram(std::initializer_list<const Shader*> shaders) {
	shaderProgram = glCreateProgram();

	for (auto shader : shaders)
		glAttachShader(shaderProgram, shader->GetShaderID());

	glLinkProgram(shaderProgram);
}

ShaderProgram::~ShaderProgram() {
	glDeleteProgram(shaderProgram);
}

void ShaderProgram::Use() const {
	glUseProgram(shaderProgram);
}

GLuint ShaderProgram::GetAttributeLocation(const char* name) const {
	return glGetAttribLocation(shaderProgram, name);
}

GLuint ShaderProgram::GetUniformLocation(const char* name) const {
	return glGetUniformLocation(shaderProgram, name);
}

#include "ShaderProgram.hpp"

#include "Shader.hpp"

ShaderProgram::ShaderProgram(std::initializer_list<const Shader*> shaders) {
	shaderProgram = glCreateProgram();

	for (const Shader* shader : shaders)
		glAttachShader(shaderProgram, shader->GetShaderID());

	glLinkProgram(shaderProgram);

    for (const Shader* shader : shaders)
        glDetachShader(shaderProgram, shader->GetShaderID());
}

ShaderProgram::~ShaderProgram() {
	glDeleteProgram(shaderProgram);
}

void ShaderProgram::Use() const {
	glUseProgram(shaderProgram);
}

GLuint ShaderProgram::GetAttributeLocation(const char* name) const {
	return glGetAttribLocation(shaderProgram, name);
}

GLuint ShaderProgram::GetUniformLocation(const char* name) const {
	return glGetUniformLocation(shaderProgram, name);
}

Detach shaders after linking shader program.


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

#include "testing/embedder_test.h"
#include "testing/gtest/include/gtest/gtest.h"

class FPDFParserEmbeddertest : public EmbedderTest {
};

TEST_F(FPDFParserEmbeddertest, LoadError_454695) {
  // Test trailer dictionary with $$ze instead of Size.
  EXPECT_TRUE(OpenDocument("testing/resources/bug_454695.pdf"));
}

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

#include "../../../testing/embedder_test.h"
#include "testing/gtest/include/gtest/gtest.h"

class FPDFParserEmbeddertest : public EmbedderTest {
};

TEST_F(FPDFParserEmbeddertest, LoadError_454695) {
  // Test trailer dictionary with $$ze instead of Size.
  EXPECT_TRUE(OpenDocument("testing/resources/bug_454695.pdf"));
}

Update the path of header file to avoid a compiling error in chrome


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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  dialog->ShowModalDialog();
  active_dialog_ = dialog;
}

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

#include "chrome/browser/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  // Set active_dialog_ before showing it, because ShowModalDialog can wind up
  // calling ShowNextDialog in some cases, which will change active_dialog_.
  active_dialog_ = dialog;
  dialog->ShowModalDialog();
}

Set active_dialog_ before showing it, since showing a dialog can sometimes actually move to the next one in the queue instead.


#include "AutonomousCommandGroup.h"
#include "../RobotMap.h"

AutonomousCommandGroup::AutonomousCommandGroup()
{

}

#include "AutonomousCommandGroup.h"

#include "RaiseContainer.h"
#include "DownContainer.h"
#include "RaiseTrash.h"
#include "DownTrash.h"
#include "MoveContainer.h"
#include "../RobotMap.h"

AutonomousCommandGroup::AutonomousCommandGroup()
{
	AddSequential(new RaiseTrash());
	AddSequential(new DownTrash());
	AddSequential(new RaiseContainer());
	AddSequential(new MoveContainer());
	AddSequential(new DownContainer());
}

Set order of Autonomous Commands in CommandGroup


// Copyright (c) 2012-2013, the scalloc Project Authors.  All rights reserved.
// Please see the AUTHORS file for details.  Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.

#include "allocators/global_sbrk_allocator.h"

#include <sys/mman.h>  // mmap

#include "log.h"

uintptr_t GlobalSbrkAllocator::current_;

void GlobalSbrkAllocator::InitModule() {
  size_t size = 1UL << 35;  // 32GiB
  void* p = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (p == MAP_FAILED) {
    ErrorOut("mmap failed");
  }
  current_ = reinterpret_cast<uintptr_t>(p);
}

// Copyright (c) 2012-2013, the scalloc Project Authors.  All rights reserved.
// Please see the AUTHORS file for details.  Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.

#include "allocators/global_sbrk_allocator.h"

#include <sys/mman.h>  // mmap

#include "log.h"

uintptr_t GlobalSbrkAllocator::current_;

void GlobalSbrkAllocator::InitModule() {
#ifdef __x86_64__
  size_t size = 1UL << 35;  // 32GiB
#endif
#ifdef __i386__
  size_t size = 1UL << 31;
#endif

  void* p = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (p == MAP_FAILED) {
    ErrorOut("mmap failed");
  }
  current_ = reinterpret_cast<uintptr_t>(p);
}

Add large sbrk support for 32 bit platforms.


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

#include "vm/version.h"

#include "vm/cpu.h"
#include "vm/os.h"

namespace dart {

// TODO(iposva): Avoid racy initialization.
static const char* formatted_version = NULL;

const char* Version::String() {
  if (formatted_version == NULL) {
    const char* os = OS::Name();
    const char* arch = CPU::Id();
    formatted_version = OS::SCreate(NULL, "%s on \"%s_%s\"", str_, os, arch);
  }
  return formatted_version;
}

const char* Version::SnapshotString() {
  return snapshot_hash_;
}

const char* Version::CommitString() {
  return commit_;
}

const char* Version::SdkHash() {
  return git_short_hash_;
}

const char* Version::snapshot_hash_ = "{{SNAPSHOT_HASH}}";
const char* Version::str_ = "{{VERSION_STR}} ({{CHANNEL}}) ({{COMMIT_TIME}})";
const char* Version::commit_ = "{{VERSION_STR}}";
const char* Version::git_short_hash_ = "{{GIT_HASH}}";

}  // namespace dart

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

#include "platform/atomic.h"

#include "vm/cpu.h"
#include "vm/os.h"
#include "vm/version.h"

namespace dart {

// We use require-release semantics to ensure initializing stores to the string
// are visible when the string becomes visible.
static AcqRelAtomic<const char*> formatted_version = nullptr;

const char* Version::String() {
  if (formatted_version.load() == nullptr) {
    const char* os = OS::Name();
    const char* arch = CPU::Id();
    char* version_string =
        OS::SCreate(nullptr, "%s on \"%s_%s\"", str_, os, arch);
    const char* expect_old_is_null = nullptr;
    if (!formatted_version.compare_exchange_strong(expect_old_is_null,
                                                   version_string)) {
      free(version_string);
    }
  }
  return formatted_version.load();
}

const char* Version::SnapshotString() {
  return snapshot_hash_;
}

const char* Version::CommitString() {
  return commit_;
}

const char* Version::SdkHash() {
  return git_short_hash_;
}

const char* Version::snapshot_hash_ = "{{SNAPSHOT_HASH}}";
const char* Version::str_ = "{{VERSION_STR}} ({{CHANNEL}}) ({{COMMIT_TIME}})";
const char* Version::commit_ = "{{VERSION_STR}}";
const char* Version::git_short_hash_ = "{{GIT_HASH}}";

}  // namespace dart

Use atomic to avoid racy version string initialization


// Test for disabling LSan at link-time.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: %env_lsan_opts=$LSAN_BASE %run %t
// RUN: %env_lsan_opts=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s

#include <sanitizer/lsan_interface.h>

int argc_copy;

extern "C" {
int __attribute__((used)) __lsan_is_turned_off() {
  return (argc_copy == 1);
}
}

int main(int argc, char *argv[]) {
  volatile int *x = new int;
  *x = 42;
  argc_copy = argc;
  return 0;
}

// CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer: 4 byte(s) leaked in 1 allocation(s)

// Test for disabling LSan at link-time.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: %env_lsan_opts=$LSAN_BASE %run %t
// RUN: %env_lsan_opts=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s
//
// UNSUPPORTED: darwin

#include <sanitizer/lsan_interface.h>

int argc_copy;

extern "C" {
int __attribute__((used)) __lsan_is_turned_off() {
  return (argc_copy == 1);
}
}

int main(int argc, char *argv[]) {
  volatile int *x = new int;
  *x = 42;
  argc_copy = argc;
  return 0;
}

// CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer: 4 byte(s) leaked in 1 allocation(s)

Revert "Prevent DCE on __lsan_is_turned_off and re-enable test case"


#include "MicroBit.h"

extern "C" {
    void mp_run(void);

    void microbit_display_event(void);
}

static void event_listener(MicroBitEvent evt) {
    if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) {
        microbit_display_event();
    }
}

void app_main() {
    /*
    // debugging: print memory layout
    extern uint32_t __data_start__, __data_end__;
    extern uint32_t __bss_start__, __bss_end__;
    extern uint32_t __HeapLimit, __StackLimit, __StackTop;
    printf("__data_start__ = %p\r\n", &__data_start__);
    printf("__data_end__   = %p\r\n", &__data_end__);
    printf("__bss_start_ _ = %p\r\n", &__bss_start__);
    printf("__bss_end__    = %p\r\n", &__bss_end__);
    printf("__HeapLimit    = %p\r\n", &__HeapLimit);
    printf("__StackLimit   = %p\r\n", &__StackLimit);
    printf("__StackTop     = %p\r\n", &__StackTop);
    */

    uBit.MessageBus.listen(MICROBIT_ID_DISPLAY,
        MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener);
    while (1) {
        mp_run();
    }
}

#include "MicroBit.h"

extern "C" {
    void mp_run(void);

    void microbit_display_event(void);
}

static void event_listener(MicroBitEvent evt) {
    if (evt.value == MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE) {
        microbit_display_event();
    }
}

void app_main() {
    /*
    // debugging: print memory layout
    extern uint32_t __data_start__, __data_end__;
    extern uint32_t __bss_start__, __bss_end__;
    extern uint32_t __HeapLimit, __StackLimit, __StackTop;
    printf("__data_start__ = %p\r\n", &__data_start__);
    printf("__data_end__   = %p\r\n", &__data_end__);
    printf("__bss_start_ _ = %p\r\n", &__bss_start__);
    printf("__bss_end__    = %p\r\n", &__bss_end__);
    printf("__HeapLimit    = %p\r\n", &__HeapLimit);
    printf("__StackLimit   = %p\r\n", &__StackLimit);
    printf("__StackTop     = %p\r\n", &__StackTop);
    */

    currentFiber->flags |= MICROBIT_FIBER_FLAG_DO_NOT_PAGE;

    uBit.MessageBus.listen(MICROBIT_ID_DISPLAY,
        MICROBIT_DISPLAY_EVT_ANIMATION_COMPLETE, event_listener,
        MESSAGE_BUS_LISTENER_REENTRANT | MESSAGE_BUS_LISTENER_NONBLOCKING);

    while (1) {
        mp_run();
    }
}

Update to use new DAL feature where stack is not paged.


#include <bts/blockchain/address.hpp>
#include <bts/blockchain/pts_address.hpp>
#include <bts/blockchain/types.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/filesystem.hpp>
#include <fc/variant_object.hpp>
#include <fc/exception/exception.hpp>

#include <iostream>

using namespace bts::blockchain;

int main( int argc, char** argv )
{

    if( argc == 2 )
    {
        fc::ecc::private_key k;
        try{
            auto key = bts::blockchain::public_key_type(std::string(argv[1]));
            auto obj = fc::mutable_variant_object();

            obj["public_key"] = public_key_type(key);
            obj["native_address"] = bts::blockchain::address(key);
            obj["pts_address"] = bts::blockchain::pts_address(key);

            std::cout << fc::json::to_pretty_string(obj);
            return 0;

        } catch (fc::exception e) {
            std::cout << e.to_detail_string();
        }
    }
    return -1;
}

#include <bts/blockchain/address.hpp>
#include <bts/blockchain/pts_address.hpp>
#include <bts/blockchain/types.hpp>
#include <bts/utilities/key_conversion.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/filesystem.hpp>
#include <fc/variant_object.hpp>
#include <fc/exception/exception.hpp>

#include <iostream>

using namespace bts::blockchain;

int main( int argc, char** argv )
{
    if( argc == 2 )
    {
        try
        {
            bts::blockchain::public_key_type key(argv[1]);
            fc::mutable_variant_object obj;

            obj["public_key"] = key;
            obj["native_address"] = bts::blockchain::address((fc::ecc::public_key_data)key);
            obj["pts_address"] = bts::blockchain::pts_address((fc::ecc::public_key)key);

            std::cout << fc::json::to_pretty_string(obj);
            return 0;

        }
        catch (fc::exception e)
        {
            std::cout << e.to_detail_string();
        }
    }
    return -1;
}

Fix compile errors on win32, update Qt submodule to fix compile errors there