#include "utils/connection.h"

namespace utils {

Connection::Connection(const std::string& host, const std::string& port)
  : socket(io_service) {
  tcp::resolver resolver(io_service);
  tcp::resolver::query query(host, port);
  boost::asio::connect(socket, resolver.resolve(query));
  response_buf.prepare(8192);
}

Connection::~Connection() {
  socket.close();
}

jsoncons::json Connection::receive_response(boost::system::error_code* error) {
  auto len = boost::asio::read_until(socket, response_buf, "\n", *error);
  if (*error) {
    return jsoncons::json();
  }
  auto buf = response_buf.data();
  std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len);
  response_buf.consume(len);
  return jsoncons::json::parse_string(reply);
}

void Connection::send_requests(const std::vector<jsoncons::json>& msgs) {
  jsoncons::output_format format;
  format.escape_all_non_ascii(true);
  boost::asio::streambuf request_buf;
  std::ostream s(&request_buf);
  for (const auto& m : msgs) {
    // std::cout << "Responded with: " << pretty_print(m) << std::endl;
    m.to_stream(s, format);
    s << std::endl;
  }
  socket.send(request_buf.data());
}

}  // namespace utils

#include "utils/connection.h"

namespace utils {

Connection::Connection(const std::string& host, const std::string& port)
  : socket(io_service) {
  tcp::resolver resolver(io_service);
  tcp::resolver::query query(host, port);
  boost::asio::connect(socket, resolver.resolve(query));
  response_buf.prepare(8192);
}

Connection::~Connection() {
  socket.close();
}

jsoncons::json Connection::receive_response(boost::system::error_code* error) {
  auto len = boost::asio::read_until(socket, response_buf, "\n", *error);
  if (*error) {
    return jsoncons::json();
  }
  auto buf = response_buf.data();
  std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len);
  response_buf.consume(len);
  return jsoncons::json::parse_string(reply);
}

void Connection::send_requests(const std::vector<jsoncons::json>& msgs) {
  jsoncons::output_format format;
  format.escape_all_non_ascii(true);
  boost::asio::streambuf request_buf;
  std::ostream s(&request_buf);
  for (const auto& m : msgs) {
    std::cout << "Responded with: " << pretty_print(m) << std::endl;
    m.to_stream(s, format);
    s << std::endl;
  }
  socket.send(request_buf.data());
}

}  // namespace utils

Add debug for server responses


// Test reading of PCH without original input files.

// Generate the PCH, removing the original file:
// RUN: echo 'struct S{char c; int i; }; void foo() {}' > %t.h
// RUN: echo 'template <typename T> void tf() { T::foo(); }' >> %t.h
// RUN: echo '#define RETURN return &i' >> %t.h
// RUN: %clang_cc1 -x c++ -emit-pch -o %t.h.pch %t.h
// RUN: rm %t.h

// Check diagnostic with location in original source:
// RUN: %clang_cc1 -include-pch %t.h.pch -Wpadded -emit-obj %s 2> %t.stderr
// RUN: grep 'bytes to align' %t.stderr

// Check diagnostic with 2nd location in original source:
// RUN: not %clang_cc1 -DREDECL -include-pch %t.h.pch -emit-obj %s 2> %t.stderr
// RUN: grep 'previous definition is here' %t.stderr

// Check diagnostic with instantiation location in original source:
// RUN: not %clang_cc1 -DINSTANTIATION -include-pch %t.h.pch -emit-obj %s 2> %t.stderr
// RUN: grep 'cannot be used prior to' %t.stderr

void qq(S*) {}

#ifdef REDECL
float foo() {return 0f;}
#endif

#ifdef INSTANTIATION
void f() {
  tf<int>();
}
#endif

// Test reading of PCH without original input files.

// Generate the PCH, removing the original file:
// RUN: echo 'struct S{char c; int i; }; void foo() {}' > %t.h
// RUN: echo 'template <typename T> void tf() { T::foo(); }' >> %t.h
// RUN: echo '#define RETURN return &i' >> %t.h
// RUN: %clang_cc1 -x c++ -emit-pch -o %t.h.pch %t.h
// RUN: rm %t.h

// Check diagnostic with location in original source:
// RUN: %clang_cc1 -include-pch %t.h.pch -Wpadded -emit-obj -o %t.o %s 2> %t.stderr
// RUN: grep 'bytes to align' %t.stderr

// Check diagnostic with 2nd location in original source:
// RUN: not %clang_cc1 -DREDECL -include-pch %t.h.pch -emit-obj -o %t.o %s 2> %t.stderr
// RUN: grep 'previous definition is here' %t.stderr

// Check diagnostic with instantiation location in original source:
// RUN: not %clang_cc1 -DINSTANTIATION -include-pch %t.h.pch -emit-obj -o %t.o %s 2> %t.stderr
// RUN: grep 'cannot be used prior to' %t.stderr

void qq(S*) {}

#ifdef REDECL
float foo() {return 0f;}
#endif

#ifdef INSTANTIATION
void f() {
  tf<int>();
}
#endif

Use tempfiles for the .o outputs.


// 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 "chrome/browser/metrics/metrics_service.h"

#include <string>

#include "base/base64.h"

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

class MetricsServiceTest : public ::testing::Test {
};

// Ensure the ClientId is formatted as expected.
TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) {
  std::string clientid = MetricsService::GenerateClientID();
  EXPECT_EQ(36U, clientid.length());
  std::string hexchars = "0123456789ABCDEF";
  for (uint32 i = 0; i < clientid.length(); i++) {
    char current = clientid.at(i);
    if (i == 8 || i == 13 || i == 18 || i == 23) {
      EXPECT_EQ('-', current);
    } else {
      EXPECT_TRUE(std::string::npos != hexchars.find(current));
    }
  }
}

TEST(MetricsServiceTest, IsPluginProcess) {
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN));
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN));
  EXPECT_FALSE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU));
}

// 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 <ctype.h>
#include <string>

#include "chrome/browser/metrics/metrics_service.h"
#include "testing/gtest/include/gtest/gtest.h"

// Ensure the ClientId is formatted as expected.
TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) {
  std::string clientid = MetricsService::GenerateClientID();
  EXPECT_EQ(36U, clientid.length());

  for (size_t i = 0; i < clientid.length(); ++i) {
    char current = clientid[i];
    if (i == 8 || i == 13 || i == 18 || i == 23)
      EXPECT_EQ('-', current);
    else
      EXPECT_TRUE(isxdigit(current));
  }
}

TEST(MetricsServiceTest, IsPluginProcess) {
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN));
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN));
  EXPECT_FALSE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU));
}

Clean up MetricsService unit test.


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

struct X {
  void ref() & {}
  void cref() const& {}
};

void test() {
  X{}.ref(); // expected-error{{cannot initialize object parameter of type 'X' with an expression of type 'X'}}
  X{}.cref(); // expected-no-error

  (X{}.*&X::ref)(); // expected-error{{pointer-to-member function type 'void (X::*)() &' can only be called on an lvalue}}
  (X{}.*&X::cref)(); // expected-no-error
}

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

struct X {
  void ref() & {}
  void cref() const& {}
};

void test() {
  X{}.ref(); // expected-error{{cannot initialize object parameter of type 'X' with an expression of type 'X'}}
  X{}.cref(); // expected-no-error

  (X{}.*&X::ref)(); // expected-error-re{{pointer-to-member function type 'void (X::*)() {{.*}}&' can only be called on an lvalue}}
  (X{}.*&X::cref)(); // expected-no-error
}

Fix MSVC bots which include '__attribute__((thiscall))' in pretty-printed member function types.


#include "Thread/ScopedLock.hh"

namespace LilWrapper
{
  ScopedLock::ScopedLock(Mutex *mutex)
    : _mutex(mutex)
  {
    this->_mutex->lock();
  }

  ScopedLock::~ScopedLock()
  {
    this->_mutex->unlock();
  }
}

#include "Thread/ScopedLock.hh"

namespace LilWrapper
{
  ScopedLock::ScopedLock(Mutex *mutex)
    : _mutex(mutex)
  {
    if (this->_mutex)
      this->_mutex->lock();
  }

  ScopedLock::~ScopedLock()
  {
    if (this->_mutex)
      this->_mutex->unlock();
  }
}

Make sure the Mutex exists before using it.


#include <bits/stdc++.h>
#define pb push_back
using namespace std;
typedef vector <string> vs;
int toNum(string a){
	stringstream toNum(a);
	int num;
	toNum >> num;
	return num;
}
vs split(string line, char d){
	vector < string > elements;
	stringstream ss(line);
	string item;
	while(getline(ss, item, d))	elements.pb(item);
	return elements;
}

int main(){
  vs d1 = split("1990/10/5", '/');
  for (string s: d1){
    cout << toNum(s) << endl;
  }

  char a = 'a';
  cout << (isalnum(a)?"true":"false")  << endl;
  cout <<( isalpha(a)?"true":"false") << endl;
  cout << (isblank(a)?"true":"false")  << endl;
  cout << (isdigit(a)?"true":"false")  << endl;
  cout << (islower(a)?"true":"false")  << endl;
  cout << (ispunct(a)?"true":"false")  << endl;
  cout << (isupper(a)?"true":"false")  << endl;
  cout << (isxdigit(a) ?"true":"false") << endl;
  cout << (char)tolower(a) << endl;
  cout << (char)toupper(a) << endl;
  return 0;
}

#include <bits/stdc++.h>
#define pb push_back
using namespace std;
typedef vector <string> vs;
int toNum(string a){
	stringstream toNum(a);
	int num;
	toNum >> num;
	return num;
}

string toString(double d){
  stringstream ss;
	ss << fixed << setprecision(10) << fl;
	string num = ss.str();
	return num;
}

vs split(string line, char d){
	vector < string > elements;
	stringstream ss(line);
	string item;
	while(getline(ss, item, d))	elements.pb(item);
	return elements;
}

int main(){
  vs d1 = split("1990/10/5", '/');
  for (string s: d1){
    cout << toNum(s) << endl;
  }

  char a = 'a';
  cout << (isalnum(a)?"true":"false")  << endl;
  cout <<( isalpha(a)?"true":"false") << endl;
  cout << (isblank(a)?"true":"false")  << endl;
  cout << (isdigit(a)?"true":"false")  << endl;
  cout << (islower(a)?"true":"false")  << endl;
  cout << (ispunct(a)?"true":"false")  << endl;
  cout << (isupper(a)?"true":"false")  << endl;
  cout << (isxdigit(a) ?"true":"false") << endl;
  cout << (char)tolower(a) << endl;
  cout << (char)toupper(a) << endl;
  return 0;
}

Create useful function to convert a number to string.


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

#include "logaction.h"

LogAction::LogAction(Application *application)
    : mDialog(application)
{
}

QString LogAction::name() const
{
    return "log";
}

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

QString LogAction::title() const
{
    return tr("View Log");
}

bool LogAction::invoke(const QVariantMap &)
{
    mDialog.show();
}

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

#include "logaction.h"

LogAction::LogAction(Application *application)
    : mDialog(application)
{
}

QString LogAction::name() const
{
    return "log";
}

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

QString LogAction::title() const
{
    return tr("View Log");
}

bool LogAction::invoke(const QVariantMap &)
{
    mDialog.show();
    return true;
}

