#include "gamelib/sprite/SpriteData.hpp"
#include <cmath>

namespace gamelib
{
    AnimationData::AnimationData() :
        length(1),
        speed(0),
        offset(0)
    { }

    void AnimationData::update(float fps)
    {
        offset = std::fmod(offset + speed / fps, length);
    }

    sf::IntRect AnimationData::getRect(int texw, int texh) const
    {
        int x = rect.left + (int)offset * rect.width;
        return sf::IntRect(x % texw, (rect.top + x / texw * rect.height) % texh, rect.width, rect.height);
    }
}

#include "gamelib/sprite/SpriteData.hpp"
#include <cmath>

namespace gamelib
{
    AnimationData::AnimationData() :
        length(1),
        speed(0),
        offset(0)
    { }

    void AnimationData::update(float fps)
    {
        if (length > 1 && speed != 0)
            offset = std::fmod(offset + speed / fps, length);
    }

    sf::IntRect AnimationData::getRect(int texw, int texh) const
    {
        int x = rect.left + (int)offset * rect.width;
        return sf::IntRect(x % texw, (rect.top + x / texw * rect.height) % texh, rect.width, rect.height);
    }
}

Fix bug causing a wrong frame index

Fix bug causing a wrong frame index

Using this formula to calculate the image index
    offset = std::fmod(offset + speed / fps, length),
a length of 1 or speed = 0 and an offset > 0 would result in a wrong
index.


