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

#include "GameController.h"

#include <QFileOpenEvent>

extern "C" {
#include "platform/commandline.h"
}

using namespace QGBA;

GBAApp::GBAApp(int& argc, char* argv[])
	: QApplication(argc, argv)
	, m_window(&m_configController)
{
#ifdef BUILD_SDL
	SDL_Init(SDL_INIT_NOPARACHUTE);
#endif

    QApplication::setApplicationName(PROJECT_NAME);
    QApplication::setApplicationVersion(PROJECT_VERSION);

	GBAArguments args = {};
    if (m_configController.parseArguments(&args, argc, argv)) {
    	m_window.argumentsPassed(&args);
    } else {
    	m_window.loadConfig();
    }
	freeArguments(&args);

    m_window.show();
}

bool GBAApp::event(QEvent* event) {
	if (event->type() == QEvent::FileOpen) {
		m_window.controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file());
		return true;
	}
	return QApplication::event(event);
}

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

#include "GameController.h"

#include <QFileOpenEvent>

extern "C" {
#include "platform/commandline.h"
}

using namespace QGBA;

GBAApp::GBAApp(int& argc, char* argv[])
	: QApplication(argc, argv)
	, m_window(&m_configController)
{
#ifdef BUILD_SDL
	SDL_Init(SDL_INIT_NOPARACHUTE);
#endif

    QApplication::setApplicationName(PROJECT_NAME);
    QApplication::setApplicationVersion(PROJECT_VERSION);

    m_window.show();

	GBAArguments args = {};
    if (m_configController.parseArguments(&args, argc, argv)) {
		m_window.argumentsPassed(&args);
    } else {
		m_window.loadConfig();
    }
	freeArguments(&args);
}

bool GBAApp::event(QEvent* event) {
	if (event->type() == QEvent::FileOpen) {
		m_window.controller()->loadGame(static_cast<QFileOpenEvent*>(event)->file());
		return true;
	}
	return QApplication::event(event);
}

Fix window geometry on launch when window is still hidden


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

// <shared_mutex>

// template <class Mutex> class shared_lock;

// shared_lock(mutex_type& m, adopt_lock_t);

#include <shared_mutex>
#include <cassert>

int main()
{
#if _LIBCPP_STD_VER > 11
    std::shared_timed_mutex m;
    m.lock();
    std::shared_lock<std::shared_timed_mutex> lk(m, std::adopt_lock);
    assert(lk.mutex() == &m);
    assert(lk.owns_lock() == true);
#endif  // _LIBCPP_STD_VER > 11
}

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

// <shared_mutex>

// template <class Mutex> class shared_lock;

// shared_lock(mutex_type& m, adopt_lock_t);

#include <shared_mutex>
#include <cassert>

int main()
{
#if _LIBCPP_STD_VER > 11
    std::shared_timed_mutex m;
    m.lock_shared();
    std::shared_lock<std::shared_timed_mutex> lk(m, std::adopt_lock);
    assert(lk.mutex() == &m);
    assert(lk.owns_lock() == true);
#endif  // _LIBCPP_STD_VER > 11
}

Fix PR23041. Use lock_shared() as opposed to lock() in shared_lock test.


#include "sipnondialogclient.h"

#include <QDebug>

SIPNonDialogClient::SIPNonDialogClient(SIPTransactionUser *tu): SIPClientTransaction (tu)
{}

void SIPNonDialogClient::set_remoteURI(SIP_URI& uri)
{
  remoteUri_ = uri;
}

void SIPNonDialogClient::getRequestMessageInfo(RequestType type,
                                               std::shared_ptr<SIPMessageInfo>& outMessage)
{
  SIPClientTransaction::getRequestMessageInfo(type, outMessage);

  if (type == SIP_REGISTER)
  {
    outMessage->expires = 600; // TODO: Implement resending
  }
}

bool SIPNonDialogClient::processResponse(SIPResponse& response,
                                         std::shared_ptr<SIPDialogState> state)
{
  // TODO
  Q_UNUSED(response);
  Q_UNUSED(state);

  if (getOngoingRequest() == SIP_REGISTER)
  {
    qDebug() << "Got a response for REGISTER! TODO: Processing not implemented!";
  }
  return false;
}

void SIPNonDialogClient::startTransaction(RequestType type)
{
  SIPClientTransaction::startTransaction(type);
}

void SIPNonDialogClient::registerToServer()
{
  startTransaction(SIP_REGISTER);
  emit sendNondialogRequest(remoteUri_, SIP_REGISTER);
}

#include "sipnondialogclient.h"

#include <QDebug>

SIPNonDialogClient::SIPNonDialogClient(SIPTransactionUser *tu): SIPClientTransaction (tu)
{}

void SIPNonDialogClient::set_remoteURI(SIP_URI& uri)
{
  remoteUri_ = uri;
}

void SIPNonDialogClient::getRequestMessageInfo(RequestType type,
                                               std::shared_ptr<SIPMessageInfo>& outMessage)
{
  SIPClientTransaction::getRequestMessageInfo(type, outMessage);

  if (type == SIP_REGISTER)
  {
    outMessage->expires = 600; // TODO: Implement resending

    if (!outMessage->vias.empty())
    {
      outMessage->vias.back().alias = true;
      outMessage->vias.back().rport = true;
    }
  }
}

bool SIPNonDialogClient::processResponse(SIPResponse& response,
                                         std::shared_ptr<SIPDialogState> state)
{
  // TODO
  Q_UNUSED(response);
  Q_UNUSED(state);

  if (getOngoingRequest() == SIP_REGISTER)
  {
    qDebug() << "Got a response for REGISTER! TODO: Processing not implemented!";
  }
  return false;
}

void SIPNonDialogClient::startTransaction(RequestType type)
{
  SIPClientTransaction::startTransaction(type);
}

void SIPNonDialogClient::registerToServer()
{
  startTransaction(SIP_REGISTER);
  emit sendNondialogRequest(remoteUri_, SIP_REGISTER);
}

Send alias and rport parameters to proxy.


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

#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell_test.h"

using WebKit::WebView;

class WebViewTest : public TestShellTest {
};

TEST_F(WebViewTest, GetContentAsPlainText) {
  WebView* view = test_shell_->webView();
  ASSERT_TRUE(view != 0);

  view->setIsActive(true);
  EXPECT_TRUE(view->isActive());

  view->setIsActive(false);
  EXPECT_FALSE(view->isActive());

  view->setIsActive(true);
  EXPECT_TRUE(view->isActive());
}

// TODO(viettrungluu): add more tests

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

#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell_test.h"

using WebKit::WebView;

class WebViewTest : public TestShellTest {
};

TEST_F(WebViewTest, ActiveState) {
  WebView* view = test_shell_->webView();
  ASSERT_TRUE(view != 0);

  view->setIsActive(true);
  EXPECT_TRUE(view->isActive());

  view->setIsActive(false);
  EXPECT_FALSE(view->isActive());

  view->setIsActive(true);
  EXPECT_TRUE(view->isActive());
}

// TODO(viettrungluu): add more tests

Rename unit test: WebViewTest.GetContentAsPlainText -> WebViewTest.ActiveState.


#include "bitfield.h"

unsigned long getBitField(uint8_t* data, int start_bit, int num_bits) {
  unsigned long ret = 0;

  int start_byte = start_bit / 8;

  if (num_bits <= 8 ) {
      // Bit fields are positioned according to big-endian bit layout, but
      // inside the bit field, values are represented as little-endian.
      // Therefore, to get the bit field, we just need to convert to big-endian
      // bit ordering to find the field, and directly use the value we find in
      // the field.
      int bit_position = start_bit % 8;
      ret = data[start_byte];
      int end_bit = bit_position + num_bits;
      ret = ret >> (8 - end_bit);
  } else {
      int end_byte = (start_bit + num_bits) / 8;

      // The lowest byte address contains the most significant bit.
      for (int i = start_byte; i <= end_byte; i++) {
          ret = ret << 8;
          ret = ret | data[i];
      }

      //Calculates value to shift bitfield of interest to LSB
      ret = ret >> (8 - ((start_bit + num_bits) % 8));
  }

  // Mask out any other bits besides those in the bitfield.
  unsigned long bitmask = (unsigned long)((0x1 << num_bits) - 1);
  return ret & bitmask;
}

#include "bitfield.h"

unsigned long getBitField(uint8_t* data, int startBit, int numBits) {
  unsigned long ret = 0;

  int startByte = startBit / 8;

  if (numBits <= 8 ) {
      // Bit fields are positioned according to big-endian bit layout, but
      // inside the bit field, values are represented as little-endian.
      // Therefore, to get the bit field, we just need to convert to big-endian
      // bit ordering to find the field, and directly use the value we find in
      // the field.
      int bitPosition = startBit % 8;
      ret = data[startByte];
      int endBit = bitPosition + numBits;
      ret = ret >> (8 - endBit);
  } else {
      int endByte = (startBit + numBits) / 8;

      // The lowest byte address contains the most significant bit.
      for (int i = startByte; i <= endByte; i++) {
          ret = ret << 8;
          ret = ret | data[i];
      }

      //Calculates value to shift bitfield of interest to LSB
      ret = ret >> (8 - ((startBit + numBits) % 8));
  }

  // Mask out any other bits besides those in the bitfield.
  unsigned long bitmask = (unsigned long)((0x1 << numBits) - 1);
  return ret & bitmask;
}

Revert naming change - we're using camelCase everywhere else.


// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Enchants/Enchant.hpp>

namespace RosettaStone
{
Enchant::Enchant(Effect& effect)
{
    effects.emplace_back(effect);
}

Enchant::Enchant(std::vector<Effect>& effects)
{
    effects = effects;
}

void Enchant::ActivateTo(Character* character)
{
    for (auto& effect : effects)
    {
        effect.Apply(character);
    }
}
}  // namespace RosettaStone

// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Enchants/Enchant.hpp>

namespace RosettaStone
{
Enchant::Enchant(Effect& effect)
{
    effects.emplace_back(effect);
}

Enchant::Enchant(std::vector<Effect>& _effects)
{
    effects = _effects;
}

void Enchant::ActivateTo(Character* character)
{
    for (auto& effect : effects)
    {
        effect.Apply(character);
    }
}
}  // namespace RosettaStone

Correct argument name of constructor (effects -> _effects)


/**
 * @file example.cpp
 * @author Marcus Edel
 *
 * Simple random agent.
 */

#include <iostream>

#include "environment.hpp"

using namespace gym;

int main(int argc, char* argv[])
{
  const std::string environment = "CartPole-v0";
  const std::string host = "127.0.0.1";
  const std::string port = "4040";

  double totalReward = 0;
  size_t totalSteps = 0;

  Environment env(host, port, environment);
  env.reset();

  while (1)
  {
    env.step(env.action_space.sample());
    env.render();
    totalReward += env.reward;
    totalSteps += 1;

    if (env.done)
    {
      break;
    }
  }

  std::cout << "Total steps: " << totalSteps << " reward: " << totalReward
      << std::endl;

  return 0;
}

/**
 * @file example.cpp
 * @author Marcus Edel
 *
 * Simple random agent.
 */

#include <iostream>

#include "environment.hpp"

using namespace gym;

int main(int argc, char* argv[])
{
  const std::string environment = "SpaceInvaders-v0";
  const std::string host = "kurg.org";
  const std::string port = "4040";

  double totalReward = 0;
  size_t totalSteps = 0;

  Environment env(host, port, environment);
  env.compression(9);
  env.monitor.start("./dummy/", true, true);

  env.reset();
  env.render();

  while (1)
  {
    arma::mat action = env.action_space.sample();
    std::cout << "action: \n" << action << std::endl;

    env.step(action);

    totalReward += env.reward;
    totalSteps += 1;

    if (env.done)
    {
      break;
    }

    std::cout << "Current step: " << totalSteps << " current reward: "
      << totalReward << std::endl;
  }

  std::cout << "Total steps: " << totalSteps << " reward: " << totalReward
      << std::endl;

  return 0;
}

