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

#include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"

namespace chromeos {

StatsOptionsHandler::StatsOptionsHandler() {
}

// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
}

void StatsOptionsHandler::Initialize() {
}

// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
      base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
                 base::Unretained(this)));
}

void StatsOptionsHandler::HandleMetricsReportingCheckbox(
    const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
  const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
  const bool enabled = (checked_str == "true");
  UserMetrics::RecordAction(
      enabled ?
      UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
      UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}

}  // namespace chromeos

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

#include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"

using content::UserMetricsAction;

namespace chromeos {

StatsOptionsHandler::StatsOptionsHandler() {
}

// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
}

void StatsOptionsHandler::Initialize() {
}

// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
      base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
                 base::Unretained(this)));
}

void StatsOptionsHandler::HandleMetricsReportingCheckbox(
    const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
  const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
  const bool enabled = (checked_str == "true");
  content::RecordAction(
      enabled ?
      UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
      UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}

}  // namespace chromeos

Fix CrOS Official build from options2 copy.

BUG=none
TEST=none
TBR=csilv

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

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


#include <%QAPP_INCLUDE%>
#include "%INCLUDE%"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    %CLASS% w;
#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
    w.showMaximized();
#else
    w.show();
#endif
    return a.exec();
}

#include <%QAPP_INCLUDE%>
#include "%INCLUDE%"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    %CLASS% w;
#if defined(Q_WS_S60)
    w.showMaximized();
#else
    w.show();
#endif
    return a.exec();
}

Remove special showMaximized case for Maemo 5

The Maemo 5 window manager already makes sure applications always run
maximized.

Reviewed-by: Robert Griebl


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

namespace ccspec {
namespace core {

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

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

} // namespace core
} // namespace ccspec

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

namespace ccspec {
namespace core {

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

void after(std::string scope, Hook hook) {
    ExampleGroup* parent_group = groups_being_defined.top();
    if (scope == "each" || scope == "example")
        parent_group->addAfterEachHook(hook);
    else if (scope == "all" || scope == "context")
        parent_group->addAfterAllHook(hook);
    else
        throw "no such after hook type";
}

} // namespace core
} // namespace ccspec

Correct after hook exception message

Correct after hook exception message


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

#include "chrome/browser/ui/views/find_bar_host.h"

#include "base/logging.h"
#include "ui/base/events/event.h"

void FindBarHost::AudibleAlert() {
#if defined(OS_WIN)
  MessageBeep(MB_OK);
#else
  // TODO(mukai):
  NOTIMPLEMENTED();
#endif
}

bool FindBarHost::ShouldForwardKeyEventToWebpageNative(
    const ui::KeyEvent& key_event) {
  return true;
}

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

#include "chrome/browser/ui/views/find_bar_host.h"

#include "base/logging.h"
#include "ui/base/events/event.h"

void FindBarHost::AudibleAlert() {
#if defined(OS_WIN)
  MessageBeep(MB_OK);
#endif
}

bool FindBarHost::ShouldForwardKeyEventToWebpageNative(
    const ui::KeyEvent& key_event) {
  return true;
}

Remove NOTIMPLEMENTED() in FindBarHost::AudibleAlert() for ChromeOS.

BUG=None
TEST=None
R=jennyz,jamescook
TBR=sky

Review URL: https://chromiumcodereview.appspot.com/23819045

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


//===--- UnaryStaticAssertCheck.cpp - clang-tidy---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "UnaryStaticAssertCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace modernize {

void UnaryStaticAssertCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus1z)
    return;

  Finder->addMatcher(staticAssertDecl().bind("static_assert"), this);
}

void UnaryStaticAssertCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *MatchedDecl =
      Result.Nodes.getNodeAs<StaticAssertDecl>("static_assert");
  const StringLiteral *AssertMessage = MatchedDecl->getMessage();

  SourceLocation Loc = MatchedDecl->getLocation();

  if (!AssertMessage || AssertMessage->getLength() ||
      AssertMessage->getLocStart().isMacroID() || Loc.isMacroID())
    return;

  diag(Loc,
       "use unary 'static_assert' when the string literal is an empty string")
      << FixItHint::CreateRemoval(AssertMessage->getSourceRange());
}

} // namespace modernize
} // namespace tidy
} // namespace clang

//===--- UnaryStaticAssertCheck.cpp - clang-tidy---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "UnaryStaticAssertCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace modernize {

void UnaryStaticAssertCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus17)
    return;

  Finder->addMatcher(staticAssertDecl().bind("static_assert"), this);
}

void UnaryStaticAssertCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *MatchedDecl =
      Result.Nodes.getNodeAs<StaticAssertDecl>("static_assert");
  const StringLiteral *AssertMessage = MatchedDecl->getMessage();

  SourceLocation Loc = MatchedDecl->getLocation();

  if (!AssertMessage || AssertMessage->getLength() ||
      AssertMessage->getLocStart().isMacroID() || Loc.isMacroID())
    return;

  diag(Loc,
       "use unary 'static_assert' when the string literal is an empty string")
      << FixItHint::CreateRemoval(AssertMessage->getSourceRange());
}

} // namespace modernize
} // namespace tidy
} // namespace clang

Fix build after r319688: s/CPlusPlus1z/CPlusPlus17/

git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@319690 91177308-0d34-0410-b5e6-96231b3b80d8


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

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

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

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

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

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

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

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

        return true;
    }
}

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

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

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

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

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

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

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

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

        return true;
    }
}

Check if the result of graphics_get_display_size is less than 0


/*************************************************************************
> File Name: ruleOfFive.cpp
> Author: Chan-Ho Chris Ohk
> E-mail: utilForever@gmail.com, utilForever@kaist.ac.kr
> Created Time: 2015/4/26
> Personal Blog: https://github.com/utilForever
************************************************************************/
#include <utility>

class Resource
{
private:
	int x = 0;
};

class RO3
{
private:
	Resource* pResource;
};

class RO5
{
private:
	Resource* pResource;

public:
	RO5()
		: pResource{ new Resource{} }
	{ }

	RO5(const RO5& rhs)
		: pResource{ new Resource(*(rhs.pResource)) }
	{ }

	RO5(RO5&& rhs)
		: pResource{ rhs.pResource }
	{
		rhs.pResource = nullptr;
	}

	RO5& operator=(const RO5& rhs)
	{
		if (&rhs != this)
		{
			delete pResource;
			pResource = nullptr;
			pResource = new Resource(*(rhs.pResource));
		}

		return *this;
	}

	RO5& operator=(RO5&& rhs)
	{
		if (&rhs != this)
		{
			delete pResource;
			pResource = rhs.pResource;
			rhs.pResource = nullptr;
		}

		return *this;
	}

	~RO5()
	{
		delete pResource;
	}
};

Update Rule of Five Example

Update Rule of Five Example


// Solution to problem from Crack Coding interviews. Implement an
// algorithm to determine if a string has all unique characters
#include "check_unique_char.h"

CheckUniqueChar::CheckUniqueChar() {

}

CheckUniqueChar::~CheckUniqueChar() {

}

// Takes O(n) running time
bool CheckUniqueChar::solver_boolean(std::string test_string) {

}

// Takes O(nlogn) running time
bool CheckUniqueChar::solver_sorted(std::string test_string) {

}

bool CheckUniqueChar:test_case() {

}

Add functions to new problem for CheckUniqueChar


#include <GL/gl.h>
#include <orz/exception.h>
#include "hw3d_opengl_texture.h"

namespace Hw3D
{
	Texture::Lock OpenGlTexture::LockRegion(const Geom::RectInt &region, bool readOnly)
	{
		return Texture::Lock();
	}

	void OpenGlTexture::UnlockRegion()
	{

	}

	OpenGlTexture::OpenGlTexture(Geom::SizeInt dimensions, Format fmt, Pool pool):
		Texture(dimensions, fmt),
		m_textureName(0)
	{
		glGenTextures(1, &m_textureName);
		if(m_textureName == GL_INVALID_VALUE)
		{
			m_textureName = 0;
			DO_THROW(Err::CriticalError, "Failed allocating texture");
		}
	}

	OpenGlTexture::~OpenGlTexture()
	{
		glDeleteTextures(1, &m_textureName);
	}
}

#include <GL/gl.h>
#include <orz/exception.h>
#include "hw3d_opengl_texture.h"
#include "hw3d_opengl_common.h"

namespace Hw3D
{
	Texture::Lock OpenGlTexture::LockRegion(const Geom::RectInt &region, bool readOnly)
	{
		return Texture::Lock();
	}

	void OpenGlTexture::UnlockRegion()
	{

	}

	OpenGlTexture::OpenGlTexture(Geom::SizeInt dimensions, Format fmt, Pool pool):
		Texture(dimensions, fmt),
		m_textureName(0)
	{
		glGenTextures(1, &m_textureName);
		if(m_textureName == GL_INVALID_VALUE)
		{
			m_textureName = 0;
			DO_THROW(Err::CriticalError, "Failed allocating texture");
		}
		glBindTexture(GL_TEXTURE_2D, m_textureName);
		glTexImage2D(
			GL_TEXTURE_2D,
			0,
			GetGlInternalFormat(fmt),
			dimensions.Width,
			dimensions.Height,
			0,
			GetGlFormat(fmt),
			GetGlDataType(fmt),
			nullptr
		);

		GLenum err;

		if((err = glGetError()) != GL_NO_ERROR)
		{
			DO_THROW(Err::CriticalError, "glTexImage2D failed: " + GetGlErrorString(err));
		}
	}

	OpenGlTexture::~OpenGlTexture()
	{
		glDeleteTextures(1, &m_textureName);
	}
}

Create OpenGl texture object when creating OpenGlTexture


#include "CppUTest\CommandLineTestRunner.h"
#include <stdio.h>
#include "mbed.h"
#include "testrunner.h"
#include "test_env.h"

/**
Object 'console' is used to show prints on console.
It is declared in \cpputest\src\Platforms\armcc\UtestPlatform.cpp
*/
Serial console(STDIO_UART_TX, STDIO_UART_RX);

int main(int ac, char** av)
{
    unsigned failureCount = 0;
    {
        // Some compilers may not pass ac, av so we need to supply them ourselves
        int ac = 2;
        char* av[] = {__FILE__, "-v"};
        failureCount = CommandLineTestRunner::RunAllTests(ac, av);
    }

    notify_completion(failureCount == 0);
    return failureCount;
}

#include "CommandLineTestRunner.h"
#include <stdio.h>
#include "mbed.h"
#include "testrunner.h"
#include "test_env.h"

/**
Object 'console' is used to show prints on console.
It is declared in \cpputest\src\Platforms\armcc\UtestPlatform.cpp
*/
Serial console(STDIO_UART_TX, STDIO_UART_RX);

