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

#include "crypto/ec_signature_creator.h"

#include "base/logging.h"

namespace crypto {

// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
  NOTIMPLEMENTED();
  return NULL;
}

ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key,
                                       HASH_HashType hash_type)
    : key_(key),
      hash_type_(hash_type) {
  NOTIMPLEMENTED();
}

ECSignatureCreator::~ECSignatureCreator() { }

bool ECSignatureCreator::Sign(const uint8* data,
                              int data_len,
                              std::vector<uint8>* signature) {
  NOTIMPLEMENTED();
  return false;
}

}  // namespace crypto

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

#include "crypto/ec_signature_creator.h"

#include "base/logging.h"

namespace crypto {

// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
  NOTIMPLEMENTED();
  return NULL;
}

ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key)
    : key_(key) {
  NOTIMPLEMENTED();
}

ECSignatureCreator::~ECSignatureCreator() { }

bool ECSignatureCreator::Sign(const uint8* data,
                              int data_len,
                              std::vector<uint8>* signature) {
  NOTIMPLEMENTED();
  return false;
}

}  // namespace crypto

Remove wrong parameter from ECSignatureCreator's constructor in openssl implement.

The wrong parameter was unused and broke the linux redux build.

TBR=wtc
BUG=None.
TEST=Linux redux bot should be green.
Review URL: https://chromiumcodereview.appspot.com/9234024

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@119053 0039d316-1c4b-4281-b951-d872f2087c98


#include "../Coin.h"
#include "../Params.h"
#include "../../../streams.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(sigma_coin_tests)

BOOST_AUTO_TEST_CASE(pubcoin_serialization)
{
    secp_primitives::GroupElement coin;
    coin.randomize();

    sigma::PublicCoinV3 pubcoin(coin, sigma::ZQ_GOLDWASSER);

    CDataStream serialized(SER_NETWORK, PROTOCOL_VERSION);
    serialized << pubcoin;

    sigma::PublicCoinV3 deserialized;
    serialized >> deserialized;

    BOOST_CHECK(pubcoin == deserialized);
}

BOOST_AUTO_TEST_CASE(pubcoin_validate)
{
    auto params = sigma::ParamsV3::get_default();

    sigma::PrivateCoinV3 privcoin(params);
    auto& pubcoin = privcoin.getPublicCoin();

    BOOST_CHECK(pubcoin.validate());
}

BOOST_AUTO_TEST_SUITE_END()

#include "../Coin.h"
#include "../Params.h"
#include "../../../streams.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(sigma_coin_tests)

BOOST_AUTO_TEST_CASE(pubcoin_serialization)
{
    secp_primitives::GroupElement coin;
    coin.randomize();

    sigma::PublicCoinV3 pubcoin(coin, sigma::ZQ_GOLDWASSER);

    CDataStream serialized(SER_NETWORK, PROTOCOL_VERSION);
    serialized << pubcoin;

    sigma::PublicCoinV3 deserialized;
    serialized >> deserialized;

    BOOST_CHECK(pubcoin == deserialized);
}

BOOST_AUTO_TEST_CASE(pubcoin_validate)
{
    auto params = sigma::ParamsV3::get_default();

    sigma::PrivateCoinV3 privcoin(params);
    auto& pubcoin = privcoin.getPublicCoin();

    BOOST_CHECK(pubcoin.validate());
}

BOOST_AUTO_TEST_CASE(getter_setter_priv)
{
    auto params = sigma::ParamsV3::get_default();

    sigma::PrivateCoinV3 privcoin(params);
    sigma::PrivateCoinV3 new_privcoin(params);

    BOOST_CHECK(privcoin.getPublicCoin() != new_privcoin.getPublicCoin());
    BOOST_CHECK(privcoin.getSerialNumber() != new_privcoin.getSerialNumber());
    BOOST_CHECK(privcoin.getRandomness() != new_privcoin.getRandomness());
    BOOST_CHECK(privcoin.getVersion() == new_privcoin.getVersion());

    new_privcoin.setPublicCoin(privcoin.getPublicCoin());
    new_privcoin.setRandomness(privcoin.getRandomness());
    new_privcoin.setSerialNumber(privcoin.getSerialNumber());
    new_privcoin.setVersion(2);

    BOOST_CHECK(privcoin.getPublicCoin() == new_privcoin.getPublicCoin());
    BOOST_CHECK(privcoin.getSerialNumber() == new_privcoin.getSerialNumber());
    BOOST_CHECK(privcoin.getRandomness() == new_privcoin.getRandomness());
    BOOST_CHECK(new_privcoin.getVersion() == 2);
}

BOOST_AUTO_TEST_SUITE_END()

Add coin serialize deserialize priv coin


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

#include "os/posix/posix_hook.h"

#include <dlfcn.h>

void PosixHookInit()
{
}

bool PosixHookDetect(const char *identifier)
{
  return dlsym(RTLD_DEFAULT, identifier) != NULL;
}

void PosixHookLibrary(const char *name, dlopenCallback cb)
{
}

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

#include "os/posix/posix_hook.h"

#include <dlfcn.h>
#include <stddef.h>

void PosixHookInit()
{
}

bool PosixHookDetect(const char *identifier)
{
  return dlsym(RTLD_DEFAULT, identifier) != NULL;
}

void PosixHookLibrary(const char *name, dlopenCallback cb)
{
}

Apply same fix to apple

Apply same fix to apple


// ep1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <gtest\gtest.h>

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

// ep1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <memory>
#include <gtest\gtest.h>

using namespace std;

struct Foo {
	virtual int Plus(int left, int right)
	{
		return 2;
	}
};

struct Bar : public Foo {
	virtual int Plus(int left, short right)
	{
		return 4;
	}
};

TEST(Episode1, OverrideTest_CallParent)
{
	unique_ptr<Foo> op(new Foo());
	EXPECT_EQ(2, op->Plus(1, 1));
}

TEST(Episode1, OverrideTest_CallDerived)
{
	unique_ptr<Foo> op(new Bar());
	EXPECT_EQ(4, op->Plus(1, 1));
}

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

Add two tests to demo 'override' specifier.


// Copyright (c) 2012-2015 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 "compat/sanity.h"
#include "key.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(basic_sanity)
{
  BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test");
  BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test");
  BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test");
}

BOOST_AUTO_TEST_SUITE_END()

// Copyright (c) 2012-2015 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 "compat/sanity.h"
#include "key.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(basic_sanity)
{
  BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test");
  BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test");
  BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test");
  BOOST_CHECK_MESSAGE(init_and_check_sodium() == 0, "libsodium sanity test");
}

BOOST_AUTO_TEST_SUITE_END()

Add the sanity test for libsodium.

Add the sanity test for libsodium.

Tested:
./src/test/test_bitcoin --run_test=sanity_tests


/*
 * Unit tests for the checkerboard.
 * Author: Dino Wernli
 */

#include <gtest/gtest.h>

#include "scene/texture/checkerboard.h"
#include "test/test_util.h"

namespace {

static IntersectionData DataWithCoords(Scalar ss, Scalar tt) {
  Ray r(Point3(0, 0, 0), Vector3(0, 0, 1));
  IntersectionData data(r);
  data.texture_coordinate.s = ss;
  data.texture_coordinate.t = tt;
  return data;
}

TEST(Checkerboard, IsChanging) {
  Color3 blue(0, 0, 1);
  Color3 red(1, 0, 0);
  Checkerboard cb(blue, red);

  EXPECT_TRUE(TestUtil::ColorsEqual(blue, cb.Evaluate(DataWithCoords(0, 0))));
  EXPECT_TRUE(TestUtil::ColorsEqual(red, cb.Evaluate(DataWithCoords(0, 0.1))));
}

}

/*
 * Unit tests for the checkerboard.
 * Author: Dino Wernli
 */

#include <gtest/gtest.h>

#include "scene/texture/checkerboard.h"
#include "test/test_util.h"

namespace {

static IntersectionData DataWithCoords(Scalar ss, Scalar tt) {
  Ray r(Point3(0, 0, 0), Vector3(0, 0, 1));
  IntersectionData data(r);
  data.texture_coordinate.s = ss;
  data.texture_coordinate.t = tt;
  return data;
}

TEST(Checkerboard, IsChanging) {
  Color3 blue(0, 0, 1);
  Color3 red(1, 0, 0);
  Checkerboard cb(blue, red, 5 /* length */);

  EXPECT_TRUE(TestUtil::ColorsEqual(blue, cb.Evaluate(DataWithCoords(0, 0))));
  EXPECT_TRUE(TestUtil::ColorsEqual(red, cb.Evaluate(DataWithCoords(0, 0.1))));
}

}

Fix failing test due to missing checkerboard constructor param.


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"

using namespace autowiring;

// Index that will be given to the next auto_id instance.  Zero is reserved.
static int s_index = 1;

const auto_id_block auto_id_t<void>::s_block{
  0,
  &typeid(void),
  &typeid(s<void>),
  0,
  0,
  nullptr,
  nullptr
};

int autowiring::CreateIndex(void) {
  return s_index++;
}

std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
  return nullptr;
}

std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
  return nullptr;
}

// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "auto_id.h"

using namespace autowiring;

// Index that will be given to the next auto_id instance.  Zero is reserved.
static int s_index = 1;

const auto_id_block auto_id_t<void>::s_block{
  0,
  &typeid(void),
  &typeid(s<void>),
  0,
  0,
  nullptr,
  nullptr
};

const auto_id_t_init<void, true> auto_id_t_init<void, true>::init;
const auto_id_t_init<void, false> auto_id_t_init<void, false>::init;

int autowiring::CreateIndex(void) {
  return s_index++;
}

std::shared_ptr<CoreObject> auto_id_block::NullToObj(const std::shared_ptr<void>&) AUTO_NOEXCEPT
{
  return nullptr;
}

std::shared_ptr<void> auto_id_block::NullFromObj(const std::shared_ptr<CoreObject>&) AUTO_NOEXCEPT
{
  return nullptr;
}

Fix msvc14 64-bit release mode linker error

We declare but never explicitly define the void `init` blocks.  Somehow this still works on every other build configuration, but not VC2015 release mode.  Fix this.


#include "codearea.h"

#include <algorithm>

namespace openlocationcode {

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

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

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

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

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

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

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

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

} // namespace openlocationcode

#include "codearea.h"

#include <algorithm>

namespace openlocationcode {

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

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

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

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

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

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

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

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

} // namespace openlocationcode

Fix obsolete structure init in CodeArea::GetCenter()

Fix structure initialization syntax which is non-standard and "obsolete since GCC 2.5" (https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gcc/Designated-Inits.html). Just use the C99 style, as anything else doesn't work even with recent Microsoft compilers.


// Copyright 2013 The Flutter 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 "impeller/archivist/archivist_fixture.h"

#include "flutter/fml/paths.h"

namespace impeller {
namespace testing {

ArchivistFixture::ArchivistFixture() {
  std::stringstream stream;
  stream << flutter::testing::GetCurrentTestName() << ".db";
  archive_file_name_ = fml::paths::JoinPaths(
      {flutter::testing::GetFixturesPath(), stream.str()});
}

ArchivistFixture::~ArchivistFixture() = default;

const std::string ArchivistFixture::GetArchiveFileName() const {
  return archive_file_name_;
}

void ArchivistFixture::SetUp() {
  DeleteArchiveFile();
}

void ArchivistFixture::TearDown() {
  // TODO: Tear this down. For now, I am inspecting the files for readability of
  // schema.
  // DeleteArchiveFile();
}

void ArchivistFixture::DeleteArchiveFile() const {
  fml::UnlinkFile(archive_file_name_.c_str());
}

}  // namespace testing
}  // namespace impeller