Use demo server as default and record performance.


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

#include "chrome/test/ui/ui_test.h"

class LocaleTestsDa : public UITest {
 public:
  LocaleTestsDa() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"da");
  }
};

class LocaleTestsHe : public UITest {
 public:
  LocaleTestsHe() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"he");
  }
};

class LocaleTestsZhTw : public UITest {
 public:
  LocaleTestsZhTw() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-tw");
  }
};

#if defined(OS_WIN) || defined(OS_LINUX)
// These 3 tests started failing between revisions 13115 and 13120.
// See bug 9758.
TEST_F(LocaleTestsDa, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsHe, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsZhTw, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}
#endif

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

#include "chrome/test/ui/ui_test.h"

class LocaleTestsDa : public UITest {
 public:
  LocaleTestsDa() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"da");
  }
};

class LocaleTestsHe : public UITest {
 public:
  LocaleTestsHe() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"he");
  }
};

class LocaleTestsZhTw : public UITest {
 public:
  LocaleTestsZhTw() : UITest() {
    launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-TW");
  }
};

#if defined(OS_WIN) || defined(OS_LINUX)
// These 3 tests started failing between revisions 13115 and 13120.
// See bug 9758.
TEST_F(LocaleTestsDa, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsHe, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}

TEST_F(LocaleTestsZhTw, TestStart) {
  // Just making sure we can start/shutdown cleanly.
}
#endif

Change zh-tw to zh-TW when it's used to find the locale data pack on Linux (case-sensitive file system).


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

void bar(int const *foo) {
  __builtin_trap(); // Set break point at this line.
}

int main() {
  int foo[] = {1,2,3};
  bar(foo);
}

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

bool bar(int const *foo) {
  return foo != 0; // Set break point at this line.
}

int main() {
  int foo[] = {1,2,3};
  return bar(foo);
}

Fix rdar-13338477 test-case for Linux. - Using __builtin_trap confuses the stack unwinder - __builtin_trap specific test will be added shortly


// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: remove-cstr-calls . %t.cpp --
// RUN: FileCheck -input-file=%t.cpp %s
// REQUIRES: shell

namespace std {
template<typename T> class allocator {};
template<typename T> class char_traits {};
template<typename C, typename T, typename A> struct basic_string {
  basic_string();
  basic_string(const C *p, const A& a = A());
  const C *c_str() const;
};
typedef basic_string<char, std::char_traits<char>, std::allocator<char> > string;
}
namespace llvm { struct StringRef { StringRef(const char *p); }; }

void f1(const std::string &s) {
  f1(s.c_str());
  // CHECK: void f1
  // CHECK-NEXT: f1(s)
}
void f2(const llvm::StringRef r) {
  std::string s;
  f2(s.c_str());
  // CHECK: std::string s;
  // CHECK-NEXT: f2(s)
}
void f3(const llvm::StringRef &r) {
  std::string s;
  f3(s.c_str());
  // CHECK: std::string s;
  // CHECK: f3(s)
}

// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: remove-cstr-calls . %t.cpp --
// RUN: FileCheck -input-file=%t.cpp %s
// REQUIRES: shell

namespace std {
template<typename T> class allocator {};
template<typename T> class char_traits {};
template<typename C, typename T, typename A> struct basic_string {
  basic_string();
  basic_string(const C *p, const A& a = A());
  const C *c_str() const;
};
typedef basic_string<char, std::char_traits<char>, std::allocator<char> > string;
}
namespace llvm {
struct StringRef {
  StringRef(const char *p);
  StringRef(const std::string &);
};
}

void f1(const std::string &s) {
  f1(s.c_str());
  // CHECK: void f1
  // CHECK-NEXT: f1(s)
}
void f2(const llvm::StringRef r) {
  std::string s;
  f2(s.c_str());
  // CHECK: std::string s;
  // CHECK-NEXT: f2(s)
}
void f3(const llvm::StringRef &r) {
  std::string s;
  f3(s.c_str());
  // CHECK: std::string s;
  // CHECK: f3(s)
}

Fix a remove-cstr-calls test that fails checking of the produced code.


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

#include "ppapi/proxy/ppapi_messages.h"

#include "base/file_path.h"
#include "ipc/ipc_channel_handle.h"
#include "ppapi/c/dev/pp_file_info_dev.h"
#include "ppapi/c/ppb_var.h"

// This actually defines the implementations of all the IPC message functions.
#define MESSAGES_INTERNAL_IMPL_FILE "ppapi/proxy/ppapi_messages_internal.h"
#include "ipc/ipc_message_impl_macros.h"

Add a blank line to force this file to be recompiled on Mac on the bots.


#include <Nazara/Audio.hpp>
#include <Nazara/Core.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Lua.hpp>
#include <Nazara/Network.hpp>
#include <Nazara/Noise.hpp>
#include <Nazara/Physics.hpp>
#include <Nazara/Renderer.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Application.hpp>
#include <iostream>

int main(int argc, char* argv[])
{
	// This "example" has only one purpose: Giving an empty project for you to test whatever you want
	// If you wish to have multiple test projects, you only have to copy/paste this directory and change the name in the build.lua
	Ndk::Application application(argc, argv);

	// Do what you want here

	return EXIT_SUCCESS;
}

#include <Nazara/Audio.hpp>
#include <Nazara/Core.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Lua.hpp>
#include <Nazara/Network.hpp>
#include <Nazara/Noise.hpp>
#include <Nazara/Physics2D.hpp>
#include <Nazara/Physics3D.hpp>
#include <Nazara/Renderer.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Application.hpp>
#include <iostream>

int main(int argc, char* argv[])
{
	// This "example" has only one purpose: Giving an empty project for you to test whatever you want
	// If you wish to have multiple test projects, you only have to copy/paste this directory and change the name in the build.lua
	Ndk::Application application(argc, argv);

	// Do what you want here

	return EXIT_SUCCESS;
}

Fix compilation of Tut00 after Physics change


// RUN: %clang_analyze_cc1 -analyzer-checker=optin.osx.OSObjectCStyleCast %s -verify
#include "os_object_base.h"

struct OSArray : public OSObject {
  unsigned getCount();
};

struct A {
  int x;
};
struct B : public A {
  unsigned getCount();
};

unsigned warn_on_explicit_downcast(OSObject * obj) {
  OSArray *a = (OSArray *) obj; // expected-warning{{C-style cast of OSObject. Use OSDynamicCast instead}}
  return a->getCount();
}

void no_warn_on_upcast(OSArray *arr) {
  OSObject *obj = (OSObject *) arr;
  obj->retain();
  obj->release();
}

unsigned no_warn_on_dynamic_cast(OSObject *obj) {
  OSArray *a = OSDynamicCast(OSArray, obj);
  return a->getCount();
}

unsigned long no_warn_on_primitive_conversion(OSArray *arr) {
  return (unsigned long) arr;
}

unsigned no_warn_on_other_type_cast(A *a) {
  B *b = (B *) a;
  return b->getCount();
}

// RUN: %clang_analyze_cc1 -analyzer-checker=optin.osx.OSObjectCStyleCast %s -verify
#include "os_object_base.h"

struct OSArray : public OSObject {
  unsigned getCount();
};

struct A {
  int x;
};
struct B : public A {
  unsigned getCount();
};

unsigned warn_on_explicit_downcast(OSObject * obj) {
  OSArray *a = (OSArray *) obj; // expected-warning{{C-style cast of OSObject. Use OSDynamicCast instead}}
  return a->getCount();
}

void no_warn_on_upcast(OSArray *arr) {
  OSObject *obj = (OSObject *) arr;
  obj->retain();
  obj->release();
}

unsigned no_warn_on_dynamic_cast(OSObject *obj) {
  OSArray *a = OSDynamicCast(OSArray, obj);
  return a->getCount();
}

__SIZE_TYPE__ no_warn_on_primitive_conversion(OSArray *arr) {
  return (__SIZE_TYPE__) arr;
}

unsigned no_warn_on_other_type_cast(A *a) {
  B *b = (B *) a;
  return b->getCount();
}

Fix test to pass on LLP64 targets


// Ouzel by Elviss Strazdins

#include "RenderTarget.hpp"
#include "Graphics.hpp"
#include "Texture.hpp"

namespace ouzel::graphics
{
    RenderTarget::RenderTarget(Graphics& initGraphics,
                               const std::vector<Texture*>& initColorTextures,
                               Texture* initDepthTexture):
        resource{*initGraphics.getDevice()},
        colorTextures{initColorTextures},
        depthTexture{initDepthTexture}
    {
        std::set<std::size_t> colorTextureIds;

        for (const auto& colorTexture : colorTextures)
            colorTextureIds.insert(colorTexture ? colorTexture->getResource() : 0);

        initGraphics.addCommand(std::make_unique<InitRenderTargetCommand>(resource,
                                                                          colorTextureIds,
                                                                          depthTexture ? depthTexture->getResource() : RenderDevice::ResourceId(0)));
    }
}

// Ouzel by Elviss Strazdins

#include "RenderTarget.hpp"
#include "Graphics.hpp"
#include "Texture.hpp"

namespace ouzel::graphics
{
    RenderTarget::RenderTarget(Graphics& initGraphics,
                               const std::vector<Texture*>& initColorTextures,
                               Texture* initDepthTexture):
        resource{*initGraphics.getDevice()},
        colorTextures{initColorTextures},
        depthTexture{initDepthTexture}
    {
        std::set<RenderDevice::ResourceId> colorTextureIds;

        for (const auto& colorTexture : colorTextures)
            colorTextureIds.insert(colorTexture ? colorTexture->getResource() : 0);

        initGraphics.addCommand(std::make_unique<InitRenderTargetCommand>(resource,
                                                                          colorTextureIds,
                                                                          depthTexture ? depthTexture->getResource() : RenderDevice::ResourceId(0)));
    }
}

Use ResourceId instead of size_t


#include "grune/grammars/anbncn.hpp"
#include "grune/grammars/turtle.hpp"
#include "grune/grammars/tom_dick_and_harry.hpp"
#include "grune-yaml/grune-yaml.hpp"

#include <fstream>