int main(int ac, char** av)
{
    unsigned failureCount = 0;
    {
        // Some compilers may not pass ac, av so we need to supply them ourselves
        int ac = 2;
        char* av[] = {__FILE__, "-v"};
        failureCount = CommandLineTestRunner::RunAllTests(ac, av);
    }

    notify_completion(failureCount == 0);
    return failureCount;
}

Remove an include path with undefined behaviour on non-windows systems


#include <inttypes.h>
#include <stdio.h>

extern "C" bool _TSsop2leFT3lhsNSs5int643rhsS__NSs4bool(int64_t l, int64_t r) {
  return l <= r;
}

extern "C" double _TSsop1sFT1aNSs6double_S_(double x) {
    return -x;
}

extern "C" void _T3fib5printFT1iNSs5int64_T_(int64_t l) {
  printf("%lld\n", l);
}

extern "C" void _T3fib5printFT1iNS_6double_T_(double l) {
  printf("%f\n", l);
}

extern "C" void _T5nbody5printFT1iNSs6double_T_(double l) {
  printf("%f\n", l);
}

extern "C" bool _TSs19convertToLogicValueFT1vNSs4bool_i1(bool b) {
  return b;
}

extern "C"
double
_TNSs6double26convert_from_float_literalFT3valf64_S_(double x)
{
    return x;
}

#include <inttypes.h>
#include <stdio.h>

extern "C" void _T3fib5printFT1iNSs5int64_T_(int64_t l) {
  printf("%lld\n", l);
}

extern "C" void _T3fib5printFT1iNS_6double_T_(double l) {
  printf("%f\n", l);
}

extern "C" void _T5nbody5printFT1iNSs6double_T_(double l) {
  printf("%f\n", l);
}

// This cannot be implemented in swift.swift until we have pattern matching.
extern "C" bool _TSs19convertToLogicValueFT1vNSs4bool_i1(bool b) {
  return b;
}

extern "C"
double
_TNSs6double26convert_from_float_literalFT3valf64_S_(double x)
{
    return x;
}

Implement all the integer comparison operators in swift.swift.  Despite
the indirection, each of these compiles into nice simple IR at -O3, with:
 swift swift.swift -I test -emit-llvm | opt -O3 -S | less

for example:

define i1 @_TSsop1gFT3lhsNSs5int643rhsS__NSs4bool(i64, i64) nounwind readnone {
entry:
  %2 = icmp sgt i64 %0, %1
  ret i1 %2
}

Swift SVN r1125


#include <QPixmap>

#include "restdialog.h"

RestDialog::RestDialog(QWidget *parent) :
    QDialog(parent)
{
    Qt::WindowFlags flags = windowFlags();
    setWindowFlags((flags & ~Qt::WindowContextHelpButtonHint) |
                   Qt::WindowStaysOnTopHint);
    ui_restDialog = QSharedPointer<Ui::RestDialog>(new Ui::RestDialog());
    ui_restDialog->setupUi(this);

    // set message
    QString message = settings.value("message", QString()).toString();
    ui_restDialog->messageLabel->setText(message);

    // possibly set image
    bool useImage = settings.value("use_img", false).toBool();
    if (useImage)
        setImage();

    activateWindow();
}

void RestDialog::setImage()
{
    QString imagePath = settings.value("img_path", QString()).toString();
    QPixmap image(imagePath);
    if (image.isNull())
        return;
    ui_restDialog->imageLabel->setPixmap(image);
}

bool RestDialog::isPostponed() const
{
    return ui_restDialog->afterCheckBox->isChecked();
}

#include <QPixmap>
#include <QDesktopWidget>

#include "restdialog.h"

RestDialog::RestDialog(QWidget *parent) :
    QDialog(parent)
{
    Qt::WindowFlags flags = windowFlags();
    setWindowFlags((flags & ~Qt::WindowContextHelpButtonHint) |
                   Qt::WindowStaysOnTopHint);
    ui_restDialog = QSharedPointer<Ui::RestDialog>(new Ui::RestDialog());
    ui_restDialog->setupUi(this);

    // set message
    QString message = settings.value("message", QString()).toString();
    ui_restDialog->messageLabel->setText(message);

    // possibly set image
    bool useImage = settings.value("use_img", false).toBool();
    if (useImage)
        setImage();

    activateWindow();
}

void RestDialog::setImage()
{
    QString imagePath = settings.value("img_path", QString()).toString();
    QPixmap image(imagePath);
    if (image.isNull())
        return;

    // check that image is not bigger than screen resolution
    QSize imageSize = image.size();
    int screenWidth = QApplication::desktop()->width();
    int screenHeight = QApplication::desktop()->height();
    if ((imageSize.height() >= screenHeight) ||
            (imageSize.width() >= screenWidth))
    {
        // let's scale it
        image = image.scaled((screenWidth - width() - 50),
                             (screenHeight - height() - 50),
                             Qt::KeepAspectRatio);
    }

    ui_restDialog->imageLabel->setPixmap(image);
}

bool RestDialog::isPostponed() const
{
    return ui_restDialog->afterCheckBox->isChecked();
}

Check that image in message dialog is not bigger than screen


#include "behaviours/audio_voice_fade_behaviour.h"
#include "../audio_voice.h"
#include "audio_facade.h"
#include "halley/utils/utils.h"

using namespace Halley;

AudioVoiceFadeBehaviour::AudioVoiceFadeBehaviour(float fadeTime, float sourceVolume, float targetVolume, bool stopAtEnd)
	: curTime(0)
	, fadeTime(fadeTime)
	, volume0(sourceVolume)
	, volume1(targetVolume)
	, stopAtEnd(stopAtEnd)
{
}

void AudioVoiceFadeBehaviour::onAttach(AudioVoice& audioSource)
{
}

bool AudioVoiceFadeBehaviour::update(float elapsedTime, AudioVoice& audioSource)
{
	curTime += elapsedTime;
	const float t = clamp(curTime / fadeTime, 0.0f, 1.0f);
	const float volume = lerp(volume0, volume1, t);

	audioSource.getDynamicGainRef() *= gainToVolume(volume);

	if (curTime >= fadeTime) {
		if (stopAtEnd) {
			audioSource.stop();
		}
		return false;
	}
	return true;
}

#include "behaviours/audio_voice_fade_behaviour.h"
#include "../audio_voice.h"
#include "audio_facade.h"
#include "halley/utils/utils.h"

using namespace Halley;

AudioVoiceFadeBehaviour::AudioVoiceFadeBehaviour(float fadeTime, float sourceVolume, float targetVolume, bool stopAtEnd)
	: curTime(0)
	, fadeTime(fadeTime)
	, volume0(sourceVolume)
	, volume1(targetVolume)
	, stopAtEnd(stopAtEnd)
{
}

void AudioVoiceFadeBehaviour::onAttach(AudioVoice& audioSource)
{
}

bool AudioVoiceFadeBehaviour::update(float elapsedTime, AudioVoice& audioSource)
{
	curTime += elapsedTime;
	const float t = fadeTime == 0.0f ? 1.0f : clamp(curTime / fadeTime, 0.0f, 1.0f);
	const float volume = lerp(volume0, volume1, t);

	audioSource.setUserGain(audioSource.getDynamicGainRef() * gainToVolume(volume));

	if (curTime >= fadeTime) {
		if (stopAtEnd) {
			audioSource.stop();
		}
		return false;
	}
	return true;
}

Change AudioVoiceFadeBehaviour to use userGain


// RUN: %clangxx -w -fsanitize=bool %s -o %t
// RUN: %run %t 2>&1 | FileCheck %s

#include <iostream>

extern "C" {
void __ubsan_get_current_report_data(const char **OutIssueKind,
                                     const char **OutMessage,
                                     const char **OutFilename,
                                     unsigned *OutLine, unsigned *OutCol,
                                     char **OutMemoryAddr);

// Override the weak definition of __ubsan_on_report from the runtime, just
// for testing purposes.
void __ubsan_on_report(void) {
  const char *IssueKind, *Message, *Filename;
  unsigned Line, Col;
  char *Addr;
  __ubsan_get_current_report_data(&IssueKind, &Message, &Filename, &Line, &Col,
                                  &Addr);

  std::cout << "Issue: " << IssueKind << "\n"
            << "Location: " << Filename << ":" << Line << ":" << Col << "\n"
            << "Message: " << Message << std::endl;

  (void)Addr;
}
}

int main() {
  char C = 3;
  bool B = *(bool *)&C;
  // CHECK: Issue: invalid-bool-load
  // CHECK-NEXT: Location: {{.*}}monitor.cpp:[[@LINE-2]]:12
  // CHECK-NEXT: Message: Load of value 3, which is not a valid value for type 'bool'
  return 0;
}

// RUN: %clangxx -w -fsanitize=bool %s -o %t
// RUN: %run %t 2>&1 | FileCheck %s

// __ubsan_on_report is not defined as weak. Redefining it here isn't supported
// on Windows.
//
// UNSUPPORTED: win32

#include <iostream>

extern "C" {
void __ubsan_get_current_report_data(const char **OutIssueKind,
                                     const char **OutMessage,
                                     const char **OutFilename,
                                     unsigned *OutLine, unsigned *OutCol,
                                     char **OutMemoryAddr);

// Override the definition of __ubsan_on_report from the runtime, just for
// testing purposes.
void __ubsan_on_report(void) {
  const char *IssueKind, *Message, *Filename;
  unsigned Line, Col;
  char *Addr;
  __ubsan_get_current_report_data(&IssueKind, &Message, &Filename, &Line, &Col,
                                  &Addr);

  std::cout << "Issue: " << IssueKind << "\n"
            << "Location: " << Filename << ":" << Line << ":" << Col << "\n"
            << "Message: " << Message << std::endl;

  (void)Addr;
}
}

int main() {
  char C = 3;
  bool B = *(bool *)&C;
  // CHECK: Issue: invalid-bool-load
  // CHECK-NEXT: Location: {{.*}}monitor.cpp:[[@LINE-2]]:12
  // CHECK-NEXT: Message: Load of value 3, which is not a valid value for type 'bool'
  return 0;
}

[ubsan] Mark a test case as unsupported on Windows

__ubsan_on_report isn't defined as weak, and redefining it in a test is
not supported on Windows.

See the error message here: https://reviews.llvm.org/D48446

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


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

#include "chrome/renderer/extensions/api_definitions_natives.h"

#include <algorithm>

#include "chrome/common/extensions/features/base_feature_provider.h"

namespace {
const char kInvalidExtensionNamespace[] = "Invalid extension namespace";
}