// Copyright 2013 The Flutter 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 "impeller/archivist/archivist_fixture.h"

#include "flutter/fml/paths.h"

namespace impeller {
namespace testing {

ArchivistFixture::ArchivistFixture() {
  std::stringstream stream;
  stream << "Test" << flutter::testing::GetCurrentTestName() << ".db";
  archive_file_name_ = stream.str();
}

ArchivistFixture::~ArchivistFixture() = default;

const std::string ArchivistFixture::GetArchiveFileName() const {
  return fml::paths::JoinPaths(
      {flutter::testing::GetFixturesPath(), archive_file_name_});
}

void ArchivistFixture::SetUp() {
  DeleteArchiveFile();
}

void ArchivistFixture::TearDown() {
  DeleteArchiveFile();
}

void ArchivistFixture::DeleteArchiveFile() const {
  auto fixtures = flutter::testing::OpenFixturesDirectory();
  if (fml::FileExists(fixtures, archive_file_name_.c_str())) {
    fml::UnlinkFile(fixtures, archive_file_name_.c_str());
  }
}

}  // namespace testing
}  // namespace impeller

Fix temporary database file deletion.

Fix temporary database file deletion.


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

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

namespace extensions {

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

}  // namespace extensions

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

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

#include <mach/mach_host.h>

#include "base/mac/scoped_mach_port.h"

namespace extensions {

bool CpuInfoProvider::QueryCpuTimePerProcessor(std::vector<CpuTime>* times) {
  natural_t num_of_processors;
  base::mac::ScopedMachPort host(mach_host_self());
  mach_msg_type_number_t type;
  processor_cpu_load_info_data_t* cpu_infos;

  if (host_processor_info(host.get(),
                          PROCESSOR_CPU_LOAD_INFO,
                          &num_of_processors,
                          reinterpret_cast<processor_info_array_t*>(&cpu_infos),
                          &type) == KERN_SUCCESS) {
    std::vector<CpuTime> results;
    int64 user = 0, nice = 0, sys = 0, idle = 0;

    for (natural_t i = 0; i < num_of_processors; ++i) {
      CpuTime time;

      user = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_USER]);
      sys  = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_SYSTEM]);
      nice = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_NICE]);
      idle = static_cast<int64>(cpu_infos[i].cpu_ticks[CPU_STATE_IDLE]);

      time.kernel = sys;
      time.user = user + nice;
      time.idle = idle;
      results.push_back(time);
    }

    vm_deallocate(mach_task_self(),
                  reinterpret_cast<vm_address_t>(cpu_infos),
                  num_of_processors * sizeof(processor_cpu_load_info));

    times->swap(results);
    return true;
  }

  return false;
}

}  // namespace extensions

Add code to implement querying CPU time for each processor on Mac for systemInfo.cpu API.

BUG=136519
TEST=None

Review URL: https://chromiumcodereview.appspot.com/11233037

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@164863 0039d316-1c4b-4281-b951-d872f2087c98


// Copyright 2015 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 "skia/ext/opacity_filter_canvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkTLazy.h"

namespace skia {

OpacityFilterCanvas::OpacityFilterCanvas(SkCanvas* canvas,
                                         float opacity,
                                         bool disable_image_filtering)
    : INHERITED(canvas->imageInfo().width(), canvas->imageInfo().height()),
      alpha_(SkScalarRoundToInt(opacity * 255)),
      disable_image_filtering_(disable_image_filtering) {
  this->addCanvas(canvas);
}

void OpacityFilterCanvas::onFilterPaint(SkPaint* paint, Type) const {
  if (alpha_ < 255)
    paint->setAlpha(alpha_);

  if (disable_image_filtering_)
    paint->setFilterQuality(kNone_SkFilterQuality);
}

void OpacityFilterCanvas::onDrawPicture(const SkPicture* picture,
                                        const SkMatrix* matrix,
                                        const SkPaint* paint) {
  SkTLazy<SkPaint> filteredPaint;
  if (paint) {
    this->onFilterPaint(filteredPaint.set(*paint), kPicture_Type);
  }

  // Unfurl pictures in order to filter nested paints.
  this->SkCanvas::onDrawPicture(picture, matrix, filteredPaint.getMaybeNull());
}

}  // namespace skia

// Copyright 2015 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 "skia/ext/opacity_filter_canvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkTLazy.h"

namespace skia {

OpacityFilterCanvas::OpacityFilterCanvas(SkCanvas* canvas,
                                         float opacity,
                                         bool disable_image_filtering)
    : INHERITED(canvas),
      alpha_(SkScalarRoundToInt(opacity * 255)),
      disable_image_filtering_(disable_image_filtering) { }

void OpacityFilterCanvas::onFilterPaint(SkPaint* paint, Type) const {
  if (alpha_ < 255)
    paint->setAlpha(alpha_);

  if (disable_image_filtering_)
    paint->setFilterQuality(kNone_SkFilterQuality);
}

void OpacityFilterCanvas::onDrawPicture(const SkPicture* picture,
                                        const SkMatrix* matrix,
                                        const SkPaint* paint) {
  SkTLazy<SkPaint> filteredPaint;
  if (paint) {
    this->onFilterPaint(filteredPaint.set(*paint), kPicture_Type);
  }

  // Unfurl pictures in order to filter nested paints.
  this->SkCanvas::onDrawPicture(picture, matrix, filteredPaint.getMaybeNull());
}

}  // namespace skia

Use the canvas-based SkPaintFilterCanvas ctor in OpacityFilterCanvas

Using the new constructor ensures that the proxy canvas is correctly
initialized with the target canvas state.

BUG=516790
R=reed@google.com,robertphillips@google.com

Review URL: https://codereview.chromium.org/1287203004

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#343832}


#include "SliderKnob.h"

SliderKnob::SliderKnob(std::wstring bitmapName,
    int x, int y, int width, int height) :
Meter(bitmapName, x, y, 1),
_track(x, y, width, height) {
    _units = _track.Width - _rect.Width;
}

Gdiplus::Rect SliderKnob::Location() {
    return _rect;
}

void SliderKnob::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
    graphics->DrawImage(_bitmap, _rect,
        0, 0, _rect.Width, _track.Height, Gdiplus::UnitPixel);
}

void SliderKnob::Value(float value) {
    Meter::Value(value);
    X(_trackX + CalcUnits());
}

int SliderKnob::TrackX() const {
    return _trackX;
}

int SliderKnob::TrackY() const {
    return _trackY;
}

int SliderKnob::TrackWidth() const {
    return _trackWidth;
}

int SliderKnob::TrackHeight() const {
    return _trackHeight;
}

int SliderKnob::X() const {
    return Meter::X();
}

int SliderKnob::Y() const {
    return Meter::Y();
}

void SliderKnob::X(int x) {
    _rect.X = x;
}

void SliderKnob::Y(int y) {
    _rect.Y = y;
}

#include "SliderKnob.h"

SliderKnob::SliderKnob(std::wstring bitmapName,
    int x, int y, int width, int height) :
Meter(bitmapName, x, y, 1),
_track(x, y, width, height) {
    _units = _track.Width - _rect.Width;
}

Gdiplus::Rect SliderKnob::Location() {
    return _rect;
}

void SliderKnob::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
    graphics->DrawImage(_bitmap, _rect,
        0, 0, _rect.Width, _track.Height, Gdiplus::UnitPixel);
}

void SliderKnob::Value(float value) {
    Meter::Value(value);
    X(TrackX() + CalcUnits());
}

int SliderKnob::TrackX() const {
    return _track.X;
}

int SliderKnob::TrackY() const {
    return _track.Y;
}

int SliderKnob::TrackWidth() const {
    return _track.Width;
}

int SliderKnob::TrackHeight() const {
    return _track.Height;
}

int SliderKnob::X() const {
    return _rect.X;
}

int SliderKnob::Y() const {
    return _rect.Y;
}

void SliderKnob::X(int x) {
    _rect.X = x;
}

void SliderKnob::Y(int y) {
    _rect.Y = y;
}

int SliderKnob::Width() const {
    return _rect.Width;
}

int SliderKnob::Height() const {
    return _rect.Height;
}

Update for new rect tracking

Update for new rect tracking


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

  MYPROJECT: A software package for whatever.

  Copyright (c) University College London (UCL). All rights reserved.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.

  See LICENSE.txt in the top level directory for details.

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

#include <mpMyFunctions.h>
#include <iostream>

#ifdef BUILD_Eigen
#include <Eigen/Dense>
#endif

#ifdef BUILD_Boost
#include <boost/math/special_functions/round.hpp>
#endif

#ifdef BUILD_OpenCV
#include <cv.h>
#endif

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

#ifdef BUILD_Eigen
  Eigen::MatrixXd m(2,2);
  std::cout << "Printing 2x2 matrix ..." << m << std::endl;
#endif

#ifdef BUILD_Boost
  std::cout << "Rounding to ... " << boost::math::round(0.123) << std::endl;
#endif

#ifdef BUILD_OpenCV
  cv::Matx44d matrix = cv::Matx44d::eye();
  std::cout << "Printing 4x4 matrix ..." << matrix << std::endl;
#endif

  std::cout << "Calculating ... " << mp::MyFirstFunction(1) << std::endl;
  return 0;
}

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

  MYPROJECT: A software package for whatever.

  Copyright (c) University College London (UCL). All rights reserved.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.

  See LICENSE.txt in the top level directory for details.

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

#include <mpMyFunctions.h>
#include <iostream>

#ifdef BUILD_Eigen
#include <Eigen/Dense>
#endif

#ifdef BUILD_Boost
#include <boost/math/special_functions/round.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem/path.hpp>
#endif

#ifdef BUILD_OpenCV
#include <cv.h>
#endif

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

#ifdef BUILD_Eigen
  Eigen::MatrixXd m(2,2);
  std::cout << "Printing 2x2 matrix ..." << m << std::endl;
#endif

#ifdef BUILD_Boost
  std::cout << "Rounding to ... " << boost::math::round(0.123) << std::endl;
  boost::posix_time::ptime startTime = boost::posix_time::second_clock::local_time();
  boost::filesystem::path pathname( "/tmp/tmp.txt" );
#endif

#ifdef BUILD_OpenCV
  cv::Matx44d matrix = cv::Matx44d::eye();
  std::cout << "Printing 4x4 matrix ..." << matrix << std::endl;
#endif

  std::cout << "Calculating ... " << mp::MyFirstFunction(1) << std::endl;
  return 0;
}

Make sure Im using Boost libraries, not just headers.


#include "fade_effect.h"

unsigned int FadeEffect::maxDelay()
{
    return -1;
}

void FadeEffect::init()
{
    // Handle a corner case in which the update just increments
    // a color and overflows the byte
    if( R() == 255 ) R(254);
    if( G() == 255 ) G(254);
    if( B() == 255 ) R(254);
    stage = 0;
    renderTime = 0;
}

