#include "perceptioninfoprivate.h"

#include "btperceptioninfoscriptable.h"

using namespace GluonEngine;

PerceptionInfoPrivate::PerceptionInfoPrivate(QObject * parent)
	: QSharedData()
{
	info = new btPerceptionInfoScriptable(parent);
	QScriptValue extensionObject = engine.globalObject();
	script = 0;
}

PerceptionInfoPrivate::PerceptionInfoPrivate(const PerceptionInfoPrivate& other)
	: QSharedData()
	, info(other.info)
	, updateFunc(other.updateFunc)
	, drawFunc(other.drawFunc)
	, getAdjustedValueFunc(other.getAdjustedValueFunc)
	, script(other.script)
{
	QScriptValue extensionObject = engine.globalObject();
}

PerceptionInfoPrivate::~PerceptionInfoPrivate()
{
}

#include "perceptioninfoprivate.h"

#include "btperceptioninfoscriptable.h"

using namespace GluonEngine;

PerceptionInfoPrivate::PerceptionInfoPrivate(QObject * parent)
	: QSharedData()
{
	info = new btPerceptionInfoScriptable(parent);
	QScriptValue extensionObject = engine.globalObject();
	script = 0;
}

PerceptionInfoPrivate::PerceptionInfoPrivate(const PerceptionInfoPrivate& other)
	: QSharedData()
	, info(other.info)
	, drawFunc(other.drawFunc)
	, updateFunc(other.updateFunc)
	, getAdjustedValueFunc(other.getAdjustedValueFunc)
	, script(other.script)
{
	QScriptValue extensionObject = engine.globalObject();
}

PerceptionInfoPrivate::~PerceptionInfoPrivate()
{
}

Fix an initialization order issue in the copy ctor to avoid the warning

CCMAIL: d033e22ae348aeb5660fc2140aec35850c4da997@leinir.dk


#include "simplegameworld.h"

void SimpleGameWorld::addEntity(shared_ptr< gamefw::Entity > entity)
{
    m_entity_list.push_back(entity);
}

void SimpleGameWorld::update()
{
    foreach(shared_ptr<gamefw::Entity> entity, m_entity_list) {
            entity->m_position.x += entity->m_velocity_local.x *
                            glm::cos(glm::radians(entity->m_orientation.x)) +
                            -entity->m_velocity_local.z *
                            glm::sin(glm::radians(entity->m_orientation.x));
            entity->m_position.z += entity->m_velocity_local.x *
                            glm::sin(glm::radians(entity->m_orientation.x)) +
                            entity->m_velocity_local.z *
                            glm::cos(glm::radians(entity->m_orientation.x));
            entity->m_position.y += entity->m_velocity_local.y;
    }
}

#include "simplegameworld.h"

void SimpleGameWorld::addEntity(shared_ptr< gamefw::Entity > entity)
{
    m_entity_list.push_back(entity);
}

void SimpleGameWorld::update()
{
    foreach(shared_ptr<gamefw::Entity> entity, m_entity_list) {
            entity->m_position.x += entity->m_velocity_local.x *
                            glm::cos(glm::radians(entity->m_orientation.x)) +
                            -entity->m_velocity_local.z *
                            glm::sin(glm::radians(entity->m_orientation.x));
            entity->m_position.z += entity->m_velocity_local.x *
                            glm::sin(glm::radians(entity->m_orientation.x)) +
                            entity->m_velocity_local.z *
                            glm::cos(glm::radians(entity->m_orientation.x));
            entity->m_position.y += entity->m_velocity_local.y;

	    entity->m_orientation += entity->m_angular_velocity;
    }
}

Add orientation update in SimpleGameWorld::Update.


#include "util/file_piece.hh"

#include "util/file.hh"
#include "util/scoped.hh"
#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"
#include "util/murmur_hash.hh"
#include "util/probing_hash_table.hh"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <fstream>
#include <iostream>

#include <boost/scoped_array.hpp>
#include <boost/functional/hash.hpp>

int main() {

  std::fstream backing("../source.uniq.rand.gz", std::ios::in);
  util::FilePiece test(backing, NULL, 1);
  //An example of how not to read a file (try/catch), will change later, but for now, hacking
  while(true){
    try {
      StringPiece line = test.ReadLine();

      std::cout << line << std::endl;

    } catch (util::EndOfFileException e){
      std::cout << "End of file" << std::endl;
      break;
    }
  }

  return 0;
}

#include "util/file_piece.hh"

#include "util/file.hh"
#include "util/scoped.hh"
#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"
#include "util/murmur_hash.hh"
#include "util/probing_hash_table.hh"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <fstream>
#include <iostream>

#include <boost/scoped_array.hpp>
#include <boost/functional/hash.hpp>

int main() {

  //std::fstream backing("../source.uniq.rand.gz", std::ios::in);
  util::FilePiece test("../source.uniq.rand.gz", NULL, 1);
  //An example of how not to read a file (try/catch), will change later, but for now, hacking
  while(true){
    try {
      StringPiece line = test.ReadLine();

      std::cout << line << std::endl;

    } catch (util::EndOfFileException e){
      std::cout << "End of file" << std::endl;
      break;
    }
  }

  return 0;
}

Fix reading from archived file in example


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

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

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

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

namespace tensorflow {
namespace tpu {

/* static */
void TpuCompilationCacheMetrics::IncrementCacheLookupCount(
    bool is_cache_hit, absl::string_view session_name) {
  // A placeholder for tracking metrics.
}

/* static */
void TpuCompilationCacheMetrics::SetCacheEntryCount(int64 count) {
  // A placeholder for tracking metrics.
}

}  // namespace tpu
}  // namespace tensorflow

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

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

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

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

namespace tensorflow {
namespace tpu {

// TODO(henrytan): remove this once `TpuCompilationCache` migration to OSS is
// completed.
#if defined(LIBTFTPU)
/* static */
void TpuCompilationCacheMetrics::IncrementCacheLookupCount(
    bool is_cache_hit, absl::string_view session_name) {
  // A placeholder for tracking metrics.
}

/* static */
void TpuCompilationCacheMetrics::SetCacheEntryCount(int64 count) {
  // A placeholder for tracking metrics.
}
#endif  // LIBTFTPU

}  // namespace tpu
}  // namespace tensorflow

Add LIBTFTPU macro qualifier to the definition of the TpuCompilationCacheMetrics.

PiperOrigin-RevId: 319157570
Change-Id: I0ee8c7036ec37eaba0cf661e5448c5cbc599d6df


// Clang on MacOS can find libc++ living beside the installed compiler.
// This test makes sure our libTooling-based tools emulate this properly with
// fixed compilation database.
//
// RUN: rm -rf %t
// RUN: mkdir %t
//
// Install the mock libc++ (simulates the libc++ directory structure).
// RUN: cp -r %S/Inputs/mock-libcxx %t/
//
// RUN: cp $(which clang-check) %t/mock-libcxx/bin/
// RUN: cp "%s" "%t/test.cpp"
// RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ -target x86_64-apple-darwin

#include <mock_vector>
vector v;

// Clang on MacOS can find libc++ living beside the installed compiler.
// This test makes sure our libTooling-based tools emulate this properly with
// fixed compilation database.
//
// RUN: rm -rf %t
// RUN: mkdir %t
//
// Install the mock libc++ (simulates the libc++ directory structure).
// RUN: cp -r %S/Inputs/mock-libcxx %t/
//
// RUN: cp $(which clang-check) %t/mock-libcxx/bin/
// RUN: cp "%s" "%t/test.cpp"
// RUN: %t/mock-libcxx/bin/clang-check -p "%t" "%t/test.cpp" -- -stdlib=libc++ -target x86_64-apple-darwin
// REQUIRES: system-darwin
#include <mock_vector>
vector v;

Add a REQUIRES: darwin line for a mac test.

This test, apparently for macs, fails on Windows as lit can't emulate
the shell subprocess $(which...) correctly. Some other netbsd and linux
buildbots also fail here. Limit to macs as a temporary workaround.

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


#include "texture.hpp"

#include <string>

#include <SDL_image.h>

const std::string Texture::filename(const std::string &name)
{
  return "/textures/" + name;
}

Texture::Texture(const Adapter &adapter, const std::string &name)
{
  SDL_Surface *surface = IMG_Load(adapter.filename<Texture>(name).c_str());

  glGenTextures(1, &_id);
  glBindTexture(GL_TEXTURE_2D, _id);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels);

  SDL_FreeSurface(surface);
}

void Texture::use() const
{
  glBindTexture(GL_TEXTURE_2D, _id);
}

#include "texture.hpp"

#include <string>

#define STB_IMAGE_IMPLEMENTATION
#define STBI_ASSERT(x)
#define STBI_ONLY_PNG
#include <stb_image.h>

const std::string Texture::filename(const std::string &name)
{
  return "/textures/" + name;
}

Texture::Texture(const Adapter &adapter, const std::string &name)
{
  GLsizei width, height, comp;
  GLvoid *data = stbi_load(adapter.filename<Texture>(name).c_str(), &width, &height, &comp, 0);

  glGenTextures(1, &_id);
  glBindTexture(GL_TEXTURE_2D, _id);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

  stbi_image_free(data);
}

void Texture::use() const
{
  glBindTexture(GL_TEXTURE_2D, _id);
}

Use STB Image instead of SDL Image

Use STB Image instead of SDL Image


#include "line.hpp"

// Include standard headers
#include <cmath>     // NAN, std::isnan, std::pow
#include <string>    // std::string
#include <vector>    // std::vector

namespace geometry
{
    // constructor.
    // can be used for creating n-dimensional lines.
    Line::Line(std::vector<float> point1, std::vector<float> point2)
    {
        if (point1 == point2)
        {
            this->is_valid = false; // two identical points do not define a line.
            this->general_form_coefficients.push_back(NAN);
            this->general_form_constant = NAN;
        }
        else
        {
            this->is_valid = true; // two distinct points define a line.
        }
    }

    // constructor.
    // can be used for creating n-dimensional lines.
    Line::Line(std::vector<float> general_form_coefficients, float general_form_constant)
    {
        this->general_form_coefficients = general_form_coefficients;
        this->general_form_constant = general_form_constant;
    }

    std::string Line::get_general_form_equation()
    {
        // TODO: implement this function!
        std::string line_equation;
        return line_equation;
    }
}

#include "line.hpp"

// Include standard headers
#include <cmath>     // NAN, std::isnan, std::pow
#include <string>    // std::string
#include <vector>    // std::vector