namespace extensions {

ApiDefinitionsNatives::ApiDefinitionsNatives(Dispatcher* dispatcher,
                                             ChromeV8Context* context)
    : ChromeV8Extension(dispatcher, context) {
  RouteFunction("GetExtensionAPIDefinitionsForTest",
                base::Bind(
                    &ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest,
                    base::Unretained(this)));
}

void ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  std::vector<std::string> apis;
  FeatureProvider* feature_provider = BaseFeatureProvider::GetByName("api");
  const std::vector<std::string>& feature_names =
      feature_provider->GetAllFeatureNames();
  for (std::vector<std::string>::const_iterator i = feature_names.begin();
       i != feature_names.end(); ++i) {
    if (!feature_provider->GetParent(feature_provider->GetFeature(*i)) &&
        context()->GetAvailability(*i).is_available()) {
      apis.push_back(*i);
    }
  }
  args.GetReturnValue().Set(
    dispatcher()->v8_schema_registry()->GetSchemas(apis));
}

}  // namespace extensions

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

#include "chrome/renderer/extensions/api_definitions_natives.h"

#include <algorithm>

#include "chrome/common/extensions/features/base_feature_provider.h"

namespace extensions {

ApiDefinitionsNatives::ApiDefinitionsNatives(Dispatcher* dispatcher,
                                             ChromeV8Context* context)
    : ChromeV8Extension(dispatcher, context) {
  RouteFunction("GetExtensionAPIDefinitionsForTest",
                base::Bind(
                    &ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest,
                    base::Unretained(this)));
}

void ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  std::vector<std::string> apis;
  FeatureProvider* feature_provider = BaseFeatureProvider::GetByName("api");
  const std::vector<std::string>& feature_names =
      feature_provider->GetAllFeatureNames();
  for (std::vector<std::string>::const_iterator i = feature_names.begin();
       i != feature_names.end(); ++i) {
    if (!feature_provider->GetParent(feature_provider->GetFeature(*i)) &&
        context()->GetAvailability(*i).is_available()) {
      apis.push_back(*i);
    }
  }
  args.GetReturnValue().Set(
    dispatcher()->v8_schema_registry()->GetSchemas(apis));
}

}  // namespace extensions

Remove an unused const kInvalidExtensionNamespace.

BUG=None
Test=None

Review URL: https://chromiumcodereview.appspot.com/17032002

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


#include <cstdio>
#include <cstdlib>

#include "util/debug.hpp"

bool nest::mc::util::failed_assertion(const char *assertion, const char *file,
                                      int line, const char *func)
{
    std::fprintf(stderr, "%s:%d %s: Assertion `%s' failed.\n", file, line, func, assertion);
    std::abort();
    return false;
}

#include <cstdlib>
#include <iostream>

#include "util/debug.hpp"

bool nest::mc::util::failed_assertion(const char *assertion, const char *file,
                                      int line, const char *func)
{
    // Explicit flush, as we can't assume default buffering semantics on stderr/cerr,
    // and abort() mignt not flush streams.

    std::cerr << file << ':' << line << " " << func
              << ": Assertion `" << assertion << "' failed." << std::endl;
    std::abort();
    return false;
}

Use cerr in preference to stderr for assertion message.

* Finds an actual (possibly) reasonable use for std::endl.


#include "./Sphere.hpp"
#include "./misc.hpp"
#include <algorithm>
#include <cmath>

namespace yks {

	Optional<float> intersect(const vec3& origin, float radius, const Ray& r) {
		const vec3 o = r.origin - origin;
		const vec3 v = r.direction;

		float t1, t2;
		const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2);

		if (solutions == 0) {
			return Optional<float>();
		} else if (solutions == 1) {
			return make_optional<float>(t1);
		} else {
			return make_optional<float>(std::min(t1, t2));
		}
	}

	vec3 uniform_point_on_sphere(float a, float b) {
		const float y = 2.0f * a - 1.0f;
		const float latitude = std::asin(y);
		const float longitude = b * two_pi;
		const float cos_latitude = std::cos(latitude);

		return mvec3(cos_latitude * cos(longitude), y, cos_latitude * sin(longitude));
	}

}

#include "./Sphere.hpp"
#include "./misc.hpp"
#include <algorithm>
#include <cmath>

namespace yks {

	Optional<float> intersect(const vec3& origin, float radius, const Ray& r) {
		const vec3 o = r.origin - origin;
		const vec3 v = r.direction;

		float t1, t2;
		const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - radius*radius, t1, t2);

		if (solutions == 0) {
			return Optional<float>();
		} else if (solutions == 1) {
			return make_optional<float>(t1);
		} else {
			return make_optional<float>(std::min(t1, t2));
		}
	}

	vec3 uniform_point_on_sphere(float a, float b) {
		const float y = 2.0f * a - 1.0f;
		const float longitude = b * two_pi;
		const float cos_latitude = std::sqrt(1.0f - sqr(y));

		return mvec3(cos_latitude * std::cos(longitude), y, cos_latitude * std::sin(longitude));
	}

}

Optimize sphere sampling code using trig identity


/*
 * AnimationTask.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <esp_log.h>

#include "nvs_flash.h"
#include "esp_wifi.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"

#include "AnimationTask.h"
#include "sdkconfig.h"

static char tag[] = "AnimationTask";

AnimationTask::AnimationTask(const char* taskName, I2C* i2c)
        : Esp32RtosTask(taskName),
          m_i2c(i2c) {
}

AnimationTask::~AnimationTask() {
}

void AnimationTask::run(void* data) {
    while (1) {
        ESP_LOGW(tag, "AnimationTask::run");
        delay(1000);
    }
}

/*
 * AnimationTask.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <esp_log.h>

#include "nvs_flash.h"
#include "esp_wifi.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"

#include "AnimationTask.h"
#include "sdkconfig.h"

static char tag[] = "AnimationTask";

AnimationTask::AnimationTask(const char* taskName, I2C* i2c)
        : Esp32RtosTask(taskName),
          m_i2c(i2c) {
}

AnimationTask::~AnimationTask() {
}

void AnimationTask::run(void* data) {
    m_i2c->init(I2C_NUM_1, I2C_MODE_MASTER, GPIO_NUM_18, GPIO_NUM_19, GPIO_PULLUP_DISABLE, GPIO_PULLUP_DISABLE, 100000);
    m_i2c->i2c_is31_init(I2C_NUM_1);
    while (1) {
        ESP_LOGW(tag, "AnimationTask::run");
        m_i2c->i2c_is31_pwm(I2C_NUM_1);
        m_i2c->i2c_is31_en(I2C_NUM_1);
        delay(1000);
    }
}

Initialize and enable LEDs in animation to test


/*
 * AnimationTask.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <esp_log.h>

#include "AnimationTask.h"
#include "sdkconfig.h"

static char tag[] = "AnimationTask";

AnimationTask::AnimationTask(std::string taskName) : Task(taskName) {
}

AnimationTask::~AnimationTask() {
}

void AnimationTask::run(void *data) {
    ESP_LOGW(tag, "AnimationTask::run");
}

/*
 * AnimationTask.cpp
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#include <esp_log.h>

#include "AnimationTask.h"
#include "sdkconfig.h"

static char tag[] = "AnimationTask";

AnimationTask::AnimationTask(std::string taskName)
        : Task(taskName) {
}

AnimationTask::~AnimationTask() {
}

void AnimationTask::run(void *data) {
    while (1) {
        ESP_LOGW(tag, "AnimationTask::run");
        delay(1000);
    }
}

Fix animation task, run should not return


#include <boost/test/unit_test.hpp>

#include "../uint256.h"

extern void SHA256Transform(void* pstate, void* pinput, const void* pinit);

BOOST_AUTO_TEST_SUITE(miner_tests)

BOOST_AUTO_TEST_CASE(sha256transform_equality)
{
    unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

    unsigned char pstate[32];
    unsigned char pinput[32];

    int i;

    for (i = 0; i < 32; i++) {
        pinput[i] = i;
        pstate[i] = 0;
    }

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

		BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

#include <boost/test/unit_test.hpp>

#include "../uint256.h"

extern void SHA256Transform(void* pstate, void* pinput, const void* pinit);

BOOST_AUTO_TEST_SUITE(miner_tests)

BOOST_AUTO_TEST_CASE(sha256transform_equality)
{
    unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};

    unsigned char pstate[32];
    unsigned char pinput[64];

    int i;

    for (i = 0; i < 32; i++) {
        pinput[i] = i;
        pinput[i+32] = 0;
    }

    uint256 hash;

    SHA256Transform(&hash, pinput, pSHA256InitState);

    BOOST_TEST_MESSAGE(hash.GetHex());

    uint256 hash_reference("0x2df5e1c65ef9f8cde240d23cae2ec036d31a15ec64bc68f64be242b1da6631f3");

    BOOST_CHECK(hash == hash_reference);
}

BOOST_AUTO_TEST_SUITE_END()

Fix miner_test unit test bug

Fix miner_test unit test bug


//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "mtac/remove_dead_basic_blocks.hpp"
#include "mtac/Function.hpp"

using namespace eddic;

bool mtac::remove_dead_basic_blocks::operator()(mtac::Function& function){
    unsigned int before = function.bb_count();

    if(before <= 2){
        return false;
    }

    auto it = iterate(function);

    //ENTRY is always accessed
    ++it;

    while(it.has_next()){
        auto& block = *it;

        if(block->predecessors.empty()){
            it.erase();
        } else {
            ++it;
        }
    }

    return function.bb_count() < before;
}

//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <unordered_set>

#include "mtac/remove_dead_basic_blocks.hpp"
#include "mtac/Function.hpp"

using namespace eddic;

bool mtac::remove_dead_basic_blocks::operator()(mtac::Function& function){
    bool optimized;
    bool optimized_once = false;

    do {
        optimized = false;

        unsigned int before = function.bb_count();

        if(before <= 2){
            return optimized_once;
        }

        std::unordered_set<basic_block_p> live_basic_blocks;

        for(auto& basic_block : function){
            if(basic_block->index < 0){
                live_basic_blocks.insert(basic_block);
            } else {
                for(auto& predecessor : basic_block->predecessors){
                    if(live_basic_blocks.find(predecessor) != live_basic_blocks.end()){
                        live_basic_blocks.insert(basic_block);
                        break;
                    }
                }
            }
        }

        auto it = iterate(function);

        while(it.has_next()){
            auto& block = *it;

            if(live_basic_blocks.find(block) == live_basic_blocks.end()){
                it.erase();
            } else {
                ++it;
            }
        }

        optimized = function.bb_count() < before;
        if(optimized){
            optimized_once = true;
        }
    } while(optimized);

    return optimized_once;
}

Improve removal of dead basic blocks to remove all dead basic blocks at once


#include "tags/tag-database-factory.h"
#include <QFile>
#include "tags/tag-database-in-memory.h"
#include "tags/tag-database-sqlite.h"

TagDatabase *TagDatabaseFactory::Create(QString directory)
{
	if (!directory.endsWith("/") && !directory.endsWith("\\")) {
		directory += "/";
	}

	const QString typesFile = directory + "tag-types.txt";

	if (QFile::exists(directory + "tags.db")) {
		return new TagDatabaseSqlite(typesFile, directory + "tags.db");
	}

	return new TagDatabaseInMemory(typesFile, directory + "tags.txt");
}

#include "tags/tag-database-factory.h"
#include <QFile>
#include "tags/tag-database-in-memory.h"
#include "tags/tag-database-sqlite.h"

TagDatabase *TagDatabaseFactory::Create(QString directory)
{
	if (!directory.endsWith("/") && !directory.endsWith("\\")) {
		directory += "/";
	}

	const QString typesFile = directory + "tag-types.txt";

	if (QFile::exists(directory + "tags.txt")) {
		return new TagDatabaseInMemory(typesFile, directory + "tags.txt");
	}

	return new TagDatabaseSqlite(typesFile, directory + "tags.db");
}

Switch default tag database from TXT to SQLite


// FIXME: The standalone module still seems to cause clang to want to test for
// the existence of a 'foo' directory:
// RUN: mkdir %t
// RUN: cp %s %t
// RUN: mkdir %t/foo
// RUN: cd %t
// RUN: not %clang_cc1 -fmodules -fsyntax-only %s 2>&1 | FileCheck %s

// CHECK: error: no matching function for call to 'foo'
// CHECK: note: candidate function not viable: requires 0 arguments, but 1 was provided

// FIXME: This should use -verify, but it seems it doesn't hook up the
// SourceManager correctly or something, and the foo.h note gets attributed to
// the synthetic module translation unit "foo.map Line 2:...".
// %clang_cc1 -fmodules -verify %s

#pragma clang module build foo
module foo {
  umbrella "foo"
  module * {
    export *
  }
}
#pragma clang module contents
#pragma clang module begin foo.foo
# 1 "foo.h" 1
#ifndef FOO_FOO_H
void foo();
#endif
#pragma clang module end
#pragma clang module endbuild
#pragma clang module import foo.foo
// expected-note@foo.h:2 {{candidate function not viable: requires 0 arguments, but 1 was provided}}
int main() {
  foo(1); // expected-error {{no matching function for call to 'foo'}}
}

// FIXME: The standalone module still seems to cause clang to want to test for
// the existence of a 'foo' directory:
// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: cp %s %t
// RUN: rm -rf %t/foo
// RUN: mkdir %t/foo
// RUN: cd %t
// RUN: not %clang_cc1 -fmodules -fsyntax-only %s 2>&1 | FileCheck %s

// CHECK: error: no matching function for call to 'foo'
// CHECK: note: candidate function not viable: requires 0 arguments, but 1 was provided

// FIXME: This should use -verify, but it seems it doesn't hook up the
// SourceManager correctly or something, and the foo.h note gets attributed to
// the synthetic module translation unit "foo.map Line 2:...".
// %clang_cc1 -fmodules -verify %s

#pragma clang module build foo
module foo {
  umbrella "foo"
  module * {
    export *
  }
}
#pragma clang module contents
#pragma clang module begin foo.foo
# 1 "foo.h" 1
#ifndef FOO_FOO_H
void foo();
#endif
#pragma clang module end
#pragma clang module endbuild
#pragma clang module import foo.foo
// expected-note@foo.h:2 {{candidate function not viable: requires 0 arguments, but 1 was provided}}
int main() {
  foo(1); // expected-error {{no matching function for call to 'foo'}}
}

Fix buildbot break after r360195

Fix buildbot break after r360195

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


#include <vector>
#include <boost/any.hpp>
#include <v8.h>

#include "JSFunctionInvokable.hpp"
#include "../JSObjectScript.hpp"
#include "JSInvokableUtil.hpp"

namespace Sirikata
{
namespace JS
{

  boost::any JSFunctionInvokable::invoke(std::vector<boost::any>& params)
  {
    /* Invoke the function handle */

    int argc =