void FadeEffect::update()
{
    if( millis() < renderTime ) return;

    switch(stage)
    {
    case 0:
        if( G( G()+1 ) == 255 ) ++stage;
        break;
    case 1:
        if( R( R()-1 ) == 0 ) ++stage;
        break;
    case 2:
        if( B( B()+1 ) == 255 ) ++stage;
        break;
    case 3:
        if( G( G()-1 ) == 0 ) ++stage;
        break;
    case 4:
        if( R( R()+1 ) == 255 ) ++stage;
        break;
    case 5:
        if( B( B()-1 ) == 0 ) ++stage;
        break;
    }
    if( stage == 6 )
        stage = 0;

    renderTime += ceil((float)m_duration / 1536);
}

#include "fade_effect.h"

unsigned int FadeEffect::maxDelay()
{
    return -1;
}

void FadeEffect::init()
{
    // Handle a corner case in which the update just increments
    // a color and overflows the byte
    if( R() == 255 ) R(254);
    if( G() == 255 ) G(254);
    if( B() == 255 ) R(254);
    if( R() == 0 ) R(1);
    if( G() == 0 ) G(1);
    if( B() == 0 ) R(1);
    stage = 0;
    renderTime = 0;
}

void FadeEffect::update()
{
    if( millis() < renderTime ) return;

    switch(stage)
    {
    case 0:
        if( G( G()+1 ) == 255 ) ++stage;
        break;
    case 1:
        if( R( R()-1 ) == 0 ) ++stage;
        break;
    case 2:
        if( B( B()+1 ) == 255 ) ++stage;
        break;
    case 3:
        if( G( G()-1 ) == 0 ) ++stage;
        break;
    case 4:
        if( R( R()+1 ) == 255 ) ++stage;
        break;
    case 5:
        if( B( B()-1 ) == 0 ) ++stage;
        break;
    }
    if( stage == 6 )
        stage = 0;

    renderTime += ceil((float)m_duration / 1536);
}

Handle another fade effect corner case when colour is black


// Nikita Kouevda
// 2013/11/01

#include <iostream>

#include "prime.hpp"

using namespace std;

int main(int argc, char *argv[]) {
  if (argc < 2) {
    cerr << "Usage: prime number ..." << endl;
    return 1;
  }

  for (int i = 1; i < argc; ++i) {
    cout << argv[i] << " is";

    if (!isPrime(atol(argv[i]))) {
      cout << " not";
    }

    cout << " prime" << endl;
  }

  return 0;
}

// Nikita Kouevda
// 2013/11/04

#include <iostream>

#include "prime.hpp"

using namespace std;

int main(int argc, char *argv[]) {
  int i, n;
  char *endptr;

  if (argc < 2) {
    cerr << "usage: prime number ..." << endl;
    return 1;
  }

  for (i = 1; i < argc; ++i) {
    n = strtol(argv[i], &endptr, 10);

    if (*endptr) {
      cerr << "prime: illegal argument: " << argv[i] << endl;
      continue;
    }

    cout << argv[i] << " is";

    if (!isPrime(n)) {
      cout << " not";
    }

    cout << " prime" << endl;
  }

  return 0;
}

Use strtol instead of atol; verify conversion.


#include "MediaServiceHandler.h"

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

namespace com { namespace kurento { namespace kms {

MediaServerServiceHandler::MediaServerServiceHandler()
{
	manager = MediaSessionManager::getInstance();
}

MediaServerServiceHandler::~MediaServerServiceHandler() {
	MediaSessionManager::releaseInstance(manager);
}

void MediaServerServiceHandler::createMediaSession(MediaSession& _return) {
	_return = manager->createMediaSession();
}

void MediaServerServiceHandler::deleteMediaSession(const MediaSession& session) {
	manager->deleteMediaSession(session);
}

}}} // com::kurento::kms

#include "MediaServiceHandler.h"
#include "log.h"

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

using ::com::kurento::log::Log;

static Log l("MediaServiceHandler");
#define d(...) aux_debug(l, __VA_ARGS__);
#define i(...) aux_info(l, __VA_ARGS__);

namespace com { namespace kurento { namespace kms {

MediaServerServiceHandler::MediaServerServiceHandler()
{
	manager = MediaSessionManager::getInstance();
}

MediaServerServiceHandler::~MediaServerServiceHandler() {
	MediaSessionManager::releaseInstance(manager);
}

void MediaServerServiceHandler::createMediaSession(MediaSession& _return) {
	i("createMediaSession");
	_return = manager->createMediaSession();
}

void MediaServerServiceHandler::deleteMediaSession(const MediaSession& session) {
	i("deleteMediaSession");
	manager->deleteMediaSession(session);
}

}}} // com::kurento::kms

Add basic log on MediaService

Add basic log on MediaService


// Insure __block_holder_tmp is allocated on the stack.
// RUN: %llvmgxx %s -S -O2 -o - | egrep {__block_holder_tmp.*alloca}
// <rdar://problem/5865221>
extern void fubar_dispatch_sync(void (^PP)(void));
void fubar() {
  __block void *voodoo;
 fubar_dispatch_sync(^(void){voodoo=0;});
}

// Insure __block_holder_tmp is allocated on the stack.  Darwin only.
// RUN: %llvmgxx %s -S -O2 -o - | egrep {__block_holder_tmp.*alloca}
// XFAIL: *
// XTARGET: darwin
// <rdar://problem/5865221>
// END.
extern void fubar_dispatch_sync(void (^PP)(void));
void fubar() {
  __block void *voodoo;
 fubar_dispatch_sync(^(void){voodoo=0;});
}

Mark this test as Darwin only.  Patch by Bill Wendling.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@74829 91177308-0d34-0410-b5e6-96231b3b80d8


// StackTrace.cpp

// Implements the functions to print current stack traces

#include "Globals.h"
#include "StackTrace.h"
#ifdef _WIN32
	#include "../StackWalker.h"
#else
	#ifdef __GLIBC__
		#include <execinfo.h>
	#endif
	#include <unistd.h>
#endif

// FreeBSD uses size_t for the return type of backtrace()
#if defined(__FreeBSD__) && (__FreeBSD__ >= 10)
	#define btsize size_t
#else
	#define btsize int
#endif

void PrintStackTrace(void)
{
	#ifdef _WIN32
		// Reuse the StackWalker from the LeakFinder project already bound to MCS
		// Define a subclass of the StackWalker that outputs everything to stdout
		class PrintingStackWalker :
			public StackWalker
		{
			virtual void OnOutput(LPCSTR szText) override
			{
				puts(szText);
			}
		} sw;
		sw.ShowCallstack();
	#else
		#ifdef __GLIBC__
			// Use the backtrace() function to get and output the stackTrace:
			// Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
			void * stackTrace[30];
			btsize numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace));
			backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO);
		#endif
	#endif
}

// StackTrace.cpp

// Implements the functions to print current stack traces

#include "Globals.h"
#include "StackTrace.h"
#ifdef _WIN32
	#include "../StackWalker.h"
#else
	#ifdef __GLIBC__
		#include <execinfo.h>
	#endif
	#include <unistd.h>
#endif

void PrintStackTrace(void)
{
	#ifdef _WIN32
		// Reuse the StackWalker from the LeakFinder project already bound to MCS
		// Define a subclass of the StackWalker that outputs everything to stdout
		class PrintingStackWalker :
			public StackWalker
		{
			virtual void OnOutput(LPCSTR szText) override
			{
				puts(szText);
			}
		} sw;
		sw.ShowCallstack();
	#else
		#ifdef __GLIBC__
			// Use the backtrace() function to get and output the stackTrace:
			// Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
			void * stackTrace[30];
			auto numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace));
			backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO);
		#endif
	#endif
}

Use C++11 auto instead of per-platform types.

Closes #2686.


// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new TextFileNFDelegate);
    app.loadScriptNodes("Nodin/NodeScripts/Lua");

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.loadScriptNodes("Nodin/NodeScripts/Lua");

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

Stop using redundant class TextFileNFDelegate.


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

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

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

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_->RemoveObserver(this);
  RenderViewHostDestroyed();
  render_view_host_ = NULL;
}

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

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

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

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_ = NULL;
  RenderViewHostDestroyed();
}

Fix heap corruption that occurs when RenderViewHostObserver calls RenderViewHost to unregister when the latter is in its destructor.

TBR=dmichael
Review URL: http://codereview.chromium.org/6813043

git-svn-id: http://src.chromium.org/svn/trunk/src@80946 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: 14f59872a905c9786c25eddd18d25c90a2692474


#include <constrained_ik/enum_types.h>
#include <ros/console.h>

using namespace constrained_ik::constraint_types;

const std::string ConstraintType::names_[] = {"Primary", "Auxiliary", "Inactive"};
const std::map<std::string, ConstraintTypes> ConstraintType::name_to_enum_map_ = boost::assign::map_list_of ("Primary", Primary) ("Auxiliary", Auxiliary) ("Inactive", Inactive);

ConstraintTypes ConstraintType::stringToEnum(std::string constraint_type_name)
{
  std::map<std::string, ConstraintTypes>::const_iterator it;
  it = name_to_enum_map_.find(constraint_type_name);
  if (it != name_to_enum_map_.end())
    return it->second;
  else
    ROS_ERROR("No enumerator named %s. Valid names: Primary, Auxiliary, Inactive", constraint_type_name.c_str());
}

#include <constrained_ik/enum_types.h>
#include <ros/console.h>

using namespace constrained_ik::constraint_types;

const std::string ConstraintType::names_[] = {"Primary", "Auxiliary", "Inactive"};
const std::map<std::string, ConstraintTypes> ConstraintType::name_to_enum_map_ = boost::assign::map_list_of ("primary", Primary) ("auxiliary", Auxiliary) ("inactive", Inactive);

ConstraintTypes ConstraintType::stringToEnum(std::string constraint_type_name)
{
  std::map<std::string, ConstraintTypes>::const_iterator it;
  std::transform(constraint_type_name.begin(), constraint_type_name.end(), constraint_type_name.begin(), ::tolower);
  it = name_to_enum_map_.find(constraint_type_name);
  if (it != name_to_enum_map_.end())
    return it->second;
  else
    ROS_ERROR("No enumerator named %s. Valid names (Not case sensitive): Primary, Auxiliary, Inactive", constraint_type_name.c_str());
}

Make ConstraintType::stringToEnum not case sensitive


#include <xpcc/architecture.hpp>
#include "../stm32f4_discovery.hpp"

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	defaultSystemClock::enable();

	LedOrange::setOutput(xpcc::Gpio::High);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::High);
	LedBlue::setOutput(xpcc::Gpio::High);

	// Enable USART 2
	GpioOutputA2::connect(Usart2::Tx);
	GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
	Usart2::initialize<defaultSystemClock, 9600>(12);

	while (1)
	{
		static uint8_t c = 'A';
		LedRed::toggle();
		LedGreen::toggle();
		Usart2::write(c);
		++c;
		if (c == 'Z' + 1) {
			c = 'A';
		}
		xpcc::delay_ms(500);
	}

	return 0;
}

#include <xpcc/architecture.hpp>
#include "../stm32f4_discovery.hpp"

// ----------------------------------------------------------------------------
/**
 * Very basic example of USART usage.
 * The ASCII sequence 'A', 'B', 'C, ... , 'Z', 'A', 'B', 'C', ...
 * is printed with 9600 baud, 8N1 at pin PA3.
 */