namespace geometry
{
    // constructor.
    // can be used for creating n-dimensional lines.
    Line::Line(std::vector<float> point1, std::vector<float> point2)
    {
        if (point1 == point2)
        {
            this->is_valid = false; // two identical points do not define a line.
            this->general_form_coefficients.push_back(NAN);
            this->general_form_constant = NAN;
        }
        else
        {
            this->is_valid = true; // two distinct points define a line.
            this->are_points_defined = true;
            this->point1 = point1;
            this->point2 = point2;
        }
    }

    // constructor.
    // can be used for creating n-dimensional lines.
    Line::Line(std::vector<float> general_form_coefficients, float general_form_constant)
    {
        this->general_form_coefficients = general_form_coefficients;
        this->general_form_constant = general_form_constant;
    }

    std::string Line::get_general_form_equation()
    {
        // TODO: implement this function!
        std::string line_equation;
        return line_equation;
    }
}

Define variables `are_points_defined`, `point1`, `point2`.

	modified:   cpp/ylikuutio/geometry/line.cpp


#include <MinConsole.hpp>
#include <Windows.h>

namespace MinConsole
{
void* GetOutputHandle()
{
	static void* Handle = nullptr;

	if( Handle == nullptr )
	{
		Handle = GetStdHandle(STD_OUTPUT_HANDLE);
	}

	return Handle;
}

void SetTextColor(Color NewColor)
{
	SetConsoleTextAttribute(
		GetOutputHandle(),
		static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor)
	);
}

std::size_t GetWidth()
{
	CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
	if( GetConsoleScreenBufferInfo(
		GetOutputHandle(),
		&ConsoleInfo) )
	{
		return static_cast<size_t>(ConsoleInfo.dwSize.X);
	}
	return 0;
}
}

#include <MinConsole.hpp>
#include <Windows.h>
#include <mutex>

namespace MinConsole
{
void* GetOutputHandle()
{
	static void* Handle = nullptr;
	std::once_flag HandleCached;
	std::call_once(HandleCached, [=]()
		{
			Handle = GetStdHandle(STD_OUTPUT_HANDLE);
		});
	return Handle;
}

void SetTextColor(Color NewColor)
{
	SetConsoleTextAttribute(
		GetOutputHandle(),
		static_cast<std::underlying_type_t<MinConsole::Color>>(NewColor)
	);
}

std::size_t GetWidth()
{
	CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
	if( GetConsoleScreenBufferInfo(
		GetOutputHandle(),
		&ConsoleInfo) )
	{
		return static_cast<size_t>(ConsoleInfo.dwSize.X);
	}
	return 0;
}
}

Set StdHandle initialization with with call_once


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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.0;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

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

#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.15;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

Revert 191028 "[Sync] Disable unrecoverable error uploading."

Reverted on ToT (patch was merged to 27 branch)

> [Sync] Disable unrecoverable error uploading.
>
> Disabling for 27 branch.
>
> BUG=134607
> TBR=rlarocque@chromium.org
>
> Review URL: https://codereview.chromium.org/12770030

TBR=zea@chromium.org
Review URL: https://codereview.chromium.org/12710014

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


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

#include <string>

#if defined(OS_CHROMEOS)
#include "base/basictypes.h"
#include "base/string_util.h"
#endif

namespace l10n_util {

// Return true blindly for now.
bool IsLocaleSupportedByOS(const std::string& locale) {
#if !defined(OS_CHROMEOS)
  return true;
#else
  // We don't have translations yet for am, fa and sw.
  // We don't have fonts for te and kn, yet.
  // TODO(jungshik): Once the above issues are resolved, change this back
  // to return true.
  static const char* kUnsupportedLocales[] = {"am", "fa", "kn", "sw", "te"};
  for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) {
    if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i]))
      return false;
  }
  return true;
#endif
}

}  // namespace l10n_util

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

#include <string>

#if defined(OS_CHROMEOS)
#include "base/basictypes.h"
#include "base/string_util.h"
#endif

namespace l10n_util {

// Return true blindly for now.
bool IsLocaleSupportedByOS(const std::string& locale) {
#if !defined(OS_CHROMEOS)
  return true;
#else
  // We don't have translations yet for am, and sw.
  // TODO(jungshik): Once the above issues are resolved, change this back
  // to return true.
  static const char* kUnsupportedLocales[] = {"am", "sw"};
  for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) {
    if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i]))
      return false;
  }
  return true;
#endif
}

}  // namespace l10n_util

Enable Kannada, Farsi and Telugu on CrOS

BUG=chromium-os:21717
TEST=On login screen, Kannada, Telugu and Farsi can be selected.
Review URL: http://codereview.chromium.org/8301012

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


#include "OptionsManager.h"

#include <fstream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"

OptionsManager::OptionsManager(std::string optionsFilename)
{
    loadOptions(optionsFilename);
}

void OptionsManager::loadOptions(std::string optionsFilename)
{
    std::ifstream ifs(optionsFilename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
                    std::istreambuf_iterator<char>()};

    mOptions = spotify::json::decode<Options>(str.c_str());
    mOptions.filename = optionsFilename;

    createOutputDirectory(optionsFilename);
}

void OptionsManager::createOutputDirectory(std::string optionsFilename)
{
    // TODO(hryniuk): move it elsewhere
    auto outputDirectory = mOptions.outputDirectory;
    boost::filesystem::path p(optionsFilename);
    p.remove_filename();
    p.append(outputDirectory);
    boost::filesystem::create_directories(p);
    auto relativeOutputDirectory = p.string();
    mOptions.relativeOutputDirectory = relativeOutputDirectory;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

#include "OptionsManager.h"

#include <fstream>
#include <iostream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"

OptionsManager::OptionsManager(std::string optionsFilename)
{
    loadOptions(optionsFilename);
}

void OptionsManager::loadOptions(std::string optionsFilename)
{
    std::ifstream ifs(optionsFilename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
                    std::istreambuf_iterator<char>()};
    try
    {
        mOptions = spotify::json::decode<Options>(str.c_str());
    }
    catch (spotify::json::decode_exception e)
    {
        std::cout << "spotify::json::decode_exception encountered at "
            << e.offset()
            << ": "
            << e.what();
        throw;
    }
    mOptions.filename = optionsFilename;

    createOutputDirectory(optionsFilename);
}

void OptionsManager::createOutputDirectory(std::string optionsFilename)
{
    // TODO(hryniuk): move it elsewhere
    auto outputDirectory = mOptions.outputDirectory;
    boost::filesystem::path p(optionsFilename);
    p.remove_filename();
    p.append(outputDirectory);
    boost::filesystem::create_directories(p);
    auto relativeOutputDirectory = p.string();
    mOptions.relativeOutputDirectory = relativeOutputDirectory;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

Print exception details on decode failure


#include "SkinManager.h"

#include "Skin.h"

SkinManager *SkinManager::instance;

SkinManager *SkinManager::Instance() {
    if (instance == NULL) {
        instance = new SkinManager();
    }
    return instance;
}

SkinManager::~SkinManager() {
    delete _skin;
}

void SkinManager::LoadSkin(std::wstring skinXML) {
    delete _skin;
    _skin = new Skin(skinXML);
}

Skin *SkinManager::CurrentSkin() {
    return _skin;
}

#include "SkinManager.h"

#include "Skin.h"
#include "SkinV3.h"

SkinManager *SkinManager::instance;

SkinManager *SkinManager::Instance() {
    if (instance == NULL) {
        instance = new SkinManager();
    }
    return instance;
}

SkinManager::~SkinManager() {
    delete _skin;
}

void SkinManager::LoadSkin(std::wstring skinXML) {
    delete _skin;
    _skin = new SkinV3(skinXML);
}

Skin *SkinManager::CurrentSkin() {
    return _skin;
}

Load a v3 skin for now

Load a v3 skin for now


// Test that verifies TSan runtime doesn't contain compiler-emitted
// memcpy/memmove calls. It builds the binary with TSan and passes it to
// check_memcpy.sh script.

// RUN: %clangxx_tsan -O1 %s -o %t
// RUN: llvm-objdump -d %t | FileCheck %s

int main() {
  return 0;
}

// CHECK-NOT: callq {{.*<(__interceptor_)?mem(cpy|set)>}}
// tail calls:
// CHECK-NOT: jmpq {{.*<(__interceptor_)?mem(cpy|set)>}}

// Test that verifies TSan runtime doesn't contain compiler-emitted
// memcpy/memmove calls. It builds the binary with TSan and passes it to
// check_memcpy.sh script.

// RUN: %clangxx_tsan -O1 %s -o %t
// RUN: llvm-objdump -d %t | FileCheck %s

// REQUIRES: compiler-rt-optimized

int main() {
  return 0;
}

// CHECK-NOT: callq {{.*<(__interceptor_)?mem(cpy|set)>}}
// tail calls:
// CHECK-NOT: jmpq {{.*<(__interceptor_)?mem(cpy|set)>}}

Disable test with debug runtime

[tsan] Disable test with debug runtime

Test expects at least -O1 compiled runtime.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@308121 91177308-0d34-0410-b5e6-96231b3b80d8


#include "JSON.h"
#include <string>

namespace ouroboros
{
	JSON::JSON()
	:mpArr(nullptr)
	{}

	JSON::JSON(const std::string& aJSON)
	:mpArr(parse_json2(aJSON.c_str(), aJSON.length()))
	{}

	JSON::~JSON()
	{
		free(mpArr);
	}

	bool JSON::exists(const std::string& aPath) const
	{
		if (mpArr)
		{
			const json_token * ptr = find_json_token(mpArr, aPath.c_str());
			if (ptr)
			{
				return true;
			}
		}
		return false;
	}

	std::string JSON::get(const std::string& aPath) const
	{
		if (mpArr)
		{
			const json_token * ptr = find_json_token(mpArr, aPath.c_str());
			if (ptr)
			{
				return std::string(ptr->ptr, ptr->len);
			}
		}
		return std::string();
	}

	bool JSON::empty() const
	{
		return (!mpArr);
	}

}

#include "JSON.h"
#include <string>
#include <cstdlib>

namespace ouroboros
{
	JSON::JSON()
	:mpArr(nullptr)
	{}

	JSON::JSON(const std::string& aJSON)
	:mpArr(parse_json2(aJSON.c_str(), aJSON.length()))
	{}

	JSON::~JSON()
	{
		free(mpArr);
	}

	bool JSON::exists(const std::string& aPath) const
	{
		if (mpArr)
		{
			const json_token * ptr = find_json_token(mpArr, aPath.c_str());
			if (ptr)
			{
				return true;
			}
		}
		return false;
	}

	std::string JSON::get(const std::string& aPath) const
	{
		if (mpArr)
		{
			const json_token * ptr = find_json_token(mpArr, aPath.c_str());
			if (ptr)
			{
				return std::string(ptr->ptr, ptr->len);
			}
		}
		return std::string();
	}

	bool JSON::empty() const
	{
		return (!mpArr);
	}

}

Add cstdlib so that the code compiles on OSX


#include <string>
#include <ccspec/core/hooks.h>
#include <ccspec/core/example_group.h>

namespace ccspec {
namespace core {

void before(std::string entity, Hook hook) {
    ExampleGroup* parent_group = groups_being_defined.top();
    if (entity == "each")
        parent_group->addBeforeEachHook(hook);
    else
        throw "no such before hook type";
}

} // namespace core
} // namespace ccspec

#include <string>
#include <ccspec/core/hooks.h>
#include <ccspec/core/example_group.h>

namespace ccspec {
namespace core {

void before(std::string entity, Hook hook) {
    ExampleGroup* parent_group = groups_being_defined.top();
    if (entity == "each" || entity == "example")
        parent_group->addBeforeEachHook(hook);
    else
        throw "no such before hook type";
}

} // namespace core
} // namespace ccspec

Add "each" alias that's new in RSpec 3

Add "each" alias that's new in RSpec 3


#include <client/client.h>
#include <server/server.h>

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

int main(int argc, char **argv)
{
  int separator;
  char** compile_argv;

  separator = 0;
  for (int i = 1; i < argc; ++i) {
    if (strcmp(argv[i], "--") == 0) {
      separator = i;
      break;
    }
  }

  compile_argv = argv + separator;
  compile_argv[0] = separator >= 2 ? argv[separator - 1] : (char*) "clang";

  /* Start the server and send the compile command. */
  if (!clc::server::is_running())
    clc::server::start();

  /* Run the compiler and print error message if execvp returns. */
  execvp(compile_argv[0], compile_argv);
  err(EXIT_FAILURE, "%s", compile_argv[0]);
}

#include <client/client.h>
#include <server/server.h>

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

int main(int argc, char **argv)
{
  int separator;
  char** compile_argv;

  separator = 0;
  for (int i = 1; i < argc; ++i) {
    if (strcmp(argv[i], "--") == 0) {
      separator = i;
      break;
    } else if (strcmp(argv[i], "--start") == 0) {
      clc::server::start();
      return EXIT_SUCCESS;
    } else if (strcmp(argv[i], "--stop") == 0) {
      clc::server::stop();
      return EXIT_SUCCESS;
    }
  }

  compile_argv = argv + separator;
  compile_argv[0] = separator >= 2 ? argv[separator - 1] : (char*) "clang";

  /* Start the server and send the compile command. */
  if (!clc::server::is_running())
    clc::server::start();

  /* Run the compiler and print error message if execvp returns. */
  execvp(compile_argv[0], compile_argv);
  err(EXIT_FAILURE, "%s", compile_argv[0]);
}

Add --start and --stop commands to manage the server.


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

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

// <utility>

// template <class T1, class T2> struct pair

// constexpr pair();

#include <utility>
#include <type_traits>

#include "archetypes.hpp"

int main() {
    using NonThrowingDefault = NonThrowingTypes::DefaultOnly;
    using ThrowingDefault = NonTrivialTypes::DefaultOnly;
    static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, ThrowingDefault>>::value, "");
    static_assert(!std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, ThrowingDefault>>::value, "");
    static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, NonThrowingDefault>>::value, "");
    static_assert( std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, NonThrowingDefault>>::value, "");
}

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

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

