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

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

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

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    if (0 == add) {
        return SkColorFilter::CreateModeFilter(mul | SK_ColorBLACK,
                                               SkXfermode::Mode::kModulate_Mode);
    }
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

Simplify LightingFilter in add-free case
am: 0698300cc5

* commit '0698300cc567384d6c528b5b1757ed8abe930dc5':
  Simplify LightingFilter in add-free case

Change-Id: Ic395be971bac84e1d2e6f8b9043c026051c21361


#include <QApplication>

#include "mainwindow.h"
#include "runguard.h"

int main(int argc, char **argv)
{
    RunGuard guard("UwNDcyZjc6MjE1tN2Ma3NGIf5OGx");

    if (!guard.tryToRun())
        return 0;

    QApplication a(argc, argv);
    MainWindow w;

    w.show();

    return a.exec();
}

#include <QApplication>

#include "mainwindow.h"
#include "runguard.h"

QString getUserName()
{
    QString name = qgetenv("USER");

    if (name.isEmpty())
        name = qgetenv("USERNAME");

    return name;
}

int main(int argc, char **argv)
{
    RunGuard guard(getUserName() + "-doer-UwNDcyZjc6MjE1tN2Ma3NGIf5OGx");

    if (!guard.tryToRun())
        return 0;

    QApplication a(argc, argv);
    MainWindow w;

    w.show();

    return a.exec();
}

Allow to run doer as a different user on the same machine


#include <iostream>
#include <cstdlib> // for RAND_MAX
#include <ctime>
using namespace std;

int main(int argc, char* argv[]) {
   const int LARGEST_POSSIBLE = 100;

   srand(time(0)); // seed the random number generator based on current time
   //srand(10);
   rand();
   // the rand() function generates a random integer from 0 to RAND_MAX
   int chosen = rand() % 101               ; // how to cut interval to [0, 100]?
   cout << "I choose the number " << chosen << "!" << endl;
   cout << "RAND_MAX is " << RAND_MAX << endl;
}

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

int main(int argc, char* argv[]) {
   const int LARGEST_POSSIBLE = 100;

   // Some of this will look funny for now; we will explain later.

   // A random_device helps to "seed" a number generator.
   random_device rd;
   // a compiler-chosen "good" random number generator.
   default_random_engine engine(rd());

   // Takes the output of the engine and maps it to a uniform distribution
   // between two parameters.
   uniform_int_distribution<int> distr(1, LARGEST_POSSIBLE);

   // Now "call" the distribution to get a number.
   int chosen = distr(engine);
   cout << "I choose the number " << chosen << "!" << endl;

   // Every time I call the distribution I get a new number.
   cout << "Next number: " << distr(engine) << endl;
   cout << "Next number: " << distr(engine) << endl;
}

Use C++11 <random> instead of C rand().

Use C++11 <random> instead of C rand().


#include <Pith/Config.hpp>
#include <Pith/Page.hpp>
#include <gtest/gtest.h>

using namespace Pith;

TEST(TestPage, StackAllocate) {
	Page p;
}

TEST(TestPage, mapOnePage) {
	Span<Page> pages{nullptr, 1};
	auto result = Page::map(pages);
	EXPECT_TRUE(result);
	EXPECT_NE(result(), nullptr);
	pages.value(result());
	EXPECT_EQ(Page::unmap(pages), 0);
}

TEST(TestPage, setPermissions) {
	Span<Page> pages{nullptr, 1};
}

TEST(TestPage, setPermissionsOnUnmappedPage) {
	Span<Page> pages{nullptr, 1};

	// Get a fresh page.
	{
		auto r = Page::map(pages);
		ASSERT_TRUE(r);
		pages.value(r());
	}

	// Explicitly unmap it.
	{
		auto e = Page::unmap(pages);
		ASSERT_EQ(e, 0);
	}

	// Fail to set permissions on unmapped page.
	{
		auto e = Page::setPermissions(pages, Page::Permissions::READ);
		ASSERT_NE(e, 0);
	}
}

#if 0
TEST(PageSpan, mapAndUnmap) {
	PageSpan pages{nullptr, 1};
	auto map = pages.map();
	map.unmap();
}
#endif  // 0

#include <Pith/Config.hpp>
#include <Pith/Page.hpp>
#include <gtest/gtest.h>

using namespace Pith;

TEST(TestPage, stackAllocate) {
	[[maybe_unused]] Page p;
}

TEST(TestPage, mapOnePage) {
	Span<Page> pages{nullptr, 1};
	auto result = Page::map(pages);
	EXPECT_TRUE(result);
	EXPECT_NE(result(), nullptr);
	pages.value(result());
	EXPECT_EQ(Page::unmap(pages), 0);
}

TEST(TestPage, setPermissions) {
	Span<Page> pages{nullptr, 1};
}

TEST(TestPage, setPermissionsOnUnmappedPage) {
	Span<Page> pages{nullptr, 1};

	// Get a fresh page.
	{
		auto r = Page::map(pages);
		ASSERT_TRUE(r);
		pages.value(r());
	}

	// Explicitly unmap it.
	{
		auto e = Page::unmap(pages);
		ASSERT_EQ(e, 0);
	}

	// Fail to set permissions on unmapped page.
	{
		auto e = Page::setPermissions(pages, Page::Permissions::READ);
		ASSERT_NE(e, 0);
	}
}

#if 0
TEST(PageSpan, mapAndUnmap) {
	PageSpan pages{nullptr, 1};
	auto map = pages.map();
	map.unmap();
}
#endif  // 0

Mark stack allocated page as unused

Mark stack allocated page as unused

Signed-off-by: Robert Young <42c59959a3f4413d6a1b4d7b4f99db457d199e49@gmail.com>


//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_networking_sntp.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp =
{
    "nanoFramework.Networking.Sntp",
    0x733B4551,
    method_lookup,
    { 1, 0, 2, 49 }
};

//
// Copyright (c) 2018 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include "nf_networking_sntp.h"

static const CLR_RT_MethodHandler method_lookup[] =
{
    NULL,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Start___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::Stop___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::UpdateNow___STATIC__VOID,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_IsStarted___STATIC__BOOLEAN,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server1___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server1___STATIC__VOID__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::get_Server2___STATIC__STRING,
    Library_nf_networking_sntp_nanoFramework_Networking_Sntp::set_Server2___STATIC__VOID__STRING,
};

const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Networking_Sntp =
{
    "nanoFramework.Networking.Sntp",
    0x733B4551,
    method_lookup,
    { 1, 0, 2, 2 }
};

Update nanoFramework.Networking.Sntp version to 1.0.2 ***NO_CI***


/**
 * Zillians MMO
 * Copyright (C) 2007-2010 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "language/logging/LoggerWrapper.h"
#include "language/ThorScriptVM.h"

int main(int argc, char** argv)
{
	zillians::language::ThorScriptVM vm;
	return vm.main(argc, argv);
}

/**
 * Zillians MMO
 * Copyright (C) 2007-2010 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "language/logging/LoggerWrapper.h"
#include "language/ThorScriptVM.h"

int main(int argc, const char** argv)
{
	zillians::language::ThorScriptVM vm;
	return vm.main(argc, argv);
}

Fix warning: convert from char** to const char**


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

using namespace Halide;

int main(int argc, char **argv) {
    // Test if the compiler itself is thread-safe. This test is
    // intended to be run in a thread-sanitizer.
    std::vector<std::thread> threads;
    for (int i = 0; i < 1000; i++) {
        threads.emplace_back([]{
            Func f;
            Var x;
            f(x) = x;
            f.realize(100);
        });
    }

    for (auto &t : threads) {
        t.join();
    }

    printf("Success!\n");

    return 0;
}

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

using namespace Halide;

static std::atomic<int> foo;

int main(int argc, char **argv) {
    // Test if the compiler itself is thread-safe. This test is
    // intended to be run in a thread-sanitizer.
    std::vector<std::future<void>> futures;
    for (int i = 0; i < 1000; i++) {
        futures.emplace_back(std::async(std::launch::async, []{
            Func f;
            Var x;
            f(x) = x;
            f.realize(100);
        }));
    }

    for (auto &f : futures) {
        f.wait();
    }

    printf("Success!\n");

    return 0;
}

Use std::async() instead of std::thread()

It is guaranteed to use a pool-like behavior; to ensure that every task
is executed by spawning a new thread, we must explicitly specify
std::launch::async.


/*
 * ty, a collection of GUI and command-line tools to manage Teensy devices
 *
 * Distributed under the MIT license (see LICENSE.txt or http://opensource.org/licenses/MIT)
 * Copyright (c) 2015 Niels Martignène <niels.martignene@gmail.com>
 */

#include <QSettings>

#include "database.hh"

using namespace std;

void SettingsDatabase::put(const QString &key, const QVariant &value)
{
    if (!settings_)
        return;

    settings_->setValue(key, value);
}

void SettingsDatabase::remove(const QString &key)
{
    if (!settings_)
        return;

    settings_->remove(key);
}

QVariant SettingsDatabase::get(const QString &key, const QVariant &default_value) const
{
    if (!settings_)
        return default_value;

    return settings_->value(key, default_value);
}

void SettingsDatabase::clear()
{
    if (!settings_)
        return;

    settings_->clear();
}

/*
 * ty, a collection of GUI and command-line tools to manage Teensy devices
 *
 * Distributed under the MIT license (see LICENSE.txt or http://opensource.org/licenses/MIT)
 * Copyright (c) 2015 Niels Martignène <niels.martignene@gmail.com>
 */

#include <QSettings>

#include "database.hh"

using namespace std;

void SettingsDatabase::put(const QString &key, const QVariant &value)
{
    settings_->setValue(key, value);
}

void SettingsDatabase::remove(const QString &key)
{
    settings_->remove(key);
}

QVariant SettingsDatabase::get(const QString &key, const QVariant &default_value) const
{
    return settings_->value(key, default_value);
}

void SettingsDatabase::clear()
{
    settings_->clear();
}

Remove 'useless' checks from SettingsDatabase


#include "MainWindow.h"

#include <Application.h>
#include <Menu.h>
#include <MenuItem.h>
#include <View.h>

#include "MainView.h"