MAIN_FUNCTION
{
	defaultSystemClock::enable();

	LedOrange::setOutput(xpcc::Gpio::High);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::High);
	LedBlue::setOutput(xpcc::Gpio::High);

	// Enable USART 2
	GpioOutputA2::connect(Usart2::Tx);
	GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
	Usart2::initialize<defaultSystemClock, 9600>(12);

	while (1)
	{
		static uint8_t c = 'A';
		LedRed::toggle();
		LedGreen::toggle();
		Usart2::write(c);
		++c;
		if (c > 'Z') {
			c = 'A';
		}
		xpcc::delay_ms(500);
	}

	return 0;
}

Document what is expected from UART example


#include "hapticbutton.h"
#include <QPainter>

HapticButton::HapticButton(const QString &label) :
    QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
    setMinimumSize(100, 100);
}

void HapticButton::mousePressEvent(QMouseEvent *)
{
    if (m_checkable) {
        m_checked = !m_checked;
        emit toggled(m_checked);
    } else {
        emit clicked();
    }
}

void HapticButton::paintEvent(QPaintEvent *)
{
    QPainter paint(this);

    QRect r(0, 0, width()-1, height()-1);
    paint.drawRoundedRect(r, 10, 10);
    paint.drawText(r, Qt::AlignCenter, m_label);
}

#include "hapticbutton.h"
#include <QPainter>

HapticButton::HapticButton(const QString &label) :
    QWidget(0), m_label(label), m_checked(false), m_checkable(false)
{
    setMinimumSize(100, 100);
}

void HapticButton::mousePressEvent(QMouseEvent *)
{
    if (m_checkable) {
        m_checked = !m_checked;
        emit toggled(m_checked);
    } else {
        emit clicked();
    }
}

void HapticButton::paintEvent(QPaintEvent *)
{
    QPainter paint(this);

    QRect r(1, 1, width()-2, height()-2);
    paint.drawRoundedRect(r, 10, 10);
    paint.drawText(r, Qt::AlignCenter, m_label);
}

Fix cropped hapticsquare buttons on devices

Task: MOBILITY-1826


#include <ccspec/core/formatter.h>

namespace ccspec {
namespace core {

using std::exception_ptr;
using std::list;
using std::ostream;

// public methods.

void Formatter::examplePassed(const ExecutionResult& execution_result) const {
    (void) execution_result;
}

void Formatter::exampleFailed(const ExecutionResult& execution_result) const {
    (void) execution_result;
}

void Formatter::afterEachHookFailed(exception_ptr failure) const {
    (void) failure;
}

void Formatter::aroundHookFailed(exception_ptr failure) const {
    (void) failure;
}

void Formatter::startDump() const {}

void Formatter::dumpFailures(const list<exception_ptr>& failures) const {
    (void) failures;
}

// Protected methods.

Formatter::Formatter(ostream& output) : output_(output) {}

} // namespace core
} // namespace ccspec

#include <ccspec/core/formatter.h>

namespace ccspec {
namespace core {

using std::exception_ptr;
using std::list;
using std::ostream;

// public methods.

void Formatter::examplePassed(const ExecutionResult&) const {}

void Formatter::exampleFailed(const ExecutionResult&) const {}

void Formatter::afterEachHookFailed(exception_ptr) const {}

void Formatter::aroundHookFailed(exception_ptr) const {}

void Formatter::startDump() const {}

void Formatter::dumpFailures(const list<exception_ptr>&) const {}

// Protected methods.

Formatter::Formatter(ostream& output) : output_(output) {}

} // namespace core
} // namespace ccspec

Remove formal parameters to avoid complier warning

The compiler warning for unused variables can be avoided by leaving out
the formal parameters instead of doing a void cast no-op.


#include <exception>
#include <iostream>
#include <cstdlib>
#include "IMPL/LCIOExceptionHandler.h"

namespace IMPL {

  // create one globale instance of the handler
  LCIOExceptionHandler* LCIOExceptionHandler::_me = 0 ;

/** Method catches any std::exception, prints the message to stdout
 * and then exits the program.
 */
void lcio_unexpected(){

  try{

    throw ;

  }catch( std::exception& e){

    std::cout << " A runtime error has occured : "
	      << e.what()
	      << std::endl
	      << " the program will have to be terminated - sorry." << std::endl ;
    exit(1) ;
  }
}

  LCIOExceptionHandler::LCIOExceptionHandler(){

    std::set_unexpected( lcio_unexpected ) ;
    std::set_terminate( lcio_unexpected ) ;
  }

  LCIOExceptionHandler* LCIOExceptionHandler::createInstance(){

    if( ! _me ){
      _me = new LCIOExceptionHandler ;
    }

    return _me ;
  }
}

#include <exception>
#include <iostream>
#include <cstdlib>
#include "IMPL/LCIOExceptionHandler.h"

namespace IMPL {

  // create one globale instance of the handler
  LCIOExceptionHandler* LCIOExceptionHandler::_me = 0 ;

/** Method catches any std::exception, prints the message to stdout
 * and then exits the program.
 */
void lcio_unexpected(){

  try{

    throw ;

  }catch( std::exception& e){

    std::cout << " A runtime error has occured : "
	      << e.what()
	      << std::endl
	      << " the program will have to be terminated - sorry." << std::endl ;
    exit(1) ;
  }
}

  LCIOExceptionHandler::LCIOExceptionHandler(){}

  LCIOExceptionHandler* LCIOExceptionHandler::createInstance(){

    if( ! _me ){
      _me = new LCIOExceptionHandler ;
    }

    return _me ;
  }
}

Remove deprecated set_unexpected and set_terminate


#include "./compile.h"
#include "tree_sitter/compiler.h"

namespace node_tree_sitter_compiler {

using namespace v8;

NAN_METHOD(Compile) {
  String::Utf8Value grammar_json(info[0]);
  TSCompileResult compile_result = ts_compile_grammar(*grammar_json);

  if (compile_result.error_message) {
    Local<Value> error = Nan::Error(compile_result.error_message);
    Local<Object>::Cast(error)->Set(Nan::New("isGrammarError").ToLocalChecked(), Nan::True());
    Nan::ThrowError(error);
  } else {
    info.GetReturnValue().Set(Nan::New(compile_result.code).ToLocalChecked());
  }
}

}  // namespace node_tree_sitter_compiler

#include "./compile.h"
#include "tree_sitter/compiler.h"

namespace node_tree_sitter_compiler {

using namespace v8;

NAN_METHOD(Compile) {
  String::Utf8Value grammar_json(info[0]);
  TSCompileResult compile_result = ts_compile_grammar(*grammar_json);

  if (compile_result.error_type != TSCompileErrorTypeNone) {
    Local<Value> error = Nan::Error(compile_result.error_message);
    Local<Object>::Cast(error)->Set(Nan::New("isGrammarError").ToLocalChecked(), Nan::True());
    Nan::ThrowError(error);
  } else {
    info.GetReturnValue().Set(Nan::New(compile_result.code).ToLocalChecked());
  }
}

}  // namespace node_tree_sitter_compiler

Use the error_type field to check for errors


#include "platform/platform.h"
#include "WProgram.h"

void openxc::platform::initialize() {
    // this is required to initialize the Wiring library from MPIDE's toolchain
    // (inspired by Arduino)
    init();
}

#include "platform/platform.h"
#include "WProgram.h"

extern "C" {
extern void __use_isr_install(void);
__attribute__((section(".comment"))) void (*__use_force_isr_install)(void) = &__use_isr_install;
}

void openxc::platform::initialize() {
    // this is required to initialize the Wiring library from MPIDE's toolchain
    // (inspired by Arduino)
    init();
}

Install ISR on PIC32 with updated build script.


// RUN: %clang_cc1 -emit-llvm-only -triple %itanium_abi_triple -fdump-record-layouts %s 2>/dev/null \
// RUN:            | FileCheck %s

union A {
  int f1: 3;
  A();
};

A::A() {}

union B {
  int f1: 69;
  B();
};

B::B() {}

// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT:   0 | union A
// CHECK-NEXT:   0 |   int f1
// CHECK-NEXT:     | [sizeof=4, dsize=1, align=4
// CHECK-NEXT:     |  nvsize=1, nvalign=4]

// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT:   0 | union B
// CHECK-NEXT:   0 |   int f1
// CHECK-NEXT:     | [{{sizeof=16, dsize=9, align=8|sizeof=12, dsize=9, align=4}}
// CHECK-NEXT:     |  {{nvsize=9, nvalign=8|nvsize=9, nvalign=4}}]

// RUN: %clang_cc1 -emit-llvm-only -triple %itanium_abi_triple -fdump-record-layouts %s 2>/dev/null \
// RUN:            | FileCheck %s

union A {
  int f1: 3;
  A();
};

A::A() {}

union B {
  char f1: 35;
  B();
};

B::B() {}

// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT:   0 | union A
// CHECK-NEXT:   0 |   int f1
// CHECK-NEXT:     | [sizeof=4, dsize=1, align=4
// CHECK-NEXT:     |  nvsize=1, nvalign=4]

// CHECK:*** Dumping AST Record Layout
// CHECK-NEXT:   0 | union B
// CHECK-NEXT:   0 |   int f1
// CHECK-NEXT:     | [sizeof=8, dsize=5, align=4
// CHECK-NEXT:     |  nvsize=5, nvalign=4]

Test case B is updated to work for 32-bit and 64-bit platforms

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@220271 91177308-0d34-0410-b5e6-96231b3b80d8


#include "utils.h"

#include <nlohmann/json.hpp>

using json = nlohmann::json;

std::string get_with_def(const std::map<std::string, std::string> &m, const std::string &key,
                         const std::string &defval)
{
  auto it = m.find(key);
  if (it == m.end())
    return defval;
  return it->second;
}

std::map<std::string, std::string> parse_to_map(const std::string &js)
{
  std::map<std::string, std::string> m;
  if (js.size())
    {
      json j = json::parse(js);
      for (auto v : j.items())
        m[v.key()] = v.value();
    }
  return m;
}

std::string geocoder_type(const std::string &t_class, const std::string &t_value)
{
  if (t_class == "building" || t_value == "yes")
    return t_class;
  return t_class + "_" + t_value;
}

#include "utils.h"

#include <nlohmann/json.hpp>

using json = nlohmann::json;

std::string get_with_def(const std::map<std::string, std::string> &m, const std::string &key,
                         const std::string &defval)
{
  auto it = m.find(key);
  if (it == m.end())
    return defval;
  return it->second;
}

std::map<std::string, std::string> parse_to_map(const std::string &js)
{
  std::map<std::string, std::string> m;
  if (js.size())
    {
      json j = json::parse(js);
      for (auto v : j.items())
        m[v.key()] = v.value();
    }
  return m;
}

std::string geocoder_type(const std::string &t_class, const std::string &t_value)
{
  if (t_value == "yes")
    return t_class;
  return t_class + "_" + t_value;
}

Use full tag for buildings if available

Use full tag for buildings if available


#include "utils/LinearAlg2D.h"

int main(int argc, char** argv)
{
	// Pick a function that's not defined in the header.
	const float angle =
		cura::LinearAlg2D::getAngleLeft
		(
			cura::Point(1.0, 1.0),
			cura::Point(1.0, 2.0),
			cura::Point(3.0, 3.0)
		);
	return (angle != 0.f) ? 0 : 1;
}

#include "settings/Settings.h"  // For the default definition of 'CURA_ENGINE_VERSION' if none is given.
#include "utils/LinearAlg2D.h"  // For testing calling a simple non-header function.

#include <cstdio>