/*
MIT License

Copyright (c) 2017 Blockchain-VCS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

bool __nosha256 = false;
bool __useJSONFormat = false;

Add Use JSON as a command line argument

Add Use JSON as a command line argument


/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_AppMessageHandler.hpp"

namespace JDKSAvdeccMCU
{

}

/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_AppMessageHandler.hpp"

namespace JDKSAvdeccMCU
{
    const char *jdksavdeccmcu_appmessagehandler_file = __FILE__;
}

Add symbol to empty file

Add symbol to empty file


#include "librt_error.h"

using namespace librt;

Error::Error() :
    errorCode_(Error::Code::Ok),
    message_()
{
}

Error::Error(Error::Code errorCode, std::__cxx11::string &&message) :
    errorCode_(errorCode),
    message_(message)
{
}

Error::Error(Error &&other) :
    errorCode_(other.errorCode_),
    message_(std::move(other.message_))
{
}

Error &Error::operator =(Error &&other)
{
    errorCode_ = other.errorCode_;
    message_ = std::move(other.message_);

    return *this;
}

Error &Error::operator =(std::pair<Error::Code, std::string> &&other)
{
    errorCode_ = other.first;
    message_ = std::move(other.second);

    return *this;
}

Error::Code Error::errorCode() const
{
    return errorCode_;
}

const std::string &Error::message() const
{
    return message_;
}

#include "librt_error.h"

using namespace librt;

Error::Error() :
    errorCode_(Error::Code::Ok),
    message_()
{
}

Error::Error(Error::Code errorCode, std::string &&message) :
    errorCode_(errorCode),
    message_(message)
{
}

Error::Error(Error &&other) :
    errorCode_(other.errorCode_),
    message_(std::move(other.message_))
{
}

Error &Error::operator =(Error &&other)
{
    errorCode_ = other.errorCode_;
    message_ = std::move(other.message_);

    return *this;
}

Error &Error::operator =(std::pair<Error::Code, std::string> &&other)
{
    errorCode_ = other.first;
    message_ = std::move(other.second);

    return *this;
}

Error::Code Error::errorCode() const
{
    return errorCode_;
}

const std::string &Error::message() const
{
    return message_;
}

Remove cxx11 namespace from Error

Remove cxx11 namespace from Error


//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 <iostream>

#include "AssemblyFileWriter.hpp"
#include "Functions.hpp"

using namespace eddic;

using std::endl;

void MainDeclaration::write(AssemblyFileWriter& writer){
    writer.stream() << ".text" << endl
                    << ".globl main" << endl
                    << "\t.type main, @function" << endl;
}

void FunctionCall::checkFunctions(Program& program){
    if(!program.exists(m_function)){
        throw CompilerException("The function does not exists");
    }
}

void Function::write(AssemblyFileWriter& writer){
    writer.stream() << endl << m_name << ":" << endl;

    writer.stream() << "pushl %ebp" << std::endl;
    writer.stream() << "movl %esp, %ebp" << std::endl;

    ParseNode::write(writer);

    writer.stream() << "leave" << std::endl;
    writer.stream() << "ret" << std::endl;
}

void FunctionCall::write(AssemblyFileWriter& writer){
    writer.stream() << "call " << m_function << endl;
}

//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 <iostream>

#include "AssemblyFileWriter.hpp"
#include "Functions.hpp"

using namespace eddic;

using std::endl;

void MainDeclaration::write(AssemblyFileWriter& writer){
    writer.stream() << ".text" << endl
                    << ".globl main" << endl
                    << "\t.type main, @function" << endl;
}

void FunctionCall::checkFunctions(Program& program){
    if(!program.exists(m_function)){
        throw CompilerException("The function \"" + m_function + "\"does not exists");
    }
}

void Function::write(AssemblyFileWriter& writer){
    writer.stream() << endl << m_name << ":" << endl;

    writer.stream() << "pushl %ebp" << std::endl;
    writer.stream() << "movl %esp, %ebp" << std::endl;

    ParseNode::write(writer);

    writer.stream() << "leave" << std::endl;
    writer.stream() << "ret" << std::endl;
}

void FunctionCall::write(AssemblyFileWriter& writer){
    writer.stream() << "call " << m_function << endl;
}

Add the function name on the error reporting


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

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

#include "chrome/browser/sync/glue/data_type_controller.h"
#include "sync/util/data_type_histogram.h"

namespace browser_sync {

bool DataTypeController::IsUnrecoverableResult(StartResult result) {
  return (result == UNRECOVERABLE_ERROR);
}

syncer::SyncError DataTypeController::CreateAndUploadError(
    const tracked_objects::Location& location,
    const std::string& message,
    syncable::ModelType type) {
  ChromeReportUnrecoverableError();
  return syncer::SyncError(location, message, type);
}

void DataTypeController::RecordUnrecoverableError(
    const tracked_objects::Location& from_here,
    const std::string& message) {
  DVLOG(1) << "Datatype Controller failed for type "
           << ModelTypeToString(type()) << "  "
           << message << " at location "
           << from_here.ToString();
  UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeRunFailures", type(),
                            syncable::MODEL_TYPE_COUNT);
  ChromeReportUnrecoverableError();
}

}  // namespace browser_sync

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

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

#include "chrome/browser/sync/glue/data_type_controller.h"
#include "sync/util/data_type_histogram.h"

namespace browser_sync {

bool DataTypeController::IsUnrecoverableResult(StartResult result) {
  return (result == UNRECOVERABLE_ERROR);
}

syncer::SyncError DataTypeController::CreateAndUploadError(
    const tracked_objects::Location& location,
    const std::string& message,
    syncable::ModelType type) {
  // TODO(sync): remove this once search engines triggers less errors, such as
  // due to crbug.com/130448.
  if (type != syncable::SEARCH_ENGINES)
    ChromeReportUnrecoverableError();
  return syncer::SyncError(location, message, type);
}

void DataTypeController::RecordUnrecoverableError(
    const tracked_objects::Location& from_here,
    const std::string& message) {
  DVLOG(1) << "Datatype Controller failed for type "
           << ModelTypeToString(type()) << "  "
           << message << " at location "
           << from_here.ToString();
  UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeRunFailures", type(),
                            syncable::MODEL_TYPE_COUNT);

  // TODO(sync): remove this once search engines triggers less errors, such as
  // due to crbug.com/130448.
  if (type() != syncable::SEARCH_ENGINES)
    ChromeReportUnrecoverableError();
}

}  // namespace browser_sync

[Sync] Disable uploading of search engine datatype errors.

Due to their prevalence, and because the ones occurring all have bugs tracking
them, we're disabling the uploading until the error rate goes down.

BUG=135196,130448
TEST=

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

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


#include <string.h>
#include "tree_sitter/runtime.h"

void test_log(void *payload, TSLogType type, const char *string) { }

TSLogger logger = {
  .log = test_log,
};

extern "C" const TSLanguage *TS_LANG();

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  const char *str = reinterpret_cast<const char *>(data);

  TSParser *parser = ts_parser_new();
  ts_parser_set_language(parser, TS_LANG());
  ts_parser_halt_on_error(parser, TS_HALT_ON_ERROR);

  TSTree *tree = ts_parser_parse_string(parser, NULL, str, size);
  TSNode root_node = ts_document_root_node(tree);

  ts_tree_delete(tree);
  ts_parser_delete(parser);

  return 0;
}

#include <string.h>
#include "tree_sitter/runtime.h"

void test_log(void *payload, TSLogType type, const char *string) { }

TSLogger logger = {
  .log = test_log,
};

extern "C" const TSLanguage *TS_LANG();

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  const char *str = reinterpret_cast<const char *>(data);

  TSParser *parser = ts_parser_new();
  ts_parser_set_language(parser, TS_LANG());
  ts_parser_halt_on_error(parser, TS_HALT_ON_ERROR);

  TSTree *tree = ts_parser_parse_string(parser, NULL, str, size);
  TSNode root_node = ts_tree_root_node(tree);

  ts_tree_delete(tree);
  ts_parser_delete(parser);

  return 0;
}

Use ts_tree_root_node in fuzz driver

Use ts_tree_root_node in fuzz driver


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

#include "datastore.h"

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

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(Post_EmptyTask_Test) {
		// You::DataStore::DataStore sut;
		// sut.post(std::unordered_map<std::wstring, std::wstring>());
		Assert::IsTrue(true);
	}
};
}  // namespace YouDataStoreTests

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

#include "datastore.h"

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

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(DataStoreDummyTest) {
		// You::DataStore::DataStore sut;
		// sut.post(std::unordered_map<std::wstring, std::wstring>());
		Assert::IsTrue(true);
	}
};
}  // namespace YouDataStoreTests

Rename incomplete test on datastore to DataStoreDummyTest


#include <iostream>

#include "EventAction.hh"

#include "G4Event.hh"
#include "RunAction.hh"
#include "Run.hh"

EventAction::EventAction():
    G4UserEventAction{},
    _draw_flag("all")
{
}

EventAction::~EventAction()
{
}

void EventAction::BeginOfEventAction(const G4Event* evt)
{
    G4cout << "EV: " << evt->GetEventID() << G4endl;
}

void EventAction::EndOfEventAction(const G4Event*)
{
}

#include <iostream>

#include "EventAction.hh"

#include "G4Event.hh"
#include "RunAction.hh"
#include "Run.hh"

EventAction::EventAction():
    G4UserEventAction{},
    _draw_flag("all")
{
}

EventAction::~EventAction()
{
}

void EventAction::BeginOfEventAction(const G4Event*)
{
    // G4cout << "EV: " << evt->GetEventID() << G4endl;
}

void EventAction::EndOfEventAction(const G4Event*)
{
}

Remove printout from event action

Remove printout from event action


#include "cardreader.h"

#include <QEvent>
#include <QKeyEvent>

bool CardReader::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() != QEvent::KeyPress) {
		return false;
	}

	if (cardNumber.isEmpty()) {
		writeTime.start();
	}

	//accumulate characters
	QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
	cardNumber += keyEvent->text();

	//send signal on enter (RFID card reader ends string input with an enter)
	if (keyEvent->key() == Qt::Key_Return) {
		//disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader
		if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) {
			emit newCardNumber(cardNumber);
		}

		cardNumber.clear();
	}

	return true;
}

#include "cardreader.h"

#include <QEvent>
#include <QKeyEvent>

bool CardReader::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() != QEvent::KeyPress) {
		return false;
	}

	if (cardNumber.isEmpty()) {
		writeTime.start();
	}

	//accumulate characters
	QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
	cardNumber += keyEvent->text();

	//send signal on enter (RFID card reader ends string input with an enter)
	if (keyEvent->key() == Qt::Key_Return) {
		//disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader
		if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) {
			emit newCardNumber(cardNumber.simplified());
		}

		cardNumber.clear();
	}

	return true;
}

Simplify card string before emitting, in case any key characters are added by the return.


#include <hw/serial.hpp>

extern "C"
void __serial_print1(const char* cstr)
{
  const uint16_t port = 0x3F8; // Serial 1
  while (*cstr) {
    while (not (hw::inb(port + 5) & 0x20));
    hw::outb(port, *cstr++);
  }
}

#include <hw/serial.hpp>

extern "C"
void __serial_print1(const char* cstr)
{
  const uint16_t port = 0x3F8; // Serial 1
  static bool init = false;
  if (!init) {
    init = true;
    // properly initialize serial port
    hw::outb(port + 1, 0x00);    // Disable all interrupts
    hw::outb(port + 3, 0x80);    // Enable DLAB (set baud rate divisor)
    hw::outb(port + 0, 0x03);    // Set divisor to 3 (lo byte) 38400 baud
    hw::outb(port + 1, 0x00);    //                  (hi byte)
    hw::outb(port + 3, 0x03);    // 8 bits, no parity, one stop bit
    hw::outb(port + 2, 0xC7);    // Enable FIFO, clear them, with 14-byte threshold
  }

  while (*cstr) {
    while (not (hw::inb(port + 5) & 0x20));
    hw::outb(port, *cstr++);
  }
}

serial: Initialize the default serial port properly


#include "mainwindow.h"
#include <QGridLayout>
#include <QLabel>
#include <QEvent>
#include <QKeyEvent>

#include <iostream>

MainWindow::MainWindow(QWidget *parent)
{
	QGridLayout *layout = new QGridLayout(this);
	layout->addWidget(new QLabel("ARK kryssesystem"));

	//install cardReader as an filter which intercepts keyboard events
	CardReader *cardReader = new CardReader(this);
	installEventFilter(cardReader);
}

bool CardReader::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() != QEvent::KeyPress) {
		return false;
	}

	if (cardNumber.isEmpty()) {
		writeTime.start();
	}

	//accumulate characters
	QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
	cardNumber += keyEvent->text();

	//send signal on enter (RFID card reader ends string input with an enter)
	if (keyEvent->key() == Qt::Key_Return) {
		//disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader
		if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) {
			emit newCardNumber(cardNumber);
		}

		cardNumber.clear();
	}

	return true;
}

#include "mainwindow.h"
#include <QGridLayout>
#include <QLabel>
#include <QEvent>
#include <QKeyEvent>

#include <iostream>

MainWindow::MainWindow(QWidget *parent)
{
	QGridLayout *layout = new QGridLayout(this);
	layout->addWidget(new QLabel("ARK kryssesystem. Bipp et kort:"));

	QLabel *testLabel = new QLabel;
	layout->addWidget(testLabel);

	//install cardReader as an filter which intercepts keyboard events
	CardReader *cardReader = new CardReader(this);
	installEventFilter(cardReader);
	connect(cardReader, SIGNAL(newCardNumber(QString)), testLabel, SLOT(setText(QString)));
}

bool CardReader::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() != QEvent::KeyPress) {
		return false;
	}

	if (cardNumber.isEmpty()) {
		writeTime.start();
	}

	//accumulate characters
	QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
	cardNumber += keyEvent->text();

	//send signal on enter (RFID card reader ends string input with an enter)
	if (keyEvent->key() == Qt::Key_Return) {
		//disallow entries with duration less than a time limit in order to avoid keyboard input and allow only the fast RFID reader
		if (writeTime.elapsed() < CARDREADER_TIME_LIMIT_MS) {
			emit newCardNumber(cardNumber);
		}

		cardNumber.clear();
	}

	return true;
}

Test qlabel for displaying string from card reader.


/*
Copyright (C) 2014,2015,2018 Rodrigo Jose Hernandez Cordoba

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 "SettingsDialog.h"
#include <QColorDialog>
namespace AeonGames
{
    SettingsDialog::SettingsDialog()
    {
        setupUi ( this );
        settings.beginGroup ( "MainWindow" );
        backgroundColorPushButton->setPalette ( QPalette ( settings.value ( "background color", QColor ( 57, 57, 57 ) ).value<QColor>() ) );
        settings.endGroup();
    }

    SettingsDialog::~SettingsDialog()
    {
    }

    void SettingsDialog::onChangeBackgroundColor()
    {

        QColor color = QColorDialog::getColor ( backgroundColorPushButton->palette().background().color() );
        settings.beginGroup ( "MainWindow" );
        settings.setValue ( "background color", color );
        settings.endGroup();
        backgroundColorPushButton->setPalette ( QPalette ( color ) );
        emit backgroundColor ( color );
    }
}

/*
Copyright (C) 2014,2015,2018,2019 Rodrigo Jose Hernandez Cordoba

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 "SettingsDialog.h"
#include <QColorDialog>
namespace AeonGames
{
    SettingsDialog::SettingsDialog()
    {
        setupUi ( this );
        settings.beginGroup ( "MainWindow" );
        backgroundColorPushButton->setPalette ( QPalette ( settings.value ( "background color", QColor ( 57, 57, 57 ) ).value<QColor>() ) );
        settings.endGroup();
    }

    SettingsDialog::~SettingsDialog()
    {
    }

    void SettingsDialog::onChangeBackgroundColor()
    {
#if QT_VERSION < QT_VERSION_CHECK(5, 13, 0)
        QColor color = QColorDialog::getColor ( backgroundColorPushButton->palette().background().color() );
#else
        QColor color = QColorDialog::getColor ( backgroundColorPushButton->palette().window().color() );
#endif
        settings.beginGroup ( "MainWindow" );
        settings.setValue ( "background color", color );
        settings.endGroup();
        backgroundColorPushButton->setPalette ( QPalette ( color ) );
        emit backgroundColor ( color );
    }
}

Fix compilation against Qt 5.13.

Fix compilation against Qt 5.13.


#ifndef UHX_NO_UOBJECT

#include "Core.h"
#include "IntPtr.h"
#include "uhx/ue/RuntimeLibrary.h"
#include "HAL/PlatformAtomics.h"

static int uhx_tls_slot = 0;

#if defined(_MSC_VER)
unreal::UIntPtr *uhx::ue::RuntimeLibrary_obj::tlsObj = nullptr;
#elif defined(__GNUC__)
thread_local unreal::UIntPtr *uhx::ue::RuntimeLibrary_obj::tlsObj = nullptr;
#else
static int uhx_tls_obj = FPlatformTLS::AllocTlsSlot();

unreal::UIntPtr uhx::ue::RuntimeLibrary_obj::getTlsObj() {
  unreal::UIntPtr *ret = (unreal::UIntPtr *) FPlatformTLS::GetTlsValue(uhx_tls_obj);
  if (!ret) {
    ret = (unreal::UIntPtr*) uhx::GcRef::createRoot();
    FPlatformTLS::SetTlsValue(uhx_tls_obj, (void*) ret);
    return *ret = uhx::expose::HxcppRuntime::createArray();
  }
  return *ret;
}
#endif

int uhx::ue::RuntimeLibrary_obj::allocTlsSlot() {
  return FPlatformAtomics::InterlockedIncrement(&uhx_tls_slot);
}

#endif

Update to latest perforce change

[CL-33310] Update to latest perforce change


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

#include "base/message_loop.h"
#include "base/perf_test_suite.h"
#include "chrome/common/chrome_paths.cc"

int main(int argc, char **argv) {
  chrome::RegisterPathProvider();
  MessageLoop main_message_loop;

  return PerfTestSuite(argc, argv).Run();
}

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

#include "base/message_loop.h"
#include "base/perf_test_suite.h"
#include "chrome/common/chrome_paths.cc"

int main(int argc, char **argv) {
  PerfTestSuite suite(argc, argv);
  chrome::RegisterPathProvider();
  MessageLoop main_message_loop;

  return suite.Run();
}

Fix error
[FATAL:at_exit.cc(40)] Check failed: false. Tried to RegisterCallback without an AtExitManager
in (possibly unused) binary perf_tests

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

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


// Test main file for the Player and Team classes

#include "Player.hpp"
#include "Team.hpp"

int main()
{
    // Don't do anything
    return 0;
}

// Test main file for the Player and Team classes

#include "Player.hpp"
#include "Team.hpp"
#include <string>
#include <iostream>

int main()
{
    // Test code from the assignment description

    Player::Player p1("Charlotte", 24, 10, 7);
    Player::Player p2("Emily", 21, 13, 9);
    Player::Player p3("Anne", 20, 10, 8);
    Player::Player p4("Jane", 19, 10, 10);
    Player::Player p5("Mary", 18, 11, 8);
    p5.setRebounds(12);

    Team::Team team1(p1, p2, p3, p4, p5);

    Player::Player p = team1.getShootingGuard();
    std::cout << p.getName() << std::endl;

    return 0;
}

Test code from assignment description

Test code from assignment description


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

#include "base/basictypes.h"
#include "base/file_path.h"
#include "build/build_config.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

class DefaultPluginUITest : public UITest {
 public:
  DefaultPluginUITest() {
    dom_automation_enabled_ = true;
  }
};

TEST_F(DefaultPluginUITest, DefaultPluginLoadTest) {
  // Open page with default plugin.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("default_plugin.html");
  NavigateToURL(net::FilePathToFileURL(test_file));

  // Check that the default plugin was loaded. It executes a bit of javascript
  // in the HTML file which replaces the innerHTML of div |result| with "DONE".
  scoped_refptr<TabProxy> tab(GetActiveTab());
  std::wstring out;
  ASSERT_TRUE(tab->ExecuteAndExtractString(L"",
      L"domAutomationController.send("
      L"document.getElementById('result').innerHTML)", &out));
  ASSERT_EQ(L"DONE", out);
}

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

#include "base/basictypes.h"
#include "base/file_path.h"
#include "build/build_config.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"

class DefaultPluginUITest : public UITest {
 public:
  DefaultPluginUITest() {
    dom_automation_enabled_ = true;
  }
};

#if defined(OS_WIN)
#define MAYBE_DefaultPluginLoadTest DISABLED_DefaultPluginLoadTest
#else
#define MAYBE_DefaultPluginLoadTest DefaultPluginLoadTest
#endif
TEST_F(DefaultPluginUITest, MAYBE_DefaultPluginLoadTest) {
  // Open page with default plugin.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("default_plugin.html");
  NavigateToURL(net::FilePathToFileURL(test_file));

  // Check that the default plugin was loaded. It executes a bit of javascript
  // in the HTML file which replaces the innerHTML of div |result| with "DONE".
  scoped_refptr<TabProxy> tab(GetActiveTab());
  std::wstring out;
  ASSERT_TRUE(tab->ExecuteAndExtractString(L"",
      L"domAutomationController.send("
      L"document.getElementById('result').innerHTML)", &out));
  ASSERT_EQ(L"DONE", out);
}

Disable DefaultPluginUITest::DefaultPluginLoadTest on windows as it crashes.

BUG=57952
TEST=none
TBR=thakis@chromium.org

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


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

#include "AndroidTextInputState.h"

#include <react/renderer/components/text/conversions.h>
#include <react/renderer/debug/debugStringConvertibleUtils.h>

namespace facebook {
namespace react {

#ifdef ANDROID
folly::dynamic AndroidTextInputState::getDynamic() const {
  // Java doesn't need all fields, so we don't pass them along.
  folly::dynamic newState = folly::dynamic::object();
  newState["mostRecentEventCount"] = mostRecentEventCount;
  if (mostRecentEventCount != 0) {
    newState["attributedString"] = toDynamic(attributedString);
    newState["hash"] = newState["attributedString"]["hash"];
  }
  newState["paragraphAttributes"] =
      toDynamic(paragraphAttributes); // TODO: can we memoize this in Java?
  return newState;
}
#endif

} // namespace react
} // namespace facebook

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

#include "AndroidTextInputState.h"

#include <react/renderer/components/text/conversions.h>
#include <react/renderer/debug/debugStringConvertibleUtils.h>

namespace facebook {
namespace react {

#ifdef ANDROID
folly::dynamic AndroidTextInputState::getDynamic() const {
  // Java doesn't need all fields, so we don't pass them along.
  folly::dynamic newState = folly::dynamic::object();
  newState["mostRecentEventCount"] = mostRecentEventCount;
  newState["attributedString"] = toDynamic(attributedString);
  newState["hash"] = newState["attributedString"]["hash"];
  newState["paragraphAttributes"] =
      toDynamic(paragraphAttributes); // TODO: can we memoize this in Java?
  return newState;
}
#endif

} // namespace react
} // namespace facebook

Fix initial render of RN Android TextInput

Summary:
This diff fixes the initial render of RN Android TextInput. The problem was that "attributedString" was not serialized until an event was sent from native side.

Changelog: [internal] internal

Reviewed By: JoshuaGross

Differential Revision: D23383969

fbshipit-source-id: 86601434b1fbaa9f712bdb79b013a1d004bc55a4


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

#include "Application.h"

ouzel::AppPtr ouzelMain(const std::vector<std::string>& args)
{
    std::shared_ptr<ouzel::Application> application(new ouzel::Application());

    return application;
}

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

#include "Application.h"

ouzel::AppPtr ouzelMain(const std::vector<std::string>& args)
{
    std::shared_ptr<ouzel::Application> application = std::make_shared<ouzel::Application>();

    return application;
}

Use make_shared instead of new for creation of Application instance


/**
 *  fastcall.cpp
 *
 *  This file holds some PHP functions implementation in C directly.
 *
 */