MainWindow::MainWindow(void)
	:	BWindow(BRect(100,100,500,400),"Font Demo", B_TITLED_WINDOW,
					B_ASYNCHRONOUS_CONTROLS)
{
	BRect r(Bounds());
	r.bottom = 20;
	fMenuBar = new BMenuBar(r,"menubar");
	AddChild(fMenuBar);
	r = Bounds();
	r.top = 20;
	MainView *view = new MainView(r);
	AddChild(view);
}
void
MainWindow::MessageReceived(BMessage *msg)
{
	switch (msg->what)
	{
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool
MainWindow::QuitRequested(void)
{
	be_app->PostMessage(B_QUIT_REQUESTED);
	return true;
}

#include "MainWindow.h"

#include <Application.h>
#include <Menu.h>
#include <MenuItem.h>
#include <View.h>

#include "MainView.h"

MainWindow::MainWindow(void)
	:	BWindow(BRect(100, 100, 900, 550),"Font Demo", B_TITLED_WINDOW,
					B_ASYNCHRONOUS_CONTROLS)
{
	BRect r(Bounds());
	r.bottom = 20;
	fMenuBar = new BMenuBar(r,"menubar");
	AddChild(fMenuBar);
	r = Bounds();
	r.top = 20;
	MainView *view = new MainView(r);
	AddChild(view);
}
void
MainWindow::MessageReceived(BMessage *msg)
{
	switch (msg->what)
	{
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool
MainWindow::QuitRequested(void)
{
	be_app->PostMessage(B_QUIT_REQUESTED);
	return true;
}

Make the initial window size larger to see all text


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

#include "cc/blink/web_external_bitmap_impl.h"

#include "cc/resources/shared_bitmap.h"

namespace cc_blink {

namespace {

SharedBitmapAllocationFunction g_memory_allocator;

}  // namespace

void SetSharedBitmapAllocationFunction(
    SharedBitmapAllocationFunction allocator) {
  g_memory_allocator = allocator;
}

WebExternalBitmapImpl::WebExternalBitmapImpl() {
}

WebExternalBitmapImpl::~WebExternalBitmapImpl() {
}

void WebExternalBitmapImpl::setSize(blink::WebSize size) {
  if (size != size_) {
    shared_bitmap_ = g_memory_allocator(gfx::Size(size));
    size_ = size;
  }
}

blink::WebSize WebExternalBitmapImpl::size() {
  return size_;
}

uint8* WebExternalBitmapImpl::pixels() {
  return shared_bitmap_->pixels();
}

}  // namespace cc_blink

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

#include "cc/blink/web_external_bitmap_impl.h"

#include "cc/resources/shared_bitmap.h"

namespace cc_blink {

namespace {

SharedBitmapAllocationFunction g_memory_allocator;

}  // namespace

void SetSharedBitmapAllocationFunction(
    SharedBitmapAllocationFunction allocator) {
  g_memory_allocator = allocator;
}

WebExternalBitmapImpl::WebExternalBitmapImpl() {
}

WebExternalBitmapImpl::~WebExternalBitmapImpl() {
}

void WebExternalBitmapImpl::setSize(blink::WebSize size) {
  if (size != size_) {
    shared_bitmap_ = g_memory_allocator(gfx::Size(size));
    size_ = size;
  }
}

blink::WebSize WebExternalBitmapImpl::size() {
  return size_;
}

uint8* WebExternalBitmapImpl::pixels() {
  if (!shared_bitmap_) {
    // crbug.com/520417: not sure why a non-null WebExternalBitmap is
    // being passed to prepareMailbox when the shared_bitmap_ is null.
    // Best hypothesis is that the bitmap is zero-sized.
    DCHECK(size_.isEmpty());
    return nullptr;
  }
  return shared_bitmap_->pixels();
}

}  // namespace cc_blink

Add null check in WebExternalBitmapImpl::pixels.

This should work around problems with zero-sized canvases.

BUG=520417
CQ_INCLUDE_TRYBOTS=tryserver.blink:linux_blink_rel

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

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


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

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t s) {
  return HeapAlloc(win_heap, 0, s);
}

void* win_heap_realloc(void* p, size_t s) {
  if (!p)
    return win_heap_malloc(s);
  return HeapReAlloc(win_heap, 0, p, s);
}

void win_heap_free(void* s) {
  HeapFree(win_heap, 0, s);
}

size_t win_heap_msize(void* p) {
  return HeapSize(win_heap, 0, p);
}

}  // extern "C"

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

// This is a simple allocator based on the windows heap.

extern "C" {

HANDLE win_heap;

bool win_heap_init(bool use_lfh) {
  win_heap = HeapCreate(0, 0, 0);
  if (win_heap == NULL)
    return false;

  if (use_lfh) {
    ULONG enable_lfh = 2;
    HeapSetInformation(win_heap, HeapCompatibilityInformation,
                       &enable_lfh, sizeof(enable_lfh));
    // NOTE: Setting LFH may fail.  Vista already has it enabled.
    //       And under the debugger, it won't use LFH.  So we
    //       ignore any errors.
  }

  return true;
}

void* win_heap_malloc(size_t size) {
  return HeapAlloc(win_heap, 0, size);
}

void win_heap_free(void* size) {
  HeapFree(win_heap, 0, size);
}

void* win_heap_realloc(void* ptr, size_t size) {
  if (!ptr)
    return win_heap_malloc(size);
  if (!size) {
    win_heap_free(ptr);
    return NULL;
  }
  return HeapReAlloc(win_heap, 0, ptr, size);
}

size_t win_heap_msize(void* ptr) {
  return HeapSize(win_heap, 0, ptr);
}

}  // extern "C"

Fix the windows allocator to behave properly on realloc.

The spec says that calling realloc(ptr, 0) should free ptr
and return NULL.

BUG=none
TEST=none

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

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


#include "yugong.hpp"

#include <cstdint>
#include <cstdlib>

namespace yg {

    void YGStack::alloc(YGStack &stack, uintptr_t size) {
        void *mem = std::malloc(size);
        uintptr_t start = (uintptr_t)mem;

        stack.start = start;
        stack.size = size;
        stack.sp = start + size;
    }

    void YGStack::free(YGStack &stack) {
        void *mem = (void*)stack.start;
        std::free(mem);
    }

    void ll::push_initial_frame(YGStack &stack, FuncPtr func) {
        uintptr_t *stack_bottom = (uintptr_t*)(stack.start + stack.size);
        stack_bottom[-1] = 0;
        stack_bottom[-2] = (uintptr_t)func;
        stack_bottom[-3] = (uintptr_t)_yg_func_begin_resume;
        stack.sp = (uintptr_t)(&stack_bottom[-3]);
    }

}

#include "yugong.hpp"

#include <cstdint>
#include <cstdlib>

namespace yg {

    void YGStack::alloc(YGStack &stack, uintptr_t size) {
        void *mem = std::malloc(size);
        uintptr_t start = reinterpret_cast<uintptr_t>(mem);

        stack.start = start;
        stack.size = size;
        stack.sp = start + size;
    }

    void YGStack::free(YGStack &stack) {
        void *mem = reinterpret_cast<void*>(stack.start);
        std::free(mem);
    }

    void ll::push_initial_frame(YGStack &stack, FuncPtr func) {
        uintptr_t *stack_bottom = reinterpret_cast<uintptr_t*>(stack.start + stack.size);
        stack_bottom[-1] = 0;
        stack_bottom[-2] = reinterpret_cast<uintptr_t>(func);
        stack_bottom[-3] = reinterpret_cast<uintptr_t>(_yg_func_begin_resume);
        stack.sp         = reinterpret_cast<uintptr_t>(&stack_bottom[-3]);
    }

}

Use C++-style reinterpret_cast when possible.


#define BOOST_TEST_MODULE rainback
#include "init.hpp"

#include <QApplication>

struct QApplicationFixture
{
    int argc;
    char name[100];
    char* argv[1];

    QApplication* app;
public:
    QApplicationFixture() :
        argc(1)
    {
        strcpy(name, "rainback");
        argv[0] = name;
        app = new QApplication(argc, argv);
    }

    ~QApplicationFixture()
    {
        delete app;
    }
};

BOOST_GLOBAL_FIXTURE(QApplicationFixture);

// vim: set ts=4 sw=4 :

#define BOOST_TEST_MODULE rainback
#include "init.hpp"

#include <QCoreApplication>

struct QApplicationFixture
{
    int argc;
    char name[100];
    char* argv[1];

    QCoreApplication* app;
public:
    QApplicationFixture() :
        argc(1)
    {
        strcpy(name, "rainback");
        argv[0] = name;
        app = new QCoreApplication(argc, argv);
    }

    ~QApplicationFixture()
    {
        delete app;
    }
};

BOOST_GLOBAL_FIXTURE(QApplicationFixture);

// vim: set ts=4 sw=4 :

Make the test fixture use QApplication

Make the test fixture use QApplication


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

#include <limits.h>

const bool swchar = (wchar_t)-1 > (wchar_t)0;

#ifdef __WCHAR_UNSIGNED__
int signed_test[!swchar];
#else
int signed_test[swchar];
#endif

int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)];
int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];

// RUN: %clang -fsyntax-only -verify %s
// RUN: %clang -fsyntax-only -verify -fshort-wchar %s

#include <limits.h>

const bool swchar = (wchar_t)-1 > (wchar_t)0;

#ifdef __WCHAR_UNSIGNED__
int signed_test[!swchar];
#else
int signed_test[swchar];
#endif

int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)];
int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];

Fix test on MSVC: since the test includes a system header it cannot use clang_cc1.

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


#include <libclientserver.h>

Thread::Thread()
{
	m_IsRunning = false;
	m_IsDetached = false;
}

Thread::~Thread()
{
	if (IsRunning())
		Stop();

}

void Thread::Start()
{
	m_IsRunning = true;
	if (pthread_create(&m_thread, NULL, RunInternal, this) != 0)
		abort();
}

void Thread::Stop()
{
#ifdef DEBUG
	if (IsDetached() == true)
		abort();

	if (m_IsRunning == false)
	{
		abort();	//Attempted to stop an already stopped thread
	}
#endif
	if (pthread_join(m_thread, NULL) != 0)
		abort();
}

void Thread::Detach()
{
	if (pthread_detach(m_thread) != 0)
		abort();
	m_IsDetached = true;
}

bool Thread::IsRunning()
{
	return m_IsRunning;
}

bool Thread::IsDetached()
{
	return m_IsDetached;
}

void Thread::Run()
{
	abort();	//You should override this function
}

void *Thread::RunInternal(void *ptr)
{
	class Thread *self = (Thread *) ptr;
	self->Run();
	return NULL;
}

#include <libclientserver.h>

Thread::Thread()
{
	m_IsRunning = false;
	m_IsDetached = false;
}

Thread::~Thread()
{
	if (IsRunning())
		Stop();

}

void Thread::Start()
{
	m_IsRunning = true;
	if (pthread_create(&m_thread, NULL, RunInternal, this) != 0)
		abort();
}

void Thread::Stop()
{
#ifdef DEBUG
	if (IsDetached() == true)
		abort();

	if (m_IsRunning == false)
	{
		abort();	//Attempted to stop an already stopped thread
	}
#endif
	if (pthread_join(m_thread, NULL) != 0)
		abort();
	m_IsRunning = false;
}

void Thread::Detach()
{
	if (pthread_detach(m_thread) != 0)
		abort();
	m_IsDetached = true;
}

bool Thread::IsRunning()
{
	return m_IsRunning;
}

bool Thread::IsDetached()
{
	return m_IsDetached;
}

void Thread::Run()
{
	abort();	//You should override this function
}

void *Thread::RunInternal(void *ptr)
{
	class Thread *self = (Thread *) ptr;
	self->Run();
	return NULL;
}

Fix State Tracking when thread stops

Fix State Tracking when thread stops


#include "hotkey.h"
#include "ui_hotkey.h"

hotkey::hotkey(QWidget *parent) :
    s(s),
    QWidget(parent),
    ui(new Ui::hotkey)
{
    ui->setupUi(this);
}

hotkey::~hotkey()
{
    delete ui;
}

void hotkey::keyPressEvent(QKeyEvent *event)
{
    int uKey = event->key();
    Qt::Key key = static_cast<Qt::Key>(uKey);
    if(key == Qt::Key_unknown)
    {
       return;
    }
    if(key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Alt )
    {
        return ;
    }
    Qt::KeyboardModifiers modifiers = event->modifiers();
    if(modifiers & Qt::ShiftModifier)
        uKey += Qt::SHIFT;
    if(modifiers & Qt::ControlModifier)
        uKey += Qt::CTRL;
    if(modifiers & Qt::AltModifier)
        uKey += Qt::ALT;
    ui->label_2->setText(QKeySequence(uKey).toString());
    this->s->setText(QKeySequence(uKey).toString());
}