int main(int argc, char** argv)
{
	// Test which version do we have here?
	std::fprintf(stdout, "test-package called for version: %s\n", CURA_ENGINE_VERSION);

	// Pick a function that's not defined in the header.
	const float angle =
		cura::LinearAlg2D::getAngleLeft
		(
			cura::Point(1.0, 1.0),
			cura::Point(1.0, 2.0),
			cura::Point(3.0, 3.0)
		);
	return (angle != 0.f) ? 0 : 1;
}

Debug which version is build with test-package.

part of CURA-8830


//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <thread>
#include <mutex>

struct Complex {
    std::mutex mutex;
    int i;

    Complex() : i(0) {}

    void mul(int x){
        std::lock_guard<std::mutex> lock(mutex);
        i *= x;
    }

    void div(int x){
        std::lock_guard<std::mutex> lock(mutex);
        i /= x;
    }

    void both(int x, int y){
        std::lock_guard<std::mutex> lock(mutex);
        mul(x);
        div(y);
    }
};

int main(){
    Complex complex;
    complex.both(32, 23);

    return 0;
}

Set the code to MIT license

Set the code to MIT license


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

int a<::> = { 1, 2, 3 };
int b = a<:::a<:0:>:>;
bool c = a<:0:><::b;

template<int &n> void f() {}
template void f<::b>();

#define x a<:: ## : b :>
int d = x; // expected-error {{pasting formed ':::', an invalid preprocessing token}} expected-error {{expected unqualified-id}}

const char xs[] = R"(\
??=\U0000)";
static_assert(sizeof(xs) == 12, "did not revert all changes");

Test that we correctly handle reversion of line splicing etc in raw string
literals. As suggested by Sean Silva.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@172694 91177308-0d34-0410-b5e6-96231b3b80d8


/*
 * InitWeightTestProbe.cpp
 *
 *  Created on: Sep 6, 2011
 *      Author: kpeterson
 */

#include "InitWeightTestProbe.hpp"
#include "../PetaVision/src/include/pv_arch.h"
#include "../PetaVision/src/layers/HyPerLayer.hpp"
#include <string.h>
#include <assert.h>

namespace PV {

InitWeightTestProbe::InitWeightTestProbe(const char * filename, HyPerCol * hc, const char * msg)
: StatsProbe(filename, hc, msg)
{
}

InitWeightTestProbe::InitWeightTestProbe(const char * msg)
: StatsProbe(msg)
{
}

int InitWeightTestProbe::outputState(float time, HyPerLayer * l)
{
	int status = StatsProbe::outputState(time, l);
#ifdef PV_USE_MPI
   InterColComm * icComm = l->getParent()->icCommunicator();
   const int rcvProc = 0;
   if( icComm->commRank() != rcvProc ) {
      return 0;
   }
#endif // PV_USE_MPI
	if(time>2.0f){
		assert((fMin>-0.999)&&(fMin<0.001));
		assert((fMax>-0.999)&&(fMax<0.001));
		assert((avg>-0.999)&&(avg<0.001));
	}

	return status;
}

} /* namespace PV */

/*
 * InitWeightTestProbe.cpp
 *
 *  Created on: Sep 6, 2011
 *      Author: kpeterson
 */

#include "InitWeightTestProbe.hpp"
#include "../PetaVision/src/include/pv_arch.h"
#include "../PetaVision/src/layers/HyPerLayer.hpp"
#include <string.h>
#include <assert.h>

namespace PV {

InitWeightTestProbe::InitWeightTestProbe(const char * filename, HyPerCol * hc, const char * msg)
: StatsProbe(filename, hc, msg)
{
}

InitWeightTestProbe::InitWeightTestProbe(const char * msg)
: StatsProbe(msg)
{
}

int InitWeightTestProbe::outputState(float time, HyPerLayer * l)
{
	int status = StatsProbe::outputState(time, l);
#ifdef PV_USE_MPI
   InterColComm * icComm = l->getParent()->icCommunicator();
   const int rcvProc = 0;
   if( icComm->commRank() != rcvProc ) {
      return 0;
   }
#endif // PV_USE_MPI
	if(time>2.0f){
		assert((fMin>-0.001)&&(fMin<0.001));
		assert((fMax>-0.001)&&(fMax<0.001));
		assert((avg>-0.001)&&(avg<0.001));
	}

	return status;
}

} /* namespace PV */

Fix thresholds of fMin, fMax and avg for test to pass

git-svn-id: 173bfced7225b0a4144fa0e9d72f2fb8f54e5b79@4214 7c0444ca-5550-0410-9008-faecdbe78eb5


#include "unit_tests/tests.hpp"
#include "grune/non_terminal.hpp"

using namespace grune;

class sequence_tests : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE(sequence_tests);
    CPPUNIT_TEST(test_to_string);
    CPPUNIT_TEST_SUITE_END();

public:
    void test_to_string()
    {
        non_terminal A("A");
        non_terminal B("B");
        symbol c("c");

        sequence s { A, B, c };

        std::string expected = "A, B, \"c\"";
        CPPUNIT_ASSERT_EQUAL(expected, to_string(s));

        expected = "\"\"";
        CPPUNIT_ASSERT_EQUAL(expected, to_string(sequence()));

        sequence_list sl { s, { A, c, B } };
        expected = "A, B, \"c\" | A, \"c\", B";
        CPPUNIT_ASSERT_EQUAL(expected, to_string(sl));

        expected = "\"\"";
        CPPUNIT_ASSERT_EQUAL(expected, to_string(sequence_list()));
    }

};

CPPUNIT_TEST_SUITE_REGISTRATION(sequence_tests);

#include "unit_tests/tests.hpp"
#include "grune/non_terminal.hpp"

using namespace grune;

BOOST_AUTO_TEST_SUITE(sequence_tests)

void test_to_string()
{
    non_terminal A("A");
    non_terminal B("B");
    symbol c("c");

    sequence s { A, B, c };

    std::string expected = "A, B, \"c\"";
    BOOST_CHECK_EQUAL(expected, to_string(s));

    expected = "\"\"";
    BOOST_CHECK_EQUAL(expected, to_string(sequence()));

    sequence_list sl { s, { A, c, B } };
    expected = "A, B, \"c\" | A, \"c\", B";
    BOOST_CHECK_EQUAL(expected, to_string(sl));

    expected = "\"\"";
    BOOST_CHECK_EQUAL(expected, to_string(sequence_list()));
}

BOOST_AUTO_TEST_SUITE_END()

Convert sequence tests to Boost UTF

Convert sequence tests to Boost UTF


#include "login/http-post-login.h"
#include <QNetworkRequest>
#include <QUrlQuery>
#include "models/site.h"
#include "network/network-manager.h"

HttpPostLogin::HttpPostLogin(HttpAuth *auth, Site *site, NetworkManager *manager, MixedSettings *settings)
	: HttpLogin("post", auth, site, manager, settings)
{}

NetworkReply *HttpPostLogin::getReply(const QUrl &url, const QUrlQuery &query) const
{
	QNetworkRequest request(url);
	request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

	return m_manager->post(request, query.query(QUrl::FullyEncoded).toUtf8());
}

#include "login/http-post-login.h"
#include <QNetworkRequest>
#include <QUrlQuery>
#include "models/site.h"
#include "network/network-manager.h"

HttpPostLogin::HttpPostLogin(HttpAuth *auth, Site *site, NetworkManager *manager, MixedSettings *settings)
	: HttpLogin("post", auth, site, manager, settings)
{}

NetworkReply *HttpPostLogin::getReply(const QUrl &url, const QUrlQuery &query) const
{
	QNetworkRequest request(url);
	request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

	QString data = query.query(QUrl::FullyEncoded)
		.replace('+', "%2B")
		.replace("%20", "+");
	return m_manager->post(request, data.toUtf8());
}

Fix encoding of data in HTTP POST login

Fix encoding of data in HTTP POST login


#include <ros/ros.h>
#include <nav_msgs/OccupancyGrid.h>

int main(int argc, char *argv[]){
    ros::init(argc, argv, "local_map_2d_publisher");
    ros::NodeHandle node;
    ros::Publisher map_lc_pub = node.advertise<nav_msgs::OccupancyGrid>("local_map", 1);

    const int size = 5;

    nav_msgs::OccupancyGrid map_lc;
    map_lc.resolution = 2;
    map_lc.frame_id = "/world";
    map_lc.info.origin.position.x = -size/2;
    map_lc.info.origin.position.y = -size/2;
    map_lc.header.stamp = ros::Time::now();
    map_lc.info.width = size;
    map_lc.info.height = size;
    map_lc.data.resize(size * size);

    for(int row=0; row < size; row++){
        for(int col=0; col < size; col++){
            map_lc.data[(row*map_lc.info.width)+col] = 0;
        }
    }

    map_lc_pub.publish(map_lc);
    ros::spin();
}

#include <ros/ros.h>
#include <nav_msgs/OccupancyGrid.h>

int main(int argc, char *argv[]){
    ros::init(argc, argv, "local_map_2d_publisher");
    ros::NodeHandle node;
    ros::Publisher map_lc_pub = node.advertise<nav_msgs::OccupancyGrid>("local_map", 1);

    const int size = 5;

    nav_msgs::OccupancyGrid map_lc;
    map_lc.info.resolution = 2;
    map_lc.header.frame_id = "/world";
    map_lc.header.stamp = ros::Time::now();
    map_lc.info.origin.position.x = -size/2;
    map_lc.info.origin.position.y = -size/2;
    map_lc.info.width = size;
    map_lc.info.height = size;
    map_lc.data.resize(size * size);

    for(int row=0; row < size; row++){
        for(int col=0; col < size; col++){
            map_lc.data[(row*map_lc.info.width)+col] = 0;
        }
    }

    map_lc_pub.publish(map_lc);
    ros::spin();
}

Fix illegal access to member

Fix illegal access to member


#include "catch.hpp"

#include "MedianOfTwoSortedArrays.hpp"

TEST_CASE("Median Of Two Sorted Arrays") {
  Solution s;

  SECTION("Two nums are empty") {
    vector<int> nums1;
    vector<int> nums2;
    REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 0.0);
  }

  SECTION("Two nums do not overlap") {
    vector<int> nums1 {1, 2, 3};
    vector<int> nums2 {4, 5, 6};
    REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 3.5);
  }
}

#include "catch.hpp"

#include "MedianOfTwoSortedArrays.hpp"

TEST_CASE("Median Of Two Sorted Arrays") {
  Solution s;

  SECTION("Two nums are empty") {
    vector<int> nums1;
    vector<int> nums2;
    REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 0.0);
  }

  SECTION("Two nums do not overlap (even case)") {
    vector<int> nums1 {1, 2, 3};
    vector<int> nums2 {4, 5, 6};
    REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 3.5);
  }

  SECTION("Two overlapped nums (even case)") {
    vector<int> nums1 {1, 2, 7};
    vector<int> nums2 {4, 5, 6};
    REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 4.5);
  }

  SECTION("Two nums do not overlap (odd case)") {
    vector<int> nums1 {1, 2};
    vector<int> nums2 {4, 5, 6};
    REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 4.0);
  }

  SECTION("Two overlapped nums (odd case)") {
    vector<int> nums1 {1, 7};
    vector<int> nums2 {4, 5, 6};
    REQUIRE(s.findMedianSortedArrays(nums1, nums2) == 5.0);
  }
}

Update Problem 4 test case

Update Problem 4 test case


#include "../src/engine.h"
#include "drawdevice.h"