Fix compilation error on MSVC++.


#include <stdio.h>
#include "Halide.h"

#define CHECK(f, s32, s64) \
    static_assert(offsetof(buffer_t, f) == (sizeof(void*) == 8 ? (s64) : (s32)), #f " is wrong")

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

    CHECK(dev, 0, 0);
    CHECK(host, 8, 8);
    CHECK(extent, 12, 16);
    CHECK(stride, 28, 32);
    CHECK(min, 44, 48);
    CHECK(elem_size, 60, 64);
    CHECK(host_dirty, 64, 68);
    CHECK(dev_dirty, 65, 69);
    CHECK(_padding, 66, 70);

    static_assert(sizeof(buffer_t) == (sizeof(void*) == 8 ? 72 : 68), "size is wrong");

    // Ensure alignment is at least that of a pointer.
    static_assert(alignof(buffer_t) >= alignof(uint8_t*), "align is wrong");

    printf("Success!\n");
    return 0;
}

#include <stdio.h>
#include "Halide.h"

#define CHECK(f, s32, s64) \
    static_assert(offsetof(buffer_t, f) == (sizeof(void*) == 8 ? (s64) : (s32)), #f " is wrong")

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

    CHECK(dev, 0, 0);
    CHECK(host, 8, 8);
    CHECK(extent, 12, 16);
    CHECK(stride, 28, 32);
    CHECK(min, 44, 48);
    CHECK(elem_size, 60, 64);
    CHECK(host_dirty, 64, 68);
    CHECK(dev_dirty, 65, 69);
    CHECK(_padding, 66, 70);

    static_assert(sizeof(void*) == 8 ?
                    sizeof(buffer_t) == 72 :
                    // Some compilers may insert padding at the end of the struct
                    // so that an array will stay appropriately aligned for
                    // the int64 field.
                    (sizeof(buffer_t) == 68 || sizeof(buffer_t) == 72), "size is wrong");

    // Ensure alignment is at least that of a pointer.
    static_assert(alignof(buffer_t) >= alignof(uint8_t*), "align is wrong");

    printf("Success!\n");
    return 0;
}

Allow for struct padding in test


#include <ncurses.h>

#include "print.hpp"
#include "lightsout.hpp"
#include "keybindings.hpp"
using namespace roadagain;

int main()
{
    initscr();
    cbreak();
    noecho();
    curs_set(0);
    start_color();
    init_colors();

    board b(5, 5);
    keybindings k("emacs");
    while (!b.is_perfect()){
        char c = getch();
        const char* key = keyname(c);

        b.move_board(k.dy(key), k.dx(key));
    }

    endwin();
    return 0;
}

#include <ncurses.h>
#include <cstring>

#include <string>

#include "print.hpp"
#include "lightsout.hpp"
#include "keybindings.hpp"
using namespace roadagain;

int main(int argc, char** argv)
{
    initscr();
    cbreak();
    noecho();
    curs_set(0);
    start_color();
    init_colors();

    std::string key = "vim";
    for (int i = 1; i < argc; i++){
        if (std::strncmp("--key=", argv[i], 6) == 0){
            key = argv[i] + 6;
        }
    }

    board b(5, 5);
    keybindings k(key.c_str());
    while (!b.is_perfect()){
        char c = getch();
        const char* key = keyname(c);

        b.move_board(k.dy(key), k.dx(key));
    }

    endwin();
    return 0;
}

Add getting keybindings from argv


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

#include "base/system_monitor.h"

namespace base {

void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) {
  PowerEvent power_event;
  switch (event_id) {
    case PBT_APMPOWERSTATUSCHANGE:
      power_event = POWER_STATE_EVENT;
      break;
    case PBT_APMRESUMEAUTOMATIC:
      power_event = RESUME_EVENT;
      break;
    case PBT_APMSUSPEND:
      power_event = SUSPEND_EVENT;
      break;
    default:
      DCHECK(false);
  }
  ProcessPowerMessage(power_event);
}

// Function to query the system to see if it is currently running on
// battery power.  Returns true if running on battery.
bool SystemMonitor::IsBatteryPower() {
  SYSTEM_POWER_STATUS status;
  if (!GetSystemPowerStatus(&status)) {
    LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
    return false;
  }
  return (status.ACLineStatus == 0);
}

} // namespace base

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

#include "base/system_monitor.h"

namespace base {

void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) {
  PowerEvent power_event;
  switch (event_id) {
    case PBT_APMPOWERSTATUSCHANGE:  // The power status changed.
      power_event = POWER_STATE_EVENT;
      break;
    case PBT_APMRESUMEAUTOMATIC:  // Non-user initiated resume from suspend.
    case PBT_APMRESUMESUSPEND:    // User initiated resume from suspend.
      power_event = RESUME_EVENT;
      break;
    case PBT_APMSUSPEND:  // System has been suspended.
      power_event = SUSPEND_EVENT;
      break;
    default:
      return;

    // Other Power Events:
    // PBT_APMBATTERYLOW - removed in Vista.
    // PBT_APMOEMEVENT - removed in Vista.
    // PBT_APMQUERYSUSPEND - removed in Vista.
    // PBT_APMQUERYSUSPENDFAILED - removed in Vista.
    // PBT_APMRESUMECRITICAL - removed in Vista.
    // PBT_POWERSETTINGCHANGE - user changed the power settings.
  }
  ProcessPowerMessage(power_event);
}

// Function to query the system to see if it is currently running on
// battery power.  Returns true if running on battery.
bool SystemMonitor::IsBatteryPower() {
  SYSTEM_POWER_STATUS status;
  if (!GetSystemPowerStatus(&status)) {
    LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
    return false;
  }
  return (status.ACLineStatus == 0);
}

} // namespace base

Update comments and remove bogus DCHECK in windows-specific broadcasted power message status.


Add dummy test for memory allocator.


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

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

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/op.h"

namespace tensorflow {

REGISTER_OP("BytesLimit").Output("out: int64").SetIsStateful();
REGISTER_OP("MaxBytesInUse").Output("out: int64").SetIsStateful();

}  // namespace tensorflow

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

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

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"

namespace tensorflow {

REGISTER_OP("BytesLimit")
    .Output("out: int64")
    .SetIsStateful()
    .SetShapeFn(shape_inference::ScalarShape);
REGISTER_OP("MaxBytesInUse")
    .Output("out: int64")
    .SetIsStateful()
    .SetShapeFn(shape_inference::ScalarShape);

}  // namespace tensorflow

Add static shape inference to BytesLimit and MaxBytesInUse.


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

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

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"

namespace tensorflow {
namespace {

class XlaReplicaIdOp : public XlaOpKernel {
 public:
  explicit XlaReplicaIdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
  void Compile(XlaOpKernelContext* ctx) override;

 private:
  TF_DISALLOW_COPY_AND_ASSIGN(XlaReplicaIdOp);
};

void XlaReplicaIdOp::Compile(XlaOpKernelContext* ctx) {
  ctx->SetOutput(0, xla::ReplicaId(ctx->builder()));
}

REGISTER_XLA_OP(Name("XlaReplicaId"), XlaReplicaIdOp);

}  // namespace
}  // namespace tensorflow

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

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

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"

namespace tensorflow {
namespace {

class XlaReplicaIdOp : public XlaOpKernel {
 public:
  explicit XlaReplicaIdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
  void Compile(XlaOpKernelContext* ctx) override;

 private:
  TF_DISALLOW_COPY_AND_ASSIGN(XlaReplicaIdOp);
};

void XlaReplicaIdOp::Compile(XlaOpKernelContext* ctx) {
  ctx->SetOutput(
      0, xla::ConvertElementType(xla::ReplicaId(ctx->builder()), xla::S32));
}

REGISTER_XLA_OP(Name("XlaReplicaId"), XlaReplicaIdOp);

}  // namespace
}  // namespace tensorflow

Convert the result of xla::ReplicaId to S32


#include <string>

#include "catch.hpp"

#include "Chemharp.hpp"
#include "FormatFactory.hpp"
#include "Frame.hpp"
#include "formats/XYZ.hpp"

using namespace harp;

// Dummy format clase
class DummyFormat : public Format {
public:
    DummyFormat(){}
    std::string description() const {return "";}
    REGISTER_FORMAT;
};
REGISTER(DummyFormat, "Dummy");
REGISTER_EXTENSION(DummyFormat, ".dummy");

TEST_CASE("Get registered format", "[format factory]"){
    auto dummy = DummyFormat();
    auto format = FormatFactory::by_extension(".dummy");
    REQUIRE(typeid(dummy) == typeid(*format));
    format = FormatFactory::format("Dummy");
    REQUIRE(typeid(dummy) == typeid(*format));

    auto XYZ = XYZFormat();
    format = FormatFactory::by_extension(".xyz");
    REQUIRE(typeid(XYZ) == typeid(*format));
    format = FormatFactory::format("XYZ");
    REQUIRE(typeid(XYZ) == typeid(*format));
}

#include <string>

#include "catch.hpp"

#include "Chemharp.hpp"
#include "FormatFactory.hpp"
#include "Error.hpp"
#include "formats/XYZ.hpp"

#include "Frame.hpp"
using namespace harp;

// Dummy format clase
class DummyFormat : public Format {
public:
    DummyFormat(){}
    std::string description() const {return "";}
    REGISTER_FORMAT;
};
REGISTER(DummyFormat, "Dummy");
REGISTER_EXTENSION(DummyFormat, ".dummy");

TEST_CASE("Registering a new format", "[format factory]"){
    CHECK(FormatFactory::register_extension(".testing",[](){
                return unique_ptr<Format>(new DummyFormat());
         })
    );
    // We can not register the same format twice
    CHECK_THROWS_AS(FormatFactory::register_extension(".testing",[](){
                return unique_ptr<Format>(new DummyFormat());
         }),
         FormatError
    );

    CHECK(FormatFactory::register_format("DummyFormat",[](){
                return unique_ptr<Format>(new DummyFormat());
         })
    );
    // We can not register the same format twice
    CHECK_THROWS_AS(FormatFactory::register_format("DummyFormat",[](){
                return unique_ptr<Format>(new DummyFormat());
         }),
         FormatError
    );
}

TEST_CASE("Geting registered format", "[format factory]"){
    auto dummy = DummyFormat();
    auto format = FormatFactory::by_extension(".dummy");
    REQUIRE(typeid(dummy) == typeid(*format));
    format = FormatFactory::format("Dummy");
    REQUIRE(typeid(dummy) == typeid(*format));

    auto XYZ = XYZFormat();
    format = FormatFactory::by_extension(".xyz");
    REQUIRE(typeid(XYZ) == typeid(*format));
    format = FormatFactory::format("XYZ");
    REQUIRE(typeid(XYZ) == typeid(*format));
}

Add tests for registering the formats


// For now, this is an empty .cc file that only serves to confirm
// named_value_vector.h is
// a stand-alone header.

#include "drake/systems/framework/named_value_vector.h"

Add newline at end of file.


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

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

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

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

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

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

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

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

  return render_view_host_->Send(message);
}

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

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

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

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

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

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

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

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

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

  return render_view_host_->Send(message);
}

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

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


// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "VerticalBar.h"