#include "includes.h"

namespace Php {

    bool class_exists(const std::string &classname, bool autoload) {
        // we need the tsrm_ls variable
        TSRMLS_FETCH();

        zend_class_entry **ce;
        int found;
        const char * str = classname.c_str();
        int32_t len = (int32_t)classname.length();

        if (autoload) {
            char lc_name[len + 1];
            zend_str_tolower_copy(lc_name, str, len);

            char *name = lc_name;
            if (lc_name[0] == '\\') {
                name = &lc_name[1];
                --len;
            }

            found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce);
            return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS));
        }

        if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) {
            return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0);
        }
        return false;
    }

}

/**
 *  fastcall.cpp
 *
 *  This file holds some PHP functions implementation in C directly.
 *
 */

#include "includes.h"

namespace Php {

    bool class_exists(const std::string &classname, bool autoload) {
        // we need the tsrm_ls variable
        TSRMLS_FETCH();

        zend_class_entry **ce;
        int found;
        const char * str = classname.c_str();
        int32_t len = (int32_t)classname.length();

        if (autoload) {
            char *lc_name = new char[len + 1];
            zend_str_tolower_copy(lc_name, str, len);

            char *name = lc_name;
            if (lc_name[0] == '\\') {
                name = &lc_name[1];
                --len;
            }

            found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce);
            delete [] lc_name;
            return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS));
        }

        if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) {
            return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0);
        }
        return false;
    }

}

Change C99 VLA C++ dynamic array

Change C99 VLA C++ dynamic array


#include <jni.h>
#include <string>
#include "SpatialFilter.h"
#include "VideoProcessor.h"

extern "C"

jstring
Java_cn_edu_seu_evmhr_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */,
        jstring jFileName) {
    const char* jnamestr = env->GetStringUTFChars(jFileName, NULL);

    VideoProcessor VP;
    VP.setInput(jnamestr);

    std::stringstream ss;
    ss << VP.colorMagnify();

    std::string peaks;
    ss >> peaks;

    return env->NewStringUTF(peaks.c_str());
}

#include <jni.h>
#include <string>
#include "SpatialFilter.h"
#include "VideoProcessor.h"

extern "C"

jstring
Java_cn_edu_seu_evmhr_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */,
        jstring jFileName) {
    const char* jnamestr = env->GetStringUTFChars(jFileName, NULL);

    VideoProcessor VP;
    VP.setInput(jnamestr);

    double length = VP.getLengthMS() / 1000;
    int peaks = VP.colorMagnify();

    std::stringstream ss;
    ss << std::floor(60 / length * peaks);

    std::string heartRate;
    ss >> heartRate;

    return env->NewStringUTF(heartRate.c_str());
}

Move heart rate calculation to cpp

Move heart rate calculation to cpp


#include "SharedResource.h"

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(Basic_construction)
{
    SharedResource<int> shared_int;
}

BOOST_AUTO_TEST_CASE(Construction_with_argument)
{
    SharedResource<int> shared_int(5);
}

BOOST_AUTO_TEST_CASE(Construction_no_default_constructor)
{
    struct TestClass
    {
        TestClass() = delete;
        TestClass(int) { }
    };

    SharedResource<TestClass> stc2(5);
}

BOOST_AUTO_TEST_CASE(Basic_Locking)
{
    SharedResource<int> shared_int(0);
    shared_int.lock();
}

BOOST_AUTO_TEST_CASE(Locking_with_accessor)
{
    SharedResource<int> shared_int(0);
    auto shared_int_accessor = shared_int.lock();
}

BOOST_AUTO_TEST_CASE(Accessor_isValid)
{
    SharedResource<int> shared_int(0);
    auto shared_int_accessor = shared_int.lock();
    BOOST_CHECK(shared_int_accessor.isValid());
    auto shared_int_accessor_new(std::move(shared_int_accessor));
    BOOST_CHECK(!shared_int_accessor.isValid());
    BOOST_CHECK(shared_int_accessor_new.isValid());
}

Test for SharedResourse::Accessor::isValid method added


// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "checksumaggregators.h"

namespace proton::bucketdb {

std::unique_ptr<ChecksumAggregator>
ChecksumAggregator::create(ChecksumType type, BucketChecksum seed) {
    switch (type) {
    case ChecksumType::LEGACY:
        return std::make_unique<LegacyChecksumAggregator>(seed);
    case ChecksumType::XXHASH64:
        return std::make_unique<XXH64ChecksumAggregator>(seed);
    }
    return std::unique_ptr<ChecksumAggregator>();
}

}

// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "checksumaggregators.h"

namespace proton::bucketdb {

std::unique_ptr<ChecksumAggregator>
ChecksumAggregator::create(ChecksumType type, BucketChecksum seed) {
    switch (type) {
    case ChecksumType::LEGACY:
        return std::make_unique<LegacyChecksumAggregator>(seed);
    case ChecksumType::XXHASH64:
        return std::make_unique<XXH64ChecksumAggregator>(seed);
    }
    abort();
}

}

Use abort instead to signal unreachable code.


// cc.in79
// problem with templatized forward decl?
// no, was a problem with templatized prototypes

class istream;

template<class TP> class smanip;
//template<class TP> class smanip {};

template<class TP>
inline istream& operator>>(istream& i, const smanip<TP>& m);
//int foo(smanip<TP> &m);

typedef smanip<int> smanip_int;