#ifdef _WIN32
               1
#else
               0
#endif
               ;
    int base_offset = argc; // need to work around windows weirdness
   argc += params.size();

   v8::HandleScope handle_scope;
   v8::Context::Scope  context_scope(script_->context());

   std::vector<v8::Handle<v8::Value> >argv(argc);

   if (base_offset) argv[0] = v8::Handle<v8::Value>();

   for(uint32 i = 0; i < params.size(); i++)
       argv[base_offset+i] = InvokableUtil::AnyToV8(script_, params[i]);

  //TryCatch try_catch;

   // We are currently executing in the global context of the entity
   // FIXME: need to take care fo the "this" pointer
   v8::Handle<v8::Value> result = script_->invokeCallback(function_, argc, &argv[0]);

   if(result.IsEmpty())
   {
     /*
     v8::String::Utf8Value error(try_catch.Exception());
     const char* cMsg = ToCString(error);
     std::cerr << cMsg << "\n";
     */
   }

   return boost::any(result) ;

  }
}
}

#include <vector>
#include <boost/any.hpp>
#include <v8.h>

#include "JSFunctionInvokable.hpp"
#include "../JSObjectScript.hpp"
#include "JSInvokableUtil.hpp"

namespace Sirikata
{
namespace JS
{

  boost::any JSFunctionInvokable::invoke(std::vector<boost::any>& params)
  {
    /* Invoke the function handle */

    int argc = params.size();

   v8::HandleScope handle_scope;
   v8::Context::Scope  context_scope(script_->context());

   std::vector<v8::Handle<v8::Value> >argv(argc);

   for(uint32 i = 0; i < params.size(); i++)
       argv[i] = InvokableUtil::AnyToV8(script_, params[i]);

  //TryCatch try_catch;

   // We are currently executing in the global context of the entity
   // FIXME: need to take care fo the "this" pointer
   v8::Handle<v8::Value> result = script_->invokeCallback(function_, argc, &argv[0]);

   if(result.IsEmpty())
   {
     /*
     v8::String::Utf8Value error(try_catch.Exception());
     const char* cMsg = ToCString(error);
     std::cerr << cMsg << "\n";
     */
   }

   return boost::any(result) ;

  }
}
}

Remove old windows workaround for V8 function invokations.


#include "TestUpdaterOptions.h"

#include "TestUtils.h"
#include "UpdaterOptions.h"

void TestUpdaterOptions::testOldFormatArgs()
{
	const int argc = 6;
	char* argv[argc];
	argv[0] = "updater";
	argv[1] = "CurrentDir=/path/to/app";
	argv[2] = "TempDir=/tmp/updater";
	argv[3] = "UpdateScriptFileName=/tmp/updater/file_list.xml";
	argv[4] = "AppFileName=/path/to/app/theapp";
	argv[5] = "PID=123456";

	UpdaterOptions options;
	options.parse(argc,argv);

	TEST_COMPARE(options.mode,UpdateInstaller::Setup);
	TEST_COMPARE(options.installDir,"/path/to/app");
	TEST_COMPARE(options.packageDir,"/tmp/updater");
	TEST_COMPARE(options.scriptPath,"/tmp/updater/file_list.xml");
	TEST_COMPARE(options.waitPid,123456);
}

int main(int,char**)
{
	TestList<TestUpdaterOptions> tests;
	tests.addTest(&TestUpdaterOptions::testOldFormatArgs);
	return TestUtils::runTest(tests);
}

#include "TestUpdaterOptions.h"

#include "TestUtils.h"
#include "UpdaterOptions.h"

void TestUpdaterOptions::testOldFormatArgs()
{
	const int argc = 6;
	char* argv[argc];
	argv[0] = strdup("updater");
	argv[1] = strdup("CurrentDir=/path/to/app");
	argv[2] = strdup("TempDir=/tmp/updater");
	argv[3] = strdup("UpdateScriptFileName=/tmp/updater/file_list.xml");
	argv[4] = strdup("AppFileName=/path/to/app/theapp");
	argv[5] = strdup("PID=123456");

	UpdaterOptions options;
	options.parse(argc,argv);

	TEST_COMPARE(options.mode,UpdateInstaller::Setup);
	TEST_COMPARE(options.installDir,"/path/to/app");
	TEST_COMPARE(options.packageDir,"/tmp/updater");
	TEST_COMPARE(options.scriptPath,"/tmp/updater/file_list.xml");
	TEST_COMPARE(options.waitPid,123456);

	for (int i=0; i < argc; i++)
	{
		free(argv[i]);
	}
}

int main(int,char**)
{
	TestList<TestUpdaterOptions> tests;
	tests.addTest(&TestUpdaterOptions::testOldFormatArgs);
	return TestUtils::runTest(tests);
}

Fix warnings about conversion from string literal to char*

UpdaterOptions::parse() will probably not have a need to modify its
arguments but for consistency with the declaration of main() it takes a char*,
so strdup() the strings.


#include "Item.h"

using namespace node;
using namespace v8;

namespace node_iTunes {

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

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

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

}

#include "Item.h"

using namespace node;
using namespace v8;

namespace node_iTunes {

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

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

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

}

Add support for 'Source' in Item::WrapInstance.


#include <cstdio>
#include <cstdint>
#include <string>
#include <memory>
#include <list>

#include "boost/format.hpp"

#include "packet.h"
#include "exceptions.h"
#include "parser.h"

namespace parse4880 {

PGPPacket::PGPPacket(std::string contents) : contents_(contents) {
}

std::shared_ptr<PGPPacket> PGPPacket::ParsePacket(uint8_t tag,
                                                  std::string packet) {
  switch (tag) {
    case 2:
      return std::shared_ptr<PGPPacket>(new SignaturePacket(packet));
      break;
    case 6:
      return std::shared_ptr<PGPPacket>(new PublicKeyPacket(packet));
      break;
    case 13:
      return std::shared_ptr<PGPPacket>(new UserIDPacket(packet));
      break;
    case 14:
      return std::shared_ptr<PGPPacket>(new PublicSubkeyPacket(packet));
      break;

    default:
      return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
  }
}

const std::list<std::shared_ptr<PGPPacket>>& PGPPacket::subpackets() const {
  return subpackets_;
}

const std::string& PGPPacket::contents() const {
  return contents_;
}

}

#include <cstdio>
#include <cstdint>
#include <string>
#include <memory>
#include <list>

#include "boost/format.hpp"

#include "packet.h"
#include "exceptions.h"
#include "parser.h"