VerticalBar::VerticalBar(std::wstring bitmapName, int x, int y,
    int units, bool reversed) :
Meter(bitmapName, x, y, units),
_pixelsPerUnit(_rect.Height / _units),
_reversed(reversed) {

}

void VerticalBar::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
    int height = _pixelsPerUnit * CalcUnits();
    int yOffset = _rect.Y + _rect.Height - height;

    Gdiplus::Rect drawRect(_rect.X, yOffset, _rect.Width, height);
    if (_reversed) {
        drawRect.Y = _rect.Y;
    }

    Gdiplus::ImageAttributes ia;
    Gdiplus::ColorMap blackToRed;
    blackToRed.oldColor = Gdiplus::Color(255, 255, 0, 255);  // black
    blackToRed.newColor = Gdiplus::Color(255, 255, 0, 0);// red
    ia.SetRemapTable(1, &blackToRed);

    graphics->DrawImage(_bitmap, drawRect,
        0, 0, _rect.Width, height, Gdiplus::UnitPixel, &ia, NULL, NULL);

    UpdateDrawnValues();
}

// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)

#include "VerticalBar.h"

VerticalBar::VerticalBar(std::wstring bitmapName, int x, int y,
    int units, bool reversed) :
Meter(bitmapName, x, y, units),
_pixelsPerUnit(_rect.Height / _units),
_reversed(reversed) {

}

void VerticalBar::Draw(Gdiplus::Bitmap *buffer, Gdiplus::Graphics *graphics) {
    int height = _pixelsPerUnit * CalcUnits();
    int yOffset = _rect.Y + _rect.Height - height;

    Gdiplus::Rect drawRect(_rect.X, yOffset, _rect.Width, height);
    if (_reversed) {
        drawRect.Y = _rect.Y;
    }

    graphics->DrawImage(_bitmap, drawRect, 0, 0, _rect.Width, height,
        Gdiplus::UnitPixel, &_imageAttributes,NULL, NULL);

    UpdateDrawnValues();
}

Remove color transformation test code


// Copyright (c) 2004-present, Facebook, Inc.

// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

#include "ComponentDescriptorRegistry.h"

namespace facebook {
namespace react {

void ComponentDescriptorRegistry::registerComponentDescriptor(SharedComponentDescriptor componentDescriptor) {
  ComponentHandle componentHandle = componentDescriptor->getComponentHandle();
  _registryByHandle[componentHandle] = componentDescriptor;

  ComponentName componentName = componentDescriptor->getComponentName();
  _registryByName[componentName] = componentDescriptor;
}

const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const SharedShadowNode &shadowNode) const {
  ComponentHandle componentHandle = shadowNode->getComponentHandle();
  return _registryByHandle.at(componentHandle);
}

const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const ComponentName &componentName) const {
  return _registryByName.at(componentName);
}

} // namespace react
} // namespace facebook

// Copyright (c) 2004-present, Facebook, Inc.

// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

#include "ComponentDescriptorRegistry.h"

namespace facebook {
namespace react {

void ComponentDescriptorRegistry::registerComponentDescriptor(SharedComponentDescriptor componentDescriptor) {
  ComponentHandle componentHandle = componentDescriptor->getComponentHandle();
  _registryByHandle[componentHandle] = componentDescriptor;

  ComponentName componentName = componentDescriptor->getComponentName();
  _registryByName[componentName] = componentDescriptor;
}

const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const SharedShadowNode &shadowNode) const {
  ComponentHandle componentHandle = shadowNode->getComponentHandle();
  return _registryByHandle.at(componentHandle);
}

const SharedComponentDescriptor ComponentDescriptorRegistry::operator[](const ComponentName &componentName) const {
  auto it = _registryByName.find(componentName);
  if (it == _registryByName.end()) {
     throw std::invalid_argument(("Unable to find componentDescriptor for " + componentName).c_str());
   }
   return it->second;
}

} // namespace react
} // namespace facebook

Improve error message when a component descriptor is not implemented


#include <ionWindow.h>
#include <ionGraphics.h>
#include <ionGraphicsGL.h>
#include <ionScene.h>

using namespace ion;
using namespace Scene;
using namespace Graphics;

int main()
{
	////////////////////
	// ionEngine Init //
	////////////////////

	Log::AddDefaultOutputs();

	SingletonPointer<CWindowManager> WindowManager;
	SingletonPointer<CSceneManager> SceneManager;

	WindowManager->Init();
	CWindow * Window = WindowManager->CreateWindow(vec2i(640, 480), "DemoScene", EWindowType::Windowed);

	IGraphicsAPI * GraphicsAPI = new COpenGLAPI();

	CSimpleMesh * Mesh = CGeometryCreator::CreateSphere();

	ICamera * Camera = nullptr;
	SceneManager->GetScene()->SetActiveCamera(Camera = SceneManager->GetFactory()->AddPerspectiveCamera((Window->GetAspectRatio())));
	Camera->SetPosition(vec3f(0, 0, -3));

	ion::GL::Context::Init();
	while (! WindowManager->ShouldClose())
	{
		WindowManager->PollEvents();
		SceneManager->DrawAll();
		Window->SwapBuffers();
	}

	return 0;
}

#include <ionWindow.h>
#include <ionGraphics.h>
#include <ionGraphicsGL.h>
#include <ionScene.h>

using namespace ion;
using namespace Scene;
using namespace Graphics;

int main()
{
	////////////////////
	// ionEngine Init //
	////////////////////

	Log::AddDefaultOutputs();

	SingletonPointer<CWindowManager> WindowManager;
	SingletonPointer<CSceneManager> SceneManager;

	WindowManager->Init();
	CWindow * Window = WindowManager->CreateWindow(vec2i(640, 480), "DemoScene", EWindowType::Windowed);

	IGraphicsAPI * GraphicsAPI = new COpenGLAPI();

	CSimpleMesh * Mesh = CGeometryCreator::CreateSphere();

	ICamera * Camera = nullptr;
	//SceneManager->GetScene()->SetActiveCamera(Camera = SceneManager->GetFactory()->AddPerspectiveCamera((Window->GetAspectRatio())));
	//Camera->SetPosition(vec3f(0, 0, -3));

	//ion::GL::Context::Init();
	while (WindowManager->Run())
	{
		SceneManager->DrawAll();
		Window->SwapBuffers();
	}

	return 0;
}

Comment out broken parts of Demo04 to fix build


//===-- EmitFunctions.cpp - interface to insert instrumentation --*- C++ -*--=//
//
// This inserts a global constant table with function pointers all along
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Instrumentation/EmitFunctions.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"

using std::vector;

namespace {
  struct EmitFunctionTable : public Pass {
    bool run(Module &M);
  };

  RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table");
}

// Create a new pass to add function table
//
Pass *createEmitFunctionTablePass() {
  return new EmitFunctionTable();
}

// Per Module pass for inserting function table
bool EmitFunctionTable::run(Module &M){
  vector<const Type*> vType;
  vector<Constant *> vConsts;
  for(Module::iterator MI = M.begin(), ME = M.end(); MI!=ME; ++MI)
    if (!MI->isExternal()) {
      ConstantPointerRef *CP = ConstantPointerRef::get(MI);
      vType.push_back(MI->getType());
      vConsts.push_back(CP);
    }

  StructType *sttype = StructType::get(vType);
  ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);

  GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true, false,
                                          cstruct, "llvmFunctionTable");
  M.getGlobalList().push_back(gb);
  return true;  // Always modifies program
}

//===-- EmitFunctions.cpp - interface to insert instrumentation --*- C++ -*--=//
//
// This inserts a global constant table with function pointers all along
//
//===----------------------------------------------------------------------===//

#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"

using std::vector;

namespace {
  struct EmitFunctionTable : public Pass {
    bool run(Module &M);
  };

  RegisterOpt<EmitFunctionTable> X("emitfuncs", "Emit a Function Table");
}

// Per Module pass for inserting function table
bool EmitFunctionTable::run(Module &M){
  vector<const Type*> vType;
  vector<Constant *> vConsts;
  for(Module::iterator MI = M.begin(), ME = M.end(); MI!=ME; ++MI)
    if (!MI->isExternal()) {
      ConstantPointerRef *CP = ConstantPointerRef::get(MI);
      vType.push_back(MI->getType());
      vConsts.push_back(CP);
    }

  StructType *sttype = StructType::get(vType);
  ConstantStruct *cstruct = ConstantStruct::get(sttype, vConsts);

  GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true, false,
                                          cstruct, "llvmFunctionTable");
  M.getGlobalList().push_back(gb);
  return true;  // Always modifies program
}

Remove unused header and function


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

template<typename T>
class X0 {
public:
  void f(T t);
};

template<typename T>
void X0<T>::f(T t) {
  t = 17;
}

// FIXME: Later, we'll want to write an explicit template
// declaration (extern template) for X0<int*>, then try to
// call X0<int*>::f. The translation unit should succeed,
// because we're not allowed to instantiate the out-of-line
// definition of X0<T>::f. For now, this is just a parsing
// test.
extern template class X0<int>;

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

template<typename T>
class X0 {
public:
  void f(T t);

  struct Inner {
    void g(T t);
  };
};

template<typename T>
void X0<T>::f(T t) {
  t = 17;
}

extern template class X0<int>;

extern template class X0<int*>;

template<typename T>
void X0<T>::Inner::g(T t) {
  t = 17;
}

void test_intptr(X0<int*> xi, X0<int*>::Inner xii) {
  xi.f(0);
  xii.g(0);
}

Improve testing for extern temp templates, slightly. We are (properly) suppressing the implicit instantiation of members of extern templates