// <utility>

// template <class T1, class T2> struct pair

// constexpr pair();

#include <utility>
#include <type_traits>

struct ThrowingDefault {
  ThrowingDefault() { }
};

struct NonThrowingDefault {
  NonThrowingDefault() noexcept { }
};

int main() {

    static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, ThrowingDefault>>::value, "");
    static_assert(!std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, ThrowingDefault>>::value, "");
    static_assert(!std::is_nothrow_default_constructible<std::pair<ThrowingDefault, NonThrowingDefault>>::value, "");
    static_assert( std::is_nothrow_default_constructible<std::pair<NonThrowingDefault, NonThrowingDefault>>::value, "");
}

Fix test failure on GCC 4.9

[libcxx] Fix test failure on GCC 4.9

GCC 4.9 seems to think that a constexpr default constructor implies
the constructor to be noexcept.

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@348850 91177308-0d34-0410-b5e6-96231b3b80d8


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

template<typename T>
struct X1 {
  friend void f6(int) { } // expected-error{{redefinition of}} \
                          // expected-note{{previous definition}}
};

X1<int> x1a;
X1<float> x1b; // expected-note {{in instantiation of}}

template<typename T>
struct X2 {
  operator int();

  friend void f(int x) { } // expected-error{{redefinition}} \
                           // expected-note{{previous definition}}
};

int array0[sizeof(X2<int>)];
int array1[sizeof(X2<float>)]; // expected-note{{instantiation of}}

void g() {
  X2<int> xi;
  f(xi);
  X2<float> xf;
  f(xf);
}

Add test case from PR6952, which now works (thanks to Gabor).

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


#include <iostream>

using namespace std;

class Greeting {
    protected:
        string s;
    public:
        Greeting(){
            s = "Hello, ";
        }
        virtual ~Greeting() { }
        virtual void printGreeting() = 0;
};

class GitHubGreeting : public Greeting {
    public:
        GitHubGreeting() {
            s += "GitHub!";
            printGreeting();
        }
        GitHubGreeting(GitHubGreeting & h) { }
        GitHubGreeting(GitHubGreeting * h) { }
        virtual ~GitHubGreeting() { }
        void operator=(GitHubGreeting & h) { }
        void printGreeting() {
            cout << s << endl;
        }
};

int main() {
    GitHubGreeting h;
    return 0;
}

#include <iostream>

using namespace std;

class Greeting {
    protected:
        string s;
    public:
        Greeting(){
            s = "Hello, ";
        }
        virtual ~Greeting() { }
        virtual void printGreeting() = 0;
};

class GitHubGreeting : public Greeting {
    public:
        GitHubGreeting() {
            s += "GitHub!";
            printGreeting();
        }
        GitHubGreeting(GitHubGreeting & h) { GitHubGreeting(); }
        GitHubGreeting(GitHubGreeting * h) { GitHubGreeting(); }
        virtual ~GitHubGreeting() { }
        void operator=(GitHubGreeting & h) { }
        void printGreeting() {
            cout << s << endl;
        }
};

int main() {
    GitHubGreeting h;
    return 0;
}

Fix the copy constructors to call the base constructor


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

#include "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h"

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_service.h"

namespace {

// Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm
// command line: http://goo.gl/uLwIL
const char kInitialWindowFile[] =
    "/var/run/state/windowmanager/initial-chrome-window-mapped";

}  // namespace

namespace chromeos {

InitialBrowserWindowObserver::InitialBrowserWindowObserver() {
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
                 content::NotificationService::AllSources());
}

void InitialBrowserWindowObserver::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  registrar_.RemoveAll();
  file_util::WriteFile(FilePath(kInitialWindowFile), "", 0);
}

}  // namespace chromeos

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

#include "chrome/browser/chromeos/legacy_window_manager/initial_browser_window_observer.h"

#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"

namespace {

// Taken from the --initial_chrome_window_mapped_file flag in the chromeos-wm
// command line: http://goo.gl/uLwIL
const char kInitialWindowFile[] =
    "/var/run/state/windowmanager/initial-chrome-window-mapped";

void WriteInitialWindowFile() {
  if (file_util::WriteFile(FilePath(kInitialWindowFile), "", 0) == -1)
    LOG(ERROR) << "Failed to touch " << kInitialWindowFile;
}

}  // namespace

namespace chromeos {

InitialBrowserWindowObserver::InitialBrowserWindowObserver() {
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_WINDOW_READY,
                 content::NotificationService::AllSources());
}

void InitialBrowserWindowObserver::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  registrar_.RemoveAll();
  content::BrowserThread::PostTask(
      content::BrowserThread::IO, FROM_HERE,
      base::Bind(&WriteInitialWindowFile));
}

}  // namespace chromeos

aura: Write initial browser window file from IO thread.