void hotkey::keyReleaseEvent(QKeyEvent *event)
{
    this->~hotkey();
}

#include "hotkey.h"
#include "ui_hotkey.h"

hotkey::hotkey(QWidget *parent) :
    s(s),
    QWidget(parent),
    ui(new Ui::hotkey)
{
    ui->setupUi(this);
}

hotkey::~hotkey()
{
    delete ui;
}

void hotkey::keyPressEvent(QKeyEvent *event)
{
    int uKey = event->key();
    Qt::Key key = static_cast<Qt::Key>(uKey);
    if(key == Qt::Key_unknown)
    {
       return;
    }
    if(key == Qt::Key_Control || key == Qt::Key_Shift || key == Qt::Key_Alt || key == Qt::Key_Meta)
    {
        return ;
    }
    Qt::KeyboardModifiers modifiers = event->modifiers();
    if(modifiers & Qt::ShiftModifier)
        uKey += Qt::SHIFT;
    if(modifiers & Qt::ControlModifier)
        uKey += Qt::CTRL;
    if(modifiers & Qt::AltModifier)
        uKey += Qt::ALT;
    if(modifiers & Qt::MetaModifier)
        uKey += Qt::META;
    ui->label_2->setText(QKeySequence(uKey).toString());
    this->s->setText(QKeySequence(uKey).toString());
}

void hotkey::keyReleaseEvent(QKeyEvent *event)
{
    this->~hotkey();
}

Allow meta key to be shortcut assigned

Allow meta key to be shortcut assigned

This follows the pattern that's already in place for assigning hotkeys.
I simply added the Qt binding for the meta key and now you can assign
meta hot keys!


#include "box.hpp"

Box::Box(): // default constructor
        min_{0.0, 0.0, 0.0},
        max_{0.0, 0.0, 0.0}
        {}

Box::Box(Box const& b): // copy constructor
        min_{b.min_},
        max_{b.max_}
        {}

Box::Box(Box&& b): // move constructor
        Box()
        {
                swap(*this, b);
        }

Box::Box(glm::vec3 const& min, glm::vec3 const& max):
        min_{min},
        max_{max}
        {}

void Box::swap(Box & b1, Box & b2) {
        std::swap(b1.min_, b2.min_);
        std::swap(b1.max_, b2.max_);
}

glm::vec3 Box::getMin() const {
        return min_;
}

glm::vec3 Box::getMax() const {
        return max_;
}

/* virtual */ double area() const {
        return 0.0;
}

/* virtual */ double volume() const {
        return 0.0;
}

Add dummy area and volume methods.

Add dummy area and volume methods.


/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2012 Sandro Santilli <strk@keybit.net>
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/util/Interrupt.h>
#include <geos/util/GEOSException.h> // for inheritance

namespace geos {
namespace util { // geos::util

class GEOS_DLL InterruptedException: public GEOSException {
public:
	InterruptedException() :
		GEOSException("InterruptedException", "Interrupted!") {}
};

void
Interrupt::interrupt() { throw InterruptedException(); }

bool Interrupt::requested = false;
Interrupt::Callback *Interrupt::callback = 0;
void *Interrupt::callback_arg = 0;

} // namespace geos::util
} // namespace geos

/**********************************************************************
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.osgeo.org
 *
 * Copyright (C) 2012 Sandro Santilli <strk@keybit.net>
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************/

#include <geos/util/Interrupt.h>
#include <geos/util/GEOSException.h> // for inheritance

namespace geos {
namespace util { // geos::util

class GEOS_DLL InterruptedException: public GEOSException {
public:
	InterruptedException() :
		GEOSException("InterruptedException", "Interrupted!") {}
};

void
Interrupt::interrupt() {
  requested = false;
  throw InterruptedException();
}

bool Interrupt::requested = false;
Interrupt::Callback *Interrupt::callback = 0;
void *Interrupt::callback_arg = 0;

} // namespace geos::util
} // namespace geos

Clear interruption request flag just before interrupting

git-svn-id: 6c2b1bd10c324c49ea9d9e6e31006a80e70507cb@3670 5242fede-7e19-0410-aef8-94bd7d2200fb


Add a beter commit message

TODO: Add a beter commit message


Put the thingie in the thingie

Put the thingie in the thingie


#include <X11/keysym.h>

#include "grid.hpp"
#include "thumbnail_manager.hpp"
#include "x_connection.hpp"
#include "x_client_chooser.hpp"
#include "x_client_thumbnail_gl.hpp"

int main(int argc, char ** argv)
{
  xcb_keysym_t east_key = XK_l;
  xcb_keysym_t west_key = XK_h;
  xcb_keysym_t north_key = XK_k;
  xcb_keysym_t south_key = XK_j;
  xcb_keysym_t quit_key = XK_Escape;
  xcb_keysym_t action_key = XK_Tab;
  xcb_mod_mask_t mod = XCB_MOD_MASK_1;

  x_connection c;

  grid_t grid;

  x_client_thumbnail::factory factory;

  thumbnail_manager tm(c, &grid, &factory);
  x_client_chooser cp(c, &tm,
                      east_key, west_key, north_key, south_key,
                      quit_key, action_key, mod);

  c.run_event_loop();

  return 0;
}

#include <signal.h>
#include <X11/keysym.h>

#include "grid.hpp"
#include "thumbnail_manager.hpp"
#include "x_connection.hpp"
#include "x_client_chooser.hpp"
#include "x_client_thumbnail_gl.hpp"

x_event_source_t * g_event_source = NULL;

void sig_handler(int signum)
{
  if (g_event_source) g_event_source->shutdown();
}

int main(int argc, char ** argv)
{
  xcb_keysym_t east_key = XK_l;
  xcb_keysym_t west_key = XK_h;
  xcb_keysym_t north_key = XK_k;
  xcb_keysym_t south_key = XK_j;
  xcb_keysym_t quit_key = XK_Escape;
  xcb_keysym_t action_key = XK_Tab;
  xcb_mod_mask_t mod = XCB_MOD_MASK_1;

  x_connection c;
  g_event_source = &c;

  signal(SIGINT,  sig_handler);
  signal(SIGTERM, sig_handler);

  grid_t grid;

  x_client_thumbnail::factory factory;

  thumbnail_manager tm(c, &grid, &factory);
  x_client_chooser cp(c, &tm,
                      east_key, west_key, north_key, south_key,
                      quit_key, action_key, mod);

  c.run_event_loop();

  return 0;
}

Implement a simple signal handler

Implement a simple signal handler


// Solution to the TwoSum problem from LeetCode
#include "two_sum.h"

TwoSum::TwoSum() {

}

vector<int> TwoSum::solver(vector<int>& nums, int target) {
  for(int i=0; i<nums.size(); i++) {
    for(int j=0; j<nums.size(); j++) {
      int value = nums[i] + nums[j];

      if ((value == target) && (i != j)) { // Return if value equals target
        vector<int> return_vector = {i,j};
        return return_vector;
      }
    }
  }
  return {-1, -1};
}

// Run Basic test cases on solver
bool TwoSum::test_case() {
  vector<int> test_vector = {3,2,4};
  vector<int> result = solver(test_vector, 6);
  if (result[0] == 1 && result[1] == 2)
    return true;
  else
    return false;
}

// Solution to the TwoSum problem from LeetCode
#include "two_sum.h"

TwoSum::TwoSum() {

}

vector<int> TwoSum::solver(vector<int>& nums, int target) {
  for(int i=0; i<nums.size(); i++) {
    for(int j=0; j<nums.size(); j++) {
      int sum = nums[i] + nums[j];

      if ((sum == target) && (i != j)) { // Return if sum equals target
        vector<int> return_vector = {i,j};
        return return_vector;
      }
    }
  }
  return {-1, -1};
}

// Run Basic test cases on solver
bool TwoSum::test_case() {
  vector<int> test_vector = {3,2,4};
  vector<int> result = solver(test_vector, 6);
  if (result[0] == 1 && result[1] == 2)
    return true;
  else
    return false;
}

Rename variable value to sum

Rename variable value to sum


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

#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

#include <mock_vector>
vector v;

Set '-target' flag in the test checking the MacOS include dir

To fix a buildbot failure on PS4, see
http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/builds/42251

The test was added in r351222 and aims to check only a particular
Mac configuration. However it relied on the default compiler target
by default, therefore unintentionally failing on PS4.

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


#include "logger.h"

Logger::Level Logger::logLevel = Logger::Level::ERROR;

void Logger::Error(std::string msg) {
	std::cerr << "[Error]: " << msg.c_str() << std::endl;
}

void Logger::Warn(std::string msg) {
	if (Logger::logLevel >= Logger::Level::WARN) {
		std::cout << "[Warn]: " << msg.c_str() << std::endl;
	}
}

void Logger::Info(std::string msg) {
	if (Logger::logLevel >= Logger::Level::INFO) {
		std::cout << "[Info]: " << msg.c_str() << std::endl;
	}
}

void Logger::Debug(std::string msg) {
	if (Logger::logLevel == Logger::Level::DEBUG) {
		std::cout << "[Debug]: " << msg.c_str() << std::endl;
	}
}

#include "logger.h"

Logger::Level Logger::logLevel = Logger::Level::WARN;

void Logger::Error(std::string msg) {
	std::cerr << "[Error]: " << msg.c_str() << std::endl;
}

void Logger::Warn(std::string msg) {
	if (Logger::logLevel >= Logger::Level::WARN) {
		std::cout << "[Warn]: " << msg.c_str() << std::endl;
	}
}

void Logger::Info(std::string msg) {
	if (Logger::logLevel >= Logger::Level::INFO) {
		std::cout << "[Info]: " << msg.c_str() << std::endl;
	}
}

void Logger::Debug(std::string msg) {
	if (Logger::logLevel == Logger::Level::DEBUG) {
		std::cout << "[Debug]: " << msg.c_str() << std::endl;
	}
}

Change default log level to WARN

Change default log level to WARN


/*
 * Copyright (c) 1998-2005, Index Data.
 * See the file LICENSE for details.
 *
 * $Id: tstquery.cpp,v 1.2 2006-03-29 13:14:15 adam Exp $
 */

#include <stdlib.h>
#include <yazpp/z-query.h>

using namespace yazpp_1;

void tst1(const char *query_str_in, const char *query_expected)
{
    Yaz_Z_Query q;

    q = query_str_in;

    Yaz_Z_Query q2;

    q2 = q;

    char query_str_out[100];
    q2.print(query_str_out, sizeof(query_str_out)-1);

    if (strcmp(query_str_out, query_expected))
    {
	fprintf(stderr, "tstquery: query mismatch out=%s expected=%s\n",
		query_str_out, query_expected);
	exit(1);
    }
}

int main(int argc, char **argv)
{
    tst1("", "");
    tst1("x", "RPN: @attrset Bib-1 x");
    tst1("@and a b", "RPN: @attrset Bib-1 @and a b");
}

/*
 * Local variables:
 * c-basic-offset: 4
 * indent-tabs-mode: nil
 * End:
 * vim: shiftwidth=4 tabstop=8 expandtab
 */