/*
 * Copyright 2014 The Imaging Source Europe GmbH
 *
 * 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 "DeviceInterface.h"
#include "logging.h"

#include "BackendLoader.h"

#include <algorithm>
#include <memory>

using namespace tcam;

std::shared_ptr<DeviceInterface> tcam::openDeviceInterface (const DeviceInfo& device)
{

    try
    {
        return BackendLoader::getInstance().open_device(device);
    }
    catch (...)
    {
        tcam_log(TCAM_LOG_ERROR, "Encountered Error while creating device interface.");
        return nullptr;
    }
    return nullptr;
}

/*
 * Copyright 2014 The Imaging Source Europe GmbH
 *
 * 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 "DeviceInterface.h"
#include "logging.h"

#include "BackendLoader.h"

#include <algorithm>
#include <memory>

using namespace tcam;

std::shared_ptr<DeviceInterface> tcam::openDeviceInterface (const DeviceInfo& device)
{

    try
    {
        return BackendLoader::getInstance().open_device(device);
    }
    catch (const std::runtime_error& err)
    {
        tcam_error("Encountered Error while creating device interface. %s", err.what());
        return nullptr;
    }
    catch (...)
    {
        tcam_error("Caught unhandled exception while opening device.");
    }
    return nullptr;
}

Add exception description string to log for runtime_error


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

#include "PlaceJumpController.h"
#include "IPlaceJumpsModel.h"
#include "LatLongAltitude.h"
#include "Types.h"
#include "ICameraTransitionController.h"

namespace ExampleApp
{
    namespace PlaceJumps
    {
        namespace SdkModel
        {
            PlaceJumpController::PlaceJumpController(CameraTransitions::SdkModel::ICameraTransitionController& cameraTransitionController)
                : m_cameraTransitionController(cameraTransitionController)
            {
            }

            void PlaceJumpController::JumpTo(const View::IPlaceJumpModel& jumpModel)
            {
                m_cameraTransitionController.StartTransitionTo(jumpModel.GetLocation().ToECEF(), jumpModel.GetDistance(), jumpModel.GetHeadingDegrees());
            }
        }
    }
}

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

#include "PlaceJumpController.h"
#include "IPlaceJumpsModel.h"
#include "LatLongAltitude.h"
#include "Types.h"
#include "ICameraTransitionController.h"

namespace ExampleApp
{
    namespace PlaceJumps
    {
        namespace SdkModel
        {
            PlaceJumpController::PlaceJumpController(CameraTransitions::SdkModel::ICameraTransitionController& cameraTransitionController)
                : m_cameraTransitionController(cameraTransitionController)
            {
            }

            void PlaceJumpController::JumpTo(const View::IPlaceJumpModel& jumpModel)
            {
                m_cameraTransitionController.StartTransitionTo(jumpModel.GetLocation().ToECEF(), jumpModel.GetDistance(), Eegeo::Math::Deg2Rad(jumpModel.GetHeadingDegrees()));
            }
        }
    }
}

Fix for MPLY-6024. PLacejump system now correctly converts degrees to radians for target headings. Buddy: Vimarsh


#include "Item.h"

using namespace node;
using namespace v8;

namespace node_iTunes {

// Convenience function that takes an iTunesItem instance (or any subclass)
// and wraps it up into the proper JS class type, and returns it.
// TODO: Implement some kind of Object Cache, so if the same instance is
//       attempting to be wrapped again, then the same JS Object is returned.
v8::Handle<Value> Item::WrapInstance(iTunesItem* item) {
  HandleScope scope;

  NSLog(@"%@", item);
  if (item == nil) {
    return scope.Close(Null());
  }

  NSString* className = NSStringFromClass([item class]);
  NSLog(@"Class: %@", className);
  Local<Object> jsItem;
  if ([className isEqualToString:@"ITunesURLTrack" ]) {
    jsItem = url_track_constructor_template->GetFunction()->NewInstance();
  } else {
    jsItem = track_constructor_template->GetFunction()->NewInstance();
  }
  Item* itemWrap = ObjectWrap::Unwrap<Item>(jsItem);
  itemWrap->itemRef = item;
  return scope.Close(jsItem);
}

}

#include "Item.h"

using namespace node;
using namespace v8;

namespace node_iTunes {

// Convenience function that takes an iTunesItem instance (or any subclass)
// and wraps it up into the proper JS class type, and returns it.
// TODO: Implement some kind of Object Cache, so if the same instance is
//       attempting to be wrapped again, then the same JS Object is returned.
v8::Handle<Value> Item::WrapInstance(iTunesItem* item) {
  HandleScope scope;

  //NSLog(@"%@", [item persistentID]);
  if (item == nil) {
    return scope.Close(Null());
  }

  NSString* className = NSStringFromClass([item class]);
  //NSLog(@"Class: %@", className);
  Local<Object> jsItem;
  if ([className isEqualToString:@"ITunesURLTrack" ]) {
    jsItem = url_track_constructor_template->GetFunction()->NewInstance();
  } else if ([className isEqualToString:@"ITunesFileTrack" ]) {
    jsItem = file_track_constructor_template->GetFunction()->NewInstance();
  } else if ([className isEqualToString:@"ITunesTrack" ]) {
    jsItem = track_constructor_template->GetFunction()->NewInstance();
  } else {
    jsItem = item_constructor_template->GetFunction()->NewInstance();
  }
  Item* itemWrap = ObjectWrap::Unwrap<Item>(jsItem);
  itemWrap->itemRef = item;
  return scope.Close(jsItem);
}

}

Remove NSLog statements. Add WrapInstance support for FileTrack.


// This is the starting point
//
#include <iostream>
#include <fstream>
#include <sstream>

int main() {
    std::string first_input;
    std::string second_input;

    std::cout << "Enter the first string" << std::endl;
    std::cin >> first_input;
    std::cout << "Enter the second string" << std::endl;
    std::cin >> second_input;

    if (first_input == second_input) {
        std::cout << "Match!" << std::endl;
    }

    std::string fileName;
    std::cout << "Enter a filename in which to look for the string" << std::endl;
    std::cin >> fileName;

    std::ifstream file_input_stream(fileName);
    std::string line;
    if (file_input_stream.is_open()) {
        std::cout << "Successfully opened " << fileName << std::endl;
        while(true) {
            if (file_input_stream.fail()) {
                std::cout << "The file input stream went into an error state" << std::endl;
                break;
            }
            getline(file_input_stream, line);
            std::cout << line << std::endl;
            if (first_input == line) {
                std::cout << "Match!" << std::endl;
            }
        }
    } else {
        std::cout << "Could not open file for reading" << std::endl;
    }

    return 0;
}

// This is the starting point
//
#include <iostream>
#include <fstream>
#include <sstream>

int main(int argc, char * argv[]) {
    std::cout << "You supplied " << argc << " arguments, which were: " << std::endl;
    for (size_t i = 0; i < argc; ++i) {
        std::cout << argv[i] << std::endl;
    }
    std::string first_input;
    std::string second_input;

    std::cout << "Enter the first string" << std::endl;
    std::cin >> first_input;
    std::cout << "Enter the second string" << std::endl;
    std::cin >> second_input;

    if (first_input == second_input) {
        std::cout << "Match!" << std::endl;
    }

    std::string fileName;
    std::cout << "Enter a filename in which to look for the string" << std::endl;
    std::cin >> fileName;

    std::ifstream file_input_stream(fileName);
    std::string line;
    if (file_input_stream.is_open()) {
        std::cout << "Successfully opened " << fileName << std::endl;
        while(true) {
            if (file_input_stream.fail()) {
                std::cout << "The file input stream went into an error state" << std::endl;
                break;
            }
            getline(file_input_stream, line);
            std::cout << line << std::endl;
            if (first_input == line) {
                std::cout << "Match!" << std::endl;
            }
        }
    } else {
        std::cout << "Could not open file for reading" << std::endl;
    }

    return 0;
}

Add ability to read arguments from the command line


#include "Game/Game_Result.h"

#include <string>

#include "Game/Color.h"
#include "Utility.h"

Game_Result::Game_Result() : victor(NONE), cause()
{
}

Game_Result::Game_Result(Color winner,
                         const std::string& reason) :
                             victor(winner),
                             cause(reason)
{
}

bool Game_Result::game_has_ended() const
{
    return ! cause.empty();
}

Color Game_Result::winner() const
{
    return victor;
}

std::string Game_Result::ending_reason() const
{
    return cause;
}

std::string Game_Result::game_ending_annotation() const
{
    switch(winner())
    {
        case WHITE:
            return "1-0";
        case BLACK:
            return "0-1";
        default:
            return game_has_ended() ? "1/2-1/2" : "";
    }
}

std::string Game_Result::game_record_annotation() const
{
    if(game_has_ended())
    {
        std::string prefix = "\t";
        if(String::ends_with(cause, "mates"))
        {
            prefix =  "#" + prefix;
        }
        return prefix + game_ending_annotation();
    }
    else
    {
        return {};
    }
}

#include "Game/Game_Result.h"

#include <string>

#include "Game/Color.h"
#include "Utility.h"

Game_Result::Game_Result() : victor(NONE), cause()
{
}

Game_Result::Game_Result(Color winner,
                         const std::string& reason) :
                             victor(winner),
                             cause(reason)
{
}

bool Game_Result::game_has_ended() const
{
    return ! cause.empty();
}

Color Game_Result::winner() const
{
    return victor;
}

std::string Game_Result::ending_reason() const
{
    return cause;
}

std::string Game_Result::game_ending_annotation() const
{
    switch(winner())
    {
        case WHITE:
            return "1-0";
        case BLACK:
            return "0-1";
        default:
            return game_has_ended() ? "1/2-1/2" : "";
    }
}

std::string Game_Result::game_record_annotation() const
{
    if(game_has_ended())
    {
        std::string prefix = " ";
        if(String::ends_with(cause, "mates"))
        {
            prefix =  "#" + prefix;
        }
        return prefix + game_ending_annotation();
    }
    else
    {
        return {};
    }
}

Replace tab with space to separate game result


unsigned __int32 Ret_Int(unsigned __int32 argVal){
	unsigned __int32 retVal = (unsigned __int32)argVal;
	return retVal;
}
unsigned __int32 Ret_Ptr(void *argVal){
	unsigned __int32 retVal = (unsigned __int32)argVal;
	return retVal;
}

void Set_Val(__int32 *argVal, __int32 val){
	*argVal = val;;

}

void Mul_Val(__int32 *arg1,__int32 *arg2,__int32 *arg3){
	*arg3 = (*arg1)*(*arg2);

}

#if defined(_MSC_VER)
#define EXPORT_API extern "C" __declspec(dllexport)
#else
#define EXPORT_API extern "C" __attribute__((visibility("default")))
#endif

EXPORT_API unsigned __int32 Ret_Int(unsigned __int32 argVal){
	unsigned __int32 retVal = (unsigned __int32)argVal;
	return retVal;
}
EXPORT_API unsigned __int32 Ret_Ptr(void *argVal){
	unsigned __int32 retVal = (unsigned __int32)argVal;
	return retVal;
}

EXPORT_API void Set_Val(__int32 *argVal, __int32 val){
	*argVal = val;;

}

EXPORT_API void Mul_Val(__int32 *arg1,__int32 *arg2,__int32 *arg3){
	*arg3 = (*arg1)*(*arg2);

}

Fix a test bug where dllexport qualifier was missing.


//===-- ExampleClangProtoFuzzer.cpp - Fuzz Clang --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements a function that runs Clang on a single
///  input and uses libprotobuf-mutator to find new inputs. This function is
///  then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//

#include "cxx_proto.pb.h"
#include "handle-cxx/handle_cxx.h"
#include "proto-to-cxx/proto_to_cxx.h"
#include "fuzzer-initialize/fuzzer_initialize.h"
#include "src/libfuzzer/libfuzzer_macro.h"

using namespace clang_fuzzer;

DEFINE_BINARY_PROTO_FUZZER(const Function& input) {
  auto S = FunctionToString(input);
  HandleCXX(S, GetCLArgs());
}

//===-- ExampleClangProtoFuzzer.cpp - Fuzz Clang --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements a function that runs Clang on a single
///  input and uses libprotobuf-mutator to find new inputs. This function is
///  then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//

#include "cxx_proto.pb.h"
#include "handle-cxx/handle_cxx.h"
#include "proto-to-cxx/proto_to_cxx.h"
#include "fuzzer-initialize/fuzzer_initialize.h"
#include "src/libfuzzer/libfuzzer_macro.h"

using namespace clang_fuzzer;

DEFINE_BINARY_PROTO_FUZZER(const Function& input) {
  auto S = FunctionToString(input);
  HandleCXX(S, "./test.cc", GetCLArgs());
}

Update proto fuzzer example for r375453.


#include "gtest/gtest.h"
#include "maze.h"
#include "mazereader.h"
#include "mazeflooder.h"
#include "mazepathfinder.h"
#include "mazeprinter.h"

TEST(PathFinder,test){
    MazeResetData();
    ReadMAZFile("mazefiles/empty.maz");
    FloodMazeClassic(DefaultGoal());
    ASSERT_EQ(0xFE,MazeGetWalls(Home()));
    int pathLength = IsolatePath(Home(),Goal());
    PrintMaze(DIRS);
    ASSERT_EQ(12,pathLength);
}

#include "gtest/gtest.h"
#include "maze.h"
#include "mazereader.h"
#include "mazeflooder.h"
#include "mazepathfinder.h"
#include "mazeprinter.h"

TEST(PathFinder,test){
    MazeResetData();
    ReadMAZFile("mazefiles/empty.maz");
    FloodMazeClassic(DefaultGoal());
    ASSERT_EQ(0xFE,MazeGetWalls(Home()));
//    int pathLength = IsolatePath(Home(),Goal());
//    PrintMaze(DIRS);
//    ASSERT_EQ(12,pathLength);
}

Disable testPathFinder. Does not terminate!


#include "Timer.h"

#define BOOST_TEST_MODULE TimerTest
#include <boost/test/unit_test.hpp>

#include <string>
#include <iostream>
#include <unistd.h>

BOOST_AUTO_TEST_CASE(timer_basic_test) {
  Timer timer;
  const int sleep_time_microsec = 40; // ad-hoc microseconds to pass unit tests.

  timer.start();
  BOOST_REQUIRE(timer.is_running());
  BOOST_REQUIRE(usleep(sleep_time_microsec) == 0);
  // BOOST_CHECK(timer.get_elapsed_cpu_time() > 0.0);
  // BOOST_CHECK(timer.get_elapsed_cpu_time_microseconds() > 0);
  BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0);
  BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0);

  timer.restart();
  BOOST_REQUIRE(timer.is_running());
  BOOST_REQUIRE(usleep(sleep_time_microsec) == 0);
  // BOOST_CHECK(timer.get_elapsed_cpu_time() > 0.0);
  // BOOST_CHECK(timer.get_elapsed_cpu_time_microseconds() > 0);
  BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0);
  BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0);

  const std::string s = timer.ToString();
  BOOST_CHECK(!s.empty());
}

#include "Timer.h"

#define BOOST_TEST_MODULE TimerTest
#include <boost/test/unit_test.hpp>

#include <string>
#include <unistd.h>

BOOST_AUTO_TEST_CASE(timer_basic_test) {
  Timer timer;
  const int sleep_time_microsec = 40; // ad-hoc microseconds to pass unit tests.

  timer.start();
  BOOST_REQUIRE(timer.is_running());
  BOOST_REQUIRE(usleep(sleep_time_microsec) == 0);
  BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0);
  BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0);

  timer.restart();
  BOOST_REQUIRE(timer.is_running());
  BOOST_REQUIRE(usleep(sleep_time_microsec) == 0);
  BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0);
  BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0);

  const std::string s = timer.ToString();
  BOOST_CHECK(!s.empty());
}

Delete assertions to check elapsed CPU time.


// RUN: %llvmgxx %s -S -o - | not grep llvm.global_ctor

struct S {
  int  A[2];
};

int XX = (int)&(((struct S*)0)->A[1]);

// RUN: %llvmgxx %s -S -o - | not grep llvm.global_ctor

struct S {
  int  A[2];
};

int XX = (int)(long)&(((struct S*)0)->A[1]);

Make it work on 64-bit systems.


// http://www.geeksforgeeks.org/pure-virtual-destructor-c/
// 1) C++ Accepts pure virtual destructors, a Base class needs to provide definition for pure
// virtual destructor as well because it is being called in reverse order and compiler
// looks for its definition
// 2) class contains abstract class if it contains any pure virtual functions
// 3) If a base class has pure virtual functions
// in the derived class to implement it
#include <iostream>
using namespace std;

class Base {
    public:
    virtual ~Base() = 0; // pure virtual destructor
    virtual void foo() = 0;
};

// Definition of destructor
// if this is not defined compiler throws
// linker error
Base :: ~Base() {
    cout<<"Base destructor called\n";
}

class Derived : public Base {
    public:
    ~Derived() {
        cout<<"Derived destructor called\n";
    }
    void foo() {
        cout<<"I am foo\n";
    }
};

int main() {
    // the below is not possible because Base is abstract
    // Derived *d = new Base();
    // Base is inaccessible here when it is not public
    Base *b = new Derived();
    // first calls derived then calls base
    delete b;
    return 0;
}

// http://www.geeksforgeeks.org/pure-virtual-destructor-c/
// 1) C++ Accepts pure virtual destructors, a Base class needs to provide definition for pure
// virtual destructor as well because it is being called in reverse order and compiler
// looks for its definition
// 2) class contains abstract class if it contains any pure virtual functions
// 3) If a base class has pure virtual functions
// in the derived class to implement it

/**
 * Virtual destructor are useful when
 * a derived class object is destroyed
 * only its destructor is called, if the base
 * class destructor is made as virtual, then both
 * derived and base class destructor is called.
 */
