#include "SetOutputPacket.h"

IPOCS::SetOutputPacket::SetOutputPacket()
{
  this->RNID_PACKET = 13;
}

IPOCS::Packet* IPOCS::SetOutputPacket::create()
{
  return new IPOCS::SetOutputPacket();
}

uint8_t IPOCS::SetOutputPacket::parseSpecific(uint8_t buffer[])
{
  this->RQ_OUTPUT_COMMAND = (SetOutputPacket::E_RQ_OUTPUT_COMMAND)buffer[0];
  this->RT_DURATION = (buffer[1] << 8) + buffer[2];
  return 3;
}

uint8_t IPOCS::SetOutputPacket::serializeSpecific(uint8_t buffer[])
{
  buffer[0] = this->RQ_OUTPUT_COMMAND;
  buffer[1] = this->RT_DURATION >> 8;
  buffer[2] = this->RT_DURATION & 0x100;
  return 3;
}

__attribute__((constructor))
static void initialize_packet_throwpoints() {
  IPOCS::Packet::registerCreator(13, &IPOCS::SetOutputPacket::create);
}

#include "SetOutputPacket.h"

IPOCS::SetOutputPacket::SetOutputPacket()
{
  this->RNID_PACKET = 13;
}

IPOCS::Packet* IPOCS::SetOutputPacket::create()
{
  return new IPOCS::SetOutputPacket();
}

uint8_t IPOCS::SetOutputPacket::parseSpecific(uint8_t buffer[])
{
  this->RQ_OUTPUT_COMMAND = (SetOutputPacket::E_RQ_OUTPUT_COMMAND)buffer[0];
  this->RT_DURATION = (buffer[1] << 8) + buffer[2];
  return 3;
}

uint8_t IPOCS::SetOutputPacket::serializeSpecific(uint8_t buffer[])
{
  buffer[0] = this->RQ_OUTPUT_COMMAND;
  buffer[1] = this->RT_DURATION >> 8;
  buffer[2] = this->RT_DURATION & 0xFF;
  return 3;
}

__attribute__((constructor))
static void initialize_packet_throwpoints() {
  IPOCS::Packet::registerCreator(13, &IPOCS::SetOutputPacket::create);
}

Fix set order serialization bug


/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2013 Razor team
 * Authors:
 *   Kuzma Shapran <kuzma.shapran@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <lxqt/lxqtapplication.h>
#include "lxqttranslate.h"

#include "main_window.h"

int main(int argc, char *argv[])
{
    LxQt::Application a(argc, argv);
    TRANSLATE_APP;

    MainWindow w;
    w.show();

    return a.exec();
}

/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2013 Razor team
 * Authors:
 *   Kuzma Shapran <kuzma.shapran@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <LXQt/Application>
#include "lxqttranslate.h"

#include "main_window.h"

int main(int argc, char *argv[])
{
    LxQt::Application a(argc, argv);
    TRANSLATE_APP;

    MainWindow w;
    w.show();

    return a.exec();
}

Use new LXQt header files.