/*
 * Copyright (c) 1998-2006, Index Data.
 * See the file LICENSE for details.
 *
 * $Id: tstquery.cpp,v 1.3 2006-07-07 12:57:15 adam Exp $
 */

#include <stdlib.h>
#include <yazpp/z-query.h>

using namespace yazpp_1;

void tst1(const char *query_str_in, const char *query_expected)
{
    Yaz_Z_Query q;

    q = query_str_in;

    Yaz_Z_Query q2;

    q2 = q;

    char query_str_out[100];
    q2.print(query_str_out, sizeof(query_str_out)-1);

    if (strcmp(query_str_out, query_expected))
    {
	fprintf(stderr, "tstquery: query mismatch out=%s expected=%s\n",
		query_str_out, query_expected);
	exit(1);
    }
}

int main(int argc, char **argv)
{
    tst1("", "");
    tst1("x", "RPN @attrset Bib-1 x");
    tst1("@and a b", "RPN @attrset Bib-1 @and a b");
}

/*
 * Local variables:
 * c-basic-offset: 4
 * indent-tabs-mode: nil
 * End:
 * vim: shiftwidth=4 tabstop=8 expandtab
 */

Update test becuase yaz_query_to_wrbuf now omits : before query type in string output.


#include "board.hpp"
#include "gtest/gtest.h"

class BoardTest : public ::testing::Test {
protected:
    BoardTest() : board_(1, 2) {
    }
    virtual ~BoardTest() {
    }

    virtual void SetUp() {
    }

    Quoridor::Board board_;
};

TEST_F(BoardTest, set_size)
{
    board_.set_size(10, 11);
    EXPECT_EQ(10, board_.row_num());
    EXPECT_EQ(11, board_.col_num());
}

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

#include "board.hpp"
#include "exception.hpp"
#include "gtest/gtest.h"

class BoardTest : public ::testing::Test {
protected:
    BoardTest() : board_(1, 2) {
    }

    Quoridor::Board board_;
};

TEST_F(BoardTest, ctor)
{
    EXPECT_EQ(1, board_.row_num());
    EXPECT_EQ(2, board_.col_num());
    // test invalid Board construction
    EXPECT_THROW(Quoridor::Board(-1, 1), Quoridor::Exception);
    EXPECT_THROW(Quoridor::Board(8, 0), Quoridor::Exception);
}

TEST_F(BoardTest, set_size)
{
    // test invalid Board sizes
    EXPECT_THROW(board_.set_size(0, 0), Quoridor::Exception);
    EXPECT_THROW(board_.set_size(0, 1), Quoridor::Exception);
    EXPECT_THROW(board_.set_size(1, 0), Quoridor::Exception);
    EXPECT_THROW(board_.set_size(-1, -1), Quoridor::Exception);
    EXPECT_THROW(board_.set_size(-1, 1), Quoridor::Exception);
    EXPECT_THROW(board_.set_size(1, -1), Quoridor::Exception);

    board_.set_size(10, 11);
    EXPECT_EQ(10, board_.row_num());
    EXPECT_EQ(11, board_.col_num());
}

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

Add failure tests into Board unittests.

Add failure tests into Board unittests.


/*
 * ============================================================================
 *       Filename:  server_main.cc
 *    Description:  Server main for testing
 *        Version:  1.0
 *        Created:  04/25/2015 06:37:53 PM
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  Rafael Gozlan, rafael.gozlan@epita.fr
 *   Organization:  Flihabi
 * ============================================================================
 */
#include <stdlib.h>
#include <unistd.h>

#include "server.hh"

#define NB_TESTS 10

int main()
{
    Server *s = new Server();
    int ids[NB_TESTS];
    for (int i = 0; i < NB_TESTS; ++i)
        ids[i] = s->execBytecode("This is some bytecode");
    Result *r;
    for (int i = 0; i < NB_TESTS; ++i)
    {
        while ((r = s->getResult(ids[i])) == NULL)
        {
            std::cout << "Server: Waiting for result";
            sleep(1);
        }
        std::cout << "Server received: " << r->value << std::endl;
    }
}

/*
 * ============================================================================
 *       Filename:  server_main.cc
 *    Description:  Server main for testing
 *        Version:  1.0
 *        Created:  04/25/2015 06:37:53 PM
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  Rafael Gozlan, rafael.gozlan@epita.fr
 *   Organization:  Flihabi
 * ============================================================================
 */
#include <stdlib.h>
#include <unistd.h>

#include "server.hh"

#define NB_TESTS 10

int main()
{
    Server *s = new Server();
    int ids[NB_TESTS];
    std::string string = "This is some bytecode";
    string += '\0';
    string += "This is something else";
    for (int i = 0; i < NB_TESTS; ++i)
        ids[i] = s->execBytecode(string);
    Result *r;
    for (int i = 0; i < NB_TESTS; ++i)
    {
        while ((r = s->getResult(ids[i])) == NULL)
        {
            std::cout << "Server: Waiting for result";
            sleep(1);
        }
        std::cout << "Server received: " << r->value << std::endl;
    }
}

Add stronger test for server

Testing: Add stronger test for server


// FIXME: Disabled, appears to have undefined behavior, and needs to be updated to match new warnings.
// RUN: clang-cc -fsyntax-only -verify %s
// XFAIL: *

namespace A {
    int VA;
    void FA() {}
    struct SA { int V; };
}

using A::VA;
using A::FA;
using typename A::SA;

void main()
{
    VA = 1;
    FA();
    SA x;   //Still needs handling.
}

struct B {
    void f(char){};
    void g(char){};
};
struct D : B {
    using B::f;
    void f(int);
    void g(int);
};
void D::f(int) { f('c'); } // calls B::f(char)
void D::g(int) { g('c'); } // recursively calls D::g(int)

namespace E {
    template <typename TYPE> int funcE(TYPE arg) { return(arg); }
}

using E::funcE<int>; // expected-error{{use of template specialization in using directive not allowed}}

namespace F {
    struct X;
}

using F::X;
// Should have some errors here.  Waiting for implementation.
void X(int);
struct X *x;

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

namespace A {
    int VA;
    void FA() {}
    struct SA { int V; };
}

using A::VA;
using A::FA;
using typename A::SA;

int main()
{
    VA = 1;
    FA();
    SA x;   //Still needs handling.
}

struct B {
    void f(char){};
    void g(char){};
};
struct D : B {
    using B::f;
    void f(int);
    void g(int);
};
void D::f(int) { f('c'); } // calls B::f(char)
void D::g(int) { g('c'); } // recursively calls D::g(int)

namespace E {
    template <typename TYPE> int funcE(TYPE arg) { return(arg); }
}

using E::funcE<int>; // expected-error{{using declaration can not refer to a template specialization}}

namespace F {
    struct X;
}

using F::X;
// Should have some errors here.  Waiting for implementation.
void X(int);
struct X *x;

Tweak expected error to match what should happen, once using declarations work

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


#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"
#include "transaction.h"
#include "internal/operations/post_operation.h"
#include "dummy_values.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(pushOperationToTransaction) {
		Transaction sut;
		Internal::PostOperation postOp(0, task1);
		sut.push(std::shared_ptr<Internal::IOperation>(&postOp));
	}
};

}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You

#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"
#include "transaction.h"
#include "internal/operations/post_operation.h"
#include "dummy_values.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(pushOperationToTransaction) {
		Transaction sut;
		Internal::PostOperation postOp(0, task1);
		sut.push(std::shared_ptr<Internal::IOperation>(&postOp));
		Assert::AreEqual(boost::lexical_cast<size_t>(1), sut.operationsQueue.size());
	}
};

}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You

Add assert statement for unit test

Add assert statement for unit test


//===- llvm/unittest/IR/AttributesTest.cpp - Attributes unit tests --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Attributes.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"
using namespace llvm;

namespace {

TEST(Attributes, Uniquing) {
  LLVMContext C;

  Attribute AttrA = Attribute::get(C, Attribute::AlwaysInline);
  Attribute AttrB = Attribute::get(C, Attribute::AlwaysInline);
  EXPECT_EQ(AttrA, AttrB);

  AttributeWithIndex AWIs[] = {
    AttributeWithIndex::get(C, 1, Attribute::ZExt),
    AttributeWithIndex::get(C, 2, Attribute::SExt)
  };

  AttributeSet SetA = AttributeSet::get(C, AWIs);
  AttributeSet SetB = AttributeSet::get(C, AWIs);
  EXPECT_EQ(SetA, SetB);
}

} // end anonymous namespace

//===- llvm/unittest/IR/AttributesTest.cpp - Attributes unit tests --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Attributes.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"
using namespace llvm;

namespace {

TEST(Attributes, Uniquing) {
  LLVMContext C;

  Attribute AttrA = Attribute::get(C, Attribute::AlwaysInline);
  Attribute AttrB = Attribute::get(C, Attribute::AlwaysInline);
  EXPECT_EQ(AttrA, AttrB);

  AttributeSet ASs[] = {
    AttributeSet::get(C, 1, Attribute::ZExt),
    AttributeSet::get(C, 2, Attribute::SExt)
  };

  AttributeSet SetA = AttributeSet::get(C, ASs);
  AttributeSet SetB = AttributeSet::get(C, ASs);
  EXPECT_EQ(SetA, SetB);
}

} // end anonymous namespace

Fix test to not use the AttributeSet's AttributeWithIndex creation method.

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


/**
 * Tests of str_rope and rope_node.
 *
 * @author Jean-Claude Paquin
 **/

#include <catch.hpp>
#include <primitives/str_rope.h>

TEST_CASE("Empty rope_node", "[rope_node]") {
    std::unique_ptr<rope_node> node = std::make_unique<rope_node>();

    SECTION("Empty node has nullptr left & right") {
        REQUIRE(!node->data.left);
        REQUIRE(!node->data.right);
    }

    SECTION("Empty node to string") {
        REQUIRE(*node->to_string().get() == "");
    }
}

TEST_CASE("String rope_node", "[rope_node]") {
    std::unique_ptr<rope_node> node = std::make_unique<rope_node>(std::string("wow!"));
}

TEST_CASE("Copy constructor for rope_node", "[rope_node]") {
    std::unique_ptr<rope_node> node = std::make_unique<rope_node>(std::string("that's a low price!"));

    std::unique_ptr<rope_node> dupl = std::make_unique<rope_node>(*node.get());

    REQUIRE(*dupl->to_string().get() == *node->to_string().get());
}

/**
 * Tests of str_rope and rope_node.
 *
 * @author Jean-Claude Paquin
 **/

#include <catch.hpp>
#include <primitives/str_rope.h>

TEST_CASE("Empty rope_node", "[rope_node]") {
    std::unique_ptr<rope_node> node = std::make_unique<rope_node>();

    SECTION("Empty node has nullptr left & right") {
        REQUIRE(!node->data.left);
        REQUIRE(!node->data.right);
    }

    SECTION("Empty node to string") {
        REQUIRE(*node->to_string().get() == "");
    }

    SECTION("Empty node is not a leaf") {
        REQUIRE(!node->is_leaf);
    }
}

TEST_CASE("String rope_node", "[rope_node]") {
    std::unique_ptr<rope_node> node = std::make_unique<rope_node>(std::string("wow!"));

    SECTION("String node is a leaf") {
        REQUIRE(node->is_leaf);
    }
}