template<class TP> class smanip {
  smanip *whatever;
  smanip<TP> *whatever2;
};

void f()
{
  smanip_int s;
  s.whatever;
}

// in/t0079.cc
// problem with templatized forward decl?
// no, was a problem with templatized prototypes

class istream;

template<class TP> class smanip;
//template<class TP> class smanip {};

template<class TP>
inline istream& operator>>(istream& i, const smanip<TP>& m);
//int foo(smanip<TP> &m);

typedef smanip<int> smanip_int;

template<class TP> class smanip {
public:
  smanip *whatever;
  smanip<TP> *whatever2;
};

void f()
{
  smanip_int s;
  s.whatever;
}

Fix gcc compilation issue, thanks to Evan Driscoll.


#include <ostree.h>
#include <stdlib.h>

extern "C" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) {
  (void)self;
  const char *hash = getenv("OSTREE_HASH");
  return ostree_deployment_new(0, "dummy-os", hash, 1, hash, 1);
}

extern "C" const char *ostree_deployment_get_csum(OstreeDeployment *self) {
  (void)self;
  return getenv("OSTREE_HASH");
}

#include <ostree.h>
#include <stdlib.h>

extern "C" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) {
  (void)self;
  static OstreeDeployment *deployment;

  if (deployment != nullptr) {
    return deployment;
  }

  const char *hash = getenv("OSTREE_HASH");
  deployment = ostree_deployment_new(0, "dummy-os", hash, 1, hash, 1);
  return deployment;
}

extern "C" const char *ostree_deployment_get_csum(OstreeDeployment *self) {
  (void)self;
  return getenv("OSTREE_HASH");
}

Fix mem leak in test code

aktualizr-lite: Fix mem leak in test code

Pretty much the same idea as:

 https://github.com/advancedtelematic/aktualizr/pull/1398

Signed-off-by: Andy Doan <e3579b1e47f273529f0f929453e939a68ede9fd1@foundries.io>


//===- AArch64MachineLegalizer.cpp -------------------------------*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements the targeting of the Machinelegalizer class for
/// AArch64.
/// \todo This should be generated by TableGen.
//===----------------------------------------------------------------------===//

#include "AArch64MachineLegalizer.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/Target/TargetOpcodes.h"

using namespace llvm;

#ifndef LLVM_BUILD_GLOBAL_ISEL
#error "You shouldn't build this"
#endif

AArch64MachineLegalizer::AArch64MachineLegalizer() {
  setAction(TargetOpcode::G_ADD, LLT::vector(2, 64), Legal);
  computeTables();
}

//===- AArch64MachineLegalizer.cpp -------------------------------*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements the targeting of the Machinelegalizer class for
/// AArch64.
/// \todo This should be generated by TableGen.
//===----------------------------------------------------------------------===//

#include "AArch64MachineLegalizer.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/Target/TargetOpcodes.h"

using namespace llvm;

#ifndef LLVM_BUILD_GLOBAL_ISEL
#error "You shouldn't build this"
#endif

AArch64MachineLegalizer::AArch64MachineLegalizer() {
  using namespace TargetOpcode;
  const LLT s32 = LLT::scalar(32);
  const LLT s64 = LLT::scalar(64);
  const LLT v2s32 = LLT::vector(2, 32);
  const LLT v4s32 = LLT::vector(4, 32);
  const LLT v2s64 = LLT::vector(2, 64);

  for (auto BinOp : {G_ADD, G_SUB, G_AND, G_OR, G_XOR})
    for (auto Ty : {s32, s64, v2s32, v4s32, v2s64})
      setAction(BinOp, Ty, Legal);

  for (auto MemOp : {G_LOAD, G_STORE})
    for (auto Ty : {s32, s64})
      setAction(MemOp, Ty, Legal);

  setAction(G_BR, LLT::unsized(), Legal);

  computeTables();
}

Mark basic binops/memops as legal.

[AArch64][GlobalISel] Mark basic binops/memops as legal.

We currently use and test these, and select most of them. Mark them
as legal even though we don't go through the full ir->asm flow yet.

This doesn't currently have standalone tests, but the verifier will
soon learn to check that the regbankselect/select tests are legal.

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


#include <memory>
#include "PPMLoader.hpp"

std::shared_ptr<Image> PPMLoader::load(const char *pathToImage) {
	FILE *file = fopen(pathToImage, "r");

	char magicNumber[8];
	fscanf(file, "%s\n", magicNumber);

	int width, height;
	fscanf(file, "%d %d\n", &width, &height);

	int maxValue;
	fscanf(file, "%d\n", &maxValue);

	auto image = std::make_shared<Image>(width, height);

	size_t index = 0;

	while (1) {
		uint8_t r, g, b;
		int elementsRead = fscanf(file, "%d %d %d", &r, &g, &b);

		if (elementsRead < 3) {
			break;
		}
		image->setValueOnChannel1(index, normalize(r, maxValue, 255));
		image->setValueOnChannel2(index, normalize(g, maxValue, 255));
		image->setValueOnChannel3(index, normalize(b, maxValue, 255));
		index++;
	}
	image->colorSpace = ColorSpaceRGB;
	return image;
}

size_t PPMLoader::normalize(size_t colorValue, int originalMaxValue, int normalizedMaxValue) {
	return (size_t) ((colorValue / (float) originalMaxValue) * normalizedMaxValue);
}

#include <memory>
#include "PPMLoader.hpp"

std::shared_ptr<Image> PPMLoader::load(const char *pathToImage) {
	FILE *file = fopen(pathToImage, "r");

	char magicNumber[8];
	fscanf(file, "%s\n", magicNumber);

	int width, height;
	fscanf(file, "%d %d\n", &width, &height);

	int maxValue;
	fscanf(file, "%d\n", &maxValue);

	auto image = std::make_shared<Image>(width, height);

	size_t index = 0;

	while (1) {
		size_t r, g, b;
		int elementsRead = fscanf(file, "%d %d %d", &r, &g, &b);

		if (elementsRead < 3) {
			break;
		}
		image->setValueOnChannel1(index, normalize(r, maxValue, 255));
		image->setValueOnChannel2(index, normalize(g, maxValue, 255));
		image->setValueOnChannel3(index, normalize(b, maxValue, 255));
		index++;
	}
	image->colorSpace = ColorSpaceRGB;
	return image;
}

size_t PPMLoader::normalize(size_t colorValue, int originalMaxValue, int normalizedMaxValue) {
	return (size_t) ((colorValue / (float) originalMaxValue) * normalizedMaxValue);
}

Replace int_8 with size_t to fix conversion bug


// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new AdditionNFDelegate);
    app.addNodeFactory(new ConstantNFDelegate);
    app.addNodeFactory(new PrinterNFDelegate);
    app.addNodeFactory(new TextFileNFDelegate);

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new AdditionNFDelegate);
    app.addNodeFactory(new ConstantNFDelegate);
    app.addNodeFactory(new PrinterNFDelegate);
    app.addNodeFactory(new TextFileNFDelegate);
    app.loadScriptNodes("Nodin/NodeScripts/Lua");

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

Use function to load all script files in script directory.


#include <QApplication>
#include <QtDeclarative>
#include <QDeclarativeView>
#include <QDeclarativeContext>

#include "settingspersistor.h"

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

    QSettings settings("qmltweeter.conf", QSettings::IniFormat);
    settings.sync();

    QDeclarativeView view;
    QDeclarativeContext *context = view.rootContext();

    SettingsPersistor settingsPersistor(context, &settings);
    context->setContextProperty("settings", &settingsPersistor);

    QString searchTerm = settings.value("searchTerm", QString("meego")).toString();
    context->setContextProperty("searchTerm", QVariant::fromValue(searchTerm));

    view.setSource(QUrl("qrc:///qml/qmltweeter.qml"));

    QObject *rootObject = dynamic_cast<QObject*>(view.rootObject());
    QObject::connect(&settingsPersistor, SIGNAL(settingsSaved(QVariant)), rootObject, SLOT(settingsSaved(QVariant)));

    view.show();

    return app.exec();
}

#include <QApplication>
#include <QtDeclarative>
#include <QDeclarativeView>
#include <QDeclarativeContext>

#include "settingspersistor.h"

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

    QSettings settings("qmltweeter.conf", QSettings::IniFormat);
    settings.sync();

    QDeclarativeView view;
    QDeclarativeContext *context = view.rootContext();

    SettingsPersistor settingsPersistor(context, &settings);
    context->setContextProperty("settings", &settingsPersistor);

    QString searchTerm = settings.value("searchTerm", QString("meego")).toString();
    context->setContextProperty("searchTerm", QVariant::fromValue(searchTerm));

    view.setSource(QUrl("qrc:///qml/qmltweeter.qml"));

    QObject *rootObject = view.rootObject();
    QObject::connect(&settingsPersistor, SIGNAL(settingsSaved(QVariant)), rootObject, SLOT(settingsSaved(QVariant)));

    view.show();

    return app.exec();
}

Remove unnecessary dynamic_cast to base class

Signed-off-by: Sami Rosendahl <b33c757bb777642ab0d59c699f8d5782929a814f@reaktor.fi>


// request symbols
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/DynamicExprInfo.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/UserInterface/UserInterface.h"

#include "clang/AST/Type.h"

#include "llvm/Support/raw_ostream.h"

namespace cling {
void libcling__symbol_requester() {
   const char* const argv[] = {"libcling__symbol_requester", 0};
   cling::Interpreter I(1, argv);
   cling::UserInterface U(I);
   cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call.
   printValuePublicDefault(llvm::outs(), 0, VPI);
   cling_PrintValue(0, 0, 0);
   flushOStream(llvm::outs());
   LookupHelper h(0);
   h.findType("");
   h.findScope("");
   h.findFunctionProto(0, "", "");
   h.findFunctionArgs(0, "", "");
   cling::runtime::internal::DynamicExprInfo DEI(0,0,false);
   DEI.getExpr();
   cling::InterpreterCallbacks cb(0);
}

}

// request symbols
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/DynamicExprInfo.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/UserInterface/UserInterface.h"

#include "clang/AST/Type.h"

#include "llvm/Support/raw_ostream.h"