I was carelessly doing this from the UI thread before. :-(

BUG=107938
TEST=none

Review URL: http://codereview.chromium.org/8993012

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


#include "gtest/gtest.h"
#include "Models/GaussianModel.hpp"

#include "test_utils/test_utils.hpp"
#include <fstream>

namespace {
  using namespace BOOM;
  using std::endl;
  using std::cout;

  class ParamPolicy2Test : public ::testing::Test {
   protected:
    ParamPolicy2Test() {
      GlobalRng::rng.seed(8675309);
    }
  };

  TEST_F(ParamPolicy2Test, ParamVectorTest) {
    GaussianModel model1(1.2, 3.7);
    EXPECT_EQ(2, model1.parameter_vector().size());
    model1.disable_parameter_1();

    model1.set_mu(0.1);
    EXPECT_DOUBLE_EQ(0.1, model1.mu());
    EXPECT_DOUBLE_EQ(2.7, model1.sigma());

    EXPECT_EQ(1, model1.parameter_vector().size());

  }

}  // namespace

#include "gtest/gtest.h"
#include "Models/GaussianModel.hpp"

#include "test_utils/test_utils.hpp"
#include <fstream>

namespace {
  using namespace BOOM;
  using std::endl;
  using std::cout;

  class ParamPolicy2Test : public ::testing::Test {
   protected:
    ParamPolicy2Test() {
      GlobalRng::rng.seed(8675309);
    }
  };

  TEST_F(ParamPolicy2Test, ParamVectorTest) {
    GaussianModel model1(1.2, 3.7);
    EXPECT_EQ(2, model1.parameter_vector().size());

    // Fix the mean at its current value.
    model1.disable_parameter_1();

    model1.set_mu(0.1);
    EXPECT_DOUBLE_EQ(0.1, model1.mu());
    EXPECT_DOUBLE_EQ(3.7, model1.sigma());

    EXPECT_EQ(1, model1.parameter_vector().size());
    Vector params = model1.vectorize_params();
    EXPECT_EQ(1, params.size());
    EXPECT_DOUBLE_EQ(square(3.7), params[0]);
  }

}  // namespace

Fix a typo in a test case for ParamPolicy2.


#pragma once

#include <glkernel/Kernel.h>

#include <glm/vec2.hpp>

#include <glkernel/Kernel.h>

#include <glkernel/uniform_noise.h>
#include <glkernel/normal_noise.h>
#include <glkernel/square_points.hpp>

namespace glkernel
{

void test()
{
    { auto noise = glkernel::Kernel<float>();      }
    { auto noise = glkernel::Kernel<double>();     }

    { auto noise = glkernel::Kernel<glm::vec2>();  }
    { auto noise = glkernel::Kernel<glm::dvec2>(); }

    { auto noise = glkernel::Kernel<glm::vec3>();  }
    { auto noise = glkernel::Kernel<glm::dvec3>(); }

    { auto noise = glkernel::Kernel<glm::vec4>();  }
    { auto noise = glkernel::Kernel<glm::dvec4>(); }
}

} // namespace glkernel

Remove pragma once from cpp file

Remove pragma once from cpp file


#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include "OpenniLaserScanner.h"

class MyMwListener : public OpenniLaser::OpenniLaserScanner::Listener
{
public:
	sensor_msgs::LaserScan scan;
	void readyForNextData(OpenniLaser::OpenniLaserScanner* scanner)
	{
		openni::VideoFrameRef frame;
		scan = scanner->getNextData(frame);
	}
};

int main(int argc, char **argv)
{
	 ros::init(argc, argv, "openni2_laserscan");

	  ros::NodeHandle n;
	  ros::Publisher scan_pub = n.advertise<sensor_msgs::LaserScan>("openni2_laserscan", 50);

	  int count = 0;
	  ros::Rate r(1.0);

		OpenniLaser::OpenniLaserScanner laserScanner;

		if (!laserScanner.isValid())
		{
			printf("openni_laserscan: error in initialization\n");
			return 1;
		}
		printf("openni_laserscan: running\n");

		MyMwListener myListener;

		laserScanner.setListener(myListener);

	  while(n.ok()){
	    scan_pub.publish(myListener.scan);
	    ++count;
	    r.sleep();
	  }

	  laserScanner.resetListener();
	  printf("openni_laserscan: stopped\n");
	  return 0;
}

#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include "OpenniLaserScanner.h"

class MyMwListener : public OpenniLaser::OpenniLaserScanner::Listener
{
public:
	sensor_msgs::LaserScan scan;
	void readyForNextData(OpenniLaser::OpenniLaserScanner* scanner)
	{
		openni::VideoFrameRef frame;
		scan = scanner->getNextData(frame);
	}
};

int main(int argc, char **argv)
{
	 ros::init(argc, argv, "openni2_laserscan");

	  ros::NodeHandle n;
	  ros::Publisher scan_pub = n.advertise<sensor_msgs::LaserScan>("openni2_laserscan", 50);

	  int count = 0;
	  ros::Rate r(30.0);

		OpenniLaser::OpenniLaserScanner laserScanner;

		if (!laserScanner.isValid())
		{
			printf("openni_laserscan: error in initialization\n");
			return 1;
		}
		printf("openni_laserscan: running\n");

		MyMwListener myListener;

		laserScanner.setListener(myListener);

	  while(n.ok()){
	    scan_pub.publish(myListener.scan);
	    ++count;
	    r.sleep();
	  }

	  laserScanner.resetListener();
	  printf("openni_laserscan: stopped\n");
	  return 0;
}

Set publishing fequenzy from 1 to 30 hz

Set publishing fequenzy from 1 to 30 hz


#include "stdafx.h"
#include "AutowiringTest.h"
#include "Autowired.h"
#include "TestFixtures/SimpleObject.h"
#include "TestFixtures/SimpleReceiver.h"

TEST_F(AutowiringTest, VerifyAutowiredFast) {
  // Add an object:
  m_create->Inject<SimpleObject>();

  // Verify that AutowiredFast can find this object
  AutowiredFast<SimpleObject> sobj;
  ASSERT_TRUE(sobj.IsAutowired()) << "Failed to autowire an object which was just injected into a context";
}

TEST_F(AutowiringTest, VerifyAutowiredFastNontrivial) {
  // This will cause a cache entry to be inserted into the CoreContext's memoization system.
  // If there is any improper or incorrect invalidation in that system, then the null entry
  // will create problems when we attempt to perform an AutowiredFast later on.
  AutowiredFast<CallableInterface>();

  // Now we add the object
  AutoRequired<SimpleReceiver>();

  // Verify that AutowiredFast can find this object from its interface
  Autowired<CallableInterface> ci;
  ASSERT_TRUE(ci.IsAutowired()) << "Failed to autowire an interface advertised by a newly-inserted object";
}

#include "stdafx.h"
#include "AutowiringTest.h"
#include "Autowired.h"
#include "TestFixtures/SimpleObject.h"
#include "TestFixtures/SimpleReceiver.h"

TEST_F(AutowiringTest, VerifyAutowiredFast) {
  // Add an object:
  m_create->Inject<SimpleObject>();

  // Verify that AutowiredFast can find this object
  AutowiredFast<SimpleObject> sobj;
  ASSERT_TRUE(sobj.IsAutowired()) << "Failed to autowire an object which was just injected into a context";
}

TEST_F(AutowiringTest, VerifyAutowiredFastNontrivial) {
  // This will cause a cache entry to be inserted into the CoreContext's memoization system.
  // If there is any improper or incorrect invalidation in that system, then the null entry
  // will create problems when we attempt to perform an AutowiredFast later on.
  AutowiredFast<CallableInterface>();

  // Now we add the object
  AutoRequired<SimpleReceiver>();

  // Verify that AutowiredFast can find this object from its interface
  AutowiredFast<CallableInterface> ci;
  ASSERT_TRUE(ci.IsAutowired()) << "Failed to autowire an interface advertised by a newly-inserted object";
}

Revert "Fixed incorrect autowiring test."

This reverts commit 1938e906243ae1f789e33cadcbd97bddd565592c.


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

#include "net/base/network_change_notifier_helper.h"
#include <algorithm>
#include "base/logging.h"

namespace net {

namespace internal {

NetworkChangeNotifierHelper::NetworkChangeNotifierHelper()
    : is_notifying_observers_(false) {}

NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() {
  DCHECK(observers_.empty());
}

void NetworkChangeNotifierHelper::AddObserver(Observer* observer) {
  DCHECK(!is_notifying_observers_);
  observers_.push_back(observer);
}

void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) {
  DCHECK(!is_notifying_observers_);
  observers_.erase(std::remove(observers_.begin(), observers_.end(), observer));
}

void NetworkChangeNotifierHelper::OnIPAddressChanged() {
  DCHECK(!is_notifying_observers_);
  is_notifying_observers_ = true;
  for (std::vector<Observer*>::iterator it = observers_.begin();
       it != observers_.end(); ++it) {
    (*it)->OnIPAddressChanged();
  }
  is_notifying_observers_ = false;
}

}  // namespace internal

}  // namespace net

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

#include "net/base/network_change_notifier_helper.h"
#include <algorithm>
#include "base/logging.h"

namespace net {

namespace internal {

NetworkChangeNotifierHelper::NetworkChangeNotifierHelper()
    : is_notifying_observers_(false) {}

NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() {
  // TODO(willchan): Re-enable this DCHECK after fixing http://crbug.com/34391
  // since we're leaking URLRequestContextGetters that cause this DCHECK to
  // fire.
  // DCHECK(observers_.empty());
}

void NetworkChangeNotifierHelper::AddObserver(Observer* observer) {
  DCHECK(!is_notifying_observers_);
  observers_.push_back(observer);
}

void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) {
  DCHECK(!is_notifying_observers_);
  observers_.erase(std::remove(observers_.begin(), observers_.end(), observer));
}

void NetworkChangeNotifierHelper::OnIPAddressChanged() {
  DCHECK(!is_notifying_observers_);
  is_notifying_observers_ = true;
  for (std::vector<Observer*>::iterator it = observers_.begin();
       it != observers_.end(); ++it) {
    (*it)->OnIPAddressChanged();
  }
  is_notifying_observers_ = false;
}

}  // namespace internal

}  // namespace net

Disable DCHECK'ing that all NetworkChangeNotifiers are removed.
BUG=34391

Review URL: http://codereview.chromium.org/560026

git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@37982 4ff67af0-8c30-449e-8e8b-ad334ec8d88c