/* Copyright (c) 2013-2019 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "RotatedHeaderView.h"

#include <QPainter>

using namespace QGBA;

RotatedHeaderView::RotatedHeaderView(Qt::Orientation orientation, QWidget* parent)
	: QHeaderView(orientation, parent)
{
}

void RotatedHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const {
	painter->save();
	painter->translate(rect.x() + rect.width(), rect.y());
	painter->rotate(90);
	QHeaderView::paintSection(painter, QRect(0, 0, rect.height(), rect.width()), logicalIndex);
	painter->restore();
}

QSize RotatedHeaderView::sectionSizeFromContents(int logicalIndex) const {
	return QHeaderView::sectionSizeFromContents(logicalIndex).transposed();
}

/* Copyright (c) 2013-2019 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "RotatedHeaderView.h"

#include <QPainter>

using namespace QGBA;

RotatedHeaderView::RotatedHeaderView(Qt::Orientation orientation, QWidget* parent)
	: QHeaderView(orientation, parent)
{
	int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, 0, this);
	setMinimumSectionSize(fontMetrics().height() + margin);
}

void RotatedHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const {
	painter->save();
	painter->translate(rect.x() + rect.width(), rect.y());
	painter->rotate(90);
	QHeaderView::paintSection(painter, QRect(0, 0, rect.height(), rect.width()), logicalIndex);
	painter->restore();
}

QSize RotatedHeaderView::sectionSizeFromContents(int logicalIndex) const {
	return QHeaderView::sectionSizeFromContents(logicalIndex).transposed();
}

Fix logging config section width


// 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 "chromeos/system/devicetype.h"

#include <string>

#include "base/sys_info.h"

namespace chromeos {

namespace {
const char kDeviceType[] = "CHROMEOS_DEVICE_TYPE";
}

DeviceType GetDeviceType() {
  std::string value;
  if (base::SysInfo::GetLsbReleaseValue(kDeviceType, &value)) {
    if (value == "CHROMEBASE")
      return DeviceType::kChromebase;
    else if (value == "CHROMEBIT")
      return DeviceType::kChromebit;
    // Most devices are Chromebooks, so we will also consider reference boards
    // as chromebooks.
    else if (value == "CHROMEBOOK" || value == "REFERENCE")
      return DeviceType::kChromebook;
    else if (value == "CHROMEBOX")
      return DeviceType::kChromebox;
    else
      LOG(ERROR) << "Unknown device type \"" << value << "\"";
  }

  return DeviceType::kUnknown;
}

}  // namespace chromeos

// 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 "chromeos/system/devicetype.h"

#include <string>

#include "base/sys_info.h"

namespace chromeos {

namespace {
const char kDeviceType[] = "DEVICETYPE";
}

DeviceType GetDeviceType() {
  std::string value;
  if (base::SysInfo::GetLsbReleaseValue(kDeviceType, &value)) {
    if (value == "CHROMEBASE")
      return DeviceType::kChromebase;
    else if (value == "CHROMEBIT")
      return DeviceType::kChromebit;
    // Most devices are Chromebooks, so we will also consider reference boards
    // as chromebooks.
    else if (value == "CHROMEBOOK" || value == "REFERENCE")
      return DeviceType::kChromebook;
    else if (value == "CHROMEBOX")
      return DeviceType::kChromebox;
    else
      LOG(ERROR) << "Unknown device type \"" << value << "\"";
  }

  return DeviceType::kUnknown;
}

}  // namespace chromeos

Use the correct lsb key when fetching the CrOS device type.


#include "Mocks.hpp"

namespace testing {

enum level : std::uint8_t { debug, info, warn, error };

} // namespace testing

namespace blackhole { namespace sink {

template<>
struct priority_traits<testing::level> {
    static inline
    priority_t map(testing::level lvl) {
        switch (lvl) {
        case testing::level::debug:
            return priority_t::debug;
        case testing::level::info:
            return priority_t::info;
        case testing::level::warn:
            return priority_t::warning;
        case testing::level::error:
            return priority_t::err;
        }
    }
};

} } // namespace blackhole::sink

TEST(Functional, SyslogConfiguredVerboseLogger) {
    verbose_logger_t<testing::level> log;

    typedef formatter::string_t formatter_type;
    typedef sink::syslog_t<testing::level> sink_type;

    auto formatter = std::make_unique<formatter_type>("%(message)s [%(...L)s]");
    auto sink = std::make_unique<sink_type>("testing");
    auto frontend = std::make_unique<frontend_t<formatter_type, sink_type, testing::level>>(std::move(formatter), std::move(sink));
    log.add_frontend(std::move(frontend));

    log::record_t record = log.open_record(level::error);
    if (record.valid()) {
        record.attributes["message"] = { utils::format("Some message from: '%s'!", "Hell") };
        // Add another attributes.
        log.push(std::move(record));
    }
}

#include "Mocks.hpp"

namespace testing {

enum level : std::uint8_t { debug, info, warn, error };

} // namespace testing

namespace blackhole { namespace sink {

template<>
struct priority_traits<testing::level> {
    static inline
    priority_t map(testing::level lvl) {
        switch (lvl) {
        case testing::level::debug:
            return priority_t::debug;
        case testing::level::info:
            return priority_t::info;
        case testing::level::warn:
            return priority_t::warning;
        case testing::level::error:
            return priority_t::err;
        }
    }
};

} } // namespace blackhole::sink

TEST(Functional, SyslogConfiguredVerboseLogger) {
    verbose_logger_t<testing::level> log;

    typedef formatter::string_t formatter_type;
    typedef sink::syslog_t<testing::level> sink_type;

    auto formatter = std::make_unique<formatter_type>("%(message)s [%(...L)s]");
    auto sink = std::make_unique<sink_type>("testing");
    auto frontend = std::make_unique<frontend_t<formatter_type, sink_type, testing::level>>(std::move(formatter), std::move(sink));
    log.add_frontend(std::move(frontend));

    log::record_t record = log.open_record(level::error);
    if (record.valid()) {
        record.attributes["message"] = { utils::format("Some message from: '%s'!", "Hell"), log::attribute::scope::event };
        log.push(std::move(record));
    }
}

Fix message scope level for functional test.


#include "devicethread.h"

DeviceThread::DeviceThread()
{
  exit = false;
}

void DeviceThread::finish()
{
  exit = true;
}

DeviceThread::run()
{
  int ret;
  while(!exit)
  {
    if(!board.isConnected())
    {
      ret = board.attachDevice();
      if(ret < 0)
      {
        //Failed to attach
        wait(3000);
        notConnected();
        continue;
      }
      else
        connected();
    }

    //Connected, do actual work in this thread...

    //Update status
    getBacklightState();

    //Process command queue
    while(!cmd.isEmpty())
    {
      Command_t c = cmd.dequeue();
      if(!IS_GET(c.cmd))
        board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3);
      else
      {
        //TODO:
      }
    }

    //Wait for some time period. Number chosen at random as prime.
    wait(635);
  }
}

void DeviceThread::enqueue(const Command_t & c)
{
  cmd.enqueue(c);
}

#include "devicethread.h"

DeviceThread::DeviceThread()
{
  exit = false;
}

void DeviceThread::finish()
{
  exit = true;
}

DeviceThread::run()
{
  int ret;
  while(!exit)
  {
    if(!board.isConnected())
    {
      ret = board.attachDevice();
      if(ret < 0)
      {
        //Failed to attach
        wait(3000);
        notConnected();
        continue;
      }
      else
        connected();
    }

    //Connected, do actual work in this thread...

    //Update status
    getBacklightState();

    //Process command queue
    while(!cmd.isEmpty())
    {
      Command_t c = cmd.dequeue();
      if(!IS_GET(c.cmd))
        board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3);
      else
      {
        uint8_t buf[EP_LEN];
        board.sendCmd(c.cmd, c.arg1, c.arg2, c.arg3, &buf);
        if(buf[0] == CMD_RES && buf[1] == CMD_BL_GET_STATE)
          emit(backlightResponse(buf[2], buf[3]));
      }
    }

    //Wait for some time period. Number chosen at random as prime.
    wait(635);
  }
}

void DeviceThread::enqueue(const Command_t & c)
{
  cmd.enqueue(c);
}

Handle get command response parsin


// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>

#if defined(__FreeBSD__)
// The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
// that, it was never implemented.  So just define it to zero.
#undef  MAP_NORESERVE
#define MAP_NORESERVE 0
#endif

int main() {
#ifdef __x86_64__
  const size_t kLog2Size = 39;
#elif defined(__mips64) || defined(__aarch64__)
  const size_t kLog2Size = 32;
#endif
  const uintptr_t kLocation = 0x40ULL << kLog2Size;
  void *p = mmap(
      reinterpret_cast<void*>(kLocation),
      1ULL << kLog2Size,
      PROT_READ|PROT_WRITE,
      MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
      -1, 0);
  fprintf(stderr, "DONE %p %d\n", p, errno);
  return p == MAP_FAILED;
}

// CHECK: DONE

// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>

#if defined(__FreeBSD__)
// The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
// that, it was never implemented.  So just define it to zero.
#undef  MAP_NORESERVE
#define MAP_NORESERVE 0
#endif

int main() {
#ifdef __x86_64__
  const size_t kLog2Size = 39;
#elif defined(__mips64) || defined(__aarch64__)
  const size_t kLog2Size = 32;
#endif
  const uintptr_t kLocation = 0x40ULL << kLog2Size;
  void *p = mmap(
      reinterpret_cast<void*>(kLocation),
      1ULL << kLog2Size,
      PROT_READ|PROT_WRITE,
      MAP_PRIVATE|MAP_ANON|MAP_NORESERVE,
      -1, 0);
  fprintf(stderr, "DONE %p %d\n", p, errno);
  return p == MAP_FAILED;
}

// CHECK: DONE

Use MAP_ANON instead of MAP_ANONYMOUS


#include <hal.h>

#include <pwm_config.hpp>

PWMDriver *pwmPlatformInit(void) {
  pwmStart(&PWMD8, &motor_pwm_config);
  palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4));
  return &PWMD8;
}

// TODO(yoos): process multiple drivers
void pwmPlatformSet(uint8_t ch, float dc) {
  pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000);
  pwmEnableChannel(&PWMD8, ch, width);
}

#include <hal.h>

#include <pwm_config.hpp>

PWMDriver *pwmPlatformInit(void) {
  pwmStart(&PWMD8, &motor_pwm_config);
  palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4));
  return &PWMD8;
}

// TODO(yoos): process multiple drivers
void pwmPlatformSet(uint8_t ch, float dc) {
  pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f);
  pwmEnableChannel(&PWMD8, ch, width);
}

Use `f` suffix on floating point numbers.


// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/auto_tuple.h>
#include <string>

class TupleTest:
  public testing::Test
{};

TEST_F(TupleTest, CallTest) {
  autowiring::tuple<int, int, std::string> t(101, 102, "Hello world!");

  ASSERT_EQ(101, autowiring::get<0>(t)) << "First tuple value was invalid";
  ASSERT_EQ(102, autowiring::get<1>(t)) << "Second tuple value was invalid";
}

TEST_F(TupleTest, TieTest) {
  std::unique_ptr<int> val(new int(22));

  autowiring::tuple<std::unique_ptr<int>&> tup(val);
  ASSERT_EQ(22, *autowiring::get<0>(tup)) << "Tied tuple did not retrieve the expected value";
}

TEST_F(TupleTest, AddressTest) {
  autowiring::tuple<std::unique_ptr<int>> tup;
  std::unique_ptr<int>& v = autowiring::get<0>(tup);

  ASSERT_EQ(&tup.value, &v) << "Get operation did not provide a correct reference to the underlying tuple value";
}

Add a test to verify get's return value behavior


// Tests -fsanitize-coverage=inline-8bit-counters
//
// REQUIRES: has_sancovcc,stable-runtime
// UNSUPPORTED: i386-darwin, x86_64-darwin, x86_64h-darwin
//
// RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1

#include <stdio.h>
#include <assert.h>

const char *first_counter;

extern "C"
void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) {
  printf("INIT: %p %p\n", start, end);
  assert(end - start > 1);
  first_counter = start;
}

int main() {
  assert(first_counter);
  assert(*first_counter == 1);
}

// Tests -fsanitize-coverage=inline-8bit-counters
//
// REQUIRES: has_sancovcc,stable-runtime
// UNSUPPORTED: i386-darwin
//
// RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters 2>&1

#include <stdio.h>
#include <assert.h>

const char *first_counter;

extern "C"
void __sanitizer_cov_8bit_counters_init(const char *start, const char *end) {
  printf("INIT: %p %p\n", start, end);
  assert(end - start > 1);
  first_counter = start;
}

int main() {
  assert(first_counter);
  assert(*first_counter == 1);
}

Stop marking this test as unsupported on Darwin


// Native C++ Libraries
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

// C++ Interpreter Libraries
#include <Console.h>
#include <Varible.h>
#include <Include.h>

using namespace std;

int main()
{
	RESTART:
	string input = "";
	ConsoleOutCheck(input);
	CheckForInt(input);
	CheckForIntAfterMath(input);
	CHECKFORIOSTREAM(input);
	getline(cin, input);
	goto RESTART;
}

// Native C++ Libraries
#include <iostream>
#include <string>
#include <sstream>
#include <vector>

// C++ Interpreter Libraries
#include <Console.h>
#include <Varible.h>
#include <Include.h>

using namespace std;

int main()
{
	cout << "CPP Interpreter v0.1. Here you can type C++ code in the terminal and get instant feedback from it.\n\n\n";
	RESTART:
	cout << "--->";
	string input = "";
	ConsoleOutCheck(input);
	CheckForInt(input);
	CheckForIntAfterMath(input);
	CHECKFORIOSTREAM(input);
	getline(cin, input);
	goto RESTART;
}

Add a message on the start of CPP-Interpreter.


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

// <chrono>

// treat_as_floating_point

#include <chrono>
#include <type_traits>

#include "test_macros.h"

template <class T>
void
test()
{
    static_assert((std::is_base_of<std::is_floating_point<T>,
                                   std::chrono::treat_as_floating_point<T> >::value), "");
#if TEST_STD_VER > 14
    static_assert((std::is_base_of<std::is_floating_point<T>,
                                   std::chrono::treat_as_floating_point_v<T> >), "");
#endif
}

struct A {};

int main()
{
    test<int>();
    test<unsigned>();
    test<char>();
    test<bool>();
    test<float>();
    test<double>();
    test<long double>();
    test<A>();
}

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

// <chrono>

// treat_as_floating_point

#include <chrono>
#include <type_traits>

#include "test_macros.h"

template <class T>
void
test()
{
    static_assert((std::is_base_of<std::is_floating_point<T>,
                                   std::chrono::treat_as_floating_point<T> >::value), "");
#if TEST_STD_VER > 14
    static_assert(std::is_floating_point<T>::value ==
                                  std::chrono::treat_as_floating_point_v<T>, "");
#endif
}

struct A {};

int main()
{
    test<int>();
    test<unsigned>();
    test<char>();
    test<bool>();
    test<float>();
    test<double>();
    test<long double>();
    test<A>();
}

Fix bad test that was previously getting ifdef-ed away


// Copyright 2017, Dawid Kurek, <dawikur@gmail.com>

#include "lel.hpp"

#include "gtest/gtest.h"

class sizeof_lambdas_test : public ::testing::Test {
 protected:
  LeL::Placeholder<'x'> _x;
  LeL::Placeholder<'y'> _y;
};

TEST_F(sizeof_lambdas_test, base_placeholder_is_1) {
  ASSERT_EQ(1, sizeof(_x));
}

TEST_F(sizeof_lambdas_test, DISABLED_placeholder_with_one_int_equals_size_of_int) {
  ASSERT_EQ(sizeof(1), sizeof(_x + 1));
}

TEST_F(sizeof_lambdas_test, DISABLED_placeholder_with_two_ints_equals_sizof_to_ints) {
  ASSERT_EQ(sizeof(1) + sizeof(5), sizeof(_x + 1 < 5));
}

TEST_F(sizeof_lambdas_test, DISABLED_multiple_base_placehlder_is_1) {
  ASSERT_EQ(1, sizeof(_x < _y));
}

Add tests on sizeof lambdas


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

struct D;
struct B {
 virtual D& operator = (const D&);
};
struct D : B { D(); virtual void a(); };
void D::a() {}

// CHECK: @_ZTV1D = {{.*}} @_ZN1DaSERKS_
// CHECK: define linkonce_odr {{.*}} @_ZN1DaSERKS_

Tweak test to check for a bit more.


// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s

#include <stdio.h>

char bigchunk[1 << 30];

int main() {
  printf("Hello, world!\n");
  scanf("%s", bigchunk);
// CHECK-NOT: Hello, world!
// CHECK: Shadow memory range interleaves with an existing memory mapping.
// CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range.
// CHECK: Dumping process modules:
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll
}

// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
// REQUIRES: asan-32-bits

#include <stdio.h>

char bigchunk[1 << 30];

int main() {
  printf("Hello, world!\n");
  scanf("%s", bigchunk);
// CHECK-NOT: Hello, world!
// CHECK: Shadow memory range interleaves with an existing memory mapping.
// CHECK: ASan shadow was supposed to be located in the [0x2fff0000-0x{{.*}}ffff] range.
// CHECK: Dumping process modules:
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}shadow_mapping_failure
// CHECK-DAG: 0x{{[0-9a-f]*}}-0x{{[0-9a-f]*}} {{.*}}ntdll.dll
}

Disable irrelevant unittest on win64


#include <UnitTest++.h>

#include "../src/ToJsonWriter.h"

SUITE(ArticleToJsonWriterTests)
{
    TEST(WriteArticleWithoutLinks)
    {
        ToJsonWriter atj;
        Article a("Farm");
        CHECK_EQUAL("{\"Farm\":[]}", atj.convertToJson(&a));
    }

    TEST(WriteArticleWithOneLink)
    {
        ToJsonWriter atj;
        Article a("Farm");
        a.addLink(new Article("Animal"));
        CHECK_EQUAL("{\"Farm\":[\"Animal\"]}", atj.convertToJson(&a));
    }

    TEST(WriteArticleWithMultipleLinks)
    {
        ToJsonWriter atj;
        Article a("Farm");
        a.addLink(new Article("Animal"));
        a.addLink(new Article("Pig"));
        a.addLink(new Article("Equality"));
        CHECK_EQUAL("{\"Farm\":[\"Animal\",\"Pig\",\"Equality\"]}", atj.convertToJson(&a));
    }

    TEST(WriteEmptyArticleCollection)
    {
        ToJsonWriter atj;
        ArticleCollection ac;
        CHECK_EQUAL("{}", atj.convertToJson(ac));
    }

    TEST(WriteArticleCollection_OneArticleWithoutLinks)
    {
        ToJsonWriter atj;
        ArticleCollection ac;
        ac.add(new Article("Foo"));
        CHECK_EQUAL("{\"Foo\":[]}", atj.convertToJson(ac));
    }
}

#include <UnitTest++.h>

#include "../src/ToJsonWriter.h"

SUITE(ArticleToJsonWriterTests)
{
    TEST(WriteArticleWithoutLinks)
    {
        ToJsonWriter atj;
        Article a("Farm");
        CHECK_EQUAL("{\"Farm\":{\"forward_links\":[]}}", atj.convertToJson(&a));
    }

    TEST(WriteArticleWithOneLink)
    {
        ToJsonWriter atj;
        Article a("Farm");
        a.addLink(new Article("Animal"));
        CHECK_EQUAL("{\"Farm\":{\"forward_links\":[\"Animal\"]}}", atj.convertToJson(&a));
    }

    TEST(WriteArticleWithMultipleLinks)
    {
        ToJsonWriter atj;
        Article a("Farm");
        a.addLink(new Article("Animal"));
        a.addLink(new Article("Pig"));
        a.addLink(new Article("Equality"));
        CHECK_EQUAL("{\"Farm\":{\"forward_links\":[\"Animal\",\"Pig\",\"Equality\"]}}", atj.convertToJson(&a));
    }

    TEST(WriteEmptyArticleCollection)
    {
        ToJsonWriter atj;
        ArticleCollection ac;
        CHECK_EQUAL("{}", atj.convertToJson(ac));
    }

    TEST(WriteArticleCollection_OneArticleWithoutLinks)
    {
        ToJsonWriter atj;
        ArticleCollection ac;
        ac.add(new Article("Foo"));
        CHECK_EQUAL("{\"Foo\":{\"forward_links\":[]}}", atj.convertToJson(ac));
    }
}

Change requirements for json writer:


// Chapter 23, Try This 1: replace 333 in example with 10

#include<iostream>
#include<iomanip>

int main()
{
    float x = 1.0/10;
    float sum = 0;
    for (int i = 0; i<10; ++i) sum += x;
    std::cout << std::setprecision(15) << sum << '\n';
}

// Chapter 24, Try This 1: replace 333 in example with 10

#include<iostream>
#include<iomanip>

int main()
{
    float x = 1.0/10;
    float sum = 0;
    for (int i = 0; i<10; ++i) sum += x;
    std::cout << std::setprecision(15) << sum << '\n';
}

Correct typo (23 to 24)


/*
 * auxiliary.cpp - Auxiliary public functions
 *
 *   Copyright 2010 Jesús Torres <jmtorres@ull.es>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <string>
#include <vector>

#include <boost/shared_array.hpp>

#include <cli/auxiliary.hpp>

#include "fileno.hpp"

namespace cli { namespace auxiliary
{

    boost::shared_array<const char*>
    stdVectorStringToArgV(const std::vector<std::string> &strings)
    {
        int length = strings.size();
        boost::shared_array<const char*> argv =
            boost::shared_array<const char*>(new const char*[length]);
        for (int i = 0; i < length; i++) {
            argv[i] = strings[i].c_str();
        }
        return argv;
    }

}}

/*
 * auxiliary.cpp - Auxiliary public functions
 *
 *   Copyright 2010 Jesús Torres <jmtorres@ull.es>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <string>
#include <vector>

#include <boost/shared_array.hpp>

#include <cli/auxiliary.hpp>

#include "fileno.hpp"

namespace cli { namespace auxiliary
{

    boost::shared_array<const char*>
    stdVectorStringToArgV(const std::vector<std::string> &strings)
    {
        int length = strings.size();
        boost::shared_array<const char*> argv =
            boost::shared_array<const char*>(new const char*[length + 1]);
        for (int i = 0; i < length; i++) {
            argv[i] = strings[i].c_str();
        }
        argv[length] = NULL;
        return argv;
    }

}}

Add null at the of argv when converting from std::vector<std:string>


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

#include "SkTypes.h"

#if !defined(__has_feature)
    #define __has_feature(x) 0
#endif

#if __has_feature(address_sanitizer)

extern "C" {

    const char* __lsan_default_suppressions();
    const char* __lsan_default_suppressions() {
        return "leak:libfontconfig\n"       // FontConfig looks like it leaks, but it doesn't.
               "leak:libGL.so\n"            // For NVidia driver.
               "leak:libGLX_nvidia.so\n"    // For NVidia driver.
               "leak:libnvidia-glcore.so\n" // For NVidia driver.
               "leak:__strdup\n"            // An eternal mystery, skia:2916.
               ;
    }

}

#endif

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

#include "SkTypes.h"

#if !defined(__has_feature)
    #define __has_feature(x) 0
#endif

#if __has_feature(address_sanitizer)

extern "C" {

    const char* __lsan_default_suppressions();
    const char* __lsan_default_suppressions() {
        return "leak:libfontconfig\n"       // FontConfig looks like it leaks, but it doesn't.
               "leak:libGL.so\n"            // For NVidia driver.
               "leak:libGLX_nvidia.so\n"    // For NVidia driver.
               "leak:libnvidia-glcore.so\n" // For NVidia driver.
               "leak:libnvidia-tls.so\n"    // For NVidia driver.
               "leak:__strdup\n"            // An eternal mystery, skia:2916.
               ;
    }

}

#endif

Add another NVIDIA LSAN suppression.


Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to replace m by its own transpose." << endl;
cout << "If we do m = m.transpose(), then m becomes:" << endl;
m = m.transpose() * 1;
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m = m.transpose().eval(). Then m becomes" << endl;
m = M;
m = m.transpose().eval();
cout << m << endl << "which is right." << endl;

Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to copy a column into a row." << endl;
cout << "If we do m.col(1) = m.row(0), then m becomes:" << endl;
m.col(1) = m.row(0);
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes" << endl;
m = M;
m.col(1) = m.row(0).eval();
cout << m << endl << "which is right." << endl;

Make snippet run successfully again: the snippet for 'eval' was taking m=m.transpose() as an example of code that needs an explicit call to eval(), but that doesn't work anymore now that we have the clever assert detecting aliasing issues.


#include "mainwindow.hpp"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setApplicationName("KShare");
    a.setOrganizationName("ArsenArsen");
    a.setApplicationVersion("1.0");

    MainWindow w;
    w.show();
    return a.exec();
}

#include "mainwindow.hpp"
#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <stdio.h>

bool verbose = false;

void handler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    switch (type)
    {
    case QtDebugMsg:
        if (verbose)
            fprintf(stdout, "DEBUG %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData());
        break;
    case QtInfoMsg:
        fprintf(stdout, "INFO %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData());
        break;
    case QtWarningMsg:
        fprintf(stderr, "WARN %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData());
        break;
    case QtCriticalMsg:
        fprintf(stderr, "CRIT %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData());
        break;
    case QtFatalMsg:
        fprintf(stderr, "FATAL %s:%s(%d): %s\n", context.file, context.function, context.line, localMsg.constData());
        break;
    }
}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(handler);
    QApplication a(argc, argv);
    a.setApplicationName("KShare");
    a.setOrganizationName("ArsenArsen");
    a.setApplicationVersion("1.0");

    QCommandLineParser parser;
    parser.addHelpOption();

    QCommandLineOption h({ "b", "background" }, "Does not show the main window, starts in tray.");
    QCommandLineOption v({ "v", "verbose" }, "Enables QtDebugMsg outputs");
    parser.addOption(h);
    parser.addOption(v);
    parser.process(a);
    verbose = parser.isSet(v);

    MainWindow w;
    if (!parser.isSet(h)) w.show();
    return a.exec();
}

Add command line options. WE GOING 1.0


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

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

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

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

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

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

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

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

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

Enable ExtensionApiTest.GetViews on all platforms.


/* Copyright (c) 2013-2014 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "GBAApp.h"
#include "Window.h"

#ifdef QT_STATIC
#include <QtPlugin>
#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
Q_IMPORT_PLUGIN(QWindowsAudioPlugin);
#endif
#endif

int main(int argc, char* argv[]) {
	QGBA::GBAApp application(argc, argv);
	return application.exec();
}

/* Copyright (c) 2013-2014 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "GBAApp.h"
#include "Window.h"

#ifdef QT_STATIC
#include <QtPlugin>
#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
#ifdef BUILD_QT_MULTIMEDIA
Q_IMPORT_PLUGIN(QWindowsAudioPlugin);
#endif
#endif
#endif

int main(int argc, char* argv[]) {
	QGBA::GBAApp application(argc, argv);
	return application.exec();
}

Fix Windows build when Qt Multimedia is disabled


#include "OI.h"
#include "Commands/DefaultDrive.h"
#include "Subsystems/Chassis.h"
#include "Misc/ToggleClass.h"

/// Default constructor of the class.
DefaultDrive::DefaultDrive()
{
	Requires(Chassis::GetInstance());
	shifterToggle = new Toggle<bool>(false, true);
}

/// Called just before this Command runs the first time.
void DefaultDrive::Initialize()
{
	Chassis::GetInstance()->ReleaseAngle();
}

//Pass values from joysticks to the Drive subsystem
void DefaultDrive::Execute()
{
	OI* oi = OI::GetInstance();
	double moveSpeed = -oi->gamepad->GetRawAxis(LST_AXS_LJOYSTICKY);
	double turnSpeed = -oi->gamepad->GetRawAxis(LST_AXS_RJOYSTICKX);

	// Only driving manual should require Quadratic inputs. By default it should be turned off
	// Therefore here we turn it on explicitly.
	Chassis::GetInstance()->DriveArcade(moveSpeed, turnSpeed, true);
}

/// Make this return true when this Command no longer needs to run execute().
/// \return always false since this is the default command and should never finish.
bool DefaultDrive::IsFinished()
{
	return false;
}

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

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

#include "OI.h"
#include "Commands/DefaultDrive.h"
#include "Subsystems/Chassis.h"
#include "Misc/ToggleClass.h"

/// Default constructor of the class.
DefaultDrive::DefaultDrive()
{
	Requires(Chassis::GetInstance());
	shifterToggle = new Toggle<bool>(false, true);
}

/// Called just before this Command runs the first time.
void DefaultDrive::Initialize()
{
	Chassis::GetInstance()->ReleaseAngle();
}

//Pass values from joysticks to the Drive subsystem
void DefaultDrive::Execute()
{
	OI* oi = OI::GetInstance();
	double moveSpeed = -oi->stickL->GetY();
	double turnSpeed = -oi->stickR->GetX();

	// Only driving manual should require Quadratic inputs. By default it should be turned off
	// Therefore here we turn it on explicitly.
	Chassis::GetInstance()->DriveArcade(moveSpeed, turnSpeed, true);
}

/// Make this return true when this Command no longer needs to run execute().
/// \return always false since this is the default command and should never finish.
bool DefaultDrive::IsFinished()
{
	return false;
}

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

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

Return to driving on Joysticks


//===========================================
//  Lumina-DE source code
//  Copyright (c) 2015, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "LHomeButton.h"
#include "../../LSession.h"

#include <LuminaX11.h>

LHomeButtonPlugin::LHomeButtonPlugin(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){
  button = new QToolButton(this);
    button->setAutoRaise(true);
    button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);

    connect(button, SIGNAL(clicked()), this, SLOT(showDesktop()));
    this->layout()->setContentsMargins(0,0,0,0);
    this->layout()->addWidget(button);

  QTimer::singleShot(0,this, SLOT(OrientationChange())); //Update icons/sizes
}

LHomeButtonPlugin::~LHomeButtonPlugin(){

}

void LHomeButtonPlugin::updateButtonVisuals(){
  button->setIcon( LXDG::findIcon("go-home", "") );
}

// ========================
//    PRIVATE FUNCTIONS
// ========================
void LHomeButtonPlugin::showDesktop(){
  QList<WId> wins = LSession::handle()->XCB->WindowList();
  for(int i=0; i<wins.length(); i++){
    if( LXCB::INVISIBLE != LSession::handle()->XCB->WindowState(wins[i]) ){
      LSession::handle()->XCB->MinimizeWindow(wins[i]);
    }
  }
}

//===========================================
//  Lumina-DE source code
//  Copyright (c) 2015, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "LHomeButton.h"
#include "../../LSession.h"

#include <LuminaX11.h>

LHomeButtonPlugin::LHomeButtonPlugin(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){
  button = new QToolButton(this);
    button->setAutoRaise(true);
    button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);

    connect(button, SIGNAL(clicked()), this, SLOT(showDesktop()));
    this->layout()->setContentsMargins(0,0,0,0);
    this->layout()->addWidget(button);

  QTimer::singleShot(0,this, SLOT(OrientationChange())); //Update icons/sizes
}

LHomeButtonPlugin::~LHomeButtonPlugin(){

}

void LHomeButtonPlugin::updateButtonVisuals(){
  button->setIcon( LXDG::findIcon("user-desktop", "") );
}

// ========================
//    PRIVATE FUNCTIONS
// ========================
void LHomeButtonPlugin::showDesktop(){
  QList<WId> wins = LSession::handle()->XCB->WindowList();
  for(int i=0; i<wins.length(); i++){
    if( LXCB::INVISIBLE != LSession::handle()->XCB->WindowState(wins[i]) ){
      LSession::handle()->XCB->MinimizeWindow(wins[i]);
    }
  }
}

Change the icon for the "showdesktop" plugin to be an image of the desktop (user-desktop) instead of a house.


/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

#include "BasicListItem.h"

using namespace bb::cascades;

BasicListItem::BasicListItem() {
    item_ = new StandardListItem();
    setRoot(item_);
}

void BasicListItem::setData(QObject* data) {
    updateImage(data->property("leftImage").value<QUrl>());
    updateTitle(data->property("title").toString());
    connect(data, SIGNAL(leftImageChanged(const QUrl&)), SLOT(updateImage(const QUrl&)));
    connect(data, SIGNAL(titleChanged(const QString&)), SLOT(updateTitle(const QString&)));
    data_->disconnect(this);
    data_ = data;
}

void BasicListItem::updateImage(const QUrl& url) {
    item_->setImage(Image(url));
}

void BasicListItem::updateTitle(const QString& title) {
    item_->setTitle(title);
}

/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

#include "BasicListItem.h"

using namespace bb::cascades;

BasicListItem::BasicListItem() {
    item_ = new StandardListItem();
    setRoot(item_);
}

void BasicListItem::setData(QObject* data) {
    updateImage(data->property("leftImage").value<QUrl>());
    updateTitle(data->property("title").toString());
    connect(data, SIGNAL(leftImageChanged(const QUrl&)), SLOT(updateImage(const QUrl&)));
    connect(data, SIGNAL(titleChanged(const QString&)), SLOT(updateTitle(const QString&)));
    data_->disconnect(this);
    data_ = data;
}

void BasicListItem::updateImage(const QUrl& url) {
    if (url.isEmpty()) {
        item_->resetImage();
        return;
    }
    item_->setImage(Image(url));
}

void BasicListItem::updateTitle(const QString& title) {
    item_->setTitle(title);
}

Reset list item image when setting empty URL.


/**
 * @file
 *      sum_two_sales_data.cpp
 * @author
 *      Henrik Samuelsson
 */