namespace cling {
namespace internal {
void libcling__symbol_requester() {
   const char* const argv[] = {"libcling__symbol_requester", 0};
   cling::Interpreter I(1, argv);
   cling::UserInterface U(I);
   cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call.
   printValuePublicDefault(llvm::outs(), 0, VPI);
   cling_PrintValue(0, 0, 0);
   flushOStream(llvm::outs());
   LookupHelper h(0);
   h.findType("");
   h.findScope("");
   h.findFunctionProto(0, "", "");
   h.findFunctionArgs(0, "", "");
   cling::runtime::internal::DynamicExprInfo DEI(0,0,false);
   DEI.getExpr();
   cling::InterpreterCallbacks cb(0);
}
}
}

Put the symbol requester func into the proper namespace!

git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@46987 27541ba8-7e3a-0410-8455-c3a389f83636


/*
 * Copyright (c) , Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "platform/mbed_assert.h"
#include "gtest/gtest.h"
#include <stdio.h>
#include <stdbool.h>

bool mbed_assert_throw_errors = false;

extern "C" void mbed_assert_internal(const char *expr, const char *file, int line)
{
    fprintf(stderr, "mbed assertation failed: %s, file: %s, line %d \n", expr, file, line);
    if (mbed_assert_throw_errors) {
        throw 1;
    }

    /* Ensure we fail the unit test if the Mbed assertion fails. Without this,
     * we might not notice the assertion failure as it wouldn't be bubbled up
     * to googletest. Note that this is after the above throw, as some tests
     * check that an exception is thrown (i.e. negative tests). */
    FAIL();
}

/*
 * Copyright (c) , Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "platform/mbed_assert.h"
#include "gtest/gtest.h"
#include <stdio.h>
#include <stdbool.h>

bool mbed_assert_throw_errors = false;

extern "C" void mbed_assert_internal(const char *expr, const char *file, int line)
{
    fprintf(stderr, "mbed assertation failed: %s, file: %s, line %d \n", expr, file, line);
    if (mbed_assert_throw_errors) {
#ifdef __EXCEPTIONS
        throw 1;
#else
        FAIL();
#endif
    }

    /* Ensure we fail the unit test if the Mbed assertion fails. Without this,
     * we might not notice the assertion failure as it wouldn't be bubbled up
     * to googletest. Note that this is after the above throw, as some tests
     * check that an exception is thrown (i.e. negative tests). */
    FAIL();
}

Allow unit tests to be compiled with -fno-exception


/*
 * dis.cpp
 *
 *  Created on: Sep 20, 2015
 *      Author: anon
 */

#include "arm/ARMDisassembler.h"

#include <memory>
#include <string>
#include <cstdint>
#include <iostream>

using namespace std;
using namespace Disassembler;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: ./%s [thumb|arm] <hex_opcode>" << endl;
        return -1;
    }

    string arg_mode { argv[1] };
    string arg_opcode { argv[2] };

    ARMMode mode = (arg_mode == "thumb") ? ARMMode_Thumb : ARMMode_ARM;
    uint32_t opcode = std::stoul(arg_opcode, nullptr, 16);

    ARMDisassembler dis;
    shared_ptr<ARMInstruction> ins = dis.disassemble(opcode, mode);
    cout << "Disassembled instruction: " << (void *) opcode << " -> " << ins->toString() << endl;

    return 0;
}

/*
 * dis.cpp
 *
 *  Created on: Sep 20, 2015
 *      Author: anon
 */

#include "arm/ARMDisassembler.h"

#include <memory>
#include <string>
#include <cstdint>
#include <iostream>

using namespace std;
using namespace Disassembler;

int main(int argc, char **argv) {
    if (argc < 2) {
        cerr << "Usage: ./%s [thumb|arm] <hex_opcode>" << endl;
        return -1;
    }

    string arg_mode { argv[1] };
    string arg_opcode { argv[2] };

    uint32_t opcode = std::stoul(arg_opcode, nullptr, 16);

    ARMMode mode;
    if (arg_mode == "thumb") {
        mode = ARMMode_Thumb;
        cout << "Using mode THUMB" << endl;

        if (opcode > 0xffff) {
            opcode = (opcode >> 16) | ((opcode << 16) & 0xffffffff);
        }
    } else {
        mode = ARMMode_ARM;
        cout << "Using mode THUMB" << endl;
    }

    ARMDisassembler dis { ARMv7All };
    shared_ptr<ARMInstruction> ins = dis.disassemble(opcode, mode);
    cout << "Disassembled instruction: " << (void *) opcode << " -> " << ins->toString() << endl;

    return 0;
}

Make sure we invert the thumb2 opcodes.

Make sure we invert the thumb2 opcodes.


#include "util/testing.h"

#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>

namespace cert_trans {
namespace test {

void InitTesting(const char* name, int* argc, char*** argv,
                 bool remove_flags) {
  // Change the defaults. Can be overridden on command line.
  // Log to stderr instead of log files.
  FLAGS_logtostderr = true;
  // Only log fatal messages by default.
  FLAGS_minloglevel = 3;
  ::testing::InitGoogleTest(argc, *argv);
  google::ParseCommandLineFlags(argc, argv, remove_flags);
  google::InitGoogleLogging(name);
}

}  // namespace test
}  // namespace cert_trans

#include "util/testing.h"

#include <event2/thread.h>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>

namespace cert_trans {
namespace test {

void InitTesting(const char* name, int* argc, char*** argv,
                 bool remove_flags) {
  // Change the defaults. Can be overridden on command line.
  // Log to stderr instead of log files.
  FLAGS_logtostderr = true;
  // Only log fatal messages by default.
  FLAGS_minloglevel = 3;
  ::testing::InitGoogleTest(argc, *argv);
  google::ParseCommandLineFlags(argc, argv, remove_flags);
  google::InitGoogleLogging(name);
  evthread_use_pthreads();
}

}  // namespace test
}  // namespace cert_trans

Call evthread_use_pthreads() in all tests.


// REQUIRES: static-analyzer
// RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s
extern void *malloc(unsigned long);
extern void free(void *);

void f() {
  int *p = new int(42);
  delete p;
  delete p;
  // CHECK: warning: Attempt to free released memory [clang-analyzer-cplusplus.NewDelete]
}

void g() {
  void *q = malloc(132);
  free(q);
  free(q);
  // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]
}

// REQUIRES: static-analyzer
// RUN: clang-tidy %s -checks='-*,clang-analyzer-*' -- | FileCheck %s
extern void *malloc(unsigned long);
extern void free(void *);

void f() {
  int *p = new int(42);
  delete p;
  delete p;
  // CHECK: warning: Attempt to delete released memory [clang-analyzer-cplusplus.NewDelete]
}

void g() {
  void *q = malloc(132);
  free(q);
  free(q);
  // CHECK: warning: Attempt to free released memory [clang-analyzer-unix.Malloc]
}

Fix a lit test failure after MallocChecker changes

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


#include "arithmetics.hpp"

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

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

#include "arithmetics.hpp"

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

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

Fix bug to see Travis succeed

Fix bug to see Travis succeed


#include <numeric>
#include <vector>

#include SPECIFIC_HEADER

int main(int /*argc*/, char** /*argv*/)
{
  constexpr unsigned num_entries = 1e7;
  std::vector<int> in(num_entries);
  std::iota(std::begin(in), std::end(in), 0);
  auto out = product_except(in);

  bool success = out[1] == 0;
  return !success;
}

#include <numeric>
#include <vector>

#include SPECIFIC_HEADER

int main(int /*argc*/, char** /*argv*/)
{
  constexpr unsigned num_entries = 10000000;
  std::vector<int> in(num_entries);
  std::iota(std::begin(in), std::end(in), 0);
  auto out = product_except(in);

  bool success = out[1] == 0;
  return !success;
}

Fix double to unsigned error

[product-except-self][vs] Fix double to unsigned error


#include <iostream>
#include <algorithm>
#include "io/PGMIO.hpp"
#include "matrix/Matrix.hpp"

using namespace sipl;

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

    // const std::string filename{argv[1]};
    PGMIO pgm;
    auto mat = pgm.read<uint8_t>("tmp_ascii.pgm");
    // pgm.write(mat, "tmp_binary.pgm", PGMIO::PType::BINARY);
    pgm.write(mat, "tmp_ascii2.pgm", PGMIO::PType::ASCII);
}

#include <iostream>
#include <algorithm>
#include "io/PgmIO.hpp"
#include "matrix/Matrix.hpp"

using namespace sipl;

int main(int argc, char** argv)
{
    if (argc < 3) {
        std::cout << "Usage:" << std::endl;
        std::cout << "    " << argv[0] << " infile.pgm outfile.pgm"
                  << std::endl;
        std::exit(1);
    }

    // const std::string filename{argv[1]};
    PgmIO pgm;
    auto mat = pgm.read(argv[1]);
    pgm.write(mat, argv[2], PGMIO::PType::BINARY);
    // pgm.write(mat, argv[2], PGMIO::PType::ASCII);
}

Update for removal of type-specifier from reader


#include <iostream>
#include <fstream>
#include <memory>

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

int FindSingleElement(const std::shared_ptr<int>& inputArray, int size);

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

	auto testCases = engine.LoadTestCases();

	for (const auto& testCase : testCases)
	{
		if (testCase.Size % 2 == 0) //only odd inputs accepted
			continue;

		auto singleElement = FindSingleElement(testCase.Data, testCase.Size);

		std::cout << singleElement << std::endl;
	}

	return 0;
}

int FindSingleElement(const std::shared_ptr<int>& inputArray, int size)
{
	return 0;
}

#include <iostream>
#include <fstream>
#include <memory>

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

int FindSingleElement(const std::shared_ptr<int>& inputArray, int size);

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

	auto testCases = engine.LoadTestCases();

	for (const auto& testCase : testCases)
	{
		if (testCase.Size % 2 == 0) //only odd inputs accepted
			continue;

		auto singleElement = FindSingleElement(testCase.Data, testCase.Size);

		std::cout << singleElement << std::endl;
	}

	return 0;
}

int FindSingleElement(const std::shared_ptr<int>& inputArray, int size)
{
	const int INT_SIZE_IN_BITS = 32;

	//this method only works if there are 'n' occurrences of each element other than the single element
	//in the case of this test data, there are two occurrences of every other element since the problem states pairs of people
	const int EXPECTED_ELEMENT_OCCURRENCES = 2;

	int result = 0;
	auto ptr = inputArray.get();

	for (int bit = 0; bit < INT_SIZE_IN_BITS; ++bit)
	{
		int sum = 0;
		int bitMask = 1 << bit;

		for (int i = 0; i < size; ++i)
			if (ptr[i] & bitMask)
				sum++;

		if (sum % EXPECTED_ELEMENT_OCCURRENCES != 0)
			result |= bitMask;
	}

	return result;
}