/*
 * Rectangular Window Function Unit for Jamoma DSP
 * Copyright © 2009 by Trond Lossius
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTRectangularWindow.h"

#define thisTTClass RectangularWindow
#define thisTTClassName		"rectangular"
#define thisTTClassTags		"audio, processor, function, window"

TT_AUDIO_CONSTRUCTOR
{
	setProcessMethod(processAudio);
	setCalculateMethod(calculateValue);
}

RectangularWindow::~RectangularWindow()
{
	;
}

TTErr RectangularWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	if ((x>0) && (x<1.0))
		y = 1.0;
	else
		y = 0.0;

	return kTTErrNone;
}

TTErr RectangularWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(calculateValue);
}

/*
 * Rectangular Window Function Unit for Jamoma DSP
 * Copyright © 2009 by Trond Lossius
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTRectangularWindow.h"

#define thisTTClass RectangularWindow
#define thisTTClassName		"rectangular"
#define thisTTClassTags		"audio, processor, function, window"

TT_AUDIO_CONSTRUCTOR
{
	setProcessMethod(processAudio);
	setCalculateMethod(calculateValue);
}

RectangularWindow::~RectangularWindow()
{
	;
}

TTErr RectangularWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	y = 1.0;
	return kTTErrNone;
}

TTErr RectangularWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(calculateValue);
}

Revert "Fixing a bug with rectangular window that would prevent it from being 0 at the end points"

This reverts commit bfc5a0e6166c8d601378bfbb66bd1ea66fe30a3a.


// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <bcm_host.h>
#include "WindowResourceRasp.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    WindowResourceRasp::WindowResourceRasp()
    {
        bcm_host_init();
    }

    WindowResourceRasp::~WindowResourceRasp()
    {
        bcm_host_deinit();
    }

    bool WindowResourceRasp::init(const Size2& newSize,
                                  bool newResizable,
                                  bool newFullscreen,
                                  bool newExclusiveFullscreen,
                                  const std::string& newTitle,
                                  bool newHighDpi,
                                  bool depth)
    {
        if (!WindowResource::init(newSize,
                                  newResizable,
                                  newFullscreen,
                                  newExclusiveFullscreen,
                                  newTitle,
                                  newHighDpi,
                                  depth))
        {
            return false;
        }

        uint32_t screenWidth;
        uint32_t screenHeight;
        int32_t success = graphics_get_display_size(0, &screenWidth, &screenHeight);

        if (success < 0)
        {
            Log(Log::Level::ERR) << "Failed to get display size";
            return false;
        }

        size.width = static_cast<float>(screenWidth);
        size.height = static_cast<float>(screenHeight);
        resolution = size;

        return true;
    }
}

// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <bcm_host.h>
#include "WindowResourceRasp.hpp"
#include "utils/Log.hpp"

namespace ouzel
{
    WindowResourceRasp::WindowResourceRasp()
    {
        bcm_host_init();
    }

    WindowResourceRasp::~WindowResourceRasp()
    {
        bcm_host_deinit();
    }

    bool WindowResourceRasp::init(const Size2& newSize,
                                  bool newResizable,
                                  bool newFullscreen,
                                  bool newExclusiveFullscreen,
                                  const std::string& newTitle,
                                  bool newHighDpi,
                                  bool depth)
    {
        if (!WindowResource::init(newSize,
                                  newResizable,
                                  newFullscreen,
                                  newExclusiveFullscreen,
                                  newTitle,
                                  newHighDpi,
                                  depth))
        {
            return false;
        }

        DISPMANX_DISPLAY_HANDLE_T display = vc_dispmanx_display_open(0);
        if (!display)
        {
            Log(Log::Level::ERR) << "Failed to open display";
            return false;
        }

        DISPMANX_MODEINFO_T modeInfo;
        int32_t success = vc_dispmanx_display_get_info(display, &modeInfo);

        if (success < 0)
        {
            Log(Log::Level::ERR) << "Failed to get display size";
            vc_dispmanx_display_close(display);
            return false;
        }

        size.width = static_cast<float>(modeInfo.width);
        size.height = static_cast<float>(modeInfo.height);
        resolution = size;

        vc_dispmanx_display_close(display);

        return true;
    }
}

Use vc_ functions to get display size

Use vc_ functions to get display size


#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.id = msg->id;
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    const auto& now_pos = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.angle = std::move(now_pos);
    result.id = msg->id;
    pub.publish(std::move(result));
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Add std::move to all local value

Add std::move to all local value


/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <memory>
#include <gflags/gflags.h>

#include <thrift/lib/cpp2/server/ThriftServer.h>

#include "treadmill/services/sleep/sleepserver/SleepHandler.h"

using namespace apache::thrift;
using namespace apache::thrift::async;

using namespace facebook::windtunnel::treadmill::services::sleep;

DEFINE_int32(port,
             12345,
             "Port for sleep service (default: 12345).");

DEFINE_int32(num_workers,
             4,
             "Number of workers (default: 4).");

int main(int argc, char* argv[]) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  auto handler = std::make_shared<SleepHandler>();
  auto server = folly::make_unique<ThriftServer>();
  server->setPort(FLAGS_port);
  server->setNWorkerThreads(FLAGS_num_workers);
  server->setInterface(std::move(handler));

  server->serve();

  return 0;
}

/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <memory>
#include <gflags/gflags.h>

#include <thrift/lib/cpp2/server/ThriftServer.h>

#include "treadmill/services/sleep/sleepserver/SleepHandler.h"

using namespace apache::thrift;
using namespace apache::thrift::async;

using namespace facebook::windtunnel::treadmill::services::sleep;

DEFINE_int32(port,
             12345,
             "Port for sleep service (default: 12345).");

DEFINE_int32(num_workers,
             4,
             "Number of workers (default: 4).");

int main(int argc, char* argv[]) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  auto handler = std::make_shared<SleepHandler>();
  auto server = folly::make_unique<ThriftServer>();
  server->setPort(FLAGS_port);
  server->setNumIOWorkerThreads(FLAGS_num_workers);
  server->setInterface(std::move(handler));

  server->serve();

  return 0;
}

Rename thrift methods from NWorker/NPoolThreads to NumIOWorker/NumCPUWorkerThreads for all remaining directories

Summary:
Use new, less confusing names for mentioned thrift methods.

Codemod with 'Yes to All'. Reverted changes in thrift/

Reviewed By: yfeldblum

Differential Revision: D4076812

fbshipit-source-id: 4962ec0aead1f6a45efc1ac7fc2778f39c72e1d0


#include "square.h"
#include <gtest/gtest.h>

TEST(TestSuite, squareTwo)
{
  const double ret = square(2);
  ASSERT_EQ(5, ret);
}

TEST(TestSuite, squareFour)
{
  const double ret = square(4.1);
  ASSERT_EQ(16.81, ret);
}

// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

#include "square.h"
#include <gtest/gtest.h>

TEST(TestSuite, squareTwo)
{
  const double ret = square(2);
  ASSERT_EQ(4, ret);
}

TEST(TestSuite, squareFour)
{
  const double ret = square(4.1);
  ASSERT_EQ(16.81, ret);
}

// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Revert "Make sure failed tests actually fail."

This reverts commit de0b36b9bdd42abfa1f5b05db1e814f0e278e919.


#include "../test.h"
#include <QUrl>
#include "../../src/input/scxml_importer.h"

TEST(Test_ScxmlImporter, foo)
{
  ScxmlImporter importer(QUrl::fromLocalFile("../config/simple_state.xml"));
}

#include "../test.h"
#include <QUrl>
#include <QStateMachine>
#include <QGuiApplication>
#include <QWindow>
#include <QKeyEvent>
#include <thread>
#include <chrono>
#include "../../src/input/scxml_importer.h"

TEST(Test_ScxmlImporter, foo)
{
  int zero = 0;
  QGuiApplication application(zero, static_cast<char **>(nullptr));
  QWindow window;

  ScxmlImporter importer(QUrl::fromLocalFile("../config/simple_state.xml"),
                         &window);
  auto stateMachine = importer.getStateMachine();
  std::cout << "running:" << stateMachine->isRunning() << std::endl;

  stateMachine->start();

  window.show();

  std::cout << "running:" << stateMachine->isRunning() << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(500));

  std::cout << "error:" << stateMachine->errorString().toStdString() << std::endl;
  std::cout << "running:" << stateMachine->isRunning() << std::endl;

  stateMachine->postEvent(
      new QKeyEvent(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier));

  application.exec();
}

Test for now starts an application.

Test for now starts an application.


/**
 * Copyright (c) 2016-present, Facebook, 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 "aten_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(ATen, ATenOp<CPUContext>);
template<>
at::Backend ATenOp<CPUContext>::backend() const {
  return at::kCPU;
}

OPERATOR_SCHEMA(ATen);
CAFFE_KNOWN_TYPE(at::Half);

namespace math {
template<>
void Set<at::Half,CPUContext>(TIndex N, at::Half h, at::Half* v, CPUContext * c) {
  Set(0, h.x, (uint16_t*) v, c);
}
}

}

/**
 * Copyright (c) 2016-present, Facebook, 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 "aten_op.h"

namespace caffe2 {

REGISTER_CPU_OPERATOR(ATen, ATenOp<CPUContext>);
template<>
at::Backend ATenOp<CPUContext>::backend() const {
  return at::kCPU;
}

OPERATOR_SCHEMA(ATen);
CAFFE_KNOWN_TYPE(at::Half);

namespace math {
template<>
void Set<at::Half,CPUContext>(const size_t N, const at::Half h, at::Half* v, CPUContext * c) {
  Set(0, h.x, (uint16_t*) v, c);
}
}

}

Fix function signature in ATenOp for at::Half Set function

Summary:
https://github.com/caffe2/caffe2/commit/c777be07d97c556d0acb7b5e15c5f16f4914dcf0 changed the type signature for the Set function, this fixes it for the ATenOp
Closes https://github.com/caffe2/caffe2/pull/1464

Reviewed By: zdevito

Differential Revision: D6317561

Pulled By: jamesr66a

fbshipit-source-id: e54d553f44ccf0d5fc695e14dc671dde77004b54


#include "qmimedatabase.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QFile>

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

    if (argc <= 1) {
        printf( "No filename specified\n" );
        return 1;
    }
    const QString fileName = QFile::decodeName(argv[1]);
    //int accuracy;
    QMimeDatabase db;
    QMimeType mime;
    if (fileName == QLatin1String("-")) {
        QFile qstdin;
        qstdin.open(stdin, QIODevice::ReadOnly);
        const QByteArray data = qstdin.readAll();
        //mime = QMimeType::findByContent(data, &accuracy);
        mime = db.findByData(data);
    //} else if (args->isSet("c")) {
        //mime = QMimeType::findByFileContent(fileName, &accuracy);
    } else {
        //mime = QMimeType::findByPath(fileName, 0, args->isSet("f"), &accuracy);
        mime = db.findByFile(fileName);
    }
    if ( mime.isValid() /*&& !mime.isDefault()*/ ) {
        printf("%s\n", mime.name().toLatin1().constData());
        //printf("(accuracy %d)\n", accuracy);
    } else {
        return 1; // error
    }

    return 0;
}

#include "qmimedatabase.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QFile>

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

    if (argc <= 1) {
        printf( "No filename specified\n" );
        return 1;
    }
    QString option;
    int fnPos = 1;
    if (argc > 2) {
        option = QString::fromLatin1(argv[1]);
        ++fnPos;
    }
    const QString fileName = QFile::decodeName(argv[fnPos]);
    //int accuracy;
    QMimeDatabase db;
    QMimeType mime;
    if (fileName == QLatin1String("-")) {
        QFile qstdin;
        qstdin.open(stdin, QIODevice::ReadOnly);
        const QByteArray data = qstdin.readAll();
        //mime = QMimeType::findByContent(data, &accuracy);
        mime = db.findByData(data);
    } else if (option == "-c") {
        QFile file(fileName);
        if (file.open(QIODevice::ReadOnly)) {
            mime = db.findByData(file.read(32000));
        }
    } else {
        //mime = QMimeType::findByPath(fileName, 0, args->isSet("f"), &accuracy);
        mime = db.findByFile(fileName);
    }
    if ( mime.isValid() /*&& !mime.isDefault()*/ ) {
        printf("%s\n", mime.name().toLatin1().constData());
        //printf("(accuracy %d)\n", accuracy);
    } else {
        return 1; // error
    }

    return 0;
}

Add suport for mimetypefinder -c file (find by file contents)


#include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
#include <random>

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

using namespace std;

// Implementation of the One-Time Pad key generation

int main(int argc, char* argv[])
{
    if(argc < 2) {
        cout << "Usage: " << argv[0] << " len (key lenght in bytes)" << endl;
        return -1;
    }

    int len = atoi(argv[1]);
    if(len < 1)
    {
        cout << "Error in key size specification, must be > 1" << endl;
        return -1;
    }

    // Open random device:
    std::random_device rd2("/dev/random");
    std::uniform_int_distribution<> dis(0,255);
    for(unsigned int i = 0; i < len; ++i)
    {
        std::cout << hex << setw(2) << setfill('0') << dis(rd2);
    }
    std::cout << dec << endl;

    return 0;
}

#include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
#include <random>

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

using namespace std;

// Implementation of the One-Time Pad key generation