#include <iostream>
#include "Sales_item.h"

/**
 * @brief
 *      Reads two sales_item's objects prints the sum.
 * @note
 *      The exercise instructions in the book state that the two objects have
 *      the same ISBN. It is assumed that it is up to the user to enter objects
 *      with the same ISBN, the program will not check this.
 * @return
 *      0 upon correct and completed execution
 */
int main() {
    Sales_item item1, item2;
    std::cin >> item1 >> item2;
    std::cout << item1 + item2;
    return 0;
}

/**
 * @file
 *      sum_two_sales_data.cpp
 * @author
 *      Henrik Samuelsson
 */
#include <iostream>
#include "Sales_item.h"

/**
 * @brief
 *      Reads two sales_item's objects and prints the sum.
 * @note
 *      The exercise instructions in the book state that the two objects have
 *      the same ISBN. It is assumed that it is up to the user to enter objects
 *      with the same ISBN, the program will not check this.
 * @return
 *      0 upon correct and completed execution
 */
int main() {
    Sales_item item1, item2;
    std::cin >> item1 >> item2;
    std::cout << item1 + item2;
    return 0;
}

Edit of comments in 1.21.


#include "../common_includes.h"
#include "blend.h"

using namespace ogles_gpgpu;

const char *BlendProc::fshaderBlendSrc = OG_TO_STR
(
#if defined(OGLES_GPGPU_OPENGLES)
 precision highp float;
#endif

 varying vec2 textureCoordinate;
 varying vec2 textureCoordinate2;

 uniform sampler2D inputImageTexture;
 uniform sampler2D inputImageTexture2;
 uniform float alpha;

 void main()
 {
    vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);
    vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate);
    gl_FragColor = mix(textureColor, textureColor2, alpha);
 });