Implement method for finding single element by counting occurrences of each bit across all elements in the input array


#include <Eigen/Core>
#include "./test.h"
#include "../src/labelling/labels.h"
#include "../src/labelling/label.h"

TEST(Test_Labels, ChangeNotification)
{
  Labels labels;

  int changedLabelId = -1;
  Labels::Action receivedAction;

  auto removeSubscription = labels.subscribe([&changedLabelId, &receivedAction](
      Labels::Action action, const Label &label)
                                             {
                                               receivedAction = action;
                                               changedLabelId = label.id;
                                             });

  labels.add(Label(1, "Label text", Eigen::Vector3f(1, 2, 3)));

  ASSERT_EQ(1, changedLabelId);
  ASSERT_EQ(Labels::Action::Add, receivedAction);

  removeSubscription();
  labels.add(Label(2, "Label text", Eigen::Vector3f(1, 2, 3)));

  ASSERT_EQ(1, changedLabelId);
}

TEST(Test_Labels, Remove)
{
  Labels labels;

  Label label(1, "Label text", Eigen::Vector3f(1, 2, 3));
  labels.add(label);

  ASSERT_EQ(1, labels.count());

  int changedLabelId = -1;
  Labels::Action receivedAction;
  auto removeSubscription = labels.subscribe([&changedLabelId, &receivedAction](
      Labels::Action action, const Label &label)
                                             {
                                               receivedAction = action;
                                               changedLabelId = label.id;
                                             });
  labels.remove(label);

  ASSERT_EQ(0, labels.count());
  ASSERT_EQ(1, changedLabelId);
  ASSERT_EQ(Labels::Action::Delete, receivedAction);
}

Add test for removing a label.

Add test for removing a label.


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

// REQUIRES: linux

#include <assert.h>
#include <cxxabi.h>

static bool AtexitImplCalled = false;

extern "C" int __cxa_thread_atexit_impl(void (*dtor)(void *), void *obj,
                                        void *dso_symbol) {
  assert(dtor == reinterpret_cast<void (*)(void *)>(1));
  assert(obj == reinterpret_cast<void *>(2));
  assert(dso_symbol == reinterpret_cast<void *>(3));
  AtexitImplCalled = true;
  return 4;
}

int main() {
  int RV = __cxxabiv1::__cxa_thread_atexit(
      reinterpret_cast<void (*)(void *)>(1), reinterpret_cast<void *>(2),
      reinterpret_cast<void *>(3));
  assert(RV == 4);
  assert(AtexitImplCalled);
  return 0;
}

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

// UNSUPPORTED: libcppabi-no-threads
// REQUIRES: linux

#include <assert.h>
#include <cxxabi.h>

static bool AtexitImplCalled = false;

extern "C" int __cxa_thread_atexit_impl(void (*dtor)(void *), void *obj,
                                        void *dso_symbol) {
  assert(dtor == reinterpret_cast<void (*)(void *)>(1));
  assert(obj == reinterpret_cast<void *>(2));
  assert(dso_symbol == reinterpret_cast<void *>(3));
  AtexitImplCalled = true;
  return 4;
}

int main() {
  int RV = __cxxabiv1::__cxa_thread_atexit(
      reinterpret_cast<void (*)(void *)>(1), reinterpret_cast<void *>(2),
      reinterpret_cast<void *>(3));
  assert(RV == 4);
  assert(AtexitImplCalled);
  return 0;
}

Mark thread exit test as unsupported w/o threads

git-svn-id: 6a9f6578bdee8d959f0ed58970538b4ab6004734@285523 91177308-0d34-0410-b5e6-96231b3b80d8


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents1) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}

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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}

// Disabled, flakily exceeds timeout, http://crbug.com/72165.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebNavigationEvents1) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}

Disable ExtensionApiTest.WebNavigationEvents1, flakily exceeds test timeout

TBR=jochen

BUG=72165
TEST=browser_tests
Review URL: http://codereview.chromium.org/6286142

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

Former-commit-id: e606e1da3ebcab3f6e962919f186165748174703


#include "pch.h"

#include "style.h"

using namespace Windows::Foundation;

style::style()
    : fill_(paint_type::color, Colors::Black)
    , stroke_(paint_type::none, Colors::Black)
    , strokeWidth_(length{ 0, unit::unspecified })
{
}

ICanvasBrush^ style::fillBrush(ICanvasResourceCreator^ resourceCreator)
{
    return fill_.brush(resourceCreator);
}

ICanvasBrush^ style::strokeBrush(ICanvasResourceCreator^ resourceCreator)
{
    return stroke_.brush(resourceCreator);
}

float style::stroke_width()
{
    return strokeWidth_.Number; // TODO: respect the Unit!
}

inherited_style::inherited_style()
{
    style defaultStyle;
    stack_.push(defaultStyle);
}

void inherited_style::push()
{
    stack_.push(stack_.top());
}

void inherited_style::pop()
{
    stack_.pop();
    assert(!stack_.empty());
}

#include "pch.h"

#include "style.h"

using namespace Windows::Foundation;

style::style()
    : fill_(paint_type::color, Colors::Black)
    , stroke_(paint_type::none, Colors::Black)
    , strokeWidth_(length{ 1, unit::unspecified })
{
}

ICanvasBrush^ style::fillBrush(ICanvasResourceCreator^ resourceCreator)
{
    return fill_.brush(resourceCreator);
}

ICanvasBrush^ style::strokeBrush(ICanvasResourceCreator^ resourceCreator)
{
    return stroke_.brush(resourceCreator);
}

float style::stroke_width()
{
    return strokeWidth_.Number; // TODO: respect the Unit!
}

inherited_style::inherited_style()
{
    style defaultStyle;
    stack_.push(defaultStyle);
}

void inherited_style::push()
{
    stack_.push(stack_.top());
}

void inherited_style::pop()
{
    stack_.pop();
    assert(!stack_.empty());
}

Set default stroke-width to 1

Set default stroke-width to 1


//
// Copyright (c) 2010 The ANGLE Project 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 <math.h>
#include <stdlib.h>

#include "util.h"

#ifdef _MSC_VER
    #include <locale.h>
#else
    #include <sstream>
#endif

double atof_dot(const char *str)
{
#ifdef _MSC_VER
    return _atof_l(str, _create_locale(LC_NUMERIC, "C"));
#else
    double result;
    std::istringstream s(str);
    std::locale l("C");
    s.imbue(l);
    s >> result;
    return result;
#endif
}

//
// Copyright (c) 2010 The ANGLE Project 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 <math.h>
#include <stdlib.h>

#include "util.h"

#ifdef _MSC_VER
    #include <locale.h>
#else
    #include <sstream>
#endif

double atof_dot(const char *str)
{
#ifdef _MSC_VER
    _locale_t l = _create_locale(LC_NUMERIC, "C");
    double result = _atof_l(str, l);
    _free_locale(l);
    return result;
#else
    double result;
    std::istringstream s(str);
    std::locale l("C");
    s.imbue(l);
    s >> result;
    return result;
#endif
}

Fix memory leak in float literal parsing
Issue=93

Contributed by Benoit Jacob


// 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 "webkit/support/gc_extension.h"

#include "v8/include/v8.h"

const char kGCExtensionName[] = "v8/GCController";

namespace extensions_v8 {

// static
v8::Extension* GCExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kGCExtensionName,
      "(function () {"
      "   var v8_gc;"
      "   if (gc) v8_gc = gc;"
      "   GCController = new Object();"
      "   GCController.collect ="
      "     function() {if (v8_gc) v8_gc(); };"
      " })();");
  return extension;
}

}  // namespace extensions_v8

// 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 "webkit/support/gc_extension.h"

#include "v8/include/v8.h"

const char kGCExtensionName[] = "v8/GCController";

namespace extensions_v8 {

// static
v8::Extension* GCExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kGCExtensionName,
      "(function () {"
      "   var v8_gc;"
      "   if (gc) v8_gc = gc;"
      "   GCController = new Object();"
      "   GCController.collect ="
      "     function() {if (v8_gc) v8_gc(); };"
      "   GCController.minorCollect ="
      "     function() {if (v8_gc) v8_gc(true); };"
      " })();");
  return extension;
}

}  // namespace extensions_v8

Add GCController.minorCollect(), which triggers one minor GC cycle

Currently there is no way to test behavior of minor GC cycles in layout tests.
This patch adds the ability.

In V8, with the --expose-gc option, gc() triggers 7 major GC cycles.
gc(true) triggers 1 minor GC cycle.

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

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


#include "HalideRuntime.h"
#include "runtime_internal.h"

extern "C" {

WEAK __attribute__((always_inline)) int halide_profiler_set_current_func(halide_profiler_state *state, int tok, int t) {
    __sync_synchronize();
    state->current_func = tok + t;
    __sync_synchronize();
    return 0;
}

}

#include "HalideRuntime.h"
#include "runtime_internal.h"

extern "C" {

WEAK __attribute__((always_inline)) int halide_profiler_set_current_func(halide_profiler_state *state, int tok, int t) {
    // Do a volatile store to discourage llvm from reordering it.
    volatile int *ptr = &(state->current_func);
    *ptr = tok + t;
    return 0;
}

}

Use a volatile store instead of a memory barrier

It's lower overhead.


#include "pch.h"
#include "json_rpc_debug_logger.h"

#include <QDebug>

namespace jcon {

void JsonRpcDebugLogger::logInfo(const QString& message)
{
    qDebug().noquote() << message;
}

void JsonRpcDebugLogger::logWarning(const QString& message)
{
    qDebug().noquote() << message;
}

void JsonRpcDebugLogger::logError(const QString& message)
{
    qDebug().noquote() << message;
}

}

Remove inclusion of non-existing precompiled header