#include <QtGui>

int main(int argc, char *argv[])
{
    Engine *eng = new Engine;
    if (!eng->loadWorldFromFile("world.rooms"))
    {
        eng->getLogger()->write("ERROR: cannot load world.rooms!", Log::ERROR);
        delete eng;
        return 1;
    }
    QApplication qt_app(argc, argv);
    QFile file("style.qss");
    if (file.exists())
    {
        file.open(QFile::ReadOnly);
        QString styleSheet = QLatin1String(file.readAll());
        qt_app.setStyleSheet(styleSheet);
    }
    QMainWindow qt_wnd;
    RoomsManager *man = eng->getRoomsManager();
    qt_wnd.setBaseSize(man->width(), man->height());
    qt_wnd.setWindowTitle(man->worldName().c_str());
    DrawDevice qt_draw_device(eng, &qt_wnd);
    qt_draw_device.initialize();
    qt_wnd.setCentralWidget(&qt_draw_device);
    qt_wnd.show();
    int r = qt_app.exec();
    delete eng;
    return r;
}

#include "../src/engine.h"
#include "drawdevice.h"

#include <QtGui>

int main(int argc, char *argv[])
{
    Engine *eng = new Engine;
    if (!eng->loadWorldFromFile("world.rooms"))
    {
        eng->getLogger()->write("ERROR: cannot load world.rooms!", Log::ERROR);
        delete eng;
        return 1;
    }
    QApplication qt_app(argc, argv);
    QFile file("style.qss");
    if (file.exists())
    {
        file.open(QFile::ReadOnly);
        QString styleSheet = QLatin1String(file.readAll());
        qt_app.setStyleSheet(styleSheet);
    }
    QMainWindow qt_wnd;
    RoomsManager *man = eng->getRoomsManager();
    qt_wnd.resize(man->width(), man->height());
    qt_wnd.setWindowTitle(man->worldName().c_str());
    DrawDevice qt_draw_device(eng, &qt_wnd);
    qt_draw_device.initialize();
    qt_wnd.setCentralWidget(&qt_draw_device);
    qt_wnd.show();
    int r = qt_app.exec();
    delete eng;
    return r;
}

Use resize to specify the size of the central widget


#include "theme-loader.h"
#include <QDir>
#include <QApplication>

ThemeLoader::ThemeLoader(QString path)
	: m_path(path)
{}

QStringList ThemeLoader::getAllThemes() const
{
	return QDir(m_path).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
}

bool ThemeLoader::setTheme(QString name)
{
	QFile f(m_path + "/" + name + "/style.css");
	if (!f.open(QFile::ReadOnly | QFile::Text))
		return false;

	QString css = f.readAll();
	f.close();
	qApp->setStyleSheet(css);
	return true;
}

#include "theme-loader.h"
#include <QDir>
#include <QApplication>

ThemeLoader::ThemeLoader(QString path)
	: m_path(path)
{}

QStringList ThemeLoader::getAllThemes() const
{
	return QDir(m_path).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
}

bool ThemeLoader::setTheme(QString name)
{
	QString dir = QString(m_path).replace('\\', '/') + name + "/";

	QFile f(dir + "style.css");
	if (!f.open(QFile::ReadOnly | QFile::Text))
		return false;

	QString css = f.readAll();
	f.close();

	// Replace urls relative paths by absolute ones
	css.replace("url(", "url(" + dir);

	qApp->setStyleSheet(css);
	return true;
}

Allow to use relative path images in themes


#include "EpsilonDashboard.h"
#include <QApplication>
#include <QLockFile>
#include <QDebug>
#include <QDir>

int main(int argc, char* argv[])
{
    QString tmpDir = QDir::tempPath();
    QLockFile lockFile(tmpDir + "/epsilonDashboard.lock");

    /* Trying to close the Lock File, if the attempt is unsuccessful for 100 milliseconds,
     * then there is a Lock File already created by another process.
     * Therefore, we issue a warning and close the program
     */
    if (!lockFile.tryLock(100))
    {
        qDebug() << "An instance of dashboard already exists.";
        qDebug() << "If you are sure you only have one instance of dashboard running, please delete the file /tmp/epsilonDashboard.lock as root.";
        qDebug() << "Quitting...";
        return 1;
    }
    else
    {
        qDebug() << "No other instance of dashboard exists.";
        qDebug() << "Launching dashboard...";
    }

    QScopedPointer<EpsilonDashboard> app;
    app.reset(new EpsilonDashboard(argc, argv));
    return app->exec();
}

#include "EpsilonDashboard.h"
#include <QApplication>
#include <QLockFile>
#include <QDebug>
#include <QDir>

int main(int argc, char* argv[])
{
#if QT_VERSION >= 0x050600
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QString tmpDir = QDir::tempPath();
    QLockFile lockFile(tmpDir + "/epsilonDashboard.lock");

    /* Trying to close the Lock File, if the attempt is unsuccessful for 100 milliseconds,
     * then there is a Lock File already created by another process.
     * Therefore, we issue a warning and close the program
     */
    if (!lockFile.tryLock(100))
    {
        qDebug() << "An instance of dashboard already exists.";
        qDebug() << "If you are sure you only have one instance of dashboard running, please delete the file /tmp/epsilonDashboard.lock as root.";
        qDebug() << "Quitting...";
        return 1;
    }
    else
    {
        qDebug() << "No other instance of dashboard exists.";
        qDebug() << "Launching dashboard...";
    }

    QScopedPointer<EpsilonDashboard> app;
    app.reset(new EpsilonDashboard(argc, argv));
    return app->exec();
}

Fix for High DPI Screens

Fix for High DPI Screens


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

#include "SparcTargetAsmInfo.h"

using namespace llvm;

SparcELFTargetAsmInfo::SparcELFTargetAsmInfo(const TargetMachine &TM):
  ELFTargetAsmInfo(TM) {
  Data16bitsDirective = "\t.half\t";
  Data32bitsDirective = "\t.word\t";
  Data64bitsDirective = 0;  // .xword is only supported by V9.
  ZeroDirective = "\t.skip\t";
  CommentString = "!";
  ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
  COMMDirectiveTakesAlignment = true;
}

std::string SparcELFTargetAsmInfo::PrintSectionFlags(unsigned flags) const {
  std::string Flags = ",";

  if (flags & SectionFlags::Mergeable)
    return ELFTargetAsmInfo::PrintSectionFlags(flags);

  if (!(flags & SectionFlags::Debug))
    Flags += "#alloc";
  if (flags & SectionFlags::Code)
    Flags += "#execinstr";
  if (flags & SectionFlags::Writeable)
    Flags += "#write";
  if (flags & SectionFlags::TLS)
    Flags += "#tls";

  return Flags;
}

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

#include "SparcTargetAsmInfo.h"

using namespace llvm;

SparcELFTargetAsmInfo::SparcELFTargetAsmInfo(const TargetMachine &TM):
  ELFTargetAsmInfo(TM) {
  Data16bitsDirective = "\t.half\t";
  Data32bitsDirective = "\t.word\t";
  Data64bitsDirective = 0;  // .xword is only supported by V9.
  ZeroDirective = "\t.skip\t";
  CommentString = "!";
  ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
  COMMDirectiveTakesAlignment = true;
  CStringSection=".rodata.str";
}

std::string SparcELFTargetAsmInfo::PrintSectionFlags(unsigned flags) const {
  std::string Flags = ",";

  if (flags & SectionFlags::Mergeable)
    return ELFTargetAsmInfo::PrintSectionFlags(flags);

  if (!(flags & SectionFlags::Debug))
    Flags += "#alloc";
  if (flags & SectionFlags::Code)
    Flags += "#execinstr";
  if (flags & SectionFlags::Writeable)
    Flags += "#write";
  if (flags & SectionFlags::TLS)
    Flags += "#tls";

  return Flags;
}

Use mergeable strings sections on sparc

Use mergeable strings sections on sparc

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@54541 91177308-0d34-0410-b5e6-96231b3b80d8


#include <emscripten/bind.h>

#include "checksieve.h"

using namespace emscripten;

EMSCRIPTEN_BINDINGS(sieve) {

    value_object<yy::position>("position")
        .field("column", &yy::position::column)
        .field("line", &yy::position::line)
        ;
    value_object<yy::location>("location")
        .field("begin", &yy::location::begin)
        .field("end", &yy::location::end)
        ;
    value_object<sieve::parse_result>("parse_result")
        .field("location", &sieve::parse_result::location)
        .field("status", &sieve::parse_result::status)
        .field("error", &sieve::parse_result::error)
        ;
    class_<sieve::parse_options>("parse_options")
        .constructor<>()
        ;

    function("version", optional_override(
                [](){
                  return std::string(sieve::version());
                }));
    function("sieve_parse_string", optional_override(
                [](const std::string s, struct sieve::parse_options o) {
                  return sieve_parse_string(s.c_str(), o);
                }));
}

#include <emscripten/bind.h>

#include "checksieve.h"

using namespace emscripten;

EMSCRIPTEN_BINDINGS(sieve) {

    value_object<yy::position>("position")
        .field("column", &yy::position::column)
        .field("line", &yy::position::line)
        ;
    value_object<yy::location>("location")
        .field("begin", &yy::location::begin)
        .field("end", &yy::location::end)
        ;
    value_object<sieve::parse_result>("parse_result")
        .field("location", &sieve::parse_result::location)
        .field("status", &sieve::parse_result::status)
        .field("error", &sieve::parse_result::error)
        .field("hint", &sieve::parse_result::hint)
        ;
    class_<sieve::parse_options>("parse_options")
        .constructor<>()
        ;

    function("version", optional_override(
                [](){
                  return std::string(sieve::version());
                }));
    function("sieve_parse_string", optional_override(
                [](const std::string s, struct sieve::parse_options o) {
                  return sieve_parse_string(s.c_str(), o);
                }));
}

Add bindings for parse_result hints.

Add bindings for parse_result hints.


#include <qv4unwindhelper.h>

#include <wtf/Platform.h>

#if CPU(X86_64) && OS(LINUX)
#  define USE_DW2_HELPER
#elif CPU(X86) && OS(LINUX)
#  define USE_DW2_HELPER
#elif OS(WINDOWS)
    // SJLJ will unwind on Windows
#  define USE_NULL_HELPER
#elif OS(IOS)
    // SJLJ will unwind on iOS
#  define USE_NULL_HELPER
#elif OS(ANDROID)
#  warning "TODO!"
#  define USE_NULL_HELPER
#else
#  warning "Unsupported/untested platform!"
#  define USE_NULL_HELPER
#endif

#ifdef USE_DW2_HELPER
#  include <qv4unwindhelper_p-dw2.h>
#endif // USE_DW2_HELPER

#ifdef USE_NULL_HELPER
using namespace QQmlJS::VM;
UnwindHelper *UnwindHelper::create() { return 0; }
UnwindHelper::UnwindHelper() {}
UnwindHelper::~UnwindHelper() {}
void UnwindHelper::registerFunction(Function *function) {Q_UNUSED(function);}
void UnwindHelper::registerFunctions(QVector<Function *> functions) {Q_UNUSED(functions);}
void UnwindHelper::deregisterFunction(Function *function) {Q_UNUSED(function);}
void UnwindHelper::deregisterFunctions(QVector<Function *> functions) {Q_UNUSED(functions);}
#endif // USE_NULL_HELPER

#include <qv4unwindhelper.h>

#include <wtf/Platform.h>