#define MAKE_SAMPLE(name) \
    do { \
        std::ofstream out(#name ".yaml"); \
        out << YAML::Node(grune::grammars::name()) << std::endl; \
    } while(0)

int main()
{
    MAKE_SAMPLE(anbncn);
    MAKE_SAMPLE(cyclic_manhattan_turtle);
    MAKE_SAMPLE(tom_dick_and_harry);
}

#include "grune/grammars/anbncn.hpp"
#include "grune/grammars/turtle.hpp"
#include "grune/grammars/tom_dick_and_harry.hpp"
#include "grune-yaml/grune-yaml.hpp"

#include <fstream>

#define MAKE_SAMPLE_IMPL(name) \
    do { \
        std::ofstream out(#name ".yaml"); \
        out << YAML::Node(grune::grammars::name()) << std::endl; \
    } while(0)

#ifndef COVERITY_BUILD
#define MAKE_SAMPLE(name) MAKE_SAMPLE_IMPL(name)
#else
#include <coverity-test-separation.h>
#define MAKE_SAMPLE(name) \
    do { \
        COVERITY_TS_START_TEST(#name); \
        MAKE_SAMPLE_IMPL(name); \
        COVERITY_TS_END_TEST(); \
    } while(0)
#endif

int main()
{
#ifdef COVERITY_BUILD
    COVERITY_TS_SET_SUITE_NAME("grune-yaml/make-samples");
#endif
    MAKE_SAMPLE(anbncn);
    MAKE_SAMPLE(cyclic_manhattan_turtle);
    MAKE_SAMPLE(tom_dick_and_harry);
}

Add test separation for YAML make-samples


// REQUIRES: x86-registered-target,x86-64-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin -S %s -o %t-64.s
// RUN: FileCheck -check-prefix CHECK-LP64 --input-file=%t-64.s %s
// RUN: %clang_cc1 -triple i386-apple-darwin -S %s -o %t-32.s
// RUN: FileCheck -check-prefix CHECK-LP32 --input-file=%t-32.s %s

struct A {};

struct B
{
  operator A&();
};

struct D : public B {
  operator A();
};

extern B f();
extern D d();

int main() {
	const A& rca = f();
	const A& rca2 = d();
}

// CHECK-LP64: callq    __ZN1BcvR1AEv
// CHECK-LP64: callq    __ZN1BcvR1AEv

// CHECK-LP32: calll     L__ZN1BcvR1AEv
// CHECK-LP32: calll     L__ZN1BcvR1AEv

// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm %s -o - | \
// RUN: FileCheck %s
// RUN: %clang_cc1 -triple i386-apple-darwin -emit-llvm %s -o - | \
// RUN: FileCheck %s

struct A {};

struct B
{
  operator A&();
};

struct D : public B {
  operator A();
};

extern B f();
extern D d();

int main() {
	const A& rca = f();
	const A& rca2 = d();
}

// CHECK: call %struct.A* @_ZN1BcvR1AEv
// CHECK: call %struct.A* @_ZN1BcvR1AEv

Check IR on this test.


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

#include "Window.h"
#include "ProceduralRenderer.h"

#include <glbinding/gl/gl.h>
#include <glbinding/Binding.h>

using namespace gl;

int main() {
    Window w;
    w.init("procedural");

    glbinding::Binding::initialize();
    std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;
    w.initAfterGL();

    std::vector<std::string> includes {"gradient", "chess"};
    auto renderer = std::make_unique<ProceduralRenderer>(includes);

    w.setRenderer(std::move(renderer));
    w.loop();

    return 0;
}

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <sstream>

#include "Window.h"
#include "ProceduralRenderer.h"

#include <glbinding/gl/gl.h>
#include <glbinding/Binding.h>

using namespace gl;

std::map<std::string, std::string> parseArguments(int argc, char * argv[])
{
    std::vector<std::string> arguments;
    for (int i = 0; i < argc; ++i)
    {
        arguments.push_back(argv[i]);
    }

    std::map<std::string, std::string> options;
    for (auto& argument : arguments)
    {
        const auto equalPosition = argument.find("=");
        if (argument.substr(0, 2) == "--" && equalPosition != std::string::npos)
        {
            const auto key = argument.substr(2, equalPosition - 2);
            const auto value = argument.substr(equalPosition + 1);
            options[key] = value;
        }
    }
    return options;
}

int main(int argc, char * argv[]) {
    const auto options = parseArguments(argc, argv);

    Window w;
    if (options.find("gl") != options.end())
    {
        const auto version = options.at("gl");
        const auto dotPosition = version.find(".");
        if (dotPosition != std::string::npos)
        {
            int major, minor;
            std::istringstream(version.substr(0, dotPosition)) >> major;
            std::istringstream(version.substr(dotPosition + 1)) >> minor;
            w.requestGLVersion(major, minor);
        }
    }
    w.init("procedural");

    glbinding::Binding::initialize();
    std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;
    w.initAfterGL();

    std::vector<std::string> includes {"gradient", "chess"};
    auto renderer = std::make_unique<ProceduralRenderer>(includes);

    w.setRenderer(std::move(renderer));
    w.loop();

    return 0;
}

Add argument for requesting specific OpenGl version


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

namespace N { };

namespace A = N;

int B; // expected-note {{previous definition is here}}
namespace B = N; // expected-error {{redefinition of 'B' as different kind of symbol}}

namespace C { } // expected-note {{previous definition is here}}
namespace C = N; // expected-error {{redefinition of 'C'}}

int i;
namespace D = i; // expected-error {{expected namespace name}}

namespace E = N::Foo; // expected-error {{expected namespace name}}

namespace F {
  namespace A { namespace B { } } // expected-note {{candidate found by name lookup is 'F::A::B'}}
  namespace B { } // expected-note {{candidate found by name lookup is 'F::B'}}
  using namespace A;
  namespace D = B; // expected-error {{reference to 'B' is ambiguous}}
}

namespace G {
  namespace B = N;
}

namespace H {
  namespace A1 { }
  namespace A2 { }

  // These all point to A1.
  namespace B = A1; // expected-note {{previous definition is here}}
  namespace B = A1;
  namespace C = B;
  namespace B = C;

  namespace B = A2; // expected-error {{redefinition of 'B' as different kind of symbol}}
}

namespace I {
  namespace A1 { int i; }

  namespace A2 = A1;
}

int f() {
  return I::A2::i;
}

namespace J {
  namespace A {
    namespace B { void func (); }
  }

  namespace C = A;

  using namespace C::B;

  void g() {
    func();
  }
}

Check in test for namespace aliases+using directives.


#include "list.h"
#include "gtest/gtest.h"
#include <string>

class listTest : public testing::Test {
 protected:
  virtual void SetUp() {
    // NOT YET IMPLEMENTED
  }
  virtual void TearDown() {}
  // setup fixtures
  list<int> list_1;
  list<int> list_2;
  list<std::string> list_str;
};

TEST(listNodeTest, DefaultCtor) {
  int element_1 = 100;
  std::string element_2("Hello world");
  listNode<int> node_1(element_1);
  listNode<std::string> node_2(element_2);
  EXPECT_EQ(element_1, node_1.element_);
  EXPECT_EQ(element_2, node_2.element_);
  EXPECT_EQ(nullptr, node_2.prev_);
  EXPECT_EQ(nullptr, node_2.next_);
  // test the move constructor for node:
  listNode<int> node_3(std::move(element_1));
  listNode<std::string> node_4(std::move(element_2));
  EXPECT_EQ(100, node_3.element_);
  EXPECT_EQ("Hello world", node_4.element_);
  EXPECT_TRUE(element_2.empty());
}

TEST_F(listTest, DefaultCtor) {
  list<int> list_temp;
  EXPECT_EQ(0u, list_temp.size());
}

#include "list.h"
#include "gtest/gtest.h"
#include <string>

class listTest : public testing::Test {
 protected:
  virtual void SetUp() {
    // NOT YET IMPLEMENTED
  }
  virtual void TearDown() {}
  // setup fixtures
  list<int> list_1;
  list<int> list_2;
  list<std::string> list_str;
};

// test the helper class listNodeTest
// this is a canonical example of writing testable code:
// to test private members, just write another helper class
// and make its data public
TEST(listNodeTest, DefaultCtor) {
  int element_1 = 100;
  std::string element_2("Hello world");
  listNode<int> node_1(element_1);
  listNode<std::string> node_2(element_2);
  EXPECT_EQ(element_1, node_1.element_);
  EXPECT_EQ(element_2, node_2.element_);
  EXPECT_EQ(nullptr, node_2.prev_);
  EXPECT_EQ(nullptr, node_2.next_);
  // test the move constructor for node:
  listNode<int> node_3(std::move(element_1));
  listNode<std::string> node_4(std::move(element_2));
  EXPECT_EQ(100, node_3.element_);
  EXPECT_EQ("Hello world", node_4.element_);
  EXPECT_TRUE(element_2.empty());
}

TEST_F(listTest, DefaultCtor) {
  list<int> list_temp;
  EXPECT_EQ(0u, list_temp.size());
}

Add more documentation for listNodeTest


/*
 *
 * Copyright 2019 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     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 <stdbool.h>
#include <stdint.h>

#include "src/core/lib/slice/b64.h"
#include "include/grpc/support/alloc.h"

bool squelch = true;
bool leak_check = true;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  if (size < 2) return 0;
  const bool url_safe = static_cast<uint8_t>(0x100) < data[0];
  const bool multiline = static_cast<uint8_t>(0x100) < data[1];
  char* res = grpc_base64_encode(reinterpret_cast<const char*>(data + 2),
                                 size - 2, url_safe, multiline);
  gpr_free(res);
  return 0;
}

/*
 *
 * Copyright 2019 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     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 <stdbool.h>
#include <stdint.h>

#include "include/grpc/support/alloc.h"
#include "src/core/lib/slice/b64.h"

bool squelch = true;
bool leak_check = true;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  if (size < 2) return 0;
  const bool url_safe = static_cast<uint8_t>(0x100) < data[0];
  const bool multiline = static_cast<uint8_t>(0x100) < data[1];
  char* res = grpc_base64_encode(reinterpret_cast<const char*>(data + 2),
                                 size - 2, url_safe, multiline);
  gpr_free(res);
  return 0;
}

Fix include order for clang_format.


#include "jsonparser.h"

JSONParser::JSONParser(QObject *parent) :
    QObject(parent)
{
    clearData();
}

void JSONParser::clearData()
{
    p_data = "{ ";
}

void JSONParser::addVariable(const QString name, int value)
{
    p_data.append("\"");
    p_data.append(name);
    p_data.append("\":");
    p_data.append(QString::number(value));
    p_data.append(",");
}

void JSONParser::setData(QString &value)
{
    if(value != p_data)
    {
        p_data = value;
        emit dataChanged();
    }
}

QString JSONParser::data() {
    QString result = p_data.remove(p_data.length() - 1, 1);
    result.append(" }");

    return result;
}

#include "jsonparser.h"

JSONParser::JSONParser(QObject *parent) :
    QObject(parent)
{
    clearData();
}

void JSONParser::clearData()
{
    p_data = "{ ";
}

void JSONParser::addVariable(const QString name, int value)
{
    p_data.append("\"");
    p_data.append(name);
    p_data.append("\":");
    p_data.append(QString::number(value));
    p_data.append(",");
}

void JSONParser::setData(QString &value)
{
    if(value != p_data)
    {
        p_data = value;
        emit dataChanged();
    }
}

QString JSONParser::data() {
    QString result = p_data;
    result.remove(result.length() - 1, 1);
    result.append(" }");

    return result;
}

Fix C++: getter changed data - JSONPARSER


/**
 * Coverity Scan model
 *
 * Manage false positives by giving coverity some hints.
 *
 * Updates to this file must be manually submitted by an admin to:
 *
 *   https://scan.coverity.com/projects/1222
 *
 */

// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
  if (tag == 1 || tag == 2) {
    __coverity_panic__();
  }
}

//==============================
// runtime
//

// chpl_error() ends execution
void chpl_error(const char* message, int32_t lineno, c_string filename) {
  __coverity_panic__();
}

// chpl_internal_error() ends execution
void chpl_internal_error(const char* message) {
  __coverity_panic__();
}

/**
 * Coverity Scan model
 *
 * Manage false positives by giving coverity some hints.
 *
 * Updates to this file must be manually submitted by an admin to:
 *
 *   https://scan.coverity.com/projects/1222
 *
 */

// When tag is 1 or 2, let coverity know that execution is halting. Those
// tags correspond to INT_FATAL and USR_FATAL respectively.
//
// INT_FATAL, et al, work by calling setupError and then
// handleError. setupError simply sets some static globals, then handleError
// looks at those to decide how to error. For example, when INT_FATAL calls
// handleError it will abort execution because exit_immediately is true.
//
// Here we're fibbing to coverity by telling it that setupError results in
// abort (as opposed to handleError), but the effect should be the same.
void setupError(const char *filename, int lineno, int tag) {
  if (tag == 1 || tag == 2) {
    __coverity_panic__();
  }
}

//==============================
// runtime
//

// chpl_error() ends execution
// Note: this signature doesn't match the real one precisely, but it's
//       close enough.
void chpl_error(const char* message, int lineno, const char* filename) {
  __coverity_panic__();
}

// chpl_internal_error() ends execution
void chpl_internal_error(const char* message) {
  __coverity_panic__();
}

Fix unrecognized types in Coverity Scan model chpl_*error() decls.


// RUN: clang-cc -emit-llvm -triple x86_64-apple-darwin10 -o - %s | FileCheck %s
template<typename T>
struct X {
  static T member1;
  static T member2;
  static T member3;
};

template<typename T>
T X<T>::member1;

template<typename T>
T X<T>::member2 = 17;

// CHECK: @_ZN1XIiE7member1E = global i32 0
template int X<int>::member1;

// CHECK: @_ZN1XIiE7member2E = global i32 17
template int X<int>::member2;

// For implicit instantiation of
long& get(bool Cond) {
  // CHECK: @_ZN1XIlE7member1E = weak global i64 0
  // CHECK: @_ZN1XIlE7member2E = weak global i64 17
  return Cond? X<long>::member1 : X<long>::member2;
}

// RUN: clang-cc -emit-llvm -triple x86_64-apple-darwin10 -o - %s | FileCheck %s
template<typename T>
struct X {
  static T member1;
  static T member2;
  static T member3;
};

template<typename T>
T X<T>::member1;

template<typename T>
T X<T>::member2 = 17;

// CHECK: @_ZN1XIiE7member1E = global i32 0
template int X<int>::member1;

// CHECK: @_ZN1XIiE7member2E = global i32 17
template int X<int>::member2;

// For implicit instantiation of
long& get(bool Cond1, bool Cond2) {
  // CHECK: @_ZN1XIlE7member1E = weak global i64 0
  // CHECK: @_ZN1XIlE7member2E = weak global i64 17
  // CHECK: @_ZN1XIlE7member3E = external global i64
  return Cond1? X<long>::member1
       : Cond2? X<long>::member2
              : X<long>::member3;
}

Check the implicit instantiation of a static data member of a class template that has no out-of-line definition.


#include "caffe2/operators/scale_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(Scale, ScaleOp<float, CPUContext>);
OPERATOR_SCHEMA(Scale)
  .NumInputs(1)
  .NumOutputs(1)
  .AllowInplace({{0, 0}})
  .SetDoc(R"DOC(
Scale takes one input data (Tensor<float>) and produces one output data
(Tensor<float>) whose value is the input data tensor scaled element-wise.
)DOC")
  .Arg("scale", "(float, default 1.0) the scale to apply.");

class GetScaleGradient : public GradientMakerBase {
  using GradientMakerBase::GradientMakerBase;
  vector<OperatorDef> GetGradientDefs() override {
    return SingleGradientDef(
        "Scale", "",
        vector<string>{GO(0)},
        vector<string>{GI(0)},
        Def().arg());
  }
};
REGISTER_GRADIENT(Scale, GetScaleGradient);
}  // namespace caffe2

#include "caffe2/operators/scale_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(Scale, ScaleOp<float, CPUContext>);
OPERATOR_SCHEMA(Scale)
  .NumInputs(1)
  .NumOutputs(1)
  .AllowInplace({{0, 0}})
  .SetDoc(R"DOC(
Scale takes one input data (Tensor<float>) and produces one output data
(Tensor<float>) whose value is the input data tensor scaled element-wise.
)DOC")
  .Arg("scale", "(float, default 1.0) the scale to apply.");

class GetScaleGradient : public GradientMakerBase {
  using GradientMakerBase::GradientMakerBase;
  vector<OperatorDef> GetGradientDefs() override {
    // CopyArguments is true by default so the "scale" arg is going to be copied
    return SingleGradientDef(
        "Scale", "", vector<string>{GO(0)}, vector<string>{GI(0)});
  }
};
REGISTER_GRADIENT(Scale, GetScaleGradient);
}  // namespace caffe2