#include "reg_filter_mode_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		boost::optional<FilterModeTranslator::external_type> FilterModeTranslator::get_value(internal_type const sval) {
			if (sval.empty()) return boost::none;
			if (sval == "Bilinear") {
				return Filter::Mode::Bilinear;
			}
			if (sval == "Nearest") {
				return Filter::Mode::NearestNeighbor;
			}
			if (sval == "Lanczos3") {
				return Filter::Mode::Lanczos3;
			}

			switch (FromAString<int>(sval)) {
			case 1:
				return Filter::Mode::NearestNeighbor;
			case 2:
				return Filter::Mode::Bilinear;
			case 3:
				return Filter::Mode::Lanczos3;
			}

			return boost::none;
		}

		boost::optional<FilterModeTranslator::internal_type> FilterModeTranslator::put_value(external_type const& val) {
			switch (val) {
			case Filter::Mode::NearestNeighbor:
				return "Nearest";
			case Filter::Mode::Bilinear:
				return "Bilinear";
			case Filter::Mode::Lanczos3:
				return "Lanczos3";
			}

			return boost::none;
		}
	}
}

#include "reg_filter_mode_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		boost::optional<FilterModeTranslator::external_type> FilterModeTranslator::get_value(internal_type const sval) {
			if (sval.empty()) return boost::none;
			if (sval == "Bilinear") {
				return Filter::Mode::Bilinear;
			}
			if (sval == "Nearest") {
				return Filter::Mode::NearestNeighbor;
			}
			if (sval == "Lanczos3") {
				return Filter::Mode::Lanczos3;
			}

			switch (FromAString<int>(sval)) {
			case 1:
				return Filter::Mode::NearestNeighbor;
			case 2:
				return Filter::Mode::Bilinear;
			case 3:
				return Filter::Mode::Lanczos3;
			}

			return boost::none;
		}

		boost::optional<FilterModeTranslator::internal_type> FilterModeTranslator::put_value(external_type const& val) {
			switch (val) {
			case Filter::Mode::NearestNeighbor:
				return std::string("Nearest");
			case Filter::Mode::Bilinear:
				return std::string("Bilinear");
			case Filter::Mode::Lanczos3:
				return std::string("Lanczos3");
			}

			return boost::none;
		}
	}
}

Fix compile errors on Linux

Fix compile errors on Linux


#include <sdk/config.h>

#ifndef SCHEDULER_CORO_OSTHREAD
# include "Coro.c"
#endif

Include sdk/config.h before testing configuration macros.

	* src/scheduler/libcoroutine/Coro.cc: Here.


//===- MachineDominators.cpp - Machine Dominator Calculation --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators on machine functions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/Passes.h"

using namespace llvm;

TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
TEMPLATE_INSTANTIATION(class DominatorTreeBase<MachineBasicBlock>);

namespace {
  char MachineDominatorTree::ID = 0;
  RegisterPass<MachineDominatorTree>
  E("machinedomtree", "MachineDominator Tree Construction", true);
}

const PassInfo *llvm::MachineDominatorsID = E.getPassInfo();

//===- MachineDominators.cpp - Machine Dominator Calculation --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators on machine functions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/Passes.h"

using namespace llvm;

TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
TEMPLATE_INSTANTIATION(class DominatorTreeBase<MachineBasicBlock>);

char MachineDominatorTree::ID = 0;

namespace {
  RegisterPass<MachineDominatorTree>
  E("machinedomtree", "MachineDominator Tree Construction", true);
}

const PassInfo *llvm::MachineDominatorsID = E.getPassInfo();

Fix build issue on certain compilers.

Fix build issue on certain compilers.

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


#include "gtest/gtest.h"
#include "braincloud/BrainCloudClient.h"
#include "TestResult.h"
#include "TestBCGlobalFile.h"
#include <vector>
using namespace BrainCloud;

static const std::string testfileName = "png1.png";
static const std::string testFileId = "34802251-0da0-419e-91b5-59d91790af15";
static const std::string testFolderPath = "/existingfolder/";

TEST_F(TestBCGlobalFile, GetFileInfo)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getFileInfo(testFileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetFileInfoSimple)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getFileInfoSimple(testFolderPath, testfileName, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetGlobalCDNUrl)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getGlobalCDNUrl(testFileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetGlobalFileList)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getGlobalFileList(testFolderPath, true, &tr);
	tr.run(m_bc);
}

#include "gtest/gtest.h"
#include "braincloud/BrainCloudClient.h"
#include "TestResult.h"
#include "TestBCGlobalFile.h"
#include <vector>
using namespace BrainCloud;

static const std::string testfileName = "testGlobalFile.png";
static const std::string testFileId = "ed2d2924-4650-4a88-b095-94b75ce9aa18";
static const std::string testFolderPath = "/fname/";

TEST_F(TestBCGlobalFile, GetFileInfo)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getFileInfo(testFileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetFileInfoSimple)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getFileInfoSimple(testFolderPath, testfileName, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetGlobalCDNUrl)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getGlobalCDNUrl(testFileId, &tr);
	tr.run(m_bc);
}

TEST_F(TestBCGlobalFile, GetGlobalFileList)
{
	TestResult tr;
	m_bc->getGlobalFileService()->getGlobalFileList(testFolderPath, true, &tr);
	tr.run(m_bc);
}

Revert updating file/folder parameter for Global File unit tests


#include "JNIRhodes.h"

#include "gapikey.h"

#include <common/rhoparams.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"

RHO_GLOBAL void mapview_create(rho_param *p)
{
#ifdef GOOGLE_API_KEY
    jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
    if (!clsMapView) return;
    jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V");
    if (!midCreate) return;

    if (p->type != RHO_PARAM_HASH) {
        RAWLOG_ERROR("create: wrong input parameter (expect Hash)");
        return;
    }

    JNIEnv *env = jnienv();
    jobject paramsObj = RhoValueConverter(env).createObject(p);
    env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj);
#else
    RHO_NOT_IMPLEMENTED;
#endif
}

#include "JNIRhodes.h"

#include "gapikey.h"

#include <common/rhoparams.h>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "MapView"

extern "C" void alert_show_popup(char *);

RHO_GLOBAL void mapview_create(rho_param *p)
{
#ifdef GOOGLE_API_KEY
    jclass clsMapView = getJNIClass(RHODES_JAVA_CLASS_MAPVIEW);
    if (!clsMapView) return;
    jmethodID midCreate = getJNIClassStaticMethod(clsMapView, "create", "(Ljava/lang/String;Ljava/util/Map;)V");
    if (!midCreate) return;

    if (p->type != RHO_PARAM_HASH) {
        RAWLOG_ERROR("create: wrong input parameter (expect Hash)");
        return;
    }

    JNIEnv *env = jnienv();
    jobject paramsObj = RhoValueConverter(env).createObject(p);
    env->CallStaticVoidMethod(clsMapView, midCreate, env->NewStringUTF(GOOGLE_API_KEY), paramsObj);
#else
    alert_show_popup("Google API key problem");
#endif
}

Add alert when Google API key was not specified


#include "DotGraphOutput.hh"
#include "EdgeType.hh"

string getEdgeStyle(EdgeType t) {
  switch (t) {
  case EdgeType::Plane:
    return "[color=red]";
  case EdgeType::Train:
    return "[color=blue,style=dotted]";
  default:
    return "";
  }
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << this->graph_.getVertex(i).name()
	 << " -> " << this->graph_.getVertex(e->getOtherEnd(i)).name()
	 << " " << getEdgeStyle(e->type())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;

#include "DotGraphOutput.hh"
#include "EdgeType.hh"

#include <sstream>

template <typename V>
string getEdgeStyle(EdgeType t, V val) {

  stringstream ss;
  string end("\"]");

  switch (t) {
  case EdgeType::Plane:
    ss << string("[color=red, label=\"") << val << end;
    break;
  case EdgeType::Train:
    ss << string("[color=blue, style=dotted, label=\"") << val << end ;
    break;
  default:
    ss << string("[label=\"") << val << end;
    break;
  }
  return ss.str();
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    st << "\t" << i << " [label=\"" << this->graph_.getVertex(i).name() << "\"];" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << i
	 << " -> " << e->getOtherEnd(i)
	 << " " << getEdgeStyle(e->type(), e->distance())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;

Add edges values and proper labels to node in Dot output


#ifdef LEGACY_LINUX

// Wrappers for eventfd(), since CentOS backported the system
// calls but not the libc wrappers.

#include "arch/linux/system_event/eventfd.hpp"
#include "utils.hpp"
#include <sys/syscall.h>

int eventfd(int count, int flags) {
    rassert(flags == 0); // Legacy kernel doesn't have eventfd2.
    return syscall(SYS_eventfd, count);
}

int eventfd_read(int fd, eventfd_t *value) {
    int res = read(fd, value, sizeof(eventfd_t));
    return (res == sizeof(eventfd_t)) ? 0 : -1;
}

int eventfd_write(int fd, eventfd_t value) {
  int res = write(fd, &value, sizeof(eventfd_t));
  return (res == sizeof(eventfd_t)) ? 0 : -1;
}

#endif

#ifdef LEGACY_LINUX

// Wrappers for eventfd(), since CentOS backported the system
// calls but not the libc wrappers.

#include "arch/linux/system_event/eventfd.hpp"
#include "utils.hpp"
#include <sys/syscall.h>

int eventfd(int count, UNUSED int flags) {
    rassert(flags == 0); // Legacy kernel doesn't have eventfd2.
    return syscall(SYS_eventfd, count);
}

int eventfd_read(int fd, eventfd_t *value) {
    int res = read(fd, value, sizeof(eventfd_t));
    return (res == sizeof(eventfd_t)) ? 0 : -1;
}

int eventfd_write(int fd, eventfd_t value) {
  int res = write(fd, &value, sizeof(eventfd_t));
  return (res == sizeof(eventfd_t)) ? 0 : -1;
}

#endif

Fix a compiler error glitch with some bullshit.


/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

#include "mainwindow.h"
#include "version.h"
#include <QApplication>
#include <QCommandLineParser>

using namespace UnTech::GuiQt;

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("UnTech Editor GUI");
    app.setOrganizationDomain(UNTECH_DOMAIN);
    app.setApplicationVersion(UNTECH_VERSION);

    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("file", "utres file", "[file]");
    parser.process(app);

    MainWindow* window = new MainWindow();
    window->show();

    const QStringList args = parser.positionalArguments();
    if (args.size() > 0) {
        window->loadProject(args.first());
    }

    return app.exec();
}

/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

#include "mainwindow.h"
#include "version.h"
#include <QApplication>
#include <QCommandLineParser>
#include <QSettings>

using namespace UnTech::GuiQt;

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("UnTech Editor GUI");
    app.setOrganizationDomain(UNTECH_DOMAIN);
    app.setApplicationVersion(UNTECH_VERSION);

#ifdef Q_OS_WIN
    // Use an ini file instead of the registry to store GUI settings.
    //
    // The `window_state` QSettings key is ~5.3KB (as of December 2019) and
    // Microsoft's documentation recommends that we do not store values > 2048 bytes in the registry.
    // https://docs.microsoft.com/en-us/windows/win32/sysinfo/registry-element-size-limits
    QSettings::setDefaultFormat(QSettings::IniFormat);
#endif

    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("file", "utres file", "[file]");
    parser.process(app);

    MainWindow* window = new MainWindow();
    window->show();

    const QStringList args = parser.positionalArguments();
    if (args.size() > 0) {
        window->loadProject(args.first());
    }

    return app.exec();
}