namespace parse4880 {

PGPPacket::PGPPacket(std::string contents) : contents_(contents) {
}

std::shared_ptr<PGPPacket> PGPPacket::ParsePacket(uint8_t tag,
                                                  std::string packet) {
  try {
    switch (tag) {
      case 2:
        return std::shared_ptr<PGPPacket>(new SignaturePacket(packet));
        break;
      case 6:
        return std::shared_ptr<PGPPacket>(new PublicKeyPacket(packet));
        break;
      case 13:
        return std::shared_ptr<PGPPacket>(new UserIDPacket(packet));
        break;
      case 14:
        return std::shared_ptr<PGPPacket>(new PublicSubkeyPacket(packet));
        break;
      default:
        return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
    }
  } catch (unsupported_feature_error e) {
    return std::shared_ptr<PGPPacket>(new UnknownPGPPacket(tag, packet));
  }
}

const std::list<std::shared_ptr<PGPPacket>>& PGPPacket::subpackets() const {
  return subpackets_;
}

const std::string& PGPPacket::contents() const {
  return contents_;
}

}

Create UnknownPGPPackets in case of unsupported feature.


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

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

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

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

#include "tensorflow/core/platform/rocm_rocdl_path.h"

#include <stdlib.h>

#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/rocm/rocm_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

string ROCmRoot() {
  VLOG(3) << "ROCM root = " << TF_ROCM_TOOLKIT_PATH;
  return TF_ROCM_TOOLKIT_PATH;
}

}  // namespace tensorflow

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

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

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

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

#include "tensorflow/core/platform/rocm_rocdl_path.h"

#include <stdlib.h>

#if !defined(PLATFORM_GOOGLE) && TENSORFLOW_USE_ROCM
#include "third_party/gpus/rocm/rocm_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

string ROCmRoot() {
#if TENSORFLOW_USE_ROCM
  VLOG(3) << "ROCM root = " << TF_ROCM_TOOLKIT_PATH;
  return TF_ROCM_TOOLKIT_PATH;
#else
  return "";
#endif
}

}  // namespace tensorflow

Address potential issues encountered in non-ROCm systems.


#include "xchainer/python/error.h"

#include "xchainer/error.h"

#include "xchainer/python/common.h"

namespace xchainer {

namespace py = pybind11;  // standard convention

void InitXchainerError(pybind11::module& m) {
    py::register_exception<XchainerError>(m, "XchainerError");
    py::register_exception<DeviceError>(m, "DeviceError");
    py::register_exception<DtypeError>(m, "DtypeError");
    py::register_exception<DimensionError>(m, "DimensionError");
}

}  // namespace xchainer

#include "xchainer/python/error.h"

#include "xchainer/error.h"

#include "xchainer/python/common.h"

namespace xchainer {

namespace py = pybind11;  // standard convention

void InitXchainerError(pybind11::module& m) {
    py::register_exception<XchainerError>(m, "XchainerError");
    py::register_exception<BackendError>(m, "BackendError");
    py::register_exception<DeviceError>(m, "DeviceError");
    py::register_exception<DtypeError>(m, "DtypeError");
    py::register_exception<DimensionError>(m, "DimensionError");
}

}  // namespace xchainer

Add python binding to BackendError

Add python binding to BackendError


#include "../include/graph/dijkstra.cpp"
#include "../include/graph/weighted_graph.cpp"
#include "../include/others/fast_cin.cpp"
#include "../include/others/fast_cout.cpp"

using Graph = WeightedGraph<long long>;

int main() {
  int n, m, s, t;
  fcin >> n >> m >> s >> t;
  Graph rg(n);
  for (int i = 0; i < m; ++i) {
    int a, b;
    long long c;
    fcin >> a >> b >> c;
    add_edge(rg, b, a, c);
  }
  std::vector<int> prev;
  auto d = dijkstra(rg, t, prev);

  if (d[s] == inf<long long>()) {
    fcout << -1 << fendl;
    return 0;
  }
  if (d[s] == 0) {
    // Hack for multiple solutions.
    fcout << 0 << " " << 1 << fendl;
    fcout << s << " " << t << fendl;
    return 0;
  }

  std::vector<int> trace;
  trace.reserve(m);
  trace.push_back(s);
  while (trace.back() != t) {
    int v = trace.back();
    trace.push_back(prev[v]);
  }
  int size = trace.size() - 1;
  fcout << d[s] << " " << size << fendl;
  for (int i = 0; i < size; ++i) {
    fcout << trace[i] << " " << trace[i + 1] << fendl;
  }
  return 0;
}

#include "../include/graph/dijkstra.cpp"
#include "../include/graph/weighted_graph.cpp"
#include "../include/others/fast_cin.cpp"
#include "../include/others/fast_cout.cpp"

using Graph = WeightedGraph<long long>;

int main() {
  int n, m, s, t;
  fcin >> n >> m >> s >> t;
  Graph rg(n);
  for (int i = 0; i < m; ++i) {
    int a, b;
    long long c;
    fcin >> a >> b >> c;
    add_edge(rg, b, a, c);
  }
  std::vector<int> prev;
  auto d = dijkstra(rg, t, prev);

  if (d[s] == inf<long long>()) {
    fcout << -1 << fendl;
    return 0;
  }

  std::vector<int> trace;
  trace.reserve(m);
  trace.push_back(s);
  while (trace.back() != t) {
    int v = trace.back();
    trace.push_back(prev[v]);
  }
  int size = trace.size() - 1;
  fcout << d[s] << " " << size << fendl;
  for (int i = 0; i < size; ++i) {
    fcout << trace[i] << " " << trace[i + 1] << fendl;
  }
  return 0;
}

Remove needless hack for the newest oj version


#include <catch.hpp>
#include <string>
#include "test_data.hpp"
#include "libslic3r.h"

using namespace Slic3r::Test;
using namespace std::literals;

SCENARIO("PrintObject: object layer heights") {
    GIVEN("20mm cube and config that has a 3mm nozzle and a 2mm requested layer height") {
        auto config {Slic3r::Config::new_from_defaults()};
        TestMesh m { TestMesh::cube_20x20x20 };
        Slic3r::Model model;
        auto event_counter {0U};
        std::string stage;
        int value {0};
        config->set("fill_density", 0);
        config->set("nozzle_diameter", "3");
        config->set("layer_height", 2.0);
        config->set("first_layer_height", 2.0);

        WHEN("generate_object_layers() is called with a starting layer of 2mm") {
            auto print {Slic3r::Test::init_print({m}, model, config)};
            const auto& object = *(print->objects.at(0));
            auto result {print->objects[0]->generate_object_layers(2.0)};
            THEN("The output vector has 10 entries") {
                REQUIRE(result.size() == 10);
            }
            AND_THEN("Each layer is approximately 2mm above the previous Z") {
                coordf_t last = 0.0;
                for (size_t i = 0; i < result.size(); i++) {
                    REQUIRE((result[i] - last) == Approx(2.0));
                    last = result[i];
                }
            }
        }
    }
}

#include <catch.hpp>
#include <string>
#include "test_data.hpp"
#include "libslic3r.h"

using namespace Slic3r::Test;
using namespace std::literals;

SCENARIO("PrintObject: object layer heights") {
    GIVEN("20mm cube and config that has a 3mm nozzle and a 2mm requested layer height") {
        auto config {Slic3r::Config::new_from_defaults()};
        TestMesh m { TestMesh::cube_20x20x20 };
        Slic3r::Model model;
        config->set("nozzle_diameter", "3");
        config->set("layer_height", 2.0);
        config->set("first_layer_height", 2.0);

        WHEN("generate_object_layers() is called with a starting layer of 2mm") {
            auto print {Slic3r::Test::init_print({m}, model, config)};
            auto result {print->objects[0]->generate_object_layers(2.0)};
            THEN("The output vector has 10 entries") {
                REQUIRE(result.size() == 10);
            }
            AND_THEN("Each layer is approximately 2mm above the previous Z") {
                coordf_t last = 0.0;
                for (size_t i = 0; i < result.size(); i++) {
                    REQUIRE((result[i] - last) == Approx(2.0));
                    last = result[i];
                }
            }
        }
    }
}

Remove some dead code in the printgcode test.


#include "log.h"
#include "ethernetutil.h"

void initializeEthernet(EthernetDevice* device, Server* server,
        uint8_t MACAddr[], uint8_t IPAddr[])
{
    debug("initializing Ethernet...");
    device->ptrServer = server;
    Ethernet.begin(MACAddr, IPAddr);
    device->ptrServer->begin();
}

// The message bytes are sequentially popped from the
// send queue to the send buffer. After the buffer is full
// or the queue is emtpy, the contents of the buffer are
// sent over the ethernet to listening clients.
void processEthernetSendQueue(EthernetDevice* device)
{
    unsigned int byteCount = 0;
    char sendBuffer[MAX_MESSAGE_SIZE];
    while(!QUEUE_EMPTY(uint8_t, &device->sendQueue) &&
            byteCount < MAX_MESSAGE_SIZE) {
        sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue);
    }

    device->ptrServer->write((uint8_t*) sendBuffer, byteCount);
}

Move braces up onto same line as conditional.