Fix warning in ScaleOp grad


/*
 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
 * Distributed under the MIT License
 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
 */

#include "MyGUI_ControllerRepeatClick.h"

namespace MyGUI
{
	ControllerRepeatClick::ControllerRepeatClick() :
		mInit(0.5),
		mStep(0.1),
		mTimeLeft(0)
	{
	}

	ControllerRepeatClick::~ControllerRepeatClick()
	{
	}

	bool ControllerRepeatClick::addTime(MyGUI::Widget* _widget, float _time)
	{
		if(mTimeLeft == 0)
			mTimeLeft = mInit;

		mTimeLeft -= _time;
		while (mTimeLeft <= 0)
		{
			mTimeLeft += mStep;
			eventRepeatClick(_widget, this);
		}
		return true;
	}

	void ControllerRepeatClick::setRepeat(float init, float step)
	{
		mInit = init;
		mStep = step;
	}

	void ControllerRepeatClick::setProperty(const std::string& _key, const std::string& _value)
	{
	}

	void ControllerRepeatClick::prepareItem(MyGUI::Widget* _widget)
	{
	}
}

/*
 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
 * Distributed under the MIT License
 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
 */

#include "MyGUI_ControllerRepeatClick.h"

namespace MyGUI
{
	ControllerRepeatClick::ControllerRepeatClick() :
		mInit(0.5),
		mStep(0.1),
		mTimeLeft(0)
	{
	}

	ControllerRepeatClick::~ControllerRepeatClick()
	{
	}

	bool ControllerRepeatClick::addTime(MyGUI::Widget* _widget, float _time)
	{
		if(mTimeLeft == 0)
			mTimeLeft = mInit;

		if (mStep <= 0)
			return true;

		mTimeLeft -= _time;
		while (mTimeLeft <= 0)
		{
			mTimeLeft += mStep;
			eventRepeatClick(_widget, this);
		}
		return true;
	}

	void ControllerRepeatClick::setRepeat(float init, float step)
	{
		mInit = init;
		mStep = step;
	}

	void ControllerRepeatClick::setProperty(const std::string& _key, const std::string& _value)
	{
	}

	void ControllerRepeatClick::prepareItem(MyGUI::Widget* _widget)
	{
	}
}

Fix ControllerRepeatClick potential infinite loop for bad step values


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

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "core/fpdfapi/fpdf_page/cpdf_contentmarkitem.h"

#include "core/fpdfapi/fpdf_parser/include/cpdf_dictionary.h"

CPDF_ContentMarkItem::CPDF_ContentMarkItem() {
  m_ParamType = None;
}

CPDF_ContentMarkItem::CPDF_ContentMarkItem(const CPDF_ContentMarkItem& src) {
  m_MarkName = src.m_MarkName;
  m_ParamType = src.m_ParamType;
  if (m_ParamType == DirectDict) {
    m_pParam = ToDictionary(src.m_pParam->Clone());
  } else {
    m_pParam = src.m_pParam;
  }
}

CPDF_ContentMarkItem::~CPDF_ContentMarkItem() {
  if (m_ParamType == DirectDict && m_pParam)
    m_pParam->Release();
}

FX_BOOL CPDF_ContentMarkItem::HasMCID() const {
  if (m_pParam &&
      (m_ParamType == DirectDict || m_ParamType == PropertiesDict)) {
    return m_pParam->KeyExist("MCID");
  }
  return FALSE;
}

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

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "core/fpdfapi/fpdf_page/cpdf_contentmarkitem.h"

#include "core/fpdfapi/fpdf_parser/include/cpdf_dictionary.h"

CPDF_ContentMarkItem::CPDF_ContentMarkItem()
    : m_ParamType(None), m_pParam(nullptr) {}

CPDF_ContentMarkItem::CPDF_ContentMarkItem(const CPDF_ContentMarkItem& src) {
  m_MarkName = src.m_MarkName;
  m_ParamType = src.m_ParamType;
  if (m_ParamType == DirectDict) {
    m_pParam = ToDictionary(src.m_pParam->Clone());
  } else {
    m_pParam = src.m_pParam;
  }
}

CPDF_ContentMarkItem::~CPDF_ContentMarkItem() {
  if (m_ParamType == DirectDict && m_pParam)
    m_pParam->Release();
}

FX_BOOL CPDF_ContentMarkItem::HasMCID() const {
  if (m_pParam &&
      (m_ParamType == DirectDict || m_ParamType == PropertiesDict)) {
    return m_pParam->KeyExist("MCID");
  }
  return FALSE;
}

Add a missing initialisation for CPDF_ContentMarkItem.


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

int main()
{
	ofSetupOpenGL(600, 500, OF_WINDOW);
	ofRunApp(new ofApp());
}

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

int main()
{
#ifdef TARGET_RASPBERRY_PI
	ofSetupOpenGL(600, 500, OF_FULLSCREEN);
#else
    ofSetupOpenGL(600, 500, OF_WINDOW);
#endif
	ofRunApp(new ofApp());
}

Add fullscreen for Raspberry Pi


#include <iostream>
#include <tcp/tcp_server.hpp>
#include <sstream>

int main(int argc, char** argv)
{
  //initialize default port number and max connection cout
  int port = 12001, max_connection_count= 1000;

  // check if there are any passed arguments
  if(argc > 1)
  {
    // initialize string stream from argument
    std::istringstream arg_stream(argv[1]);

    // bind arguments stream to port int variable if valid
    if ( !(arg_stream >> port) )
      std::cerr << "Invalid number " << argv[1] << '\n';
  }

  // create server instance with specified port number
  TcpServer server(port);

  //start listening to connections
  server.Listen(max_connection_count);

  return 0;
}

#include <iostream>
#include <tcp/tcp_server.hpp>
#include <sstream>

int main(int argc, char** argv)
{
  //initialize default port number and max connection cout
  int port = 12001, max_connection_count= 1000;

  // check if there are any passed arguments
  if(argc > 1)
  {
    // initialize string stream from argument
    std::istringstream arg_stream(argv[1]);

    // bind arguments stream to port int variable if valid
    if ( !(arg_stream >> port) )
      std::cerr << "Invalid number " << argv[1] << '\n';
  }

  // create server instance with specified port number
  TcpServer server(port);

  //start listening to connections
  int result = server.Listen(max_connection_count);
  if(result != 0)
    cout << "Faild to start server !" << std::endl;

  return 0;
}

Update tcp server demo add error msg


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBSTInternal(TreeNode* root, int minVal, int maxVal)
    {
        if (root == NULL) {
            return true;
        }

	return (root->val > minVal &&
		root->val < maxVal &&
		isValidBSTInternal(root->left, minVal, root->val) &&
		isValidBSTInternal(root->right, root->val, maxVal));
    }

    bool isValidBST(TreeNode* root) {
        int minVal, maxVal;
        return isValidBSTInternal(root, LONG_MIN, LONG_MAX);
    }
};

#include <cstddef>
#include <climits>
/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    bool isValidBSTInternal(TreeNode* root, int minVal, int maxVal)
    {
        if (root == NULL) {
            return true;
        }

	return (root->val > minVal &&
		root->val < maxVal &&
		isValidBSTInternal(root->left, minVal, root->val) &&
		isValidBSTInternal(root->right, root->val, maxVal));
    }

    bool isValidBST(TreeNode* root) {

        return isValidBSTInternal(root, INT_MIN, INT_MAX);
    }
};

Clean up of the code.


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "AsynchronousEventBeat.h"