int main(int argc, char* argv[])
{
    if(argc < 2) {
        cout << "Usage: " << argv[0] << " len (key lenght in bytes)" << endl;
        return -1;
    }

    int len = atoi(argv[1]);
    if(len < 1)
    {
        cout << "Error in key size specification, must be > 1" << endl;
        return -1;
    }

    // Open random device:
    std::random_device rd("/dev/urandom");
    std::uniform_int_distribution<> dis(0,255);
    for(unsigned int i = 0; i < len; ++i)
    {
        std::cout << hex << setw(2) << setfill('0') << dis(rd);
    }
    std::cout << dec << endl;

    return 0;
}

Change to /dev/urandom, as /dev/random was just haning/very slow


#include "common.th"

_start:
  prologue

  c <- 67
  call(totient)

  illegal

// Computes the number of values less than C that are relatively prime to C.
// Stores the result in B.
totient:
  b <- 0
  d <- c

loop:
  k <- d == a
  jnzrel(k, done)

  pushall(b,c,d)

  call(gcd)

  k <- b <> 1
  k <- k + 1

  popall(b,c,d)

  b <- b + k

  d <- d - 1
  goto(loop)

done:
  ret

#include "common.th"

_start:
  prologue

  c <- 67
  call(totient)

  illegal

// Computes the number of values less than C that are relatively prime to C.
// Stores the result in B.
totient:
  b <- 0
  d <- c

loop:
  k <- d == a
  jnzrel(k, done)

  pushall(b,c,d)

  call(gcd)

  k <- b <> 1

  popall(b,c,d)

  b <- b + k + 1

  d <- d - 1
  goto(loop)

done:
  ret

Reduce instruction count of totient

Reduce instruction count of totient


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

// UNSUPPORTED: c++98, c++03
// REQUIRES: diagnose-if-support

// <unordered_set>

// Test that we generate a reasonable diagnostic when the specified hash is
// not enabled.

#include <unordered_set>
#include <utility>

using VT = std::pair<int, int>;
using Set = std::unordered_set<VT>;

int main() {

  Set s; // expected-error@__hash_table:* {{the specified hash functor does not meet the requirements for an enabled hash}}

  // FIXME: It would be great to suppress the below diagnostic all together.
  //        but for now it's sufficient that it appears last. However there is
  //        currently no way to test the order diagnostics are issued.
  // expected-error@memory:* {{call to implicitly-deleted default constructor of 'std::__1::hash<std::__1::pair<int, int> >'}}
}

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

// REQUIRES: diagnose-if-support
// UNSUPPORTED: c++98, c++03

// Libc++ only provides a defined primary template for std::hash in C++14 and
// newer.
// UNSUPPORTED: c++11

// <unordered_set>

// Test that we generate a reasonable diagnostic when the specified hash is
// not enabled.

#include <unordered_set>
#include <utility>

using VT = std::pair<int, int>;
using Set = std::unordered_set<VT>;

int main() {

  Set s; // expected-error@__hash_table:* {{the specified hash functor does not meet the requirements for an enabled hash}}

  // FIXME: It would be great to suppress the below diagnostic all together.
  //        but for now it's sufficient that it appears last. However there is
  //        currently no way to test the order diagnostics are issued.
  // expected-error@memory:* {{call to implicitly-deleted default constructor of 'std::__1::hash<std::__1::pair<int, int> >'}}
}

Mark test as unsupported in C++11

Mark test as unsupported in C++11

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@296571 91177308-0d34-0410-b5e6-96231b3b80d8


#include "SubstringWithConcatenationOfAllWords.hpp"

#include <unordered_map>
using namespace std;

vector<int> SubstringWithConcatenationOfAllWords::findSubstring(string s, vector<string>& words)
{
  vector<int> ret;
  size_t seglen = words[0].size();
  size_t nsegs = words.size();
  if (nsegs == 0 || s.size() == 0 || seglen == 0 || seglen * nsegs > s.size())
    return ret;

  unordered_map<string, int> records;
  for (auto w : words)
    records[w]++;

  int p = 0;
  while (p + seglen * nsegs - 1 < s.size()) {
    unordered_map<string, int> local = records;
    int i;
    for (i = 0; i < nsegs; i++) {
      string seg = s.substr(p + i * seglen, seglen);
      if (local.find(seg) == local.end() || local[seg] == 0)
        break;
      else
        local[seg]--;
    }
    if (i == nsegs)
      ret.push_back(p);
    p++;
  }

  return ret;
}

#include "SubstringWithConcatenationOfAllWords.hpp"

#include <unordered_map>
using namespace std;

vector<int> SubstringWithConcatenationOfAllWords::findSubstring(string s, vector<string>& words)
{
  vector<int> ret;
  size_t strlen = s.size();
  size_t numw = words.size();

  if (strlen == 0 || numw == 0) return ret;

  size_t wlen = words[0].size();
  size_t substrlen = numw * wlen;

  if (wlen == 0 || substrlen > strlen) return ret;

  unordered_map<string, int> records;
  for (auto w : words)
    records[w]++;

  for (int p = 0; p + substrlen - 1 < strlen; p++) {
    unordered_map<string, int> local = records;
    int q;
    for (q = 0; q < numw; q++) {
      string seg = s.substr(p + q * wlen, wlen);
      if (local.find(seg) == local.end() || local[seg] == 0)
        break;
      else
        local[seg]--;
    }
    if (q == numw)
      ret.push_back(p);
  }

  return ret;
}

Clean up Problem 30 solution

Clean up Problem 30 solution


#include <motor/multirotor_quad_x_motor_mapper.hpp>

#include <array>

MultirotorQuadXMotorMapper::MultirotorQuadXMotorMapper() {
}

void MultirotorQuadXMotorMapper::init() {
  PWMMotorMapper::init();
}

void MultirotorQuadXMotorMapper::run(actuator_setpoint_t& input) {
  // Calculate output shifts
  std::array<float, 4> output_shifts = {
     1.0f * input.pitch_sp + 1.0f * input.roll_sp + 1.0f * input.yaw_sp, // front left
    -1.0f * input.pitch_sp + 1.0f * input.roll_sp - 1.0f * input.yaw_sp, // front right
    -1.0f * input.pitch_sp - 1.0f * input.roll_sp + 1.0f * input.yaw_sp, // back right
     1.0f * input.pitch_sp - 1.0f * input.roll_sp - 1.0f * input.yaw_sp  // back left
  };

  // Add throttle to shifts to get absolute output value
  std::array<float, 4> outputs = { 0 };
  for(int i = 0; i < 4; i++) {
    outputs[i] = input.throttle_sp + output_shifts[i];
  }

  setMotorSpeeds(outputs);
}

#include <motor/multirotor_quad_x_motor_mapper.hpp>

#include <array>

MultirotorQuadXMotorMapper::MultirotorQuadXMotorMapper() {
}

void MultirotorQuadXMotorMapper::init() {
  PWMMotorMapper::init();
}

void MultirotorQuadXMotorMapper::run(actuator_setpoint_t& input) {
  // Calculate output shifts
  // TODO(yoos): comment on motor indexing convention starting from positive
  // X in counterclockwise order.
  std::array<float, 4> output_shifts = {
      1.0f * input.roll_sp - 1.0f * input.pitch_sp + 1.0f * input.yaw_sp,   // front left
      1.0f * input.roll_sp + 1.0f * input.pitch_sp - 1.0f * input.yaw_sp,   // back left
    - 1.0f * input.roll_sp + 1.0f * input.pitch_sp + 1.0f * input.yaw_sp,   // back right
    - 1.0f * input.roll_sp - 1.0f * input.pitch_sp - 1.0f * input.yaw_sp    // front right
  };

  // Add throttle to shifts to get absolute output value
  std::array<float, 4> outputs = { 0 };
  for(int i = 0; i < 4; i++) {
    outputs[i] = input.throttle_sp + output_shifts[i];
  }

  setMotorSpeeds(outputs);
}

Reorder quadrotor motors per convention.


#include <puppet/compiler/settings.hpp>
#include <boost/filesystem.hpp>
#include <unistd.h>

using namespace std;
namespace fs = boost::filesystem;
namespace sys = boost::system;

namespace puppet { namespace compiler {

    string settings::default_code_directory()
    {
        auto home = getenv("HOME");

        // For root or if the directory exists, use the global code directory
        sys::error_code ec;
        if (!home || geteuid() == 0 || fs::is_directory("/etc/puppetlabs/code", ec)) {
            return "/etc/puppetlabs/code";
        }

        // Otherwise, use the local directory
        return (fs::path(home) / ".puppetlabs" / "etc" / "code").string();
    }

    vector<string> settings::default_environment_directories()
    {
        vector<string> directories = {
            "$codedir/environments",
        };
        return directories;
    }

    vector<string> settings::default_module_directories()
    {
        vector<string> directories = {
            "$codedir/modules",
            "/opt/puppetlabs/puppet/modules",
        };
        return directories;
    }

}}  // namespace puppet::compiler

#include <puppet/compiler/settings.hpp>
#include <boost/filesystem.hpp>
#include <unistd.h>

using namespace std;
namespace fs = boost::filesystem;
namespace sys = boost::system;

namespace puppet { namespace compiler {

    string settings::default_code_directory()
    {
        auto home = getenv("HOME");

        // For root or users without a HOME directory, use the global location
        if (!home || geteuid() == 0) {
            return "/etc/puppetlabs/code";
        }

        // Otherwise, use the local directory
        return (fs::path(home) / ".puppetlabs" / "etc" / "code").string();
    }

    vector<string> settings::default_environment_directories()
    {
        vector<string> directories = {
            "$codedir/environments",
        };
        return directories;
    }

    vector<string> settings::default_module_directories()
    {
        vector<string> directories = {
            "$codedir/modules",
            "/opt/puppetlabs/puppet/modules",
        };
        return directories;
    }

}}  // namespace puppet::compiler

Fix default code directory for non-root user.

Fixing the default code directory for non-root users, which should be under
`~/.puppetlabs/etc/code`.

The bug was that there was a check to see if the global location existed, and
if it did, to use that location even when non-root.

The fix is to remove that check and only use the global location for root.
This matches the behavior of Puppet.


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

// <regex>

// class match_results<BidirectionalIterator, Allocator>

// match_results(const match_results&& m) noexcept;

#include <regex>
#include <cassert>
#include "test_macros.h"
#include "test_allocator.h"

template <class CharT, class Allocator>
void
test(const Allocator& a)
{
    typedef std::match_results<const CharT*, Allocator> SM;
    ASSERT_NOEXCEPT(SM(std::declval<SM&&>()));

    SM m0(a);
    SM m1(std::move(m0));
    assert(m1.size() == 0);
    assert(m1.str() == std::basic_string<CharT>());
    assert(m1.get_allocator() == a);
}