Use an ini file to store GUI settings in windows

The `window_state` QSettings key is ~5.3KB and Microsoft's documentation
recommends that we do not store values > 2048 bytes in the registry.


#include "nwg_service.h"

#include "nwg_eventloop.h"

namespace Nwg
{

Service::Service(EventLoop *eventLoop)
    : _eventLoop(eventLoop),
      _protocolCodec(nullptr),
      _handler(nullptr)
{
}

Service::~Service()
{
    _protocolCodec.reset();
    _handler.reset();
}

void Service::setBuffSize(int buffSize) { _buffSize = buffSize; }
void Service::setReadBuffSize(int readBuffSize) { _readBuffSize = readBuffSize; }

void Service::setProtocolCodec(const std::shared_ptr<ProtocolCodec> &protocolCodec)
{
    _protocolCodec = protocolCodec;
}

void Service::setHandler(const std::shared_ptr<Handler> &handler)
{
    _handler = handler;
}

EventLoop *Service::getEventLoop() const { return _eventLoop; }

size_t Service::getBuffSize() { return _buffSize; }
size_t Service::getReadBuffSize() { return _readBuffSize; }

ProtocolCodec &Service::getProtocolCodec()
{
    return *_protocolCodec;
}

Handler &Service::getHandler()
{
    return *_handler;
}

} /* namespace Nwg */

#include "nwg_service.h"

#include "nwg_eventloop.h"
#include "nwg_basicprotocolcodec.h"

namespace Nwg
{

Service::Service(EventLoop *eventLoop)
    : _eventLoop(eventLoop),
      _protocolCodec(nullptr),
      _handler(nullptr)
{
}

Service::~Service()
{
    _protocolCodec.reset();
    _handler.reset();
}

void Service::setBuffSize(int buffSize) { _buffSize = buffSize; }
void Service::setReadBuffSize(int readBuffSize) { _readBuffSize = readBuffSize; }

void Service::setProtocolCodec(const std::shared_ptr<ProtocolCodec> &protocolCodec)
{
    _protocolCodec = protocolCodec;
}

void Service::setHandler(const std::shared_ptr<Handler> &handler)
{
    _handler = handler;
}

EventLoop *Service::getEventLoop() const { return _eventLoop; }

size_t Service::getBuffSize() { return _buffSize; }
size_t Service::getReadBuffSize() { return _readBuffSize; }

ProtocolCodec &Service::getProtocolCodec()
{
    if (_protocolCodec == nullptr) {
        _protocolCodec = std::make_shared<Nwg::BasicProtocolCodec>();
    }
    return *_protocolCodec;
}

Handler &Service::getHandler()
{
    return *_handler;
}

} /* namespace Nwg */

Create BasicProtocolCodec if _protocolCodec is null

@ Service::getProtocolCodec()


#include "PrologInterface.h"

void PrologLifetime::begin(int argc, char *argv[]) {
  if (!PL_initialise(argc, argv)) {
    PL_halt(EXIT_FAILURE);
  }
}

void PrologLifetime::end() {
  PL_halt(EXIT_SUCCESS);
}

#include "PrologInterface.h"

void PrologLifetime::begin(int argc, char *argv[]) {
  if (!PL_initialise(argc, argv)) {
    PL_halt(EXIT_FAILURE);
  }
}

void PrologLifetime::end() {
  PL_cleanup(EXIT_SUCCESS);
}

Use PL_cleanup instead of PL_halt

Use PL_cleanup instead of PL_halt

PL_halt halts execution (silly me, of course it does). We don't want
that, so we use PL_cleanup instead.


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

#include "atom/common/event_emitter_caller.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
                                      v8::Local<v8::Object> obj,
                                      ValueVector* args) {
  v8::Local<v8::String> emit_name = StringToSymbol(isolate, "emit");
  v8::Local<v8::Value> emit = obj->Get(emit_name);
  if (emit.IsEmpty() || !emit->IsFunction()) {
    isolate->ThrowException(v8::Exception::TypeError(
        StringToV8(isolate, "\"emit\" is not a function")));
    return v8::Undefined(isolate);
  }

  v8::MaybeLocal<v8::Value> result = emit.As<v8::Function>()->Call(
      isolate->GetCurrentContext(), obj, args->size(), &args->front());
  if (result.IsEmpty()) {
    return v8::Undefined(isolate);
  }

  return result.ToLocalChecked();
}

}  // namespace internal

}  // namespace mate

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

#include "atom/common/event_emitter_caller.h"

#include "atom/common/node_includes.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
                                      v8::Local<v8::Object> obj,
                                      ValueVector* args) {
  return node::MakeCallback(
      isolate, obj, "emit", args->size(), &args->front());
}

}  // namespace internal

}  // namespace mate

Use node::MakeCallback to emit events in C++

Fix #2165


#include "GoogleLogFatalHandler.hpp"

#include "Headers.hpp"

namespace google {
namespace glog_internal_namespace_ {
void DumpStackTraceToString(string* stacktrace);
}
}  // namespace google

static void DumpStackTraceToFileAndExit() {
  string s;
  google::glog_internal_namespace_::DumpStackTraceToString(&s);
  LOG(ERROR) << "STACK TRACE:\n" << s;

  // TOOD(hamaji): Use signal instead of sigaction?
  if (google::glog_internal_namespace_::IsFailureSignalHandlerInstalled()) {
// Set the default signal handler for SIGABRT, to avoid invoking our
// own signal handler installed by InstallFailureSignalHandler().
#ifdef HAVE_SIGACTION
    struct sigaction sig_action;
    memset(&sig_action, 0, sizeof(sig_action));
    sigemptyset(&sig_action.sa_mask);
    sig_action.sa_handler = SIG_DFL;
    sigaction(SIGABRT, &sig_action, NULL);
#elif defined(OS_WINDOWS)
    signal(SIGABRT, SIG_DFL);
#endif  // HAVE_SIGACTION
  }

  abort();
}

namespace et {
void GoogleLogFatalHandler::handle() {
  google::InstallFailureFunction(&DumpStackTraceToFileAndExit);
}

}  // namespace et

#include "GoogleLogFatalHandler.hpp"

#include "Headers.hpp"

namespace google {
namespace glog_internal_namespace_ {
void DumpStackTraceToString(string* stacktrace);
}
}  // namespace google

static void DumpStackTraceToFileAndExit() {
  string s;
  google::glog_internal_namespace_::DumpStackTraceToString(&s);
  LOG(ERROR) << "STACK TRACE:\n" << s;
  abort();
}

namespace et {
void GoogleLogFatalHandler::handle() {
  google::InstallFailureFunction(&DumpStackTraceToFileAndExit);
}

}  // namespace et

Remove logic that isn't supported on Ubuntu/Debian


#include <RGBColor.h>

RGBColor RGBColor::black(glm::vec3(0.f, 0.f, 0.f));
RGBColor RGBColor::red(glm::vec3(1.f, 0.f, 0.f));

RGBColor::RGBColor()
    : color(glm::vec3(0.f, 0.f, 0.f))
{
}

RGBColor::RGBColor(const glm::vec3& color)
    : color(color)
{
}

glm::vec3 RGBColor::GetRGBComponents() const
{
    return this->color;
}

uint32_t RGBColor::GetRGBAIntPacked() const
{
    uint32_t col = 0xFF;
    col = col | ((uint32_t)(color.x * 0xFF) << 24);
    col = col | ((uint32_t)(color.y * 0xFF) << 16);
    col = col | ((uint32_t)(color.z * 0xFF) << 8);
    return col;
}

#include <RGBColor.h>

RGBColor RGBColor::black(glm::vec3(0.f, 0.f, 0.f));
RGBColor RGBColor::red(glm::vec3(1.f, 0.f, 0.f));

RGBColor::RGBColor()
    : color(glm::vec3(0.f, 0.f, 0.f))
{
}

RGBColor::RGBColor(const glm::vec3& color)
    : color(color)
{
}

glm::vec3 RGBColor::GetRGBComponents() const
{
    return this->color;
}

uint32_t RGBColor::GetRGBAIntPacked() const
{
    uint32_t col = 0;
    col = col | ((uint32_t)(color.x * 0xFF));
    col = col | ((uint32_t)(color.y * 0xFF) << 8);
    col = col | ((uint32_t)(color.z * 0xFF) << 16);
    col = col | (0xFF << 24);
    return col;
}

Correct for color order inside PNG

Correct for color order inside PNG


// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: clang-tidy %t.cpp -fix -checks=llvm.* --
// RUN: FileCheck -input-file=%t.cpp %s

namespace i {
}
// CHECK: } // namespace i

class A { A(int i); }; // Not fixing this, because the check is in google-.
// CHECK: class A { A(int i); };

// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: clang-tidy %t.cpp -fix -checks=^llvm-.* --
// RUN: FileCheck -input-file=%t.cpp %s

namespace i {
}
// CHECK: } // namespace i

class A { A(int i); }; // Not fixing this, because the check is in google-.
// CHECK: class A { A(int i); };

Use more specific checks filter in the test.

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


// XFAIL: hexagon
// Test this without pch.
// RUN: %clang_cc1 -include %S/cxx-typeid.h -fsyntax-only -verify %s

// RUN: %clang_cc1 -x c++-header -emit-pch -o %t.pch %S/cxx-typeid.h
// RUN: %clang_cc1 -include-pch %t.pch -fsyntax-only -verify %s

// expected-no-diagnostics

void f() {
    (void)typeid(int);
}

Remove XFAIL now that the test is standalone.

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