TEST_CASE("Copy constructor for rope_node", "[rope_node]") {
    SECTION("Copied node is a leaf node") {
        std::unique_ptr<rope_node> node = std::make_unique<rope_node>(std::string("that's a low price!"));

        std::unique_ptr<rope_node> dupl = std::make_unique<rope_node>(*node.get());

        REQUIRE(*dupl->to_string().get() == *node->to_string().get());
        REQUIRE(dupl->is_leaf);
    }

    SECTION("Copied node is not a leaf node") {
        rope_node node;
        rope_node dupl(node);

        REQUIRE(!dupl.is_leaf);
    }
}

Add more tests for rope_node

Add more tests for rope_node


// RUN: %clang_cc1 -g -S -masm-verbose -o - %s | FileCheck %s

// CHECK: abbrev_begin:
// CHECK: DW_AT_accessibility
// CHECK-NEXT: DW_FORM_data1

class A {
public:
  int p;
private:
  int pr;
};

A a;

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

// CHECK: [ DW_TAG_member ] [p] [{{[^]]*}}] [from int]
// CHECK: [ DW_TAG_member ] [pr] [{{[^]]*}}] [private] [from int]

class A {
public:
  int p;
private:
  int pr;
};

A a;

Fix test case due to r196394 and improve it to not rely on LLVM code generation either.

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


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

#include <iostream>

int main() {
  int i;
  std::cout << "Type i: ";
  std::cin >> i;
  return 0;
// CHECK: Type i:
// CHECK-NOT: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]]
}

// First, check this works with the default blacklist:
// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: echo "42" | %run %t 2>&1 | FileCheck %s
//
// Then, make sure it still works when a user uses his own blacklist file:
// RUN: %clang_cl_asan -O0 %s -fsanitize-blacklist=%p/../Helpers/initialization-blacklist.txt -Fe%t2
// RUN: echo "42" | %run %t2 2>&1 | FileCheck %s

#include <iostream>

int main() {
  int i;
  std::cout << "Type i: ";
  std::cin >> i;
  return 0;
// CHECK: Type i:
// CHECK-NOT: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]]
}

Add a test case for PR22431

[ASan/Win] Add a test case for PR22431

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


#include <ionCore.h>
#include <catch.hpp>

TEST_CASE("ionStandardLibrary::String::Build")
{
	REQUIRE(String::Build("") == string());
	REQUIRE(String::Build("Test") == "Test");
	REQUIRE(String::Build("Hello %d", 123) == "Hello 123");
	REQUIRE(String::Build("%c %d %X %s", 'a', 42, 0xABCD, "foo") == "a 42 ABCD foo");
}

#include <ionCore.h>
#include <catch.hpp>

TEST_CASE("ionStandardLibrary::ConditionalMapAccess")
{
	map<int, int *> Test;
	REQUIRE(! ConditionalMapAccess(Test, 0));
	REQUIRE(! ConditionalMapAccess(Test, 1));
	REQUIRE(! ConditionalMapAccess(Test, 2));

	int X, Y;

	Test[0] = & X;
	Test[1] = & Y;
	Test[2] = & Y;
	REQUIRE(! ConditionalMapAccess(Test, -1));
	REQUIRE(& X == ConditionalMapAccess(Test, 0));
	REQUIRE(& Y == ConditionalMapAccess(Test, 1));
	REQUIRE(& Y == ConditionalMapAccess(Test, 2));
	REQUIRE(! ConditionalMapAccess(Test, 3));
	REQUIRE(! ConditionalMapAccess(Test, 4));
}

TEST_CASE("ionStandardLibrary::String::Build")
{
	REQUIRE(String::Build("") == string());
	REQUIRE(String::Build("Test") == "Test");
	REQUIRE(String::Build("Hello %d", 123) == "Hello 123");
	REQUIRE(String::Build("%c %d %X %s", 'a', 42, 0xABCD, "foo") == "a 42 ABCD foo");
}

Add Conditional Map Access test

Add Conditional Map Access test


#include "ButtonEntity.h"

ButtonEntity::ButtonEntity()
{
}

ButtonEntity::~ButtonEntity()
{
}

int ButtonEntity::Update(float dT, InputHandler * inputHandler)
{
	int result = 0;
	return result;
}

int ButtonEntity::React(int entityID, EVENT reactEvent)
{
	int result = 0;
	return result;
}

int ButtonEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp)
{
	int result = 0;
	return result;
}

#include "ButtonEntity.h"

ButtonEntity::ButtonEntity()
{
}

ButtonEntity::~ButtonEntity()
{
}

int ButtonEntity::Update(float dT, InputHandler * inputHandler)
{
	int result = 0;
	return result;
}

int ButtonEntity::React(int entityID, EVENT reactEvent)
{
	int result = 0;
	return result;
}

int ButtonEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp)
{
	int result = 0;
	this->InitializeBase(entityID, pComp, gComp);
	return result;
}

UPDATE Initialize now calls InitializeBase as expected


#include "protect.hpp"
#include "../Exception.hpp"
#include "../Jump_Tag.hpp"

#ifndef TAG_RAISE
#define TAG_RAISE 0x6
#endif

VALUE Rice::detail::
protect(
    RUBY_VALUE_FUNC f,
    VALUE arg)
{
  int state = 0;
  VALUE retval = rb_protect(f, arg, &state);
  if(state != 0)
  {
    if(state == TAG_RAISE && ruby_errinfo != Qnil)
    {
      // TODO: convert NoMemoryError into bad_alloc?
      throw Rice::Exception(ruby_errinfo);
    }
    throw Jump_Tag(state);
  }
  return retval;
}

#include "protect.hpp"
#include "../Exception.hpp"
#include "../Jump_Tag.hpp"

#ifndef TAG_RAISE
#define TAG_RAISE 0x6
#endif

VALUE Rice::detail::
protect(
    RUBY_VALUE_FUNC f,
    VALUE arg)
{
  int state = 0;
  VALUE retval = rb_protect(f, arg, &state);
  if(state != 0)
  {
    if(state == TAG_RAISE && RTEST(ruby_errinfo))
    {
      // TODO: convert NoMemoryError into bad_alloc?
      VALUE err = ruby_errinfo;
      ruby_errinfo = 0;
      throw Rice::Exception(err);
    }
    throw Jump_Tag(state);
  }
  return retval;
}

Reset ruby_errinfo when catching exceptions, otherwise exceptions can strangely be resurrected.


#include "vsteventkeeper.h"

#include <cstdint>

namespace Airwave {

VstEventKeeper::VstEventKeeper() :
	events_(nullptr),
	data_(nullptr)
{
}

VstEventKeeper::~VstEventKeeper()
{
	delete [] events_;
}

void VstEventKeeper::reload(int count, const VstEvent events[])
{
	if(!events_ || events_->numEvents < count) {
		delete [] events_;

		size_t size = sizeof(VstEvents) + count * (sizeof(VstEvent*) +
				sizeof(VstEvent));

		uint8_t* buffer = new uint8_t[size];
		events_ = reinterpret_cast<VstEvents*>(buffer);

		size_t offset = sizeof(VstEvents) + count * sizeof(VstEvent*);
		data_ = reinterpret_cast<VstEvent*>(buffer + offset);
	}

	events_->numEvents = count;
	events_->reserved = 0;

	for(int i = 0; i < count; ++i) {
		data_[i] = events[i];
		events_->events[i] = &data_[i];
	}
}

VstEvents* VstEventKeeper::events()
{
	return events_;
}

} // namespace Airwave

#include "vsteventkeeper.h"

#include <algorithm>
#include <cstdint>

namespace Airwave {

VstEventKeeper::VstEventKeeper() :
	events_(nullptr),
	data_(nullptr)
{
}

VstEventKeeper::~VstEventKeeper()
{
	delete [] events_;
}

void VstEventKeeper::reload(int count, const VstEvent events[])
{
	if(!events_ || events_->numEvents < count) {
		delete [] events_;

		int extraCount = std::max(count - 2, 0);

		size_t size = sizeof(VstEvents) + extraCount * sizeof(VstEvent*) +
				count * sizeof(VstEvent);

		uint8_t* buffer = new uint8_t[size];
		events_ = reinterpret_cast<VstEvents*>(buffer);

		size_t offset = sizeof(VstEvents) + extraCount * sizeof(VstEvent*);
		data_ = reinterpret_cast<VstEvent*>(buffer + offset);
	}

	events_->numEvents = count;
	events_->reserved = 0;

	for(int i = 0; i < count; ++i) {
		data_[i] = events[i];
		events_->events[i] = &data_[i];
	}
}

VstEvents* VstEventKeeper::events()
{
	return events_;
}

} // namespace Airwave

Fix buffer size and memory offset calculations in VstEventKeeper


#include "configuration.h"
#include "AboutDialog.h"
#include "ui_AboutDialog.h"

#define define2string_p(x) #x
#define define2string(x) define2string_p(x)

AboutDialog::AboutDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AboutDialog)
{
    ui->setupUi(this);
    connect(ui->okButton, SIGNAL(clicked()), this, SLOT(accept()));

    ui->appnameLabel->setText(tr("%1 %2").arg(QGC_APPLICATION_NAME).arg(QGC_APPLICATION_VERSION));
    QString hash = QString(define2string(GIT_HASH));
    hash.truncate(8);
    ui->versionLabel->setText(tr("(%1-%2)").arg(hash)
                               .arg(define2string(GIT_COMMIT)));
}

AboutDialog::~AboutDialog()
{
    delete ui;
}

#include "configuration.h"
#include "AboutDialog.h"
#include "ui_AboutDialog.h"

#define define2string_p(x) #x
#define define2string(x) define2string_p(x)

AboutDialog::AboutDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AboutDialog)
{
    ui->setupUi(this);
    connect(ui->okButton, SIGNAL(clicked()), this, SLOT(accept()));

    ui->appnameLabel->setText(tr("%1 %2").arg(QGC_APPLICATION_NAME).arg(QGC_APPLICATION_VERSION));
    QString hash = QString(define2string(GIT_HASH));
    hash.truncate(8);
    ui->versionLabel->setText(tr("(%1-%2)").arg(hash)
                               .arg(define2string(GIT_COMMIT)));
    ui->linkLabel->setOpenExternalLinks(true);
}

AboutDialog::~AboutDialog()
{
    delete ui;
}

Enable http link in about box to launch system web browser


// Copyright (c) 2020-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <tinyformat.h>
#include <util/syserror.h>

#include <cstring>

std::string SysErrorString(int err)
{
    char buf[256];
    /* Too bad there are three incompatible implementations of the
     * thread-safe strerror. */
    const char *s = nullptr;
#ifdef WIN32
    if (strerror_s(buf, sizeof(buf), err) == 0) s = buf;
#else
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
    s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
    if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf;
#endif
#endif
    if (s != nullptr) {
        return strprintf("%s (%d)", s, err);
    } else {
        return strprintf("Unknown error (%d)", err);
    }
}

// Copyright (c) 2020-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <tinyformat.h>
#include <util/syserror.h>

#include <cstring>

std::string SysErrorString(int err)
{
    char buf[1024];
    /* Too bad there are three incompatible implementations of the
     * thread-safe strerror. */
    const char *s = nullptr;
#ifdef WIN32
    if (strerror_s(buf, sizeof(buf), err) == 0) s = buf;
#else
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
    s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
    if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf;
#endif
#endif
    if (s != nullptr) {
        return strprintf("%s (%d)", s, err);
    } else {
        return strprintf("Unknown error (%d)", err);
    }
}