int main()
{
    test<char>   (std::allocator<std::sub_match<const char *> >());
    test<wchar_t>(std::allocator<std::sub_match<const wchar_t *> >());

    test<char>   (test_allocator<std::sub_match<const char*> >(3));
    test<wchar_t>(test_allocator<std::sub_match<const wchar_t*> >(3));
}

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

// <regex>

// class match_results<BidirectionalIterator, Allocator>

// match_results(match_results&& m) noexcept;

#include <regex>
#include <cassert>
#include "test_macros.h"
#include "test_allocator.h"

template <class CharT, class Allocator>
void
test(const Allocator& a)
{
    typedef std::match_results<const CharT*, Allocator> SM;
    ASSERT_NOEXCEPT(SM(std::declval<SM&&>()));

    SM m0(a);
    SM m1(std::move(m0));
    assert(m1.size() == 0);
    assert(m1.str() == std::basic_string<CharT>());
    assert(m1.get_allocator() == a);
}

int main()
{
    test<char>   (std::allocator<std::sub_match<const char *> >());
    test<wchar_t>(std::allocator<std::sub_match<const wchar_t *> >());

    test<char>   (test_allocator<std::sub_match<const char*> >(3));
    test<wchar_t>(test_allocator<std::sub_match<const wchar_t*> >(3));
}

Remove a 'const' from the synopsis. NFC

Remove a 'const' from the synopsis. NFC

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@344997 91177308-0d34-0410-b5e6-96231b3b80d8


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

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

Add C++ Interpreter Libraries to the main source.


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

SSMRESULT CResourceConnectivity::finalConstruct()
{
	SSMRESULT res = SSM_E_FAIL;
    OC::PlatformConfig cfg(OC::ServiceType::InProc, OC::ModeType::Both,
            "134.134.161.33", 56831, OC::QualityOfService::NonConfirmable);

	m_pPlatform = new OC::OCPlatform(cfg);

	SSM_CLEANUP_NULL_ASSERT(m_pPlatform);
	res = SSM_S_OK;

CLEANUP:
	return res;
}

void CResourceConnectivity::finalRelease()
{
}

void* CResourceConnectivity::getPlatform()
{
	return m_pPlatform;
}

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

SSMRESULT CResourceConnectivity::finalConstruct()
{
	SSMRESULT res = SSM_E_FAIL;
    OC::PlatformConfig cfg(OC::ServiceType::InProc, OC::ModeType::Both,
            "134.134.161.33", 56831, OC::QualityOfService::NonConfirmable);

	m_pPlatform = new OC::OCPlatform(cfg);

	SSM_CLEANUP_NULL_ASSERT(m_pPlatform);

	res = SSM_S_OK;

CLEANUP:
	return res;
}

void CResourceConnectivity::finalRelease()
{
	SAFE_DELETE(m_pPlatform);
}

void* CResourceConnectivity::getPlatform()
{
	return m_pPlatform;
}

Fix to call OIC platform destructor

[SSM] Fix to call OIC platform destructor

Problem: There is no destructor caller

How: Call platform destructor when OIC platform manager destroying

Change-Id: I83b033494f3bb84e5341c21d7ec4051e110a9ff8
Signed-off-by: Kim Jee Hyeok <ecfb86b5d85d5430a7602d1e11f4f25d16714d36@samsung.com>


#include <cmath>
#include <stdexcept>

#include "Layer/filter.hpp"
#include "Utility/utility.hpp"

using namespace Convolutional;
using namespace Convolutional::Layer;

Filter::Filter(std::size_t size) :
bias{Utility::GetRandomNumberBetween(-1.0, 1.0)} {
	// TODO jnf: constexpr check if size is perfect square
	weights.reserve(size);
	for (size_t i = 0; i < size; ++i) {
		weights.push_back(Utility::GetRandomNumberBetween(-1.0, 1.0));
	}
}

auto Filter::ProcessMatrix(Matrix matrix) const -> Matrix {
	if (matrix.GetElementCount() != weights.size()) {
		throw std::invalid_argument("Number of weights in filter does not match number of elements in matrix");
	}

	Matrix featureMap{matrix.GetSubmatrix(position, GetReceptiveField(matrix.GetSize()))};

	auto featureValue = bias;
	auto weight = weights.begin();
	for (const auto& element : featureMap) {
		featureValue += element * *weight;
		++weight;
	}
	featureValue = sigmoid(featureValue);

	for (auto& element : featureMap) {
		element = featureValue;
	}

	return featureMap;
}

auto Filter::sigmoid(Matrix::element_t n) -> double {
	return tanh(n);
}

#include <cmath>
#include <stdexcept>

#include "Layer/filter.hpp"
#include "Utility/utility.hpp"

using namespace Convolutional;
using namespace Convolutional::Layer;

Filter::Filter(std::size_t size) :
bias{Utility::GetRandomNumberBetween(-1.0, 1.0)} {
	// TODO jnf: constexpr check if size is perfect square
	weights.reserve(size);
	for (size_t i = 0; i < size; ++i) {
		weights.push_back(Utility::GetRandomNumberBetween(-1.0, 1.0));
	}
}

auto Filter::ProcessMatrix(Matrix matrix) const -> Matrix {
	if (matrix.GetElementCount() != weights.size()) {
		throw std::invalid_argument("Number of weights in filter does not match number of elements in matrix");
	}

	auto featureValue = bias;
	auto weight = weights.begin();
	for (const auto& element : matrix) {
		featureValue += element * *weight;
		++weight;
	}
	featureValue = sigmoid(featureValue);

	for (auto& element : matrix) {
		element = featureValue;
	}

	return matrix;
}

auto Filter::sigmoid(Matrix::element_t n) -> double {
	return tanh(n);
}

Remove corpses from old code

Remove corpses from old code


#include <iostream>

#include "..\..\shared\ProblemEngine.h"

int FindShortestPath(const int * const data, int size);