#if CPU(X86_64) && (OS(LINUX) || OS(MAC_OS_X))
#  define USE_DW2_HELPER
#elif CPU(X86) && OS(LINUX)
#  define USE_DW2_HELPER
#elif OS(WINDOWS)
    // SJLJ will unwind on Windows
#  define USE_NULL_HELPER
#elif OS(IOS)
    // SJLJ will unwind on iOS
#  define USE_NULL_HELPER
#elif OS(ANDROID)
#  warning "TODO!"
#  define USE_NULL_HELPER
#else
#  warning "Unsupported/untested platform!"
#  define USE_NULL_HELPER
#endif

#ifdef USE_DW2_HELPER
#  include <qv4unwindhelper_p-dw2.h>
#endif // USE_DW2_HELPER

#ifdef USE_NULL_HELPER
using namespace QQmlJS::VM;
UnwindHelper *UnwindHelper::create() { return 0; }
UnwindHelper::UnwindHelper() {}
UnwindHelper::~UnwindHelper() {}
void UnwindHelper::registerFunction(Function *function) {Q_UNUSED(function);}
void UnwindHelper::registerFunctions(QVector<Function *> functions) {Q_UNUSED(functions);}
void UnwindHelper::deregisterFunction(Function *function) {Q_UNUSED(function);}
void UnwindHelper::deregisterFunctions(QVector<Function *> functions) {Q_UNUSED(functions);}
#endif // USE_NULL_HELPER

Enable DW2 unwind helper on MacOS.

Enable DW2 unwind helper on MacOS.

Change-Id: I1c1671d0b3953ce2e8f57bbf68023731470e3da1
Reviewed-by: Simon Hausmann <a975102812d593b3191088e3d0aeaeb6f11dbcf5@digia.com>


#include <cstdlib>

extern "C" void __cxa_pure_virtual()
{
}

void* operator new(size_t size)
{
	return malloc(size);
}

void* operator new[](size_t size)
{
	return malloc(size);
}

void operator delete(void *ptr)
{
	free(ptr);
}

void operator delete[](void *ptr)
{
	free(ptr);
}

#include <os/Board.h>

#include <cstdio>
#include <cstdlib>

extern "C" void __cxa_pure_virtual()
{
	printf("__cxa_pure_virtual() called.  Probably a bad build.\n");
	os::board::shutdown();
}

void* operator new(size_t size)
{
	return malloc(size);
}

void* operator new[](size_t size)
{
	return malloc(size);
}

void operator delete(void *ptr)
{
	free(ptr);
}

void operator delete[](void *ptr)
{
	free(ptr);
}

Add a basic implementation for __cxa_pure_virtual


#include <GL/glew.h>
#include "editor.h"
#include <util.h>

#include <QtWidgets/QApplication>

int main(int argc, char *argv[]) {
	freopen(util::savePath("editor_log.txt").c_str(), "a", stderr);
	QApplication a(argc, argv);
	Editor w;
	w.show();
	return a.exec();
}

#include <GL/glew.h>
#include "editor.h"
#include <util.h>

#include <QtWidgets/QApplication>

int main(int argc, char *argv[]) {
	freopen(util::savePath("editor_log.txt").c_str(), "a", stderr);
	util::logWithTime("Editor started");
	QApplication a(argc, argv);
	Editor w;
	w.show();
	int result = a.exec();
	util::logWithTime("Editor ended");
	return result;
}

Add started and ended timestamps

Add started and ended timestamps

Add "Editor started" and "Editor ended" timestamps to editor log.


#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>

int main(int argc, char* argv[])
{
    using namespace std;

    vector<string> cmdlineargs(argv+1, argv+argc);

    for(auto rbiterv=cmdlineargs.rbegin(); rbiterv != cmdlineargs.rend(); ++rbiterv) {
        auto& arg = *rbiterv;

        for(auto rbiterarg = arg.rbegin(); rbiterarg != arg.rend(); ++rbiterarg) {
            cout << *rbiterarg;
        }

        cout << endl;
    }

    return EXIT_SUCCESS;
}

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>

int main(int argc, char* argv[])
{
    using namespace std;

    vector<string> cmdlineargs {argv+1, argv+argc};

    for(auto rbiterv=cmdlineargs.rbegin(); rbiterv != cmdlineargs.rend(); ++rbiterv) {
        auto& arg = *rbiterv;

        for(auto rbiterarg = arg.rbegin(); rbiterarg != arg.rend(); ++rbiterarg) {
            cout << *rbiterarg;
        }

        cout << endl;
    }

    return EXIT_SUCCESS;
}

Use initializer list syntax to construct the vector of strings


// Copyright 2013 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 "data_fetcher_shared_memory.h"

#include "base/logging.h"
#include "data_fetcher_impl_android.h"

namespace content {

DataFetcherSharedMemory::~DataFetcherSharedMemory() {
  if (started_)
    StopFetchingDeviceMotionData();
}

bool DataFetcherSharedMemory::NeedsPolling() {
  return false;
}

bool DataFetcherSharedMemory::FetchDeviceMotionDataIntoBuffer() {
  NOTREACHED();
  return false;
}

bool DataFetcherSharedMemory::StartFetchingDeviceMotionData(
    DeviceMotionHardwareBuffer* buffer) {
  DCHECK(buffer);
  device_motion_buffer_ = buffer;
  return DataFetcherImplAndroid::GetInstance()->
      StartFetchingDeviceMotionData(buffer);
  started_ = true;
}

void DataFetcherSharedMemory::StopFetchingDeviceMotionData() {
  DataFetcherImplAndroid::GetInstance()->StopFetchingDeviceMotionData();
  started_ = false;
}

}  // namespace content

// Copyright 2013 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 "data_fetcher_shared_memory.h"

#include "base/logging.h"
#include "data_fetcher_impl_android.h"

namespace content {

DataFetcherSharedMemory::~DataFetcherSharedMemory() {
  if (started_)
    StopFetchingDeviceMotionData();
}

bool DataFetcherSharedMemory::NeedsPolling() {
  return false;
}

bool DataFetcherSharedMemory::FetchDeviceMotionDataIntoBuffer() {
  NOTREACHED();
  return false;
}

bool DataFetcherSharedMemory::StartFetchingDeviceMotionData(
    DeviceMotionHardwareBuffer* buffer) {
  DCHECK(buffer);
  device_motion_buffer_ = buffer;
  started_ = DataFetcherImplAndroid::GetInstance()->
      StartFetchingDeviceMotionData(buffer);
  return started_;
}

void DataFetcherSharedMemory::StopFetchingDeviceMotionData() {
  DataFetcherImplAndroid::GetInstance()->StopFetchingDeviceMotionData();
  started_ = false;
}

}  // namespace content

Fix |started_| variable for Device Motion Android data fetcher.

Ensure proper stopping of sensors upon fetcher destruction.

BUG=

Review URL: https://chromiumcodereview.appspot.com/22336011

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@216522 0039d316-1c4b-4281-b951-d872f2087c98


#include <chrono>
#include <thread>

#include "AudioSubsystem.h"
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "Decoders/WAV/WAVDataProvider.h"
#include "Utils.h"

int main( int argc, char* argv[] )
{
	const char* FileName = ( argc > 1 ) ? argv[1] : "test.wav";

	auto AudioSubsystem = CreateAudioSubsystem_OpenAL();

	AudioSubsystem->Start();

	auto TestBlob = ReadFileAsBlob( FileName );
	auto Provider = CreateWaveDataProvider( FileName, TestBlob );
	auto Source = AudioSubsystem->CreateAudioSource();
	Source->BindDataProvider( Provider );
	Source->Play();

	while ( Source->IsPlaying() && !IsKeyPressed() );

	std::this_thread::sleep_for( std::chrono::milliseconds(300) );

	Source = nullptr;

	AudioSubsystem->Stop();

	return 0;
};

#include <chrono>
#include <thread>

#include "AudioSubsystem.h"
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "Decoders/WAV/WAVDataProvider.h"
#include "Utils.h"

int main( int argc, char* argv[] )
{
	const char* FileName = ( argc > 1 ) ? argv[1] : "test.wav";

	auto AudioSubsystem = CreateAudioSubsystem_OpenAL();

	AudioSubsystem->Start();

	auto TestBlob = ReadFileAsBlob( FileName );
	auto Provider = CreateWaveDataProvider( FileName, TestBlob );
	auto Source = AudioSubsystem->CreateAudioSource();
	Source->BindDataProvider( Provider );
	Source->Play();

	while ( Source->IsPlaying() && !IsKeyPressed() );

	std::this_thread::sleep_for( std::chrono::milliseconds(300) );

	Source->Stop();
	Source = nullptr;

	AudioSubsystem->Stop();

	return 0;
};

Stop the source before exit

Stop the source before exit


#include "CurlHandle.h"

#include <curl/curl.h>

namespace embeddedmz {

CurlHandle::CurlHandle() { curl_global_init(CURL_GLOBAL_ALL); }

CurlHandle::~CurlHandle() { curl_global_cleanup(); }

CurlHandle &CurlHandle::instance() {
  static CurlHandle inst{};
  return inst;
}

} // namespace embeddedmz

#include "CurlHandle.h"

#include <curl/curl.h>
#include <stdexcept>

namespace embeddedmz {

CurlHandle::CurlHandle() {
  const auto eCode = curl_global_init(CURL_GLOBAL_ALL);
  if (eCode != CURLE_OK) {
    throw std::runtime_error{"Error initializing libCURL"};
  }
}

CurlHandle::~CurlHandle() { curl_global_cleanup(); }

CurlHandle &CurlHandle::instance() {
  static CurlHandle inst{};
  return inst;
}

} // namespace embeddedmz

Check error code on curl_init

Check error code on curl_init


#include "qmljscodestylesettingsfactory.h"
#include "qmljscodestylesettingspage.h"
#include "qmljstoolsconstants.h"
#include <texteditor/tabpreferences.h>
#include <texteditor/tabsettings.h>
#include <QtGui/QLayout>

using namespace QmlJSTools;

QmlJSCodeStylePreferencesFactory::QmlJSCodeStylePreferencesFactory()
{
}

QString QmlJSCodeStylePreferencesFactory::languageId()
{
    return Constants::QML_JS_SETTINGS_ID;
}

QString QmlJSCodeStylePreferencesFactory::displayName()
{
    return Constants::QML_JS_SETTINGS_NAME;
}

TextEditor::IFallbackPreferences *QmlJSCodeStylePreferencesFactory::createPreferences(
    const QList<TextEditor::IFallbackPreferences *> &fallbacks) const
{
    return 0;
}

QWidget *QmlJSCodeStylePreferencesFactory::createEditor(TextEditor::IFallbackPreferences *preferences,
                                                           TextEditor::TabPreferences *tabPreferences,
                                                           QWidget *parent) const
{
    Q_UNUSED(preferences)

    Internal::QmlJSCodeStylePreferencesWidget *widget = new Internal::QmlJSCodeStylePreferencesWidget(parent);
    widget->layout()->setMargin(0);
    widget->setTabPreferences(tabPreferences);
    return widget;
}

#include "qmljscodestylesettingsfactory.h"
#include "qmljscodestylesettingspage.h"
#include "qmljstoolsconstants.h"
#include <texteditor/tabpreferences.h>
#include <texteditor/tabsettings.h>
#include <QtGui/QLayout>

using namespace QmlJSTools;