/*
 * 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 "SkFontHost.h"
#include "SkTypeface.h"
#include "SkTypeface_win.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

/*
 * 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 "SkFontHost.h"
#include "SkTypeface.h"

//static
void SkFontHost::EnsureTypefaceAccessible(const SkTypeface& typeface) {
    //No sandbox, nothing to do.
}

Remove unneeded include which is breaking build.


//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Bastian Holst <bastianholst@gmx.de>
//

#include "KmlRegionTagHandler.h"

#include "MarbleDebug.h"

#include "KmlElementDictionary.h"
#include "GeoDataFeature.h"
#include "GeoParser.h"
#include "GeoDataRegion.h"

namespace Marble
{
namespace kml
{
KML_DEFINE_TAG_HANDLER( Region )

GeoNode* KmlRegionTagHandler::parse( GeoParser& parser ) const
{
    Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_Region ) );

    GeoDataRegion region;

    GeoStackItem parentItem = parser.parentElement();
#ifdef DEBUG_TAGS
    mDebug() << "Parsed <" << kmlTag_Region << ">"
             << " parent item name: " << parentItem.qualifiedName().first;
#endif

    if( parentItem.represents( kmlTag_Region ) || parentItem.represents( kmlTag_Region ) ) {
        parentItem.nodeAs<GeoDataFeature>()->setRegion( region );
        return &parentItem.nodeAs<GeoDataFeature>()->region();
    } else {
        return 0;
    }
}

}
}

//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Bastian Holst <bastianholst@gmx.de>
//

#include "KmlRegionTagHandler.h"

#include "MarbleDebug.h"

#include "KmlElementDictionary.h"
#include "GeoDataFeature.h"
#include "GeoParser.h"
#include "GeoDataRegion.h"

namespace Marble
{
namespace kml
{
KML_DEFINE_TAG_HANDLER( Region )

GeoNode* KmlRegionTagHandler::parse( GeoParser& parser ) const
{
    Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_Region ) );

    GeoDataRegion region;

    GeoStackItem parentItem = parser.parentElement();
#ifdef DEBUG_TAGS
    mDebug() << "Parsed <" << kmlTag_Region << ">"
             << " parent item name: " << parentItem.qualifiedName().first;
#endif

    if( parentItem.is<GeoDataFeature>() ) {
        parentItem.nodeAs<GeoDataFeature>()->setRegion( region );
        return &parentItem.nodeAs<GeoDataFeature>()->region();
    } else {
        return 0;
    }
}

}
}

Fix logic error in kml region parsing (region never attached to doc).

Thanks again to thomasjfox for reporting.


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

#include <core_io.h>
#include <primitives/transaction.h>
#include <test/fuzz/fuzz.h>
#include <util/strencodings.h>

#include <cassert>
#include <cstdint>
#include <string>
#include <vector>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string tx_hex = HexStr(buffer);
    CMutableTransaction mtx;
    const bool result_none = DecodeHexTx(mtx, tx_hex, false, false);
    const bool result_try_witness = DecodeHexTx(mtx, tx_hex, false, true);
    const bool result_try_witness_and_maybe_no_witness = DecodeHexTx(mtx, tx_hex, true, true);
    const bool result_try_no_witness = DecodeHexTx(mtx, tx_hex, true, false);
    assert(!result_none);
    if (result_try_witness_and_maybe_no_witness) {
        assert(result_try_no_witness || result_try_witness);
    }
    // if (result_try_no_witness) { // Uncomment when https://github.com/bitcoin/bitcoin/pull/17775 is merged
    if (result_try_witness) { // Remove stop-gap when https://github.com/bitcoin/bitcoin/pull/17775 is merged
        assert(result_try_witness_and_maybe_no_witness);
    }
}

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

#include <core_io.h>
#include <primitives/transaction.h>
#include <test/fuzz/fuzz.h>
#include <util/strencodings.h>

#include <cassert>
#include <cstdint>
#include <string>
#include <vector>

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string tx_hex = HexStr(buffer);
    CMutableTransaction mtx;
    const bool result_none = DecodeHexTx(mtx, tx_hex, false, false);
    const bool result_try_witness = DecodeHexTx(mtx, tx_hex, false, true);
    const bool result_try_witness_and_maybe_no_witness = DecodeHexTx(mtx, tx_hex, true, true);
    const bool result_try_no_witness = DecodeHexTx(mtx, tx_hex, true, false);
    assert(!result_none);
    if (result_try_witness_and_maybe_no_witness) {
        assert(result_try_no_witness || result_try_witness);
    }
    if (result_try_no_witness) {
        assert(result_try_witness_and_maybe_no_witness);
    }
}

Fix DecodeHexTx fuzzing harness issue

fuzz: Fix DecodeHexTx fuzzing harness issue


#include "mem/st/visitor/DepBuilder.hpp"

namespace mem { namespace st { namespace visitor {

DepBuilder::DepBuilder ()
{
   _name = "st.DepBuilder";
}

bool
DepBuilder::visit (st::Symbol* sym)
{
   printf("Visit...\n");
   if (sym->isClassSymbol())
   {
      visitClass(static_cast<st::Class*>(sym));
   }
   return true;
}

void
DepBuilder::visitClass (st::Class* cls_sym)
{
   printf("Visiting CLS !\n");
   _dep_tree.addDependency(NULL, cls_sym);
}

} } }

#include "mem/st/visitor/DepBuilder.hpp"

namespace mem { namespace st { namespace visitor {

DepBuilder::DepBuilder ()
{
   _name = "st.DepBuilder";
}

bool
DepBuilder::visit (st::Symbol* sym)
{
   if (sym->isClassSymbol())
   {
      visitClass(static_cast<st::Class*>(sym));
   }
   return true;
}

void
DepBuilder::visitClass (st::Class* cls_sym)
{
   _dep_tree.addDependency(NULL, cls_sym);
}

} } }

Add support for basic ops in LLVM

Add support for basic ops in LLVM


#include <MetaEvent.h>
#include <MetaFactory.h>
#include <ratio>

namespace test {

namespace metaEventSuite {

using namespace id::attribute;
using namespace std;

	class MetaEventSuite : public ::testing::Test {
		public:
			ID posID = Position::value();
			MetaFactory& f=MetaFactory::instance();
			MetaEvent e;
			MetaEventSuite(){
				MetaAttribute position = posID;
				position.value() = f.create({{0,1}, {1,1}, {2,1}});
				position.unit()  = Meter();
				position.scale() = ratio<1, 1000>();
        e.add(position);
			}
	};

	TEST_F(MetaEventSuite, findAttributeTest) {
		MetaAttribute test = posID;
		test.value() = f.create({{0,1}, {1,1}, {2,1}});
		test.unit()  = Meter();
		test.scale() = ratio<1, 1000>();
    const MetaAttribute* posPtr = e.attribute(posID);
    ASSERT_NE(posPtr, nullptr) << "Position attribute could not be retrieved";
    const MetaAttribute& pos = *posPtr;
		EXPECT_EQ(pos, test) << "Position attribute not stored correctly";
	}
}}

#include <MetaEvent.h>
#include <MetaFactory.h>
#include <ratio>

namespace test {

namespace metaEventSuite {

using namespace id::attribute;
using namespace std;

	class MetaEventSuite : public ::testing::Test {
		public:
			ID posID = Position::value();
			MetaFactory& f=MetaFactory::instance();
			MetaEvent e;
			MetaEventSuite(){
				MetaAttribute position = posID;
				position.value() = f.create({{{0,1}, {1,1}, {2,1}}});
				position.unit()  = Meter();
				position.scale() = ratio<1, 1000>();
        e.add(position);
			}
	};

	TEST_F(MetaEventSuite, findAttributeTest) {
		MetaAttribute test = posID;
		test.value() = f.create({{0, 1, 2}});
		test.unit()  = Meter();
		test.scale() = ratio<1, 1000>();
    const MetaAttribute* posPtr = e.attribute(posID);
    ASSERT_NE(posPtr, nullptr) << "Position attribute could not be retrieved";
    const MetaAttribute& pos = *posPtr;
		EXPECT_EQ(pos, test) << "Position attribute not stored correctly";
	}

	TEST_F(MetaEventSuite, typeTest) {
		EventType eT;
		eT.add(AttributeType(posID, ValueType(id::type::Double::value(), 1, 3, true), ratio<1,1000>(), Meter()));
		EXPECT_EQ((EventType)e, eT) << "Inferred MetaEvent-Type is wrong";
	}
}}

Add MetaEvent EventType cast test

Unit-Tests: Add MetaEvent EventType cast test


// RUN: %clang_cc1 %s -ast-print -fms-extensions | FileCheck %s

// FIXME: align attribute print

// CHECK: int x __attribute__((aligned(4, 0)));
int x __attribute__((aligned(4)));

// FIXME: Print this at a valid location for a __declspec attr.
// CHECK: int y __declspec(align(4, 1));
__declspec(align(4)) int y;

// CHECK: void foo() __attribute__((const));
void foo() __attribute__((const));

// CHECK: void bar() __attribute__((__const));
void bar() __attribute__((__const));

// FIXME: Print this with correct format and order.
// CHECK: void foo1() __attribute__((pure)) __attribute__((noinline));
void foo1() __attribute__((noinline, pure));

Add a test case for attribute print.

Add a test case for attribute print.

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


// This file is part of nbind, copyright (C) 2014-2015 BusFaster Ltd.
// Released under the MIT license, see LICENSE.

#include <cstdio>

#include "nbind/api.h"
#include "Coord.h"

class Nullable {

public:

	static Coord *getCoord() {
		return(new Coord(60, 25));
	}

	static Coord *getNull() {
		return(nullptr);
	}

	static void foo(Coord *coord) {
		printf("%p\n", coord);
	}

	static void bar(Coord *coord) {
		printf("%p\n", coord);
	}

};

#include "nbind/nbind.h"

#ifdef NBIND_CLASS

NBIND_CLASS(Coord) {}

NBIND_CLASS(Nullable) {
	method(getCoord);
	method(getNull);
	method(foo);
	method(bar, "bar", nbind::Nullable());
}

#endif

// This file is part of nbind, copyright (C) 2014-2015 BusFaster Ltd.
// Released under the MIT license, see LICENSE.

#include <cstdio>

#include "nbind/api.h"
#include "Coord.h"

class Nullable {

public:

	static Coord *getCoord() {
		return(new Coord(60, 25));
	}

	static Coord *getNull() {
		return(nullptr);
	}

	static void foo(Coord *coord) {
		printf("%p\n", coord);
	}

	static void bar(Coord *coord) {
		printf("%p\n", coord);
	}

};

#include "nbind/nbind.h"

#ifdef NBIND_CLASS

NBIND_CLASS(Nullable) {
	method(getCoord);
	method(getNull);
	method(foo);
	method(bar, "bar", nbind::Nullable());
}

#endif

Remove duplicate class from testbench. Otherwise wrong constructor gets run on OS X without any flaw in nbind itself.


#include "mdist.hpp"
#include "../search/idastar.hpp"
#include "../search/astar.hpp"
#include "../incl/utils.hpp"
#include <cstdio>

static void search(TilesMdist &, Search<TilesMdist> &, TilesMdist::State &);

int main(int argc, char *argv[]) {
	TilesMdist d(stdin);
//	Idastar<TilesMdist, true, true> srch;
	Astar<TilesMdist, true> srch;
	TilesMdist::State s0 = d.initstate();
	search(d, srch, s0);
	return 0;
}

static void search(TilesMdist &d, Search<TilesMdist> &srch, TilesMdist::State &s0) {
	dfheader(stdout);
	dfpair(stdout, "initial heuristic", "%d", d.h(s0));
	Result<TilesMdist> res = srch.search(d, s0);
	res.output(stdout);
	dffooter(stdout);
}

#include "mdist.hpp"
#include "../search/idastar.hpp"
#include "../search/astar.hpp"
#include "../incl/utils.hpp"
#include <cstdio>

static void search(TilesMdist&, Search<TilesMdist>&, TilesMdist::State&);
static Search<TilesMdist> *getsearch(int, char *[]);

int main(int argc, char *argv[]) {
	TilesMdist d(stdin);
	Search<TilesMdist> *srch = getsearch(argc, argv);
	TilesMdist::State s0 = d.initstate();
	search(d, *srch, s0);
	delete srch;
	return 0;
}

static void search(TilesMdist &d, Search<TilesMdist> &srch, TilesMdist::State &s0) {
	dfheader(stdout);
	dfpair(stdout, "initial heuristic", "%d", d.h(s0));
	Result<TilesMdist> res = srch.search(d, s0);
	res.output(stdout);
	dffooter(stdout);
}

static Search<TilesMdist> *getsearch(int argc, char *argv[]) {
	Search<TilesMdist> *srch = NULL;

	if (argc > 1 && strcmp(argv[1], "idastar") == 0)
		srch = new Idastar<TilesMdist, true, true>();
	else
		srch = new Astar<TilesMdist, true>();

	return srch;
}

Switch search algorithms via command-line arguments.


/**
 *  @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  @file main.cpp
 */