int main(int argc, char * argv[])
{
	ProblemEngine<> engine("input.txt");
	if (!engine.IsFileOk())
	{
		std::cout << "Unable to open input.txt" << std::endl;
		return 1;
	}

	auto testCases = engine.LoadTestCases();

	for (const auto& testCase : testCases)
	{
		auto data = testCase.Datas.front().get();
		auto size = testCase.Sizes.front();

		auto sp = FindShortestPath(data, size);

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

	return 0;
}

int FindShortestPath(const int * const data, int size)
{
	return 0;
}

#include <iostream>

#include "..\..\shared\ProblemEngine.h"

int FindShortestPath(int ** data, int rowSize);

int** CreateMatrix(const int * const input, int rowSize)
{
	auto ret = new int*[rowSize];
	for (int i = 0; i < rowSize; ++i)
	{
		ret[i] = new int[rowSize];
		for (int j = 0; j < rowSize; ++j)
			ret[i][j] = input == nullptr ? 0 : input[i * rowSize + j];
	}
	return ret;
}

void DeleteMatrix(int **& input, int rowSize)
{
	for (int i = 0; i < rowSize; ++i)
		delete[] input[i];
	delete[] input;
	input = nullptr;
}

int min(int a, int b, int c)
{
	if (a < b && a < c) return a;
	if (b < a && b < c) return b;
	return c;
}

int main(int argc, char * argv[])
{
	ProblemEngine<> engine("input.txt");
	if (!engine.IsFileOk())
	{
		std::cout << "Unable to open input.txt" << std::endl;
		return 1;
	}

	auto testCases = engine.LoadTestCases();

	for (const auto& testCase : testCases)
	{
		auto data = testCase.Datas.front().get();
		auto size = testCase.Sizes.front();

		auto rowSize = static_cast<int>(sqrt(size));
		if (size != rowSize * rowSize)
			throw std::exception("input data is not a square matrix");

		int ** matrix = CreateMatrix(data, rowSize);
		auto sp = FindShortestPath(matrix, rowSize);
		DeleteMatrix(matrix, rowSize);

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

	return 0;
}

int FindShortestPath(int ** ptr, int rowSize)
{
	return 0;
}

Create matrix out of input data to simplify algorithm


#include <cstdlib>
#include <ATK/EQ/BesselFilter.h>
#include <ATK/EQ/IIRFilter.h>

#include <ATK/Mock/SimpleSinusGeneratorFilter.h>

int main(int argc, char** argv)
{
  ATK::SimpleSinusGeneratorFilter<double> generator;
  generator.set_output_sampling_rate(1024 * 64);
  generator.set_amplitude(1);
  generator.set_frequency(1000);

  ATK::IIRFilter<ATK::BesselLowPassCoefficients<double> > filter;
  filter.set_input_sampling_rate(1024 * 64);
  filter.set_output_sampling_rate(1024 * 64);
  filter.set_cut_frequency(100);
  filter.set_order(3);

  filter.set_input_port(0, &generator, 0);

  for(size_t i = 0; i < 1024*1024; ++i)
    filter.process(1024);

  return EXIT_SUCCESS;
}

#include <cstdlib>
#include <ATK/EQ/BesselFilter.h>
#include <ATK/EQ/IIRFilter.h>

#include <ATK/Mock/SimpleSinusGeneratorFilter.h>

int main(int argc, char** argv)
{
  ATK::SimpleSinusGeneratorFilter<double> generator;
  generator.set_output_sampling_rate(1024 * 64);
  generator.set_amplitude(1);
  generator.set_frequency(1000);

  ATK::IIRFilter<ATK::BesselLowPassCoefficients<double> > filter;
  filter.set_input_sampling_rate(1024 * 64);
  filter.set_output_sampling_rate(1024 * 64);
  filter.set_cut_frequency(100);
  filter.set_order(7);

  filter.set_input_port(0, &generator, 0);

  for(size_t i = 0; i < 1024*1024; ++i)
    filter.process(1024);

  return EXIT_SUCCESS;
}

MAke it simpler to vectorize (even if this is not the proper way)


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

#include <stdlib.h>
#include <sys/wait.h>

#include "gtest/gtest.h"

const int kDefaultLibFuzzerError = 77;

TEST(LibFuzzerExampleTest, Crash) {
  char dir_template[] = "/tmp/libfuzzer_example_test_XXXXXX";
  auto dir = mkdtemp(dir_template);
  ASSERT_TRUE(dir);

  std::string cmd =
      "./libfuzzer_example -max_len=10000 -runs=100000 -artifact_prefix=" +
      std::string(dir) + "/ " + dir;
  int retvalue = std::system(cmd.c_str());
  EXPECT_EQ(kDefaultLibFuzzerError, WSTOPSIG(retvalue));

  // Cleanup.
  EXPECT_EQ(0, std::system((std::string("rm -rf ") + dir).c_str()));
}

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

#include <stdlib.h>
#include <sys/wait.h>

#include "gtest/gtest.h"

const int kDefaultLibFuzzerError = 77;

TEST(LibFuzzerExampleTest, Crash) {
  char dir_template[] = "/tmp/libfuzzer_example_test_XXXXXX";
  auto dir = mkdtemp(dir_template);
  ASSERT_TRUE(dir);

  std::string cmd =
      "./libfuzzer_example -max_len=10000 -runs=300000 -artifact_prefix=" +
      std::string(dir) + "/ " + dir;
  int retvalue = std::system(cmd.c_str());
  EXPECT_EQ(kDefaultLibFuzzerError, WSTOPSIG(retvalue));

  // Cleanup.
  EXPECT_EQ(0, std::system((std::string("rm -rf ") + dir).c_str()));
}

Increase number of iterations in libFuzzer test


#include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"

static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
    return NULL;
}

static PyMethodDef QuantucciaMethods[] = {
	{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
	{NULL, NULL, 0, NULL}
};

static struct PyModuleDef quantuccia_module_def = {
	PyModuleDef_HEAD_INIT,
	"quantuccia",
	NULL,
	-1,
	QuantucciaMethods,
	NULL,
	NULL,
	NULL,
	NULL
};

PyMODINIT_FUNC PyInit_quantuccia(void){
    PyObject *m;
    m = PyModule_Create(&quantuccia_module_def);
    return m;
}

#include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"

static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
    return Py_None;
}

static PyMethodDef QuantucciaMethods[] = {
	{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
	{NULL, NULL, 0, NULL}
};

static struct PyModuleDef quantuccia_module_def = {
	PyModuleDef_HEAD_INIT,
	"quantuccia",
	NULL,
	-1,
	QuantucciaMethods,
	NULL,
	NULL,
	NULL,
	NULL
};

PyMODINIT_FUNC PyInit_quantuccia(void){
    PyObject *m;
    m = PyModule_Create(&quantuccia_module_def);
    return m;
}

Change return NULL -> return Py_None.

Change return NULL -> return Py_None.


#include <iostream>
#include <string>
#include <utility>
#include <map>
#include <vector>
#include <functional>

#include <useful/sort.hpp>
#include <useful/range.hpp>

using namespace useful;

using wcount = std::map<std::string, int>;

int main(void) {
	wcount words;
	std::string word;

	while (std::cin >> word)
		words[word] += 1;

	std::vector<std::pair<std::string, int>> wordv(words.begin(), words.end());
	std::partial_sort(wordv.begin(), wordv.begin() + 10, wordv.end(),
			cmp2nd<std::string, int, std::greater<int>>()
			//std::not2(cmp2nd<std::string, int>())
			//[](auto &a, auto &b) { return a.second > b.second; }
			);

	for (const auto p : take(wordv, 10))
		std::cout << p.second << ": " << p.first << '\n';

	return 0;
}

#include <iostream>
#include <string>
#include <utility>
#include <map>
#include <vector>
#include <functional>
#include <algorithm>

#include <useful/sort.hpp>
#include <useful/range.hpp>

using namespace useful;

using wcount = std::map<std::string, int>;

int main(void) {
	wcount words;
	std::string word;

	while (std::cin >> word)
		words[word] += 1;

	std::vector<std::pair<std::string, int>> wordv(words.begin(), words.end());
	std::partial_sort(wordv.begin(), wordv.begin() + 10, wordv.end(),
			cmp2nd<std::string, int, std::greater<int>>()
			//std::not2(cmp2nd<std::string, int>())
			//[](auto &a, auto &b) { return a.second > b.second; }
			);

	for (const auto p : take(wordv, 10))
		std::cout << p.second << ": " << p.first << '\n';

	return 0;
}

Add test program demonstrating finding most common words.


#include <aerial_autonomy/common/html_utils.h>
#include <gtest/gtest.h>
#include <iostream>

/// \brief TEST
/// Simple Html table tests
TEST(HtmlTableWriterTests, SimpleTable) {
  HtmlTableWriter table_writer;
  table_writer.beginRow();
  table_writer.addHeader("Header");
  table_writer.beginRow();
  double data = 2.0;
  table_writer.addCell(data, "Hello");
  table_writer.addCell("Data");
  table_writer.addCell("Data", "Hello", Colors::white);
  std::cout << "Table: \n" << table_writer.getTableString() << std::endl;
}
TEST(HtmlTableWriterTests, TableError) {
  HtmlTableWriter table_writer;
  EXPECT_THROW(table_writer.addHeader("Hello"), std::runtime_error);
  EXPECT_THROW(table_writer.addCell("Hello"), std::runtime_error);
}
/// Simple Html division tests
TEST(HtmlTableWriterTests, SimpleDivision) {
  HtmlDivisionWriter division_writer;
  division_writer.addHeader("Hello", 1);
  division_writer.addText("My text");
  std::cout << "Division: \n" << division_writer.getDivisionText() << std::endl;
}
///

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

#include <aerial_autonomy/common/html_utils.h>
#include <gtest/gtest.h>
#include <iostream>

/// \brief TEST
/// Simple Html table tests
TEST(HtmlTableWriterTests, SimpleTable) {
  HtmlTableWriter table_writer;
  table_writer.beginRow();
  table_writer.addHeader("Header");
  table_writer.beginRow();
  double data = 2.0;
  table_writer.addCell(data, "Hello");
  table_writer.addCell("Data");
  table_writer.addCell("Data", "Hello", Colors::white);
  ///\todo Add an automatic way of validating html string
  std::cout << "Table: \n" << table_writer.getTableString() << std::endl;
}
TEST(HtmlTableWriterTests, TableError) {
  HtmlTableWriter table_writer;
  EXPECT_THROW(table_writer.addHeader("Hello"), std::runtime_error);
  EXPECT_THROW(table_writer.addCell("Hello"), std::runtime_error);
}
/// Simple Html division tests
TEST(HtmlTableWriterTests, SimpleDivision) {
  HtmlDivisionWriter division_writer;
  division_writer.addHeader("Hello", 1);
  division_writer.addText("My text");
  std::cout << "Division: \n" << division_writer.getDivisionText() << std::endl;
}
///

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

Add todo for automatic html validation

Add todo for automatic html validation


#include "KVNetworkAccessManager.h"

#include <QDebug>

#include "KVNetworkReply.h"

KVNetworkAccessManager::KVNetworkAccessManager(QObject *parent) :
	QNetworkAccessManager(parent)
{

}

QNetworkReply *KVNetworkAccessManager::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData)
{
	QNetworkRequest request = req;
	request.setRawHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");

	if(request.url().host() != "localhost" && request.url().host() != "127.0.0.1")
	{
		if(op == QNetworkAccessManager::PostOperation)
		{
			qDebug() << "POST" << request.url().path();
			QNetworkReply *r = QNetworkAccessManager::createRequest(op, request, outgoingData);
			KVNetworkReply *reply = new KVNetworkReply(r->parent(), r, this);
			return reply;
		}
		else if(op == QNetworkAccessManager::GetOperation)
		{
			qDebug() << "GET" << request.url().path();
		}
	}

	QNetworkReply *reply = QNetworkAccessManager::createRequest(op, request, outgoingData);
	return reply;
}

#include "KVNetworkAccessManager.h"

#include <QDebug>

#include "KVNetworkReply.h"

KVNetworkAccessManager::KVNetworkAccessManager(QObject *parent) :
	QNetworkAccessManager(parent)
{

}

QNetworkReply *KVNetworkAccessManager::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData)
{
	QNetworkRequest request = req;
	request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36");

	if(request.url().host() != "localhost" && request.url().host() != "127.0.0.1")
	{
		if(op == QNetworkAccessManager::PostOperation)
		{
			qDebug() << "POST" << request.url().path();
			QNetworkReply *r = QNetworkAccessManager::createRequest(op, request, outgoingData);
			KVNetworkReply *reply = new KVNetworkReply(r->parent(), r, this);
			return reply;
		}
		else if(op == QNetworkAccessManager::GetOperation)
		{
			qDebug() << "GET" << request.url().path();
		}
	}

	QNetworkReply *reply = QNetworkAccessManager::createRequest(op, request, outgoingData);
	return reply;
}

Use the same User-Agent everywhere, just because


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

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

const char *first_counter;

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

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

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

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

const char *first_counter;

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

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

Mark sancov test as unsupported on Darwin

This test has been failing on all Darwin bots since it was introduced:
http://lab.llvm.org:8080/green/job/clang-stage1-configure-RA_check/32111

fatal error: error in backend: Global variable '__sancov_gen_' has an invalid section specifier '__DATA,__sancov_counters': mach-o section specifier requires a section whose length is between 1 and 16 characters.
Target: x86_64-apple-darwin15.6.0

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@304673 91177308-0d34-0410-b5e6-96231b3b80d8


#include <QTest>
#include "test-suite.h"
#include "custom-network-access-manager.h"
#include <iostream>

int main(int argc, char *argv[])
{
	#ifdef HEADLESS
		QCoreApplication a(argc, argv);
	#else
		QGuiApplication a(argc, argv);
	#endif

	QMap<QString,int> results;
	int failed = 0;

	CustomNetworkAccessManager::TestMode = true;

	for (QObject *suite : TestSuite::suites)
	{
		int result = QTest::qExec(suite);
		results.insert(suite->metaObject()->className(), result);
		if (result != 0)
		{
			failed++;
		}
	}

	for (auto key : results.keys())
	{
		std::cout << '[' << (results.value(key) != 0 ? "FAIL" : "OK") << "] " << key.toStdString() << std::endl;
	}

	return failed;
}

#include <QTest>
#include "test-suite.h"
#include "custom-network-access-manager.h"
#include <iostream>

int main(int argc, char *argv[])
{
	#ifdef HEADLESS
		QCoreApplication a(argc, argv);
	#else
		QGuiApplication a(argc, argv);
	#endif

	QStringList testSuites;
	for (int i = 1; i < argc; ++i)
		testSuites.append(argv[i]);

	QMap<QString,int> results;
	int failed = 0;

	CustomNetworkAccessManager::TestMode = true;

	for (QObject *suite : TestSuite::suites)
	{
		if (!testSuites.isEmpty() && !testSuites.contains(suite->metaObject()->className()))
			continue;

		int result = QTest::qExec(suite);
		results.insert(suite->metaObject()->className(), result);
		if (result != 0)
		{
			failed++;
		}
	}

	for (auto key : results.keys())
	{
		std::cout << '[' << (results.value(key) != 0 ? "FAIL" : "OK") << "] " << key.toStdString() << std::endl;
	}

	return failed;
}

Allow to only run some test suites from the test runner