QmlJSCodeStylePreferencesFactory::QmlJSCodeStylePreferencesFactory()
{
}

QString QmlJSCodeStylePreferencesFactory::languageId()
{
    return Constants::QML_JS_SETTINGS_ID;
}

QString QmlJSCodeStylePreferencesFactory::displayName()
{
    return Constants::QML_JS_SETTINGS_NAME;
}

TextEditor::IFallbackPreferences *QmlJSCodeStylePreferencesFactory::createPreferences(
    const QList<TextEditor::IFallbackPreferences *> &fallbacks) const
{
    Q_UNUSED(fallbacks);
    return 0;
}

QWidget *QmlJSCodeStylePreferencesFactory::createEditor(TextEditor::IFallbackPreferences *preferences,
                                                           TextEditor::TabPreferences *tabPreferences,
                                                           QWidget *parent) const
{
    Q_UNUSED(preferences)

    Internal::QmlJSCodeStylePreferencesWidget *widget = new Internal::QmlJSCodeStylePreferencesWidget(parent);
    widget->layout()->setMargin(0);
    widget->setTabPreferences(tabPreferences);
    return widget;
}

Fix warning about unused parameter

Fix warning about unused parameter

Change-Id: I2844ebae2cd834b187f01b62d414692aa29b0605
Reviewed-on: http://codereview.qt.nokia.com/354
Reviewed-by: Qt Sanity Bot <5581206bb7e0307f0d99eb71898ae6b694149ca5@ovi.com>
Reviewed-by: Jarek Kobus <021d51876099fe64879cc5072886d1d0ff71e1ac@nokia.com>


#include "Wall.h"

Wall::Wall(Vector b, Vector t) :
	b_(b),
	t_(t)
{

}

bool Wall::OnLeft(Vector p) {
	return (p.i < b_.i);
}

bool Wall::Between(Vector p) {
	return (p.j < t_.j) && (p.j > b_.j);
}

float Wall::Left() {
	return b_.i - 0.1;
}

float Wall::Right() {
	return b_.i + 0.1;
}

void Wall::Draw() {
	glColor3f(0, 0, 0);

	glBegin(GL_LINES);
		glVertex2f(b_.i, b_.j);
		glVertex2f(t_.i, t_.j);
	glEnd();
}

#include "Wall.h"

Wall::Wall(Vector b, Vector t) :
	b_(b),
	t_(t)
{

}

bool Wall::OnLeft(Vector p) {
	return (p.i < b_.i);
}

bool Wall::Between(Vector p) {
	return (p.j < t_.j) && (p.j > b_.j);
}

float Wall::Left() {
	return b_.i - 0.1;
}

float Wall::Right() {
	return b_.i + 0.1;
}

void Wall::Draw() {
	glColor3f(0, 0, 0);

	glBegin(GL_LINES);
		glVertex2f(b_.i, b_.j);
		glVertex2f(b_.i, t_.j);
	glEnd();
}

Make walls draw what they actually do

Make walls draw what they actually do


#include "board.h"
#include <aery32/all.h>

using namespace aery;

#define UART0_PINMASK ((1 << 0) | (1 << 1))

int main(void)
{
	init_board();
	gpio_init_pins(porta, UART0_PINMASK, GPIO_FUNCTION_A);

	gpio_set_pin_high(LED);

	/*
	 * Initializes USART0 in async mode with 8 data bits, 1 stop bit
	 * and no parity. After then sets up baud rate to 115200 bit/s
	 * (error 0.8%) and enables rx/tx.
	 */
	usart_init_serial(usart0);
	usart_setup_speed(usart0, USART_CLK_PBA, 71);
	usart_enable_rx(usart0);
	usart_enable_tx(usart0);

	#define BUFSIZE 100
	char buf[BUFSIZE] = "";

	for(;;) {
		usart_puts(usart0, "in: ");
		usart_gets(usart0, buf, BUFSIZE);

		usart_puts(usart0, "\r\nout: ");
		usart_puts(usart0, buf);
		usart_puts(usart0, "\r\n\n");
	}

	return 0;
}

#include "board.h"
#include <aery32/all.h>

using namespace aery;

int main(void)
{
	init_board();

	/*
	 * In UC3A:
	 * PA00 => RXD
	 * PA01 => TXD
	 */
	#define UART0_SERIAL_PINMASK (0x1)
	gpio_init_pins(porta, UART0_SERIAL_PINMASK, GPIO_FUNCTION_A);

	/*
	 * Initializes USART0 in async mode with 8 data bits, 1 stop bit
	 * and no parity. After then sets up baud rate to 115200 bit/s
	 * (error 0.8%) and enables rx/tx.
	 *
	 * Baud rate divider has been selected in assumption that
	 * F_PBA is 66 MHz.
	 */
	usart_init_serial(usart0);
	usart_setup_speed(usart0, USART_CLK_PBA, 71);
	usart_enable_rx(usart0);
	usart_enable_tx(usart0);

	gpio_set_pin_high(LED);

	#define BUFSIZE 100
	char buf[BUFSIZE] = "";

	for(;;) {
		usart_puts(usart0, "in: ");
		usart_gets(usart0, buf, BUFSIZE);

		usart_puts(usart0, "\r\nout: ");
		usart_puts(usart0, buf);
		usart_puts(usart0, "\r\n\n");
	}

	return 0;
}

Add more commenting to serial echo example


#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>

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

  QQmlEngine engine;
  QQmlContext *objectContext = new QQmlContext(engine.rootContext());

  QQmlComponent component(&engine, "main.qml");
  QObject *object = component.create(objectContext);

  // ... delete object and objectContext when necessary

  return app.exec();
}

#include <QGuiApplication>
#include <QQuickView>

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

  QQuickView view;
  view.setSource(QUrl::fromLocalFile("main.qml"));
  view.show();

  return app.exec();
}

Use QQuickView instead of QQmlEngine.

Use QQuickView instead of QQmlEngine.


#include <catch.hpp>
#include "../wold.hpp"

namespace wold {

  TEST_CASE("foo", "[]") {
    REQUIRE(foo() == 42);
  }

} // namespace wold

#include <catch.hpp>
#include "../wold.hpp"

#include <boost/spirit/home/x3.hpp>
#include <iostream>

namespace wold {

  TEST_CASE("foo", "[]") {
    REQUIRE(foo() == 42);
  }

  TEST_CASE("parsing", "[]") {
    using boost::spirit::x3::double_;
    using boost::spirit::x3::ascii::space;

    auto text = std::string("  val 12.3 ");
    double result;
    auto success = boost::spirit::x3::phrase_parse(
        text.begin(), text.end(),
        "val" >> double_,
        space,
        result);

    REQUIRE(success);
    std::cout << result << "\n";
  }

} // namespace wold

Add basic x3 parsing demo test

Add basic x3 parsing demo test


#include <iostream>

using namespace std;

int main() {
  cout << "Hello, world!" << endl;
}

#include <iostream>
#include <chrono>
#include <thread>
#include <string>
#include <fstream>
#include <sstream>

const std::string NETWORK_IF = "eth0";

using namespace std;

int main() {
  while (true) {
    // Get current point in time as reference
    const auto now = std::chrono::steady_clock::now();
    const auto date = std::chrono::duration_cast<std::chrono::microseconds>(
        now.time_since_epoch()).count();

    // Read CPU load information
    long long int user = 0;
    long long int nice = 0;
    long long int system = 0;
    long long int idle = 0;
    long long int iowait = 0;
    long long int irq = 0;
    long long int softirq = 0;
    long long int steal = 0;
    long long int guest = 0;
    long long int guest_nice = 0;
    {
      ifstream in("/proc/stat");
      string line;
      getline(in, line);
      istringstream l(line);
      string dump;
      l >> dump;
      l >> user;
      l >> nice;
      l >> system;
      l >> idle;
      l >> iowait;
      l >> irq;
      l >> softirq;
      l >> steal;
      l >> guest;
      l >> guest_nice;
    }

    // Bytes received/sent on NETWORK_IF
    long long int bytes_recv = 0;
    long long int bytes_send = 0;
    {
      ifstream in("/proc/net/dev");
      for (string line; getline(in, line); ) {
        istringstream l(line);
        string interface;
        l >> interface;
        if (interface == NETWORK_IF + ":") {
          l >> bytes_recv;
          for (int i = 0; i < 8; i++) {
            l >> bytes_send;
          }
        }
      }
    }

    cout << date
         << " " << bytes_recv << " " << bytes_send
         << " " << user << " " << nice << " " << system << " " << idle
         << " " << iowait << " " << irq << " " << softirq
         << " " << steal << " " << guest << " " << guest_nice
         << endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }
}

Add code to print cpu load information and bytes sent/received


#include "graphics/texture.h"
#include "graphics/opengl.h"

namespace sp {

void BasicTexture::setRepeated(bool)
{

}

void BasicTexture::setSmooth(bool value)
{
    smooth = value;
}

void BasicTexture::loadFromImage(Image&& image)
{
    this->image = std::move(image);
}

void BasicTexture::bind()
{
    if (handle == 0)
    {
        glGenTextures(1, &handle);
        glBindTexture(GL_TEXTURE_2D, handle);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smooth ? GL_LINEAR : GL_NEAREST);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPtr());
    }

    glBindTexture(GL_TEXTURE_2D, handle);
}

}

#include "graphics/texture.h"
#include "graphics/opengl.h"

namespace sp {

void BasicTexture::setRepeated(bool)
{

}

void BasicTexture::setSmooth(bool value)
{
    smooth = value;
}

void BasicTexture::loadFromImage(Image&& image)
{
    this->image = std::move(image);
}

void BasicTexture::bind()
{
    if (handle == 0)
    {
        glGenTextures(1, &handle);
        glBindTexture(GL_TEXTURE_2D, handle);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smooth ? GL_LINEAR : GL_NEAREST);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPtr());

        image = {};
    }

    glBindTexture(GL_TEXTURE_2D, handle);
}

}

Clear image after GPU upload.

Clear image after GPU upload.


/*
 *  AvanceDB - an in-memory database similar to Apache CouchDB
 *  Copyright (C) 2015-2017 Ripcord Software
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "set_thread_name.h"

#if __GNUG__ && not defined(__clang__)
#include <pthread.h>

bool SetThreadName::Set(std::thread& thread, const char* name) {
    auto status = ::pthread_setname_np(thread.native_handle(), name) == 0;
    return status;
}

bool SetThreadName::Set(const char* name) {
    auto status = pthread_setname_np(::pthread_self(), name) == 0;
    return status;
}
#else
bool SetThreadName::Set(std::thread&, const char*) {
    return false;
}

bool SetThreadName::Set(const char*) {
    return false;
}
#endif

/*
 *  AvanceDB - an in-memory database similar to Apache CouchDB
 *  Copyright (C) 2015-2017 Ripcord Software
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "set_thread_name.h"

#if __GNUG__ && !defined(__clang__)
#include <pthread.h>

bool SetThreadName::Set(std::thread& thread, const char* name) {
    auto status = ::pthread_setname_np(thread.native_handle(), name) == 0;
    return status;
}

bool SetThreadName::Set(const char* name) {
    auto status = pthread_setname_np(::pthread_self(), name) == 0;
    return status;
}
#else
bool SetThreadName::Set(std::thread&, const char*) {
    return false;
}

bool SetThreadName::Set(const char*) {
    return false;
}
#endif

Correct the set thread name macro

Correct the set thread name macro