#include <iostream>
using namespace std;

class Base {
    public:
    virtual ~Base() = 0; // pure virtual destructor
    virtual void foo() = 0;
};

// Definition of destructor
// if this is not defined compiler throws
// linker error
Base :: ~Base() {
    cout<<"Base destructor called\n";
}

class Derived : public Base {
    public:
    ~Derived() {
        cout<<"Derived destructor called\n";
    }
    void foo() {
        cout<<"I am foo\n";
    }
};

int main() {
    // the below is not possible because Base is abstract
    // Derived *d = new Base();
    // Base is inaccessible here when it is not public
    Base *b = new Derived();
    // first calls derived then calls base
    delete b;
    return 0;
}

Add explaination to why virtual destructors are needed


#include "ofMain.h"
#include "ofApp.h"
#include "ofAppGLFWWindow.h"

int main() {
    ofGLFWWindowSettings settings;
    settings.width = 1280;
    settings.height = 720;
    settings.setPosition(ofVec2f(300,0));
    settings.resizable = true;
    shared_ptr<ofAppBaseWindow> mainWindow = ofCreateWindow(settings);
    mainWindow->setFullscreen(true);

    settings.width = 500;
    settings.height = 800;
    settings.setPosition(ofVec2f(0,0));
    shared_ptr<ofAppBaseWindow> guiWindow = ofCreateWindow(settings);

    shared_ptr<ofApp> mainApp(new ofApp);
    mainApp->setupGui();
    ofAddListener(guiWindow->events().draw, mainApp.get(), &ofApp::drawGui);

    ofRunApp(mainWindow, mainApp);
    ofRunMainLoop();
}

#include "ofMain.h"
#include "ofApp.h"
#include "ofAppGLFWWindow.h"

int main() {
    ofGLFWWindowSettings settings;
    settings.width = 1280;
    settings.height = 720;
    settings.setPosition(ofVec2f(300,0));
    settings.resizable = true;
    shared_ptr<ofAppBaseWindow> mainWindow = ofCreateWindow(settings);
    mainWindow->setFullscreen(true);

    settings.width = 500;
    settings.height = 900;
    settings.setPosition(ofVec2f(0,0));
    shared_ptr<ofAppBaseWindow> guiWindow = ofCreateWindow(settings);

    shared_ptr<ofApp> mainApp(new ofApp);
    mainApp->setupGui();
    ofAddListener(guiWindow->events().draw, mainApp.get(), &ofApp::drawGui);

    ofRunApp(mainWindow, mainApp);
    ofRunMainLoop();
}

Make GUI window a bit taller


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

struct Base {
  virtual void override();
};

struct S : Base {
  virtual void final() final;
  virtual void override() override;
};

struct T {
  // virt-specifier-seq is only valid in member-declarators, and a function definition is not a member-declarator.
  // FIXME: This currently doesn't work.
  // virtual void f() const override { }
};

struct override;
struct Base2 {
  virtual override override(int override);
};

struct A : Base2 {
  virtual struct override override(int override) override;
};

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

struct Base {
  virtual void override();
};

struct S : Base {
  virtual void final() final;
  virtual void override() override;
};

struct T : Base {
  virtual void override() override { }
};

struct override;
struct Base2 {
  virtual override override(int override);
};

struct A : Base2 {
  virtual struct override override(int override) override;
};

Remove obsolete FIXME. override on definitions is fine.


/*
Author: vpetrigo
Task:
    ,
        .
        .

   ,   0.
       .

   ,
  0 (  0    ,
     ).

   .
Sample Input:
1
2
1
2
1
0
Sample Output:
2

*/

#include <iostream>

using namespace std;

int main() {
    int prev = -1;
    int cur = -1;

    bool prev_gr = false;
    int cnt = 0;

    while (cin >> cur && cur != 0) {
        if (prev != -1) {
            if (prev < cur && !prev_gr) {
                prev_gr = true;
            }
            else if (prev_gr) {
                if (cur < prev) {
                    ++cnt;
                    prev_gr = false;
                }
                else if (cur == prev) {
                    prev_gr = false;
                }
            }
            else {
                prev_gr = false;
            }
        }

        prev = cur;
    }

    cout << cnt;

    return 0;
}

/*
Author: vpetrigo
Task:
    ,
        .
        .

   ,   0.
       .

   ,
  0 (  0    ,
     ).

   .
Sample Input:
1
2
1
2
1
0
Sample Output:
2

*/

#include <iostream>

using namespace std;

int main() {
    int prev = -1;
    int cur = -1;

    bool prev_gr = false;
    int cnt = 0;

    // Option 1
    while (cin >> cur && cur != 0) {
        if (prev != -1) {
            if (prev < cur && !prev_gr) {
                prev_gr = true;
            }
            else if (prev_gr) {
                if (cur < prev) {
                    ++cnt;
                    prev_gr = false;
                }
                else if (cur == prev) {
                    prev_gr = false;
                }
            }
            else {
                prev_gr = false;
            }
        }

        prev = cur;
    }

    // Option 2

    int next;

    if (cin >> prev && prev != 0) {
        if (cin >> cur && cur != 0) {
            if (cin >> next) {
                while (next != 0) {
                    if (prev < cur && cur > next) {
                        ++cnt;
                    }
                    prev = cur;
                    cur = next;
                    cin >> next;
                }
            }
        }
    }

    cout << cnt;

    return 0;
}

Add another solution for week 3, task 13


// RUN: %clang_cc1 -fsyntax-only -verify %s

class X {};

void test() {
  X x;

  x.int; // expected-error{{expected unqualified-id}}
  x.~int(); // expected-error{{expected a class name}}
  x.operator; // expected-error{{expected a type}}
  x.operator typedef; // expected-error{{expected a type}} expected-error{{type name does not allow storage class}}
}

void test2() {
  X *x;

  x->int; // expected-error{{expected unqualified-id}}
  x->~int(); // expected-error{{expected a class name}}
  x->operator; // expected-error{{expected a type}}
  x->operator typedef; // expected-error{{expected a type}} expected-error{{type name does not allow storage class}}
}

// PR6327
namespace test3 {
  template <class A, class B> struct pair {};

  void test0() {
    pair<int, int> z = minmax({}); // expected-error {{expected expression}}
  }