BlendProc::BlendProc(float alpha) : alpha(alpha)
{

}

void BlendProc::getUniforms()
{
    TwoInputProc::getUniforms();
    shParamUAlpha = shader->getParam(UNIF, "alpha");
}

void BlendProc::setUniforms()
{
    TwoInputProc::setUniforms();
    glUniform1f(shParamUAlpha, alpha);
}

int BlendProc::render(int position)
{
    // Always render on position == 0
    if(position == 0)
    {
        FilterProcBase::render(position);
    }
    return position;
}

#include "../common_includes.h"
#include "blend.h"

using namespace ogles_gpgpu;

const char *BlendProc::fshaderBlendSrc = OG_TO_STR
(
#if defined(OGLES_GPGPU_OPENGLES)
 precision highp float;
#endif

 varying vec2 textureCoordinate;
 varying vec2 textureCoordinate2;

 uniform sampler2D inputImageTexture;
 uniform sampler2D inputImageTexture2;
 uniform float alpha;

 void main()
 {
    vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);
    vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate);
    gl_FragColor = mix(textureColor, textureColor2, alpha);
 });

BlendProc::BlendProc(float alpha) : alpha(alpha)
{

}

void BlendProc::getUniforms()
{
    TwoInputProc::getUniforms();
    shParamUAlpha = shader->getParam(UNIF, "alpha");
}

void BlendProc::setUniforms()
{
    TwoInputProc::setUniforms();
    glUniform1f(shParamUAlpha, alpha);
}

int BlendProc::render(int position)
{
    // Always render on position == 0
    TwoInputProc::render(position);
    return position;
}

Update filter for newer TwoInptProc::render() mechanism


#include "signal_handlers.h"

#include <cstring>

#include <iostream>

#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>

namespace keron {
namespace server {
std::atomic_int stop(0);

static BOOL handler(DWORD fdwCtrlType)
{

	switch (fdwCtrlType) {
		case CTRL_C_EVENT:
		case CTRL_CLOSE_EVENT:
			std::cout << "The server is going DOWN!" << std::endl;
			stop = 1;
			return TRUE;
		case CTRL_BREAK_EVENT:
		case CTRL_LOGOFF_EVENT:
		case CTRL_SHUTDOWN_EVENT:
			std::cout << "The server is going DOWN!" << std::endl;
			stop = 1;
			// Same return as the default case.
		default:
			return FALSE;
	}
}

int register_signal_handlers()
{
	return SetConsoleCtrlHandler((PHANDLER_ROUTINE)handler, TRUE) == TRUE;
}

} // namespace server
} // namespace keron

#include "signal_handlers.h"

#include <cstring>

#include <iostream>

#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>

namespace keron {
namespace server {
std::atomic_int stop(0);

static BOOL handler(DWORD fdwCtrlType)
{

	switch (fdwCtrlType) {
		case CTRL_C_EVENT:
		case CTRL_CLOSE_EVENT:
			std::cout << "The server is going DOWN!" << std::endl;
			stop.store(1);
			return TRUE;
		case CTRL_BREAK_EVENT:
		case CTRL_LOGOFF_EVENT:
		case CTRL_SHUTDOWN_EVENT:
			std::cout << "The server is going DOWN!" << std::endl;
			stop.store(1);
			// Same return as the default case.
		default:
			return FALSE;
	}
}

int register_signal_handlers()
{
	return SetConsoleCtrlHandler((PHANDLER_ROUTINE)handler, TRUE) == TRUE;
}

} // namespace server
} // namespace keron

Use store instead of "=" for atomic.


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


// 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 "ppapi/shared_impl/instance_impl.h"

#include "ppapi/c/pp_errors.h"
#include "ppapi/c/ppb_input_event.h"

namespace ppapi {

InstanceImpl::~InstanceImpl() {
}

int32_t InstanceImpl::ValidateRequestInputEvents(bool is_filtering,
                                                 uint32_t event_classes) {
  // See if any bits are set we don't know about.
  if (event_classes &
      ~static_cast<uint32_t>(PP_INPUTEVENT_CLASS_MOUSE |
                             PP_INPUTEVENT_CLASS_KEYBOARD |
                             PP_INPUTEVENT_CLASS_WHEEL |
                             PP_INPUTEVENT_CLASS_TOUCH |
                             PP_INPUTEVENT_CLASS_IME))
    return PP_ERROR_NOTSUPPORTED;

  // See if the keyboard is requested in non-filtering mode.
  if (!is_filtering && (event_classes & PP_INPUTEVENT_CLASS_KEYBOARD))
    return PP_ERROR_NOTSUPPORTED;

  // Everything else is valid.
  return PP_OK;
}

}  // namespace ppapi

// 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 "ppapi/shared_impl/instance_impl.h"

#include "ppapi/c/pp_errors.h"
#include "ppapi/c/ppb_input_event.h"