#include "JPetManager/JPetManager.h"
#include "ImageReco.h"
#include "SinogramCreator.h"
using namespace std;

int main(int argc, const char* argv[])
{
  JPetManager& manager = JPetManager::getManager();

  manager.registerTask<ImageReco>("ImageReco");
  manager.registerTask<SinogramCreator>("SinogramCreator");

  manager.useTask("ImageReco", "unk.evt", "reco");
  manager.useTask("SinogramCreator", "unk.evt", "sino");

  manager.run(argc, argv);
}

/**
 *  @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  @file main.cpp
 */

#include "JPetManager/JPetManager.h"
#include "ImageReco.h"
#include "SinogramCreator.h"
#include "SinogramCreatorMC.h"
using namespace std;

int main(int argc, const char* argv[])
{
  JPetManager& manager = JPetManager::getManager();

  manager.registerTask<ImageReco>("ImageReco");
  manager.registerTask<SinogramCreator>("SinogramCreator");
  manager.registerTask<SinogramCreator>("SinogramCreatorMC");

  manager.useTask("ImageReco", "unk.evt", "reco");
  manager.useTask("SinogramCreator", "unk.evt", "sino");
  manager.useTask("SinogramCreatorMC", "unk.evt", "sino");

  manager.run(argc, argv);
}

Add SinogramCreatorMC to manager list

Add SinogramCreatorMC to manager list


#include <cstdarg>
#include <ncurses.h>

static const char* mes = NULL;
extern bool showing_message;
bool showing_message = false;

static void showmes() {
    int y,x,rows,_;
    getyx(stdscr,y,x);
    getmaxyx(stdscr,rows,_);
    move(rows-1,0);

    clrtoeol();
    printw(mes);

    move(y,x);
}

void hook_show_message() {
    if(showing_message) {
        showmes();
        showing_message = false;
    }
}

void show_message(const char* message) {
    showing_message = true;
    mes = message;
    showmes();
}

void clear_message() {
    mes = "";
    showmes();
}

#include <cstdarg>
#include <ncurses.h>

static const char* mes = NULL;
extern bool showing_message;
bool showing_message = false;

static void showmes() {
    int y,x,rows,_;
    getyx(stdscr,y,x);
    getmaxyx(stdscr,rows,_);
    move(rows-1,0);

    clrtoeol();
    printw("%s",mes);

    move(y,x);
}

void hook_show_message() {
    if(showing_message) {
        showmes();
        showing_message = false;
    }
}

void show_message(const char* message) {
    showing_message = true;
    mes = message;
    showmes();
}

void clear_message() {
    mes = "";
    showmes();
}

Use ``%s`` in first arg of ``printw`` to prevent errors


// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instr-generate | FileCheck %s

struct Member {
  ~Member();
};

struct A {
  virtual ~A();
};

struct B : A {
  Member m;
  virtual ~B();
};

// Complete dtor
// CHECK: @__llvm_profile_name__ZN1BD1Ev = private constant [9 x i8] c"_ZN1BD1Ev"

// Deleting dtor
// CHECK: @__llvm_profile_name__ZN1BD0Ev = private constant [9 x i8] c"_ZN1BD0Ev"

// Complete dtor counters and profile data
// CHECK: @__llvm_profile_counters__ZN1BD1Ev = private global [1 x i64] zeroinitializer
// CHECK: @__llvm_profile_data__ZN1BD1Ev =

// Deleting dtor counters and profile data
// CHECK: @__llvm_profile_counters__ZN1BD0Ev = private global [1 x i64] zeroinitializer
// CHECK: @__llvm_profile_data__ZN1BD0Ev =

B::~B() { }

// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instr-generate | FileCheck %s

struct Member {
  ~Member();
};

struct A {
  virtual ~A();
};

struct B : A {
  Member m;
  virtual ~B();
};

// Complete dtor
// CHECK: @__llvm_profile_name__ZN1BD1Ev = private constant [9 x i8] c"_ZN1BD1Ev"

// Deleting dtor
// CHECK: @__llvm_profile_name__ZN1BD0Ev = private constant [9 x i8] c"_ZN1BD0Ev"

// Complete dtor counters and profile data
// CHECK: @__llvm_profile_counters__ZN1BD1Ev = private global [1 x i64] zeroinitializer
// CHECK: @__llvm_profile_data__ZN1BD1Ev =

// Deleting dtor counters and profile data
// CHECK: @__llvm_profile_counters__ZN1BD0Ev = private global [1 x i64] zeroinitializer
// CHECK: @__llvm_profile_data__ZN1BD0Ev =

B::~B() { }

InstrProf: Change this triple back to %itanium_abi_triple

In my rush to fix the linux bots in r237805, I accidentally committed
a change to the triple. Revert that part.

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


//===-- Passes.cpp - Target independent code generation passes ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//

#include "llvm/CodeGen/Passes.h"
#include "Support/CommandLine.h"
#include <iostream>
using namespace llvm;

namespace {
  enum RegAllocName { simple, local, linearscan, iterativescan };

  cl::opt<RegAllocName>
  RegAlloc(
    "regalloc",
    cl::desc("Register allocator to use: (default = simple)"),
    cl::Prefix,
    cl::values(
       clEnumVal(simple,        "  simple register allocator"),
       clEnumVal(local,         "  local register allocator"),
       clEnumVal(linearscan,    "  linear scan register allocator"),
       clEnumVal(iterativescan, "  iterative scan register allocator"),
       clEnumValEnd),
    cl::init(local));
}

FunctionPass *llvm::createRegisterAllocator() {
  switch (RegAlloc) {
  default:
    std::cerr << "no register allocator selected";
    abort();
  case simple:
    return createSimpleRegisterAllocator();
  case local:
    return createLocalRegisterAllocator();
  case linearscan:
    return createLinearScanRegisterAllocator();
  case iterativescan:
    return createIterativeScanRegisterAllocator();
  }
}

//===-- Passes.cpp - Target independent code generation passes ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//

#include "llvm/CodeGen/Passes.h"
#include "Support/CommandLine.h"
#include <iostream>
using namespace llvm;

namespace {
  enum RegAllocName { simple, local, linearscan, iterativescan };

  cl::opt<RegAllocName>
  RegAlloc(
    "regalloc",
    cl::desc("Register allocator to use: (default = simple)"),
    cl::Prefix,
    cl::values(
       clEnumVal(simple,        "  simple register allocator"),
       clEnumVal(local,         "  local register allocator"),
       clEnumVal(linearscan,    "  linear scan register allocator"),
       clEnumVal(iterativescan, "  iterative scan register allocator"),
       clEnumValEnd),
    cl::init(linearscan));
}

FunctionPass *llvm::createRegisterAllocator() {
  switch (RegAlloc) {
  default:
    std::cerr << "no register allocator selected";
    abort();
  case simple:
    return createSimpleRegisterAllocator();
  case local:
    return createLocalRegisterAllocator();
  case linearscan:
    return createLinearScanRegisterAllocator();
  case iterativescan:
    return createIterativeScanRegisterAllocator();
  }
}

Make linear scan the default

Make linear scan the default

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


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

#include "base/native_library.h"

#include <dlfcn.h>

#include "base/file_path.h"
#include "base/logging.h"

namespace base {

// static
NativeLibrary LoadNativeLibrary(const FilePath& library_path) {
  void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY);
  if (!dl)
    NOTREACHED() << "dlopen failed: " << dlerror();

  return dl;
}

// static
void UnloadNativeLibrary(NativeLibrary library) {
  int ret = dlclose(library);
  if (ret < 0)
    NOTREACHED() << "dlclose failed: " << dlerror();
}

// static
void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
                                          NativeLibraryFunctionNameType name) {
  return dlsym(library, name);
}

}  // namespace base

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

#include "base/native_library.h"

#include <dlfcn.h>

#include "base/file_path.h"
#include "base/logging.h"

namespace base {

// static
NativeLibrary LoadNativeLibrary(const FilePath& library_path) {
  void* dl = dlopen(library_path.value().c_str(), RTLD_LAZY|RTLD_DEEPBIND);
  if (!dl)
    NOTREACHED() << "dlopen failed: " << dlerror();

  return dl;
}

// static
void UnloadNativeLibrary(NativeLibrary library) {
  int ret = dlclose(library);
  if (ret < 0)
    NOTREACHED() << "dlclose failed: " << dlerror();
}

// static
void* GetFunctionPointerFromNativeLibrary(NativeLibrary library,
                                          NativeLibraryFunctionNameType name) {
  return dlsym(library, name);
}

}  // namespace base

Use RTLD_DEEPBIND to make sure plugins don't use Chrome's symbols instead of their own

Review URL: http://codereview.chromium.org/112030
Patch from Antoine Labour <piman@google.com>.

git-svn-id: http://src.chromium.org/svn/trunk/src@16278 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: 8633e5e7c36b36faa44204e382a138caa205b45a


#include<string>
using namespace std;

class CCipher {
public:
	string decode(string cipherText, int shift) {
		string orig;
		for (char c : cipherText) {
			orig += 'A' + (c - 'A' - shift) % 26 ;
			//orig.append();
		}
		return orig;
	}
};

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

class CCipher {
public:
  string decode(string cipherText, int shift) {
    string orig;
    for (char c : cipherText) {
      orig += 'A' + (c - 'A' - shift + 26) % 26 ;
    }
    return orig;
  }
};