  struct string {
    class iterator {};
  };

  void test1() {
    string s;
    string::iterator i = s.foo(); // expected-error {{no member named 'foo'}}
  }
}

// Make sure we don't crash.
namespace rdar11293995 {

struct Length {
  explicit Length(PassRefPtr<CalculationValue>); // expected-error {{unknown type name}} \
                    expected-error {{expected ')'}} \
                    expected-note {{to match this '('}}
};

struct LengthSize {
    Length m_width;
    Length m_height;
};

enum EFillSizeType { Contain, Cover, SizeLength, SizeNone };

struct FillSize {
    EFillSizeType type;
    LengthSize size;
};

class FillLayer {
public:
    void setSize(FillSize f) { m_sizeType = f.type;}
private:
    unsigned m_sizeType : 2;
};

}

Add test case for rdar://11293995


// 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 "ui/aura/toplevel_window_container.h"

#include "base/utf_string_conversions.h"
#include "ui/aura/toplevel_window_event_filter.h"

namespace aura {

ToplevelWindowContainer::ToplevelWindowContainer()
    : Window(NULL) {
  set_name("ToplevelWindowContainer");
  SetEventFilter(new ToplevelWindowEventFilter(this));
}

ToplevelWindowContainer::~ToplevelWindowContainer() {
}

Window* ToplevelWindowContainer::GetTopmostWindowToActivate(
    Window* ignore) const {
  for (Window::Windows::const_reverse_iterator i = children().rbegin();
       i != children().rend(); ++i) {
         Window* w = *i;
    if (*i != ignore && (*i)->CanActivate())
      return *i;
  }
  return NULL;
}

ToplevelWindowContainer* ToplevelWindowContainer::AsToplevelWindowContainer() {
  return this;
}

const ToplevelWindowContainer*
    ToplevelWindowContainer::AsToplevelWindowContainer() const {
  return this;
}
}  // namespace aura

// 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 "ui/aura/toplevel_window_container.h"

#include "base/utf_string_conversions.h"
#include "ui/aura/toplevel_window_event_filter.h"

namespace aura {

ToplevelWindowContainer::ToplevelWindowContainer()
    : Window(NULL) {
  set_name("ToplevelWindowContainer");
  SetEventFilter(new ToplevelWindowEventFilter(this));
}

ToplevelWindowContainer::~ToplevelWindowContainer() {
}

Window* ToplevelWindowContainer::GetTopmostWindowToActivate(
    Window* ignore) const {
  for (Window::Windows::const_reverse_iterator i = children().rbegin();
       i != children().rend(); ++i) {
    if (*i != ignore && (*i)->CanActivate())
      return *i;
  }
  return NULL;
}

ToplevelWindowContainer* ToplevelWindowContainer::AsToplevelWindowContainer() {
  return this;
}

const ToplevelWindowContainer*
    ToplevelWindowContainer::AsToplevelWindowContainer() const {
  return this;
}
}  // namespace aura

Fix aura bustage on linux.


#include "ofMain.h"
#include "ofApp.h"

int main( ){

    ofSetupOpenGL(1024, 768, OF_WINDOW);
    ofxDatGui::setAssetPath("./");

    // this kicks off the running of my app
    // can be OF_WINDOW or OF_FULLSCREEN
    // pass in width and height too:
    ofRunApp(new ofApp());
}

#include "ofMain.h"
#include "ofApp.h"

int main( ){

    ofSetupOpenGL(1024, 768, OF_WINDOW);
    ofSetDataPathRoot("../Resources/data/");
    ofxDatGui::setAssetPath("./");

    // this kicks off the running of my app
    // can be OF_WINDOW or OF_FULLSCREEN
    // pass in width and height too:
    ofRunApp(new ofApp());
}

Use the data/ directory in the Mac app bundle.


#include "Config.hpp"

#include "Calculator.hpp"

Calculator::Calculator()
{
    ready = false;
}

Calculator::Calculator(int a, int b)
{
    ready = false;

    create(a, b);
}

Calculator::~Calculator()
{
    if (valid())
    {
        destroy();
    }
}

bool Calculator::create(int a, int b)
{
    if (valid())
    {
        throw std::exception("Calculator object is initialised!");
    }

    this->a = a;

    this->b = b;

    ready = !ready;

    return true;
}

bool Calculator::valid()
{
    return ready;
}

void Calculator::destroy()
{
    if (!valid())
    {
        throw std::exception("Calculator object is not initialised!");
    }

    a = b = 0;

    ready = !ready;
}

int Calculator::sum()
{
    return a + b;
}

int Calculator::mul()
{
    return a * b;
}

int Calculator::diff()
{
    return a - b;
}

int Calculator::div()
{
    if (!a)
    {
        return 0;
    }

    return a / b;
}

#include "Config.hpp"

#include "Calculator.hpp"

Calculator::Calculator()
{
    ready = false;
}

Calculator::Calculator(int a, int b)
{
    ready = false;

    create(a, b);
}

Calculator::~Calculator()
{
    if (valid())
    {
        destroy();
    }
}

bool Calculator::create(int a, int b)
{
    if (valid())
    {
        throw std::runtime_error("Calculator object is initialised!");
    }

    this->a = a;

    this->b = b;

    ready = !ready;

    return true;
}

bool Calculator::valid()
{
    return ready;
}

void Calculator::destroy()
{
    if (!valid())
    {
        throw std::runtime_error("Calculator object is not initialised!");
    }

    a = b = 0;

    ready = !ready;
}

int Calculator::sum()
{
    return a + b;
}

int Calculator::mul()
{
    return a * b;
}

int Calculator::diff()
{
    return a - b;
}

int Calculator::div()
{
    if (!a)
    {
        return 0;
    }

    return a / b;
}

Fix excepion name for linux platform.


#include <iostream>
#include <dns_sd.h>
#include <ev++.h>

#include "build_version.h"

int main(int argc, char *argv[]) {
    if (2 != argc) {
        std::cerr << argv[0] << " <announce file>" << std::endl;
        std::cerr << "Version: " << VERSION << std::endl;
        return -1;
    }
    return 0;
}

#include <iostream>
#include <dns_sd.h>
#include <ev++.h>

#include "build_version.h"

inline void check_dnsservice_errors(DNSServiceErrorType& e, const std::string& func_name) {
    std::string error(func_name);
    error += ": ";

    switch (e) {
        case kDNSServiceErr_NoError:
            return;
        case kDNSServiceErr_NameConflict:
            error += "Name in use, please choose another";
            break;
        case kDNSServiceErr_Invalid:
            error += "An invalid index or character was passed";
            break;
        case kDNSServiceErr_BadReference:
            error += "Bad reference";
            break;
        case kDNSServiceErr_BadParam:
            error += "Bad parameter value passed to function.";
            break;
        default:
            error += "Unknown error code... ";
            error += std::to_string(e);
    }

    throw std::runtime_error(error.c_str());
}

int main(int argc, char *argv[]) {
    if (2 != argc) {
        std::cerr << argv[0] << " <announce file>" << std::endl;
        std::cerr << "Version: " << VERSION << std::endl;
        return -1;
    }
    return 0;
}

Add utilty function for checking errors


#include "CanvasView.h"

#include <QMouseEvent>

CanvasView::CanvasView(QWidget* parent)
    : QGraphicsView(parent)
{

}

CanvasView::~CanvasView()
{

}

void CanvasView::mouseReleaseEvent(QMouseEvent *event)
{
    QPointF localPos = QGraphicsView::mapToScene(event->pos());
    emit signalMouseReleaseEvent(localPos);
}

#include "CanvasView.h"

#include <QMouseEvent>

CanvasView::CanvasView(QWidget* parent)
    : QGraphicsView(parent)
{

}

CanvasView::~CanvasView()
{

}

void CanvasView::mouseReleaseEvent(QMouseEvent *event)
{
    QGraphicsView::mouseReleaseEvent(event);

    QPointF localPos = QGraphicsView::mapToScene(event->pos());
    emit signalMouseReleaseEvent(localPos);
}

Fix mouse move item bug


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

#include "chrome/browser/extensions/extension_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

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

#include "chrome/browser/extensions/extension_apitest.h"