namespace facebook {
namespace react {

AsynchronousEventBeat::AsynchronousEventBeat(
    RunLoopObserver::Unique uiRunLoopObserver,
    RuntimeExecutor runtimeExecutor)
    : EventBeat({}),
      uiRunLoopObserver_(std::move(uiRunLoopObserver)),
      runtimeExecutor_(std::move(runtimeExecutor)) {
  uiRunLoopObserver_->setDelegate(this);
  uiRunLoopObserver_->enable();
}

void AsynchronousEventBeat::activityDidChange(
    RunLoopObserver::Delegate const *delegate,
    RunLoopObserver::Activity activity) const noexcept {
  assert(delegate == this);
  induce();
}

void AsynchronousEventBeat::induce() const {
  if (!isRequested_) {
    return;
  }

  // Here we know that `this` object exists because the caller has a strong
  // pointer to `owner`. To ensure the object will exist inside
  // `runtimeExecutor_` callback, we need to copy the  pointer there.
  auto weakOwner = uiRunLoopObserver_->getOwner();

  runtimeExecutor_([this, weakOwner](jsi::Runtime &runtime) mutable {
    auto owner = weakOwner.lock();
    if (!owner) {
      return;
    }

    if (!isRequested_) {
      return;
    }

    this->beat(runtime);
  });
}

} // namespace react
} // namespace facebook

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "AsynchronousEventBeat.h"

#include <react/debug/react_native_assert.h>

namespace facebook {
namespace react {

AsynchronousEventBeat::AsynchronousEventBeat(
    RunLoopObserver::Unique uiRunLoopObserver,
    RuntimeExecutor runtimeExecutor)
    : EventBeat({}),
      uiRunLoopObserver_(std::move(uiRunLoopObserver)),
      runtimeExecutor_(std::move(runtimeExecutor)) {
  uiRunLoopObserver_->setDelegate(this);
  uiRunLoopObserver_->enable();
}

void AsynchronousEventBeat::activityDidChange(
    RunLoopObserver::Delegate const *delegate,
    RunLoopObserver::Activity activity) const noexcept {
  react_native_assert(delegate == this);
  induce();
}

void AsynchronousEventBeat::induce() const {
  if (!isRequested_) {
    return;
  }

  // Here we know that `this` object exists because the caller has a strong
  // pointer to `owner`. To ensure the object will exist inside
  // `runtimeExecutor_` callback, we need to copy the  pointer there.
  auto weakOwner = uiRunLoopObserver_->getOwner();

  runtimeExecutor_([this, weakOwner](jsi::Runtime &runtime) mutable {
    auto owner = weakOwner.lock();
    if (!owner) {
      return;
    }

    if (!isRequested_) {
      return;
    }

    this->beat(runtime);
  });
}

} // namespace react
} // namespace facebook

Migrate uses of NDEBUG to REACT_NATIVE_DEBUG + react_native_assert


#include <gtest/gtest.h>

#include "Vector2f.h"

TEST(Vector2fTest, VectorAddition) {
	Vector2f v1(0, 0);
	Vector2f v2(1, 2);
	Vector2f v3(3, 4);

	Vector2f result = v1 + v1;
	EXPECT_FLOAT_EQ(0.0f, result.x);
	EXPECT_FLOAT_EQ(0.0f, result.y);

	result = v2 + v1;
	EXPECT_FLOAT_EQ(v2.x, result.x);
	EXPECT_FLOAT_EQ(v2.y, result.y);

	result = v2 + v3;
	EXPECT_FLOAT_EQ(4.0f, result.x);
	EXPECT_FLOAT_EQ(6.0f, result.y);
	// TEST
	EXPECT_FLOAT_EQ(7.0f, result.y);
}

#include <gtest/gtest.h>

#include "Vector2f.h"

Vector2f v1(0,0);
Vector2f v2(1, 2);
Vector2f v3(3, 4);
Vector2f v4(-5, 6);

TEST(Vector2fTest, VectorAddition) {

	Vector2f result = v1 + v1;
	EXPECT_FLOAT_EQ(0.0f, result.x);
	EXPECT_FLOAT_EQ(0.0f, result.y);

	result = v2 + v1;
	EXPECT_FLOAT_EQ(v2.x, result.x);
	EXPECT_FLOAT_EQ(v2.y, result.y);

	result = v2 + v3;
	EXPECT_FLOAT_EQ(4.0f, result.x);
	EXPECT_FLOAT_EQ(6.0f, result.y);

	result = v3 + v4;
	EXPECT_FLOAT_EQ(-2.0f, result.x);
	EXPECT_FLOAT_EQ(10.0f, result.y);
}

TEST(Vector2fTest, VectorDot) {

	EXPECT_FLOAT_EQ(0.0f, v1.dot(v1));
	EXPECT_FLOAT_EQ(11.0f, v2.dot(v3));
}

Add more unit tests for vector


#include "cpptoml.h"

#include <iostream>
#include <cassert>

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        std::cout << "Usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }
    cpptoml::toml_group g = cpptoml::parse_file(argv[1]);
    std::cout << g << std::endl;
    return 0;
}

#include "cpptoml.h"

#include <iostream>
#include <cassert>

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        std::cout << "Usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }

    try
    {
        cpptoml::toml_group g = cpptoml::parse_file(argv[1]);
        std::cout << g << std::endl;
    }
    catch (const cpptoml::toml_parse_exception& e)
    {
        std::cerr << "Failed to parse " << argv[1] << ": " << e.what() << std::endl;
        return 1;
    }

    return 0;
}

Handle parsing errors in the example.


#include "Game/CannonBall.h"

CannonBall::CannonBall(const QPixmap & pixmap, QVector2D velocity, QVector2D position, Player owner, QGraphicsItem * parent) : Entity(pixmap, owner, parent), m_initialVelocity(velocity), m_initialPosition(position), m_gravity(9.8), m_timeSinceShot(0)
{
	setScale(0.1);
	setPos(m_initialPosition.toPointF());
}

void CannonBall::updateEntity(double deltaTime)
{
    m_timeSinceShot += deltaTime/1000.0 * 2.0;

	double x = m_initialPosition.x() + m_initialVelocity.x() * m_timeSinceShot;
	double y = m_initialPosition.y() - m_initialVelocity.y() * m_timeSinceShot + 0.5 * m_gravity * m_timeSinceShot * m_timeSinceShot;

	setPos(x, y);
}

#include "Game/CannonBall.h"

CannonBall::CannonBall(const QPixmap & pixmap, QVector2D velocity, QVector2D position, Player owner, QGraphicsItem * parent) : Entity(pixmap, owner, parent), m_initialVelocity(velocity), m_initialPosition(position), m_gravity(9.8), m_timeSinceShot(0)
{
	setScale(0.1);
	setPos(m_initialPosition.toPointF());
}

void CannonBall::updateEntity(double deltaTime)
{
    m_timeSinceShot += deltaTime/1000.0 * 2.0;

	double x = m_initialPosition.x() + m_initialVelocity.x() * m_timeSinceShot;
	double y = m_initialPosition.y() - m_initialVelocity.y() * m_timeSinceShot + 0.5 * m_gravity * m_timeSinceShot * m_timeSinceShot;

	setPos(x, y);

   update(boundingRect());
}

Call update in update entity


// Check the value profiling instrinsics emitted by instrumentation.

// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -mllvm -enable-value-profiling -fexceptions -target %itanium_abi_triple | FileCheck %s

void (*foo) (void);

int main(int argc, const char *argv[]) {
// CHECK:  [[REG1:%[0-9]+]] = load void ()*, void ()** @foo, align 4
// CHECK-NEXT:  [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT:  call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT:  invoke void [[REG1]]()
  try {
    foo();
  } catch (int) {}
  return 0;
}

// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)

// Check the value profiling instrinsics emitted by instrumentation.

// RUN: %clangxx %s -o - -emit-llvm -S -fprofile-instr-generate -mllvm -enable-value-profiling -fexceptions -target %itanium_abi_triple | FileCheck %s

void (*foo) (void);

int main(int argc, const char *argv[]) {
// CHECK:  [[REG1:%[0-9]+]] = load void ()*, void ()** @foo
// CHECK-NEXT:  [[REG2:%[0-9]+]] = ptrtoint void ()* [[REG1]] to i64
// CHECK-NEXT:  call void @__llvm_profile_instrument_target(i64 [[REG2]], i8* bitcast ({{.*}}* @__profd_main to i8*), i32 0)
// CHECK-NEXT:  invoke void [[REG1]]()
  try {
    foo();
  } catch (int) {}
  return 0;
}

// CHECK: declare void @__llvm_profile_instrument_target(i64, i8*, i32)

Test case fix for r264783


#include <lightex/utils/file_utils.h>

#include <fstream>
#include <iostream>

namespace lightex {
namespace utils {

bool ReadDataFromFile(const std::string& path, std::string* output) {
  if (!output) {
    std::cerr << "Error: output pointer points to invalid memory." << std::endl;
    return false;
  }

  std::ifstream in(path);
  if (!in) {
    std::cerr << "Error: failed to open input file for reading: " << path << "." << std::endl;
    return false;
  }

  in.unsetf(std::ios::skipws);  // Avoids white space skipping.
  std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(*output));

  return true;
}
}  // namespace utils
}  // namespace lightex

#include <lightex/utils/file_utils.h>

#include <fstream>
#include <iostream>
#include <iterator>

namespace lightex {
namespace utils {

bool ReadDataFromFile(const std::string& path, std::string* output) {
  if (!output) {
    std::cerr << "Error: output pointer points to invalid memory." << std::endl;
    return false;
  }

  std::ifstream in(path);
  if (!in) {
    std::cerr << "Error: failed to open input file for reading: " << path << "." << std::endl;
    return false;
  }

  in.unsetf(std::ios::skipws);  // Avoids white space skipping.
  std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(*output));

  return true;
}
}  // namespace utils
}  // namespace lightex

Fix VS2015 build: istream_iterator is not a member of std


// 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 "ui/gfx/transform_util.h"

#include "ui/gfx/point.h"
#include "testing/gtest/include/gtest/gtest.h"

TEST(TransformUtilTest, GetScaleTransform) {
  const gfx::Point kAnchor(20, 40);
  const float kScale = 0.5f;

  gfx::Transform scale = gfx::GetScaleTransform(kAnchor, kScale);

  const int kOffset = 10;
  for (int sign_x = -1; sign_x <= 1; ++sign_x) {
    for (int sign_y = -1; sign_y <= 1; ++sign_y) {
      gfx::Point test(kAnchor.x() + sign_x * kOffset,
                      kAnchor.y() + sign_y * kOffset);
      scale.TransformPoint(test);

      EXPECT_EQ(gfx::Point(kAnchor.x() + sign_x * kOffset * kScale,
                           kAnchor.y() + sign_y * kOffset * kScale),
                test);
    }
  }
}

// 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 "ui/gfx/transform_util.h"

#include "ui/gfx/point.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace gfx {
namespace {

TEST(TransformUtilTest, GetScaleTransform) {
  const Point kAnchor(20, 40);
  const float kScale = 0.5f;

  Transform scale = GetScaleTransform(kAnchor, kScale);

  const int kOffset = 10;
  for (int sign_x = -1; sign_x <= 1; ++sign_x) {
    for (int sign_y = -1; sign_y <= 1; ++sign_y) {
      Point test(kAnchor.x() + sign_x * kOffset,
                 kAnchor.y() + sign_y * kOffset);
      scale.TransformPoint(test);

      EXPECT_EQ(Point(kAnchor.x() + sign_x * kOffset * kScale,
                      kAnchor.y() + sign_y * kOffset * kScale),
                test);
    }
  }
}

}  // namespace
}  // namespace gfx

Move transform_util unittest into gfx namespace.


#include <windows.h>
#include <tchar.h>
#include <stdio.h>

int _tmain(int argc, TCHAR * argv[])
{
	if(1 >= argc)
	{
		_tprintf(_T("DummLoader.exe <DllName>*\n"));
		return 0;
	}

	for(int i=1; i<argc; i++)
	{
		_tprintf(_T("Loading: \"%s\" "), argv[i]);
		HMODULE hm = LoadLibrary(argv[i]);
		_tprintf(_T("[ %s ]\n"), hm ? _T("OK") : _T("FAIL"));
	}

	return 0;
}

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