int main() {
  CCipher cc;
  assert(cc.decode("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 10) == "QRSTUVWXYZABCDEFGHIJKLMNOP");
}

Fix SRM 147, Div 2, Problem CCipher

Fix SRM 147, Div 2, Problem CCipher

- previously without system test checks
- plus length of alphabet, in case of negative shifted index


// RUN: %clang_cc1 -std=c++98 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -DNOEXCEPT="throw()" -DBAD_ALLOC="throw(std::bad_alloc)"
// RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -DNOEXCEPT=noexcept -DBAD_ALLOC=
// RUN: %clang_cc1 -std=c++1y %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -DNOEXCEPT=noexcept -DBAD_ALLOC=

// dr412: yes
// lwg404: yes
// lwg2340: yes

// REQUIRES: LP64
typedef __SIZE_TYPE__ size_t;
namespace std { struct bad_alloc {}; }
int x;
inline void* operator new(size_t) BAD_ALLOC; // expected-error {{cannot be declared 'inline'}}
inline void* operator new[](size_t) BAD_ALLOC; // expected-error {{cannot be declared 'inline'}}
inline void operator delete(void*) NOEXCEPT; // expected-error {{cannot be declared 'inline'}}
inline void operator delete[](void*) NOEXCEPT; // expected-error {{cannot be declared 'inline'}}
#if __cplusplus >= 201402L
inline void operator delete(void*, size_t) NOEXCEPT; // expected-error {{cannot be declared 'inline'}}
inline void operator delete[](void*, size_t) NOEXCEPT; // expected-error {{cannot be declared 'inline'}}
#endif

// RUN: %clang_cc1 -std=c++98 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -DNOEXCEPT="throw()" -DBAD_ALLOC="throw(std::bad_alloc)"
// RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -DNOEXCEPT=noexcept -DBAD_ALLOC=
// RUN: %clang_cc1 -std=c++1y %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -DNOEXCEPT=noexcept -DBAD_ALLOC=

// dr412: yes
// lwg404: yes
// lwg2340: yes

// REQUIRES: LP64
typedef __SIZE_TYPE__ size_t;
namespace std { struct bad_alloc {}; }

inline void* operator new(size_t) BAD_ALLOC; // expected-error {{cannot be declared 'inline'}}
inline void* operator new[](size_t) BAD_ALLOC; // expected-error {{cannot be declared 'inline'}}
inline void operator delete(void*) NOEXCEPT; // expected-error {{cannot be declared 'inline'}}
inline void operator delete[](void*) NOEXCEPT; // expected-error {{cannot be declared 'inline'}}
#if __cplusplus >= 201402L
inline void operator delete(void*, size_t) NOEXCEPT; // expected-error {{cannot be declared 'inline'}}
inline void operator delete[](void*, size_t) NOEXCEPT; // expected-error {{cannot be declared 'inline'}}
#endif

Remove unused variable from test.

Remove unused variable from test.

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


/*
 *
 * Copyright (C) 2020 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 */

#include "source/loader/driver_discovery.h"

#include "source/inc/ze_util.h"

namespace loader {

static const char *knownDriverNames[] = {
    MAKE_LIBRARY_NAME("ze_intel_gpu", "1"),
};

std::vector<DriverLibraryPath> discoverEnabledDrivers() {
    std::vector<DriverLibraryPath> enabledDrivers;
    for (auto path : knownDriverNames) {
        enabledDrivers.emplace_back(path);
    }
    return enabledDrivers;
}

} // namespace loader

/*
 *
 * Copyright (C) 2020 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 */

#include "source/loader/driver_discovery.h"

#include "source/inc/ze_util.h"
#include <iostream>
#include <sstream>
#include <string>

namespace loader {

static const char *knownDriverNames[] = {
    MAKE_LIBRARY_NAME("ze_intel_gpu", "1"),
};

std::vector<DriverLibraryPath> discoverEnabledDrivers() {
  std::vector<DriverLibraryPath> enabledDrivers;
  const char *altDrivers = nullptr;

  // ZE_ENABLE_ALT_DRIVERS is for development/debug only
  altDrivers = getenv("ZE_ENABLE_ALT_DRIVERS");
  if (altDrivers == nullptr) {
    for (auto path : knownDriverNames) {
      enabledDrivers.emplace_back(path);
    }
  } else {
    std::stringstream ss(altDrivers);
    while (ss.good()) {
      std::string substr;
      getline(ss, substr, ',');
      enabledDrivers.emplace_back(substr);
    }
  }
  return enabledDrivers;
}

} // namespace loader

Add environment variable for alternate drivers

Signed-off-by: davidoli <e17d874a9837084fa613f4cf2a73bcec0a2fe1c1@intel.com>


// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/node_includes.h"

namespace {

void Initialize(v8::Handle<v8::Object> exports, v8::Handle<v8::Value> unused,
                v8::Handle<v8::Context> context, void* priv) {
  gfx::Screen* screen = gfx::Screen::GetNativeScreen();
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("getCursorScreenPoint",
                 base::Bind(&gfx::Screen::GetCursorScreenPoint,
                            base::Unretained(screen)));
  dict.SetMethod("getPrimaryDisplay",
                 base::Bind(&gfx::Screen::GetPrimaryDisplay,
                            base::Unretained(screen)));
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_screen, Initialize)

// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/node_includes.h"

namespace {

void Initialize(v8::Handle<v8::Object> exports, v8::Handle<v8::Value> unused,
                v8::Handle<v8::Context> context, void* priv) {
  auto screen = base::Unretained(gfx::Screen::GetNativeScreen());
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("getCursorScreenPoint",
                 base::Bind(&gfx::Screen::GetCursorScreenPoint, screen));
  dict.SetMethod("getPrimaryDisplay",
                 base::Bind(&gfx::Screen::GetPrimaryDisplay, screen));
  dict.SetMethod("getAllDisplays",
                 base::Bind(&gfx::Screen::GetAllDisplays, screen));
  dict.SetMethod("getDisplayNearestPoint",
                 base::Bind(&gfx::Screen::GetDisplayNearestPoint, screen));
  dict.SetMethod("getDisplayMatching",
                 base::Bind(&gfx::Screen::GetDisplayMatching, screen));
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_screen, Initialize)

Add a few more API bindings

Add a few more API bindings


// PR1013
// Check to make sure debug symbols use the correct name for globals and
// functions.  Will not assemble if it fails to.
// RUN: %clang_cc1 -emit-llvm -g -o - %s | FileCheck %s

// CHECK: @"\01f\01oo"
int foo __asm__("f\001oo");

int bar() {
  return foo;
}

// PR1013
// Check to make sure debug symbols use the correct name for globals and
// functions.  Will not assemble if it fails to.
// RUN: %clang_cc1 -emit-llvm -g -o - %s | FileCheck %s

// CHECK: f\01oo"
int foo __asm__("f\001oo");

int bar() {
  return foo;
}

Modify the check line to be happier on windows.

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


#include <cuda_runtime_api.h>
#include <stdio.h>

int main(void)
{
  int num_devices = 0;
  cudaGetDeviceCount(&num_devices);
  if(num_devices > 0)
  {
    cudaDeviceProp properties;
    cudaGetDeviceProperties(&properties, 0);
    printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor);
    return 0;
  } // end if

  return -1;
}

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

void usage(const char *name)
{
  printf("usage: %s [device_id]\n", name);
}

int main(int argc, char **argv)
{
  int num_devices = 0;
  int device_id = 0;
  if(argc == 2)
  {
    device_id = atoi(argv[1]);
  }
  else if(argc > 2)
  {
    usage(argv[0]);
    exit(-1);
  }

  cudaGetDeviceCount(&num_devices);
  if(num_devices > device_id)
  {
    cudaDeviceProp properties;
    cudaGetDeviceProperties(&properties, device_id);
    printf("--gpu-architecture=sm_%d%d", properties.major, properties.minor);
    return 0;
  } // end if
  else
  {
    printf("No available device with id %d\n", device_id);
  }

  return -1;
}

Add an optional device_id command line argument.

--HG--
extra : convert_revision : svn%3A83215879-3e5a-4751-8c9d-778f44bb06a5/trunk%40345


// RUN: CINDEXTEST_EDITING=1 c-index-test -test-load-source local %s -Wuninitialized -Werror=unused 2>&1 | FileCheck -check-prefix=DIAGS %s

// Make sure -Wuninitialized works even though the header had a warn-as-error occurrence.

// DIAGS: error: unused variable 'x'
// DIAGS: warning: variable 'x1' is uninitialized
// DIAGS-NOT: error: use of undeclared identifier
// DIAGS: warning: variable 'x1' is uninitialized

#include "pch-warn-as-error-code-split.h"

void test() {
  int x1; // expected-note {{initialize}}
  int x2 = x1; // expected-warning {{uninitialized}}
  (void)x2;
  foo_head();
}

// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source local %s -Wuninitialized -Werror=unused 2>&1 | FileCheck -check-prefix=DIAGS %s

// Make sure -Wuninitialized works even though the header had a warn-as-error occurrence.

// DIAGS: error: unused variable 'x'
// DIAGS: warning: variable 'x1' is uninitialized
// DIAGS-NOT: error: use of undeclared identifier
// DIAGS: warning: variable 'x1' is uninitialized

#include "pch-warn-as-error-code-split.h"

void test() {
  int x1; // expected-note {{initialize}}
  int x2 = x1; // expected-warning {{uninitialized}}
  (void)x2;
  foo_head();
}

[test] Add 'env' to fix test failures in windows bots.

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


#include "common.th"

.global putnum
    // putnum takes number in C, (row,col) in D,E, and field width in F
putnum:
    pushall(h,i,j,k,l,m)
    h <- 0x100
    h <- h << 8         // h is video base
    k <- d * 80 + e     // k is offset into display
    k <- k + f          // start at right side of field
    i <- rel(hexes)     // i is base of hex transform

putnumloop:
    j <- [c & 0xf + i]  // j is character for bottom 4 bits of c
    j -> [h + k]        // write character to display
    k <- k - 1          // go to the left one character
    c <- c >>> 4        // shift down for next iteration
    l <- c == 0         // shall we loop ?
    jzrel(l,putnumloop)

putnumdone:
    popall_ret(h,i,j,k,l,m)

hexes:
    .word '0', '1', '2', '3', '4', '5', '6', '7'
    .word '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'

#include "common.th"

.global putnum
    // putnum takes number in C, (row,col) in D,E, and field width in F
putnum:
    pushall(h,i,j,k,l,m)
    h <- 0x10000        // h is video base
    k <- d * 80 + e     // k is offset into display
    k <- k + f          // start at right side of field
    i <- rel(hexes)     // i is base of hex transform

putnumloop:
    j <- [c & 0xf + i]  // j is character for bottom 4 bits of c
    j -> [h + k]        // write character to display
    k <- k - 1          // go to the left one character
    c <- c >>> 4        // shift down for next iteration
    l <- c == 0         // shall we loop ?
    jzrel(l,putnumloop)

putnumdone:
    popall_ret(h,i,j,k,l,m)

hexes:
    .word '0', '1', '2', '3', '4', '5', '6', '7'
    .word '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'

Use type3 to simplify expressions

Use type3 to simplify expressions