namespace ppapi {

InstanceImpl::~InstanceImpl() {
}

int32_t InstanceImpl::ValidateRequestInputEvents(bool is_filtering,
                                                 uint32_t event_classes) {
  // See if any bits are set we don't know about.
  if (event_classes &
      ~static_cast<uint32_t>(PP_INPUTEVENT_CLASS_MOUSE |
                             PP_INPUTEVENT_CLASS_KEYBOARD |
                             PP_INPUTEVENT_CLASS_WHEEL |
                             PP_INPUTEVENT_CLASS_TOUCH |
                             PP_INPUTEVENT_CLASS_IME))
    return PP_ERROR_NOTSUPPORTED;

  // Everything else is valid.
  return PP_OK;
}

}  // namespace ppapi

Fix return value when unfiltered keyboard events are registered.


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

namespace ti
{
	GstMediaBinding::GstMediaBinding(SharedKObject global) : MediaBinding(global)
	{
		char **argv;
		int argc = 0;
		gst_init(&argc, &argv);
	}

	GstMediaBinding::~GstMediaBinding()
	{
	}

	void GstMediaBinding::Beep()
	{
		printf("\a"); // \a to console should cause the beep sound
	}

	SharedKObject GstMediaBinding::CreateSound(std::string& url)
	{
		//This is a path so, turn it into a file:// URL
		std::string myurl = url;
		std::string path = URLUtils::URLToPath(url);
		if (path.find("://") != std::string::npos)
		{
			myurl = URLUtils::PathToFileURL(path);
		}

		SharedGstSound sound = new GstSound(myurl);
		GstSound::RegisterSound(sound);
		return sound;
	}
}

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

namespace ti
{
	GstMediaBinding::GstMediaBinding(SharedKObject global) : MediaBinding(global)
	{
		char **argv;
		int argc = 0;
		gst_init(&argc, &argv);
	}

	GstMediaBinding::~GstMediaBinding()
	{
	}

	void GstMediaBinding::Beep()
	{
		printf("\a"); // \a to console should cause the beep sound
	}

	SharedKObject GstMediaBinding::CreateSound(std::string& url)
	{
		//This is a path so, turn it into a file:// URL
		std::string myurl = url;
		std::string path = URLUtils::URLToPath(url);
		if (path.find("://") == std::string::npos)
		{
			myurl = URLUtils::PathToFileURL(path);
		}

		SharedGstSound sound = new GstSound(myurl);
		GstSound::RegisterSound(sound);
		return sound;
	}
}

Fix bug in URL parsing


#include "llvm/Testing/Support/SupportHelpers.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"

#include "gtest/gtest.h"

using namespace llvm;
using namespace llvm::unittest;

extern const char *TestMainArgv0;

SmallString<128> llvm::unittest::getInputFileDirectory() {
  llvm::SmallString<128> Result = llvm::sys::path::parent_path(TestMainArgv0);
  llvm::sys::fs::make_absolute(Result);
  llvm::sys::path::append(Result, "llvm.srcdir.txt");

  EXPECT_TRUE(llvm::sys::fs::is_directory(Result))
      << "Unit test source directory file does not exist.";

  auto File = MemoryBuffer::getFile(Result);

  EXPECT_TRUE(static_cast<bool>(File))
      << "Could not open unit test source directory file.";

  Result.clear();
  Result.append((*File)->getBuffer().trim());
  llvm::sys::path::append(Result, "Inputs");
  llvm::sys::path::native(Result);
  return std::move(Result);
}

#include "llvm/Testing/Support/SupportHelpers.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"

#include "gtest/gtest.h"

using namespace llvm;
using namespace llvm::unittest;

extern const char *TestMainArgv0;

SmallString<128> llvm::unittest::getInputFileDirectory() {
  llvm::SmallString<128> Result = llvm::sys::path::parent_path(TestMainArgv0);
  llvm::sys::fs::make_absolute(Result);
  llvm::sys::path::append(Result, "llvm.srcdir.txt");

  EXPECT_TRUE(llvm::sys::fs::is_regular_file(Result))
      << "Unit test source directory file does not exist.";

  auto File = MemoryBuffer::getFile(Result);

  EXPECT_TRUE(static_cast<bool>(File))
      << "Could not open unit test source directory file.";

  Result.clear();
  Result.append((*File)->getBuffer().trim());
  llvm::sys::path::append(Result, "Inputs");
  llvm::sys::path::native(Result);
  return std::move(Result);
}

Fix silly error in unittest helper.


#include <emscripten/bind.h>

#include "libcellml/parentedentity.h"

using namespace emscripten;

EMSCRIPTEN_BINDINGS(libcellml_parentedentity)
{
    class_<libcellml::ParentedEntity, base<libcellml::Entity>>("ParentedEntity")
        .smart_ptr<std::shared_ptr<libcellml::ParentedEntity>>("ParentedEntity")
        .function("parent", &libcellml::ParentedEntity::parent)
        .function("removeParent", &libcellml::ParentedEntity::removeParent)
        .function("hasParent", &libcellml::ParentedEntity::hasParent)
        .function("hasAncestor", &libcellml::ParentedEntity::hasAncestor)
    ;
}

#include <emscripten/bind.h>

#include "libcellml/parentedentity.h"

using namespace emscripten;

EMSCRIPTEN_BINDINGS(libcellml_parentedentity)
{
    class_<libcellml::ParentedEntity, base<libcellml::Entity>>("ParentedEntity")
        .smart_ptr<std::shared_ptr<libcellml::ParentedEntity>>("ParentedEntity")
        .function("parent", &libcellml::ParentedEntity::parent)
        .function("hasParent", &libcellml::ParentedEntity::hasParent)
        .function("hasAncestor", &libcellml::ParentedEntity::hasAncestor)
    ;
}

Remove removeParent from javascript ParentedEntity.


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

#include "views/focus/focus_manager.h"

#include "base/logging.h"