// Started failing with r29947. WebKit merge 49961:49992.
IN_PROC_BROWSER_TEST_F(DISABLED_ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

Disable test failing since r29947.


/* $Id$ */

#include <lac/sparse_vanka.templates.h>

// explicit instantiations
template class SparseVanka<float>;
template class SparseVanka<double>;

template void SparseVanka<double>::operator () (Vector<float>       &dst,
						const Vector<float> &src) const;
template void SparseVanka<double>::operator () (Vector<double>       &dst,
						const Vector<double> &src) const;

template class SparseBlockVanka<float>;
template class SparseBlockVanka<double>;

template void SparseBlockVanka<double>::operator () (Vector<float>       &dst,
						     const Vector<float> &src) const;
template void SparseBlockVanka<double>::operator () (Vector<double>       &dst,
						     const Vector<double> &src) const;

Implement the block version of the Vanka smoother.


#include "binarytree.h"

#include <iostream>

using namespace std;

template <class T>
void dotPrint(ostream& out, typename BinaryTree<T>::Inspector treeInspector, size_t id)
{
	out << id << "[label=\"" << treeInspector.getData() << "\"];" << endl;
	if (treeInspector.hasLeft())
	{
		out << id << " -> " << id + 1 << ";" << endl;
		treeInspector.goLeft();
		dotPrint<T>(out, treeInspector, id + 1);
		treeInspector.goToParent();
	}
	if (treeInspector.hasRight())
	{
		out << id << " -> " << id + 2 << ";" << endl;
		treeInspector.goRight();
		dotPrint<T>(out, treeInspector, id + 2);
		treeInspector.goToParent();
	}
}

template <class T>
void dotPrint(ostream& out, const BinaryTree<T>& tree)
{
	out << "digraph G\n{\n";
	dotPrint<T>(out, tree.getInspector(), 0);
	out << "}\n";
}

int main()
{
	BinaryTree<int> tree;

	BinaryTree<int>::Transformer tr = tree.getTransformer();

	tr.addData(5);

	tr.goLeft();
	tr.addData(2);

	tr.goToParent();
	tr.goRight();
	tr.addData(3);

	dotPrint(cout, tree);

	return 0;
}

#include "binarytree.h"

#include <iostream>

using namespace std;

template <class T>
void dotPrint(ostream& out, typename BinaryTree<T>::Inspector treeInspector, size_t id)
{
	if (treeInspector.isEmpty())
	{
		out << id << "[label=\"NULL\" shape=point];" << endl;
		return;
	}
	out << id << "[label=\"" << treeInspector.getData() << "\"];" << endl;

	out << id << " -> " << 2*id + 1 << ";" << endl;
	dotPrint<T>(out, treeInspector.left(), 2*id + 1);

	out << id << " -> " << 2*id + 2 << ";" << endl;
	dotPrint<T>(out, treeInspector.right(), 2*id + 2);
}

template <class T>
void dotPrint(ostream& out, const BinaryTree<T>& tree)
{
	out << "digraph G\n{\n";
	dotPrint<T>(out, tree.getInspector(), 0);
	out << "}\n";
}

int main()
{
	BinaryTree<int> tree;

	BinaryTree<int>::Transformer tr = tree.getTransformer();

	tr.addData(5);

	tr.goLeft();
	tr.addData(2);

	tr.goToParent();
	tr.goRight();
	tr.addData(3);

	dotPrint(cout, tree);

	return 0;
}

Fix Binary Tree DOT print


#include "TestData.h"

TEST(DataObjectTests, ScalarDataObjectHasCorrectProperties) {
    float scalarValue = 5.0;
    DataObject five(scalarValue);
    EXPECT_EQ(five.Dim(), 0);
    std::vector<int64_t> expectedShape;
    EXPECT_EQ(five.Shape(), expectedShape);
    EXPECT_EQ(five.GetKind(), DataKind::SCALAR);
}

TEST(DataObjectTests, MatrixDataObjectHasCorrectProperties) {
    Eigen::MatrixXf m(3, 2);
    DataObject matrix(m);
    EXPECT_EQ(matrix.Dim(), 2);
    std::vector<int64_t> expectedShape({3, 2});
    EXPECT_EQ(matrix.Shape(), expectedShape);
    EXPECT_EQ(matrix.GetKind(), DataKind::MATRIX);
}

TEST(DataObjectTests, ScalarDataObjectGivesCorrectScalarConversion) {
    DataObject five = Scalar(5.0);
    EXPECT_FLOAT_EQ(five.ToScalar(), 5.0);
    bool comparatorWorks = five == 5.0;
    EXPECT_EQ(comparatorWorks, true);
}

TEST(DataObjectTests, MatrixDataObjectGivesCorrectMatrixConversion) {
    Eigen::MatrixXf m(3, 2);
    DataObject matrix = Mat(m);
    EXPECT_EQ(matrix.ToMatrix(), m);
    bool comparatorWorks = matrix == m;
    EXPECT_EQ(comparatorWorks, true);
}

#include "TestData.h"

TEST(DataObjectTests, ScalarDataObjectHasCorrectProperties) {
    float scalarValue = 5.0;
    DataObject five(scalarValue);
    EXPECT_EQ(five.Dim(), 0);
    std::vector<int64_t> expectedShape;
    EXPECT_EQ(five.Shape(), expectedShape);
    EXPECT_EQ(five.GetKind(), DataKind::SCALAR);
}

TEST(DataObjectTests, MatrixDataObjectHasCorrectProperties) {
    Eigen::MatrixXf m(3, 2);
    DataObject matrix(m);
    EXPECT_EQ(matrix.Dim(), 2);
    std::vector<int64_t> expectedShape({3, 2});
    EXPECT_EQ(matrix.Shape(), expectedShape);
    EXPECT_EQ(matrix.GetKind(), DataKind::MATRIX);
}

TEST(DataObjectTests, ScalarDataObjectGivesCorrectScalarConversion) {
    DataObject five = Scalar(5.0);
    EXPECT_FLOAT_EQ(five.ToScalar(), 5.0);
    bool comparatorWorks = five == 5.0;
    EXPECT_EQ(comparatorWorks, true);
}

TEST(DataObjectTests, MatrixDataObjectGivesCorrectMatrixConversion) {
    Eigen::MatrixXf m = Eigen::MatrixXf::Zero(3, 2);
    DataObject matrix = Mat(m);
    EXPECT_EQ(matrix.ToMatrix(), m);
    bool comparatorWorks = matrix == m;
    EXPECT_EQ(comparatorWorks, true);
}

Fix hidden broken floating-point test


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

#include <pegtl.hh>

namespace modulus
{
   template< unsigned M, unsigned R = 0 >
   struct my_rule
   {
      static_assert( M > 1, "Modulus must be greater than 1" );
      static_assert( R < M, "Remainder must be less than modulus" );

      template< typename Input >
      static bool match( Input & in )
      {
         if ( in.size() ) {
            if ( ( ( * in.begin() ) % M ) == R ) {
               in.bump( 1 );
               return true;
            }
         }
         return false;
      }
   };

   struct grammar
         : pegtl::until< pegtl::eolf, my_rule< 3 > > {};
}

int main( int argc, char * argv[] )
{
   if ( argc > 1 ) {
      pegtl::parse< modulus::grammar >( 1, argv );
   }
   return 0;
}

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

#include <pegtl.hh>

namespace modulus
{
   template< unsigned M, unsigned R = 0 >
   struct my_rule
   {
      using analyze_t = pegtl::analysis::generic< pegtl::analysis::rule_type::ANY >;

      static_assert( M > 1, "Modulus must be greater than 1" );
      static_assert( R < M, "Remainder must be less than modulus" );

      template< typename Input >
      static bool match( Input & in )
      {
         if ( in.size() ) {
            if ( ( ( * in.begin() ) % M ) == R ) {
               in.bump( 1 );
               return true;
            }
         }
         return false;
      }
   };

   struct grammar
         : pegtl::until< pegtl::eolf, pegtl::must< my_rule< 3 > > > {};
}

int main( int argc, char * argv[] )
{
   if ( argc > 1 ) {
      pegtl::parse< modulus::grammar >( 1, argv );
   }
   return 0;
}

Use must<>, added required analyze_t for custom rule


/*
	This file is part of the Geometry library.
	Copyright (C) 2010-2013 Benjamin Eikel <benjamin@eikel.org>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/TextOutputter.h>
#include <cppunit/XmlOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <fstream>

int main(int /*argc*/, char ** /*argv*/) {
	CppUnit::TestResult controller;

	CppUnit::TestResultCollector result;
	controller.addListener(&result);

	CppUnit::BriefTestProgressListener progress;
	controller.addListener(&progress);

	CppUnit::TestRunner runner;
	runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());

	runner.run(controller);

	std::ofstream fileStream("cppunit_results.xml");
	CppUnit::XmlOutputter xmlOutput(&result, fileStream, "UTF-8");
	xmlOutput.write();

	CppUnit::TextOutputter textOutput(&result, std::cout);
	textOutput.write();

	return 0;
}

/*
	This file is part of the Geometry library.
	Copyright (C) 2010-2013 Benjamin Eikel <benjamin@eikel.org>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/TextOutputter.h>
#include <cppunit/XmlOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <fstream>

int main(int /*argc*/, char ** /*argv*/) {
	CppUnit::TestResult controller;

	CppUnit::TestResultCollector result;
	controller.addListener(&result);

	CppUnit::BriefTestProgressListener progress;
	controller.addListener(&progress);

	CppUnit::TestRunner runner;
	runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());

	runner.run(controller);

	std::ofstream fileStream("cppunit_results.xml");
	CppUnit::XmlOutputter xmlOutput(&result, fileStream, "UTF-8");
	xmlOutput.write();

	CppUnit::TextOutputter textOutput(&result, std::cout);
	textOutput.write();

	return result.wasSuccessful() ? 0 : 1;
}

Return value based on test run status


#include <stdlib.h>
#include <time.h>

#include "make_random_data.hpp"

int *make_data(const int size)
{
    return make_data(size, RAND_MAX);
}

int *make_data(const int size, const int max)
{
    srand(time(NULL)); /* Set a seed */

    int *data = (int *)malloc(sizeof(int) * size);
    for(int i = 0; i < size; i++)
        data[i] = rand() % (max + 1);

    return data;
}

void free_data(int *data)
{
    free(data);
}

#include <stdlib.h>
#include <time.h>

#include "make_random_data.hpp"

int *make_random_data(const int size)
{
    return make_random_data(size, RAND_MAX);
}

int *make_random_data(const int size, const int max)
{
    srand(time(NULL)); /* Set a seed */

    int *data = (int *)malloc(sizeof(int) * size);
    for(int i = 0; i < size; i++)
        data[i] = rand() % (max + 1);

    return data;
}

void free_random_data(int *data)
{
    free(data);
}

Fix function name which does not match with header file


// If user provides his own libc functions, ASan doesn't
// intercept these functions.

// RUN: %clangxx_asan -O0 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -o %t && %run %t 2>&1 | FileCheck %s
// XFAIL: freebsd

// On Windows, defining strtoll in a static build results in linker errors, but
// it works with the dynamic runtime.
// XFAIL: win32-static-asan

#include <stdlib.h>
#include <stdio.h>

extern "C" long strtol(const char *nptr, char **endptr, int base) {
  fprintf(stderr, "my_strtol_interceptor\n");
  return 0;
}

int main() {
  char *x = (char*)malloc(10 * sizeof(char));
  free(x);
  return (int)strtol(x, 0, 10);
  // CHECK: my_strtol_interceptor
  // CHECK-NOT: heap-use-after-free
}

// If user provides his own libc functions, ASan doesn't
// intercept these functions.

// RUN: %clangxx_asan -O0 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -o %t && %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -o %t && %run %t 2>&1 | FileCheck %s
// XFAIL: freebsd

// On Windows, defining strtoll in a static build results in linker errors, but
// it works with the dynamic runtime.
// XFAIL: win32-static-asan

#include <stdlib.h>
#include <stdio.h>

extern "C" long strtol(const char *nptr, char **endptr, int base) {
  fprintf(stderr, "my_strtol_interceptor\n");
  if (endptr)
    *endptr = (char*)nptr + strlen(nptr);
  return 0;
}

int main() {
  char *x = (char*)malloc(10 * sizeof(char));
  free(x);
  return (int)strtol(x, 0, 10);
  // CHECK: my_strtol_interceptor
  // CHECK-NOT: heap-use-after-free
}

Fix one test on Android N.


//! @file test-getusername.cpp
//! @author Andrew Schwartzmeyer <andschwa@microsoft.com>
//! @brief Unit tests for GetUserName

#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <unicode/unistr.h>
#include <pwd.h>
#include "getusername.h"

//! Test fixture for GetUserName
class GetUserNameTest : public ::testing::Test
{
protected:
    std::string UserName;

    GetUserNameTest(): UserName(std::string(getpwuid(geteuid())->pw_name))
    {
    }
};

TEST_F(GetUserNameTest, Success)
{
    ASSERT_EQ(GetUserName(), UserName);
}

//! @file test-getusername.cpp
//! @author Andrew Schwartzmeyer <andschwa@microsoft.com>
//! @brief Unit tests for GetUserName

#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <unicode/unistr.h>
#include <pwd.h>
#include "getusername.h"

TEST(GetUserName, Success)
{
    char* expected = getpwuid(geteuid())->pw_name;
    ASSERT_TRUE(expected != NULL);
    ASSERT_EQ(GetUserName(), std::string(expected));
}

Fix username tests by checking for null


#define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    CCoinsViewDB *pcoinsdbview;

    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        noui_connect();
        bitdb.MakeMock();
        pblocktree = new CBlockTreeDB(true);
        pcoinsdbview = new CCoinsViewDB(true);
        pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
        LoadBlockIndex();
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        delete pcoinsTip;
        delete pcoinsdbview;
        delete pblocktree;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

#define BOOST_TEST_MODULE Bitcoin Test Suite
#include <boost/test/unit_test.hpp>

#include "db.h"
#include "txdb.h"
#include "main.h"
#include "wallet.h"

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern bool fPrintToConsole;
extern void noui_connect();

struct TestingSetup {
    CCoinsViewDB *pcoinsdbview;