int _tmain(int argc, TCHAR * argv[])
{
	if(1 >= argc)
	{
		_tprintf(_T("DummLoader.exe <DllName>*\n"));
		return 0;
	}

	for(int i=1; i<argc; i++)
	{
		_tprintf(_T("Loading: \"%s\" "), argv[i]);
		HMODULE hm = LoadLibrary(argv[i]);
		DWORD lastError = GetLastError();
		_tprintf(_T("[ %s ] GetLastError = %u\n"), hm ? _T("OK") : _T("FAIL"), lastError);
	}

	return 0;
}

Add GetLastError info to DummyLoader test


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "functions.h"
#include "main-screen.h"
#include "models/profile.h"

int main(int argc, char *argv[])
{
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

	QGuiApplication app(argc, argv);
	app.setApplicationName("Grabber");
	app.setApplicationVersion(VERSION);
	app.setOrganizationName("Bionus");
	app.setOrganizationDomain("bionus.fr.cr");

	const QUrl url(QStringLiteral("qrc:/main-screen.qml"));

	QQmlApplicationEngine engine;
	QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
		if (!obj && url == objUrl) {
			QCoreApplication::exit(-1);
		}
	}, Qt::QueuedConnection);

	Profile profile(savePath());
	MainScreen mainScreen(&profile);
	engine.rootContext()->setContextProperty("backend", &mainScreen);

	engine.load(url);

	return app.exec();
}

#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "functions.h"
#include "main-screen.h"
#include "models/profile.h"

int main(int argc, char *argv[])
{
	QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

	QGuiApplication app(argc, argv);
	app.setApplicationName("Grabber");
	app.setApplicationVersion(VERSION);
	app.setOrganizationName("Bionus");
	app.setOrganizationDomain("bionus.fr.cr");

	// Copy settings files to writable directory
	const QStringList toCopy { "sites/", "themes/", "webservices/" };
	for (const QString &tgt : toCopy) {
		const QString from = savePath(tgt, true, false);
		const QString to = savePath(tgt, true, true);
		if (!QDir(to).exists() && QDir(from).exists()) {
			copyRecursively(from, to);
		}
	}

	const QUrl url(QStringLiteral("qrc:/main-screen.qml"));

	QQmlApplicationEngine engine;
	QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
		if (!obj && url == objUrl) {
			QCoreApplication::exit(-1);
		}
	}, Qt::QueuedConnection);

	Profile profile(savePath());
	MainScreen mainScreen(&profile);
	engine.rootContext()->setContextProperty("backend", &mainScreen);

	engine.load(url);

	return app.exec();
}

Copy necessary assets on Android QML startup


/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "obj_loader_demo/obj_loader_demo.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	ObjLoaderDemo::ObjLoaderDemo app(hInstance);
	DBG_UNREFERENCED_PARAMETER(hPrevInstance);
	DBG_UNREFERENCED_PARAMETER(lpCmdLine);
	DBG_UNREFERENCED_PARAMETER(nCmdShow);

	app.Initialize(L"OBJ Loader Demo", 800, 600, false);
	app.Run();

	app.Shutdown();

	return 0;
}

/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "obj_loader_demo/obj_loader_demo.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	ObjLoaderDemo::ObjLoaderDemo app(hInstance);
	DBG_UNREFERENCED_PARAMETER(hPrevInstance);
	DBG_UNREFERENCED_PARAMETER(lpCmdLine);
	DBG_UNREFERENCED_PARAMETER(nCmdShow);

	app.Initialize(L"OBJ Loader Demo", 1280, 720, false);
	app.Run();

	app.Shutdown();

	return 0;
}

Use 1280 x 720 as the default resolution


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "mmap_file_allocator_factory.h"
#include "mmap_file_allocator.h"
#include <vespa/vespalib/stllike/asciistream.h>

namespace vespalib::alloc {

MmapFileAllocatorFactory::MmapFileAllocatorFactory()
    : _dir_name(),
      _generation(0)
{
}

MmapFileAllocatorFactory::~MmapFileAllocatorFactory()
{
}

void
MmapFileAllocatorFactory::setup(const vespalib::string& dir_name)
{
    _dir_name = dir_name;
    _generation = 0;
}

std::unique_ptr<MemoryAllocator>
MmapFileAllocatorFactory::make_memory_allocator(const vespalib::string& name)
{
    if (_dir_name.empty()) {
        return {};
    }
    vespalib::asciistream os;
    os << _dir_name << "/" << _generation.fetch_add(1) << "." << name;
    return std::make_unique<MmapFileAllocator>(os.str());
};

MmapFileAllocatorFactory&
MmapFileAllocatorFactory::instance()
{
    static MmapFileAllocatorFactory instance;
    return instance;
}

}

// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "mmap_file_allocator_factory.h"
#include "mmap_file_allocator.h"
#include <vespa/vespalib/io/fileutil.h>
#include <vespa/vespalib/stllike/asciistream.h>

namespace vespalib::alloc {

MmapFileAllocatorFactory::MmapFileAllocatorFactory()
    : _dir_name(),
      _generation(0)
{
}

MmapFileAllocatorFactory::~MmapFileAllocatorFactory()
{
}

void
MmapFileAllocatorFactory::setup(const vespalib::string& dir_name)
{
    _dir_name = dir_name;
    _generation = 0;
    if (!_dir_name.empty()) {
        rmdir(_dir_name, true);
    }
}

std::unique_ptr<MemoryAllocator>
MmapFileAllocatorFactory::make_memory_allocator(const vespalib::string& name)
{
    if (_dir_name.empty()) {
        return {};
    }
    vespalib::asciistream os;
    os << _dir_name << "/" << _generation.fetch_add(1) << "." << name;
    return std::make_unique<MmapFileAllocator>(os.str());
};

MmapFileAllocatorFactory&
MmapFileAllocatorFactory::instance()
{
    static MmapFileAllocatorFactory instance;
    return instance;
}

}

Remove old swap files when setting up mmap file allocator.


// TODO: remove this later, hack for include order issues
#include "GLBlaat/GL.h"

#include <QApplication>
#include "Gui/MainWindow.h"

int main(int argc, char *argv[])
{
	// Set up Qt application
	QApplication app(argc, argv);

	VFE::MainWindow *window = new VFE::MainWindow();

	// Go!
	window->show();
	app.exec();

	// Clean up and exit
	delete window;
	return 0;
}

// TODO: remove this later, hack for include order issues
#include "GLBlaat/GL.h"

#include <QApplication>
#include "Gui/MainWindow.h"

#include <vtkWin32ProcessOutputWindow.h>

int main(int argc, char *argv[])
{
#ifdef WIN32
	// Use a more useful output window for VTK
	vtkWin32ProcessOutputWindow *ow = vtkWin32ProcessOutputWindow::New();
	vtkWin32ProcessOutputWindow::SetInstance(ow);
	ow->Delete();
#endif

	// Set up Qt application
	QApplication app(argc, argv);

	VFE::MainWindow *window = new VFE::MainWindow();

	// Go!
	window->show();
	app.exec();

	// Clean up and exit
	delete window;
	return 0;
}

Use a VTK output window we can actually read if the app crashes.


/** @file
    @brief Implementation

    @date 2014

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

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

// Internal Includes
#include <osvr/ClientKit/ContextC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/CreateContext.h>

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

// Standard includes
// - none

OSVR_ClientContext osvrClientInit(const char applicationIdentifier[],
                                  uint32_t /*flags*/) {
    return ::osvr::client::createContext(applicationIdentifier);
}
OSVR_ReturnCode osvrClientUpdate(OSVR_ClientContext ctx) {
    ctx->update();
    return OSVR_RETURN_SUCCESS;
}

OSVR_ReturnCode osvrClientShutdown(OSVR_ClientContext ctx) {
    delete ctx;
    return OSVR_RETURN_SUCCESS;
}

/** @file
    @brief Implementation

    @date 2014

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

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

// Internal Includes
#include <osvr/ClientKit/ContextC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/CreateContext.h>

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

// Standard includes
// - none

static const char HOST_ENV_VAR[] = "OSVR_HOST";

OSVR_ClientContext osvrClientInit(const char applicationIdentifier[],
                                  uint32_t /*flags*/) {
    char *host = ::getenv(HOST_ENV_VAR);
    if (nullptr != host) {
        return ::osvr::client::createContext(applicationIdentifier, host);
    } else {
        return ::osvr::client::createContext(applicationIdentifier);
    }
}
OSVR_ReturnCode osvrClientUpdate(OSVR_ClientContext ctx) {
    ctx->update();
    return OSVR_RETURN_SUCCESS;
}

OSVR_ReturnCode osvrClientShutdown(OSVR_ClientContext ctx) {
    delete ctx;
    return OSVR_RETURN_SUCCESS;
}

Add a quick and dirty way to access a remote OSVR server: using the environment variable OSVR_HOST.


#include "ShadingLanguageIncludeImplementation_ShadingLanguageIncludeARB.h"

#include <glbinding/gl/functions.h>

#include <globjects/Shader.h>

#include <globjects/base/AbstractStringSource.h>

using namespace gl;

namespace globjects
{

void ShadingLanguageIncludeImplementation_ARB::updateSources(const Shader * shader) const
{
    std::string source;
    if (shader->source()) {
        source = shader->source()->string();
    }

    const char* sourcePtr = source.c_str();
    glShaderSource(shader->id(), static_cast<GLint>(1), &sourcePtr, nullptr);
}

void ShadingLanguageIncludeImplementation_ARB::compile(const Shader * shader) const
{
    std::vector<const char*> cStrings = collectCStrings(shader->includePaths());
    glCompileShaderIncludeARB(shader->id(), static_cast<GLint>(cStrings.size()), cStrings.data(), nullptr);
}

} // namespace globjects

#include "ShadingLanguageIncludeImplementation_ShadingLanguageIncludeARB.h"

#include <glbinding/gl/functions.h>

#include <globjects/Shader.h>

#include <globjects/base/AbstractStringSource.h>

using namespace gl;

namespace globjects
{

void ShadingLanguageIncludeImplementation_ARB::updateSources(const Shader * shader) const
{
    std::string source;
    if (shader->source()) {
        source = shader->source()->string();
    }

    const char* sourcePtr = source.c_str();
    glShaderSource(shader->id(), static_cast<GLint>(1), &sourcePtr, nullptr);
}

void ShadingLanguageIncludeImplementation_ARB::compile(const Shader * shader) const
{
    if (!shader->includePaths().empty())
    {
        std::vector<const char*> cStrings = collectCStrings(shader->includePaths());
        glCompileShaderIncludeARB(shader->id(), static_cast<GLint>(cStrings.size()), cStrings.data(), nullptr);
    }
    else
    {
        glCompileShaderIncludeARB(shader->id(), 0, nullptr, nullptr);
    }

}

} // namespace globjects

Fix shading language include paths


/// Copyright 2019 Pinterest Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.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 "common/kafka/stats_enum.h"

#include <string>
#include <utility>
#include <vector>

#include "gflags/gflags.h"

DEFINE_string(kafka_stats_prefix, "", "Prefix for the kafka stats");
DEFINE_string(kafka_stats_suffix, "", "Suffix for the kafka stats");

std::string getFullStatsName(const std::string& metric_name,
                             const std::initializer_list<std::string>& tags) {
  std::string full_metric_name;
  full_metric_name.append(FLAGS_kafka_stats_prefix)
      .append(metric_name)
      .append(FLAGS_kafka_stats_suffix);
  for (const auto& tag : tags) {
    full_metric_name.append(" ").append(tag);
  }
  return full_metric_name;
}