namespace views {

void FocusManager::ClearNativeFocus() {
  NOTIMPLEMENTED();
}

void FocusManager::FocusNativeView(gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

 // static
FocusManager* FocusManager::GetFocusManagerForNativeView(
    gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

}  // namespace views

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

#include "views/focus/focus_manager.h"

#include "base/logging.h"

namespace views {

void FocusManager::ClearNativeFocus() {
  NOTIMPLEMENTED();
}

void FocusManager::FocusNativeView(gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

 // static
FocusManager* FocusManager::GetFocusManagerForNativeView(
    gfx::NativeView native_view) {
  NOTIMPLEMENTED();
  return NULL;
}

}  // namespace views

Fix compilation error in the focus manager by returning NULL from unimplemented function.


#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

typedef map< string, vector<string> > Graph;

typedef struct
{
	int finish_time;
	int visited;
}State;

void dfs(Graph &g, string v, map<string, State*> &state, int &dfs_time)
{
	state[v]->visited = 0;
	dfs_time++;
	vector<string> adjacent = g[v];
	for (vector<string>::iterator i = adjacent.begin(); i != adjacent.end(); i++) {
		if (state[*i]->visited == -1) {
			dfs(g, *i, state, dfs_time);
		}
	}
	state[v]->visited = 1;
	dfs_time++;
	state[v]->finish_time = dfs_time;
}

bool cmp(const pair<string, State*> &x, const pair<string, State*> &y)
{
	return x.second->finish_time > y.second->finish_time;
}

int main()
{
	int T;
	cin >> T;
	while(T--) {
		Graph graph;
		map<string, State*> state;
		int finish_time = 0;
		int N;
		cin >> N;
		while (N--) {
			string x, y;
			cin >> x >> y;
			graph[x].push_back(y);
			state[x] = new State;
			state[x]->finish_time = 0;
			state[x]->visited = -1;
			if (graph[y].empty()) {
				graph[y].clear();
				state[y] = new State;
				state[y]->finish_time = 0;
				state[y]->visited = -1;
			}
		}
		for (Graph::iterator i = graph.begin(); i != graph.end(); i++) {
			if (state[i->first]->visited == -1) {
				dfs(graph, i->first, state, finish_time);
			}
		}
		typedef vector< pair<string, State*> > ResType;
		ResType res;
		for (map<string, State*>::iterator i = state.begin(); i != state.end(); i++) {
			res.push_back(pair<string, State*>(i->first, i->second));
		}
		sort(res.begin(), res.end(), cmp);
		for (ResType::iterator i = res.begin(); i != res.end(); i++) {
			cout << i->first << endl;
		}

	}
	return 0;
}

Add the solution to "Potentate Permutation".


#include <iostream>
#include <execution_policy>

int main()
{
  std::async(std::con(10), [](std::concurrent_group &g)
  {
    std::cout << "agent " << g.child().index() << " arriving at barrier" << std::endl;

    g.wait();

    std::cout << "departing barrier" << std::endl;
  }).wait();

  return 0;
}

Add test for concurrent groups


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

struct NonDefaultConstructible {
  NonDefaultConstructible(const NonDefaultConstructible&);
};

template<typename T, typename U>
struct X {
  static T member;
};

template<typename T, typename U>
T X<T, U>::member; // expected-error{{no matching constructor}}

// Okay; this is a declaration, not a definition.
template<>
NonDefaultConstructible X<NonDefaultConstructible, long>::member;

NonDefaultConstructible &test(bool b) {
  return b? X<NonDefaultConstructible, int>::member // expected-note{{instantiation}}
          : X<NonDefaultConstructible, long>::member;
}

Test explicit specializations of static data members that are declarations, not definitions


/*
g++ huge-threads.cpp ../../objs/st/libst.a -g -O0 -DLINUX -o huge-threads && ./huge-threads 32756
*/
#include <stdio.h>
#include <stdlib.h>
#include "../../objs/st/st.h"

void* pfn(void* arg) {
    char v[32*1024]; // 32KB in stack.
    for (;;) {
        v[0] = v[sizeof(v) - 1] = 0xf;
        st_usleep(1000 * 1000);
    }
    return NULL;
}

int main(int argc, char** argv) {
    if (argc < 2) {
        printf("Usage: %s nn_coroutines [verbose]\n", argv[0]);
        exit(-1);
    }

    st_init();
    int nn = ::atoi(argv[1]);
    printf("pid=%d, create %d coroutines\n", ::getpid(), nn);
    for (int i = 0; i < nn; i++) {
        st_thread_t thread = st_thread_create(pfn, NULL, 1, 0);
        if (!thread) {
            printf("create thread fail, i=%d\n", i);
            return -1;
        }
        if (argc > 2) {
            printf("thread #%d: %p\n", i, thread);
        }
    }

    printf("done\n");
    st_thread_exit(NULL);
    return 0;
}

Add huge coroutine test program


/*
 * Copyright (c) 2008, Thomas Jaeger <ThJaeger@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include "util.h"

#include <sys/time.h>
#include <time.h>

void show_us(const char *str) {
	struct timeval tv;
	gettimeofday(&tv, 0);
	printf("%s: %ld.%ld\n", str, tv.tv_sec, tv.tv_usec);
}

/*
 * Copyright (c) 2008, Thomas Jaeger <ThJaeger@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include "util.h"

#include <stdio.h>
#include <sys/time.h>
#include <time.h>

void show_us(const char *str) {
	struct timeval tv;
	gettimeofday(&tv, 0);
	printf("%s: %ld.%ld\n", str, tv.tv_sec, tv.tv_usec);
}

Fix build failure on Fedora


#include <iostream>

using namespace std;

struct Destination {
    char city[32];
    int kilometers;
};

int main() {
    Destination plovdiv = { "Plovdiv", 165 }, varna = { "Varna", 469 };
    cout << plovdiv.city << " " << plovdiv.kilometers << endl;
    cout << varna.city << " " << varna.kilometers << endl;

    Destination destinations[30];
    for (int i = 0; i < 30; i++) {
        destinations[i] = {};
    }

    Destination fiveDestinations[5] = {
        { "Plovdiv", 165 },
        { "Varna", 469 },
        { "Burgas", 393 },
        { "Vidin", 199 },
        { "Dobrich", 512 }
    };

    for (int i = 0; i < 5; i++)
        cout << fiveDestinations[i].city << " " << fiveDestinations[i].kilometers << endl;

    return 0;
}

Add solution to the second problem


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if(!head) return NULL;
        int tot=countl(head);
        if(tot==1){
            TreeNode* ret=new TreeNode(head->val);
            return ret;
        }
        int mid=(tot-1)/2;
        ListNode* t=new ListNode(0);
        if(mid==0){
            t=head;
        }else{
            t=getnth(head,mid);
        }
        TreeNode* ret=new TreeNode(t->next->val);
        ret->right=sortedListToBST(t->next->next);
        t->next=NULL;
        ret->left=sortedListToBST(head);
        return ret;
    }
    int countl(ListNode* head){
        if(head->next) return countl(head->next)+1;
        return 1;
    }
    ListNode* getnth(ListNode* head, int n){
        if(n==1) return head;
        return getnth(head->next,n-1);
    }
};

Convert Sorted List to Binary Search Tree


#include "ntp-time.h"

NtpTime* ntpTime;

String hhmmss(unsigned long int now)  //format value as "hh:mm:ss"
{
   String hour = String(Time.hourFormat12(now));
   String minute = String::format("%02i",Time.minute(now));
   String second = String::format("%02i",Time.second(now));
   return hour + ":" + minute + ":" + second;
};

void setup() {
    ntpTime = new NtpTime(15);  // Do an ntp update every 15 minutes;
    ntpTime->start();
}

void loop() {
    static unsigned long waitMillis;
    struct epochMillis now;  //holds the unix epoch time to millisecond resolution
    if(millis() > waitMillis) {
        ntpTime->nowMillis(&now);  //get the current NTP time
        Particle.publish("NTP clock is: ", hhmmss(now.seconds) + "." + String::format("%03i",now.millis));
        Particle.publish("System clock is: ", hhmmss(Time.now()));
        waitMillis = millis() + (15*1000);  // wait 15 seconds
    }
}

Update to version 0.1.0 Add millisecond resolution


// done_states.cpp

#include "hsm/statemachine.h"

using namespace hsm;

class Character
{
public:
	Character();
	void Update();

	// Public to simplify sample
	bool mOpenDoor;

private:
	friend struct CharacterStates;
	StateMachine mStateMachine;
};

struct CharacterStates
{
	struct BaseState : StateWithOwner<Character>
	{
	};

	struct Alive : BaseState
	{
		virtual Transition GetTransition()
		{
			return InnerEntryTransition<Stand>();
		}
	};

	struct Stand : BaseState
	{
		virtual Transition GetTransition()
		{
			if (Owner().mOpenDoor)
			{
				Owner().mOpenDoor = false;
				return SiblingTransition<OpenDoor>();
			}

			return NoTransition();
		}
	};

	struct OpenDoor : BaseState
	{
		virtual Transition GetTransition()
		{
			if (IsInInnerState<OpenDoor_Done>())
				return SiblingTransition<Stand>();

			return InnerEntryTransition<OpenDoor_GetIntoPosition>();
		}
	};

	struct OpenDoor_GetIntoPosition : BaseState
	{
		bool IsInPosition() const { return true; } // Stub

		virtual Transition GetTransition()
		{
			if (IsInPosition())
				return SiblingTransition<OpenDoor_PlayOpenAnim>();

			return NoTransition();
		}
	};

	struct OpenDoor_PlayOpenAnim : BaseState
	{
		bool IsAnimDone() const { return true; } // Stub

		virtual Transition GetTransition()
		{
			if (IsAnimDone())
				return SiblingTransition<OpenDoor_Done>();

			return NoTransition();
		}
	};

	struct OpenDoor_Done : BaseState
	{
	};
};

Character::Character()
	: mOpenDoor(false)
{
	mStateMachine.Initialize<CharacterStates::Alive>(this);
	mStateMachine.SetDebugInfo("TestHsm", TraceLevel::Basic);
}

void Character::Update()
{
	printf(">>> Character::Update\n");

	// Update state machine
	mStateMachine.ProcessStateTransitions();
	mStateMachine.UpdateStates();
}

int main()
{
	Character character;

	character.Update();

	character.mOpenDoor = true;
	character.Update();
}

Add sample for section: Done States


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

namespace N {
  template<typename T> void f(T) {} // expected-note {{here}}
  namespace M {
    template void f<int>(int); // expected-warning {{explicit instantiation of 'N::f' must occur in namespace 'N'}}
  }
}

template<typename T> void f(T) {} // expected-note {{here}}
namespace M {
  template void f<int>(int); // expected-warning {{explicit instantiation of 'f' must occur in the global namespace}}
}

void f() {
  auto int n = 0; // expected-warning {{'auto' storage class specifier is redundant and incompatible with C++0x}}
}

int n;
struct S {
  char c;
}
s = { n }, // expected-warning {{non-constant-expression cannot be narrowed from type 'int' to 'char' in initializer list in C++0x}} expected-note {{explicit cast}}
t = { 1234 }; // expected-warning {{constant expression evaluates to 1234 which cannot be narrowed to type 'char' in C++0x}} expected-warning {{changes value}} expected-note {{explicit cast}}

Add more testing for -Wc++0x-compat warnings.


#include <cstdio>
using namespace std;

// Test that if the validator says WA, that's the verdict given even if we
// TLE afterwards (realistically because we tried to read from stdin and didn't
// get a response we expected).

int main(void) {
    printf("-1\n");
    fflush(stdout);
    for (;;);
}

Add a test for the TLE -> WA behavior


#include <cxxtest/TestDrive.h>

#include "forceplateTest_def.h"

#include <openma/instrument/forceplatetype4.h>

CXXTEST_SUITE(ForcePlateType4Test)
{
  CXXTEST_TEST(wrench)
  {
    ma::instrument::ForcePlateType4 fp("FP");
    forceplatetest_fill_sample10_type4(&fp);
    forceplatetest_compare_wrench_at_origin(&fp, fp4dataout);
  };
};

CXXTEST_SUITE_REGISTRATION(ForcePlateType4Test)
CXXTEST_TEST_REGISTRATION(ForcePlateType4Test, wrench)

Test for the force platform Type-4.


/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
**     of its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

//! [0]
void MyMainWindow::closeEvent(QCloseEvent *event)
{
    QSettings settings("MyCompany", "MyApp");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
    QMainWindow::closeEvent(event);
}
//! [0]

//! [1]
void MainWindow::readSettings()
{
    QSettings settings("MyCompany", "MyApp");
    restoreGeometry(settings.value("myWidget/geometry").toByteArray());
    restoreState(settings.value("myWidget/windowState").toByteArray());
}
//! [1]

Add missing code snippet file


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

// Sometimes this test fails on Linux: crbug.com/130138
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Idle) {
#else
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Idle) {
#endif
  ASSERT_TRUE(RunExtensionTest("idle")) << message_;
}

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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

// This test is flaky: crbug.com/130138
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Idle) {
  ASSERT_TRUE(RunExtensionTest("idle")) << message_;
}

Disable ExtensionApiTest.Idle on all platforms, since it's flaky everywhere.


#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

void calcMinkowskiDistance(const int& p, const int& numberOfData, const int* x, const int* y);
void calcChebyshevDistance(const int& numberOfData, const int* x, const int* y);

int main() {
  int numberOfData(0);
  cin >> numberOfData;

  int x[1000], y[1000];
  for(int i = 0; i < numberOfData; ++i)
    cin >> x[i];
  for(int i = 0; i < numberOfData; ++i)
    cin >> y[i];

  calcMinkowskiDistance(1, numberOfData, x, y);
  calcMinkowskiDistance(2, numberOfData, x, y);
  calcMinkowskiDistance(3, numberOfData, x, y);
  calcChebyshevDistance(numberOfData, x, y);

  return 0;
}

void calcMinkowskiDistance(const int& p, const int& numberOfData, const int* x, const int* y) {
  double sum(0.0);
  for(int i = 0; i < numberOfData; ++i )
    sum += pow((abs(*(x + i) - *(y + i))), (float)p);

  cout << fixed << setprecision(8) << pow(sum, 1.0/(float)p) << endl;
}

void calcChebyshevDistance(const int& numberOfData, const int* x, const int* y) {
  double distance(0.0);

  for(int i = 0; i < numberOfData; ++i ) {
    if(distance < abs(*(x + i) - *(y + i)))
      distance = abs(*(x + i) - *(y + i));
  }

  cout << fixed << setprecision(8) << distance << endl;
}

Add answer for ITP 1-11 D


/* **********************************************************
 * Copyright (c) 2011 Google, Inc.  All rights reserved.
 * **********************************************************/

/* Dr. Memory: the memory debugger
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License, and no later version.

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

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <windows.h>

#include "gtest/gtest.h"

TEST(NtUserTests, SystemParametersInfo) {
    NONCLIENTMETRICS metrics;
    ZeroMemory(&metrics, sizeof(NONCLIENTMETRICS));
    metrics.cbSize = sizeof(NONCLIENTMETRICS);
    EXPECT_NE(0, SystemParametersInfo(SPI_GETNONCLIENTMETRICS,
                                      sizeof(NONCLIENTMETRICS), &metrics, 0));
}

Add a test for NtUserSystemParametersInfo syscall to app_suite


#include <iostream>

using namespace std;

namespace primerLib {
    void compute() {
        cout << "primerLib::compute()" << endl;
    }

//    void compute(const void *p) {
//        cout << "primerLib::compute(const void *)" << endl;
//    }
}

void compute(int i) {
    cout << "::compute(int)" << endl;
}

void compute(double d, double d2 = 3.4) {
    cout << "::compute(double, double = 3.4)" << endl;
}

void compute(char* p1, char* p2 = 0) {
    cout << "::compute(char*, char* = 0)" << endl;
}

void f() {
    using primerLib::compute;
    compute(0);
}

int main() {
    f();
    return 0;
}

Add solution for chapter 18 test 20


#include <iostream>
#include <regex>
#include <string>

using namespace std;

int main() {
    string zipcode("(\\d{5})([-]?\\d{4})?");
    regex r(zipcode);
    string s;
    smatch m;
    while(getline(cin, s)) {
        if(regex_match(s, m, r)) {
            cout << "valid: " << m.str() << endl;
        } else {
            cout << "invalid: " << m.str() << endl;
        }
    }
    return 0;
}

Add solution for chapter 17 test 23


#include <iostream>
#include <string>
using namespace std;

struct Node
{
	string s;
	Node *left;
	Node *right;
};

Node *new_node(string s)
{
	Node *temp = new Node();
	temp->s = s;
	temp->left = NULL;
	temp->right = NULL;
	return temp;
}

bool add_edge(Node *root, Node *father, Node *child)
{
	if (root == NULL) {
		return false;
	}
	if (root->s == father->s) {
		if (root->left == NULL) {
			root->left = child;
			return true;
		}
		else {
			root->right = child;
			return true;
		}
	}
	if (!add_edge(root->left, father, child)) {
		return add_edge(root->right, father, child);
	}
	return true;
}

void pre_order(Node *root)
{
	if (root == NULL) {
		return;
	}
	cout << root->s << endl;
	pre_order(root->left);
	pre_order(root->right);
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		int k;
		cin >> k;
		string s1, s2;
		cin >> s1 >> s2;
		Node *tree = new_node(s1);
		Node *left = new_node(s2);
		tree->left = left;
		while (--k) {
			cin >> s1 >> s2;
			add_edge(tree, new_node(s1), new_node(s2));
		}
		pre_order(tree);
	}
	return 0;
}

Add the solution to "Preorder perusal".


#include <iostream>
#include <string>

using namespace std;

class Dog {
    string name;
public:
    Dog(string _name = "") {
        name = _name;
    }
    void greet() {
        cout << "Bark, bark! I am " << name << ", a talking dog." << endl;
    }
};

class Person {
    string name;
    int age;
    Dog dog;
public:
    Person(string _name, int _age, Dog _dog) {
        name = _name;
        age = _age;
        dog = _dog;
    }
    void greet() {
        cout << "Hi! I am " << name << " and I am " << age << " years old." << endl;
        cout << "And this is my dog:" << endl;
        dog.greet();
    }
};

int main() {
    Person ivan("Ivan", 15, Dog("Johny"));
    ivan.greet();

    return 0;
}

Add solution to the Person with a dog problem


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

using namespace std;
using namespace tpool;

void InputPrompt(const unsigned int cnt)
{
  cout << "[" << cnt << "] In: ";
}

unsigned int GetFibonacciNumber(const unsigned int i)
{
  if (i < 2)
    {
      return i;
    }
  else
    {
      return GetFibonacciNumber(i - 1) + GetFibonacciNumber(i - 2);
    }
}

void OutputFibonacciNumber(const unsigned int cnt, const unsigned int i)
{
  cout << "[" << cnt << "] Out: " << GetFibonacciNumber(i) << endl;
}

void SyncLoop()
{
  unsigned int i = 0, cnt = 1;

  InputPrompt(cnt);
  while(cin >> i)
    {
      OutputFibonacciNumber(cnt, i);
      InputPrompt(++cnt);
    }
}

void AsyncLoop()
{
  unsigned int i = 0, cnt = 1;
  LFixedThreadPool threadPool;

  InputPrompt(cnt);
  while(cin >> i)
    {
      threadPool.AddTask(boost::bind(&OutputFibonacciNumber, cnt, i));
      InputPrompt(++cnt);
    }
}

int main(int argc, char *argv[])
{
  // SyncLoop();
  AsyncLoop();

  return 0;
}

Add an Fibonacci example to show the usage of AddTask.


#include <stan/math/prim.hpp>
#include <test/unit/math/prim/fun/expect_matrix_eq.hpp>
#include <gtest/gtest.h>

#define EXPECT_MATRIX_NEAR(A, B, DELTA) \
  for (int i = 0; i < A.size(); i++)    \
    EXPECT_NEAR(A(i), B(i), DELTA);

TEST(MathMatrixPrim, mdivide_left_tri_low_val) {
  using stan::math::mdivide_left_tri_low;
  stan::math::matrix_d I = Eigen::MatrixXd::Identity(2, 2);

  stan::math::matrix_d Ad(2, 2);
  Ad << 2.0, 0.0, 5.0, 7.0;
  expect_matrix_eq(I, mdivide_left_tri_low(Ad, Ad));

  stan::math::matrix_d A_Ainv = Ad * mdivide_left_tri_low(Ad);
  EXPECT_MATRIX_NEAR(I, A_Ainv, 1e-15);
}

TEST(MathMatrixPrim, mdivide_left_tri_low_size_zero) {
  using stan::math::mdivide_left_tri_low;
  stan::math::matrix_d Ad(0, 0);
  stan::math::matrix_d b0(0, 2);
  stan::math::matrix_d I;

  I = mdivide_left_tri_low(Ad, Ad);
  EXPECT_EQ(0, I.rows());
  EXPECT_EQ(0, I.cols());

  I = mdivide_left_tri_low(Ad);
  EXPECT_EQ(0, I.rows());
  EXPECT_EQ(0, I.cols());

  I = mdivide_left_tri_low(Ad, b0);
  EXPECT_EQ(0, I.rows());
  EXPECT_EQ(b0.cols(), I.cols());
}

Add prim test for mdivide_left_tri_low


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

#include "content/renderer/media/media_stream_audio_source.h"

namespace content {

MediaStreamAudioSource::MediaStreamAudioSource(
    int render_view_id,
    const StreamDeviceInfo& device_info,
    const SourceStoppedCallback& stop_callback,
    MediaStreamDependencyFactory* factory)
    : render_view_id_(render_view_id),
      factory_(factory) {
  SetDeviceInfo(device_info);
  SetStopCallback(stop_callback);
}

MediaStreamAudioSource::MediaStreamAudioSource()
    : render_view_id_(-1),
      factory_(NULL) {
}

MediaStreamAudioSource::~MediaStreamAudioSource() {}

void MediaStreamAudioSource::DoStopSource() {
  audio_capturer_->Stop();
}

void MediaStreamAudioSource::AddTrack(
    const blink::WebMediaStreamTrack& track,
    const blink::WebMediaConstraints& constraints,
    const ConstraintsCallback& callback) {
  // TODO(xians): Properly implement for audio sources.
  bool result = true;
  if (factory_ && !local_audio_source_) {
    result = factory_->InitializeMediaStreamAudioSource(render_view_id_,
                                                        constraints,
                                                        this);
  }
  callback.Run(this, result);
}

void MediaStreamAudioSource::RemoveTrack(
    const blink::WebMediaStreamTrack& track) {
  NOTIMPLEMENTED();
}

}  // namespace content

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

#include "content/renderer/media/media_stream_audio_source.h"

namespace content {

MediaStreamAudioSource::MediaStreamAudioSource(
    int render_view_id,
    const StreamDeviceInfo& device_info,
    const SourceStoppedCallback& stop_callback,
    MediaStreamDependencyFactory* factory)
    : render_view_id_(render_view_id),
      factory_(factory) {
  SetDeviceInfo(device_info);
  SetStopCallback(stop_callback);
}

MediaStreamAudioSource::MediaStreamAudioSource()
    : render_view_id_(-1),
      factory_(NULL) {
}

MediaStreamAudioSource::~MediaStreamAudioSource() {}

void MediaStreamAudioSource::DoStopSource() {
  if (audio_capturer_.get())
    audio_capturer_->Stop();
}

void MediaStreamAudioSource::AddTrack(
    const blink::WebMediaStreamTrack& track,
    const blink::WebMediaConstraints& constraints,
    const ConstraintsCallback& callback) {
  // TODO(xians): Properly implement for audio sources.
  bool result = true;
  if (factory_ && !local_audio_source_) {
    result = factory_->InitializeMediaStreamAudioSource(render_view_id_,
                                                        constraints,
                                                        this);
  }
  callback.Run(this, result);
}

void MediaStreamAudioSource::RemoveTrack(
    const blink::WebMediaStreamTrack& track) {
  NOTIMPLEMENTED();
}

}  // namespace content

Fix use of invalid pointer in MediaStreamAudioSource. If the source is not initiated correctly it can happen that the |audio_capturer_| is not set. MediaStreamAudioSource::DoStop will then crash.


#include "catch.hpp"
#include <iostream>
#include <string>

#include "audio/Sound.h"

const std::string sound_file = "sound.wav";

TEST_CASE("Initial value(s) in Sound", "[Sound]")
{
	Sound* sound = new Sound();

	// volume should be at max
	CHECK(sound->get_volume() == 100);

	delete sound;
}

TEST_CASE("Opening sound chunk", "[Sound]")
{
	REQUIRE(SDL_Init(SDL_INIT_EVERYTHING) == 0);
	Sound* sound = new Sound();
	REQUIRE(sound != nullptr);

	SECTION("once w/o close")
	{
		sound->open(sound_file);
		CHECK(sound->get_sound() != nullptr);
	}
	SECTION("once")
	{
		sound->open(sound_file);
		REQUIRE(sound->get_sound() != nullptr);

		sound->close();
		CHECK(sound->get_sound() == nullptr);
	}
	SECTION("twice")
	{
		for(unsigned int i = 0; i < 2; i++)
		{
			sound->open(sound_file);
			REQUIRE(sound->get_sound() != nullptr);

			sound->close();
			CHECK(sound->get_sound() == nullptr);
		}
	}
	SECTION("thrice")
	{
		for(unsigned int i = 0; i < 3; i++)
		{
			sound->open(sound_file);
			REQUIRE(sound->get_sound() != nullptr);

			sound->close();
			CHECK(sound->get_sound() == nullptr);
		}
	}

	delete sound;
	SDL_Quit();
}

Add Sound unit testing source.


#include <iostream>
#include<stdlib.h>
#include <string.h>
using namespace std;

struct Graph {
    int V,E;
    int **adj;
};

Graph* createGraph(int V, int E) {
    Graph *G = new Graph();
    if (!G) return NULL;

    G->V = V;
    G->E = E;

    G->adj = new int*[G->V]; //row count
    for (int i = 0; i < G->V; i++) //column count
        G->adj[i] = new int[G->V];
    for (int i = 0; i < G->V; i++)
        for (int j = 0; j < G->V; j++)
            G->adj[i][j] = 0;
    int u, v;
    // 0 -> 1
    // 1 -> 2
    // 2 -> 3
    // 2 -> 0
    // 3 -> 0
    for (int i = 0; i < G->E; i++) {
        cout<<"Enter edge from u to v: ";
        cin>>u>>v;
        G->adj[u][v] = 1;
        // uncomment this for undirected graph
        // uses symmetry to initialize
        //G->adj[v][u] = 1;
    }
    return G;
}

void print(Graph *G) {
    for (int u = 0; u < G->V; u++) {
        for (int v = 0; v < G->V; v++) {
            cout<<G->adj[u][v]<<" ";
        }
    cout<<endl;
    }
}

void deleteGraph(Graph *G) {
    if (!G || !G->adj) return;
    for (int i = 0; i < G->V; i++)
        delete [] G->adj[i];
    delete [] G->adj;

    delete G;
}

int main() {
    Graph *G = createGraph(4, 5);
    print(G);
    deleteGraph(G);
    return 0;
}

Implement Graph using Adjacency Matrix


class global {
};
namespace n {
    void external_func() {
        class floating_func {
        };
    }

    enum normal_enum {};

    enum class class_enum{};

    struct str_test {};

    namespace m {
        class in_namespace {
            class in_class {
            };

            void main() {
                class in_function {
                };

                {
                    class in_inner_scope {
                    };
                }
            }
        };
    }
}

Add testing file to check output for declaration scopes.


// 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 "content/renderer/gpu/delegated_compositor_output_surface.h"

namespace content {

DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface(
    int32 routing_id,
    uint32 output_surface_id,
    const scoped_refptr<ContextProviderCommandBuffer>& context_provider,
    scoped_ptr<cc::SoftwareOutputDevice> software)
    : CompositorOutputSurface(routing_id,
                              output_surface_id,
                              context_provider,
                              software.Pass(),
                              true) {
  capabilities_.delegated_rendering = true;
  capabilities_.max_frames_pending = 1;
}

}  // 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 "content/renderer/gpu/delegated_compositor_output_surface.h"

namespace content {

DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface(
    int32 routing_id,
    uint32 output_surface_id,
    const scoped_refptr<ContextProviderCommandBuffer>& context_provider,
    scoped_ptr<cc::SoftwareOutputDevice> software)
    : CompositorOutputSurface(routing_id,
                              output_surface_id,
                              context_provider,
                              software.Pass(),
                              true) {
  capabilities_.delegated_rendering = true;
}

}  // namespace content

Set max pending frames to the default instead of 1 with ubercomp.


#include "mbed.h"
#include "EventHandler.h"
class VTest {
public:
    int vprint(void *arg) {
        if (arg) {
            int* i = static_cast<int *>(arg);
            printf("Class Print Integer: %d from %p\r\n", *i, arg);
        } else {
            printf("Class Null Arg\r\n");
        }
        return (int)(arg != 0);
    }

};

int barevprint(void *arg) {
    if (arg) {
        int* i = static_cast<int *>(arg);
        printf("Bare Print Integer: %d from %p\r\n", *i, arg);
    } else {
        printf("Class Null Arg\r\n");
    }
    return (int)(arg != 0);
}

int main(void)
{
    VTest test;
    printf("Testing mbed Event Handler...\r\n");
    int i1 = 1;
    int i2 = 2;
    EventHandler ebp(barevprint);
    EventHandler ecp(&test, &VTest::vprint);
    size_t ebsize = sizeof(ebp);
    size_t ecsize = sizeof(ecp);
    printf("sizeof(bp) = %d\r\n", ebsize);
    printf("sizeof(cp) = %d\r\n", ecsize);
    ebp.call(&i1);
    ecp.call(&i2);

    printf ("Test Complete\r\n");
    while(1){__WFI();}
    return 0;
}

Add a trivial test for EventHandler


#include <iostream>
#include <iterator>
#include <regex>
#include <string>

using namespace std;
int main(){
    string  s = "123daniel , jajaja, lol, 234234534, I am from Earth";
    regex tel("\\d{8},\\sI");

    auto words_begin = sregex_iterator(s.begin(), s.end(), tel);
    auto words_end = sregex_iterator();

    cout << "Found " << distance(words_begin, words_end)<< " words\n";

    const int N = 6;

    for (sregex_iterator i = words_begin; i != words_end; ++i) {
        smatch match = *i;
        string match_str = match.str();
        if (match_str.size() > N) {
            cout << "  " << match_str << '\n';
        }
    }

    return 0;

}

Add code for regular expresions in c++.


#include <iostream>
#include<algorithm>

using namespace std;

class interval
{
    int start;
    int duration;
};

bool myCompare(interval a, interval b)
{
    return a.start<b.start;
}
bool conflict(interval a, int timestamp)
{
    if(a.start <= timestamp && (a.start + a.duration >= timestamp ) )
        return true;
    return false;
}
int find_first(vector<interval> Calls, int timestamp)
{
    for(int i=Calls.size()-1; i>0 ;i--)
    {
        if(Calls[i].start <= timestamp)
            return i;
    }
    return -1;
}

int find_first_BS(vector<interval> Calls, int timestamp)
{
    int l =0; int r = Calls.size()-1;
    if(Calls[0].start > timestamp) // No timestamp found
        return -1;
    if(Calls[Calls.size()-1].start <= timestamp) // All Intervals Qualify
        return Calls.size()-1;
    while(l<r)
    {
        int mid = l+(r-l)/2;
        if(Calls[mid].start > timestamp) // search left
        {
            r= mid - 1;
        }
        else
        {
            l = mid + 1;
        }
    }
    return l;
}

int find_overlapping_calls(vector<interval> Calls , int timestamp)
{
    // first sort based on start time
    // as we know given a instant the possible conflicts would
    // have start time < instant and end time > instant

    sort(Calls.begin(),Calls.end(),myCompare);

    // int ix = find_first(Calls, timestamp); ---- O (n)
    int ix = find_first_BS(Calls, timestamp); // --- O(log n) Because Using Binary Search
    if(ix == -1)
        return 0;
    int count = 0;
    for(int i=ix; i>0; i--)
    {
        if(conflict(Calls[i], timestamp) == true)
            count++;
    }
    return count;
}
// Complexity :
// No Extra Space
// O(n) + O(n) ~ O(n) ---> If we use Linear Search to find the first Qualifying Ix, using the function
// find_first;
// O(log n) + O(n) ~ O(n) --- > If we Use Binary Search using the function find_first_BS
//
// Once we have the first Qualifying ix it takes linear time to go over them
// But in general on an avg it will not be O(n)
// So, Optimization to find the ix using Binary Search Makes sense

/// ----- I think a better Performance can be achieved using interval Tree Data Structure
/// But Due to time constraint I did not implement the Interval Tree

Update Interview question twitter microsoft


// Chapter 24, exercise 2: same as exercise 1, but with function objects
// instead of functions

#include<iostream>
#include "Matrix.h"
#include "MatrixIO.h"

using namespace std;
using namespace Numeric_lib;

namespace Numeric_lib {;

struct Triple1 {
    void operator()(int& a) { a *= 3; }
};

struct Triple2 {
    int operator()(int a) { return a*3; }
};

struct Triple {
    int operator()(int& a) { a*= 3; return a; }
};

}   // Numeric_lib

int main()
try
{
    int arr[] = { 1, 2, 3, 4, 5 };
    Matrix<int> m1(arr);
    cout << "m1:\t\t\t\t\t" << m1 << '\n';

    m1.apply(Triple1());
    cout << "m1 after m1.apply(Triple1()):\t\t" << m1 << '\n';

    Matrix<int> m2 = apply(Triple2(),m1);
    cout << "m1 after m2 = apply(Triple2(),m1):\t" << m1 << '\n';
    cout << "m2:\t\t\t\t\t" << m2 << '\n';

    m2.apply(Triple());
    cout << "m2 after m2.apply(Triple()):\t\t" << m2 << '\n';
    Matrix<int> m3 = apply(Triple(),m2);
    cout << "m2 after m3 = apply(Triple(),m2):\t" << m2 << '\n';
    cout << "m3:\t\t\t\t\t" << m3 << '\n';
}
catch (exception& e) {
    cerr << "Exception: " << e.what() << '\n';
}
catch (...) {
    cerr << "Exception\n";
}

Add Chapter 24, exercise 2


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

#include "logging.h"

#include "runtime.h"
#include "utils.h"

LogMessage::~LogMessage() {
  if (errno_ != -1) {
    buffer_ << ": " << strerror(errno_);
  }
  std::string msg(buffer_.str());
  if (msg.find('\n') == std::string::npos) {
    LogLine(msg.c_str());
  } else {
    msg += '\n';
    size_t i = 0;
    while (i < msg.size()) {
      size_t nl = msg.find('\n', i);
      msg[nl] = '\0';
      LogLine(&msg[i]);
      i = nl + 1;
    }
  }

  if (severity_ == FATAL) {
    art::Runtime::Abort(file_, line_number_);
  }
}

std::ostream& LogMessage::stream() {
  return buffer_;
}

Add missing file from last commit.


#include "lib/list.cpp"

using namespace std;

ListNode* swapNodes(ListNode* head) {
    if (head == NULL || head->next == NULL) {
        return head;
    }

    ListNode* fakeHead = new ListNode(0);
    fakeHead->next = head;

    ListNode* prev = fakeHead;
    ListNode* current = head;
    ListNode* temp;
    while (current != NULL && current->next != NULL) {
        temp = current->next->next;
        prev->next = current->next;
        current->next->next = current;
        current->next = temp;

        prev = current;
        current = temp;
    }

    head = fakeHead->next;

    return head;
}

int main() {
    ListNode *head, *second, *third, *fourth, *fifth, *newHead, *temp;

    // Normal List
    cout << endl << "Normal List with odd elements" << endl << endl;
    head = new ListNode(10);
    second = new ListNode(20);
    third = new ListNode(30);
    fourth = new ListNode(40);
    fifth = new ListNode(50);
    head->next = second;
    second->next = third;
    third->next = fourth;
    fourth->next = fifth;

    newHead = swapNodes(head);
    temp = newHead;
    while (temp != NULL) {
        cout << temp->val << endl;
        temp=temp->next;
    }

    // Normal List
    cout << endl << "Normal List with even elements" << endl << endl;
    head = new ListNode(10);
    second = new ListNode(20);
    third = new ListNode(30);
    fourth = new ListNode(40);
    head->next = second;
    second->next = third;
    third->next = fourth;

    newHead = swapNodes(head);
    temp = newHead;
    while (temp != NULL) {
        cout << temp->val << endl;
        temp=temp->next;
    }

    // NULL head
    cout << endl << "NULL head" << endl << endl;
    head = NULL;
    newHead = swapNodes(head);
    temp = newHead;
    while (temp != NULL) {
        cout << temp->val << endl;
        temp=temp->next;
    }

    // Only one element
    cout << endl << "Single head" << endl << endl;
    head = new ListNode(10);
    head->next = NULL;
    newHead = swapNodes(head);
    temp = newHead;
    while (temp != NULL) {
        cout << temp->val << endl;
        temp=temp->next;
    }

    return 0;
}

Swap nodes in a pair