util: Increase buffer size to 1024 in SysErrorString

Increase the error message buffer to 1024 as recommended in the manual
page (Thanks Jon Atack)


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

#include "llvm/MC/MCSchedule.h"

using namespace llvm;

static_assert(std::is_pod<MCSchedModel>::value,
              "We shouldn't have a static constructor here");
const MCSchedModel MCSchedModel::Default = {DefaultIssueWidth,
                                            DefaultMicroOpBufferSize,
                                            DefaultLoopMicroOpBufferSize,
                                            DefaultLoadLatency,
                                            DefaultHighLatency,
                                            DefaultMispredictPenalty,
                                            false,
                                            true,
                                            0,
                                            nullptr,
                                            nullptr,
                                            0,
                                            0,
                                            nullptr};

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

#include "llvm/MC/MCSchedule.h"
#include <type_traits>

using namespace llvm;

static_assert(std::is_pod<MCSchedModel>::value,
              "We shouldn't have a static constructor here");
const MCSchedModel MCSchedModel::Default = {DefaultIssueWidth,
                                            DefaultMicroOpBufferSize,
                                            DefaultLoopMicroOpBufferSize,
                                            DefaultLoadLatency,
                                            DefaultHighLatency,
                                            DefaultMispredictPenalty,
                                            false,
                                            true,
                                            0,
                                            nullptr,
                                            nullptr,
                                            0,
                                            0,
                                            nullptr};

Add <type_traits> for is_pod, fixing r241947

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


#include "builtin/class.hpp"
#include "builtin/atomic.hpp"
#include "ontology.hpp"

namespace rubinius {
  void AtomicReference::init(STATE) {
    GO(atomic_ref).set(ontology::new_class(state,
          "AtomicReference", G(object), G(rubinius)));

    G(atomic_ref)->set_object_type(state, AtomicReferenceType);
  }

  AtomicReference* AtomicReference::allocate(STATE) {
    return state->new_object<AtomicReference>(G(atomic_ref));
  }

  Object* AtomicReference::compare_and_set(STATE, Object* old, Object* new_) {
    Object** pp = &value_;
    return atomic::compare_and_swap((void**)pp, old, new_) ? cTrue : cFalse;
  }
}

#include "builtin/class.hpp"
#include "builtin/atomic.hpp"
#include "ontology.hpp"

namespace rubinius {
  void AtomicReference::init(STATE) {
    GO(atomic_ref).set(ontology::new_class(state,
          "AtomicReference", G(object), G(rubinius)));

    G(atomic_ref)->set_object_type(state, AtomicReferenceType);
  }

  AtomicReference* AtomicReference::allocate(STATE) {
    return state->new_object<AtomicReference>(G(atomic_ref));
  }

  Object* AtomicReference::compare_and_set(STATE, Object* old, Object* new_) {
    Object** pp = &value_;

    if (atomic::compare_and_swap((void**)pp, old, new_)) {
      if(mature_object_p()) this->write_barrier(state, new_);
      return cTrue;
    } else {
      return cFalse;
    }
  }
}

Fix GC-related SEGV when heavily using AtomicReference


#include <stdio.h>

#define MAX_LOOP    10000

double formula(const double x, const double k)
{
    return (x * x) / ((2 * k - 1) * (2 * k));
}

int main(void)
{
    double x;
    printf("Enter x= ");
    scanf("%lf", &x);

    double cosx = 1,
           sinx = x;

    int k = 2;
    while(k < MAX_LOOP)
    {
        cosx = cosx - cosx * formula(x, k++);
        sinx = sinx - sinx * formula(x, k++);
        cosx = cosx + cosx * formula(x, k++);
        sinx = sinx + sinx * formula(x, k++);
    }

    printf("Result is: cosx=%f sinx=%f\n", cosx, sinx);

    return 0;
}

#include <stdio.h>

#define MAX_LOOP    100

double cosine_formula(const double x, const double k)
{
    if(k == 0) return 1;
    return (x * x) / ((2 * k - 1) * (2 * k));
}

double sine_formula(const double x, const double k)
{
    if(k == 0) return x;
    return (x * x) / ((2 * k) * (2 * k + 1));
}

int main(void)
{
    double x;
    printf("Enter x= ");
    scanf("%lf", &x);

    double cosx = 0, sinx = 0;

    {
        double cosx_cache = 1, sinx_cache = 1;
        for(int k = 0; k < MAX_LOOP; ++k)
        {
            cosx_cache *= cosine_formula(x, k);
            (k % 2 == 0) ? cosx += cosx_cache : cosx -= cosx_cache;

            sinx_cache *= sine_formula(x, k);
            (k % 2 == 0) ? sinx += sinx_cache : sinx -= sinx_cache;
        }
    }

    printf("Result is: cosx=%f sinx=%f\n", cosx, sinx);

    return 0;
}

Fix the incorrect output bug

Fix the incorrect output bug


#include "arithmetics.hpp"

namespace arithmetics
{
	int add(int a, int b)
	{
		return a + b;
	}

	int add_buggy(int a, int b)
	{
		return a + b + 1;
	}
}

#include "arithmetics.hpp"

namespace arithmetics
{
	int add(int a, int b)
	{
		return a + b;
	}

	int add_buggy(int a, int b)
	{
		return a + b;
	}
}

Fix bug to see efect for Travis

Fix bug to see efect for Travis


#include "other.hpp"
using namespace LD22;

Other::~Other()
{ }

void Other::advance()
{
    Walker::advance();
}

#include "other.hpp"
#include "item.hpp"
using namespace LD22;

Other::~Other()
{ }

void Other::advance()
{
    scanItems();
    if (m_item) {
        int wx = centerx(), wy = centery();
        int ix = m_item->centerx(), iy = m_item->centery();
        int dx = ix - wx, dy = iy - wy;
        if (dx < -20)
            m_xpush = -PUSH_SCALE;
        else if (dx > 20)
            m_xpush = PUSH_SCALE;
        else
            m_xpush = 0;
        (void) dy;
    } else {
        m_xpush = 0;
    }
    Walker::advance();
}

Make Other chase after items

Make Other chase after items


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "lid_reuse_delayer_config.h"
#include <vespa/searchcore/proton/server/documentdbconfig.h>

namespace proton::documentmetastore {

LidReuseDelayerConfig::LidReuseDelayerConfig(const DocumentDBConfig & configSnapshot)
    : _visibilityDelay(configSnapshot.getMaintenanceConfigSP()->getVisibilityDelay()),
      _allowEarlyAck(configSnapshot.getMaintenanceConfigSP()->allowEarlyAck()),
      _hasIndexedOrAttributeFields(configSnapshot.getSchemaSP()->getNumIndexFields() > 0 ||
                                   configSnapshot.getSchemaSP()->getNumAttributeFields() > 0)
{
}

LidReuseDelayerConfig::LidReuseDelayerConfig()
    : LidReuseDelayerConfig(vespalib::duration::zero(), false)
{}

LidReuseDelayerConfig::LidReuseDelayerConfig(vespalib::duration visibilityDelay, bool hasIndexedOrAttributeFields_in)
    : _visibilityDelay(visibilityDelay),
      _allowEarlyAck(visibilityDelay > 1ms),
      _hasIndexedOrAttributeFields(hasIndexedOrAttributeFields_in)
{
}

}

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "lid_reuse_delayer_config.h"
#include <vespa/searchcore/proton/server/documentdbconfig.h>

namespace proton::documentmetastore {

LidReuseDelayerConfig::LidReuseDelayerConfig(const DocumentDBConfig & configSnapshot)
    : _visibilityDelay(configSnapshot.getMaintenanceConfigSP()->getVisibilityDelay()),
      _allowEarlyAck(configSnapshot.getMaintenanceConfigSP()->allowEarlyAck()),
      _hasIndexedOrAttributeFields(configSnapshot.getSchemaSP()->getNumIndexFields() > 0 ||
                                   configSnapshot.getSchemaSP()->getNumAttributeFields() > 0)
{
}

LidReuseDelayerConfig::LidReuseDelayerConfig()
    : LidReuseDelayerConfig(vespalib::duration::zero(), false)
{}

LidReuseDelayerConfig::LidReuseDelayerConfig(vespalib::duration visibilityDelay, bool hasIndexedOrAttributeFields_in)
    : _visibilityDelay(visibilityDelay),
      _allowEarlyAck(visibilityDelay > vespalib::duration::zero()),
      _hasIndexedOrAttributeFields(hasIndexedOrAttributeFields_in)
{
}

}

Allow early ack on non-zero visibility delay.


// ------------------------------------------------------------------
// ofxTPSprite.cpp
// ofxTexturePacker - https://www.github.com/danoli3/ofxTexturePacker
// Created by Daniel Rosser and Colin Friend on 9/06/2014.
// ------------------------------------------------------------------
#include "ofxTPSprite.h"

ofxTPSprite::ofxTPSprite(ofxTPSpriteData* theData) {
    data = theData;
}

void ofxTPSprite::draw(int x, int y) {
    if(data->getRotated()) {
        ofPushMatrix();
        ofRotate(90);
    }
    texture->drawSubsection(x+data->getOffsetX(), y+data->getOffsetY(),
                            data->getW(), data->getH(), data->getX(), data->getY());
    if(data->getRotated()) {
        ofPopMatrix();
    }
}

// ------------------------------------------------------------------
// ofxTPSprite.cpp
// ofxTexturePacker - https://www.github.com/danoli3/ofxTexturePacker
// Created by Daniel Rosser and Colin Friend on 9/06/2014.
// ------------------------------------------------------------------
#include "ofxTPSprite.h"

ofxTPSprite::ofxTPSprite(ofxTPSpriteData* theData) {
    data = theData;
}

void ofxTPSprite::draw(int x, int y) {
    if(data->getRotated()) {
        ofPushMatrix();
        ofRotate(90);
    }
    texture->drawSubsection(x+data->getOffsetX(), y+data->getOffsetY(), data->getW(), data->getH(), data->getX(), data->getY(), data->getW(), data->getH());
    if(data->getRotated()) {
        ofPopMatrix();
    }
}

Fix for 0.9.0 texture issues

Fix for 0.9.0 texture issues