/// Copyright 2019 Pinterest Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.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 "common/kafka/stats_enum.h"

#include <string>
#include <utility>
#include <vector>

#include "gflags/gflags.h"

DEFINE_string(kafka_stats_prefix, "", "Prefix for the kafka stats");
DEFINE_string(kafka_stats_suffix, "", "Suffix for the kafka stats");
DEFINE_string(kafka_cluster_name, "", "Cluster consuming the kafka messages");

std::string getFullStatsName(const std::string& metric_name,
                             const std::initializer_list<std::string>& tags) {
  std::string full_metric_name;
  full_metric_name.append(FLAGS_kafka_stats_prefix)
      .append(metric_name)
      .append("_")
      .append(FLAGS_kafka_stats_suffix)
      .append(" cluster=")
      .append(FLAGS_kafka_cluster_name);
  for (const auto& tag : tags) {
    full_metric_name.append(" ").append(tag);
  }
  return full_metric_name;
}

Add a new flag for cluster name


/******************************************************************************\
 * gloperate
 *
 * Copyright (C) 2014 Computer Graphics Systems Group at the
 * Hasso-Plattner-Institut (HPI), Potsdam, Germany.
\******************************************************************************/
#include <gloperate/capabilities/TypedRenderTargetCapability.h>

namespace gloperate {

/**
*  @brief
*    Constructor
*/
TypedRenderTargetCapability::TypedRenderTargetCapability()
:AbstractTypedRenderTargetCapability()
{
}

/**
*  @brief
*    Destructor
*/
TypedRenderTargetCapability::~TypedRenderTargetCapability()
{
}

const RenderTarget & TypedRenderTargetCapability::renderTarget(RenderTargetType type)
{
    return *(m_renderTargets.at(type));
}

bool TypedRenderTargetCapability::hasRenderTarget(RenderTargetType type)
{
    return (m_renderTargets.count(type) > 0);
}

void TypedRenderTargetCapability::setRenderTarget(
    RenderTargetType type,
    globjects::ref_ptr<globjects::Framebuffer> framebuffer,
    gl::GLenum attachment,
    gl::GLenum format)
{
    if (hasRenderTarget(type))
    {
        delete m_renderTargets.at(type);
    }

    m_renderTargets[type] = new RenderTarget(framebuffer, attachment, format);
}

} // namespace gloperate

/******************************************************************************\
 * gloperate
 *
 * Copyright (C) 2014 Computer Graphics Systems Group at the
 * Hasso-Plattner-Institut (HPI), Potsdam, Germany.
\******************************************************************************/
#include <gloperate/capabilities/TypedRenderTargetCapability.h>

namespace gloperate {

/**
*  @brief
*    Constructor
*/
TypedRenderTargetCapability::TypedRenderTargetCapability()
:AbstractTypedRenderTargetCapability()
{
}

/**
*  @brief
*    Destructor
*/
TypedRenderTargetCapability::~TypedRenderTargetCapability()
{
    m_renderTargets.clear();
}

const RenderTarget & TypedRenderTargetCapability::renderTarget(RenderTargetType type)
{
    return *(m_renderTargets.at(type));
}

bool TypedRenderTargetCapability::hasRenderTarget(RenderTargetType type)
{
    return (m_renderTargets.count(type) > 0);
}

void TypedRenderTargetCapability::setRenderTarget(
    RenderTargetType type,
    globjects::ref_ptr<globjects::Framebuffer> framebuffer,
    gl::GLenum attachment,
    gl::GLenum format)
{
    if (hasRenderTarget(type))
    {
        delete m_renderTargets.at(type);
    }

    m_renderTargets[type] = new RenderTarget(framebuffer, attachment, format);
}

} // namespace gloperate

Add clear map on destruction


#include "stdafx.h"
#include <string>
#include "Listener.h"

using namespace DShowLib;

// Increments the number of processed frames
void    CListener::frameReady(Grabber& caller, smart_ptr<MemBuffer> pBuffer, DWORD currFrame)
{
	done++;
}

#include "stdafx.h"
#include <string>
#include "Listener.h"

using namespace DShowLib;

// Increments the number of processed frames
void    CListener::frameReady(Grabber& caller, smart_ptr<MemBuffer> pBuffer, DWORD currFrame)
{
	MessageBeep(-1);
	done++;
}

Add sound when frame is ready


/* mbed Microcontroller Library
 * Copyright (c) 2013-2014 ARM Limited
 *
 * 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 "mbed.h"
#include "test_env.h"

DigitalOut myled(LED1);
uint32_t count = 20;

void blink() {
    if (count) {
    	if (count == 1) {
    		printf("{{success}}\r\n");
    	}
    	count--;
    }
    myled = !myled;
}

void app_start(int, char*[]) {
    MBED_HOSTTEST_TIMEOUT(20);
    MBED_HOSTTEST_SELECT(default_auto);
    MBED_HOSTTEST_DESCRIPTION(Blinky);
    MBED_HOSTTEST_START("MBED_BLINKY");
    minar::Scheduler::postCallback(&blink).period(minar::milliseconds(200));
}

/* mbed Microcontroller Library
 * Copyright (c) 2013-2014 ARM Limited
 *
 * 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 "mbed.h"
#include "test_env.h"

DigitalOut myled(LED1);
uint32_t count = 20;

void blink() {
    if (count) {
    	if (count == 1) {
    		MBED_HOSTTEST_RESULT(true);
    	}
    	count--;
    }
    myled = !myled;
}

void app_start(int, char*[]) {
    MBED_HOSTTEST_TIMEOUT(20);
    MBED_HOSTTEST_SELECT(default_auto);
    MBED_HOSTTEST_DESCRIPTION(Blinky);
    MBED_HOSTTEST_START("MBED_BLINKY");
    minar::Scheduler::postCallback(&blink).period(minar::milliseconds(200));
}

Test - fix blinky test - print host test result


#include <cstdlib>

#include <libport/backtrace.hh>
#include <libport/config.h>

#if LIBPORT_HAVE_EXECINFO_H
# include <execinfo.h>

namespace libport
{
  std::vector<const char*>
  backtrace()
  {
    enum { size = 128 };
    void* callstack[size];
    size_t frames = ::backtrace(callstack, size);
    char** strs = backtrace_symbols(callstack, frames);

    std::vector<const char*> res(frames, 0);
    for (size_t i = 0; i < frames; ++i)
      res[i] = strs[i];

    free(strs);
    return res;
  }
}

#else // ! LIBPORT_HAVE_EXECINFO_H

namespace libport
{
  std::vector<const char*>
  backtrace()
  {
    std::vector<const char*> res;
    res.push_back("(no avaible backtrace)");
  }
}

#endif

#include <cstdlib>

#include <libport/backtrace.hh>
#include <libport/config.h>

#if LIBPORT_HAVE_EXECINFO_H
# include <execinfo.h>
# include <cstdlib>

namespace libport
{
  std::vector<const char*>
  backtrace()
  {
    enum { size = 128 };
    void* callstack[size];
    size_t frames = ::backtrace(callstack, size);
    char** strs = backtrace_symbols(callstack, frames);

    std::vector<const char*> res(frames, 0);
    for (size_t i = 0; i < frames; ++i)
      res[i] = strs[i];

    free(strs);
    return res;
  }
}

#else // ! LIBPORT_HAVE_EXECINFO_H

namespace libport
{
  std::vector<const char*>
  backtrace()
  {
    std::vector<const char*> res;
    res.push_back("(no avaible backtrace)");
    return res;
  }
}

#endif

Add forgotten include and return.


#include "instr.h"

namespace sasm { namespace instr {

instr::instr(const sasm::elf::elf& elf, uint64 addr)
  : _elf(elf), _addr(addr)
{
}

void instr::_dump_addr(std::ostream& out) const
{
  out << "0x" << std::hex << _addr << std::dec << ": ";
}

}}

#include "instr.h"

namespace sasm { namespace instr {

instr::instr(const sasm::elf::elf& elf, uint64 addr)
  : _elf(elf), _addr(addr)
{
}

void instr::_dump_addr(std::ostream& out) const
{
  try
  {
    auto sym = _elf.symtab[_addr];

    if (sym.type == sasm::elf::symtab::symbol::sym_type::func)
      out << std::endl << sym.name << ":" << std::endl;
  }
  catch (std::out_of_range& e) {}

  out << "  0x" << std::hex << _addr << std::dec << ": ";
}

}}

Print function symbols when dumping asm.


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

#include "nodestate.h"

/**
* Default constructor initializing all local member variables to "null" values
*/
CNodeState::CNodeState()
{
    pindexBestKnownBlock = nullptr;
    hashLastUnknownBlock.SetNull();
    pindexLastCommonBlock = nullptr;
    pindexBestHeaderSent = nullptr;
    fSyncStarted = false;
    nDownloadingSince = 0;
    nBlocksInFlight = 0;
    nBlocksInFlightValidHeaders = 0;
    fPreferredDownload = false;
    fPreferHeaders = false;
    fRequestedInitialBlockAvailability = false;
}

/**
* Gets the CNodeState for the specified NodeId.
*
* @param[in] pnode  The NodeId to return CNodeState* for
* @return CNodeState* matching the NodeId, or NULL if NodeId is not matched
*/
CNodeState *State(NodeId pnode)
{
    std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
    if (it == mapNodeState.end())
        return nullptr;
    return &it->second;
}

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

#include "nodestate.h"

/**
* Default constructor initializing all local member variables to "null" values
*/
CNodeState::CNodeState()
{
    pindexBestKnownBlock = nullptr;
    hashLastUnknownBlock.SetNull();
    pindexLastCommonBlock = nullptr;
    pindexBestHeaderSent = nullptr;
    fSyncStarted = false;
    fSyncStartTime = -1;
    fFirstHeadersReceived = false;
    nFirstHeadersExpectedHeight = -1;
    fRequestedInitialBlockAvailability = false;
    nDownloadingSince = 0;
    nBlocksInFlight = 0;
    nBlocksInFlightValidHeaders = 0;
    fPreferredDownload = false;
    fPreferHeaders = true;
}

/**
* Gets the CNodeState for the specified NodeId.
*
* @param[in] pnode  The NodeId to return CNodeState* for
* @return CNodeState* matching the NodeId, or NULL if NodeId is not matched
*/
CNodeState *State(NodeId pnode)
{
    std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
    if (it == mapNodeState.end())
        return nullptr;
    return &it->second;
}

Initialize all variables for CNodeState


#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <cmath>
#include <iomanip>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	cout << "Szymon Blaszczynski" << endl;
	cout << setprecision(8) << M_PI << endl;
	cout << "\"Ala\"" << endl;
	getch();
	// system("PAUSE"); // work on linux? no.
	return 0;
}

#include <iostream>
// #include <conio.h> // getch
// #include <cstdlib> # system
#include <cmath>
#include <iomanip>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	cout << "Szymon Blaszczynski" << endl;
	cout << setprecision(8) << M_PI << endl;
	cout << "\"Ala\"" << endl;
	cout << "'" << endl;
	int number_0 = 0;
	int number_1 = 0;
	cout << "Podaj dwie liczby: ";
	cin >> number_0 >> number_1;
	cout << "Liczba pierwsza: " << number_0 << ", liczba druga: " << number_1 \
		<< "." << endl;
	// system("PAUSE"); // works on linux? no.
	return 0;
}

Read two integers and write them out


/**
 ** \file object/delegate-class.cc
 ** \brief Creation of the URBI object delegate.
 */

#include "object/delegate-class.hh"
#include "object/object.hh"
#include "object/primitives.hh"

#include "runner/runner.hh"
namespace object
{
  rObject delegate_class;

  /*-----------------------.
  | Primitive primitives.  |
  `-----------------------*/

