Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix logging config section width | /* Copyright (c) 2013-2019 Jeffrey Pfau
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "RotatedHeaderView.h"
#include <QPainter>
using namespace QGBA;
RotatedHeaderView::RotatedHeaderView(Qt::Orientation orientation, QWidget* parent)
: QHeaderView(orientation, parent)
{
}
void RotatedHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const {
painter->save();
painter->translate(rect.x() + rect.width(), rect.y());
painter->rotate(90);
QHeaderView::paintSection(painter, QRect(0, 0, rect.height(), rect.width()), logicalIndex);
painter->restore();
}
QSize RotatedHeaderView::sectionSizeFromContents(int logicalIndex) const {
return QHeaderView::sectionSizeFromContents(logicalIndex).transposed();
} | /* Copyright (c) 2013-2019 Jeffrey Pfau
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "RotatedHeaderView.h"
#include <QPainter>
using namespace QGBA;
RotatedHeaderView::RotatedHeaderView(Qt::Orientation orientation, QWidget* parent)
: QHeaderView(orientation, parent)
{
int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, 0, this);
setMinimumSectionSize(fontMetrics().height() + margin);
}
void RotatedHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const {
painter->save();
painter->translate(rect.x() + rect.width(), rect.y());
painter->rotate(90);
QHeaderView::paintSection(painter, QRect(0, 0, rect.height(), rect.width()), logicalIndex);
painter->restore();
}
QSize RotatedHeaderView::sectionSizeFromContents(int logicalIndex) const {
return QHeaderView::sectionSizeFromContents(logicalIndex).transposed();
} |
Remove isnan of an int | #include "Halide.h"
#include <stdint.h>
#include <stdio.h>
#include <cmath>
using namespace Halide;
// FIXME: Why aren't we using a unit test framework for this?
// See Issue #898
void h_assert(bool condition, const char* msg) {
if (!condition) {
printf("FAIL: %s\n", msg);
abort();
}
}
int main() {
// Number is larger than can be represented in half and won't be rounded
// down to the largest representable value in half(65504). but should be
// representable in single precision
const int32_t largeNum = 65536;
h_assert(!std::isnan(largeNum), "largeNum should not be NaN");
h_assert(!std::isinf(largeNum), "largeNum should not be inf");
// This should fail as it triggers overflow
float16_t fail = float16_t::make_from_signed_int(largeNum, RoundingMode::ToNearestTiesToEven);
// Supress -Wunused-but-set-variable
fail.is_infinity();
printf("Should not be reached!\n");
return 0;
}
| #include "Halide.h"
#include <stdint.h>
#include <stdio.h>
#include <cmath>
using namespace Halide;
// FIXME: Why aren't we using a unit test framework for this?
// See Issue #898
void h_assert(bool condition, const char* msg) {
if (!condition) {
printf("FAIL: %s\n", msg);
abort();
}
}
int main() {
// Number is larger than can be represented in half and won't be rounded
// down to the largest representable value in half(65504). but should be
// representable in single precision
const int32_t largeNum = 65536;
// This should fail as it triggers overflow
float16_t fail = float16_t::make_from_signed_int(largeNum, RoundingMode::ToNearestTiesToEven);
// Supress -Wunused-but-set-variable
fail.is_infinity();
printf("Should not be reached!\n");
return 0;
}
|
Fix libshogun example (preventing segfault when shogun_exit() is called before kernel objects are destroyed) | #include <shogun/base/init.h>
#include <shogun/lib/common.h>
#include <shogun/lib/GCArray.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/kernel/GaussianKernel.h>
#include <stdio.h>
using namespace shogun;
const int l=10;
int main(int argc, char** argv)
{
init_shogun();
// create array of kernels
CGCArray<CKernel*> kernels(l);
// fill array with kernels
for (int i=0; i<l; i++)
kernels.set(new CGaussianKernel(10, 1.0), i);
// print kernels
for (int i=0; i<l; i++)
{
CKernel* kernel = kernels.get(i);
printf("kernels[%d]=%p\n", i, kernel);
SG_UNREF(kernel);
}
exit_shogun();
return 0;
}
| #include <shogun/base/init.h>
#include <shogun/lib/common.h>
#include <shogun/lib/GCArray.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/kernel/GaussianKernel.h>
#include <stdio.h>
using namespace shogun;
const int l=10;
int main(int argc, char** argv)
{
init_shogun();
// we need this scope, because exit_shogun() must not be called
// before the destructor of CGCArray<CKernel*> kernels!
{
// create array of kernels
CGCArray<CKernel*> kernels(l);
// fill array with kernels
for (int i=0; i<l; i++)
kernels.set(new CGaussianKernel(10, 1.0), i);
// print kernels
for (int i=0; i<l; i++)
{
CKernel* kernel = kernels.get(i);
printf("kernels[%d]=%p\n", i, kernel);
SG_UNREF(kernel);
}
}
exit_shogun();
return 0;
}
|
Add parenthesis around predicates before query expansion. | #include "Query.hh"
QString generateQuery(QString const &base, QString const &attribute, QString const &value)
{
QString condition = QString("@%1=\"%2\"").arg(attribute).arg(value);
return generateQuery(base, condition);
}
QString generateQuery(QString const &base, QString const &condition)
{
int subSelectionPos = base.lastIndexOf('/');
if (!subSelectionPos)
return QString();
int closingBracketPos = base.mid(subSelectionPos).lastIndexOf(']');
if (closingBracketPos == -1)
return QString("%1[%2]").arg(base).arg(condition);
else
return QString("%1 and %2%3").arg(
base.left(subSelectionPos + closingBracketPos),
condition,
base.mid(subSelectionPos + closingBracketPos));
}
| #include <QtDebug>
#include "Query.hh"
QString generateQuery(QString const &base, QString const &attribute, QString const &value)
{
QString condition = QString("@%1=\"%2\"").arg(attribute).arg(value);
return generateQuery(base, condition);
}
QString generateQuery(QString const &base, QString const &condition)
{
int subSelectionPos = base.lastIndexOf('/');
if (!subSelectionPos)
return QString();
int openingBracketPos = base.indexOf('[', subSelectionPos);
if (openingBracketPos == -1)
return QString("%1[%2]").arg(base).arg(condition);
// Add parenthesis around original predicates.
QString expanded = base;
expanded.insert(openingBracketPos + 1, '(');
int closingBracketPos = expanded.lastIndexOf(']');
if (closingBracketPos == -1) {
qDebug() << "Malformed query?: " << base;
return base;
}
expanded.insert(closingBracketPos, QString(") and %1").arg(condition));
return expanded;
}
|
SET explosion life time to 10 seconds | #include "stdafx.h"
#include "Collider.h"
#include "Explosion.h"
#include "ColliderManager.h"
//Base Class of All Explosions
bool Explosion::init()
{
explosion = ParticleExplosion::create();
this->addChild(explosion);
isFlying = true;
lifeTime = 2 * Director::getInstance()->getFrameRate();
return true;
}
void Explosion::Act()
{
if (lifeTime > 0)
{
lifeTime--;
}
else
{
SetFlying(false);
removeFromParent();
ColliderManager::GetInstance()->EraseCollider(this);
}
}
bool Explosion::IsFlying()
{
return isFlying;
}
void Explosion::SetFlying(bool flag)
{
isFlying = flag;
}
bool Explosion::IsBullet()
{
return false;
}
void Explosion::SetPosition(Point pos)
{
setPosition(pos);
explosion->setPosition(Point::ZERO);
}
| #include "stdafx.h"
#include "Collider.h"
#include "Explosion.h"
#include "ColliderManager.h"
//Base Class of All Explosions
bool Explosion::init()
{
explosion = ParticleExplosion::create();
this->addChild(explosion);
isFlying = true;
lifeTime = 10 * Director::getInstance()->getFrameRate();
return true;
}
void Explosion::Act()
{
if (lifeTime > 0)
{
lifeTime--;
}
else
{
SetFlying(false);
removeFromParent();
ColliderManager::GetInstance()->EraseCollider(this);
}
}
bool Explosion::IsFlying()
{
return isFlying;
}
void Explosion::SetFlying(bool flag)
{
isFlying = flag;
}
bool Explosion::IsBullet()
{
return false;
}
void Explosion::SetPosition(Point pos)
{
setPosition(pos);
explosion->setPosition(Point::ZERO);
}
|
Increase buffer size to 1024 in SysErrorString | // Copyright (c) 2020-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <tinyformat.h>
#include <util/syserror.h>
#include <cstring>
std::string SysErrorString(int err)
{
char buf[256];
/* Too bad there are three incompatible implementations of the
* thread-safe strerror. */
const char *s = nullptr;
#ifdef WIN32
if (strerror_s(buf, sizeof(buf), err) == 0) s = buf;
#else
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf;
#endif
#endif
if (s != nullptr) {
return strprintf("%s (%d)", s, err);
} else {
return strprintf("Unknown error (%d)", err);
}
}
| // Copyright (c) 2020-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <tinyformat.h>
#include <util/syserror.h>
#include <cstring>
std::string SysErrorString(int err)
{
char buf[1024];
/* Too bad there are three incompatible implementations of the
* thread-safe strerror. */
const char *s = nullptr;
#ifdef WIN32
if (strerror_s(buf, sizeof(buf), err) == 0) s = buf;
#else
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf;
#endif
#endif
if (s != nullptr) {
return strprintf("%s (%d)", s, err);
} else {
return strprintf("Unknown error (%d)", err);
}
}
|
Fix type in uint64 Endian test | #include "gtest/gtest.h"
#include "lms/endian.h"
TEST(Endian, uint16) {
using lms::Endian;
ASSERT_EQ(0xFECAu, Endian::letoh(Endian::htobe(uint16_t(0xCAFEu))));
ASSERT_EQ(0xFECAu, Endian::betoh(Endian::htole(uint16_t(0xCAFEu))));
}
TEST(Endian, uint32) {
using lms::Endian;
ASSERT_EQ(0xEFBEADDEu, Endian::letoh(Endian::htobe(uint32_t(0xDEADBEEFu))));
ASSERT_EQ(0xEFBEADDEu, Endian::betoh(Endian::htole(uint32_t(0xDEADBEEFu))));
}
TEST(Endian, uint64) {
using lms::Endian;
ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::letoh(Endian::htobe(0xFEEDCAFEDEADBEEFu)));
ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::betoh(Endian::htole(0xFEEDCAFEDEADBEEFu)));
}
| #include "gtest/gtest.h"
#include "lms/endian.h"
TEST(Endian, uint16) {
using lms::Endian;
ASSERT_EQ(0xFECAu, Endian::letoh(Endian::htobe(uint16_t(0xCAFEu))));
ASSERT_EQ(0xFECAu, Endian::betoh(Endian::htole(uint16_t(0xCAFEu))));
}
TEST(Endian, uint32) {
using lms::Endian;
ASSERT_EQ(0xEFBEADDEu, Endian::letoh(Endian::htobe(uint32_t(0xDEADBEEFu))));
ASSERT_EQ(0xEFBEADDEu, Endian::betoh(Endian::htole(uint32_t(0xDEADBEEFu))));
}
TEST(Endian, uint64) {
using lms::Endian;
ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::letoh(Endian::htobe(uint64_t(0xFEEDCAFEDEADBEEFu))));
ASSERT_EQ(0xEFBEADDEFECAEDFEu, Endian::betoh(Endian::htole(uint64_t(0xFEEDCAFEDEADBEEFu))));
}
|
Support for leading ? wildcards | #include "Selector.h"
bool StartsWith(const std::string& prefix, const std::string& query)
{
return (query.compare(0, prefix.length(), prefix) == 0);
}
std::string ConsumePrefix(const std::string& prefix, const std::string& query)
{
if (StartsWith(prefix, query))
return query.substr(prefix.length());
else
return query;
}
| #include "Selector.h"
bool StartsWith(const std::string& prefix, const std::string& query)
{
if (prefix.length() == 0)
return true;
if (prefix[0] == '?' && query.length() > 0)
{
return StartsWith(prefix.substr(1), query.substr(1));
}
return (query.compare(0, prefix.length(), prefix) == 0);
}
std::string ConsumePrefix(const std::string& prefix, const std::string& query)
{
if (StartsWith(prefix, query))
return query.substr(prefix.length());
else
return query;
}
|
Remove hard coded dos line endings, let subversion translate them on update. | // RUN: %clang_cc1 -fdelayed-template-parsing -fsyntax-only -verify %s
template <class T>
class A {
void foo() {
undeclared();
}
void foo2();
};
template <class T>
class B {
void foo4() { } // expected-note {{previous definition is here}} expected-note {{previous definition is here}}
void foo4() { } // expected-error {{class member cannot be redeclared}} expected-error {{redefinition of 'foo4'}} expected-note {{previous definition is here}}
};
template <class T>
void B<T>::foo4() {// expected-error {{redefinition of 'foo4'}}
}
template <class T>
void A<T>::foo2() {
undeclared();
}
template <class T>
void foo3() {
undeclared();
}
template void A<int>::foo2();
void undeclared()
{
}
template <class T> void foo5() {} //expected-note {{previous definition is here}}
template <class T> void foo5() {} // expected-error {{redefinition of 'foo5'}}
| // RUN: %clang_cc1 -fdelayed-template-parsing -fsyntax-only -verify %s
template <class T>
class A {
void foo() {
undeclared();
}
void foo2();
};
template <class T>
class B {
void foo4() { } // expected-note {{previous definition is here}} expected-note {{previous definition is here}}
void foo4() { } // expected-error {{class member cannot be redeclared}} expected-error {{redefinition of 'foo4'}} expected-note {{previous definition is here}}
};
template <class T>
void B<T>::foo4() {// expected-error {{redefinition of 'foo4'}}
}
template <class T>
void A<T>::foo2() {
undeclared();
}
template <class T>
void foo3() {
undeclared();
}
template void A<int>::foo2();
void undeclared()
{
}
template <class T> void foo5() {} //expected-note {{previous definition is here}}
template <class T> void foo5() {} // expected-error {{redefinition of 'foo5'}}
|
ADD intialized the Progress variables | #include "Progression.h"
Progression* Progression::m_instance = nullptr;
Progression::Progression()
{
}
Progression::~Progression()
{
}
bool Progression::WriteToFile(std::string filename)
{
std::ofstream saveFile;
saveFile.open("..\\Debug\\Saves\\" + filename + ".txt");
if (!saveFile.is_open()) {
return false;
}
else
{
saveFile << "Allhuakbar" << "\r\n";
saveFile.close();
}
return true;
}
bool Progression::ReadFromFile(std::string filename)
{
return false;
}
| #include "Progression.h"
Progression* Progression::m_instance = nullptr;
Progression::Progression()
{
this->m_currentLevel = 0;
this->m_currentCheckpoint = 0;
this->m_unlockedLevels = 0;
}
Progression::~Progression()
{
}
bool Progression::WriteToFile(std::string filename)
{
std::ofstream saveFile;
saveFile.open("..\\Debug\\Saves\\" + filename + ".txt");
if (!saveFile.is_open()) {
return false;
}
else
{
saveFile << "Allhuakbar" << "\r\n";
saveFile.close();
}
return true;
}
bool Progression::ReadFromFile(std::string filename)
{
return false;
}
|
Change UART number in uart_example to be compatible with TI lm4f120xl. |
#include <hal/clock.hpp>
#include <hal/uart.hpp>
#include <stdio.h>
#define UNUSED(expr) do { (void)(expr); } while (0)
#define CURRENT_UART 1
//------------------------------------------------------------------------------
void callback (const types::buffer& buffer, uart::Uart& uart)
{
uart.send(buffer);
uart.send("\r\n");
}
//------------------------------------------------------------------------------
extern "C"
{
void write_stdout (const unsigned char* ptr, unsigned int len)
{
uart::get_instance(CURRENT_UART).send(ptr, len);
}
}
//------------------------------------------------------------------------------
int main(void)
{
uart::init_instance<uart::PolicyNotifyOnChar<'\r'>>(CURRENT_UART, callback);
unsigned char Idx = 0;
while(1)
{
printf ("Index : %d\r\n", Idx);
clock::msleep(500);
Idx++;
}
}
//------------------------------------------------------------------------------
|
#include <hal/clock.hpp>
#include <hal/uart.hpp>
#include <stdio.h>
#define UNUSED(expr) do { (void)(expr); } while (0)
#define CURRENT_UART 2
//------------------------------------------------------------------------------
void callback (const types::buffer& buffer, uart::Uart& uart)
{
uart.send(buffer);
uart.send("\r\n");
}
//------------------------------------------------------------------------------
extern "C"
{
void write_stdout (const unsigned char* ptr, unsigned int len)
{
uart::get_instance(CURRENT_UART).send(ptr, len);
}
}
//------------------------------------------------------------------------------
int main(void)
{
uart::init_instance<uart::PolicyNotifyOnChar<'\r'>>(CURRENT_UART, callback);
unsigned char Idx = 0;
while(1)
{
printf ("Index : %d\r\n", Idx);
clock::msleep(500);
Idx++;
}
}
//------------------------------------------------------------------------------
|
Check if input file is good | #include "../vm/debug.h"
#include "../vm/vm.h"
#include <fstream>
int main(int argc, char *argv[]) {
std::ifstream bytecode_if;
std::streamsize bytecode_size;
uint8_t *bytecode;
if (argc < 3) {
printf("Usage: %s <opcodes_key> <program>\n", argv[0]);
return 1;
}
/*
reading bytecode
*/
bytecode_if.open(argv[2], std::ios::binary | std::ios::ate);
bytecode_size = bytecode_if.tellg();
bytecode_if.seekg(0, std::ios::beg);
bytecode = new uint8_t[bytecode_size];
bytecode_if.read((char *) bytecode, bytecode_size);
VM vm((uint8_t *) argv[1], bytecode, bytecode_size);
vm.run();
return 0;
} | #include "../vm/debug.h"
#include "../vm/vm.h"
#include <fstream>
int main(int argc, char *argv[]) {
std::ifstream bytecode_if;
std::streamsize bytecode_size;
uint8_t *bytecode;
if (argc < 3) {
printf("Usage: %s <opcodes_key> <program>\n", argv[0]);
return 1;
}
/*
reading bytecode
*/
bytecode_if.open(argv[2], std::ios::binary | std::ios::ate);
if (!bytecode_if.good()) {
printf("File is not valid.\n");
return -1;
}
bytecode_size = bytecode_if.tellg();
bytecode_if.seekg(0, std::ios::beg);
bytecode = new uint8_t[bytecode_size];
bytecode_if.read((char *) bytecode, bytecode_size);
VM vm((uint8_t *) argv[1], bytecode, bytecode_size);
vm.run();
return 0;
} |
Add exiting normally to the app | #include <exception>
#include "globals.hh"
#include "G4Application.hh"
using namespace g4;
using namespace std;
/**
* @short Simple main function.
*
* It only initializes and runs application and
* prints out all exceptions.
*/
int main(int argc, char** argv)
{
try
{
// Run the application
G4Application::CreateInstance(argc, argv);
G4Application::GetInstance()->RunUI();
}
catch (const exception& exc)
{
G4cerr << "Exception thrown: " << exc.what() << endl;
exit(-1);
}
catch (const string& exc)
{
G4cerr << "Exception thrown: " << exc << endl;
exit(-1);
}
catch (const char* exc)
{
G4cerr << "Exception thrown: " << exc << endl;
exit(-1);
}
}
| #include <exception>
#include "globals.hh"
#include "G4Application.hh"
using namespace g4;
using namespace std;
/**
* @short Simple main function.
*
* It only initializes and runs application and
* prints out all exceptions.
*/
int main(int argc, char** argv)
{
try
{
// Run the application
G4Application::CreateInstance(argc, argv);
G4Application::GetInstance()->RunUI();
}
catch (const exception& exc)
{
G4cerr << "Exception thrown: " << exc.what() << endl;
exit(-1);
}
catch (const string& exc)
{
G4cerr << "Exception thrown: " << exc << endl;
exit(-1);
}
catch (const char* exc)
{
G4cerr << "Exception thrown: " << exc << endl;
exit(-1);
}
G4cout << "Application exiting normally..." << G4endl;
}
|
Change zh-tw to zh-TW when it's used to find the locale data pack on Linux (case-sensitive file system). | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_test.h"
class LocaleTestsDa : public UITest {
public:
LocaleTestsDa() : UITest() {
launch_arguments_.AppendSwitchWithValue(L"lang", L"da");
}
};
class LocaleTestsHe : public UITest {
public:
LocaleTestsHe() : UITest() {
launch_arguments_.AppendSwitchWithValue(L"lang", L"he");
}
};
class LocaleTestsZhTw : public UITest {
public:
LocaleTestsZhTw() : UITest() {
launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-tw");
}
};
#if defined(OS_WIN) || defined(OS_LINUX)
// These 3 tests started failing between revisions 13115 and 13120.
// See bug 9758.
TEST_F(LocaleTestsDa, TestStart) {
// Just making sure we can start/shutdown cleanly.
}
TEST_F(LocaleTestsHe, TestStart) {
// Just making sure we can start/shutdown cleanly.
}
TEST_F(LocaleTestsZhTw, TestStart) {
// Just making sure we can start/shutdown cleanly.
}
#endif
| // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_test.h"
class LocaleTestsDa : public UITest {
public:
LocaleTestsDa() : UITest() {
launch_arguments_.AppendSwitchWithValue(L"lang", L"da");
}
};
class LocaleTestsHe : public UITest {
public:
LocaleTestsHe() : UITest() {
launch_arguments_.AppendSwitchWithValue(L"lang", L"he");
}
};
class LocaleTestsZhTw : public UITest {
public:
LocaleTestsZhTw() : UITest() {
launch_arguments_.AppendSwitchWithValue(L"lang", L"zh-TW");
}
};
#if defined(OS_WIN) || defined(OS_LINUX)
// These 3 tests started failing between revisions 13115 and 13120.
// See bug 9758.
TEST_F(LocaleTestsDa, TestStart) {
// Just making sure we can start/shutdown cleanly.
}
TEST_F(LocaleTestsHe, TestStart) {
// Just making sure we can start/shutdown cleanly.
}
TEST_F(LocaleTestsZhTw, TestStart) {
// Just making sure we can start/shutdown cleanly.
}
#endif
|
Reduce float multiplication in strength | //=======================================================================
// 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 "tac/ReduceInStrength.hpp"
#include "tac/OptimizerUtils.hpp"
using namespace eddic;
void tac::ReduceInStrength::operator()(std::shared_ptr<tac::Quadruple>& quadruple){
switch(quadruple->op){
case tac::Operator::MUL:
if(*quadruple->arg1 == 2){
replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::ADD, *quadruple->arg2);
} else if(*quadruple->arg2 == 2){
replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::ADD, *quadruple->arg1);
}
break;
default:
break;
}
}
| //=======================================================================
// 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 "tac/ReduceInStrength.hpp"
#include "tac/OptimizerUtils.hpp"
using namespace eddic;
void tac::ReduceInStrength::operator()(std::shared_ptr<tac::Quadruple>& quadruple){
switch(quadruple->op){
case tac::Operator::MUL:
if(*quadruple->arg1 == 2){
replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::ADD, *quadruple->arg2);
} else if(*quadruple->arg2 == 2){
replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::ADD, *quadruple->arg1);
}
break;
case tac::Operator::FMUL:
if(*quadruple->arg1 == 2.0){
replaceRight(*this, quadruple, *quadruple->arg2, tac::Operator::FADD, *quadruple->arg2);
} else if(*quadruple->arg2 == 2.0){
replaceRight(*this, quadruple, *quadruple->arg1, tac::Operator::FADD, *quadruple->arg1);
}
break;
default:
break;
}
}
|
Insert card game tags in constructor | // Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Cards/Entity.h>
namespace Hearthstonepp
{
Entity::Entity(Card& _card) : card(new Card(_card))
{
// Do nothing
}
Entity::Entity(const Entity& ent)
{
FreeMemory();
card = ent.card;
gameTags = ent.gameTags;
}
Entity::~Entity()
{
FreeMemory();
}
Entity& Entity::operator=(const Entity& ent)
{
if (this == &ent)
{
return *this;
}
FreeMemory();
card = ent.card;
gameTags = ent.gameTags;
return *this;
}
Entity* Entity::Clone() const
{
return new Entity(*this);
}
void Entity::FreeMemory()
{
gameTags.clear();
delete card;
}
} // namespace Hearthstonepp | // Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Cards/Entity.h>
namespace Hearthstonepp
{
Entity::Entity(Card& _card) : card(new Card(_card))
{
for (auto& mechanic : card->mechanics)
{
gameTags.insert(std::make_pair(mechanic, 1));
}
}
Entity::Entity(const Entity& ent)
{
FreeMemory();
card = ent.card;
gameTags = ent.gameTags;
}
Entity::~Entity()
{
FreeMemory();
}
Entity& Entity::operator=(const Entity& ent)
{
if (this == &ent)
{
return *this;
}
FreeMemory();
card = ent.card;
gameTags = ent.gameTags;
return *this;
}
Entity* Entity::Clone() const
{
return new Entity(*this);
}
void Entity::FreeMemory()
{
gameTags.clear();
delete card;
}
} // namespace Hearthstonepp |
Align list items in selection window | #include "selection_window.h"
#include "../components/description_component.h"
#include "../core/game_engine.h"
#include "inspection_window.h"
#include "listbox.h"
void SelectionWindow::setup() {
setEntities(static_cast<EntityHolder*>(getArgs()));
setEscapeBehaviour(Window::EscapeBehaviour::CloseWindow);
setWidth(20);
setHeight(m_entities.size() + 4);
}
void SelectionWindow::registerWidgets() {
ListBox* box = this->createWidget<ListBox>("lstEntities", 2, 2);
for (std::string line : m_lines) {
ListBoxItem item;
item.setText(line);
box->addItem(item);
}
box->setHeight(m_lines.size());
box->setItemSelectedCallback([](ListBox* box) {
SelectionWindow* win = dynamic_cast<SelectionWindow*>(box->getWindow());
EntityId* l_target =
new EntityId(win->getEntities()[box->getSelection()]);
win->getEngine()->getWindows()->createWindow<InspectionWindow>(
l_target);
});
}
void SelectionWindow::setEntities(EntityHolder* entities) {
if (!entities)
return;
for (EntityId entity : *entities) {
DescriptionComponent* desc =
getEngine()->state()->components()->get<DescriptionComponent>(
entity);
if (desc == nullptr)
continue;
m_entities.push_back(entity);
m_lines.push_back(desc->title);
}
} | #include "selection_window.h"
#include "../components/description_component.h"
#include "../core/game_engine.h"
#include "inspection_window.h"
#include "listbox.h"
void SelectionWindow::setup() {
setEntities(static_cast<EntityHolder*>(getArgs()));
setEscapeBehaviour(Window::EscapeBehaviour::CloseWindow);
setWidth(20);
setHeight(m_entities.size() + 4);
}
void SelectionWindow::registerWidgets() {
ListBox* box = this->createWidget<ListBox>("lstEntities", 1, 1);
for (std::string line : m_lines) {
ListBoxItem item;
item.setText(line);
box->addItem(item);
}
box->setHeight(m_lines.size());
box->setItemSelectedCallback([](ListBox* box) {
SelectionWindow* win = dynamic_cast<SelectionWindow*>(box->getWindow());
EntityId* l_target =
new EntityId(win->getEntities()[box->getSelection()]);
win->getEngine()->getWindows()->createWindow<InspectionWindow>(
l_target);
});
}
void SelectionWindow::setEntities(EntityHolder* entities) {
if (!entities)
return;
for (EntityId entity : *entities) {
DescriptionComponent* desc =
getEngine()->state()->components()->get<DescriptionComponent>(
entity);
if (desc == nullptr)
continue;
m_entities.push_back(entity);
m_lines.push_back(desc->title);
}
} |
Upgrade tests for Configuration for threads | #include "tst_configuration.h"
void TST_Configuration::test()
{
CWF::Configuration configuration("");
configuration.setHost(QHostAddress("127.0.0.1"));
configuration.setPort(8080);
configuration.setDomain("www.test.com.xyz");
QVERIFY2(configuration.getHost().toString() == "127.0.0.1", "Should be 127.0.0.1");
QVERIFY2(configuration.getPort() == 8080, "Should be 8080");
QVERIFY2(configuration.getDomain() == "www.test.com.xyz", "Should be www.test.com.xyz");
}
| #include "tst_configuration.h"
void TST_Configuration::test()
{
CWF::Configuration configuration("");
configuration.setHost(QHostAddress("127.0.0.1"));
configuration.setPort(8080);
configuration.setDomain("www.test.com.xyz");
configuration.setMaxThread(200);
QVERIFY2(configuration.getHost().toString() == "127.0.0.1", "Should be 127.0.0.1");
QVERIFY2(configuration.getPort() == 8080, "Should be 8080");
QVERIFY2(configuration.getDomain() == "www.test.com.xyz", "Should be www.test.com.xyz");
QVERIFY2(configuration.getPort() == 200, "Should be 200");
}
|
Update playback extension so that javascript functions return consistent (but not constant) values in an attempt to preserve the functionality but improve compatibility of the extension. | // 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 "config.h"
#include "webkit/extensions/v8/playback_extension.h"
namespace extensions_v8 {
const char* kPlaybackExtensionName = "v8/PlaybackMode";
v8::Extension* PlaybackExtension::Get() {
v8::Extension* extension = new v8::Extension(
kPlaybackExtensionName,
"(function () {"
" var orig_date = Date;"
" Math.random = function() {"
" return 0.5;"
" };"
" Date.__proto__.now = function() {"
" return new orig_date(1204251968254);"
" };"
" Date = function() {"
" return Date.now();"
" };"
"})()");
return extension;
}
} // namespace extensions_v8
| // 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 "config.h"
#include "webkit/extensions/v8/playback_extension.h"
namespace extensions_v8 {
const char* kPlaybackExtensionName = "v8/PlaybackMode";
v8::Extension* PlaybackExtension::Get() {
v8::Extension* extension = new v8::Extension(
kPlaybackExtensionName,
"(function () {"
" var orig_date = Date;"
" var x = 0;"
" var time_seed = 1204251968254;"
" Math.random = function() {"
" x += .1;"
" return (x % 1);"
" };"
" Date.__proto__.now = function() {"
" time_seed += 50;"
" return new orig_date(time_seed);"
" };"
" Date = function() {"
" return Date.now();"
" };"
"})()");
return extension;
}
} // namespace extensions_v8
|
Fix broadcast_array test to use new fvar ctor | #include <gtest/gtest.h>
#include <stan/math/fwd/core/fvar.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/prim/scal/meta/broadcast_array.hpp>
TEST(foo, bar) {
using stan::math::detail::broadcast_array;
using stan::math::fvar;
using stan::math::var;
fvar<var> fv(0.0);
broadcast_array<fvar<var> > ba(fv);
EXPECT_EQ(0.0, ba[0].val_.vi_->val_);
EXPECT_EQ(0.0, ba[2].val_.vi_->val_);
}
| #include <gtest/gtest.h>
#include <stan/math/fwd/core/fvar.hpp>
#include <stan/math/rev/core/var.hpp>
#include <stan/math/prim/scal/meta/broadcast_array.hpp>
TEST(foo, bar) {
using stan::math::detail::broadcast_array;
using stan::math::fvar;
using stan::math::var;
fvar<var> fv(1.0, 2.1);
broadcast_array<fvar<var> > ba(fv);
EXPECT_EQ(1.0, ba[0].val_.vi_->val_);
EXPECT_EQ(1.0, ba[2].val_.vi_->val_);
}
|
Prepare for flag to allow writing. | #include <cstdint>
#include <Magick++/Blob.h>
#include <Magick++/Image.h>
#include "utils.cc"
#define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name)
#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#ifndef FUZZ_ENCODER
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER)
#endif
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
const Magick::Blob blob(Data, Size);
Magick::Image image;
image.magick(FUZZ_ENCODER);
image.fileName(std::string(FUZZ_ENCODER) + ":");
try {
image.read(blob);
}
catch (Magick::Exception &e) {
return 0;
}
Magick::Blob outBlob;
try {
image.write(&outBlob, FUZZ_ENCODER);
}
catch (Magick::Exception &e) {
}
return 0;
}
| #include <cstdint>
#include <Magick++/Blob.h>
#include <Magick++/Image.h>
#include "utils.cc"
#define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name)
#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#ifndef FUZZ_ENCODER
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER)
#endif
#define FUZZ_IMAGEMAGICK_ENCODER_WRITE 1
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
const Magick::Blob blob(Data, Size);
Magick::Image image;
image.magick(FUZZ_ENCODER);
image.fileName(std::string(FUZZ_ENCODER) + ":");
try {
image.read(blob);
}
catch (Magick::Exception &e) {
return 0;
}
#if FUZZ_IMAGEMAGICK_ENCODER_WRITE
Magick::Blob outBlob;
try {
image.write(&outBlob, FUZZ_ENCODER);
}
catch (Magick::Exception &e) {
}
#endif
return 0;
}
|
Remove erroneous extern C from service name | // This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <service>
extern "C" const char* service_name__ = SERVICE_NAME;
extern "C" const char* service_binary_name__ = SERVICE;
| // This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <service>
const char* service_name__ = SERVICE_NAME;
const char* service_binary_name__ = SERVICE;
|
Create the visitor for includes | //=======================================================================
// 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 "DependenciesResolver.hpp"
#include "ast/SourceFile.hpp"
#include "VisitorUtils.hpp"
#include "ASTVisitor.hpp"
using namespace eddic;
DependenciesResolver::DependenciesResolver(SpiritParser& p) : parser(p) {}
void DependenciesResolver::resolve(ast::SourceFile& program) const {
//TODO
}
| //=======================================================================
// 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 "DependenciesResolver.hpp"
#include "ast/SourceFile.hpp"
#include "VisitorUtils.hpp"
#include "ASTVisitor.hpp"
using namespace eddic;
DependenciesResolver::DependenciesResolver(SpiritParser& p) : parser(p) {}
class DependencyVisitor : public boost::static_visitor<> {
private:
SpiritParser& parser;
public:
DependencyVisitor(SpiritParser& p) : parser(p) {}
AUTO_RECURSE_PROGRAM()
void operator()(ast::StandardImport& import){
//TODO
}
void operator()(ast::Import& import){
//TODO
}
template<typename T>
void operator()(T&){
//Nothing to include there
}
};
void DependenciesResolver::resolve(ast::SourceFile& program) const {
DependencyVisitor visitor(parser);
visitor(program);
}
|
Add code to include entities and change target to entity | // This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Tasks/SimpleTasks/AddEnchantmentTask.hpp>
namespace RosettaStone::SimpleTasks
{
AddEnchantmentTask::AddEnchantmentTask(std::string&& cardID,
EntityType entityType)
: ITask(entityType), m_cardID(cardID)
{
// Do nothing
}
TaskID AddEnchantmentTask::GetTaskID() const
{
return TaskID::ADD_ENCHANTMENT;
}
TaskStatus AddEnchantmentTask::Impl(Player&)
{
Card enchantmentCard = Cards::FindCardByID(m_cardID);
if (enchantmentCard.id.empty())
{
return TaskStatus::STOP;
}
Power power = Cards::FindCardByID(m_cardID).power;
if (power.GetEnchant().has_value())
{
power.GetEnchant().value().ActivateTo(
dynamic_cast<Character*>(m_target));
}
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::SimpleTasks
| // This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Cards/Cards.hpp>
#include <Rosetta/Tasks/SimpleTasks/AddEnchantmentTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>
namespace RosettaStone::SimpleTasks
{
AddEnchantmentTask::AddEnchantmentTask(std::string&& cardID,
EntityType entityType)
: ITask(entityType), m_cardID(cardID)
{
// Do nothing
}
TaskID AddEnchantmentTask::GetTaskID() const
{
return TaskID::ADD_ENCHANTMENT;
}
TaskStatus AddEnchantmentTask::Impl(Player& player)
{
Card enchantmentCard = Cards::FindCardByID(m_cardID);
if (enchantmentCard.id.empty())
{
return TaskStatus::STOP;
}
Power power = Cards::FindCardByID(m_cardID).power;
if (power.GetEnchant().has_value())
{
auto entities =
IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
for (auto& entity : entities)
{
power.GetEnchant().value().ActivateTo(
dynamic_cast<Character*>(entity));
}
}
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::SimpleTasks
|
Watermark nows points to eegeo.com. Buddy: Ian H | // Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "WatermarkDataFactory.h"
namespace ExampleApp
{
namespace Watermark
{
namespace View
{
WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
const std::string& googleAnalyticsReferrerToken)
: m_appName(appName)
, m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
{
}
WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
const std::string& popupTitle,
const std::string& popupBody,
const std::string& webUrl,
const bool shouldShowShadow)
{
return WatermarkData(imageAssetUrl,
popupTitle,
popupBody,
webUrl,
shouldShowShadow);
}
WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
{
std::string imageAssetName = "eegeo_logo";
std::string popupTitle = "Maps by eeGeo";
std::string popupBody = "The " + m_appName + " app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
std::string webUrl = "http://eegeo.com/findoutmore?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";
return Create(imageAssetName,
popupTitle,
popupBody,
webUrl);
}
}
}
} | // Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "WatermarkDataFactory.h"
namespace ExampleApp
{
namespace Watermark
{
namespace View
{
WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
const std::string& googleAnalyticsReferrerToken)
: m_appName(appName)
, m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
{
}
WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
const std::string& popupTitle,
const std::string& popupBody,
const std::string& webUrl,
const bool shouldShowShadow)
{
return WatermarkData(imageAssetUrl,
popupTitle,
popupBody,
webUrl,
shouldShowShadow);
}
WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
{
std::string imageAssetName = "eegeo_logo";
std::string popupTitle = "Maps by eeGeo";
std::string popupBody = "The " + m_appName + " app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";
return Create(imageAssetName,
popupTitle,
popupBody,
webUrl);
}
}
}
} |
Add option to write created key to a JSON file for use in bts_xt_client. | #include <bts/blockchain/address.hpp>
#include <fc/crypto/elliptic.hpp>
#include <iostream>
int main( int argc, char** argv )
{
if( argc == 1 )
{
auto key = fc::ecc::private_key::generate();
std::cout << "private key: "
<< std::string( key.get_secret() ) <<"\n";
std::cout << "bts address: "
<< std::string( bts::blockchain::address( key.get_public_key() ) ) <<"\n";
return 0;
}
}
| #include <bts/blockchain/address.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/filesystem.hpp>
#include <iostream>
int main( int argc, char** argv )
{
if( argc == 1 )
{
auto key = fc::ecc::private_key::generate();
std::cout << "private key: "
<< std::string( key.get_secret() ) <<"\n";
std::cout << "bts address: "
<< std::string( bts::blockchain::address( key.get_public_key() ) ) <<"\n";
return 0;
}
else if (argc == 2)
{
std::cout << "writing new private key to JSON file " << argv[1] << "\n";
fc::ecc::private_key key(fc::ecc::private_key::generate());
fc::json::save_to_file(key, fc::path(argv[1]));
std::cout << "bts address: "
<< std::string(bts::blockchain::address(key.get_public_key())) << "\n";
return 0;
}
}
|
Include std::exception into the namespace | #include <string>
#include <ccspec/expectation/unexpected_throw.h>
namespace ccspec {
namespace expectation {
using std::string;
UnexpectedThrow::UnexpectedThrow(const std::exception& cause)
: cause_(cause) {}
string UnexpectedThrow::toString() {
return string("Unexpected exception: ") + cause_.what();
}
} // namespace expectation
} // namespace ccspec
| #include <string>
#include <ccspec/expectation/unexpected_throw.h>
namespace ccspec {
namespace expectation {
using std::exception;
using std::string;
UnexpectedThrow::UnexpectedThrow(const exception& cause)
: cause_(cause) {}
string UnexpectedThrow::toString() {
return string("Unexpected exception: ") + cause_.what();
}
} // namespace expectation
} // namespace ccspec
|
Fix failure of VPsilane_test when debug_verbose=y | /*
* Copyright 2002 California Institute of Technology
*/
#include "cantera/IdealGasMix.h"
#include "cantera/equilibrium.h"
#include "cantera/thermo/IdealSolnGasVPSS.h"
#include "cantera/thermo/ThermoFactory.h"
using namespace std;
using namespace Cantera;
int main(int argc, char** argv)
{
#ifdef _MSC_VER
_set_output_format(_TWO_DIGIT_EXPONENT);
#endif
try {
Cantera::IdealSolnGasVPSS gg("silane.xml", "silane");
ThermoPhase* g = ≫
//ThermoPhase *g = newPhase("silane.xml", "silane");
cout.precision(4);
g->setState_TPX(1500.0, 100.0, "SIH4:0.01, H2:0.99");
//g.setState_TPX(1500.0, 1.0132E5, "SIH4:0.01, H2:0.99");
Cantera::ChemEquil_print_lvl = 40;
equilibrate(*g, "TP");
std::string r = g->report(true);
cout << r;
cout << endl;
return 0;
} catch (CanteraError& err) {
std::cerr << err.what() << std::endl;
cerr << "program terminating." << endl;
return -1;
}
}
| /*
* Copyright 2002 California Institute of Technology
*/
#include "cantera/IdealGasMix.h"
#include "cantera/equilibrium.h"
#include "cantera/thermo/IdealSolnGasVPSS.h"
#include "cantera/thermo/ThermoFactory.h"
using namespace std;
using namespace Cantera;
int main(int argc, char** argv)
{
#ifdef _MSC_VER
_set_output_format(_TWO_DIGIT_EXPONENT);
#endif
try {
Cantera::IdealSolnGasVPSS gg("silane.xml", "silane");
ThermoPhase* g = ≫
//ThermoPhase *g = newPhase("silane.xml", "silane");
cout.precision(4);
g->setState_TPX(1500.0, 100.0, "SIH4:0.01, H2:0.99");
//g.setState_TPX(1500.0, 1.0132E5, "SIH4:0.01, H2:0.99");
equilibrate(*g, "TP");
std::string r = g->report(true);
cout << r;
cout << endl;
return 0;
} catch (CanteraError& err) {
std::cerr << err.what() << std::endl;
cerr << "program terminating." << endl;
return -1;
}
}
|
Set the transparent region appropriately | #include <qpiekey.h>
#include <QSizePolicy>
#include <QPainter>
#include <QPaintEvent>
QPieKey::QPieKey(QWidget *parent) : QWidget(parent)
{
bitmap = new QBitmap(40,40);
QPainter painter(bitmap);
bitmap->clear();
painter.drawEllipse(0, 0, 40, 40);
setFixedSize(40, 40);
setMask(*bitmap);
}
QPieKey::~QPieKey()
{
}
void QPieKey::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setBrush(QColor(128, 128, 128));
painter.drawRect(event->rect());
}
| #include <qpiekey.h>
#include <QSizePolicy>
#include <QPainter>
#include <QPaintEvent>
#define SIZE 60
QPieKey::QPieKey(QWidget *parent) : QWidget(parent)
{
bitmap = new QBitmap(SIZE*2,SIZE*2);
QPainter painter(bitmap);
setFixedSize(SIZE*2, SIZE*2);
bitmap->clear();
painter.setBrush(Qt::color1);
painter.drawEllipse(1, 1, SIZE*2-2, SIZE*2-2);
painter.setBrush(Qt::color0);
painter.drawEllipse(SIZE/2, SIZE/2, SIZE, SIZE);
setMask(*bitmap);
hide();
}
QPieKey::~QPieKey()
{
}
void QPieKey::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setBrush(QColor(128, 128, 128));
painter.drawRect(event->rect());
}
|
Write output to output file | #include <cstring>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char* argv[]) {
// Print help
if (argc == 1 || strcmp(argv[0], "--help") == 0) {
cout << "GLSLPreprocessor is a simple preprocessor for GLSL files." << endl
<< "Usage:" << endl
<< "GLSLPreprocessor input output" << endl;
return 0;
}
// Get input and output names.
string inputName = argv[1];
string outputName;
if (argc > 2)
outputName = argv[2];
else
outputName = inputName;
return 0;
}
| #include <cstring>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, const char* argv[]) {
// Print help
if (argc == 1 || strcmp(argv[0], "--help") == 0) {
cout << "GLSLPreprocessor is a simple preprocessor for GLSL files." << endl
<< "Usage:" << endl
<< "GLSLPreprocessor input output" << endl;
return 0;
}
// Get input and output names.
string inputName = argv[1];
string outputName;
if (argc > 2)
outputName = argv[2];
else
outputName = inputName;
// TODO: Process file.
string output = "";
// Write output file.
ofstream outFile(outputName.c_str());
outFile << output;
outFile.close();
return 0;
}
|
Add unittests for message type hash | #include "gtest/gtest.h"
#include "paxos/messages.hpp"
TEST(MessageTest, testMessageResponseUpdatesSenderAndReceiver)
{
Replica from("from_hostname");
Replica to("to_hostname");
Decree the_decree(from, 1, "", DecreeType::UserDecree);
Message m(the_decree, from, to, MessageType::RequestMessage);
Message response = Response(m, MessageType::PromiseMessage);
ASSERT_EQ(response.from.hostname, m.to.hostname);
ASSERT_EQ(response.to.hostname, m.from.hostname);
ASSERT_EQ(response.type, MessageType::PromiseMessage);
}
| #include "gtest/gtest.h"
#include "paxos/messages.hpp"
TEST(MessageTest, testMessageResponseUpdatesSenderAndReceiver)
{
Replica from("from_hostname");
Replica to("to_hostname");
Decree the_decree(from, 1, "", DecreeType::UserDecree);
Message m(the_decree, from, to, MessageType::RequestMessage);
Message response = Response(m, MessageType::PromiseMessage);
ASSERT_EQ(response.from.hostname, m.to.hostname);
ASSERT_EQ(response.to.hostname, m.from.hostname);
ASSERT_EQ(response.type, MessageType::PromiseMessage);
}
TEST(MessageTest, testMessageTypeHashFunction)
{
ASSERT_EQ(0, MessageTypeHash()(MessageType::RequestMessage));
ASSERT_EQ(1, MessageTypeHash()(MessageType::RetryRequestMessage));
ASSERT_EQ(2, MessageTypeHash()(MessageType::PrepareMessage));
ASSERT_EQ(3, MessageTypeHash()(MessageType::RetryPrepareMessage));
ASSERT_EQ(4, MessageTypeHash()(MessageType::PromiseMessage));
ASSERT_EQ(5, MessageTypeHash()(MessageType::NackMessage));
ASSERT_EQ(6, MessageTypeHash()(MessageType::AcceptMessage));
ASSERT_EQ(7, MessageTypeHash()(MessageType::AcceptedMessage));
ASSERT_EQ(8, MessageTypeHash()(MessageType::UpdateMessage));
ASSERT_EQ(9, MessageTypeHash()(MessageType::UpdatedMessage));
}
|
Improve iostream with stdio unsync: real 0m1.029s -> 0m1.020s user 0m0.538s -> 0m0.569s sys 0m0.311s -> 0m0.262s refs: 148,846,05 -> 53,570,098 | #include <iostream>
using namespace std;
#define out if(1)cout
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
#define abs(a) (((a)<0)?(-(a)):(a))
static const int MAXN = 10000001;
typedef long long int i64;
static i64 ar[MAXN];
int main()
{
int N, M;
cin >> N >> M;
for (int i = 0; i < M; i++) {
int a, b, k;
cin >> a >> b >> k;
ar[a] += k;
ar[b+1] -= k;
}
i64 cur = 0;
i64 max = 0;
for (int i = 1; i <= N; i++) {
cur += ar[i];
if (cur > max) max = cur;
}
cout << max << endl;
return 0;
}
| #include <iostream>
using namespace std;
#define out if(1)cout
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
#define abs(a) (((a)<0)?(-(a)):(a))
static const int MAXN = 10000001;
typedef long long int i64;
static i64 ar[MAXN];
int main()
{
ios::sync_with_stdio(false);
int N, M;
cin >> N >> M;
for (int i = 0; i < M; i++) {
int a, b, k;
cin >> a >> b >> k;
ar[a] += k;
ar[b+1] -= k;
}
i64 cur = 0;
i64 max = 0;
for (int i = 1; i <= N; i++) {
cur += ar[i];
if (cur > max) max = cur;
}
cout << max << endl;
return 0;
}
|
Use s.c_str() in log messages | /**
* Copyright © 2017 IBM Corporation
*
* 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 <phosphor-logging/log.hpp>
#include "errors.hpp"
namespace phosphor
{
namespace inventory
{
namespace manager
{
void InterfaceError::log() const
{
logging::log<logging::level::ERR>(
what(), phosphor::logging::entry("INTERFACE=%s", interface));
}
} // namespace manager
} // namespace inventory
} // namespace phosphor
// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| /**
* Copyright © 2017 IBM Corporation
*
* 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 <phosphor-logging/log.hpp>
#include "errors.hpp"
namespace phosphor
{
namespace inventory
{
namespace manager
{
void InterfaceError::log() const
{
logging::log<logging::level::ERR>(
what(), phosphor::logging::entry("INTERFACE=%s", interface.c_str()));
}
} // namespace manager
} // namespace inventory
} // namespace phosphor
// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
Add LOG4CPP_EXPORT for win32 dll | /*
* TimeStamp.cpp
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include <log4cpp/TimeStamp.hh>
#include <cstring>
#ifdef LOG4CPP_HAVE_GETTIMEOFDAY
#include <sys/time.h>
#else
#ifdef LOG4CPP_HAVE_FTIME
#include <sys/timeb.h>
#else
#include <time.h>
#endif
#endif
namespace log4cpp {
TimeStamp TimeStamp::_startStamp;
TimeStamp::TimeStamp() {
#ifdef LOG4CPP_HAVE_GETTIMEOFDAY
struct timeval tv;
::gettimeofday(&tv, NULL);
_seconds = tv.tv_sec;
_microSeconds = tv.tv_usec;
#else
#ifdef LOG4CPP_HAVE_FTIME
struct timeb tb;
::ftime(&tb);
_seconds = tb.time;
_microSeconds = 1000 * tb.millitm;
#else
_seconds = ::time(NULL);
_microSeconds = 0;
#endif
#endif
}
TimeStamp::TimeStamp(unsigned int seconds, unsigned int microSeconds) :
_seconds(seconds),
_microSeconds(microSeconds) {
}
}
| /*
* TimeStamp.cpp
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include <log4cpp/TimeStamp.hh>
#include <cstring>
#ifdef LOG4CPP_HAVE_GETTIMEOFDAY
#include <sys/time.h>
#else
#ifdef LOG4CPP_HAVE_FTIME
#include <sys/timeb.h>
#else
#include <time.h>
#endif
#endif
namespace log4cpp {
LOG4CPP_EXPORT TimeStamp TimeStamp::_startStamp;
TimeStamp::TimeStamp() {
#ifdef LOG4CPP_HAVE_GETTIMEOFDAY
struct timeval tv;
::gettimeofday(&tv, NULL);
_seconds = tv.tv_sec;
_microSeconds = tv.tv_usec;
#else
#ifdef LOG4CPP_HAVE_FTIME
struct timeb tb;
::ftime(&tb);
_seconds = tb.time;
_microSeconds = 1000 * tb.millitm;
#else
_seconds = ::time(NULL);
_microSeconds = 0;
#endif
#endif
}
TimeStamp::TimeStamp(unsigned int seconds, unsigned int microSeconds) :
_seconds(seconds),
_microSeconds(microSeconds) {
}
}
|
Add logging to show c++ environment. | #include "Foo.hh"
#include <string>
#include <iostream>
#define EXPORT __attribute__((visibility("default")))
EXPORT
int Foo::PrintFoo()
{
std::cout << "This is in a C++ in a dynamically linked framework!" << std::endl;
return 1;
}
| #include "Foo.hh"
#include <string>
#include <iostream>
#define EXPORT __attribute__((visibility("default")))
EXPORT
int Foo::PrintFoo()
{
#if __cplusplus
std::cout << "C++ environment detected." << std::endl;
#endif
std::cout << "Foo::PrintFoo() called." << std::endl;
return 1;
}
|
Disable Nagle on TCP socket: too slow for interactive | #include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>
namespace cucumber {
namespace internal {
SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
protocolHandler(protocolHandler),
ios(),
acceptor(ios) {
}
void SocketServer::listen(const port_type port) {
tcp::endpoint endpoint(tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.bind(endpoint);
acceptor.listen(1);
}
void SocketServer::acceptOnce() {
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
processStream(stream);
}
void SocketServer::processStream(tcp::iostream &stream) {
std::string request;
while (getline(stream, request)) {
stream << protocolHandler->handle(request) << std::endl << std::flush;
}
}
}
}
| #include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>
namespace cucumber {
namespace internal {
SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
protocolHandler(protocolHandler),
ios(),
acceptor(ios) {
}
void SocketServer::listen(const port_type port) {
tcp::endpoint endpoint(tcp::v4(), port);
acceptor.open(endpoint.protocol());
acceptor.set_option(tcp::acceptor::reuse_address(true));
acceptor.set_option(tcp::no_delay(true));
acceptor.bind(endpoint);
acceptor.listen(1);
}
void SocketServer::acceptOnce() {
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
processStream(stream);
}
void SocketServer::processStream(tcp::iostream &stream) {
std::string request;
while (getline(stream, request)) {
stream << protocolHandler->handle(request) << std::endl << std::flush;
}
}
}
}
|
Add a potential buffer overrun test. | FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "catcat", true, "catcat", "cat");
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "dogdog", true, "dogdog", "dog");
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "snek", true, "", "");
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "catdog", false);
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "dogcat", false);
| FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "catcat", true, "catcat", "cat");
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "dogdog", true, "dogdog", "dog");
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "snek", true, "", "");
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "catdog", false);
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "dogcat", false);
FIXED_TEST("(cat|dog|)\\1", ANCHOR_START, "cat", false);
|
Allow dataflow-in to accept multiple values. | #include "writer/verilog/dataflow_in.h"
#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "writer/module_template.h"
#include "writer/verilog/insn_writer.h"
#include "writer/verilog/module.h"
#include "writer/verilog/shared_reg.h"
namespace iroha {
namespace writer {
namespace verilog {
DataFlowIn::DataFlowIn(const IResource &res, const Table &table)
: Resource(res, table) {
}
void DataFlowIn::BuildResource() {
}
void DataFlowIn::BuildInsn(IInsn *insn, State *st) {
IResource *res = insn->GetResource();
IResource *parent = res->GetParentResource();
if (insn->outputs_.size() == 1 && parent != nullptr &&
resource::IsSharedReg(*(parent->GetClass()))) {
ostream &ws = tmpl_->GetStream(kInsnWireValueSection);
ws << " assign " << InsnWriter::InsnOutputWireName(*insn, 0)
<< " = " << SharedReg::RegName(*parent) << ";\n";
}
}
} // namespace verilog
} // namespace writer
} // namespace iroha
| #include "writer/verilog/dataflow_in.h"
#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "writer/module_template.h"
#include "writer/verilog/insn_writer.h"
#include "writer/verilog/module.h"
#include "writer/verilog/shared_reg.h"
namespace iroha {
namespace writer {
namespace verilog {
DataFlowIn::DataFlowIn(const IResource &res, const Table &table)
: Resource(res, table) {
}
void DataFlowIn::BuildResource() {
}
void DataFlowIn::BuildInsn(IInsn *insn, State *st) {
IResource *res = insn->GetResource();
IResource *parent = res->GetParentResource();
if (parent != nullptr &&
resource::IsSharedReg(*(parent->GetClass()))) {
int s = 0;
for (int i = 0; i < insn->outputs_.size(); ++i) {
ostream &ws = tmpl_->GetStream(kInsnWireValueSection);
ws << " assign " << InsnWriter::InsnOutputWireName(*insn, i)
<< " = " << SharedReg::RegName(*parent);
if (insn->outputs_.size() > 1) {
IRegister *reg = insn->outputs_[i];
int w = reg->value_type_.GetWidth();
ws << "[" << (s + w - 1) << ":" << s << "]";
s += w;
}
ws << ";\n";
}
}
}
} // namespace verilog
} // namespace writer
} // namespace iroha
|
Add to about dialog info about current version | #include "AboutDarkThemePluginDialog.h"
#include "ui_AboutDarkThemePluginDialog.h"
using namespace libqdark;
AboutDarkThemePluginDialog::AboutDarkThemePluginDialog(QWidget* parent)
: QDialog(parent)
, ui(new Ui::AboutDarkThemePluginDialog)
{
ui->setupUi(this);
//ui->nameLabel->setText(m_ui->nameLabel->text() + " " + KEEPASSX_VERSION);
auto nameLabelFont = ui->nameLabel->font();
nameLabelFont.setBold(true);
nameLabelFont.setPointSize(nameLabelFont.pointSize() + 4);
ui->nameLabel->setFont(nameLabelFont);
}
AboutDarkThemePluginDialog::~AboutDarkThemePluginDialog() = default;
| #include "AboutDarkThemePluginDialog.h"
#include "ui_AboutDarkThemePluginDialog.h"
#include <string>
using namespace libqdark;
AboutDarkThemePluginDialog::AboutDarkThemePluginDialog(QWidget* parent)
: QDialog(parent)
, ui(new Ui::AboutDarkThemePluginDialog)
{
ui->setupUi(this);
ui->nameLabel->setText(ui->nameLabel->text() + " " + LIBQDARK_VERSION);
auto nameLabelFont = ui->nameLabel->font();
nameLabelFont.setBold(true);
nameLabelFont.setPointSize(nameLabelFont.pointSize() + 4);
ui->nameLabel->setFont(nameLabelFont);
QString commitHash;
if (!QString(GIT_VERSION).isEmpty()) {
commitHash = GIT_VERSION;
}
if (!commitHash.isEmpty()) {
QString labelText = tr("Revision").append(": ").append(commitHash);
ui->label_git->setText(labelText);
}
auto libs = QString("%1\n- Qt %2")
.arg(ui->label_libs->text())
.arg(QString::fromLocal8Bit(qVersion()));
ui->label_libs->setText(libs);
}
AboutDarkThemePluginDialog::~AboutDarkThemePluginDialog() = default;
|
Fix arch_time_now wrong function name | #include <os>
#include "../x86_pc/idt.hpp"
void __arch_poweroff()
{
asm("cli; hlt;");
__builtin_unreachable();
}
void __platform_init()
{
// setup CPU exception handlers
x86::idt_initialize_for_cpu(0);
}
// not supported!
int64_t __arch_now() { return 0; }
void __arch_reboot(){}
void __arch_enable_legacy_irq(unsigned char){}
void __arch_disable_legacy_irq(unsigned char){}
void SMP::global_lock() noexcept {}
void SMP::global_unlock() noexcept {}
int SMP::cpu_id() noexcept { return 0; }
int SMP::cpu_count() noexcept { return 1; }
// Support for the boot_logger plugin.
__attribute__((weak))
bool os_enable_boot_logging = false;
| #include <os>
#include "../x86_pc/idt.hpp"
void __arch_poweroff()
{
asm("cli; hlt;");
__builtin_unreachable();
}
void __platform_init()
{
// setup CPU exception handlers
x86::idt_initialize_for_cpu(0);
}
// not supported!
int64_t __arch_time_now() noexcept {
return 0;
}
void __arch_reboot(){}
void __arch_enable_legacy_irq(unsigned char){}
void __arch_disable_legacy_irq(unsigned char){}
void SMP::global_lock() noexcept {}
void SMP::global_unlock() noexcept {}
int SMP::cpu_id() noexcept { return 0; }
int SMP::cpu_count() noexcept { return 1; }
// Support for the boot_logger plugin.
__attribute__((weak))
bool os_enable_boot_logging = false;
|
Improve error message about primitive failures | #include "primitives.hpp"
#include "event.hpp"
#include "gen/includes.hpp"
namespace rubinius {
bool Primitives::unknown_primitive(STATE, VMExecutable* exec, Task* task, Message& msg) {
std::cout << "\n";
state->print_backtrace();
std::cout << "Called unbound/invalid primitive: " << *msg.name->to_str(state) <<"\n";
abort();
}
#include "gen/primitives_glue.gen.cpp"
}
| #include "primitives.hpp"
#include "event.hpp"
#include "gen/includes.hpp"
namespace rubinius {
bool Primitives::unknown_primitive(STATE, VMExecutable* exec, Task* task, Message& msg) {
std::cout << "\n";
state->print_backtrace();
std::cout << "Called unbound or invalid primitive from: " << *msg.name->to_str(state) <<"\n";
abort();
}
#include "gen/primitives_glue.gen.cpp"
}
|
Fix minor coverity unitialized ptr warning |
#include <Python.h>
#include "module_lock.h"
#include "classad/classad.h"
using namespace condor;
pthread_mutex_t ModuleLock::m_mutex = PTHREAD_MUTEX_INITIALIZER;
ModuleLock::ModuleLock()
: m_release_gil(!classad::ClassAdGetExpressionCaching()),
m_owned(false)
{
acquire();
}
void
ModuleLock::acquire()
{
if (m_release_gil && !m_owned)
{
m_save = PyEval_SaveThread();
pthread_mutex_lock(&m_mutex);
m_owned = true;
}
}
ModuleLock::~ModuleLock()
{
release();
}
void
ModuleLock::release()
{
if (m_release_gil && m_owned)
{
pthread_mutex_unlock(&m_mutex);
PyEval_RestoreThread(m_save);
}
}
|
#include <Python.h>
#include "module_lock.h"
#include "classad/classad.h"
using namespace condor;
pthread_mutex_t ModuleLock::m_mutex = PTHREAD_MUTEX_INITIALIZER;
ModuleLock::ModuleLock()
: m_release_gil(!classad::ClassAdGetExpressionCaching()),
m_owned(false), m_save(0)
{
acquire();
}
void
ModuleLock::acquire()
{
if (m_release_gil && !m_owned)
{
m_save = PyEval_SaveThread();
pthread_mutex_lock(&m_mutex);
m_owned = true;
}
}
ModuleLock::~ModuleLock()
{
release();
}
void
ModuleLock::release()
{
if (m_release_gil && m_owned)
{
pthread_mutex_unlock(&m_mutex);
PyEval_RestoreThread(m_save);
}
}
|
Fix test to not be too strict with output order. | // Ensure that we have a quiet startup when we don't have the XRay
// instrumentation sleds.
//
// RUN: %clangxx -std=c++11 %s -o %t %xraylib
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1" %run %t 2>&1 | \
// RUN: FileCheck %s --check-prefix NOISY
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=0" %run %t 2>&1 | \
// RUN: FileCheck %s --check-prefix QUIET
// RUN: XRAY_OPTIONS="" %run %t 2>&1 | FileCheck %s --check-prefix DEFAULT
//
// FIXME: Understand how to make this work on other platforms
// REQUIRES: built-in-llvm-tree
// REQUIRES: x86_64-linux
#include <iostream>
using namespace std;
int main(int, char**) {
// NOISY: {{.*}}XRay instrumentation map missing. Not initializing XRay.
// QUIET-NOT: {{.*}}XRay instrumentation map missing. Not initializing XRay.
// DEFAULT-NOT: {{.*}}XRay instrumentation map missing. Not initializing XRay.
cout << "Hello, XRay!" << endl;
// NOISY-NEXT: Hello, XRay!
// QUIET: Hello, XRay!
// DEFAULT: Hello, XRay!
}
| // Ensure that we have a quiet startup when we don't have the XRay
// instrumentation sleds.
//
// RUN: %clangxx -std=c++11 %s -o %t %xraylib
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1" %run %t 2>&1 | \
// RUN: FileCheck %s --check-prefix NOISY
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=0" %run %t 2>&1 | \
// RUN: FileCheck %s --check-prefix QUIET
// RUN: XRAY_OPTIONS="" %run %t 2>&1 | FileCheck %s --check-prefix DEFAULT
//
// FIXME: Understand how to make this work on other platforms
// REQUIRES: built-in-llvm-tree
// REQUIRES: x86_64-linux
#include <iostream>
using namespace std;
int main(int, char**) {
// NOISY: {{.*}}XRay instrumentation map missing. Not initializing XRay.
// QUIET-NOT: {{.*}}XRay instrumentation map missing. Not initializing XRay.
// DEFAULT-NOT: {{.*}}XRay instrumentation map missing. Not initializing XRay.
cout << "Hello, XRay!" << endl;
// NOISY: Hello, XRay!
// QUIET: Hello, XRay!
// DEFAULT: Hello, XRay!
}
|
Mark parameters of weak main as unused | #include <Pith/Config.hpp>
#include <Pith/Version.hpp>
#include <iostream>
extern "C" int pith_main(int argc, char** argv) {
std::cout << "Pith version " << Pith::Version::STRING << " " << Pith::Version::COMMIT
<< std::endl;
return 0;
}
/// When no main is defined, pith defines a main that prints version information.
// int main (int argc, char** argv) __attribute__((weak alias("pith_main")));
#pragma weak main = pith_main
| #include <Pith/Config.hpp>
#include <Pith/Version.hpp>
#include <iostream>
extern "C" auto pith_main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) -> int {
std::cout << "Pith version " << Pith::Version::STRING << " " << Pith::Version::COMMIT
<< std::endl;
return 0;
}
/// When no main is defined, pith defines a main that prints version information.
// int main (int argc, char** argv) __attribute__((weak alias("pith_main")));
#pragma weak main = pith_main
|
Add a trivial write only GLSL test. | #include <Halide.h>
#include <stdio.h>
#include <stdlib.h>
using namespace Halide;
int main() {
// This test must be run with an OpenGL target
const Target &target = get_jit_target_from_environment();
if (!target.has_feature(Target::OpenGL)) {
fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
return 1;
}
Func f;
Var x, y, c;
f(x, y, c) = cast<uint8_t>(select(c == 0, 10*x + y,
c == 1, 127, 12));
Image<uint8_t> out(10, 10, 3);
f.bound(c, 0, 3).glsl(x, y, c);
f.realize(out);
out.copy_to_host();
for (int y=0; y<out.height(); y++) {
for (int x=0; x<out.width(); x++) {
if (!(out(x, y, 0) == 10*x+y && out(x, y, 1) == 127 && out(x, y, 2) == 12)) {
fprintf(stderr, "Incorrect pixel (%d, %d, %d) at x=%d y=%d.\n",
out(x, y, 0), out(x, y, 1), out(x, y, 2),
x, y);
return 1;
}
}
}
printf("Success!\n");
return 0;
}
| #include <Halide.h>
#include <stdio.h>
#include <stdlib.h>
using namespace Halide;
int main() {
// This test must be run with an OpenGL target
const Target &target = get_jit_target_from_environment();
if (!target.has_feature(Target::OpenGL)) {
fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
return 1;
}
Func f;
Var x, y, c;
f(x, y, c) = cast<uint8_t>(42);
Image<uint8_t> out(10, 10, 3);
f.bound(c, 0, 3).glsl(x, y, c);
f.realize(out);
out.copy_to_host();
for (int y=0; y<out.height(); y++) {
for (int x=0; x<out.width(); x++) {
for (int z=0; x<out.channels(); x++) {
if (!(out(x, y, z) == 42)) {
fprintf(stderr, "Incorrect pixel (%d) at x=%d y=%d z=%d.\n",
out(x, y, z), x, y, z);
return 1;
}
}
}
}
printf("Success!\n");
return 0;
}
|
Address a post-commit review comment on r348325. | // RUN: %clang_cc1 -std=c++17 -verify -emit-llvm-only %s
// expected-no-diagnostics
template <class T> void bar(const T &t) { foo(t); }
template <class>
struct HasFriend {
template <class T>
friend void foo(const HasFriend<T> &m) noexcept(false);
};
template <class T>
void foo(const HasFriend<T> &m) noexcept(false) {}
void f() {
HasFriend<int> x;
foo(x);
bar(x);
}
namespace PR39742 {
template<typename>
struct wrapper {
template<typename>
friend void friend_function_template() {}
};
wrapper<bool> x;
wrapper<int> y;
}
| // RUN: %clang_cc1 -std=c++17 -verify -emit-llvm-only %s
// expected-no-diagnostics
template <class T> void bar(const T &t) { foo(t); }
template <class>
struct HasFriend {
template <class T>
friend void foo(const HasFriend<T> &m) noexcept(false);
};
template <class T>
void foo(const HasFriend<T> &m) noexcept(false) {}
void f() {
HasFriend<int> x;
foo(x);
bar(x);
}
namespace PR39742 {
template<typename>
struct wrapper {
template<typename>
friend void friend_function_template() {}
};
wrapper<bool> x;
// FIXME: We should really error here because of the redefinition of
// friend_function_template.
wrapper<int> y;
}
|
Fix the order of parameters in Board class tests | #include "catch.hpp"
#include "../src/Board.h"
TEST_CASE("Board class tests", "[Board]")
{
SECTION("The constructor properly sets width and height of the board")
{
const int desired_width = 11;
const int desired_height = 12;
Board b(desired_width, desired_height);
REQUIRE(desired_width == b.width());
REQUIRE(desired_height == b.height());
}
}
| #include "catch.hpp"
#include "../src/Board.h"
TEST_CASE("Board class tests", "[Board]")
{
SECTION("The constructor properly sets width and height of the board")
{
const int desired_width = 11;
const int desired_height = 12;
Board b(desired_height, desired_width);
REQUIRE(desired_height == b.height());
REQUIRE(desired_width == b.width());
}
}
|
Detach table accessors before attaching to a new table | #include <tightdb/row.hpp>
#include <tightdb/table.hpp>
using namespace std;
using namespace tightdb;
void RowBase::attach(Table* table, size_t row_ndx)
{
if (table) {
table->register_row_accessor(this); // Throws
m_table.reset(table);
m_row_ndx = row_ndx;
}
}
void RowBase::reattach(Table* table, size_t row_ndx)
{
if (m_table.get() != table) {
if (table)
table->register_row_accessor(this); // Throws
if (m_table)
m_table->unregister_row_accessor(this);
m_table.reset(table);
}
m_row_ndx = row_ndx;
}
void RowBase::impl_detach() TIGHTDB_NOEXCEPT
{
if (m_table) {
m_table->unregister_row_accessor(this);
m_table.reset();
}
}
| #include <tightdb/row.hpp>
#include <tightdb/table.hpp>
using namespace std;
using namespace tightdb;
void RowBase::attach(Table* table, size_t row_ndx)
{
if (table) {
table->register_row_accessor(this); // Throws
m_table.reset(table);
m_row_ndx = row_ndx;
}
}
void RowBase::reattach(Table* table, size_t row_ndx)
{
if (m_table.get() != table) {
if (m_table)
m_table->unregister_row_accessor(this);
if (table)
table->register_row_accessor(this); // Throws
m_table.reset(table);
}
m_row_ndx = row_ndx;
}
void RowBase::impl_detach() TIGHTDB_NOEXCEPT
{
if (m_table) {
m_table->unregister_row_accessor(this);
m_table.reset();
}
}
|
Replace a DCHECK with DCHECK_EQ. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/cancellation_flag.h"
#include "base/logging.h"
namespace base {
void CancellationFlag::Set() {
#if !defined(NDEBUG)
DCHECK(set_on_ == PlatformThread::CurrentId());
#endif
base::subtle::Release_Store(&flag_, 1);
}
bool CancellationFlag::IsSet() const {
return base::subtle::Acquire_Load(&flag_) != 0;
}
} // namespace base
| // 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/cancellation_flag.h"
#include "base/logging.h"
namespace base {
void CancellationFlag::Set() {
#if !defined(NDEBUG)
DCHECK_EQ(set_on_, PlatformThread::CurrentId());
#endif
base::subtle::Release_Store(&flag_, 1);
}
bool CancellationFlag::IsSet() const {
return base::subtle::Acquire_Load(&flag_) != 0;
}
} // namespace base
|
Validate userid for IDENTITY command | #include "SerialCommand.h"
#include "anyware_serial.h"
void unrecognized(const char *cmd)
{
printError(F("unrecognized command"), cmd);
}
/*!
RESET [<bool>]
*/
void reset_action()
{
char *debugarg = sCmd.next();
bool debug = false;
if (debugarg) debug = atoi(debugarg);
reset(debug);
}
/*!
IDENTITY <userid>
*/
void identity_action()
{
char *userarg = sCmd.next();
if (!userarg) {
printError(F("protocol error"), F("wrong # of parameters to IDENTITY"));
return;
}
global_userid = getUserIdArg(userarg);
// FIXME: Validity check?
if (global_debug) {
Serial.print(F("DEBUG Identity set, userid="));
Serial.println(global_userid);
}
}
void setupCommonCommands()
{
sCmd.addCommand("RESET", reset_action);
sCmd.addCommand("IDENTITY", identity_action);
sCmd.setDefaultHandler(unrecognized);
}
| #include "SerialCommand.h"
#include "anyware_serial.h"
void unrecognized(const char *cmd)
{
printError(F("unrecognized command"), cmd);
}
/*!
RESET [<bool>]
*/
void reset_action()
{
char *debugarg = sCmd.next();
bool debug = false;
if (debugarg) debug = atoi(debugarg);
reset(debug);
}
/*!
IDENTITY <userid>
*/
void identity_action()
{
char *userarg = sCmd.next();
if (!userarg) {
printError(F("protocol error"), F("wrong # of parameters to IDENTITY"));
return;
}
uint8_t userid = getUserIdArg(userarg);
if (userid > 2) {
printError(F("protocol error"), F("Illegal userid argument"));
return;
}
global_userid = userid;
if (global_debug) {
Serial.print(F("DEBUG Identity set, userid="));
Serial.println(global_userid);
}
}
void setupCommonCommands()
{
sCmd.addCommand("RESET", reset_action);
sCmd.addCommand("IDENTITY", identity_action);
sCmd.setDefaultHandler(unrecognized);
}
|
Add void to fix error | #include "memory.h"
namespace EPITOME
{
template <typename T>
Room<T>::Room() {}
template <typename T>
Room<T>::~Room()
{
Empty();
}
template <typename T>
Room<T>::Room(Room&& other)
{
items = other.items;
other.items.clear();
}
template<typename T>
void Room<T>::Add(T* item)
{
items.push_back(item);
}
template <typename T>
void Room<T>::Empty()
{
for (T* a : items)
{
a->Dispose();
delete a;
}
items.clear();
}
template <typename T>
Disposable<T>::Disposable(T item)
{
this->item = item;
}
template <typename T>
Disposable<T>::Dispose() {}
} | #include "memory.h"
namespace EPITOME
{
template <typename T>
Room<T>::Room() {}
template <typename T>
Room<T>::~Room()
{
Empty();
}
template <typename T>
Room<T>::Room(Room&& other)
{
items = other.items;
other.items.clear();
}
template<typename T>
void Room<T>::Add(T* item)
{
items.push_back(item);
}
template <typename T>
void Room<T>::Empty()
{
for (T* a : items)
{
a->Dispose();
delete a;
}
items.clear();
}
template <typename T>
Disposable<T>::Disposable(T item)
{
this->item = item;
}
template <typename T>
void Disposable<T>::Dispose() {}
} |
Edit subsidy_limit_test to account for BIP42 | #include "core.h"
#include "main.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(main_tests)
BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
uint64_t nSum = 0;
for (int nHeight = 0; nHeight < 7000000; nHeight += 1000) {
uint64_t nSubsidy = GetBlockValue(nHeight, 0);
BOOST_CHECK(nSubsidy <= 50 * COIN);
nSum += nSubsidy * 1000;
BOOST_CHECK(MoneyRange(nSum));
}
BOOST_CHECK(nSum == 2099999997690000ULL);
}
BOOST_AUTO_TEST_SUITE_END()
| #include "core.h"
#include "main.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(main_tests)
BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
uint64_t nSum = 0;
for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {
uint64_t nSubsidy = GetBlockValue(nHeight, 0);
BOOST_CHECK(nSubsidy <= 50 * COIN);
nSum += nSubsidy * 1000;
BOOST_CHECK(MoneyRange(nSum));
}
BOOST_CHECK(nSum == 2099999997690000ULL);
}
BOOST_AUTO_TEST_SUITE_END()
|
Prepare to build desktop_aura/ as part of views only. | // Copyright 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ozone/ui/desktop_aura/desktop_factory_wayland.h"
#include "ozone/ui/desktop_aura/desktop_screen_wayland.h"
#include "ozone/ui/desktop_aura/desktop_window_tree_host_wayland.h"
#include "ozone/wayland/display.h"
namespace views {
DesktopFactoryWayland::DesktopFactoryWayland() : views::DesktopFactoryOzone(),
desktop_screen_(NULL) {
LOG(INFO) << "Ozone: DesktopFactoryWayland";
DesktopFactoryOzone::SetInstance(this);
}
DesktopFactoryWayland::~DesktopFactoryWayland() {
DesktopFactoryOzone::SetInstance(NULL);
delete desktop_screen_;
}
DesktopWindowTreeHost* DesktopFactoryWayland::CreateWindowTreeHost(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura) {
return new DesktopWindowTreeHostWayland(native_widget_delegate,
desktop_native_widget_aura);
}
gfx::Screen* DesktopFactoryWayland::CreateDesktopScreen() {
if (!desktop_screen_) {
desktop_screen_ = new DesktopScreenWayland();
ozonewayland::WaylandDisplay::LookAheadOutputGeometry();
}
return desktop_screen_;
}
} // namespace views
| // Copyright 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ozone/ui/desktop_aura/desktop_factory_wayland.h"
#include "ozone/ui/desktop_aura/desktop_screen_wayland.h"
#include "ozone/ui/desktop_aura/desktop_window_tree_host_wayland.h"
#include "ozone/ui/gfx/ozone_display.h"
namespace views {
DesktopFactoryWayland::DesktopFactoryWayland() : views::DesktopFactoryOzone(),
desktop_screen_(NULL) {
LOG(INFO) << "Ozone: DesktopFactoryWayland";
DesktopFactoryOzone::SetInstance(this);
}
DesktopFactoryWayland::~DesktopFactoryWayland() {
DesktopFactoryOzone::SetInstance(NULL);
delete desktop_screen_;
}
DesktopWindowTreeHost* DesktopFactoryWayland::CreateWindowTreeHost(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura) {
return new DesktopWindowTreeHostWayland(native_widget_delegate,
desktop_native_widget_aura);
}
gfx::Screen* DesktopFactoryWayland::CreateDesktopScreen() {
if (!desktop_screen_) {
desktop_screen_ = new DesktopScreenWayland();
gfx::OzoneDisplay::GetInstance()->LookAheadOutputGeometry();
}
return desktop_screen_;
}
} // namespace views
|
Update abs() to not use float. | //
// Created by Timo on 18.04.2016.
//
#include <cmath>
#include "fixed_point.h"
fixed_point::fixed_point(float x) {
q = x * std::pow(2, 16);
}
fixed_point::operator int() const {
return q / std::pow(2, 16);
}
fixed_point::operator float() const {
return q / std::pow(2, 16);
}
fixed_point abs(fixed_point fixedPoint) {
float temp = (float) fixedPoint;
if (temp >= 0) {
return fixed_point(temp);
} else {
return fixed_point(-temp);
}
}
bool fixed_point::operator==(fixed_point rhs) const {
return q == rhs.q;
}
bool fixed_point::operator!=(fixed_point rhs) const {
return q != rhs.q;
}
bool fixed_point::operator<(fixed_point rhs) const {
return q < rhs.q;
}
bool fixed_point::operator>(fixed_point rhs) const {
return q > rhs.q;
}
bool fixed_point::operator<=(fixed_point rhs) const {
return q <= rhs.q;
}
bool fixed_point::operator>=(fixed_point rhs) const {
return q >= rhs.q;
} | //
// Created by Timo on 18.04.2016.
//
#include <cmath>
#include "fixed_point.h"
fixed_point::fixed_point(float x) {
q = x * std::pow(2, 16);
}
fixed_point::operator int() const {
return q / std::pow(2, 16);
}
fixed_point::operator float() const {
return q / std::pow(2, 16);
}
fixed_point abs(fixed_point fixedPoint) {
if (fixedPoint >= 0) {
return fixedPoint;
} else {
return -fixedPoint;
}
}
bool fixed_point::operator==(fixed_point rhs) const {
return q == rhs.q;
}
bool fixed_point::operator!=(fixed_point rhs) const {
return q != rhs.q;
}
bool fixed_point::operator<(fixed_point rhs) const {
return q < rhs.q;
}
bool fixed_point::operator>(fixed_point rhs) const {
return q > rhs.q;
}
bool fixed_point::operator<=(fixed_point rhs) const {
return q <= rhs.q;
}
bool fixed_point::operator>=(fixed_point rhs) const {
return q >= rhs.q;
} |
Fix for really weird compile time configurations | #include <QtCore/QCoreApplication>
#include "signalwatcher.h"
static SignalWatcher* g_instance = 0;
SignalWatcher::SignalWatcher(void)
: QObject(qApp)
{
}
bool SignalWatcher::watch(int sig)
{
Q_UNUSED(sig)
return false;
}
bool SignalWatcher::unwatch(int sig)
{
Q_UNUSED(sig)
return false;
}
SignalWatcher::~SignalWatcher(void)
{
g_instance = 0;
}
SignalWatcher* SignalWatcher::instance(void)
{
if (!g_instance) {
g_instance = new SignalWatcher();
}
return g_instance;
}
| #include <QtCore/QCoreApplication>
#include "signalwatcher.h"
class SignalWatcherPrivate {}
static SignalWatcher* g_instance = 0;
SignalWatcher::SignalWatcher(void)
: QObject(qApp)
{
}
bool SignalWatcher::watch(int sig)
{
Q_UNUSED(sig)
return false;
}
bool SignalWatcher::unwatch(int sig)
{
Q_UNUSED(sig)
return false;
}
SignalWatcher::~SignalWatcher(void)
{
g_instance = 0;
}
SignalWatcher* SignalWatcher::instance(void)
{
if (!g_instance) {
g_instance = new SignalWatcher();
}
return g_instance;
}
|
Implement ComponentToBlob for the transform manager. | #include <Zmey/Components/TransformManager.h>
#include <nlohmann/json.hpp>
#include <Zmey/Components/ComponentRegistry.h>
namespace Zmey
{
namespace Components
{
void TransformComponentToBlob(const nlohmann::json& rawJson, IDataBlob& blob)
{
//float position[3];
//position[0] = rawJson["Position"][0];
//position[1] = rawJson["Position"][1];
//position[2] = rawJson["Position"][2];
//blob.WriteData("Position", reinterpret_cast<uint8_t*>(position), sizeof(position));
//
//float rotation[4];
//rotation[0] = rawJson["Rotation"][0];
//rotation[1] = rawJson["Rotation"][1];
//rotation[2] = rawJson["Rotation"][2];
//rotation[2] = rawJson["Rotation"][3];
//blob.WriteData("Rotation", reinterpret_cast<uint8_t*>(rotation), sizeof(rotation));
//
//float scale[3];
//scale[0] = rawJson["Scale"][0];
//scale[1] = rawJson["Scale"][1];
//scale[2] = rawJson["Scale"][2];
//blob.WriteData("Scale", reinterpret_cast<uint8_t*>(scale), sizeof(scale));
}
}
}
REGISTER_COMPONENT_MANAGER(Transform, nullptr, nullptr); // Replace with correct implementations | #include <Zmey/Components/TransformManager.h>
#include <nlohmann/json.hpp>
#include <Zmey/Components/ComponentRegistry.h>
namespace Zmey
{
namespace Components
{
void TransformComponentToBlob(const nlohmann::json& rawJson, IDataBlob& blob)
{
float position[3];
position[0] = rawJson["Position"][0];
position[1] = rawJson["Position"][1];
position[2] = rawJson["Position"][2];
blob.WriteData("Position", reinterpret_cast<uint8_t*>(position), sizeof(position));
float rotation[4];
rotation[0] = rawJson["Rotation"][0];
rotation[1] = rawJson["Rotation"][1];
rotation[2] = rawJson["Rotation"][2];
rotation[2] = rawJson["Rotation"][3];
blob.WriteData("Rotation", reinterpret_cast<uint8_t*>(rotation), sizeof(rotation));
float scale[3];
scale[0] = rawJson["Scale"][0];
scale[1] = rawJson["Scale"][1];
scale[2] = rawJson["Scale"][2];
blob.WriteData("Scale", reinterpret_cast<uint8_t*>(scale), sizeof(scale));
}
}
}
REGISTER_COMPONENT_MANAGER(Transform, &Zmey::Components::TransformComponentToBlob, nullptr); // Replace with correct implementations |
Fix Aura compile error. My bad. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_browser_main_aura.h"
#include "base/logging.h"
ChromeBrowserMainPartsAura::ChromeBrowserMainPartsAura(
const MainFunctionParams& parameters) {
NOTIMPLEMENTED();
}
void ChromeBrowserMainPartsAura::PreEarlyInitialization() {
NOTIMPLEMENTED();
}
void ChromeBrowserMainPartsAura::PostMainMessageLoopStart() {
NOTIMPLEMENTED();
}
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_browser_main_aura.h"
#include "base/logging.h"
ChromeBrowserMainPartsAura::ChromeBrowserMainPartsAura(
const MainFunctionParams& parameters)
: ChromeBrowserMainParts(parameters) {
NOTIMPLEMENTED();
}
void ChromeBrowserMainPartsAura::PreEarlyInitialization() {
NOTIMPLEMENTED();
}
void ChromeBrowserMainPartsAura::PostMainMessageLoopStart() {
NOTIMPLEMENTED();
}
|
Remove (unnecessary) win32 only header. | #define BOOST_ERROR_CODE_HEADER_ONLY
#include <Combaseapi.h>
#include <boost/system/error_code.hpp>
| #define BOOST_ERROR_CODE_HEADER_ONLY
#include <boost/system/error_code.hpp>
|
Fix SkNWayCanvas cons call when creating null canvas. | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkNullCanvas.h"
#include "SkCanvas.h"
#include "SKNWayCanvas.h"
SkCanvas* SkCreateNullCanvas() {
// An N-Way canvas forwards calls to N canvas's. When N == 0 it's
// effectively a null canvas.
return SkNEW(SkNWayCanvas);
}
| /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkNullCanvas.h"
#include "SkCanvas.h"
#include "SKNWayCanvas.h"
SkCanvas* SkCreateNullCanvas() {
// An N-Way canvas forwards calls to N canvas's. When N == 0 it's
// effectively a null canvas.
return SkNEW(SkNWayCanvas(0,0));
}
|
Update table view on add row | #include "mytablemodel.h"
int MyTableModel::rowCount(const QModelIndex &parent) const
{
return m_data.size();
}
int MyTableModel::columnCount(const QModelIndex &parent) const
{
return 2;
}
QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
Record const& dataElem = m_data[index.row()];
if (index.column() == 0)
return QVariant(dataElem.label);
else
return QVariant(dataElem.number);
}
bool MyTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
return false;
}
Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
return Qt::ItemFlags();
}
void MyTableModel::insertRow()
{
m_data.push_back({ "label", 0 });
}
| #include "mytablemodel.h"
int MyTableModel::rowCount(const QModelIndex &parent) const
{
return m_data.size();
}
int MyTableModel::columnCount(const QModelIndex &parent) const
{
return 2;
}
QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
Record const& dataElem = m_data[index.row()];
if (index.column() == 0)
return QVariant(dataElem.label);
else
return QVariant(dataElem.number);
}
bool MyTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
return false;
}
Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
return Qt::ItemFlags();
}
void MyTableModel::insertRow()
{
m_data.push_back({ "label", 0 });
emit layoutChanged();
}
|
Call Finish() on Stages removed from the stack |
#include "stagestack.h"
namespace OpenApoc {
void StageStack::Push(std::shared_ptr<Stage> newStage)
{
// Pause any current stage
if(this->Current())
this->Current()->Pause();
this->Stack.push(newStage);
newStage->Begin();
}
std::shared_ptr<Stage> StageStack::Pop()
{
std::shared_ptr<Stage> result = this->Current();
if (result)
{
Stack.pop();
}
// If there's still an item on the stack, resume it
if( this->Current() )
this->Current()->Resume();
return result;
}
std::shared_ptr<Stage> StageStack::Current()
{
if (this->Stack.empty())
return nullptr;
else
return this->Stack.top();
}
bool StageStack::IsEmpty()
{
return this->Stack.empty();
}
void StageStack::Clear()
{
while (!this->Stack.empty())
this->Stack.pop();
}
}; //namespace OpenApoc
|
#include "stagestack.h"
namespace OpenApoc {
void StageStack::Push(std::shared_ptr<Stage> newStage)
{
// Pause any current stage
if(this->Current())
this->Current()->Pause();
this->Stack.push(newStage);
newStage->Begin();
}
std::shared_ptr<Stage> StageStack::Pop()
{
std::shared_ptr<Stage> result = this->Current();
if (result)
{
result->Finish();
Stack.pop();
}
// If there's still an item on the stack, resume it
if( this->Current() )
this->Current()->Resume();
return result;
}
std::shared_ptr<Stage> StageStack::Current()
{
if (this->Stack.empty())
return nullptr;
else
return this->Stack.top();
}
bool StageStack::IsEmpty()
{
return this->Stack.empty();
}
void StageStack::Clear()
{
while (!this->IsEmpty())
this->Pop();
}
}; //namespace OpenApoc
|
Rename unit test: WebViewTest.GetContentAsPlainText -> WebViewTest.ActiveState. | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell_test.h"
using WebKit::WebView;
class WebViewTest : public TestShellTest {
};
TEST_F(WebViewTest, GetContentAsPlainText) {
WebView* view = test_shell_->webView();
ASSERT_TRUE(view != 0);
view->setIsActive(true);
EXPECT_TRUE(view->isActive());
view->setIsActive(false);
EXPECT_FALSE(view->isActive());
view->setIsActive(true);
EXPECT_TRUE(view->isActive());
}
// TODO(viettrungluu): add more tests
| // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell_test.h"
using WebKit::WebView;
class WebViewTest : public TestShellTest {
};
TEST_F(WebViewTest, ActiveState) {
WebView* view = test_shell_->webView();
ASSERT_TRUE(view != 0);
view->setIsActive(true);
EXPECT_TRUE(view->isActive());
view->setIsActive(false);
EXPECT_FALSE(view->isActive());
view->setIsActive(true);
EXPECT_TRUE(view->isActive());
}
// TODO(viettrungluu): add more tests
|
Update the application_test_main CommandLine comment. | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/test/test_timeouts.h"
#include "mojo/application/application_runner_chromium.h"
#include "mojo/application/application_test_base_chromium.h"
#include "mojo/public/c/system/main.h"
MojoResult MojoMain(MojoHandle handle) {
// An AtExitManager instance is needed to construct message loops.
base::AtExitManager at_exit;
// Initialize test timeouts, which requires CommandLine::ForCurrentProcess().
// TODO(msw): Plumb relevant command line args before initializing timeouts.
mojo::ApplicationRunnerChromium::InitBaseCommandLine();
TestTimeouts::Initialize();
return mojo::test::RunAllTests(handle);
}
| // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/test/test_timeouts.h"
#include "mojo/application/application_runner_chromium.h"
#include "mojo/application/application_test_base_chromium.h"
#include "mojo/public/c/system/main.h"
MojoResult MojoMain(MojoHandle handle) {
// An AtExitManager instance is needed to construct message loops.
base::AtExitManager at_exit;
// Initialize the current process Commandline and test timeouts.
mojo::ApplicationRunnerChromium::InitBaseCommandLine();
TestTimeouts::Initialize();
return mojo::test::RunAllTests(handle);
}
|
Comment out a very annoying NOTIMPLEMENTED(). | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/renderer_logging.h"
#include "base/logging.h"
#include "googleurl/src/gurl.h"
namespace renderer_logging {
// Sets the URL that is logged if the renderer crashes. Use GURL() to clear
// the URL.
void SetActiveRendererURL(const GURL& url) {
// TODO(port): Once breakpad is integrated we can turn this on.
NOTIMPLEMENTED();
}
} // namespace renderer_logging
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/renderer_logging.h"
#include "base/logging.h"
#include "googleurl/src/gurl.h"
namespace renderer_logging {
// Sets the URL that is logged if the renderer crashes. Use GURL() to clear
// the URL.
void SetActiveRendererURL(const GURL& url) {
// crbug.com/9646
}
} // namespace renderer_logging
|
Change to operations with Mat | #include "photoeffects.hpp"
#include "stdio.h"
using namespace cv;
int tint(InputArray src, OutputArray dst,
const Vec3b &colorTint, float density)
{
CV_Assert(src.type() == CV_8UC3);
CV_Assert(density >= 0.0f && density <= 1.0f);
dst.create(src.size(), CV_8UC3);
Mat image = src.getMat(), outputImage = dst.getMat();
float negDen = 1 - density;
for (int i = 0; i < image.rows; i++)
{
for (int j = 0; j < image.cols; j++)
{
Vec3b colorDest = image.at<Vec3b>(i, j);
colorDest = colorTint * density + negDen * colorDest;
outputImage.at<Vec3b>(i, j) = colorDest;
}
}
return 0;
}
| #include "photoeffects.hpp"
#include "stdio.h"
using namespace cv;
int tint(InputArray src, OutputArray dst,
const Vec3b &colorTint, float density)
{
CV_Assert(src.type() == CV_8UC3);
CV_Assert(density >= 0.0f && density <= 1.0f);
dst.create(src.size(), CV_8UC3);
Mat image = src.getMat(), outputImage = dst.getMat();
Mat matColTint(src.size(), CV_8UC3, Scalar(colorTint[0], colorTint[1], colorTint[2]));
outputImage = matColTint * density + image * (1 - density);
return 0;
} |
Add example to use client.redisCommand directly. | #include "RedisClient.h"
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
(void)argc;
(void)argv;
REDIS_ENDPOINT endpoints[1] = {
{ "127.0.0.1", 6379 },
//{ "127.0.0.1", 6380 },
//{ "127.0.0.1", 6381 },
};
REDIS_CONFIG conf = {
(REDIS_ENDPOINT*)&endpoints,
1,
10000,
5000,
20,
1,
};
RedisClient client(conf);
cout << "Press <ENTER> to continue..." << endl;
cin.get();
string res = client.set("key0", "value0");
cout << "SET: " << res << endl;
cout << "Press <ENTER> to continue..." << endl;
cin.get();
res = client.get("key0");
cout << "GET: " << res << endl;
cout << "Press <ENTER> to continue..." << endl;
cin.get();
client.set("count0", "0");
long long count0;
for (long long i = 0; i < 1000; i++) {
count0 = client.incr("count0");
}
cout << "INCR count0 to " << count0 << endl;
return 0;
}
| #include "RedisClient.h"
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
(void)argc;
(void)argv;
REDIS_ENDPOINT endpoints[1] = {
{ "127.0.0.1", 6379 },
//{ "127.0.0.1", 6380 },
//{ "127.0.0.1", 6381 },
};
REDIS_CONFIG conf = {
(REDIS_ENDPOINT*)&endpoints,
1,
10000,
5000,
20,
1,
};
RedisClient client(conf);
cout << "Press <ENTER> to continue..." << endl;
cin.get();
string res = client.set("key0", "value0");
cout << "SET: " << res << endl;
cout << "Press <ENTER> to continue..." << endl;
cin.get();
res = client.get("key0");
cout << "GET: " << res << endl;
cout << "Press <ENTER> to continue..." << endl;
cin.get();
client.set("count0", "0");
long long count0;
for (long long i = 0; i < 1000; i++) {
count0 = client.incr("count0");
}
cout << "INCR count0 to " << count0 << endl;
cout << "Press <ENTER> to continue..." << endl;
cin.get();
{
RedisReplyPtr reply = client.redisCommand("PING");
cout << "PING: " << reply->str << endl;
// reply will be freed out of scope.
}
return 0;
}
|
Fix missing newline in cal controller menu | #include <string>
#include <map>
#include "CalController.h"
#include "TEMLogger.h"
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_cal_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "CALIB");
}
severity_channel_logger_t& CalController::clg = my_cal_logger::get();
std::string CalController::getUserCommand() {
std::string ui = "";
while( !(commands.count(ui)) ) {
std::cout << "What now?> ";
std::getline(std::cin, ui);
std::cin.clear();
}
return ui;
}
void CalController::showCalibrationControlMenu() {
std::string m = "Entering calibration controller....\n"
"\n"
"-------------- Menu -----------------\n"
"Choose one of the following options:\n";
std::map<std::string, std::string>::const_iterator citer;
for(citer = commands.begin(); citer != commands.end(); ++citer) {
m += citer->first;
m += " - ";
m += citer->second;
}
BOOST_LOG_SEV(clg, info) << m;
}
| #include <string>
#include <map>
#include "CalController.h"
#include "TEMLogger.h"
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_cal_logger, severity_channel_logger_t) {
return severity_channel_logger_t(keywords::channel = "CALIB");
}
severity_channel_logger_t& CalController::clg = my_cal_logger::get();
std::string CalController::getUserCommand() {
std::string ui = "";
while( !(commands.count(ui)) ) {
std::cout << "What now?> ";
std::getline(std::cin, ui);
std::cin.clear();
}
return ui;
}
void CalController::showCalibrationControlMenu() {
std::string m = "Entering calibration controller....\n"
"\n"
"-------------- Menu -----------------\n"
"Choose one of the following options:\n";
std::map<std::string, std::string>::const_iterator citer;
for(citer = commands.begin(); citer != commands.end(); ++citer) {
m += citer->first;
m += " - ";
m += citer->second;
m += "\n";
}
BOOST_LOG_SEV(clg, info) << m;
}
|
Add NUCLEOs targets in TMP102 test | #include "test_env.h"
#include "TMP102.h"
#if defined(TARGET_KL25Z)
TMP102 temperature(PTC9, PTC8, 0x90);
#elif defined(TARGET_LPC812)
TMP102 temperature(D10, D11, 0x90);
#elif defined(TARGET_LPC4088)
TMP102 temperature(p9, p10, 0x90);
#elif defined(TARGET_LPC2368)
TMP102 temperature(p28, p27, 0x90);
#else
TMP102 temperature(p28, p27, 0x90);
#endif
int main()
{
float t = temperature.read();
printf("TMP102: Temperature: %f\n\r", t);
// In our test environment (ARM office) we should get a temperature within
// the range ]15, 30[C
bool result = (t > 15.0) && (t < 30.0);
notify_completion(result);
}
| #include "test_env.h"
#include "TMP102.h"
#if defined(TARGET_KL25Z)
TMP102 temperature(PTC9, PTC8, 0x90);
#elif defined(TARGET_LPC812)
TMP102 temperature(D10, D11, 0x90);
#elif defined(TARGET_LPC4088)
TMP102 temperature(p9, p10, 0x90);
#elif defined(TARGET_LPC2368)
TMP102 temperature(p28, p27, 0x90);
#elif defined(TARGET_NUCLEO_F103RB) || \
defined(TARGET_NUCLEO_L152RE) || \
defined(TARGET_NUCLEO_F302R8) || \
defined(TARGET_NUCLEO_F030R8) || \
defined(TARGET_NUCLEO_F401RE) || \
defined(TARGET_NUCLEO_F411RE) || \
defined(TARGET_NUCLEO_F072RB) || \
defined(TARGET_NUCLEO_F334R8) || \
defined(TARGET_NUCLEO_L053R8)
TMP102 temperature(I2C_SDA, I2C_SCL, 0x90);
#else
TMP102 temperature(p28, p27, 0x90);
#endif
int main()
{
float t = temperature.read();
printf("TMP102: Temperature: %f\n\r", t);
// In our test environment (ARM office) we should get a temperature within
// the range ]15, 30[C
bool result = (t > 15.0) && (t < 30.0);
notify_completion(result);
}
|
Add 'desktop' to default benchmarks | /*
* Copyright © 2017 Collabora Ltd.
*
* This file is part of vkmark.
*
* vkmark is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 2.1 of the License, or (at your option) any later version.
*
* vkmark is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with vkmark. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexandros Frantzis <alexandros.frantzis@collabora.com>
*/
#include "default_benchmarks.h"
std::vector<std::string> DefaultBenchmarks::get()
{
return std::vector<std::string>{
"vertex:device-local=true",
"vertex:device-local=false",
"texture:anisotropy=0",
"texture:anisotropy=16",
"shading:shading=gouraud",
"shading:shading=blinn-phong-inf",
"shading:shading=phong",
"shading:shading=cel",
"cube",
"clear"
};
}
| /*
* Copyright © 2017 Collabora Ltd.
*
* This file is part of vkmark.
*
* vkmark is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 2.1 of the License, or (at your option) any later version.
*
* vkmark is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with vkmark. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexandros Frantzis <alexandros.frantzis@collabora.com>
*/
#include "default_benchmarks.h"
std::vector<std::string> DefaultBenchmarks::get()
{
return std::vector<std::string>{
"vertex:device-local=true",
"vertex:device-local=false",
"texture:anisotropy=0",
"texture:anisotropy=16",
"shading:shading=gouraud",
"shading:shading=blinn-phong-inf",
"shading:shading=phong",
"shading:shading=cel",
"desktop",
"cube",
"clear"
};
}
|
Add comment about NMEA CRLF. | #include "drivers/ublox_neo7.hpp"
#include "chprintf.h"
#include "unit_config.hpp"
void UBloxNEO7::init() {
}
GPSReading UBloxNEO7::readGPS() {
GPSReading reading;
// Read all available bytes until the newline character.
std::size_t len = readUntil('\n');
// Check if a full line is ready to be processed
if(len > 0) {
// TODO: Run parser
}
// TODO
reading.lat = 1.2f;
reading.lon = 3.4f;
//char dbg_buf[16];
//chsnprintf(dbg_buf, 12, "%12c", rxbuf.data());
//chnWriteTimeout((BaseChannel*)&SD4, (uint8_t*)dbg_buf, 12, MS2ST(20));
return reading;
}
| #include "drivers/ublox_neo7.hpp"
#include "chprintf.h"
#include "unit_config.hpp"
void UBloxNEO7::init() {
}
GPSReading UBloxNEO7::readGPS() {
GPSReading reading;
// Read all available bytes until the newline character. NMEA dictates that
// messages should end with a CRLF, but we'll only look for the LF.
std::size_t len = readUntil('\n');
// Check if a full line is ready to be processed
if(len > 0) {
// TODO: Run parser
}
// TODO
reading.lat = 1.2f;
reading.lon = 3.4f;
//char dbg_buf[16];
//chsnprintf(dbg_buf, 12, "%12c", rxbuf.data());
//chnWriteTimeout((BaseChannel*)&SD4, (uint8_t*)dbg_buf, 12, MS2ST(20));
return reading;
}
|
Fix objects parented to the camera | /*
* Copyright (c) 2016 Luke San Antonio
* All rights reserved.
*
* This file provides the implementation for the engine's C interface,
* specifically tailored for LuaJIT's FFI facilities.
*/
#include "redcrane.hpp"
namespace redc
{
struct Model_Visitor : boost::static_visitor<glm::mat4>
{
glm::mat4 operator()(Mesh_Object const& msh) const
{
return msh.model;
}
glm::mat4 operator()(Cam_Object const& cam) const
{
return gfx::camera_model_matrix(cam.cam);
}
};
glm::mat4 object_model(Object const& obj)
{
// Find current
auto this_model = boost::apply_visitor(Model_Visitor{}, obj.obj);
// Find parent
glm::mat4 parent_model(1.0f);
if(obj.parent)
{
parent_model = object_model(*obj.parent);
}
// First apply the child transformations then the parent transformations.
return parent_model * this_model;
}
}
| /*
* Copyright (c) 2016 Luke San Antonio
* All rights reserved.
*
* This file provides the implementation for the engine's C interface,
* specifically tailored for LuaJIT's FFI facilities.
*/
#include "redcrane.hpp"
namespace redc
{
struct Model_Visitor : boost::static_visitor<glm::mat4>
{
glm::mat4 operator()(Mesh_Object const& msh) const
{
return msh.model;
}
glm::mat4 operator()(Cam_Object const& cam) const
{
return glm::inverse(gfx::camera_view_matrix(cam.cam));
}
};
glm::mat4 object_model(Object const& obj)
{
// Find current
auto this_model = boost::apply_visitor(Model_Visitor{}, obj.obj);
// Find parent
glm::mat4 parent_model(1.0f);
if(obj.parent)
{
parent_model = object_model(*obj.parent);
}
// First apply the child transformations then the parent transformations.
return parent_model * this_model;
}
}
|
Add for processing command line option. | // torch4microscopic.cpp : R\[ AvP[ṼGg |Cg`܂B
//
#include "stdafx.h"
int main(int argc, char* argv[])
{
return 0;
}
| // torch4microscopic.cpp : R\[ AvP[ṼGg |Cg`܂B
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <boost/program_options.hpp>
using namespace std;
using namespace boost::program_options;
int main(int argc, char* argv[])
{
//IvV`
options_description inout_options("path setting");
options_description calc_options("calculation option");
inout_options.add_options()
("input,i", value<string>(), "input path")
("output,o", value<string>(), "output path");
calc_options.add_options()
("amp_exp", "enable amplifier (exponential growth method)")
("cutback", "enable subtraction for cutback (average lowest pixel)");
variables_map cmd_values;
try
{
options_description option_marged("");
option_marged.add(inout_options).add(calc_options);
if (!cmd_values.count("input") || cmd_values.count("output"))
{
cout << option_marged << endl;
}
store(parse_command_line(argc, argv, option_marged), cmd_values);
notify(cmd_values);
}
catch (exception &e)
{
cout << e.what() << endl;
}
return 0;
}
|
Fix aura bustage on linux. | // 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 "ui/aura/toplevel_window_container.h"
#include "base/utf_string_conversions.h"
#include "ui/aura/toplevel_window_event_filter.h"
namespace aura {
ToplevelWindowContainer::ToplevelWindowContainer()
: Window(NULL) {
set_name("ToplevelWindowContainer");
SetEventFilter(new ToplevelWindowEventFilter(this));
}
ToplevelWindowContainer::~ToplevelWindowContainer() {
}
Window* ToplevelWindowContainer::GetTopmostWindowToActivate(
Window* ignore) const {
for (Window::Windows::const_reverse_iterator i = children().rbegin();
i != children().rend(); ++i) {
Window* w = *i;
if (*i != ignore && (*i)->CanActivate())
return *i;
}
return NULL;
}
ToplevelWindowContainer* ToplevelWindowContainer::AsToplevelWindowContainer() {
return this;
}
const ToplevelWindowContainer*
ToplevelWindowContainer::AsToplevelWindowContainer() const {
return this;
}
} // namespace aura
| // 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 "ui/aura/toplevel_window_container.h"
#include "base/utf_string_conversions.h"
#include "ui/aura/toplevel_window_event_filter.h"
namespace aura {
ToplevelWindowContainer::ToplevelWindowContainer()
: Window(NULL) {
set_name("ToplevelWindowContainer");
SetEventFilter(new ToplevelWindowEventFilter(this));
}
ToplevelWindowContainer::~ToplevelWindowContainer() {
}
Window* ToplevelWindowContainer::GetTopmostWindowToActivate(
Window* ignore) const {
for (Window::Windows::const_reverse_iterator i = children().rbegin();
i != children().rend(); ++i) {
if (*i != ignore && (*i)->CanActivate())
return *i;
}
return NULL;
}
ToplevelWindowContainer* ToplevelWindowContainer::AsToplevelWindowContainer() {
return this;
}
const ToplevelWindowContainer*
ToplevelWindowContainer::AsToplevelWindowContainer() const {
return this;
}
} // namespace aura
|
Fix build by adding DE_UNREF | /*-------------------------------------------------------------------------
* Vulkan CTS Framework
* --------------------
*
* Copyright (c) 2018 The Khronos Group Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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.
*
*//*!
* \file
* \brief Stub no-op version of RenderDocUtil class
*//*--------------------------------------------------------------------*/
#include "vkRenderDocUtil.hpp"
namespace vk
{
struct RenderDocPrivate
{
};
RenderDocUtil::RenderDocUtil (void)
{
}
RenderDocUtil::~RenderDocUtil (void)
{
}
bool RenderDocUtil::isValid (void)
{
return false;
}
void RenderDocUtil::startFrame (vk::VkInstance instance)
{
}
void RenderDocUtil::endFrame (vk::VkInstance instance)
{
}
} // vk
| /*-------------------------------------------------------------------------
* Vulkan CTS Framework
* --------------------
*
* Copyright (c) 2018 The Khronos Group Inc.
* Copyright (c) 2019 Intel Corporation
*
* 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.
*
*//*!
* \file
* \brief Stub no-op version of RenderDocUtil class
*//*--------------------------------------------------------------------*/
#include "vkRenderDocUtil.hpp"
namespace vk
{
struct RenderDocPrivate
{
};
RenderDocUtil::RenderDocUtil (void)
{
}
RenderDocUtil::~RenderDocUtil (void)
{
}
bool RenderDocUtil::isValid (void)
{
return false;
}
void RenderDocUtil::startFrame (vk::VkInstance instance)
{
DE_UNREF(instance);
}
void RenderDocUtil::endFrame (vk::VkInstance instance)
{
DE_UNREF(instance);
}
} // vk
|
Make this test darwin only. | // RUN: %clang -emit-llvm -g -S %s -o - | FileCheck %s
struct X {
X(int v);
int value;
};
X::X(int v) {
// CHECK_TEMPORARILY_DISABLED: call void @_ZN1XC2Ei(%struct.X* %this1, i32 %tmp), !dbg
// TEMPORARY CHECK: X
value = v;
}
| // RUN: %clang -march=x86_64-apple-darwin10 -emit-llvm -g -S %s -o - | FileCheck %s
struct X {
X(int v);
int value;
};
X::X(int v) {
// CHECK: call void @_ZN1XC2Ei(%struct.X* %this1, i32 %tmp), !dbg
value = v;
}
|
Set apu default sample rate to 44100 | #include <cstdint>
#include <APU.h>
static int null_dmc_reader(void*, unsigned int)
{
return 0x55; // causes dmc sample to be flat
}
APU::APU()
{
time = 0;
frameLength = 29780;
apu.dmc_reader(null_dmc_reader, NULL);
apu.output(&buf);
buf.clock_rate(1789773);
buf.sample_rate(96000);
}
void APU::setDmcCallback(int (*f)(void* user_data, unsigned int), void* p)
{
apu.dmc_reader(f, p);
}
void APU::writeRegister(uint16_t addr, uint8_t data)
{
apu.write_register(clock(), addr, data);
}
int APU::getStatus()
{
return apu.read_status(clock());
}
void APU::endFrame()
{
time = 0;
frameLength ^= 1;
apu.end_frame(frameLength);
buf.end_frame(frameLength);
}
long APU::samplesAvailable() const
{
return buf.samples_avail();
}
long APU::readSamples(sample_t* buffer, long bufferSize)
{
return buf.read_samples(buffer, bufferSize);
}
| #include <cstdint>
#include <APU.h>
static int null_dmc_reader(void*, unsigned int)
{
return 0x55; // causes dmc sample to be flat
}
APU::APU()
{
time = 0;
frameLength = 29780;
apu.dmc_reader(null_dmc_reader, NULL);
apu.output(&buf);
buf.clock_rate(1789773);
buf.sample_rate(44100);
}
void APU::setDmcCallback(int (*f)(void* user_data, unsigned int), void* p)
{
apu.dmc_reader(f, p);
}
void APU::writeRegister(uint16_t addr, uint8_t data)
{
apu.write_register(clock(), addr, data);
}
int APU::getStatus()
{
return apu.read_status(clock());
}
void APU::endFrame()
{
time = 0;
frameLength ^= 1;
apu.end_frame(frameLength);
buf.end_frame(frameLength);
}
long APU::samplesAvailable() const
{
return buf.samples_avail();
}
long APU::readSamples(sample_t* buffer, long bufferSize)
{
return buf.read_samples(buffer, bufferSize);
}
|
Add noexcept for getTime() in Linux build | //
// (C) Jan de Vaan 2007-2010, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "gettime.h"
// for best accuracy, getTime is implemented platform dependent.
// to avoid a global include of windows.h, this is a separate file.
#if defined(_WIN32)
#include <windows.h>
// returns a point in time in milliseconds (can only be used for time differences, not an absolute time)
double getTime() noexcept
{
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
return (static_cast<double>(time.LowPart) * 1000.0) / static_cast<double>(freq.LowPart);
}
#else
#include <sys/time.h>
double getTime()
{
timeval t;
gettimeofday(&t, nullptr);
return (t.tv_sec * 1000000.0 + t.tv_usec) / 1000.0;
}
#endif
| //
// (C) Jan de Vaan 2007-2010, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "gettime.h"
// for best accuracy, getTime is implemented platform dependent.
// to avoid a global include of windows.h, this is a separate file.
#if defined(_WIN32)
#include <windows.h>
// returns a point in time in milliseconds (can only be used for time differences, not an absolute time)
double getTime() noexcept
{
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
return (static_cast<double>(time.LowPart) * 1000.0) / static_cast<double>(freq.LowPart);
}
#else
#include <sys/time.h>
double getTime() noexcept
{
timeval t;
gettimeofday(&t, nullptr);
return (t.tv_sec * 1000000.0 + t.tv_usec) / 1000.0;
}
#endif
|
Rework to call part1-specific stuff line by line | /**
* $ g++ solution.cpp && ./a.out < input.txt
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
/**
* O(n^2) word-by-word comparison
*/
bool validate_line(string line) {
string input1, input2;
stringstream stream1(line);
int counter1 = 0;
while (stream1 >> input1) {
stringstream stream2(line);
int counter2 = 0;
while (stream2 >> input2) {
if (counter1 == counter2) {
counter2++;
continue;
}
if (input1 == input2) {
return false;
}
counter2++;
}
counter1++;
}
return true;
}
int part1() {
int total = 0;
string line;
while (getline(cin, line)) {
if (validate_line(line)) {
total++;
}
}
return total;
}
int main() {
cout << "Day 4!\n";
cout << "Part 1: " << part1() << "\n";
}
| /**
* $ g++ solution.cpp && ./a.out < input.txt
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
/**
* O(n^2) word-by-word comparison
*/
bool part1_validate(string line) {
string input1, input2;
stringstream stream1(line);
int counter1 = 0;
while (stream1 >> input1) {
stringstream stream2(line);
int counter2 = 0;
while (stream2 >> input2) {
if (counter1 == counter2) {
counter2++;
continue;
}
if (input1 == input2) {
return false;
}
counter2++;
}
counter1++;
}
return true;
}
int main() {
cout << "Day 4!\n";
int part1_total = 0;
string line;
while (getline(cin, line)) {
if (part1_validate(line)) {
part1_total++;
}
}
cout << "Part 1: " << part1_total << "\n";
}
|
Fix Aura compile error. My bad. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_browser_main_aura.h"
#include "base/logging.h"
ChromeBrowserMainPartsAura::ChromeBrowserMainPartsAura(
const MainFunctionParams& parameters) {
NOTIMPLEMENTED();
}
void ChromeBrowserMainPartsAura::PreEarlyInitialization() {
NOTIMPLEMENTED();
}
void ChromeBrowserMainPartsAura::PostMainMessageLoopStart() {
NOTIMPLEMENTED();
}
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_browser_main_aura.h"
#include "base/logging.h"
ChromeBrowserMainPartsAura::ChromeBrowserMainPartsAura(
const MainFunctionParams& parameters)
: ChromeBrowserMainParts(parameters) {
NOTIMPLEMENTED();
}
void ChromeBrowserMainPartsAura::PreEarlyInitialization() {
NOTIMPLEMENTED();
}
void ChromeBrowserMainPartsAura::PostMainMessageLoopStart() {
NOTIMPLEMENTED();
}
|
Use require equal for testing equality | #include "hiker.hpp"
#define BOOST_TEST_MODULE HikerTest
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(Life_the_universe_and_everything)
{
// The initial code and test files are completely
// *unrelated* to the chosen exercise. They are
// merely a simple example to start you off.
// You should now delete this comment!
BOOST_REQUIRE(42, answer());
} | #include "hiker.hpp"
#define BOOST_TEST_MODULE HikerTest
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(Life_the_universe_and_everything)
{
// The initial code and test files are completely
// *unrelated* to the chosen exercise. They are
// merely a simple example to start you off.
// You should now delete this comment!
BOOST_REQUIRE_EQUAL(42, answer());
} |
Add a stub for the quadratic_sieve(...) procedure. | #include <assert.h>
#include <stdio.h>
#include "utility.h"
#include "quadraticsieve.h"
void quadratic_sieve(long long& result, long long input, int& err)
{
}
| |
Correct problem statement for problem 5 | //===-- project_euler/Problem5.cpp ------------------------------*- C++ -*-===//
//
// ProjectEuler.net solutions by Will Mitchell
//
// This file is distributed under the MIT License. See LICENSE for details.
//
//===----------------------------------------------------------------------===//
///
/// \class project_euler::Problem5
/// \brief Smallest multiple
///
/// Question
/// --------
/// A palindromic number reads the same both ways. The largest palindrome made
/// from the product of two 2-digit numbers is 9009 = 91 * 99.
///
/// Find the largest palindrome made from the product of two 3-digit numbers.
///
//===----------------------------------------------------------------------===//
#include "Problem5.h"
#include <sstream>
using std::stringstream;
#include <string>
using std::string;
#include <gmpxx.h>
string project_euler::Problem5::answer() {
if (!solved)
solve();
stringstream ss;
ss << "The smallest positive number that is evenly divisible by all of the "
"numbers from 1 to 20 is " << lcm;
return ss.str();
}
std::string project_euler::Problem5::description() const {
return "Problem 5: Smallest multiple";
}
void project_euler::Problem5::solve() {
lcm = 1;
for (unsigned long i = 1ul; i <= 20ul; ++i)
mpz_lcm_ui(lcm.get_mpz_t(), lcm.get_mpz_t(), i);
solved = true;
}
| //===-- project_euler/Problem5.cpp ------------------------------*- C++ -*-===//
//
// ProjectEuler.net solutions by Will Mitchell
//
// This file is distributed under the MIT License. See LICENSE for details.
//
//===----------------------------------------------------------------------===//
///
/// \class project_euler::Problem5
/// \brief Smallest multiple
///
/// Question
/// --------
/// 2520 is the smallest number that can be divided by each of the numbers from
/// 1 to 10 without any remainder.
///
/// What is the smallest positive number that is evenly divisible by all of the
/// numbers from 1 to 20?
///
//===----------------------------------------------------------------------===//
#include "Problem5.h"
#include <sstream>
using std::stringstream;
#include <string>
using std::string;
#include <gmpxx.h>
string project_euler::Problem5::answer() {
if (!solved)
solve();
stringstream ss;
ss << "The smallest positive number that is evenly divisible by all of the "
"numbers from 1 to 20 is "
<< lcm;
return ss.str();
}
std::string project_euler::Problem5::description() const {
return "Problem 5: Smallest multiple";
}
void project_euler::Problem5::solve() {
lcm = 1;
for (unsigned long i = 1ul; i <= 20ul; ++i)
mpz_lcm_ui(lcm.get_mpz_t(), lcm.get_mpz_t(), i);
solved = true;
}
|
Mark ExtensionApiTest.Stubs as disabled on mac due to timeouts. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"
#include "net/test/test_server.h"
// Tests that we throw errors when you try using extension APIs that aren't
// supported in content scripts.
//
// If you have added a new API to extension_api.json and this test starts
// failing, most likely you need to either mark it as "unprivileged" (if it
// should be available in content scripts) or update the list of privileged APIs
// in renderer_extension_bindings.js.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Stubs) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("stubs")) << message_;
// Navigate to a simple http:// page, which should get the content script
// injected and run the rest of the test.
GURL url(test_server()->GetURL("file/extensions/test_file.html"));
ui_test_utils::NavigateToURL(browser(), url);
ResultCatcher catcher;
ASSERT_TRUE(catcher.GetNextResult());
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"
#include "net/test/test_server.h"
// Tests that we throw errors when you try using extension APIs that aren't
// supported in content scripts.
//
// If you have added a new API to extension_api.json and this test starts
// failing, most likely you need to either mark it as "unprivileged" (if it
// should be available in content scripts) or update the list of privileged APIs
// in renderer_extension_bindings.js.
// Timey-outy on mac. http://crbug.com/89116
#if defined(OS_MACOSX)
#define MAYBE_Stubs DISABLED_Stubs
#else
#define MAYBE_Stubs Stubs
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Stubs) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("stubs")) << message_;
// Navigate to a simple http:// page, which should get the content script
// injected and run the rest of the test.
GURL url(test_server()->GetURL("file/extensions/test_file.html"));
ui_test_utils::NavigateToURL(browser(), url);
ResultCatcher catcher;
ASSERT_TRUE(catcher.GetNextResult());
}
|
Work on Problem 44 some more | // Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 44
// Coded triangle numbers
namespace problem_44 {
long nth_pentagonal_number(const long n) {
return n * (3 * n - 1) / 2;
}
bool is_pentagonal(const long n) {
const long limit = n / 2 + 1;
const long two_n = n * 2;
for (long i = 0; i <= limit; ++i) {
if (i * (3 * i - 1) == two_n) {
return true;
}
}
return false;
}
long solve() {
return 1;
}
} // namespace problem_44
| // Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 44
// Coded triangle numbers
#include <cstdio>
#include <cmath>
namespace problem_44 {
long nth_pentagonal_number(const long n) {
return n * (3 * n - 1) / 2;
}
bool is_pentagonal(const long n) {
const long limit = n / 2 + 1;
const long two_n = n * 2;
for (long i = 0; i <= limit; ++i) {
if (i * (3 * i - 1) == two_n) {
return true;
}
}
return false;
}
long solve() {
for (long i = 1; true; ++i) {
const long n = nth_pentagonal_number(i);
printf("trying %ld\n", n);
const long limit_j = (n-1)/3;
for (long j = 1; j <= limit_j; ++j) {
const long first = nth_pentagonal_number(j);
for (long k = (long)(1 + sqrt(1+24*(n+first)))/6+1; true; ++k) {
const long second = nth_pentagonal_number(k);
const long diff = second - first;
// printf("%ld - %ld = %ld\n", second, first, diff);
if (diff == n) {
if (is_pentagonal(first + second)) {
return n;
}
break;
}
if (diff > n) {
break;
}
}
}
}
}
} // namespace problem_44
|
Load wrapped library early in case of Android | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 Baldur Karlsson
*
* 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.
******************************************************************************/
#include "os/posix/posix_hook.h"
void PosixHookInit()
{
}
void PosixHookLibrary(const char *name, dlopenCallback cb)
{
} | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 Baldur Karlsson
*
* 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.
******************************************************************************/
#include "os/posix/posix_hook.h"
#include <dlfcn.h>
void PosixHookInit()
{
}
void PosixHookLibrary(const char *name, dlopenCallback cb)
{
cb(dlopen(name, RTLD_NOW));
}
|
Use '.L' for global private prefix (as mspgcc) | //===-- MSP430MCAsmInfo.cpp - MSP430 asm properties -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the MSP430MCAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "MSP430MCAsmInfo.h"
using namespace llvm;
MSP430MCAsmInfo::MSP430MCAsmInfo(const Target &T, const StringRef &TT) {
AlignmentIsInBytes = false;
AllowNameToStartWithDigit = true;
}
| //===-- MSP430MCAsmInfo.cpp - MSP430 asm properties -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the MSP430MCAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "MSP430MCAsmInfo.h"
using namespace llvm;
MSP430MCAsmInfo::MSP430MCAsmInfo(const Target &T, const StringRef &TT) {
AlignmentIsInBytes = false;
AllowNameToStartWithDigit = true;
PrivateGlobalPrefix = ".L";
}
|
Disable the failing Trap.SigSysAction test under TSan. | // Copyright 2015 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 "sandbox/linux/seccomp-bpf/trap.h"
#include <signal.h>
#include "sandbox/linux/tests/unit_tests.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sandbox {
namespace {
SANDBOX_TEST_ALLOW_NOISE(Trap, SigSysAction) {
// This creates a global Trap instance, and registers the signal handler
// (Trap::SigSysAction).
Trap::Registry();
// Send SIGSYS to self. If signal handler (SigSysAction) is not registered,
// the process will be terminated with status code -SIGSYS.
// Note that, SigSysAction handler would output an error message
// "Unexpected SIGSYS received." so it is necessary to allow the noise.
raise(SIGSYS);
}
} // namespace
} // namespace sandbox
| // Copyright 2015 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 "sandbox/linux/seccomp-bpf/trap.h"
#include <signal.h>
#include "sandbox/linux/tests/unit_tests.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sandbox {
namespace {
#if !defined(THREAD_SANITIZER)
SANDBOX_TEST_ALLOW_NOISE(Trap, SigSysAction) {
// This creates a global Trap instance, and registers the signal handler
// (Trap::SigSysAction).
Trap::Registry();
// Send SIGSYS to self. If signal handler (SigSysAction) is not registered,
// the process will be terminated with status code -SIGSYS.
// Note that, SigSysAction handler would output an error message
// "Unexpected SIGSYS received." so it is necessary to allow the noise.
raise(SIGSYS);
}
#endif
} // namespace
} // namespace sandbox
|
Check assertion macro message starts with prefix and contains filename | /****************************************************************************
* Copyright (c) 2012-2019 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_Search_Exception.hpp>
#include <boost/test/unit_test.hpp>
#define BOOST_TEST_MODULE DesignByContract
BOOST_AUTO_TEST_CASE( dumb )
{
using namespace DataTransferKit;
BOOST_CHECK_NO_THROW( DTK_SEARCH_ASSERT( true ) );
BOOST_CHECK_THROW( DTK_SEARCH_ASSERT( false ), SearchException );
std::string const prefix = "DTK Search exception: ";
std::string const message = "Keep calm and chive on!";
BOOST_CHECK_EXCEPTION( throw SearchException( message ), SearchException,
[&]( SearchException const &e ) {
return prefix + message == e.what();
} );
}
| /****************************************************************************
* Copyright (c) 2012-2019 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_Search_Exception.hpp>
#include <boost/test/unit_test.hpp>
#define BOOST_TEST_MODULE DesignByContract
BOOST_AUTO_TEST_CASE( dumb )
{
using namespace DataTransferKit;
BOOST_CHECK_NO_THROW( DTK_SEARCH_ASSERT( true ) );
std::string const prefix = "DTK Search exception: ";
BOOST_CHECK_EXCEPTION(
DTK_SEARCH_ASSERT( false ), SearchException,
[&]( std::exception const &e ) {
std::string const message = e.what();
bool const message_starts_with_prefix = message.find( prefix ) == 0;
bool const message_contains_filename =
message.find( __FILE__ ) != std::string::npos;
return message_starts_with_prefix && message_contains_filename;
} );
std::string const message = "Keep calm and chive on!";
BOOST_CHECK_EXCEPTION( throw SearchException( message ), SearchException,
[&]( SearchException const &e ) {
return prefix + message == e.what();
} );
}
|
Add rotation matrix , clockwise and counterclockwise. | //Some useful equations
int main(){
//area portion of a circle
A = pi*r^2 * (theta/(2*pi))
//area chord of a circle
A = R * R * acos((R - h)/R) - (R - h) * sqrt(2 * R * h - h * h)
// h is the height of the chord
}
| //Some useful equations
int main(){
//area portion of a circle
A = pi*r^2 * (theta/(2*pi))
//area chord of a circle
A = R * R * acos((R - h)/R) - (R - h) * sqrt(2 * R * h - h * h)
// h is the height of the chord h = R - hypot(x,y)
// rotation matrix counnterclockwise
[x' y'] = [[cost -sint] [sint cost]][x y]
// rotation matrix clockwise
[x' y'] = [[cost sint] [-sint cost]][x y]
}
|
Add tests for Scene, SceneElement access | // This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest LLC.
//
// 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 <gtest/gtest.h>
#include <SurgSim/Framework/Runtime.h>
#include <SurgSim/Framework/Scene.h>
using namespace SurgSim::Framework;
TEST(SceneTest, ConstructorTest)
{
ASSERT_NO_THROW( {Scene scene;});
} | // This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest LLC.
//
// 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 <gtest/gtest.h>
#include "MockObjects.h"
#include <SurgSim/Framework/Runtime.h>
#include <SurgSim/Framework/Scene.h>
using namespace SurgSim::Framework;
TEST(SceneTest, ConstructorTest)
{
ASSERT_NO_THROW( {Scene scene;});
}
TEST(SceneTest, ElementManagement)
{
std::shared_ptr<Scene> scene(new Scene());
std::shared_ptr<MockSceneElement> element1(new MockSceneElement("one"));
std::shared_ptr<MockSceneElement> element2(new MockSceneElement("two"));
EXPECT_EQ(0, scene->getSceneElements().size());
EXPECT_TRUE(scene->addSceneElement(element1));
EXPECT_EQ(1, scene->getSceneElements().size());
EXPECT_TRUE(scene->addSceneElement(element2));
EXPECT_EQ(2, scene->getSceneElements().size());
EXPECT_FALSE(scene->addSceneElement(element1));
EXPECT_EQ(2, scene->getSceneElements().size());
EXPECT_EQ(element1, scene->getSceneElement("one"));
EXPECT_EQ(element2, scene->getSceneElement("two"));
EXPECT_EQ(nullptr, scene->getSceneElement("nonexistentelement"));
} |
Fix for ColorController. Creates an internal implementation for the default color controller to avoid a crash if it's called. | /*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "color-controller-impl.h"
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
Dali::ColorController ColorController::Get()
{
Dali::ColorController colorController;
return colorController;
}
ColorController::ColorController()
{
}
ColorController::~ColorController()
{
}
bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
{
return false;
}
bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
{
return false;
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
| /*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "color-controller-impl.h"
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
Dali::ColorController ColorController::Get()
{
return Dali::ColorController( new ColorController() );
}
ColorController::ColorController()
{
}
ColorController::~ColorController()
{
}
bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
{
return false;
}
bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
{
return false;
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
|
Add missing -S to avoid invoking assembler unnecessarily. | // Test that -Weverything does not trigger any backend remarks.
//
// This was triggering backend remarks for which there were no frontend
// flags to filter them. The handler in BackendConsumer::DiagnosticHandlerImpl
// should not emitting diagnostics for unhandled kinds.
// RUN: %clang -c -Weverything -O0 -o /dev/null %s 2> %t.err
// RUN: FileCheck < %t.err %s
typedef __char32_t char32_t;
typedef long unsigned int size_t;
template <class _CharT>
struct __attribute__((__type_visibility__("default"))) char_traits;
template <>
struct __attribute__((__type_visibility__("default"))) char_traits<char32_t> {
typedef char32_t char_type;
static void assign(char_type& __c1, const char_type& __c2) throw() {
__c1 = __c2;
}
static char_type* move(char_type* __s1, const char_type* __s2, size_t __n);
};
char32_t* char_traits<char32_t>::move(char_type* __s1, const char_type* __s2,
size_t __n) {
{ assign(*--__s1, *--__s2); }
}
// CHECK-NOT: {{^remark:}}
| // Test that -Weverything does not trigger any backend remarks.
//
// This was triggering backend remarks for which there were no frontend
// flags to filter them. The handler in BackendConsumer::DiagnosticHandlerImpl
// should not emitting diagnostics for unhandled kinds.
// RUN: %clang -c -S -Weverything -O0 -o /dev/null %s 2> %t.err
// RUN: FileCheck < %t.err %s
typedef __char32_t char32_t;
typedef long unsigned int size_t;
template <class _CharT>
struct __attribute__((__type_visibility__("default"))) char_traits;
template <>
struct __attribute__((__type_visibility__("default"))) char_traits<char32_t> {
typedef char32_t char_type;
static void assign(char_type& __c1, const char_type& __c2) throw() {
__c1 = __c2;
}
static char_type* move(char_type* __s1, const char_type* __s2, size_t __n);
};
char32_t* char_traits<char32_t>::move(char_type* __s1, const char_type* __s2,
size_t __n) {
{ assign(*--__s1, *--__s2); }
}
// CHECK-NOT: {{^remark:}}
|
Improve readability of constructor calls of Riegeli classes. | #include "agent_based_epidemic_sim/util/records.h"
namespace abesim {
constexpr int kReadFlag = O_RDONLY;
constexpr int kWriteFlag = O_CREAT | O_WRONLY;
riegeli::RecordReader<RiegeliBytesSource> MakeRecordReader(
absl::string_view filename) {
return riegeli::RecordReader<RiegeliBytesSource>(
std::forward_as_tuple(filename, kReadFlag));
}
riegeli::RecordWriter<RiegeliBytesSink> MakeRecordWriter(
absl::string_view filename, const int parallelism) {
return riegeli::RecordWriter<RiegeliBytesSink>(
std::forward_as_tuple(filename, kWriteFlag),
riegeli::RecordWriterBase::Options().set_parallelism(parallelism));
}
} // namespace abesim
| #include "agent_based_epidemic_sim/util/records.h"
namespace abesim {
constexpr int kReadFlag = O_RDONLY;
constexpr int kWriteFlag = O_CREAT | O_WRONLY;
riegeli::RecordReader<RiegeliBytesSource> MakeRecordReader(
absl::string_view filename) {
return riegeli::RecordReader(RiegeliBytesSource(filename, kReadFlag));
}
riegeli::RecordWriter<RiegeliBytesSink> MakeRecordWriter(
absl::string_view filename, const int parallelism) {
return riegeli::RecordWriter(
RiegeliBytesSink(filename, kWriteFlag),
riegeli::RecordWriterBase::Options().set_parallelism(parallelism));
}
} // namespace abesim
|
Handle flash options in chip::lowLevelInitialization() for STM32L0 | /**
* \file
* \brief chip::lowLevelInitialization() implementation for STM32L0
*
* \author Copyright (C) 2017 Cezary Gapinski cezary.gapinski@gmail.com
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/chip/lowLevelInitialization.hpp"
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
void lowLevelInitialization()
{
}
} // namespace chip
} // namespace distortos
| /**
* \file
* \brief chip::lowLevelInitialization() implementation for STM32L0
*
* \author Copyright (C) 2017 Cezary Gapinski cezary.gapinski@gmail.com
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/chip/lowLevelInitialization.hpp"
#include "distortos/chip/STM32L0-FLASH.hpp"
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
void lowLevelInitialization()
{
#ifdef CONFIG_CHIP_STM32L0_FLASH_PREFETCH_ENABLE
configurePrefetchBuffer(true);
#else // !def CONFIG_CHIP_STM32L0_FLASH_PREFETCH_ENABLE
configurePrefetchBuffer(false);
#endif // !def CONFIG_CHIP_STM32L0_FLASH_PREFETCH_ENABLE
}
} // namespace chip
} // namespace distortos
|
Make sure the pointer in PageData::html remains valid while PageData is called. | // Copyright (c) 2008-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_publisher.h"
#include "base/utf_string_conversions.h"
namespace history {
const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";
void HistoryPublisher::PublishPageThumbnail(
const std::vector<unsigned char>& thumbnail, const GURL& url,
const base::Time& time) const {
PageData page_data = {
time,
url,
NULL,
NULL,
kThumbnailImageFormat,
&thumbnail,
};
PublishDataToIndexers(page_data);
}
void HistoryPublisher::PublishPageContent(const base::Time& time,
const GURL& url,
const std::wstring& title,
const string16& contents) const {
PageData page_data = {
time,
url,
UTF16ToWide(contents).c_str(),
title.c_str(),
NULL,
NULL,
};
PublishDataToIndexers(page_data);
}
} // namespace history
| // Copyright (c) 2008-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_publisher.h"
#include "base/utf_string_conversions.h"
namespace history {
const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";
void HistoryPublisher::PublishPageThumbnail(
const std::vector<unsigned char>& thumbnail, const GURL& url,
const base::Time& time) const {
PageData page_data = {
time,
url,
NULL,
NULL,
kThumbnailImageFormat,
&thumbnail,
};
PublishDataToIndexers(page_data);
}
void HistoryPublisher::PublishPageContent(const base::Time& time,
const GURL& url,
const std::wstring& title,
const string16& contents) const {
std::wstring wide_contents = UTF16ToWide(contents);
PageData page_data = {
time,
url,
wide_contents.c_str(),
title.c_str(),
NULL,
NULL,
};
PublishDataToIndexers(page_data);
}
} // namespace history
|
Fix grammar to check for complete text | // Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/json.hpp>
#include <tao/pegtl/contrib/trace2.hpp>
namespace pegtl = TAO_PEGTL_NAMESPACE;
using grammar = pegtl::must< pegtl::json::text >;
int main( int argc, char** argv ) // NOLINT(bugprone-exception-escape)
{
for( int i = 1; i < argc; ++i ) {
std::cout << "Parsing " << argv[ i ] << std::endl;
pegtl::argv_input in( argv, i );
pegtl::trace< grammar >( in );
}
return 0;
}
| // Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/json.hpp>
#include <tao/pegtl/contrib/trace2.hpp>
namespace pegtl = TAO_PEGTL_NAMESPACE;
using grammar = pegtl::must< pegtl::json::text, pegtl::eof >;
int main( int argc, char** argv ) // NOLINT(bugprone-exception-escape)
{
for( int i = 1; i < argc; ++i ) {
std::cout << "Parsing " << argv[ i ] << std::endl;
pegtl::argv_input in( argv, i );
pegtl::trace< grammar >( in );
}
return 0;
}
|
Disable test for Windows to fix Windows buildbots. | // RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/modules.cache \
// RUN: -I %S/Inputs/odr_hash-Friend \
// RUN: -emit-obj -o /dev/null \
// RUN: -fmodules \
// RUN: -fimplicit-module-maps \
// RUN: -fmodules-cache-path=%t/modules.cache \
// RUN: -std=c++11 -x c++ %s -verify
// expected-no-diagnostics
#include "Box.h"
#include "M1.h"
#include "M3.h"
void Run() {
Box<> Present;
}
| // RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/modules.cache \
// RUN: -I %S/Inputs/odr_hash-Friend \
// RUN: -emit-obj -o /dev/null \
// RUN: -fmodules \
// RUN: -fimplicit-module-maps \
// RUN: -fmodules-cache-path=%t/modules.cache \
// RUN: -std=c++11 -x c++ %s -verify
// UNSUPPORTED: windows
// expected-no-diagnostics
#include "Box.h"
#include "M1.h"
#include "M3.h"
void Run() {
Box<> Present;
}
|
Add function header to operator<< implementation | #include "stdafx.h"
#include "UserTypeToString.h"
UserTypeToString::UserTypeToString(std::string name, int age, double netWorth) : name(name), age(age), netWorth(netWorth)
{
}
UserTypeToString::~UserTypeToString()
{
}
std::ostream& operator<<(std::ostream& os, const UserTypeToString& obj)
{
// write obj to stream
os << "name - " << obj.name.c_str() << " age - " << obj.age << " netWorth - " << obj.netWorth;
return os;
}
| #include "stdafx.h"
#include "UserTypeToString.h"
UserTypeToString::UserTypeToString(std::string name, int age, double netWorth) : name(name), age(age), netWorth(netWorth)
{
}
UserTypeToString::~UserTypeToString()
{
}
/* when streaming an instance of this type to an ostream of any kind this function will build the string
containing the state of the object.
*/
std::ostream& operator<<(std::ostream& os, const UserTypeToString& obj)
{
// write obj to stream
os << "name - " << obj.name.c_str() << " age - " << obj.age << " netWorth - " << obj.netWorth;
return os;
}
|
Fix RISCV build after r318352 | //===-- RISCVTargetInfo.cpp - RISCV Target Implementation -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
namespace llvm {
Target &getTheRISCV32Target() {
static Target TheRISCV32Target;
return TheRISCV32Target;
}
Target &getTheRISCV64Target() {
static Target TheRISCV64Target;
return TheRISCV64Target;
}
}
extern "C" void LLVMInitializeRISCVTargetInfo() {
RegisterTarget<Triple::riscv32> X(getTheRISCV32Target(), "riscv32",
"32-bit RISC-V");
RegisterTarget<Triple::riscv64> Y(getTheRISCV64Target(), "riscv64",
"64-bit RISC-V");
}
| //===-- RISCVTargetInfo.cpp - RISCV Target Implementation -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;
namespace llvm {
Target &getTheRISCV32Target() {
static Target TheRISCV32Target;
return TheRISCV32Target;
}
Target &getTheRISCV64Target() {
static Target TheRISCV64Target;
return TheRISCV64Target;
}
}
extern "C" void LLVMInitializeRISCVTargetInfo() {
RegisterTarget<Triple::riscv32> X(getTheRISCV32Target(), "riscv32",
"32-bit RISC-V", "RISCV");
RegisterTarget<Triple::riscv64> Y(getTheRISCV64Target(), "riscv64",
"64-bit RISC-V", "RISCV");
}
|
Fix unsymbolize unittest. Adding win64 address. | // When we link a binary without the -debug flag, ASan should print out VAs
// instead of RVAs. The frames for main and do_uaf should be above 0x400000,
// which is the default image base of an executable.
// RUN: rm -f %t.pdb
// RUN: %clangxx_asan -c -O2 %s -o %t.obj
// RUN: link /nologo /OUT:%t.exe %t.obj %asan_lib %asan_cxx_lib
// RUN: not %run %t.exe 2>&1 | FileCheck %s
#include <stdlib.h>
#include <stdio.h>
int __attribute__((noinline)) do_uaf(void);
int main() {
int r = do_uaf();
printf("r: %d\n", r);
return r;
}
int do_uaf(void) {
char *x = (char*)malloc(10 * sizeof(char));
free(x);
return x[5];
// CHECK: AddressSanitizer: heap-use-after-free
// CHECK: #0 {{0x[a-f0-9]+ \(.*[\\/]unsymbolized.cc.*.exe\+0x40[a-f0-9]{4}\)}}
// CHECK: #1 {{0x[a-f0-9]+ \(.*[\\/]unsymbolized.cc.*.exe\+0x40[a-f0-9]{4}\)}}
}
| // When we link a binary without the -debug flag, ASan should print out VAs
// instead of RVAs. The frames for main and do_uaf should be above 0x400000,
// which is the default image base of an executable.
// RUN: rm -f %t.pdb
// RUN: %clangxx_asan -c -O2 %s -o %t.obj
// RUN: link /nologo /OUT:%t.exe %t.obj %asan_lib %asan_cxx_lib
// RUN: not %run %t.exe 2>&1 | FileCheck %s
#include <stdlib.h>
#include <stdio.h>
int __attribute__((noinline)) do_uaf(void);
int main() {
int r = do_uaf();
printf("r: %d\n", r);
return r;
}
int do_uaf(void) {
char *x = (char*)malloc(10 * sizeof(char));
free(x);
return x[5];
// CHECK: AddressSanitizer: heap-use-after-free
// CHECK: #0 {{0x[a-f0-9]+ \(.*[\\/]unsymbolized.cc.*.exe\+(0x40|0x14000)[a-f0-9]{4}\)}}
// CHECK: #1 {{0x[a-f0-9]+ \(.*[\\/]unsymbolized.cc.*.exe\+(0x40|0x14000)[a-f0-9]{4}\)}}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.