/* Copyright 2019 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 "absl/memory/memory.h"
#include "tensorflow/core/profiler/internal/gpu/cupti_interface.h"
#include "tensorflow/core/profiler/internal/gpu/cupti_wrapper.h"

#if defined(PLATFORM_GOOGLE)
#include "tensorflow/core/profiler/internal/gpu/cupti_error_manager.h"
#endif

namespace tensorflow {
namespace profiler {

CuptiInterface* GetCuptiInterface() {
  static CuptiInterface* cupti_interface =
#if defined(PLATFORM_GOOGLE)
      new CuptiErrorManager(absl::make_unique<CuptiWrapper>());
#else
      new CuptiWrapper();
#endif
  return cupti_interface;
}

}  // namespace profiler
}  // namespace tensorflow

/* Copyright 2019 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 "absl/memory/memory.h"
#include "tensorflow/core/profiler/internal/gpu/cupti_interface.h"
#include "tensorflow/core/profiler/internal/gpu/cupti_wrapper.h"
#include "tensorflow/core/profiler/internal/gpu/cupti_error_manager.h"

namespace tensorflow {
namespace profiler {

CuptiInterface* GetCuptiInterface() {
  static CuptiInterface* cupti_interface =
      new CuptiErrorManager(absl::make_unique<CuptiWrapper>());
  return cupti_interface;
}

}  // namespace profiler
}  // namespace tensorflow

Enable usage of CuptiErrorManager on all the platforms.

PiperOrigin-RevId: 397131526
Change-Id: I6f180d63188f5c67a7666bc490e131408b1851ee


/*
 * Copyright 2016 - 2019 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <QApplication>
#include <QDebug>
#include <ox/clargs/clargs.hpp>
#include "mainwindow.hpp"

using namespace nostalgia::studio;

int main(int argc, char **args) {
	ox::ClArgs clargs(argc, const_cast<const char**>(args));
	QString argProfilePath = clargs.getString("profile").c_str();

	QApplication app(argc, args);
	app.setAttribute(Qt::AA_UseHighDpiPixmaps);

	try {
		MainWindow w(argProfilePath);
		app.setApplicationName(w.windowTitle());
		w.show();
		QObject::connect(&app, &QApplication::aboutToQuit, &w, &MainWindow::onExit);
		return app.exec();
	} catch (ox::Error err) {
		oxPanic(err, "Unhandled ox::Error");
	}
}

/*
 * Copyright 2016 - 2019 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <QApplication>
#include <QDebug>
#include <ox/clargs/clargs.hpp>
#include "mainwindow.hpp"

using namespace nostalgia::studio;

int main(int argc, char **args) {
	ox::ClArgs clargs(argc, const_cast<const char**>(args));
	QString argProfilePath = clargs.getString("profile").c_str();

	QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
	QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
	QApplication app(argc, args);

	try {
		MainWindow w(argProfilePath);
		app.setApplicationName(w.windowTitle());
		w.show();
		QObject::connect(&app, &QApplication::aboutToQuit, &w, &MainWindow::onExit);
		return app.exec();
	} catch (ox::Error err) {
		oxPanic(err, "Unhandled ox::Error");
	}
}

Fix timing of setting HiDPI options

[nostalgia/studio] Fix timing of setting HiDPI options


Fix that bug where things didn't work but now they should


Put the thingie in the thingie

Put the thingie in the thingie


/******************************************************************************
* Turbo C++11 metaprogramming Library                                         *
*                                                                             *
* Copyright (C) 2013 - 2014, Manuel Sánchez Pérez                             *
*                                                                             *
* This file is part of The Turbo Library.                                     *
*                                                                             *
* The Turbo Library is free software: you can redistribute it and/or modify   *
* it under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation, version 2 of the License.                     *
*                                                                             *
* The Turbo Library is distributed in the hope that it will be useful,        *
* but WITHOUT ANY WARRANTY; without even the implied warranty of              *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               *
* GNU Lesser General Public License for more details.                         *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with The Turbo Library. If not, see <http://www.gnu.org/licenses/>.   *
******************************************************************************/

//#include "manu343726/turbo_core/turbo_core.hpp"
#include "manu343726/turbo_computing/float.hpp"

#include <type_traits>
#include <iostream>
#include <iomanip>

using a = FLOAT(2.54);

int main()
{
    //std::cout << tml::to_string<decltype("hello")>() << std::endl;
}

/******************************************************************************
* Turbo C++11 metaprogramming Library                                         *
*                                                                             *
* Copyright (C) 2013 - 2014, Manuel Sánchez Pérez                             *
*                                                                             *
* This file is part of The Turbo Library.                                     *
*                                                                             *
* The Turbo Library is free software: you can redistribute it and/or modify   *
* it under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation, version 2 of the License.                     *
*                                                                             *
* The Turbo Library is distributed in the hope that it will be useful,        *
* but WITHOUT ANY WARRANTY; without even the implied warranty of              *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               *
* GNU Lesser General Public License for more details.                         *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with The Turbo Library. If not, see <http://www.gnu.org/licenses/>.   *
******************************************************************************/

#include "manu343726/turbo_core/turbo_core.hpp"
//#include "manu343726/turbo_computing/float.hpp"

#include <type_traits>
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << tml::to_string<decltype("hello")>() << std::endl;
}

Revert "Testing -lPUBLIC error using turbo_computing blockdependencies"

This reverts commit 887702ee386c4cdff6c5039c51d84a5c93099a13.


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

// <memory>

// unique_ptr

// Test unique_ptr default ctor

// default unique_ptr ctor should require default Deleter ctor

#include <memory>

class Deleter
{

    Deleter() {}

public:

    Deleter(Deleter&) {}
    Deleter& operator=(Deleter&) {}

    void operator()(void*) const {}
};

int main()
{
    std::unique_ptr<int[], Deleter> p;
}

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

// <memory>

// unique_ptr

// Test unique_ptr default ctor

// default unique_ptr ctor should require default Deleter ctor

#include <memory>

class Deleter
{

    Deleter() {}

public:

    Deleter(Deleter&) {}
    Deleter& operator=(Deleter&) { return *this; }

    void operator()(void*) const {}
};

int main()
{
    std::unique_ptr<int[], Deleter> p;
}

Add return statement to a test class's assignment operator. Defect found by Coverity Scan.

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


#include "BenchmarkStack.h"
#include "StackAllocator.h"

BenchmarkStack::BenchmarkStack(const int runtime)
	: Benchmark(runtime) {
}

BenchmarkResults BenchmarkStack::allocation() {
	setStartTimer();

	StackAllocator stackAllocator(1e10);

	int operations = 0;
	while(!outOfTime()){
		stackAllocator.Allocate(sizeof(int), alignof(int));			// 4  -> 4
		stackAllocator.Allocate(sizeof(bool), alignof(bool));		// 1  -> 5
																	// 3  -> 8
		stackAllocator.Allocate(sizeof(foo), alignof(foo));			// 16 -> 24

		++operations;
	}

	BenchmarkResults results = buildResults(operations, m_runtime, 0, 0);

	printResults(results);

	return results;
}

BenchmarkResults BenchmarkStack::free() {
	return buildResults(0, 0, 0, 0);
}

BenchmarkResults BenchmarkStack::read() {
	return buildResults(0, 0, 0, 0);
}

BenchmarkResults BenchmarkStack::write() {
	return buildResults(0, 0, 0, 0);
}

BenchmarkResults BenchmarkStack::all() {
	return buildResults(0, 0, 0, 0);
}

#include "BenchmarkStack.h"
#include "StackAllocator.h"

BenchmarkStack::BenchmarkStack(const int runtime)
	: Benchmark(runtime) {
}

BenchmarkResults BenchmarkStack::allocation() {
	setStartTimer();

	StackAllocator stackAllocator(1e10);

	int operations = 0;
	while(!outOfTime()){
		stackAllocator.Allocate(sizeof(int), alignof(int));			// 4  -> 4
		stackAllocator.Allocate(sizeof(bool), alignof(bool));		// 1  -> 5
																	// 3  -> 8
		stackAllocator.Allocate(sizeof(foo), alignof(foo));			// 16 -> 24

		++operations;
	}

	BenchmarkResults results = buildResults(operations, m_runtime, 0, 0);

	printResults(results);
	stackAllocator.Reset();
	return results;
}

BenchmarkResults BenchmarkStack::free() {
	return buildResults(0, 0, 0, 0);
}

BenchmarkResults BenchmarkStack::read() {
	return buildResults(0, 0, 0, 0);
}

BenchmarkResults BenchmarkStack::write() {
	return buildResults(0, 0, 0, 0);
}

BenchmarkResults BenchmarkStack::all() {
	return buildResults(0, 0, 0, 0);
}

Reset stack before benchmark finishes.

Reset stack before benchmark finishes.


// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify -fms-extensions %s
typedef long HRESULT;
typedef unsigned long ULONG;
typedef struct _GUID {
  unsigned long Data1;
  unsigned short Data2;
  unsigned short Data3;
  unsigned char Data4[8];
} GUID;
typedef GUID IID;

// remove stdcall, since the warnings have nothing to do with
// what is being tested.
#define __stdcall

extern "C" {
extern "C++" {
// expected-warning@+1 {{__declspec attribute 'novtable'}}
struct __declspec(uuid("00000000-0000-0000-C000-000000000046")) __declspec(novtable)
    IUnknown {
public:
  virtual HRESULT __stdcall QueryInterface(
      const IID &riid,
      void **ppvObject) = 0;

  virtual ULONG __stdcall AddRef(void) = 0;

  virtual ULONG __stdcall Release(void) = 0;

  template <class Q>
  HRESULT __stdcall QueryInterface(Q **pp) {
    return QueryInterface(__uuidof(Q), (void **)pp);
  }
};
}
}

__interface ISfFileIOPropertyPage : public IUnknown{};

// RUN: %clang_cc1 -fsyntax-only -verify -fms-extensions %s
// expected-no-diagnostics
typedef long HRESULT;
typedef unsigned long ULONG;
typedef struct _GUID {
  unsigned long Data1;
  unsigned short Data2;
  unsigned short Data3;
  unsigned char Data4[8];
} GUID;
typedef GUID IID;

// remove stdcall, since the warnings have nothing to do with
// what is being tested.
#define __stdcall

extern "C" {
extern "C++" {
struct __declspec(uuid("00000000-0000-0000-C000-000000000046"))
    IUnknown {
public:
  virtual HRESULT __stdcall QueryInterface(
      const IID &riid,
      void **ppvObject) = 0;

  virtual ULONG __stdcall AddRef(void) = 0;

  virtual ULONG __stdcall Release(void) = 0;

  template <class Q>
  HRESULT __stdcall QueryInterface(Q **pp) {
    return QueryInterface(__uuidof(Q), (void **)pp);
  }
};
}
}

__interface ISfFileIOPropertyPage : public IUnknown{};

Update IUnknown lit test to pass on Win32

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


#include <pangolin/video/video_help.h>
#include <pangolin/video/video_interface.h>

namespace pangolin
{

void PrintPixelFormats(std::ostream& out, bool color)
{
    const std::string c_normal = color ? "\033[0m"  : "";
    const std::string c_alias  = color ? "\033[32m" : "";

   out << "Supported pixel format codes (and their respective bits-per-pixel):" << std::endl;
   std::vector<pangolin::PixelFormat> pixelFormats = pangolin::GetSupportedPixelFormats();
   for(const auto& format: pixelFormats ){
       out << c_alias << format.format << c_normal << " (" << format.bpp << "), ";
   }
   out << std::endl;
}

void VideoHelp( std::ostream& out, const std::string& scheme_filter, HelpVerbosity verbosity)
{
#ifndef _WIN32_
    const bool use_color = true;
#else
    const bool use_color = false;
#endif

    if( verbosity >= HelpVerbosity::SYNOPSIS ) {
        PrintSchemeHelp(out, use_color);
        out << std::endl;
    }

    PrintFactoryRegistryDetails(out, *FactoryRegistry::I(), typeid(VideoInterface), scheme_filter, verbosity, use_color);

    if( verbosity >= HelpVerbosity::PARAMS ) {
        PrintPixelFormats(out, use_color);
    }
}

}

#include <pangolin/video/video_help.h>
#include <pangolin/video/video_interface.h>

#include <pangolin/factory/RegisterFactoriesVideoInterface.h>
#include <pangolin/factory/RegisterFactoriesVideoOutputInterface.h>