  void
  delegate_class_initialize ()
  {
#define DECLARE(Name)                           \
        DECLARE_PRIMITIVE(delegate, Name)
#undef DECLARE
  }

} // namespace object

/**
 ** \file object/delegate-class.cc
 ** \brief Creation of the URBI object delegate.
 */

#include "object/delegate-class.hh"
#include "object/object.hh"
#include "object/primitives.hh"

#include "runner/runner.hh"

namespace object
{
  rObject delegate_class;

  /*-----------------------.
  | Primitive primitives.  |
  `-----------------------*/

  static rObject
  delegate_class_apply (runner::Runner& r, objects_type args)
  {
    CHECK_ARG_COUNT (2);
    FETCH_ARG (1, List);
    return r.apply (args[0], arg1);
  }

  void
  delegate_class_initialize ()
  {
#define DECLARE(Name)				\
    DECLARE_PRIMITIVE(delegate, Name)
    DECLARE (apply);
#undef DECLARE
  }

} // namespace object

Add apply to Delegate type.


// RUN: %clang_cc1 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s

struct A {
  virtual ~A();
};

struct B : A { };

struct C {
  int i;
  B b;
};

// CHECK: _Z15test_value_initv
void test_value_init() {
  // This value initialization requires zero initialization of the 'B'
  // subobject followed by a call to its constructor.
  // PR5800

  // CHECK: store i32 17
  // CHECK: call void @llvm.memset.i64
  // CHECK: call void @_ZN1BC1Ev(%struct.A* %tmp1)
  C c = { 17 } ;
  // CHECK: call void @_ZN1CD1Ev(%struct.C* %c)
}

// RUN: %clang_cc1 %s -triple x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s

struct A {
  virtual ~A();
};

struct B : A { };

struct C {
  int i;
  B b;
};

// CHECK: _Z15test_value_initv
void test_value_init() {
  // This value initialization requires zero initialization of the 'B'
  // subobject followed by a call to its constructor.
  // PR5800

  // CHECK: store i32 17
  // CHECK: call void @llvm.memset.i64
  // CHECK: call void @_ZN1BC1Ev
  C c = { 17 } ;
  // CHECK: call void @_ZN1CD1Ev
}

Fix test case to unbreak testing


#include "insertion.hpp"
#include "swap.hpp"

void insertion(int *data, int size_of_data)
{
    for(int i = 0; i < size_of_data; ++i)
    {
        int j;
        for(j = i; data[j] < data[i]; --j);
        swap(data[i], data[j]);
    }
}

#include "insertion.hpp"
#include "swap.hpp"

void insertion(int *data, int size_of_data)
{
    for(int i = 0; i < size_of_data; ++i)
    {
        int j;
        for(j = i; j >= 0 && data[j] < data[i]; --j);
        swap(data[i], data[j]);
    }
}

Add boundary value in loop expression


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

int getMinHelper(vector<int> DesiredArray, int Moves)
{
    if(all_of(begin(DesiredArray), end(DesiredArray), [] (const int & element) {return element==0;}))
    {
        return Moves;
    }

    if(all_of(begin(DesiredArray), end(DesiredArray), [] (int & element) {return element%2==0;}))
    {
        for(auto & element : DesiredArray)
        {
            element/=2;
        }

        Moves++;
    }
    else
    {
        for(auto & element : DesiredArray)
        {
            if(element%2==1)
            {
                element--;

                Moves++;
            }
        }
    }

    return getMinHelper(DesiredArray, Moves);
}

int getMin(vector<int> DesiredArray)
{
    int moves{};

    int result=getMinHelper(DesiredArray, moves);

    return result;
}

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

class IncrementAndDoubling
{
    public:
        int getMinHelper(vector<int> DesiredArray, int Moves)
        {
            if(all_of(begin(DesiredArray), end(DesiredArray), [] (const int & element) {return element==0;}))
            {
                return Moves;
            }

            if(all_of(begin(DesiredArray), end(DesiredArray), [] (int & element) {return element%2==0;}))
            {
                for(auto & element : DesiredArray)
                {
                    element/=2;
                }

                Moves++;
            }
            else
            {
                for(auto & element : DesiredArray)
                {
                    if(element%2==1)
                    {
                        element--;

                        Moves++;
                    }
                }
            }

            return getMinHelper(DesiredArray, Moves);
        }

        int getMin(vector<int> DesiredArray)
        {
            int moves{};

            int result=getMinHelper(DesiredArray, moves);

            return result;
        }
};

Put functions in the required class


#include "embedded.h"

#include <QtCore>
#include <QVBoxLayout>
#include <QApplication>
#include <QDesktopWidget>

#include <maliit/namespace.h>
#include <maliit/inputmethod.h>

MainWindow::MainWindow()
    : QMainWindow()
{
    initUI();
}

MainWindow::~MainWindow()
{}

void MainWindow::initUI()
{
    setWindowTitle("Maliit embedded demo");

    setCentralWidget(new QWidget);
    QVBoxLayout *vbox = new QVBoxLayout;

    QPushButton *closeApp = new QPushButton("Close application");
    vbox->addWidget(closeApp);
    connect(closeApp, SIGNAL(clicked()),
            this,     SLOT(close()));

    // Clicking the button will steal focus from the text edit, thus hiding
    // the virtual keyboard:
    QPushButton *hideVkb = new QPushButton("Hide virtual keyboard");
    vbox->addWidget(hideVkb);

    QTextEdit *textEdit = new QTextEdit;
    vbox->addWidget(textEdit);

    QWidget *imWidget = Maliit::InputMethod::instance()->widget();
    if (imWidget) {
        imWidget->setParent(centralWidget());
        vbox->addWidget(imWidget);

        // FIXME: hack to work around the fact that plugins expect a desktop sized widget
        QSize desktopSize = QApplication::desktop()->size();
        imWidget->setMinimumSize(desktopSize.width(), desktopSize.height() - 150);
    } else {
        qCritical() << "Unable to embedded Maliit input method widget";
    }

    centralWidget()->setLayout(vbox);
    show();
    imWidget->hide();
}

#include "embedded.h"

#include <QtCore>
#include <QVBoxLayout>
#include <QApplication>
#include <QDesktopWidget>

#include <maliit/namespace.h>
#include <maliit/inputmethod.h>

MainWindow::MainWindow()
    : QMainWindow()
{
    initUI();
}

MainWindow::~MainWindow()
{}

void MainWindow::initUI()
{
    setWindowTitle("Maliit embedded demo");

    setCentralWidget(new QWidget);
    QVBoxLayout *vbox = new QVBoxLayout;

    QPushButton *closeApp = new QPushButton("Close application");
    vbox->addWidget(closeApp);
    connect(closeApp, SIGNAL(clicked()),
            this,     SLOT(close()));

    // Clicking the button will steal focus from the text edit, thus hiding
    // the virtual keyboard:
    QPushButton *hideVkb = new QPushButton("Hide virtual keyboard");
    vbox->addWidget(hideVkb);

    QTextEdit *textEdit = new QTextEdit;
    vbox->addWidget(textEdit);

    QWidget *imWidget = Maliit::InputMethod::instance()->widget();
    if (imWidget) {
        imWidget->setParent(centralWidget());
        vbox->addWidget(imWidget);
    } else {
        qCritical() << "Unable to embedded Maliit input method widget";
    }

    centralWidget()->setLayout(vbox);
    show();
}

Remove now unneded hack from embedding example.


#include "messmer/cpp-utils/tempfile/TempDir.h"
#include "messmer/fspp/fuse/Fuse.h"
#include "messmer/fspp/impl/FilesystemImpl.h"
#include "CopyDevice.h"

using cpputils::TempDir;
using copyfs::CopyDevice;
using fspp::FilesystemImpl;
using fspp::fuse::Fuse;

int main (int argc, char *argv[])
{
  TempDir dir;
  CopyDevice device(dir.path().c_str());
  FilesystemImpl fsimpl(&device);
  Fuse fuse(&fsimpl);
  printf("CopyFS initialized\nBase directory: %s\n", dir.path().c_str());
  fuse.run(argc, argv);
  return 0;
}

#include "messmer/cpp-utils/tempfile/TempDir.h"
#include "messmer/fspp/fuse/Fuse.h"
#include "messmer/fspp/impl/FilesystemImpl.h"
#include "CopyDevice.h"
#include <iostream>

using cpputils::TempDir;
using copyfs::CopyDevice;
using fspp::FilesystemImpl;
using fspp::fuse::Fuse;

int main (int argc, char *argv[])
{
  TempDir dir;
  CopyDevice device(dir.path().c_str());
  FilesystemImpl fsimpl(&device);
  Fuse fuse(&fsimpl);
  std::cout << "CopyFS initialized\nBase directory: " << dir.path().c_str() << std::endl;
  fuse.run(argc, argv);
  return 0;
}

Use cout instead of printf


// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "tools/args/verifier.h"

using namespace cpputil;

namespace stoke {

Heading& verifier_heading =
  Heading::create("Verifier Options:");

ValueArg<Strategy, StrategyReader, StrategyWriter>& strategy_arg =
  ValueArg<Strategy, StrategyReader, StrategyWriter>::create("strategy")
  .usage("(none|hold_out|extension)")
  .description("Verification strategy")
  .default_val(Strategy::NONE);

} // namespace stoke

// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "tools/args/verifier.h"

using namespace cpputil;

namespace stoke {

Heading& verifier_heading =
  Heading::create("Verifier Options:");

ValueArg<Strategy, StrategyReader, StrategyWriter>& strategy_arg =
  ValueArg<Strategy, StrategyReader, StrategyWriter>::create("strategy")
  .usage("(none|hold_out|formal|extension)")
  .description("Verification strategy")
  .default_val(Strategy::NONE);

} // namespace stoke

Add command line help for --strategy formal


#include "mainwindow.h"
#include <QApplication>
#include <QFile>
#include "applicationdata.h"
#include "blocktype.h"
#include <QJsonDocument>
#include <QJsonArray>

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

    QString appDir = a.applicationDirPath();

    QString xmlPath = appDir + "/blocks.json";
    QFile xmlFile(xmlPath);
    if (!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        // error message
        return 1;
    }
    QByteArray bytes = xmlFile.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(bytes);
    QJsonArray nodeArray = doc.array();
    ApplicationData appData;
    appData.blockTypes = BlockTypes_fromJson(nodeArray);

    MainWindow w(appData);
    w.show();

    return a.exec();
}

#include "mainwindow.h"
#include <QApplication>
#include <QFile>
#include "applicationdata.h"
#include "blocktype.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QMessageBox>

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

    QString appDir = a.applicationDirPath();

    QString xmlPath = appDir + "/blocks.json";
    QFile xmlFile(xmlPath);
    if (!xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::critical(0, "SignalCraft failed to open blocks.json",
                              "The block.json file could not be opened. Ensure that it exists.");
        return 1;
    }
    QByteArray bytes = xmlFile.readAll();
    QJsonParseError parseErr;
    QJsonDocument doc = QJsonDocument::fromJson(bytes, &parseErr);
    if (parseErr.error != QJsonParseError::NoError) {
        QMessageBox::critical(0, "SignalCraft failed to parse blocks.json",
                              "The block.json file could not be parsed as valid JSON. The parser reported: \"" +
                              parseErr.errorString() +
                              "\" at offset " +
                              QString::number(parseErr.offset) +
                              ".");
        return 1;
    }
    QJsonArray nodeArray = doc.array();
    ApplicationData appData;
    bool success;
    appData.blockTypes = BlockTypes_fromJson(nodeArray, &success);
    if (!success) {
        QMessageBox::critical(0, "SignalCraft failed to interpret blocks.json",
                              "The block.json file did not fit the required structure.");
        return 1;
    }

    MainWindow w(appData);
    w.show();

    return a.exec();
}

Handle errors loading block types