    TestingSetup() {
        fPrintToDebugger = true; // don't want to write to debug.log file
        noui_connect();
        bitdb.MakeMock();
        pblocktree = new CBlockTreeDB(1 << 20, true);
        pcoinsdbview = new CCoinsViewDB(1 << 23, true);
        pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
        LoadBlockIndex();
        bool fFirstRun;
        pwalletMain = new CWallet("wallet.dat");
        pwalletMain->LoadWallet(fFirstRun);
        RegisterWallet(pwalletMain);
    }
    ~TestingSetup()
    {
        delete pwalletMain;
        pwalletMain = NULL;
        delete pcoinsTip;
        delete pcoinsdbview;
        delete pblocktree;
        bitdb.Flush(true);
    }
};

BOOST_GLOBAL_FIXTURE(TestingSetup);

void Shutdown(void* parg)
{
  exit(0);
}

void StartShutdown()
{
  exit(0);
}

Fix tests after cache tweaks


/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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.
 *
 *  @file main.cpp
 */

#include <TString.h>
#include <DBHandler/HeaderFiles/DBHandler.h>
#include <JPetManager/JPetManager.h>

using namespace std;
int main(int argc, char* argv[])
{
	DB::SERVICES::DBHandler::createDBConnection("../DBConfig/configDB.cfg");
  JPetManager& manager = JPetManager::getManager();
  manager.parseCmdLine(argc, argv);
  manager.run();
}

Add licence header to ScopeReaderExample


#include <config/config_class.h>
#include <config/config_object.h>
#include <config/config_value.h>

#include "wanproxy_config_class_interface.h"

WANProxyConfigClassInterface wanproxy_config_class_interface;

bool
WANProxyConfigClassInterface::activate(ConfigObject *)
{
	/* Eventually would like to do something more useful here.  */
	return (true);
}

#include <config/config_class.h>
#include <config/config_object.h>
#include <config/config_value.h>

#include "wanproxy_config_class_interface.h"

WANProxyConfigClassInterface wanproxy_config_class_interface;

bool
WANProxyConfigClassInterface::activate(ConfigObject *co)
{
	if (!ConfigClassAddress::activate(co))
		return (false);

	/* Eventually would like to do something more useful here.  */
	return (true);
}

Call base class activation routine.


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

#include "chrome/browser/extensions/extension_apitest.h"

// Flaky, http://crbug.com/19866. Please consult phajdan.jr before re-enabling.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Bookmarks) {
  ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_;
}

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

#include "chrome/browser/extensions/extension_apitest.h"

// Flaky, http://crbug.com/19866. Please consult phajdan.jr before re-enabling.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Bookmarks) {
  ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_;
}

Move ExtensionApiTest.Bookmarks from DISABLED to FLAKY since it doesn't crash.


//! \file Article.cpp

#include "Article.h"

#include <algorithm>

#include "WalkerException.h"

namespace WikiWalker
{
  size_t Article::countLinks() const
  {
    if(!analyzed_ && links_.empty()) {
      throw WalkerException("Article not analyzed yet!");
    }

    return links_.size();
  }

  Article::ArticleLinkConstIterator Article::linkBegin() const
  {
    return links_.cbegin();
  }

  Article::ArticleLinkConstIterator Article::linkEnd() const
  {
    return links_.cend();
  }

  bool Article::addLink(const std::weak_ptr<const Article> article)
  {
    auto newTitle = article.lock()->title();

    // check for duplicates using title
    //! \todo Or rather compare pointers again?
    bool isNewLink =
        std::none_of(links_.cbegin(),
                     links_.cend(),
                     [&newTitle](const std::weak_ptr<const Article> x) {
                       return x.lock()->title() == newTitle;
                     });

    if(isNewLink) {
      links_.push_back(article);
      analyzed_ = true;
    }

    return isNewLink;
  }

  void Article::analyzed(bool analyzed)
  {
    analyzed_ = analyzed;
  }

  bool Article::analyzed() const
  {
    return analyzed_;
  }

  void Article::marked(bool marked)
  {
    marked_ = marked;
  }

  bool Article::marked() const
  {
    return marked_;
  }
}  // namespace WikiWalker

//! \file Article.cpp

#include "Article.h"

#include <algorithm>

#include "WalkerException.h"

namespace WikiWalker
{
  size_t Article::countLinks() const
  {
    if(!analyzed_ && links_.empty()) {
      throw WalkerException("Article not analyzed yet!");
    }

    return links_.size();
  }

  Article::ArticleLinkConstIterator Article::linkBegin() const
  {
    return links_.cbegin();
  }

  Article::ArticleLinkConstIterator Article::linkEnd() const
  {
    return links_.cend();
  }

  bool Article::addLink(const std::weak_ptr<const Article> article)
  {
    auto newTitle = article.lock()->title();

    // check for duplicates using title
    //! \todo Or rather compare pointers again?
    bool isNewLink =
        std::none_of(links_.cbegin(),
                     links_.cend(),
                     [&newTitle](const std::weak_ptr<const Article> x) {
                       auto p = x.lock();
                       return p == nullptr ? false : p->title() == newTitle;
                     });

    if(isNewLink) {
      links_.push_back(article);
      analyzed_ = true;
    }

    return isNewLink;
  }

  void Article::analyzed(bool analyzed)
  {
    analyzed_ = analyzed;
  }

  bool Article::analyzed() const
  {
    return analyzed_;
  }

  void Article::marked(bool marked)
  {
    marked_ = marked;
  }

  bool Article::marked() const
  {
    return marked_;
  }
}  // namespace WikiWalker

Fix nullptr access in article class


//
// Copyright(c) 2016-2017 benikabocha.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//

#include "Log.h"
#include "UnicodeUtil.h"

#include <iostream>

#if _WIN32

#include <Windows.h>

#endif // _WIN32

namespace saba
{
	DefaultSink::DefaultSink()
	{
		m_defaultLogger = spdlog::stdout_color_mt("default");
	}

	void DefaultSink::log(const spdlog::details::log_msg & msg)
	{
#if _WIN32
		auto utf8Message = msg.raw.str();
		std::wstring wMessage;
		if (!TryToWString(utf8Message, wMessage))
		{
			m_defaultLogger->log(msg.level, "Failed to convert message.");
			return;
		}
		int chCount = WideCharToMultiByte(
			CP_OEMCP,
			0,
			wMessage.c_str(),
			(int)wMessage.size(),
			nullptr,
			0,
			0,
			FALSE
		);
		std::string oemMessage(chCount, '\0');
		WideCharToMultiByte(
			CP_OEMCP,
			0,
			wMessage.c_str(),
			(int)wMessage.size(),
			&oemMessage[0],
			chCount,
			0,
			FALSE
		);
		m_defaultLogger->log(msg.level, oemMessage);
#else // _WIN32
		m_defaultLogger->log(msg.level, msg.raw.c_str());
#endif // _WIN32
	}

	void DefaultSink::flush()
	{
		m_defaultLogger->flush();
	}
}

//
// Copyright(c) 2016-2017 benikabocha.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//

#include "Log.h"
#include "UnicodeUtil.h"

#include <iostream>

#if _WIN32

#include <Windows.h>

#endif // _WIN32

namespace saba
{
	DefaultSink::DefaultSink()
	{
		m_defaultLogger = spdlog::stdout_color_mt("default");
#if _WIN32
		SetConsoleOutputCP(CP_UTF8);
#endif // _WIN32
	}

	void DefaultSink::log(const spdlog::details::log_msg & msg)
	{
		m_defaultLogger->log(msg.level, msg.raw.c_str());
	}

	void DefaultSink::flush()
	{
		m_defaultLogger->flush();
	}
}

Set the output code page UTF-8.(Windows)


/**
 * @file       main.cpp
 * @author     Volodymyr Shymanskyy
 * @license    This project is released under the MIT License (MIT)
 * @copyright  Copyright (c) 2015 Volodymyr Shymanskyy
 * @date       Mar 2015
 * @brief
 */

//#define BLYNK_DEBUG
#define BLYNK_PRINT stdout
#ifdef RASPBERRY
  #include <BlynkApiWiringPi.h>
#else
  #include <BlynkApiLinux.h>
#endif
#include <BlynkSocket.h>
#include <BlynkOptionsParser.h>

static BlynkTransportSocket _blynkTransport;
BlynkSocket Blynk(_blynkTransport);

#include <BlynkWidgets.h>

BLYNK_WRITE(V1)
{
  printf("Got a value: %s\n", param[0].asStr());
}

void setup()
{

}

void loop()
{
  Blynk.run();
  timer.run();
}

int main(int argc, char* argv[])
{
    const char *auth, *serv;
    uint16_t port;
    parse_options(argc, argv, auth, serv, port);

    Blynk.begin(auth, serv, port);

    setup();
    while(true) {
        loop();
    }

    return 0;
}

/**
 * @file       main.cpp
 * @author     Volodymyr Shymanskyy
 * @license    This project is released under the MIT License (MIT)
 * @copyright  Copyright (c) 2015 Volodymyr Shymanskyy
 * @date       Mar 2015
 * @brief
 */

//#define BLYNK_DEBUG
#define BLYNK_PRINT stdout
#ifdef RASPBERRY
  #include <BlynkApiWiringPi.h>
#else
  #include <BlynkApiLinux.h>
#endif
#include <BlynkSocket.h>
#include <BlynkOptionsParser.h>

static BlynkTransportSocket _blynkTransport;
BlynkSocket Blynk(_blynkTransport);

#include <BlynkWidgets.h>

BLYNK_WRITE(V1)
{
  printf("Got a value: %s\n", param[0].asStr());
}

void setup()
{

}

void loop()
{
  Blynk.run();
}

int main(int argc, char* argv[])
{
    const char *auth, *serv;
    uint16_t port;
    parse_options(argc, argv, auth, serv, port);

    Blynk.begin(auth, serv, port);

    setup();
    while(true) {
        loop();
    }

    return 0;
}

Fix linux build and update example


/*
 * main.cc
 *
 *  Copyright (c) 2015 Masatoshi Hanai
 *
 *  This software is released under MIT License.
 *  See LICENSE.
 *
 */
#include "glog/logging.h"
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "leveldb/db.h"
#include "leveldb/options.h"

/* test files */
#include "medium/com_test.cc"
#include "medium/db_via_lp_test.cc"
#include "medium/gvt_test.cc"
#include "medium/logical_process_test.cc"
#include "small/db_test.cc"
#include "small/io_test.cc"
#include "small/thread_test.cc"
#include "small/util_test.cc"

int main(int argc, char** argv) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(*argv);
  google::InstallFailureSignalHandler();

  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

/*
 * main.cc
 *
 *  Copyright (c) 2015 Masatoshi Hanai
 *
 *  This software is released under MIT License.
 *  See LICENSE.
 *
 */
#include "glog/logging.h"
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "leveldb/db.h"
#include "leveldb/options.h"

/* test files */
#include "medium/com_test.cc"
#include "medium/db_via_lp_test.cc"
#include "medium/gvt_test.cc"
#include "medium/logical_process_test.cc"
#include "small/db_test.cc"
#include "small/io_test.cc"
#include "small/thread_test.cc"
#include "small/util_test.cc"

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

  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(*argv);
  google::InstallFailureSignalHandler();

  return RUN_ALL_TESTS();
}

Fix bug for parsing google test flags