namespace pangolin
{

void PrintPixelFormats(std::ostream& out, bool color)
{
    const std::string c_normal = color ? "\033[0m"  : "";
    const std::string c_alias  = color ? "\033[32m" : "";

   out << "Supported pixel format codes (and their respective bits-per-pixel):" << std::endl;
   std::vector<pangolin::PixelFormat> pixelFormats = pangolin::GetSupportedPixelFormats();
   for(const auto& format: pixelFormats ){
       out << c_alias << format.format << c_normal << " (" << format.bpp << "), ";
   }
   out << std::endl;
}

void VideoHelp( std::ostream& out, const std::string& scheme_filter, HelpVerbosity verbosity)
{
    RegisterFactoriesVideoInterface();

#ifndef _WIN32_
    const bool use_color = true;
#else
    const bool use_color = false;
#endif

    if( verbosity >= HelpVerbosity::SYNOPSIS ) {
        PrintSchemeHelp(out, use_color);
        out << std::endl;
    }

    PrintFactoryRegistryDetails(out, *FactoryRegistry::I(), typeid(VideoInterface), scheme_filter, verbosity, use_color);

    if( verbosity >= HelpVerbosity::PARAMS ) {
        PrintPixelFormats(out, use_color);
    }
}

}

[video] Fix help system which was not registering factory methods before trying to enumerate them.


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

// type_traits

// is_swappable

// IMPORTANT: The include order is part of the test. We want to pick up
// the following definitions in this order:
//   1) is_swappable, is_nothrow_swappable
//   2) iter_swap, swap_ranges
//   3) swap(T (&)[N], T (&)[N])
// This test checks that (1) and (2) see forward declarations
// for (3).
#include <type_traits>
#include <algorithm>
#include <utility>

#include "test_macros.h"

int main()
{
    // Use a builtin type so we don't get ADL lookup.
    typedef double T[17][29];
    {
        LIBCPP_STATIC_ASSERT(std::__is_swappable<T>::value, "");
#if TEST_STD_VER > 14
        static_assert(std::is_swappable_v<T>);
#endif
    }
    {
        T t1 = {};
        T t2 = {};
       std::iter_swap(t1, t2);
       std::swap_ranges(t1, t1 + 17, t2);
    }
}

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

// type_traits

// is_swappable

// IMPORTANT: The include order is part of the test. We want to pick up
// the following definitions in this order:
//   1) is_swappable, is_nothrow_swappable
//   2) iter_swap, swap_ranges
//   3) swap(T (&)[N], T (&)[N])
// This test checks that (1) and (2) see forward declarations
// for (3).
#include <type_traits>
#include <algorithm>
#include <utility>

#include "test_macros.h"

int main()
{
    // Use a builtin type so we don't get ADL lookup.
    typedef double T[17][29];
    {
        LIBCPP_STATIC_ASSERT(std::__is_swappable<T>::value, "");
#if TEST_STD_VER > 14
        static_assert(std::is_swappable_v<T>, "");
#endif
    }
    {
        T t1 = {};
        T t2 = {};
       std::iter_swap(t1, t2);
       std::swap_ranges(t1, t1 + 17, t2);
    }
}

Fix use of terse static assert. Patch from STL@microsoft.com

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


struct C {
        int A, B;
        ~C() {}

	void operator^(C b) const { }
};

void test(C *P) {
        *P ^ *P;
}

// Non-POD classes cannot be passed into a function by component, because their
// dtors must be run.  Instead, pass them in by reference.  The C++ front-end
// was mistakenly "thinking" that 'foo' took a structure by component.

struct C {
        int A, B;
        ~C() {}
};

void foo(C b);

void test(C *P) {
	foo(*P);
}

Simplify test, include problem analysis

Simplify test, include problem analysis

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


#include <memory>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"

namespace WizardOfGalicia {
  CActor::CActor() {
    emission = 0;
    stance = Stance::STANDING;
    attack = 0;
    defence = 0;
    hp = 0;
    direction = Direction::N;
  }

  bool CActor::canMove() {
    return true;
  }

  bool CActor::canAttack() {
    return true;
  }

  void CActor::turnLeft() {

    if ( direction == Direction::N ) {
      direction = Direction::W;
    } else {
      direction = static_cast<Direction>( static_cast<int>(direction) - 1);
    }
  }

  void CActor::turnRight() {
    if ( direction == Direction::W ) {
      direction = Direction::N;
    } else {
      direction = static_cast<Direction>( static_cast<int>(direction) + 1);
    }
  }

  void CActor::onMove() {
  }

  void CActor::onAttack() {
  }

  void CActor::endOfTurn() {
  }

  void CActor::performAttack( std::shared_ptr<CActor> other ) {

    if ( abs( magicEnergy ) < abs( other->magicEnergy ) ) {
      return;
    }

    onAttack();

    int diff = ( attack - other->defence );

    if ( diff > 0 ) {
        other->hp -= diff;
    }

    int deltaEnergy = (magicEnergy + other->magicEnergy) / 2;

    magicEnergy += deltaEnergy;
  }
}

#include <memory>

#include "Vec2i.h"
#include "IMapElement.h"
#include "CActor.h"

namespace WizardOfGalicia {
  CActor::CActor() {
    emission = 0;
    stance = Stance::STANDING;
    attack = 0;
    defence = 0;
    hp = 0;
    direction = Direction::N;
  }

  bool CActor::canMove() {
    return true;
  }

  bool CActor::canAttack() {
    return true;
  }

  void CActor::turnLeft() {

    if ( direction == Direction::N ) {
      direction = Direction::W;
    } else {
      direction = static_cast<Direction>( static_cast<int>(direction) - 1);
    }
  }

  void CActor::turnRight() {
    if ( direction == Direction::W ) {
      direction = Direction::N;
    } else {
      direction = static_cast<Direction>( static_cast<int>(direction) + 1);
    }
  }

  void CActor::onMove() {
  }

  void CActor::onAttack() {
  }

  void CActor::endOfTurn() {
  }

  void CActor::performAttack( std::shared_ptr<CActor> other ) {

    if ( abs( magicEnergy ) < abs( other->magicEnergy ) ) {
      return;
    }

    onAttack();

    int diff = ( attack - other->defence );

    if ( diff > 0 ) {
        other->hp -= diff;
    }

    int deltaEnergy = (other->magicEnergy) / 2;

    magicEnergy += deltaEnergy;
  }
}

Change energy absorption, so you only absorb part of the enemy energy

Increasing energy based on your own was too much.
But this might change again.


#include <gtest/gtest.h>

#include "keystore.h"
#include "zcash/Address.hpp"

TEST(keystore_tests, store_and_retrieve_spending_key) {
    CBasicKeyStore keyStore;

    std::set<libzcash::PaymentAddress> addrs;
    keyStore.GetPaymentAddresses(addrs);
    ASSERT_EQ(0, addrs.size());

    auto sk = libzcash::SpendingKey::random();
    keyStore.AddSpendingKey(sk);

    auto addr = sk.address();
    ASSERT_TRUE(keyStore.HaveSpendingKey(addr));

    libzcash::SpendingKey skOut;
    keyStore.GetSpendingKey(addr, skOut);
    ASSERT_EQ(sk, skOut);

    keyStore.GetPaymentAddresses(addrs);
    ASSERT_EQ(1, addrs.size());
    ASSERT_EQ(1, addrs.count(addr));
}

#include <gtest/gtest.h>

#include "keystore.h"
#include "zcash/Address.hpp"

TEST(keystore_tests, store_and_retrieve_spending_key) {
    CBasicKeyStore keyStore;
    libzcash::SpendingKey skOut;

    std::set<libzcash::PaymentAddress> addrs;
    keyStore.GetPaymentAddresses(addrs);
    ASSERT_EQ(0, addrs.size());

    auto sk = libzcash::SpendingKey::random();
    auto addr = sk.address();

    // Sanity-check: we can't get a key we haven't added
    ASSERT_FALSE(keyStore.HaveSpendingKey(addr));
    ASSERT_FALSE(keyStore.GetSpendingKey(addr, skOut));

    keyStore.AddSpendingKey(sk);
    ASSERT_TRUE(keyStore.HaveSpendingKey(addr));
    ASSERT_TRUE(keyStore.GetSpendingKey(addr, skOut));
    ASSERT_EQ(sk, skOut);

    keyStore.GetPaymentAddresses(addrs);
    ASSERT_EQ(1, addrs.size());
    ASSERT_EQ(1, addrs.count(addr));
}

Rework test to check for failure to return a spending key


/* Copyright 2014-2015 Juhani Numminen
 *
 * 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 <clocale>
#include <cstring>
#include <exception>
#include <iostream>

#include "config.hpp"
#include "game.hpp"
#include "i18n.hpp"

int main(int argc, char *argv[]) {
  std::setlocale(LC_ALL, "");
  bindtextdomain("pong--11", LOCALEDIR);
  textdomain("pong--11");

  try {
    if (argc > 1 && std::strcmp(argv[1], "-s") == 0)
      Game{}.run(true);
    else
      Game{}.run(false);
  }
  catch (const std::exception& e) {
    std::cerr << _("Exception: ") << e.what() << std::endl;
    return EXIT_FAILURE;
  }
}

/* Copyright 2014-2015 Juhani Numminen
 *
 * 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 <clocale>
#include <cstring>
#include <exception>
#include <iostream>

#include "config.hpp"
#include "game.hpp"
#include "i18n.hpp"

int main(int argc, char *argv[]) {
  std::setlocale(LC_ALL, "");
  bindtextdomain("pong--11", LOCALEDIR);
  textdomain("pong--11");

  bool isSingleplayer = false;

  if (argc > 1) {
    for (int i = 1; i < argc; ++i) {
      if (std::strcmp(argv[i], "-s") == 0) {
        isSingleplayer = true;
      }
      else {
        std::fprintf(stderr, _("Invalid option: '%s'\n"), argv[i]);
        return EXIT_FAILURE;
      }
    }
  }

  try {
    Game{}.run(isSingleplayer);
  }
  catch (const std::exception& e) {
    std::cerr << _("Exception: ") << e.what() << std::endl;
    return EXIT_FAILURE;
  }
}

Add a simple option parser

Add a simple option parser


#include "DownloadManager.h"

#include <cstdio>
#include <iostream>
#include <string>

using namespace tinydm;

int main(int argc, char **argv) {
  if (argc < 2) {
    std::cerr << "Usage: tinydm [threads]" << std::endl;
    return EXIT_FAILURE;
  }

  int threads = std::atoi(argv[1]);
  if (threads == 0) {
    std::cerr << "Invalid number of threads specified" << std::endl;
    return EXIT_FAILURE;
  }

  DownloadManager dm(threads);
  std::string line;
  while (std::getline(std::cin, line)) {
    if (line.empty()) break;
    dm.download(line);
  }

  return EXIT_SUCCESS;
}

#include "DownloadManager.h"

#include <cstdio>
#include <iostream>
#include <string>

using namespace tinydm;

int main(int argc, char **argv) {
  if (argc < 2) {
    std::cerr << "Usage: tinydm [threads]" << std::endl;
    return EXIT_FAILURE;
  }

  int threads = std::atoi(argv[1]);
  if (threads <= 0) {
    std::cerr << "Invalid number of threads specified" << std::endl;
    return EXIT_FAILURE;
  }

  DownloadManager dm(threads);
  std::string line;
  while (std::getline(std::cin, line)) {
    if (line.empty()) break;
    dm.download(line);
  }

  return EXIT_SUCCESS;
}

Check for positive number of threads.

Check for positive number of threads.

Fixes #1