Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Use QApplication and set KScreen backend to XRandR | /*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program 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 General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
*************************************************************************************/
#include <QtCore/QCoreApplication>
#include "testapp.h"
int main (int argc, char *argv[])
{
QCoreApplication app(argc, argv);
TestApp *test = new TestApp(0);
app.exec();
} | /*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program 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 General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
*************************************************************************************/
#include <QtGui/QApplication>
#include "testapp.h"
int main (int argc, char *argv[])
{
setenv("KSCREEN_BACKEND", "XRandR", 1);
QApplication app(argc, argv);
TestApp *test = new TestApp(0);
app.exec();
} |
Add missing string include for win32 | // Copyright 2014 Toggl Desktop developers.
#include <windows.h>
#include <psapi.h>
#pragma comment(lib, "psapi.lib")
#include <time.h>
#include <string>
static const int kFilenameBufferSize = 255;
template <class string_type>
inline typename string_type::value_type *WriteInto(string_type *str,
size_t length_with_null) {
str->reserve(length_with_null);
str->resize(length_with_null - 1);
return &((*str)[0]);
}
void GetFocusedWindowInfo(std::string *title, std::string *filename) {
*title = "";
*filename = "";
// get window handle
HWND window_handle = GetForegroundWindow();
// get window title
int length = GetWindowTextLength(window_handle) + 1;
std::wstring title_wstring;
GetWindowText(window_handle, WriteInto(&title_wstring, length), length);
std::string str(title_wstring.begin(), title_wstring.end());
*title = str;
// get process by window handle
DWORD process_id;
GetWindowThreadProcessId(window_handle, &process_id);
// get the filename of another process
HANDLE ps = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE,
process_id);
CHAR filename_buffer[kFilenameBufferSize];
if (GetModuleFileNameExA(ps, 0, filename_buffer, kFilenameBufferSize) > 0) {
*filename = std::string(filename_buffer);
}
}
| // Copyright 2014 Toggl Desktop developers.
#include <windows.h>
#include <psapi.h>
#pragma comment(lib, "psapi.lib")
#include <time.h>
static const int kFilenameBufferSize = 255;
template <class string_type>
inline typename string_type::value_type *WriteInto(string_type *str,
size_t length_with_null) {
str->reserve(length_with_null);
str->resize(length_with_null - 1);
return &((*str)[0]);
}
void GetFocusedWindowInfo(std::string *title, std::string *filename) {
*title = "";
*filename = "";
// get window handle
HWND window_handle = GetForegroundWindow();
// get window title
int length = GetWindowTextLength(window_handle) + 1;
std::wstring title_wstring;
GetWindowText(window_handle, WriteInto(&title_wstring, length), length);
std::string str(title_wstring.begin(), title_wstring.end());
*title = str;
// get process by window handle
DWORD process_id;
GetWindowThreadProcessId(window_handle, &process_id);
// get the filename of another process
HANDLE ps = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE,
process_id);
CHAR filename_buffer[kFilenameBufferSize];
if (GetModuleFileNameExA(ps, 0, filename_buffer, kFilenameBufferSize) > 0) {
*filename = std::string(filename_buffer);
}
}
|
Fix compile failure on GCC | // 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 "chrome/common/net/test_url_fetcher_factory.h"
TestURLFetcher::TestURLFetcher(int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d)
: URLFetcher(url, request_type, d),
id_(id),
original_url_(url) {
}
URLFetcher* TestURLFetcherFactory::CreateURLFetcher(
int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d) {
TestURLFetcher* fetcher = new TestURLFetcher(id, url, request_type, d);
fetchers_[id] = fetcher;
return fetcher;
}
TestURLFetcher* TestURLFetcherFactory::GetFetcherByID(int id) const {
Fetchers::const_iterator i = fetchers_.find(id);
return i == fetchers_.end() ? NULL : i->second;
}
void TestURLFetcherFactory::RemoveFetcherFromMap(int id) {
Fetchers::const_iterator i = fetchers_.find(id);
DCHECK(i != fetchers_.end());
fetchers_.erase(i);
}
| // 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 "chrome/common/net/test_url_fetcher_factory.h"
TestURLFetcher::TestURLFetcher(int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d)
: URLFetcher(url, request_type, d),
id_(id),
original_url_(url) {
}
URLFetcher* TestURLFetcherFactory::CreateURLFetcher(
int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d) {
TestURLFetcher* fetcher = new TestURLFetcher(id, url, request_type, d);
fetchers_[id] = fetcher;
return fetcher;
}
TestURLFetcher* TestURLFetcherFactory::GetFetcherByID(int id) const {
Fetchers::const_iterator i = fetchers_.find(id);
return i == fetchers_.end() ? NULL : i->second;
}
void TestURLFetcherFactory::RemoveFetcherFromMap(int id) {
Fetchers::iterator i = fetchers_.find(id);
DCHECK(i != fetchers_.end());
fetchers_.erase(i);
}
|
Put variable name to a separate line. | //===-- Passes.cpp - Target independent code generation passes ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "Support/CommandLine.h"
#include <iostream>
using namespace llvm;
namespace {
enum RegAllocName { simple, local, linearscan, iterativescan };
cl::opt<RegAllocName RegAlloc(
"regalloc",
cl::desc("Register allocator to use: (default = simple)"),
cl::Prefix,
cl::values(
clEnumVal(simple, " simple register allocator"),
clEnumVal(local, " local register allocator"),
clEnumVal(linearscan, " linear scan register allocator"),
clEnumVal(iterativescan, " iterative scan register allocator"),
clEnumValEnd),
cl::init(local));
}
FunctionPass *llvm::createRegisterAllocator() {
switch (RegAlloc) {
default:
std::cerr << "no register allocator selected";
abort();
case simple:
return createSimpleRegisterAllocator();
case local:
return createLocalRegisterAllocator();
case linearscan:
return createLinearScanRegisterAllocator();
case iterativescan:
return createIterativeScanRegisterAllocator();
}
}
| //===-- Passes.cpp - Target independent code generation passes ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "Support/CommandLine.h"
#include <iostream>
using namespace llvm;
namespace {
enum RegAllocName { simple, local, linearscan, iterativescan };
cl::opt<RegAllocName>
RegAlloc(
"regalloc",
cl::desc("Register allocator to use: (default = simple)"),
cl::Prefix,
cl::values(
clEnumVal(simple, " simple register allocator"),
clEnumVal(local, " local register allocator"),
clEnumVal(linearscan, " linear scan register allocator"),
clEnumVal(iterativescan, " iterative scan register allocator"),
clEnumValEnd),
cl::init(local));
}
FunctionPass *llvm::createRegisterAllocator() {
switch (RegAlloc) {
default:
std::cerr << "no register allocator selected";
abort();
case simple:
return createSimpleRegisterAllocator();
case local:
return createLocalRegisterAllocator();
case linearscan:
return createLinearScanRegisterAllocator();
case iterativescan:
return createIterativeScanRegisterAllocator();
}
}
|
Check should be for component header, not not toplevel. | // csamisc_anonymousnamespaceinheader.t.cpp -*-C++-*-
// -----------------------------------------------------------------------------
// Copyright 2011 Dietmar Kuehl http://www.dietmar-kuehl.de
// Distributed under the Boost Software License, Version 1.0. (See file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
// -----------------------------------------------------------------------------
#include <csabase_analyser.h>
#include <csabase_location.h>
#include <csabase_registercheck.h>
#ident "$Id$"
// -----------------------------------------------------------------------------
static std::string const check_name("anon-namespace");
static void
anonymous_namespace_in_header(cool::csabase::Analyser& analyser, clang::NamespaceDecl const* decl)
{
if (decl->isAnonymousNamespace()
&& analyser.get_location(decl).file() != analyser.toplevel())
{
analyser.report(decl, check_name, "ANS01",
"Anonymous namespace in header");
}
}
// -----------------------------------------------------------------------------
static cool::csabase::RegisterCheck check(check_name, &anonymous_namespace_in_header);
| // csamisc_anonymousnamespaceinheader.t.cpp -*-C++-*-
// -----------------------------------------------------------------------------
// Copyright 2011 Dietmar Kuehl http://www.dietmar-kuehl.de
// Distributed under the Boost Software License, Version 1.0. (See file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
// -----------------------------------------------------------------------------
#include <csabase_analyser.h>
#include <csabase_debug.h>
#include <csabase_location.h>
#include <csabase_registercheck.h>
#ident "$Id$"
// -----------------------------------------------------------------------------
static std::string const check_name("anon-namespace");
static void anonymous_namespace_in_header(cool::csabase::Analyser& analyser,
clang::NamespaceDecl const* decl)
{
if (decl->isAnonymousNamespace() && analyser.is_component_header(decl)) {
analyser.report(decl, check_name, "ANS01",
"Anonymous namespace in header", true);
}
}
// -----------------------------------------------------------------------------
static cool::csabase::RegisterCheck check(check_name, &anonymous_namespace_in_header);
|
Update unit tests for rc3 | #include "omnicore/version.h"
#include "config/bitcoin-config.h"
#include <string>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(omnicore_version_tests)
BOOST_AUTO_TEST_CASE(version_comparison)
{
BOOST_CHECK(OMNICORE_VERSION > 900300); // Master Core v0.0.9.3
}
/**
* The following tests are very unhandy, because any version bump
* breaks the tests.
*
* TODO: might be removed completely.
*/
BOOST_AUTO_TEST_CASE(version_string)
{
BOOST_CHECK_EQUAL(OmniCoreVersion(), "0.0.10-rc2");
}
BOOST_AUTO_TEST_CASE(version_number)
{
BOOST_CHECK_EQUAL(OMNICORE_VERSION, 1000000);
}
BOOST_AUTO_TEST_CASE(config_package_version)
{
// the package version is used in the file names:
BOOST_CHECK_EQUAL(PACKAGE_VERSION, "0.0.10.0-rc2");
}
BOOST_AUTO_TEST_SUITE_END()
| #include "omnicore/version.h"
#include "config/bitcoin-config.h"
#include <string>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(omnicore_version_tests)
BOOST_AUTO_TEST_CASE(version_comparison)
{
BOOST_CHECK(OMNICORE_VERSION > 900300); // Master Core v0.0.9.3
}
/**
* The following tests are very unhandy, because any version bump
* breaks the tests.
*
* TODO: might be removed completely.
*/
BOOST_AUTO_TEST_CASE(version_string)
{
BOOST_CHECK_EQUAL(OmniCoreVersion(), "0.0.10-rc3");
}
BOOST_AUTO_TEST_CASE(version_number)
{
BOOST_CHECK_EQUAL(OMNICORE_VERSION, 1000000);
}
BOOST_AUTO_TEST_CASE(config_package_version)
{
// the package version is used in the file names:
BOOST_CHECK_EQUAL(PACKAGE_VERSION, "0.0.10.0-rc3");
}
BOOST_AUTO_TEST_SUITE_END()
|
Allow for frequencies to be modified | #include <memory>
#include "view.h"
#include "dummyfrequencyprovider.h"
#include "frequencyprovider.h"
#include <emscripten.h>
#include <SDL/SDL.h>
extern "C" {
EMSCRIPTEN_KEEPALIVE
int run_fmv_with_frequency_provider(int width, int height) {
std::shared_ptr<FMV::FrequencyProvider> provider(FMV::createDummyFrequencyProvider());
return FMV::runViewLoop(0, nullptr, {width, height}, *provider);
}
}
| #include <array>
#include <memory>
#include "view.h"
#include "frequencyprovider.h"
#include <emscripten.h>
#include <SDL/SDL.h>
namespace {
class ModifiableFrequencyProvider :
public FMV::FrequencyProvider
{
public:
static std::array<float, 255> frequencyData;
public:
void workWithCurrentFrequencies(Callback const &cb) override {
cb(ModifiableFrequencyProvider::frequencyData.data());
}
};
}
extern "C" {
EMSCRIPTEN_KEEPALIVE
int run_fmv_with_frequency_provider(int width, int height) {
ModifiableFrequencyProvider::frequencyData.fill(0.0);
ModifiableFrequencyProvider provider;
return FMV::runViewLoop(0, nullptr, {width, height}, provider);
}
EMSCRIPTEN_KEEPALIVE
void set_frequencies(float *frequencies, size_t length) {
for (size_t i = 0; i < length; ++i) {
ModifiableFrequencyProvider::frequencyData[i] = frequencies[i];
}
}
}
|
Fix an issue found by purify with my previous submission. | // 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/glue/resource_loader_bridge.h"
#include "net/http/http_response_headers.h"
namespace webkit_glue {
ResourceLoaderBridge::ResponseInfo::ResponseInfo() {
content_length = -1;
#if defined(OS_WIN)
response_data_file = base::kInvalidPlatformFileValue;
#elif defined(OS_POSIX)
response_data_file.fd = base::kInvalidPlatformFileValue;
response_data_file.auto_close = false;
#endif
}
ResourceLoaderBridge::ResponseInfo::~ResponseInfo() {
}
ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() {
}
ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() {
}
ResourceLoaderBridge::ResourceLoaderBridge() {
}
ResourceLoaderBridge::~ResourceLoaderBridge() {
}
} // namespace webkit_glue
| // 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/glue/resource_loader_bridge.h"
#include "webkit/glue/webappcachecontext.h"
#include "net/http/http_response_headers.h"
namespace webkit_glue {
ResourceLoaderBridge::ResponseInfo::ResponseInfo() {
content_length = -1;
app_cache_id = WebAppCacheContext::kNoAppCacheId;
#if defined(OS_WIN)
response_data_file = base::kInvalidPlatformFileValue;
#elif defined(OS_POSIX)
response_data_file.fd = base::kInvalidPlatformFileValue;
response_data_file.auto_close = false;
#endif
}
ResourceLoaderBridge::ResponseInfo::~ResponseInfo() {
}
ResourceLoaderBridge::SyncLoadResponse::SyncLoadResponse() {
}
ResourceLoaderBridge::SyncLoadResponse::~SyncLoadResponse() {
}
ResourceLoaderBridge::ResourceLoaderBridge() {
}
ResourceLoaderBridge::~ResourceLoaderBridge() {
}
} // namespace webkit_glue
|
Fix CSS fuzzer input size | // Copyright 2016 The PDFium 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 <memory>
#include "core/fxcrt/cfx_retain_ptr.h"
#include "core/fxcrt/fx_string.h"
#include "xfa/fde/css/cfde_csssyntaxparser.h"
#include "xfa/fde/css/fde_css.h"
#include "xfa/fgas/crt/fgas_stream.h"
#include "xfa/fxfa/parser/cxfa_widetextread.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
CFX_WideString input = CFX_WideString::FromUTF8(
CFX_ByteStringC(data, static_cast<FX_STRSIZE>(size)));
CFDE_CSSSyntaxParser parser;
parser.Init(input.c_str(), size);
FDE_CSSSyntaxStatus status;
do {
status = parser.DoSyntaxParse();
} while (status != FDE_CSSSyntaxStatus::Error &&
status != FDE_CSSSyntaxStatus::EOS);
return 0;
}
| // Copyright 2016 The PDFium 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 <memory>
#include "core/fxcrt/cfx_retain_ptr.h"
#include "core/fxcrt/fx_string.h"
#include "xfa/fde/css/cfde_csssyntaxparser.h"
#include "xfa/fde/css/fde_css.h"
#include "xfa/fgas/crt/fgas_stream.h"
#include "xfa/fxfa/parser/cxfa_widetextread.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
CFX_WideString input = CFX_WideString::FromUTF8(
CFX_ByteStringC(data, static_cast<FX_STRSIZE>(size)));
// If we convert the input into an empty string bail out.
if (input.GetLength() == 0)
return 0;
CFDE_CSSSyntaxParser parser;
parser.Init(input.c_str(), input.GetLength());
FDE_CSSSyntaxStatus status;
do {
status = parser.DoSyntaxParse();
} while (status != FDE_CSSSyntaxStatus::Error &&
status != FDE_CSSSyntaxStatus::EOS);
return 0;
}
|
Fix derived constructor to call base class constructor | #include "mjolnir/directededgebuilder.h"
namespace valhalla {
namespace mjolnir {
// Default constructor
DirectedEdgeBuilder::DirectedEdgeBuilder()
: speed_(0),
length_(0) {
}
// Sets the length of the edge in kilometers.
void DirectedEdgeBuilder::length(const float length) {
length_ = length;
}
// Sets the end node of this directed edge.
void DirectedEdgeBuilder::endnode(const GraphId& endnode) {
endnode_ = endnode;
}
// TODO - methods for access
// Sets the speed in KPH.
void DirectedEdgeBuilder::speed(const float speed) const {
// TODO - protect against exceeding max speed
speed_ = static_cast<unsigned char>(speed + 0.5f);
}
}
}
| #include "mjolnir/directededgebuilder.h"
namespace valhalla {
namespace mjolnir {
// Default constructor
DirectedEdgeBuilder::DirectedEdgeBuilder()
: DirectedEdge() {
}
// Sets the length of the edge in kilometers.
void DirectedEdgeBuilder::length(const float length) {
length_ = length;
}
// Sets the end node of this directed edge.
void DirectedEdgeBuilder::endnode(const GraphId& endnode) {
endnode_ = endnode;
}
// TODO - methods for access
// Sets the speed in KPH.
void DirectedEdgeBuilder::speed(const float speed) const {
// TODO - protect against exceeding max speed
speed_ = static_cast<unsigned char>(speed + 0.5f);
}
}
}
|
Fix incorrect comment in Pawn Advancement Gene | #include "Genes/Pawn_Advancement_Gene.h"
#include <string>
#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Utility.h"
Pawn_Advancement_Gene::Pawn_Advancement_Gene() : Gene(0.0)
{
}
Pawn_Advancement_Gene::~Pawn_Advancement_Gene()
{
}
double Pawn_Advancement_Gene::score_board(const Board& board, Color perspective) const
{
double score = 0.0;
int home_rank = (perspective == WHITE ? 2 : 7);
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = 1; rank <= 8; ++rank)
{
auto piece = board.piece_on_square(file, rank);
if(piece && piece->color() == perspective && toupper(piece->fen_symbol()) == 'P')
{
// 1 point per pawn + 1 point per move towards promotion
score += std::abs(home_rank - rank);
}
}
}
return score/(8.*5.); // normalize to 8 pawns 5 ranks from home (just before promotion)
}
Pawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const
{
return new Pawn_Advancement_Gene(*this);
}
std::string Pawn_Advancement_Gene::name() const
{
return "Pawn Advancement Gene";
}
| #include "Genes/Pawn_Advancement_Gene.h"
#include <string>
#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Utility.h"
Pawn_Advancement_Gene::Pawn_Advancement_Gene() : Gene(0.0)
{
}
Pawn_Advancement_Gene::~Pawn_Advancement_Gene()
{
}
double Pawn_Advancement_Gene::score_board(const Board& board, Color perspective) const
{
double score = 0.0;
int home_rank = (perspective == WHITE ? 2 : 7);
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = 1; rank <= 8; ++rank)
{
auto piece = board.piece_on_square(file, rank);
if(piece && piece->color() == perspective && toupper(piece->fen_symbol()) == 'P')
{
// 1 point per move towards promotion
score += std::abs(home_rank - rank);
}
}
}
return score/(8.*5.); // normalize to 8 pawns 5 ranks from home (just before promotion)
}
Pawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const
{
return new Pawn_Advancement_Gene(*this);
}
std::string Pawn_Advancement_Gene::name() const
{
return "Pawn Advancement Gene";
}
|
Fix a bug on Windows which cause a crash. | /*
* glc_declarativeview.cpp
*
* Created on: 22/04/2013
* Author: laumaya
*/
#include <QGLWidget>
#include <GLC_Context>
#include "glc_declarativeview.h"
GLC_DeclarativeView::GLC_DeclarativeView(QWidget *pParent)
: QDeclarativeView(pParent)
{
QDeclarativeView::setViewport(new QGLWidget(new GLC_Context(QGLFormat(QGL::SampleBuffers))));
QDeclarativeView::setRenderHint(QPainter::SmoothPixmapTransform);
QDeclarativeView::setRenderHint(QPainter::Antialiasing);
QDeclarativeView::setResizeMode(QDeclarativeView::SizeViewToRootObject);
}
| /*
* glc_declarativeview.cpp
*
* Created on: 22/04/2013
* Author: laumaya
*/
#include <QGLWidget>
#include <GLC_Context>
#include "glc_declarativeview.h"
GLC_DeclarativeView::GLC_DeclarativeView(QWidget *pParent)
: QDeclarativeView(pParent)
{
QDeclarativeView::setViewport(new QGLWidget(new GLC_Context(QGLFormat(QGL::SampleBuffers)), this));
QDeclarativeView::setRenderHint(QPainter::SmoothPixmapTransform);
QDeclarativeView::setRenderHint(QPainter::Antialiasing);
QDeclarativeView::setResizeMode(QDeclarativeView::SizeViewToRootObject);
}
|
Correct usage line, no need to include .py in module name. | #include <iostream>
#include <Python.h>
#include "character.h"
using namespace std;
static int error(const std::string & message){
std::cout << message << std::endl;
//PyErr_Print();
return -1;
}
int main(int argc, char ** argv){
if (argc > 1){
Py_Initialize();
/* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
try {
Character * character = new Character(argv[1]);
character->addAttribute("name", Character::String);
std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
delete character;
} catch (const PyException & ex){
error("Problem loading module! Reason: " + ex.getReason());
}
Py_Finalize();
return 0;
}
std::cout << "Usage: ./test character.py" << std::endl;
return 0;
}
| #include <iostream>
#include <Python.h>
#include "character.h"
using namespace std;
static int error(const std::string & message){
std::cout << message << std::endl;
//PyErr_Print();
return -1;
}
int main(int argc, char ** argv){
if (argc > 1){
Py_Initialize();
/* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
try {
Character * character = new Character(argv[1]);
character->addAttribute("name", Character::String);
std::cout << "Character Name: " << character->getStringValue("name") << std::endl;
delete character;
} catch (const PyException & ex){
error("Problem loading module! Reason: " + ex.getReason());
}
Py_Finalize();
return 0;
}
std::cout << "Usage: ./test character_module_name" << std::endl;
return 0;
}
|
Allow configuraiton of state-store log dir / name. Also add debug webserver to state-store. | // Copyright (c) 2012 Cloudera, Inc. All rights reserved.
//
// This file contains the main() function for the state store process,
// which exports the Thrift service StateStoreService.
#include <glog/logging.h>
#include <gflags/gflags.h>
#include "sparrow/state-store-service.h"
#include "util/cpu-info.h"
DEFINE_int32(state_store_port, 24000, "port where StateStoreService is exported");
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
impala::CpuInfo::Init();
boost::shared_ptr<sparrow::StateStore> state_store(new sparrow::StateStore());
state_store->Start(FLAGS_state_store_port);
state_store->WaitForServerToStop();
}
| // Copyright (c) 2012 Cloudera, Inc. All rights reserved.
//
// This file contains the main() function for the state store process,
// which exports the Thrift service StateStoreService.
#include <glog/logging.h>
#include <gflags/gflags.h>
#include <iostream>
#include "common/status.h"
#include "sparrow/state-store-service.h"
#include "util/cpu-info.h"
#include "util/webserver.h"
#include "util/logging.h"
#include "util/default-path-handlers.h"
DECLARE_int32(state_store_port);
DECLARE_int32(webserver_port);
DECLARE_bool(enable_webserver);
using impala::Webserver;
using impala::Status;
using namespace std;
int main(int argc, char** argv) {
// Override default for webserver port
FLAGS_webserver_port = 9190;
google::ParseCommandLineFlags(&argc, &argv, true);
impala::InitGoogleLoggingSafe(argv[0]);
impala::CpuInfo::Init();
boost::shared_ptr<sparrow::StateStore> state_store(new sparrow::StateStore());
boost::scoped_ptr<Webserver> webserver(new Webserver());
if (FLAGS_enable_webserver) {
impala::AddDefaultPathHandlers(webserver.get());
EXIT_IF_ERROR(webserver->Start());
} else {
LOG(INFO) << "Not starting webserver";
}
state_store->Start(FLAGS_state_store_port);
state_store->WaitForServerToStop();
}
|
Fix writing of v5 REPLY.TABLE. | // Copyright 2014-present Bill Fisher. All rights reserved.
#include "ofp/mptablestats.h"
#include "ofp/writable.h"
#include "ofp/constants.h"
#include "ofp/log.h"
#include "ofp/validation.h"
using namespace ofp;
void MPTableStatsBuilder::write(Writable *channel) {
UInt8 version = channel->version();
if (version == OFP_VERSION_4) {
channel->write(&msg_, 4);
channel->write(&msg_.activeCount_, 20);
channel->flush();
} else if (version == OFP_VERSION_1) {
channel->write(&msg_, sizeof(msg_));
channel->flush();
} else {
log::debug("MPTableStatsBuilder not implemented for version:", version);
}
}
| // Copyright 2014-present Bill Fisher. All rights reserved.
#include "ofp/mptablestats.h"
#include "ofp/writable.h"
#include "ofp/constants.h"
#include "ofp/log.h"
#include "ofp/validation.h"
using namespace ofp;
void MPTableStatsBuilder::write(Writable *channel) {
UInt8 version = channel->version();
if (version >= OFP_VERSION_4) {
channel->write(&msg_, 4);
channel->write(&msg_.activeCount_, 20);
channel->flush();
} else if (version == OFP_VERSION_1) {
channel->write(&msg_, sizeof(msg_));
channel->flush();
} else {
log::debug("MPTableStatsBuilder not implemented for version:", version);
}
}
|
Make our CHECK logging more useful on the target... | /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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 "logging.h"
#include <iostream>
#include <unistd.h>
#include "cutils/log.h"
static const int kLogSeverityToAndroidLogPriority[] = {
ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL
};
LogMessage::LogMessage(const char* file, int line, LogSeverity severity, int error)
: file_(file), line_number_(line), severity_(severity), errno_(error)
{
}
void LogMessage::LogLine(const char* line) {
int priority = kLogSeverityToAndroidLogPriority[severity_];
LOG_PRI(priority, LOG_TAG, "%s", line);
}
| /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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 "logging.h"
#include <iostream>
#include <unistd.h>
#include "cutils/log.h"
static const int kLogSeverityToAndroidLogPriority[] = {
ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL
};
LogMessage::LogMessage(const char* file, int line, LogSeverity severity, int error)
: file_(file), line_number_(line), severity_(severity), errno_(error)
{
const char* last_slash = strrchr(file, '/');
file_ = (last_slash == NULL) ? file : last_slash + 1;
}
void LogMessage::LogLine(const char* line) {
int priority = kLogSeverityToAndroidLogPriority[severity_];
LOG_PRI(priority, LOG_TAG, "%s:%d] %s", file_, line_number_, line);
}
|
Include stdlib (getenv and setenv) | /*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program 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 General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
*************************************************************************************/
#include <QtGui/QApplication>
#include "loop.h"
int main (int argc, char *argv[])
{
QApplication app(argc, argv);
setenv("KSCREEN_BACKEND", "XRandR", 1);
Loop *loop = new Loop(0);
loop->printConfig();
app.exec();
} | /*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program 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 General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
*************************************************************************************/
#include <stdlib.h>
#include <QtGui/QApplication>
#include "loop.h"
int main (int argc, char *argv[])
{
QApplication app(argc, argv);
setenv("KSCREEN_BACKEND", "XRandR", 1);
Loop *loop = new Loop(0);
loop->printConfig();
app.exec();
} |
Move RNG to anonymous namespace. | #include "sampling.h"
namespace {
static constexpr float M_2PI = 2.f * M_PI;
}
namespace sampling {
__thread static xorshift64star<float> uniform{4};
std::pair<Vec, float> hemisphere() {
// draw coordinates
float u1 = uniform();
float u2 = uniform();
// u1 is cos(theta)
auto z = u1;
auto r = sqrtf(fmax(0.f, 1.f - z*z));
auto phi = M_2PI * u2;
auto x = r * cosf(phi);
auto y = r * sinf(phi);
return std::make_pair(Vec{x, y, z}, u1);
}
/**
* Sample a point on the triangle.
*
* return point in world space.
*/
Vec triangle(const Triangle& triangle) {
while(true) {
float r1 = uniform();
float r2 = uniform();
if ((r1 + r2) <= 1.f) {
return triangle.vertices[0] + r1 * triangle.u + r2 * triangle.v;
}
}
}
}
| #include "sampling.h"
namespace {
static constexpr float M_2PI = 2.f * M_PI;
__thread static xorshift64star<float> uniform{4};
}
namespace sampling {
std::pair<Vec, float> hemisphere() {
// draw coordinates
float u1 = uniform();
float u2 = uniform();
// u1 is cos(theta)
auto z = u1;
auto r = sqrtf(fmax(0.f, 1.f - z*z));
auto phi = M_2PI * u2;
auto x = r * cosf(phi);
auto y = r * sinf(phi);
return std::make_pair(Vec{x, y, z}, u1);
}
/**
* Sample a point on the triangle.
*
* return point in world space.
*/
Vec triangle(const Triangle& triangle) {
while(true) {
float r1 = uniform();
float r2 = uniform();
if ((r1 + r2) <= 1.f) {
return triangle.vertices[0] + r1 * triangle.u + r2 * triangle.v;
}
}
}
}
|
Add a test of "showState()" | #include <cppcutter.h>
#include "tuishogi.cpp"
namespace tuishogi {
void
test_isMated(void)
{
using namespace osl;
NumEffectState state((SimpleState(HIRATE)));
bool mated = isMated(state);
cut_assert_false(mated);
}
} // namespace tuishogi
| #include <cppcutter.h>
#include "tuishogi.cpp"
namespace tuishogi {
void
test_showState(void)
{
// Arrange
using namespace osl;
std::stringbuf string_out;
std::streambuf* std_out = std::cout.rdbuf(&string_out);
NumEffectState state((SimpleState(HIRATE)));
const char* expected = "\
P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\
P2 * -HI * * * * * -KA * \n\
P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\
P4 * * * * * * * * * \n\
P5 * * * * * * * * * \n\
P6 * * * * * * * * * \n\
P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\
P8 * +KA * * * * * +HI * \n\
P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\
+\n\
\n";
// Act
showState(state);
std::cout << std::flush;
std::cout.rdbuf(std_out);
// TODO assert it as a std::string
std::string str = string_out.str();
int len = str.length();
char* actual = new char[len+1];
memcpy(actual, str.c_str(), len+1);
// Assert
cut_assert_equal_string(expected, actual);
}
void
test_isMated(void)
{
using namespace osl;
NumEffectState state((SimpleState(HIRATE)));
bool mated = isMated(state);
cut_assert_false(mated);
}
} // namespace tuishogi
|
Make this testcase harder, to test the read case as well. | // RUN: %llvmgxx -S %s -o -
struct QChar {unsigned short X; QChar(unsigned short); } ;
struct Command {
Command(QChar c) : c(c) {}
unsigned int type : 4;
QChar c;
};
Command X(QChar('c'));
| // RUN: %llvmgxx -S %s -o -
struct QChar {unsigned short X; QChar(unsigned short); } ;
struct Command {
Command(QChar c) : c(c) {}
unsigned int type : 4;
QChar c;
};
Command X(QChar('c'));
void Foo(QChar );
void bar() { Foo(X.c); }
|
Use block `extern "C"` so can make function `static` | /* 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 <csignal>
#include <ncurses.h>
#include <cstdlib>
#include "signals.hh"
extern "C" void myexit(int i) {
endwin();
SIG_DFL(i);
}
namespace vick {
void setup_signal_handling() {
signal(SIGABRT, myexit);
signal(SIGFPE, myexit);
signal(SIGILL, myexit);
signal(SIGINT, myexit);
signal(SIGSEGV, myexit);
signal(SIGTERM, myexit);
}
}
| /* 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 <csignal>
#include <ncurses.h>
#include <cstdlib>
#include "signals.hh"
extern "C" {
static void myexit(int i) {
endwin();
SIG_DFL(i);
}
}
namespace vick {
void setup_signal_handling() {
signal(SIGABRT, myexit);
signal(SIGFPE, myexit);
signal(SIGILL, myexit);
signal(SIGINT, myexit);
signal(SIGSEGV, myexit);
signal(SIGTERM, myexit);
}
}
|
Add missing "env" so that test added in r327322 passes on Windows bots. | // RUN: CINDEXTEST_EDITING=1 LIBCLANG_DISABLE_CRASH_RECOVERY=1 c-index-test -test-load-source-reparse 2 none -remap-file-0=%S/Inputs/reparse-issue.h,%S/Inputs/reparse-issue.h-0 -remap-file-1=%S/Inputs/reparse-issue.h,%S/Inputs/reparse-issue.h-1 -- %s 2>&1 | FileCheck %s
#include "Inputs/reparse-issue.h"
// CHECK: reparse-issue.h:4:1:{1:1-1:1}: error: C++ requires a type specifier for all declarations
| // RUN: env CINDEXTEST_EDITING=1 LIBCLANG_DISABLE_CRASH_RECOVERY=1 c-index-test -test-load-source-reparse 2 none -remap-file-0=%S/Inputs/reparse-issue.h,%S/Inputs/reparse-issue.h-0 -remap-file-1=%S/Inputs/reparse-issue.h,%S/Inputs/reparse-issue.h-1 -- %s 2>&1 | FileCheck %s
#include "Inputs/reparse-issue.h"
// CHECK: reparse-issue.h:4:1:{1:1-1:1}: error: C++ requires a type specifier for all declarations
|
Disable ExtensionApiTest.Storage because it crashes the browser_tests too. | // 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"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
| // 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"
// This test is disabled. See bug 25746
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
|
Remove variable 'size' (not used) | #include <stdio.h>
#include <string.h> /* memcpy() */
#include <stdlib.h> /* rand() */
#include "quick.hpp"
#include "swap.hpp"
void quick(int *data, const int size_of_data)
{
return quick(data, 0, size_of_data - 1);
}
void quick(int *data, const int start, const int end)
{
int size = end - start + 1;
if(size <= 1) return; /* Base case */
/* Conquer */
int pivot = end; /* Set pivot */
int ps = start, pe = end - 1;
while(ps < pe)
{
while(ps < pe && data[ps] < data[pivot]) ++ps;
while(ps < pe && data[pe] >= data[pivot]) --pe;
if(ps < pe) swap(data[ps], data[pe]);
}
if(data[pe] > data[pivot]) swap(data[pe], data[pivot]);
/* Divide */
quick(data, start, pe);
quick(data, pe + 1, end);
}
| #include <stdio.h>
#include <string.h> /* memcpy() */
#include <stdlib.h> /* rand() */
#include "quick.hpp"
#include "swap.hpp"
void quick(int *data, const int size_of_data)
{
return quick(data, 0, size_of_data - 1);
}
void quick(int *data, const int start, const int end)
{
if(start >= end) return; /* Base case */
/* Conquer */
int pivot = end; /* Set pivot */
int ps = start, pe = end - 1;
while(ps < pe)
{
while(ps < pe && data[ps] < data[pivot]) ++ps;
while(ps < pe && data[pe] >= data[pivot]) --pe;
if(ps < pe) swap(data[ps], data[pe]);
}
if(data[pe] > data[pivot]) swap(data[pe], data[pivot]);
/* Divide */
quick(data, start, pe);
quick(data, pe + 1, end);
}
|
Correct OID for ECDSA param | #include <botan/botan.h>
#include <botan/ecdsa.h>
#include <memory>
#include <iostream>
using namespace Botan;
int main()
{
try
{
std::auto_ptr<RandomNumberGenerator> rng(
RandomNumberGenerator::make_rng());
EC_Domain_Params params = get_EC_Dom_Pars_by_oid("1.3.132.8");
std::cout << params.get_curve().get_p() << "\n";
std::cout << params.get_order() << "\n";
ECDSA_PrivateKey ecdsa(*rng, params);
}
catch(std::exception& e)
{
std::cout << e.what() << "\n";
}
}
| #include <botan/botan.h>
#include <botan/ecdsa.h>
#include <memory>
#include <iostream>
using namespace Botan;
int main()
{
try
{
std::auto_ptr<RandomNumberGenerator> rng(
RandomNumberGenerator::make_rng());
EC_Domain_Params params = get_EC_Dom_Pars_by_oid("1.3.132.0.8");
std::cout << params.get_curve().get_p() << "\n";
std::cout << params.get_order() << "\n";
ECDSA_PrivateKey ecdsa(*rng, params);
}
catch(std::exception& e)
{
std::cout << e.what() << "\n";
}
}
|
Add more hardcoded puzzles and a TODO. | #include "sparse_matrix.hpp" // SparseMatrix
#include "parser.hpp" // getRows, parsePuzzle
int main(int argc, char **argv) {
std::string puzzle =
"-----------0-\n"
"-----------00\n"
"----00--0000-\n"
"00000000000--\n"
"00000000000--\n"
"0000000000---\n"
"00000000-----\n"
"0000000------\n"
"00---00------";
SparseMatrix sm(getRows(parsePuzzle(puzzle)));
sm.findSolution(0);
return 0;
}
| #include "sparse_matrix.hpp" // SparseMatrix
#include "parser.hpp" // getRows, parsePuzzle
constexpr char puzzle28[] =
"-00--0000-\n"
"00--000000\n"
"00--000000\n"
"000--00000\n"
"00000--000\n"
"000000--00\n"
"000000--00\n"
"-0000--00-";
constexpr char puzzle42[] =
"-----------0-\n"
"-----------00\n"
"----00--0000-\n"
"00000000000--\n"
"00000000000--\n"
"0000000000---\n"
"00000000-----\n"
"0000000------\n"
"00---00------";
constexpr char puzzle54[] =
"0000-0000\n"
"000---000\n"
"000---000\n"
"00-----00\n"
"000000000\n"
"000000000\n"
"000000000\n"
"000000000";
int main(int argc, char **argv) {
SparseMatrix sm(getRows(parsePuzzle(puzzle54)));
sm.findSolution(0);
return 0;
}
// TODO: Move pretty_print.py into here to deduplicate the puzzle.
|
Add copyright header to wallet_text_fixture.cpp | #include "wallet/test/wallet_test_fixture.h"
#include "rpc/server.h"
#include "wallet/db.h"
#include "wallet/wallet.h"
WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
TestingSetup(chainName)
{
bitdb.MakeMock();
bool fFirstRun;
pwalletMain = new CWallet("wallet_test.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
RegisterWalletRPCCommands(tableRPC);
}
WalletTestingSetup::~WalletTestingSetup()
{
UnregisterValidationInterface(pwalletMain);
delete pwalletMain;
pwalletMain = NULL;
bitdb.Flush(true);
bitdb.Reset();
}
| // Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet/test/wallet_test_fixture.h"
#include "rpc/server.h"
#include "wallet/db.h"
#include "wallet/wallet.h"
WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
TestingSetup(chainName)
{
bitdb.MakeMock();
bool fFirstRun;
pwalletMain = new CWallet("wallet_test.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
RegisterWalletRPCCommands(tableRPC);
}
WalletTestingSetup::~WalletTestingSetup()
{
UnregisterValidationInterface(pwalletMain);
delete pwalletMain;
pwalletMain = NULL;
bitdb.Flush(true);
bitdb.Reset();
}
|
Remove dead includes in folly/executors | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <folly/executors/GlobalExecutor.h>
#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include <folly/portability/GTest.h>
#include <folly/synchronization/Baton.h>
#include <folly/system/HardwareConcurrency.h>
using namespace folly;
DECLARE_uint32(folly_global_cpu_executor_threads);
TEST(GlobalCPUExecutorTest, CPUThreadCountFlagSet) {
gflags::FlagSaver flagsaver;
FLAGS_folly_global_cpu_executor_threads = 100;
auto cpu_threadpool = dynamic_cast<folly::CPUThreadPoolExecutor*>(
folly::getGlobalCPUExecutor().get());
EXPECT_EQ(cpu_threadpool->numThreads(), 100);
}
| /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <folly/executors/GlobalExecutor.h>
#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include <folly/portability/GTest.h>
#include <folly/synchronization/Baton.h>
DECLARE_uint32(folly_global_cpu_executor_threads);
TEST(GlobalCPUExecutorTest, CPUThreadCountFlagSet) {
gflags::FlagSaver flagsaver;
FLAGS_folly_global_cpu_executor_threads = 100;
auto cpu_threadpool = dynamic_cast<folly::CPUThreadPoolExecutor*>(
folly::getGlobalCPUExecutor().get());
EXPECT_EQ(cpu_threadpool->numThreads(), 100);
}
|
Mark ExtensionApiTest.Storage as flaky. BUG=42943 TEST=none TBR=rafaelw | // 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"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) {
ASSERT_TRUE(RunExtensionTest("cookies")) << message_;
}
| // 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"
#if defined(OS_LINUX)
// See http://crbug.com/42943.
#define MAYBE_Storage FLAKY_Storage
#else
#define MAYBE_Storage Storage
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Storage) {
ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) {
ASSERT_TRUE(RunExtensionTest("cookies")) << message_;
}
|
Clear current context for window. | /*
* Copyright Regents of the University of Minnesota, 2016. This software is released under the following license: http://opensource.org/licenses/
* Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
*
* Code author(s):
* Dan Orban (dtorban)
*/
#include <display/graphics/VRGraphicsWindowNode.h>
namespace MinVR {
VRGraphicsWindowNode::~VRGraphicsWindowNode() {
}
void VRGraphicsWindowNode::render() {
startRender();
waitForRenderComplete();
synchronize();
}
void VRGraphicsWindowNode::startRender() {
setCurrentContext();
//TODO: load data
VRDisplayNode::render();
flush();
}
void VRGraphicsWindowNode::waitForRenderComplete() {
finish();
}
void VRGraphicsWindowNode::synchronize() {
swapBuffers();
}
void VRGraphicsWindowNode::addChild(VRGraphicsWindowChild* child) {
VRDisplayNode::addChild(child);
}
} /* namespace MinVR */
| /*
* Copyright Regents of the University of Minnesota, 2016. This software is released under the following license: http://opensource.org/licenses/
* Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
*
* Code author(s):
* Dan Orban (dtorban)
*/
#include <display/graphics/VRGraphicsWindowNode.h>
namespace MinVR {
VRGraphicsWindowNode::~VRGraphicsWindowNode() {
}
void VRGraphicsWindowNode::render() {
startRender();
waitForRenderComplete();
synchronize();
}
void VRGraphicsWindowNode::startRender() {
setCurrentContext();
//TODO: load data
VRDisplayNode::render();
flush();
}
void VRGraphicsWindowNode::waitForRenderComplete() {
finish();
}
void VRGraphicsWindowNode::synchronize() {
swapBuffers();
clearCurrentContext();
}
void VRGraphicsWindowNode::addChild(VRGraphicsWindowChild* child) {
VRDisplayNode::addChild(child);
}
} /* namespace MinVR */
|
Create useful binary tree, add some assets. | #include <iostream>
using namespace std;
struct node {
int val = 0;
node * l = nullptr;
node * r = nullptr;
};
inline node* build(node *head, int value){
node *son = new node;
son->val = value;
if (head == nullptr) return son;
node * aux = head, * nxt = head;
while(nxt != nullptr){
aux = nxt;
if (value > nxt->val) nxt = nxt->r;
else nxt = nxt->l;
}
if(value > aux-> val) aux->r = son;
else aux->l = son;
return head;
}
inline void show(node* head){
if (head==nullptr) return;
show(head->l);
cout << head->val << endl;
show(head->r);
}
int main(){
node *head = new node;
head->val = 5;
head = build(head, 45);
head = build(head, 20);
show(head);
return 0;
}
| #include <bits/stdc++.h>
using namespace std;
struct node{
int val;
node *left;
node *right;
node( int v ){
val = v;
left = nullptr;
right = nullptr;
}
node* insert(node *n, int val){
if(n == nullptr ) return new node(val);
if(n->val > val) n->left = insert(n->left, val);
else n->right = insert(n->right, val);
}
void show(node *n){
if(n!=nullptr){
show(n->left);
cout << n->val << " ";
show(n->right);
}
}
string gHash(node *n) {
string hash="";
if(n->right!=nullptr)
hash += "R"+gHash(n->right);
if(n->left!=nullptr)
hash += "L"+gHash(n->left);
return hash+"!";
}
};
int main(){
node * root = new node(7);
root->insert(root,1);
root->insert(root,-1);
root->show(root);
cout << endl<<root->gHash(root) <<endl;
return 0;
}
|
Fix crash on shutdown caused by a dependency loop |
#include <gloperate/input/AbstractEventProvider.h>
#include <gloperate/input/AbstractEvent.h>
#include <gloperate/navigation/AbstractMapping.h>
namespace gloperate
{
AbstractEventProvider::AbstractEventProvider()
{
}
AbstractEventProvider::~AbstractEventProvider()
{
for (AbstractMapping * mapping : m_mappings)
{
mapping->removeProvider(this);
}
}
void AbstractEventProvider::registerMapping(AbstractMapping * mapping)
{
m_mappings.push_back(mapping);
}
void AbstractEventProvider::deregisterMapping(AbstractMapping * mapping)
{
m_mappings.remove(mapping);
}
void AbstractEventProvider::passEvent(AbstractEvent * event)
{
for (AbstractMapping * mapping : m_mappings)
{
mapping->processEvent(event);
}
}
} // namespace gloperate
|
#include <gloperate/input/AbstractEventProvider.h>
#include <gloperate/input/AbstractEvent.h>
#include <gloperate/navigation/AbstractMapping.h>
namespace gloperate
{
AbstractEventProvider::AbstractEventProvider()
{
}
AbstractEventProvider::~AbstractEventProvider()
{
// Unregister from mappings
// Note: removeProvider calls registerMapping in turn, which removes the mapping
// from m_mappings. Therefore, a for-loop would get into trouble, so we iterate
// like this until the list is empty.
while (!m_mappings.empty()) {
AbstractMapping * mapping = m_mappings.front();
mapping->removeProvider(this);
}
}
void AbstractEventProvider::registerMapping(AbstractMapping * mapping)
{
m_mappings.push_back(mapping);
}
void AbstractEventProvider::deregisterMapping(AbstractMapping * mapping)
{
m_mappings.remove(mapping);
}
void AbstractEventProvider::passEvent(AbstractEvent * event)
{
for (AbstractMapping * mapping : m_mappings)
{
mapping->processEvent(event);
}
}
} // namespace gloperate
|
Add cel shading scene to default bencharks | /*
* 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",
"shading:shading=gouraud",
"shading:shading=blinn-phong-inf",
"shading:shading=phong",
"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",
"shading:shading=gouraud",
"shading:shading=blinn-phong-inf",
"shading:shading=phong",
"shading:shading=cel",
"cube",
"clear"
};
}
|
Change the prefered content size of the anomaly browser | #include "webview.h"
#include <QPaintEvent>
WebView::WebView(QWidget *parent)
: QWebView(parent)
, inLoading(false)
{
connect(this, SIGNAL(loadStarted()), this, SLOT(newPageLoading()));
connect(this, SIGNAL(loadFinished(bool)), this, SLOT(pageLoaded(bool)));
}
void WebView::paintEvent(QPaintEvent *event)
{
if (inLoading && loadingTime.elapsed() < 750) {
QPainter painter(this);
painter.setBrush(Qt::white);
painter.setPen(Qt::NoPen);
foreach (const QRect &rect, event->region().rects()) {
painter.drawRect(rect);
}
} else {
QWebView::paintEvent(event);
}
}
void WebView::newPageLoading()
{
inLoading = true;
loadingTime.start();
}
void WebView::pageLoaded(bool)
{
inLoading = false;
update();
}
| #include "webview.h"
#include <QPaintEvent>
#include <QWebFrame>
WebView::WebView(QWidget *parent)
: QWebView(parent)
, inLoading(false)
{
connect(this, SIGNAL(loadStarted()), this, SLOT(newPageLoading()));
connect(this, SIGNAL(loadFinished(bool)), this, SLOT(pageLoaded(bool)));
page()->setPreferredContentsSize(QSize(1024, 768));
}
void WebView::paintEvent(QPaintEvent *event)
{
if (inLoading && loadingTime.elapsed() < 750) {
QPainter painter(this);
painter.setBrush(Qt::white);
painter.setPen(Qt::NoPen);
foreach (const QRect &rect, event->region().rects()) {
painter.drawRect(rect);
}
} else {
QWebView::paintEvent(event);
}
}
void WebView::newPageLoading()
{
inLoading = true;
loadingTime.start();
}
void WebView::pageLoaded(bool)
{
inLoading = false;
update();
}
|
Fix SRM 144, Div 2, Problem ImageDithering | #include <iostream>
#include <vector>
#include <assert.h>
using namespace std;
class ImageDithering {
public:
int count(string dithered, vector<string> screen) {
unsigned d[26];
for (int i = 0; i < 26; i++) {
d[i] = 0;
}
for (unsigned i = 0; i < dithered.length(); i++) {
d[dithered[i] - '0'] = 1;
}
int count = 0;
for (vector<string>::iterator str = screen.begin(); str != screen.end(); ++str) {
for (unsigned i = 0; i < str->length(); i++) {
count += d[(*str)[i] - '0'];
}
}
return count;
}
};
int main()
{
ImageDithering id;
string sc[] = {
"AAAAAAAA",
"ABWBWBWA",
"AWBWBWBA",
"ABWBWBWA",
"AWBWBWBA",
"AAAAAAAA"
};
vector<string> scr1(sc, sc + 6);
assert( id.count("BW", scr1) == 24);
return 0;
}
| #include <iostream>
#include <vector>
#include <assert.h>
using namespace std;
class ImageDithering {
public:
int count(string dithered, vector<string> screen) {
unsigned d[26];
for (int i = 0; i < 26; i++) {
d[i] = 0;
}
for (unsigned i = 0; i < dithered.length(); i++) {
d[dithered[i] - 'A'] = 1;
}
int count = 0;
for (vector<string>::iterator str = screen.begin(); str != screen.end(); ++str) {
for (unsigned i = 0; i < str->length(); i++) {
count += d[(*str)[i] - 'A'];
}
}
return count;
}
};
int main()
{
ImageDithering id;
string sc1[] = {
"AAAAAAAA",
"ABWBWBWA",
"AWBWBWBA",
"ABWBWBWA",
"AWBWBWBA",
"AAAAAAAA"
};
vector<string> scr1(sc1, sc1 + 6);
assert( id.count("BW", scr1) == 24);
string sc2[] = {"OT", "QF", "KD", "HR", "VV", "XB"};
vector<string> scr2(sc2, sc2 + 6);
assert( id.count("JSPQKYRME", scr2) == 3);
cout << id.count("JSPQKYRME", scr2);
return 0;
}
|
Revert "Alterando uma func (usando funcoes do CP3)" | ll rotatingCalipers(){
int ans = 0;
int i = 0, j = dn.size()-1;
while(i < (int)up.size() - 1 || j > 0){
// Entrou aqui: up[i] e dn[j] eh um antipodal pair
ans = max(ans, dist2(up[i],dn[j]));
if(i == (int)up.size()-1) j--;
else if(j == 0) i++;
else{
// Verifica qual o menor angulo a ser rotacionado p utilizar na rotacao
if(ccw(point(0,0), toVec(up[i], up[i+1]), toVec(dn[j],dn[j-1])))
i++;
else
j--;
}
}
return ans;
}
| ll rotatingCalipers(){
int ans = 0;
int i = 0, j = dn.size()-1;
while(i < (int)up.size() - 1 || j > 0){
// Entrou aqui: up[i] e dn[j] eh um antipodal pair
ans = max(ans, dist2(up[i],dn[j]));
if(i == (int)up.size()-1) j--;
else if(j == 0) i++;
else{
// Verifica qual o menor angulo a ser rotacionado p utilizar na rotacao
if((up[i+1].second - up[i].second) * (dn[j].first - dn[j-1].first)
> (dn[j].second - dn[j-1].second) * (up[i+1].first - up[i].first ))
i++;
else
j--;
}
}
return ans;
}
|
Remove requirement for USB library if not required | /* mbed Microcontroller Library
* Copyright (c) 2021 ARM Limited
* Copyright (c) 2021 Embedded Planet, Inc.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "USBSerial.h"
#include "platform/mbed_retarget.h"
#ifndef MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE
#define MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE 0
#endif
#if MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE
/* Retarget stdio to USBSerial */
mbed::FileHandle *mbed::mbed_target_override_console(int fd)
{
static USBSerial usb_serial;
return &usb_serial;
}
#endif
| /* mbed Microcontroller Library
* Copyright (c) 2021 ARM Limited
* Copyright (c) 2021 Embedded Planet, Inc.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE
#define MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE 0
#endif
#if MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE
#include "USBSerial.h"
#include "platform/mbed_retarget.h"
/* Retarget stdio to USBSerial */
mbed::FileHandle *mbed::mbed_target_override_console(int fd)
{
static USBSerial usb_serial;
return &usb_serial;
}
#endif
|
Fix case in name of included header | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// A simplified M113 driveline.
//
// =============================================================================
#include "m113/M113_simpleDriveline.h"
using namespace chrono;
using namespace chrono::vehicle;
namespace m113 {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
const double M113_SimpleDriveline::m_diff_maxBias = 3;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
M113_SimpleDriveline::M113_SimpleDriveline() : ChSimpleTrackDriveline("M113_SimpleDriveline") {
}
} // end namespace hmmwv
| // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// A simplified M113 driveline.
//
// =============================================================================
#include "m113/M113_SimpleDriveline.h"
using namespace chrono;
using namespace chrono::vehicle;
namespace m113 {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
const double M113_SimpleDriveline::m_diff_maxBias = 3;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
M113_SimpleDriveline::M113_SimpleDriveline() : ChSimpleTrackDriveline("M113_SimpleDriveline") {
}
} // end namespace hmmwv
|
Add timestamp to console log output | #include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/os/Console.h"
#include <stdio.h>
namespace capu
{
ConsoleLogAppender::~ConsoleLogAppender()
{
}
void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
{
m_logMutex.lock();
switch(logMessage.getLogLevel())
{
case LL_TRACE:
Console::Print(Console::WHITE, "[ Trace ] ");
break;
default:
case LL_DEBUG :
Console::Print(Console::WHITE, "[ Debug ] ");
break;
case LL_INFO :
Console::Print(Console::GREEN, "[ Info ] ");
break;
case LL_WARN :
Console::Print(Console::YELLOW, "[ Warn ] ");
break;
case LL_ERROR :
Console::Print(Console::RED, "[ Error ] ");
break;
case LL_FATAL :
Console::Print(Console::RED, "[ Fatal ] ");
break;
}
Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
Console::Print(" | %s\n", logMessage.getLogMessage());
Console::Flush();
m_logMutex.unlock();
}
}
| #include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/os/Console.h"
#include "capu/os/Time.h"
#include <stdio.h>
namespace capu
{
ConsoleLogAppender::~ConsoleLogAppender()
{
}
void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
{
m_logMutex.lock();
const uint64_t now = Time::GetMilliseconds();
Console::Print(Console::WHITE, "%.3f ", now/1000.0);
switch(logMessage.getLogLevel())
{
case LL_TRACE:
Console::Print(Console::WHITE, "[ Trace ] ");
break;
default:
case LL_DEBUG :
Console::Print(Console::WHITE, "[ Debug ] ");
break;
case LL_INFO :
Console::Print(Console::GREEN, "[ Info ] ");
break;
case LL_WARN :
Console::Print(Console::YELLOW, "[ Warn ] ");
break;
case LL_ERROR :
Console::Print(Console::RED, "[ Error ] ");
break;
case LL_FATAL :
Console::Print(Console::RED, "[ Fatal ] ");
break;
}
Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
Console::Print(" | %s\n", logMessage.getLogMessage());
Console::Flush();
m_logMutex.unlock();
}
}
|
Handle the null encoder properly in the encoder fuzz | #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;
}
#if FUZZ_IMAGEMAGICK_ENCODER_WRITE || BUILD_MAIN
Magick::Blob outBlob;
try {
image.write(&outBlob, FUZZ_ENCODER);
}
catch (Magick::Exception &e) {
}
#endif
return 0;
}
#include "travis.cc"
| #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) {
std::string encoder = FUZZ_ENCODER;
// Due to macro foolishness, if we pass -DFUZZ_IMAGEMAGICK_ENCODER=NULL,
// FUZZ_ENCODER ends up being "__null".
if (encoder == "__null") {
encoder = "NULL";
}
const Magick::Blob blob(Data, Size);
Magick::Image image;
image.magick(encoder);
image.fileName(std::string(encoder) + ":");
try {
image.read(blob);
}
catch (Magick::Exception &e) {
return 0;
}
#if FUZZ_IMAGEMAGICK_ENCODER_WRITE || BUILD_MAIN
Magick::Blob outBlob;
try {
image.write(&outBlob, encoder);
}
catch (Magick::Exception &e) {
}
#endif
return 0;
}
#include "travis.cc"
|
Change the entire logic of Quickselect | #include <stdio.h>
#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/quicksort.hpp"
int get_index_smallest(const int k, int *data, const int start, const int end)
{
if(k < 0 || k > end) return -1; /* Base case */
int p = partition(data, start, end);
if(k == 0) return data[start];
else if(p - start == k) return data[p];
else if(p - start > k) return get_index_smallest(k, data, start, p - 1);
else return get_index_smallest(k - p - 1, data, p + 1, end);
}
int main(void)
{
int k;
printf("Enter k= ");
scanf("%d", &k);
const int size = 100000;
int *data = make_random_data(size);
printf("%d\n", get_index_smallest(k, data, 0, size - 1));
free_random_data(data);
return 0;
}
| #include <stdio.h>
#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/quicksort.hpp"
int quickselection(const int k, int *data, const int start, const int end)
{
if(start >= end) return data[start];
int pivot = partition(data, start, end);
int p = pivot - start;
if(p > k - 1) return quickselection(k, data, start, pivot - 1);
if(p < k - 1) return quickselection(k - (p + 1), data, pivot + 1, end);
return data[pivot];
}
int main(void)
{
const int size = 100000;
int *data = make_random_data(size);
int k;
printf("Enter k= ");
scanf("%d", &k);
if(k <= 0 || k > size)
{
printf("Error: Out of range.\n");
return 1;
}
printf("%d\n", quickselection(k, data, 0, size - 1));
free_random_data(data);
return 0;
}
|
Fix compile error when rtc_enable_protobuf is false | /*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "test/testsupport/perf_test_histogram_writer.h"
namespace webrtc {
namespace test {
PerfTestResultWriter* CreateHistogramWriter() {
RTC_NOTREACHED() << "Cannot run perf tests with rtc_enable_protobuf = false. "
"Perf write results as protobufs.";
}
} // namespace test
} // namespace webrtc
| /*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "test/testsupport/perf_test_histogram_writer.h"
namespace webrtc {
namespace test {
PerfTestResultWriter* CreateHistogramWriter() {
RTC_NOTREACHED() << "Cannot run perf tests with rtc_enable_protobuf = false. "
"Perf write results as protobufs.";
return nullptr;
}
} // namespace test
} // namespace webrtc
|
Fix uninitialized variable which was causing valgrind failures. (the "found" variable was not initialised to "false"). | #include "findTypeVariables.h"
#include "type.h"
#include "symbol.h"
#include "symtab.h"
FindVariableType::FindVariableType(Vec<VariableType*>* init_variableTypes) {
variableTypes = init_variableTypes;
}
void FindVariableType::preProcessSymbol(Symbol* symbol) {
if (dynamic_cast<TypeSymbol*>(symbol)) {
forv_Vec(VariableType, variableType, *variableTypes) {
if (variableType == symbol->type) {
found = true;
}
}
}
}
void FindVariableType::preProcessType(Type* type) {
if (dynamic_cast<VariableType*>(type)) {
forv_Vec(VariableType, variableType, *variableTypes) {
if (variableType == type) {
found = true;
}
}
}
}
bool functionContainsVariableType(FnSymbol* fn,
Vec<VariableType*>* variableTypes) {
FindVariableType* traversal = new FindVariableType(variableTypes);
TRAVERSE(fn, traversal, true);
return traversal->found;
}
| #include "findTypeVariables.h"
#include "type.h"
#include "symbol.h"
#include "symtab.h"
FindVariableType::FindVariableType(Vec<VariableType*>* init_variableTypes) {
found = false;
variableTypes = init_variableTypes;
}
void FindVariableType::preProcessSymbol(Symbol* symbol) {
if (dynamic_cast<TypeSymbol*>(symbol)) {
forv_Vec(VariableType, variableType, *variableTypes) {
if (variableType == symbol->type) {
found = true;
}
}
}
}
void FindVariableType::preProcessType(Type* type) {
if (dynamic_cast<VariableType*>(type)) {
forv_Vec(VariableType, variableType, *variableTypes) {
if (variableType == type) {
found = true;
}
}
}
}
bool functionContainsVariableType(FnSymbol* fn,
Vec<VariableType*>* variableTypes) {
FindVariableType* traversal = new FindVariableType(variableTypes);
TRAVERSE(fn, traversal, true);
return traversal->found;
}
|
Add proper cut on position | #include "./SDACalculatePositions.h"
SDACalculatePositions::SDACalculatePositions(const char* name, const char* title,
const char* in_file_suffix, const char* out_file_suffix, const double threshold,
const double positionCut)
: JPetCommonAnalysisModule( name, title, in_file_suffix, out_file_suffix), fCut(positionCut)
{
fSelectedThreshold = threshold;
}
SDACalculatePositions::~SDACalculatePositions(){}
void SDACalculatePositions::begin()
{
}
void SDACalculatePositions::exec()
{
fReader->getEntry(fEvent);
JPetLOR& fLOR = dynamic_cast< JPetLOR& > ( fReader->getData() );
JPetHit hit = fLOR.getFirstHit();
hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0 );
fLOR.setFirstHit( hit );
hit = fLOR.getSecondHit();
hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0 );
fLOR.setSecondHit( hit );
if( fLOR.getFirstHit().getPosAlongStrip() > fCut )
{
fEvent++;
return;
}
fWriter->write(fLOR);
fEvent++;
}
void SDACalculatePositions::end()
{
}
| #include "./SDACalculatePositions.h"
SDACalculatePositions::SDACalculatePositions(const char* name, const char* title,
const char* in_file_suffix, const char* out_file_suffix, const double threshold,
const double positionCut)
: JPetCommonAnalysisModule( name, title, in_file_suffix, out_file_suffix), fCut(positionCut)
{
fSelectedThreshold = threshold;
}
SDACalculatePositions::~SDACalculatePositions(){}
void SDACalculatePositions::begin()
{
}
void SDACalculatePositions::exec()
{
fReader->getEntry(fEvent);
JPetLOR& fLOR = dynamic_cast< JPetLOR& > ( fReader->getData() );
JPetHit hit = fLOR.getFirstHit();
hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0 );
fLOR.setFirstHit( hit );
hit = fLOR.getSecondHit();
hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0 );
fLOR.setSecondHit( hit );
if( fabs(fLOR.getFirstHit().getPosAlongStrip()) > fCut && fabs(fLOR.getSecondHit().getPosAlongStrip()) > fCut )
{
fEvent++;
return;
}
fWriter->write(fLOR);
fEvent++;
}
void SDACalculatePositions::end()
{
}
|
Set up a native screen on Windows | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/browser_main_parts.h"
#include "browser/browser_context.h"
#include "browser/web_ui_controller_factory.h"
#include "net/proxy/proxy_resolver_v8.h"
namespace brightray {
BrowserMainParts::BrowserMainParts() {
}
BrowserMainParts::~BrowserMainParts() {
}
void BrowserMainParts::PreMainMessageLoopRun() {
browser_context_.reset(CreateBrowserContext());
browser_context_->Initialize();
web_ui_controller_factory_.reset(
new WebUIControllerFactory(browser_context_.get()));
content::WebUIControllerFactory::RegisterFactory(
web_ui_controller_factory_.get());
}
void BrowserMainParts::PostMainMessageLoopRun() {
browser_context_.reset();
}
int BrowserMainParts::PreCreateThreads() {
#if defined(OS_WIN)
net::ProxyResolverV8::CreateIsolate();
#else
net::ProxyResolverV8::RememberDefaultIsolate();
#endif
return 0;
}
BrowserContext* BrowserMainParts::CreateBrowserContext() {
return new BrowserContext;
}
} // namespace brightray
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/browser_main_parts.h"
#include "browser/browser_context.h"
#include "browser/web_ui_controller_factory.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/gfx/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
namespace brightray {
BrowserMainParts::BrowserMainParts() {
}
BrowserMainParts::~BrowserMainParts() {
}
void BrowserMainParts::PreMainMessageLoopRun() {
browser_context_.reset(CreateBrowserContext());
browser_context_->Initialize();
web_ui_controller_factory_.reset(
new WebUIControllerFactory(browser_context_.get()));
content::WebUIControllerFactory::RegisterFactory(
web_ui_controller_factory_.get());
#if defined(OS_WIN)
gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen());
#endif
}
void BrowserMainParts::PostMainMessageLoopRun() {
browser_context_.reset();
}
int BrowserMainParts::PreCreateThreads() {
#if defined(OS_WIN)
net::ProxyResolverV8::CreateIsolate();
#else
net::ProxyResolverV8::RememberDefaultIsolate();
#endif
return 0;
}
BrowserContext* BrowserMainParts::CreateBrowserContext() {
return new BrowserContext;
}
} // namespace brightray
|
Handle AppleClang 9 and 10 in XFAILs for aligned allocation tests | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// aligned allocation functions are not provided prior to macosx10.13
// XFAIL: availability=macosx10.12
// XFAIL: availability=macosx10.11
// XFAIL: availability=macosx10.10
// XFAIL: availability=macosx10.9
// XFAIL: availability=macosx10.8
// XFAIL: availability=macosx10.7
#include <new>
#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
# error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it"
#endif
int main() { }
| //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// Aligned allocation functions are not provided prior to macosx10.13, but
// AppleClang <= 10 does not know about this restriction and always enables them.
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.12
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.11
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.10
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.9
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.8
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.7
#include <new>
#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
# error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it"
#endif
int main() { }
|
Indent code to more or less visualize the indentation of the outputed python code. | #include "generator.h"
#include <iostream>
#include <fstream>
using namespace Mugen;
CharacterGenerator::CharacterGenerator(const std::string & filename):
filename(filename){
}
CharacterGenerator::~CharacterGenerator(){
}
void CharacterGenerator::output(const std::string & file){
Mugen::PythonStream out;
out.open(file);
out << "import mugen" << PythonStream::endl;
out << "class TestCharacter(mugen.Character):" << PythonStream::endl;
out << PythonStream::indent;
out << "def __init__(self):" << PythonStream::endl;
out << PythonStream::indent;
out << "self.setName('TestCharacter')" << PythonStream::endl;
out.clearIndents();
out << "char = TestCharacter()" << PythonStream::endl;
out << "print char.name" << PythonStream::endl;
out.close();
} | #include "generator.h"
#include <iostream>
#include <fstream>
using namespace Mugen;
CharacterGenerator::CharacterGenerator(const std::string & filename):
filename(filename){
}
CharacterGenerator::~CharacterGenerator(){
}
void CharacterGenerator::output(const std::string & file){
Mugen::PythonStream out;
out.open(file);
out << "import mugen" << PythonStream::endl;
out << "class TestCharacter(mugen.Character):" << PythonStream::endl;
out << PythonStream::indent;
out << "def __init__(self):" << PythonStream::endl;
out << PythonStream::indent;
out << "self.setName('TestCharacter')" << PythonStream::endl;
out.clearIndents();
out << "char = TestCharacter()" << PythonStream::endl;
out << "print char.name" << PythonStream::endl;
out.close();
} |
Update servo_krs for runtime speed | #include<ros/ros.h>
#include<ics3/ics>
#include<servo_msgs/IdBased.h>
ics::ICS3* driver {nullptr};
ros::Publisher pub;
void move(const servo_msgs::IdBased::ConstPtr& msg) {
servo_msgs::IdBased result;
result.id = msg->id;
try {
result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
pub.publish(result);
} catch (std::runtime_error e) {
ROS_INFO("Communicate error: %s", e.what());
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "servo_krs_node");
ros::NodeHandle n {};
ros::NodeHandle pn {"~"};
std::string path {"/dev/ttyUSB0"};
pn.param<std::string>("path", path, path);
ics::ICS3 ics {path.c_str()};
driver = &ics;
ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
ros::spin();
return 0;
}
| #include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>
ics::ICS3* driver {nullptr};
ros::Publisher pub;
void move(const servo_msgs::IdBased::ConstPtr& msg) {
servo_msgs::IdBased result;
result.id = msg->id;
try {
result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
pub.publish(result);
} catch (std::runtime_error e) {
ROS_INFO("Communicate error: %s", e.what());
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "servo_krs_node");
ros::NodeHandle pn {"~"};
std::string path {"/dev/ttyUSB0"};
pn.param<std::string>("path", path, path);
ics::ICS3 ics {std::move(path)};
driver = &ics;
ros::NodeHandle n {};
ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
ros::spin();
return 0;
}
|
Set active_dialog_ before showing it, since showing a dialog can sometimes actually move to the next one in the queue instead. | // 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/browser/app_modal_dialog_queue.h"
#include "chrome/browser/browser_list.h"
void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
if (!active_dialog_) {
ShowModalDialog(dialog);
return;
}
app_modal_dialog_queue_.push(dialog);
}
void AppModalDialogQueue::ShowNextDialog() {
if (!app_modal_dialog_queue_.empty()) {
AppModalDialog* dialog = app_modal_dialog_queue_.front();
app_modal_dialog_queue_.pop();
ShowModalDialog(dialog);
} else {
active_dialog_ = NULL;
}
}
void AppModalDialogQueue::ActivateModalDialog() {
if (active_dialog_)
active_dialog_->ActivateModalDialog();
}
void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
dialog->ShowModalDialog();
active_dialog_ = dialog;
}
| // 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/browser/app_modal_dialog_queue.h"
#include "chrome/browser/browser_list.h"
void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
if (!active_dialog_) {
ShowModalDialog(dialog);
return;
}
app_modal_dialog_queue_.push(dialog);
}
void AppModalDialogQueue::ShowNextDialog() {
if (!app_modal_dialog_queue_.empty()) {
AppModalDialog* dialog = app_modal_dialog_queue_.front();
app_modal_dialog_queue_.pop();
ShowModalDialog(dialog);
} else {
active_dialog_ = NULL;
}
}
void AppModalDialogQueue::ActivateModalDialog() {
if (active_dialog_)
active_dialog_->ActivateModalDialog();
}
void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
// Set active_dialog_ before showing it, because ShowModalDialog can wind up
// calling ShowNextDialog in some cases, which will change active_dialog_.
active_dialog_ = dialog;
dialog->ShowModalDialog();
}
|
Add message of reading path | #include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>
ics::ICS3* driver {nullptr};
ros::Publisher pub;
void move(const servo_msgs::IdBased::ConstPtr& msg) {
servo_msgs::IdBased result;
try {
result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
result.id = msg->id;
pub.publish(result);
} catch (std::runtime_error e) {
ROS_INFO("Communicate error: %s", e.what());
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "servo_krs_node");
ros::NodeHandle pn {"~"};
std::string path {"/dev/ttyUSB0"};
pn.param<std::string>("path", path, path);
ics::ICS3 ics {std::move(path)};
driver = &ics;
ros::NodeHandle n {};
ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
ros::spin();
return 0;
}
| #include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>
ics::ICS3* driver {nullptr};
ros::Publisher pub;
void move(const servo_msgs::IdBased::ConstPtr& msg) {
servo_msgs::IdBased result;
try {
result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
result.id = msg->id;
pub.publish(result);
} catch (std::runtime_error e) {
ROS_INFO("Communicate error: %s", e.what());
}
}
int main(int argc, char** argv) {
ros::init(argc, argv, "servo_krs_node");
ros::NodeHandle pn {"~"};
std::string path {"/dev/ttyUSB0"};
pn.param<std::string>("path", path, path);
ROS_INFO("Open servo motor path: %s", path.c_str());
ics::ICS3 ics {std::move(path)};
driver = &ics;
ros::NodeHandle n {};
ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
ros::spin();
return 0;
}
|
Throw an exception when App.restart fails on Linux. | /**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include <kroll/kroll.h>
#include "../app_binding.h"
namespace ti
{
void AppBinding::Restart(const ValueList& args, KValueRef result)
{
Host* host = Host::GetInstance();
std::string cmdline(host->GetApplication()->arguments.at(0));
// Remove all quotes.
size_t i = cmdline.find('\"');
while (i != std::string::npos)
{
cmdline.replace(i, 1, "");
i = cmdline.find('\"');
}
std::string script = "\"" + cmdline + "\" &";
system(script.c_str());
host->Exit(0);
}
}
| /**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include <kroll/kroll.h>
#include "../app_binding.h"
namespace ti
{
void AppBinding::Restart(const ValueList& args, KValueRef result)
{
Host* host = Host::GetInstance();
std::string cmdline(host->GetApplication()->arguments.at(0));
// Remove all quotes.
size_t i = cmdline.find('\"');
while (i != std::string::npos)
{
cmdline.replace(i, 1, "");
i = cmdline.find('\"');
}
std::string script = "\"" + cmdline + "\" &";
if (system(script.c_str()) == -1)
throw ValueException::FromString("Failed to start new process.");
host->Exit(0);
}
}
|
Handle tmp dir on Android | #include <wangle/client/persistence/test/TestUtil.h>
namespace wangle {
std::string getPersistentCacheFilename() {
char filename[] = "/tmp/fbtls.XXXXXX";
int fd = mkstemp(filename);
close(fd);
EXPECT_TRUE(unlink(filename) != -1);
return std::string(filename);
}
}
| /*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <wangle/client/persistence/test/TestUtil.h>
#include <folly/experimental/TestUtil.h>
namespace wangle {
std::string getPersistentCacheFilename() {
folly::test::TemporaryFile file("fbtls");
return file.path().string();
}
}
|
Fix a typo that broke the posix build. | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/thread_local.h"
#include <pthread.h>
#include "base/logging.h"
namespace base {
// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
int error = pthread_key_create(&slot, NULL);
CHECK(error == 0);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
int error = pthread_key_delete(slot);
DCHECK(error == 0);
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
return pthread_getspecific(slot_);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
int error = pthread_setspecific(slot, value);
CHECK(error == 0);
}
} // namespace base
| // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/thread_local.h"
#include <pthread.h>
#include "base/logging.h"
namespace base {
// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
int error = pthread_key_create(&slot, NULL);
CHECK(error == 0);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
int error = pthread_key_delete(slot);
DCHECK(error == 0);
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
return pthread_getspecific(slot);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
int error = pthread_setspecific(slot, value);
CHECK(error == 0);
}
} // namespace base
|
Convert CFLF to LF. CRLF was causing this test to fail under Mac OS X. | // RUN: clang -fsyntax-only -verify %s
namespace A { // expected-error {{error: previous definition is here}}
int A;
void f() { A = 0; }
}
void f() { A = 0; } // expected-error {{error: unexpected namespace name 'A': expected expression}}
int A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}
class A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}
class B; // expected-error {{error: previous definition is here}}
namespace B {} // expected-error {{error: redefinition of 'B' as different kind of symbol}}
void C(); // expected-error {{error: previous definition is here}}
namespace C {} // expected-error {{error: redefinition of 'C' as different kind of symbol}}
| // RUN: clang -fsyntax-only -verify %s
namespace A { // expected-error {{error: previous definition is here}}
int A;
void f() { A = 0; }
}
void f() { A = 0; } // expected-error {{error: unexpected namespace name 'A': expected expression}}
int A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}
class A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}
class B; // expected-error {{error: previous definition is here}}
namespace B {} // expected-error {{error: redefinition of 'B' as different kind of symbol}}
void C(); // expected-error {{error: previous definition is here}}
namespace C {} // expected-error {{error: redefinition of 'C' as different kind of symbol}}
|
Test UTF-16 output of GetUserName | #include <unistd.h>
#include <gtest/gtest.h>
#include "getusername.h"
TEST(GetUserName,simple)
{
// allocate a WCHAR_T buffer to receive username
DWORD lpnSize = 64;
WCHAR_T lpBuffer[lpnSize];
BOOL result = GetUserName(lpBuffer, &lpnSize);
// GetUserName returns 1 on success
ASSERT_EQ(1, result);
// get expected username
const char *username = getlogin();
// GetUserName sets lpnSize to length of username including null
ASSERT_EQ(strlen(username)+1, lpnSize);
// TODO: ASSERT_STREQ(username, Utf16leToUtf8(lpBuffer))
}
| #include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"
using std::string;
using std::vector;
using SCXCoreLib::Utf16leToUtf8;
TEST(GetUserName,simple)
{
// allocate a WCHAR_T buffer to receive username
DWORD lpnSize = 64;
WCHAR_T lpBuffer[lpnSize];
BOOL result = GetUserName(lpBuffer, &lpnSize);
// GetUserName returns 1 on success
ASSERT_EQ(1, result);
// get expected username
string username = string(getlogin());
// GetUserName sets lpnSize to length of username including null
ASSERT_EQ(username.size()+1, lpnSize);
// copy UTF-16 bytes from lpBuffer to vector for conversion
vector<unsigned char> input(reinterpret_cast<unsigned char *>(&lpBuffer[0]),
reinterpret_cast<unsigned char *>(&lpBuffer[lpnSize-1]));
// convert to UTF-8 for assertion
string output;
Utf16leToUtf8(input, output);
EXPECT_EQ(username, output);
}
|
Add missing header that defines SANITIZER_CAN_USE_PREINIT_ARRAY | //===-- ubsan_init_standalone.cc ------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//
#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
# error "UBSan is not supported on this platform!"
#endif
#include "ubsan_init.h"
#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used))
void (*__local_ubsan_preinit)(void) = __ubsan::InitAsStandalone;
#else
// Use a dynamic initializer.
class UbsanStandaloneInitializer {
public:
UbsanStandaloneInitializer() {
__ubsan::InitAsStandalone();
}
};
static UbsanStandaloneInitializer ubsan_standalone_initializer;
#endif // SANITIZER_CAN_USE_PREINIT_ARRAY
| //===-- ubsan_init_standalone.cc ------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//
#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
# error "UBSan is not supported on this platform!"
#endif
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "ubsan_init.h"
#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used))
void (*__local_ubsan_preinit)(void) = __ubsan::InitAsStandalone;
#else
// Use a dynamic initializer.
class UbsanStandaloneInitializer {
public:
UbsanStandaloneInitializer() {
__ubsan::InitAsStandalone();
}
};
static UbsanStandaloneInitializer ubsan_standalone_initializer;
#endif // SANITIZER_CAN_USE_PREINIT_ARRAY
|
Fix wrong constructor argument in binary thresh | #include "binary_threshold.h"
namespace TooManyPeeps {
BinaryThreshold::BinaryThreshold(const cv::Mat& original, cv::Mat& result, int threshold)
: ProcessFilter(original, result) {
this->threshold = threshold;
}
BinaryThreshold::BinaryThreshold(cv::Mat& image, int threshold)
: BinaryThreshold(original, result, threshold) {
}
void BinaryThreshold::execute(void) {
cv::threshold(get_original(), get_result(), threshold, MAX_OUTPUT_VALUE, cv::THRESH_BINARY);
}
};
| #include "binary_threshold.h"
namespace TooManyPeeps {
BinaryThreshold::BinaryThreshold(const cv::Mat& original, cv::Mat& result, int threshold)
: ProcessFilter(original, result) {
this->threshold = threshold;
}
BinaryThreshold::BinaryThreshold(cv::Mat& image, int threshold)
: BinaryThreshold(image, image, threshold) {
}
void BinaryThreshold::execute(void) {
cv::threshold(get_original(), get_result(), threshold, MAX_OUTPUT_VALUE, cv::THRESH_BINARY);
}
};
|
Clean up allocated memory during shutdown in OS X NetworkStatus. | /**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
*/
#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>
namespace ti
{
void NetworkStatus::InitializeLoop()
{
}
void NetworkStatus::CleanupLoop()
{
}
bool NetworkStatus::GetStatus()
{
static SCNetworkReachabilityRef primaryTarget =
SCNetworkReachabilityCreateWithName(0, "www.google.com");
if (!primaryTarget)
return true;
SCNetworkConnectionFlags flags;
SCNetworkReachabilityGetFlags(primaryTarget, &flags);
if ((flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired))
return true;
static SCNetworkReachabilityRef secondaryTarget =
SCNetworkReachabilityCreateWithName(0, "www.yahoo.com");
if (!secondaryTarget)
return true;
SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
if ((flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired))
return true;
return false;
}
}
| /**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
*/
#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>
namespace ti
{
static SCNetworkReachabilityRef primaryTarget = 0;
static SCNetworkReachabilityRef secondaryTarget = 0;
void NetworkStatus::InitializeLoop()
{
primaryTarget = SCNetworkReachabilityCreateWithName(0, "www.google.com");
secondaryTarget = SCNetworkReachabilityCreateWithName(0, "www.yahoo.com");
}
void NetworkStatus::CleanupLoop()
{
if (primaryTarget)
CFRelease(primaryTarget);
if (secondaryTarget)
CFRelease(secondaryTarget);
}
bool NetworkStatus::GetStatus()
{
if (!primaryTarget)
return true;
SCNetworkConnectionFlags flags;
SCNetworkReachabilityGetFlags(primaryTarget, &flags);
if ((flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired))
return true;
if (!secondaryTarget)
return true;
SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
if ((flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired))
return true;
return false;
}
}
|
Update for webkit header moves | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "common/content_client.h"
#include "common/application_info.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/user_agent/user_agent_util.h"
namespace brightray {
ContentClient::ContentClient() {
}
ContentClient::~ContentClient() {
}
std::string ContentClient::GetProduct() const {
auto name = GetApplicationName();
RemoveChars(name, kWhitespaceASCII, &name);
return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str());
}
std::string ContentClient::GetUserAgent() const {
return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}
base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}
gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}
}
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "common/content_client.h"
#include "common/application_info.h"
#include "base/stringprintf.h"
#include "base/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/common/user_agent/user_agent_util.h"
namespace brightray {
ContentClient::ContentClient() {
}
ContentClient::~ContentClient() {
}
std::string ContentClient::GetProduct() const {
auto name = GetApplicationName();
RemoveChars(name, kWhitespaceASCII, &name);
return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str());
}
std::string ContentClient::GetUserAgent() const {
return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}
base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}
gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}
}
|
Print Preview: Fix typo from r78639. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/print_preview_ui.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"
PrintPreviewUI::PrintPreviewUI(TabContents* contents)
: WebUI(contents),
html_source_(new PrintPreviewUIHTMLSource()) {
// PrintPreviewUI owns |handler|.
PrintPreviewHandler* handler = new PrintPreviewHandler();
AddMessageHandler(handler->Attach(this));
// Set up the chrome://print/ source.
contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}
PrintPreviewUI::~PrintPreviewUI() {
}
PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
return html_source_.get();
}
void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
FundamentalValue pages_count(expected_pages_count);
CallJavascriptFunction("createPDFPlugin", pages_count);
}
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/print_preview_ui.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"
PrintPreviewUI::PrintPreviewUI(TabContents* contents)
: WebUI(contents),
html_source_(new PrintPreviewUIHTMLSource()) {
// PrintPreviewUI owns |handler|.
PrintPreviewHandler* handler = new PrintPreviewHandler();
AddMessageHandler(handler->Attach(this));
// Set up the chrome://print/ source.
contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}
PrintPreviewUI::~PrintPreviewUI() {
}
PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
return html_source_.get();
}
void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
FundamentalValue pages_count(expected_pages_count);
CallJavascriptFunction("updatePrintPreview", pages_count);
}
|
Fix debug messages in library when removing file | #include <patlms/util/remove_file.h>
#include <patlms/util/detail/cant_remove_file_exception.h>
#include <string>
#include <cstring>
#include <cerrno>
#include <boost/log/trivial.hpp>
using namespace std;
namespace util
{
void RemoveFile(const std::string &path, detail::SystemInterfacePtr system) {
BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemovePidFile: Function call with (path=" << path << ")";
int ret = system->unlink(path.c_str());
if (ret < 0) {
BOOST_LOG_TRIVIAL(error) << "libpatlms::util::RemovePidFile: Couldn't remove pid file: " << strerror(errno);
throw detail::CantRemoveFileException();
}
BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemovePidFile: Done";
}
}
| #include <patlms/util/remove_file.h>
#include <patlms/util/detail/cant_remove_file_exception.h>
#include <string>
#include <cstring>
#include <cerrno>
#include <boost/log/trivial.hpp>
using namespace std;
namespace util
{
void RemoveFile(const std::string &path, detail::SystemInterfacePtr system) {
BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemoveFile: Function call with (path=" << path << ")";
int ret = system->unlink(path.c_str());
if (ret < 0) {
BOOST_LOG_TRIVIAL(error) << "libpatlms::util::RemoveFile: Couldn't remove file: " << strerror(errno);
throw detail::CantRemoveFileException();
}
BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemoveFile: Done";
}
}
|
Add explicit conversion to bool. | // This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 "generic_tokenizer.h"
#include "generic_tokenizer_factory.h"
namespace ufal {
namespace morphodita {
tokenizer* generic_tokenizer_factory::new_tokenizer() const {
return new generic_tokenizer(version);
}
bool generic_tokenizer_factory::load(istream& is) {
version = is.get();
return is;
}
} // namespace morphodita
} // namespace ufal
| // This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 "generic_tokenizer.h"
#include "generic_tokenizer_factory.h"
namespace ufal {
namespace morphodita {
tokenizer* generic_tokenizer_factory::new_tokenizer() const {
return new generic_tokenizer(version);
}
bool generic_tokenizer_factory::load(istream& is) {
version = is.get();
return bool(is);
}
} // namespace morphodita
} // namespace ufal
|
Implement krs send posture method. | #include "impl_send_posture.hpp"
#include "servo_msgs/KrsServoDegree.h"
std::map<std::string, const SendPosture*> SendPostureFactory::sends;
const SendPosture* SendPostureFactory::get(const std::string& name, ros::NodeHandle& nh) {
std::map<std::string, const SendPosture*>::const_iterator found_it = sends.find(name);
if (found_it != sends.end()) return create(name, nh);
return found_it->second;
}
const SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
if (name == "krs") {
sends["krs"] = new KrsSendPosture(nh);
return sends.at("krs");
}
return NULL;
}
KrsSendPosture::KrsSendPosture(ros::NodeHandle& nh) : nh(nh) {
pub = nh.advertise<servo_msgs::KrsServoDegree>("cmd_krs", 16);
nh.getParam("id_vec", id_vec);
}
void KrsSendPosture::sendPosture(std::vector<double>& posture) {
}
| #include "impl_send_posture.hpp"
#include "algorithm"
#include "servo_msgs/KrsServoDegree.h"
std::map<std::string, const SendPosture*> SendPostureFactory::sends;
const SendPosture* SendPostureFactory::get(const std::string& name, ros::NodeHandle& nh) {
std::map<std::string, const SendPosture*>::const_iterator found_it = sends.find(name);
if (found_it != sends.end()) return create(name, nh);
return found_it->second;
}
const SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
if (name == "krs") {
sends["krs"] = new KrsSendPosture(nh);
return sends.at("krs");
}
return NULL;
}
KrsSendPosture::KrsSendPosture(ros::NodeHandle& nh) : nh(nh) {
pub = nh.advertise<servo_msgs::KrsServoDegree>("cmd_krs", 16);
nh.getParam("id_vec", id_vec);
}
void KrsSendPosture::sendPosture(std::vector<double>& posture) {
servo_msgs::KrsServoDegree msg;
std::vector<double>::size_type length = std::min(posture.size(), id_vec.size());
for (std::vector<double>::size_type i = 0; i < length; i++) {
msg.id = id_vec[i];
msg.angle = posture[i];
pub.publish(msg);
}
}
|
Fix compile errors on Linux | #include "reg_language_translator.h"
#include "orz/types.h"
namespace Reg {
namespace Internal {
// TODO: Centralize (de)serialization the same way as for keyboard events
boost::optional<LanguageTranslator::external_type> LanguageTranslator::get_value(internal_type const sval) {
if (sval == "English") {
return Intl::Language::English;
}
if (sval == "Swedish") {
return Intl::Language::Swedish;
}
auto val = FromAString<int>(sval);
if (val == 0) return Intl::Language::English;
if (val == 1) return Intl::Language::Swedish;
return boost::none;
}
boost::optional<LanguageTranslator::internal_type> LanguageTranslator::put_value(external_type const& val) {
if (val == Intl::Language::English) {
return "English";
}
if (val == Intl::Language::Swedish) {
return "Swedish";
}
return boost::none;
}
}
}
| #include "reg_language_translator.h"
#include "orz/types.h"
namespace Reg {
namespace Internal {
// TODO: Centralize (de)serialization the same way as for keyboard events
boost::optional<LanguageTranslator::external_type> LanguageTranslator::get_value(internal_type const sval) {
if (sval == "English") {
return Intl::Language::English;
}
if (sval == "Swedish") {
return Intl::Language::Swedish;
}
auto val = FromAString<int>(sval);
if (val == 0) return Intl::Language::English;
if (val == 1) return Intl::Language::Swedish;
return boost::none;
}
boost::optional<LanguageTranslator::internal_type> LanguageTranslator::put_value(external_type const& val) {
if (val == Intl::Language::English) {
return std::string("English");
}
if (val == Intl::Language::Swedish) {
return std::string("Swedish");
}
return boost::none;
}
}
}
|
Update bounding box in MeshNode::setTransformation. | #include "./mesh_node.h"
#include <string>
#include "./graphics/gl.h"
MeshNode::MeshNode(std::string assetFilename, int meshIndex,
std::shared_ptr<Graphics::Mesh> mesh,
Eigen::Matrix4f transformation)
: assetFilename(assetFilename), meshIndex(meshIndex), mesh(mesh),
transformation(transformation)
{
obb = mesh->obb * transformation;
}
MeshNode::~MeshNode()
{
}
void MeshNode::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (!isVisible)
return;
renderData.modelMatrix = transformation;
mesh->render(gl, managers, renderData);
}
Eigen::Matrix4f MeshNode::getTransformation()
{
return this->transformation;
}
void MeshNode::setTransformation(Eigen::Matrix4f transformation)
{
this->transformation = transformation;
}
| #include "./mesh_node.h"
#include <string>
#include "./graphics/gl.h"
MeshNode::MeshNode(std::string assetFilename, int meshIndex,
std::shared_ptr<Graphics::Mesh> mesh,
Eigen::Matrix4f transformation)
: assetFilename(assetFilename), meshIndex(meshIndex), mesh(mesh),
transformation(transformation)
{
obb = mesh->obb * transformation;
}
MeshNode::~MeshNode()
{
}
void MeshNode::render(Graphics::Gl *gl,
std::shared_ptr<Graphics::Managers> managers,
RenderData renderData)
{
if (!isVisible)
return;
renderData.modelMatrix = transformation;
mesh->render(gl, managers, renderData);
}
Eigen::Matrix4f MeshNode::getTransformation()
{
return this->transformation;
}
void MeshNode::setTransformation(Eigen::Matrix4f transformation)
{
this->transformation = transformation;
obb = mesh->obb * transformation;
}
|
Add test translate protobuf object to json directly | #include <fstream>
#include <iostream>
#include "person.pb.h"
//#include "../pb2json.h"
#include <pb2json.h>
using namespace std;
int main(int argc,char *argv[])
{
// Test 1: read binary PB from a file and convert it to JSON
ifstream fin("dump",ios::binary);
fin.seekg(0,ios_base::end);
size_t len = fin.tellg();
fin.seekg(0,ios_base::beg);
char *buf = new char [len];
fin.read(buf,len);
google::protobuf::Message *p = new Person();
char *json = pb2json(p,buf,len);
cout<<json<<endl;
free(json);
delete p;
// Test 2: convert PB to JSON directly
Person p2;
char *json2 = pb2json(p2);
cout<<json2<<endl;
free(json2);
return 0;
}
| #include <fstream>
#include <iostream>
#include "person.pb.h"
//#include "../pb2json.h"
#include <pb2json.h>
using namespace std;
int main(int argc,char *argv[])
{
// Test 1: read binary PB from a file and convert it to JSON
ifstream fin("dump",ios::binary);
fin.seekg(0,ios_base::end);
size_t len = fin.tellg();
fin.seekg(0,ios_base::beg);
char *buf = new char [len];
fin.read(buf,len);
google::protobuf::Message *p = new Person();
char *json = pb2json(p,buf,len);
cout<<json<<endl;
free(json);
delete p;
// Test 2: convert PB to JSON directly
Person p2;
p2.set_name("Shafreeck Sea");
p2.set_id(2);
p2.set_email("renenglish@gmail.com");
Person_PhoneNumber *pn1 = p2.add_phone();
pn1->set_number("1234567");
pn1->set_type(Person::HOME);
char *json2 = pb2json(p2);
cout<<json2<<endl;
free(json2);
return 0;
}
|
Add test for simple append using DailyFileAppender | #include "log4qt/dailyfileappender.h"
#include "log4qt/simplelayout.h"
#include <QTemporaryDir>
#include <QtTest/QtTest>
using Log4Qt::DailyFileAppender;
class DailyFileAppenderTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void init();
void cleanup();
void testFileCreation();
private:
QTemporaryDir *mLogDirectory;
DailyFileAppender *mAppender;
};
void DailyFileAppenderTest::init()
{
mLogDirectory = new QTemporaryDir;
mAppender = new DailyFileAppender;
mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
}
void DailyFileAppenderTest::cleanup()
{
delete mAppender;
delete mLogDirectory; // destructor will remove temporary directory
}
void DailyFileAppenderTest::testFileCreation()
{
mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));
mAppender->activateOptions();
QVERIFY(QFileInfo::exists(mAppender->file()));
}
QTEST_GUILESS_MAIN(DailyFileAppenderTest)
#include "dailyfileappendertest.moc"
| #include "log4qt/dailyfileappender.h"
#include "log4qt/loggingevent.h"
#include "log4qt/simplelayout.h"
#include <QTemporaryDir>
#include <QtTest/QtTest>
using Log4Qt::DailyFileAppender;
class DailyFileAppenderTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void init();
void cleanup();
void testFileCreation();
void testAppend();
private:
QTemporaryDir *mLogDirectory;
DailyFileAppender *mAppender;
};
void DailyFileAppenderTest::init()
{
mLogDirectory = new QTemporaryDir;
mAppender = new DailyFileAppender;
mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
}
void DailyFileAppenderTest::cleanup()
{
delete mAppender;
delete mLogDirectory; // destructor will remove temporary directory
}
void DailyFileAppenderTest::testFileCreation()
{
mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));
mAppender->activateOptions();
QVERIFY(QFileInfo::exists(mAppender->file()));
}
void DailyFileAppenderTest::testAppend()
{
mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));
mAppender->activateOptions();
const auto fileName = mAppender->file();
QVERIFY(QFileInfo::exists(fileName));
const QFile logFile(fileName);
// nothing written yet
QCOMPARE(logFile.size(), 0);
mAppender->append(Log4Qt::LoggingEvent());
QVERIFY(logFile.size() > 0);
}
QTEST_GUILESS_MAIN(DailyFileAppenderTest)
#include "dailyfileappendertest.moc"
|
Add a simple write-then-read test | #include <fstream>
#include "rang.hpp"
int main()
{
std::cout << rang::fg::blue << "\nShould be blue";
std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out.rdbuf());
std::string word = "not blue";
std::cout << "START " << rang::fg::blue << word << " END";
std::cout.rdbuf(coutbuf);
std::cout << "\nShould again be blue" << rang::style::reset << std::endl;
return 0;
}
| #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "rang.hpp"
#include <fstream>
#include <string>
std::string RCB(std::string input)
{
std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf();
std::cout.rdbuf(out.rdbuf());
std::cout << rang::fg::blue << input << rang::style::reset;
std::cout.rdbuf(coutbuf);
out.close();
std::ifstream in("out.txt");
std::string output;
std::getline(in,output);
return output;
}
TEST_CASE("Redirected cout buffer", "RCB")
{
REQUIRE(RCB("HelloWorld") == "HelloWorld");
}
|
Fix build break on mac. TBR=ajwong | // 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 "remoting/host/event_executor_mac.h"
namespace remoting {
EventExecutorMac::EventExecutorMac(Capturer* capturer)
: EventExecutor(capturer) {
}
EventExecutorMac::~EventExecutorMac() {
}
void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
delete message;
}
} // namespace remoting
| // 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 "remoting/host/event_executor_mac.h"
#include "remoting/protocol/messages_decoder.h"
namespace remoting {
EventExecutorMac::EventExecutorMac(Capturer* capturer)
: EventExecutor(capturer) {
}
EventExecutorMac::~EventExecutorMac() {
}
void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
delete message;
}
} // namespace remoting
|
Add include for unistd.h for _exit. Otherwise, the exit test won't build w/ pnacl. | // Copyright (c) 2011 The Native Client 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 "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"
namespace {
// This will crash a PPP_Messaging function.
void CrashViaExitCall() {
printf("--- CrashViaExitCall\n");
_exit(0);
}
} // namespace
void SetupTests() {
RegisterTest("CrashViaExitCall", CrashViaExitCall);
}
void SetupPluginInterfaces() {
// none
}
| // Copyright (c) 2011 The Native Client 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 <unistd.h>
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"
namespace {
// This will crash a PPP_Messaging function.
void CrashViaExitCall() {
printf("--- CrashViaExitCall\n");
_exit(0);
}
} // namespace
void SetupTests() {
RegisterTest("CrashViaExitCall", CrashViaExitCall);
}
void SetupPluginInterfaces() {
// none
}
|
Fix diagnostic in verify test to match new Clang output | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03
// <future>
// class packaged_task<R(ArgTypes...)>
// template <class F, class Allocator>
// packaged_task(allocator_arg_t, const Allocator& a, F&& f);
// These constructors shall not participate in overload resolution if
// decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.
#include <future>
#include <cassert>
#include "test_allocator.h"
struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;
int main()
{
PT p { std::allocator_arg_t{}, test_allocator<A>{}, VPT {}}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
// expected-note@future:* 1 {{candidate template ignored: disabled by 'enable_if'}}
}
| //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03
// <future>
// class packaged_task<R(ArgTypes...)>
// template <class F, class Allocator>
// packaged_task(allocator_arg_t, const Allocator& a, F&& f);
// These constructors shall not participate in overload resolution if
// decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.
#include <future>
#include <cassert>
#include "test_allocator.h"
struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;
int main()
{
PT p { std::allocator_arg_t{}, test_allocator<A>{}, VPT {}}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
// expected-note-re@future:* 1 {{candidate template ignored: {{(disabled by 'enable_if')|(requirement '.*' was not satisfied)}}}}
}
|
Disable a Clang test until the begincatch change lands | // RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY | FileCheck %s -check-prefix=TRY
// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW
void external();
inline void not_emitted() {
throw int(13); // no error
}
int main() {
int rv = 0;
#ifdef TRY
try {
external(); // TRY: invoke void @"\01?external@@YAXXZ"
} catch (int) {
rv = 1;
// TRY: call i8* @llvm.eh.begincatch
// TRY: call void @llvm.eh.endcatch
}
#endif
#ifdef THROW
// THROW: call void @"\01?terminate@@YAXXZ"
throw int(42);
#endif
return rv;
}
| // RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTRY | FileCheck %s -check-prefix=TRY
// FIXME: Disabled until catch IRgen change lands.
// RUNX: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fcxx-exceptions -fexceptions -fno-rtti -DTHROW | FileCheck %s -check-prefix=THROW
void external();
inline void not_emitted() {
throw int(13); // no error
}
int main() {
int rv = 0;
#ifdef TRY
try {
external(); // TRY: invoke void @"\01?external@@YAXXZ"
} catch (int) {
rv = 1;
// TRY: call i8* @llvm.eh.begincatch
// TRY: call void @llvm.eh.endcatch
}
#endif
#ifdef THROW
// THROW: call void @"\01?terminate@@YAXXZ"
throw int(42);
#endif
return rv;
}
|
Fix tutorial SW UART example | #include <fastarduino/soft_uart.h>
constexpr const board::InterruptPin RX = board::InterruptPin::D0_PD0_PCI2;
#define PCI_NUM 2
REGISTER_UART_PCI_ISR(RX, PCI_NUM)
// Buffers for UARX
static const uint8_t INPUT_BUFFER_SIZE = 64;
static char input_buffer[INPUT_BUFFER_SIZE];
int main()
{
board::init();
sei();
// Start UART
typename interrupt::PCIType<RX>::TYPE pci;
serial::soft::UARX_PCI<RX> uarx{input_buffer, pci};
pci.enable();
uarx.begin(115200);
streams::istream in = uarx.in();
// Wait for a char
char value1;
in >> streams::skipws >> value1;
// Wait for an uint16_t
uint16_t value2;
in >> streams::skipws >> value2;
return 0;
}
| #include <fastarduino/soft_uart.h>
constexpr const board::InterruptPin RX = board::InterruptPin::D0_PD0_PCI2;
#define PCI_NUM 2
REGISTER_UARX_PCI_ISR(RX, PCI_NUM)
// Buffers for UARX
static const uint8_t INPUT_BUFFER_SIZE = 64;
static char input_buffer[INPUT_BUFFER_SIZE];
int main()
{
board::init();
sei();
// Start UART
typename interrupt::PCIType<RX>::TYPE pci;
serial::soft::UARX_PCI<RX> uarx{input_buffer, pci};
pci.enable();
uarx.begin(115200);
streams::istream in = uarx.in();
// Wait for a char
char value1;
in >> streams::skipws >> value1;
// Wait for an uint16_t
uint16_t value2;
in >> streams::skipws >> value2;
return 0;
}
|
Update test case, with comment to later investigate the correct behavior. Now the behavior is at least consistent. | // RUN: %clang_cc1 %s -fsyntax-only -verify -Wmissing-noreturn -Wno-unreachable-code
// A destructor may be marked noreturn and should still influence the CFG.
namespace PR6884 {
struct abort_struct {
abort_struct() {} // Make this non-POD so the destructor is invoked.
~abort_struct() __attribute__((noreturn));
};
int f() {
abort_struct();
}
int f2() {
abort_struct s;
} // expected-warning{{control reaches end of non-void function}}
}
| // RUN: %clang_cc1 %s -fsyntax-only -verify -Wmissing-noreturn -Wno-unreachable-code
// A destructor may be marked noreturn and should still influence the CFG.
namespace PR6884 {
struct abort_struct {
abort_struct() {} // Make this non-POD so the destructor is invoked.
~abort_struct() __attribute__((noreturn));
};
// FIXME: Should either of these actually warn, since the destructor is
// marked noreturn?
int f() {
abort_struct();
} // expected-warning{{control reaches end of non-void function}}
int f2() {
abort_struct s;
} // expected-warning{{control reaches end of non-void function}}
}
|
Change logging level to INFO (DEBUG is slowing down the execution too much). | #include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>
#include "LoggerFactory.h"
using namespace Log;
bool LoggerFactory::isCreated = false;
log4cpp::Category *LoggerFactory::instance;
LoggerFactory::LoggerFactory() {}
/* Factory for a simple log4cpp logger. */
log4cpp::Category* LoggerFactory::create() {
log4cpp::Category *logger = &log4cpp::Category::getRoot();
log4cpp::Appender *p_appender = new log4cpp::OstreamAppender("console", &std::cout);
log4cpp::PatternLayout *layout = new log4cpp::PatternLayout();
layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S} [%p] %c: %m%n");
p_appender->setLayout(layout);
logger->setPriority(log4cpp::Priority::DEBUG);
logger->addAppender(p_appender);
return logger;
}
/* Returns a singleton root logger. */
log4cpp::Category *LoggerFactory::getLogger() {
if (!isCreated) {
isCreated = true;
instance = create();
}
return instance;
} | #include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>
#include "LoggerFactory.h"
using namespace Log;
bool LoggerFactory::isCreated = false;
log4cpp::Category *LoggerFactory::instance;
LoggerFactory::LoggerFactory() {}
/* Factory for a simple log4cpp logger. */
log4cpp::Category* LoggerFactory::create() {
log4cpp::Category *logger = &log4cpp::Category::getRoot();
log4cpp::Appender *p_appender = new log4cpp::OstreamAppender("console", &std::cout);
log4cpp::PatternLayout *layout = new log4cpp::PatternLayout();
layout->setConversionPattern("%d{%Y-%m-%d %H:%M:%S} [%p] %c: %m%n");
p_appender->setLayout(layout);
logger->setPriority(log4cpp::Priority::INFO);
logger->addAppender(p_appender);
return logger;
}
/* Returns a singleton root logger. */
log4cpp::Category *LoggerFactory::getLogger() {
if (!isCreated) {
isCreated = true;
instance = create();
}
return instance;
} |
Fix bad performance in debug mode | // Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <atomic>
#include "rocksdb/env.h"
#include "util/thread_status_updater.h"
#include "util/thread_status_util.h"
namespace rocksdb {
#ifndef NDEBUG
// the delay for debugging purpose.
static std::atomic<int> states_delay[ThreadStatus::NUM_STATE_TYPES];
void ThreadStatusUtil::TEST_SetStateDelay(
const ThreadStatus::StateType state, int micro) {
states_delay[state].store(micro, std::memory_order_relaxed);
}
void ThreadStatusUtil::TEST_StateDelay(
const ThreadStatus::StateType state) {
Env::Default()->SleepForMicroseconds(
states_delay[state].load(std::memory_order_relaxed));
}
#endif // !NDEBUG
} // namespace rocksdb
| // Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <atomic>
#include "rocksdb/env.h"
#include "util/thread_status_updater.h"
#include "util/thread_status_util.h"
namespace rocksdb {
#ifndef NDEBUG
// the delay for debugging purpose.
static std::atomic<int> states_delay[ThreadStatus::NUM_STATE_TYPES];
void ThreadStatusUtil::TEST_SetStateDelay(
const ThreadStatus::StateType state, int micro) {
states_delay[state].store(micro, std::memory_order_relaxed);
}
void ThreadStatusUtil::TEST_StateDelay(const ThreadStatus::StateType state) {
auto delay = states_delay[state].load(std::memory_order_relaxed);
if (delay > 0) {
Env::Default()->SleepForMicroseconds(delay);
}
}
#endif // !NDEBUG
} // namespace rocksdb
|
Remove the fallback to the old bridge for tf.XlaReplicaId | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
namespace tensorflow {
namespace {
class XlaReplicaIdOp : public XlaOpKernel {
public:
explicit XlaReplicaIdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
void Compile(XlaOpKernelContext* ctx) override;
private:
TF_DISALLOW_COPY_AND_ASSIGN(XlaReplicaIdOp);
};
void XlaReplicaIdOp::Compile(XlaOpKernelContext* ctx) {
ctx->SetOutput(
0, xla::ConvertElementType(xla::ReplicaId(ctx->builder()), xla::S32));
}
REGISTER_XLA_OP(Name("XlaReplicaId"), XlaReplicaIdOp);
} // namespace
} // namespace tensorflow
| /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
namespace tensorflow {
namespace {
REGISTER_XLA_OP(Name("XlaReplicaId"), MlirXlaOpKernel);
} // namespace
} // namespace tensorflow
|
Remove some debugging printout lines. No functionality change. | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <vector>
// void assign(size_type n, const_reference v);
#include <vector>
#include <algorithm>
#include <cassert>
#include <iostream>
#include "min_allocator.h"
#include "asan_testing.h"
bool is6(int x) { return x == 6; }
template <typename Vec>
void test ( Vec &v )
{
std::cout << "Size, cap: " << v.size() << " " << v.capacity() << std::endl;
v.assign(5, 6);
std::cout << "Size, cap: " << v.size() << " " << v.capacity() << std::endl;
assert(v.size() == 5);
assert(is_contiguous_container_asan_correct(v));
assert(std::all_of(v.begin(), v.end(), is6));
}
int main()
{
{
typedef std::vector<int> V;
V d1;
V d2;
d2.reserve(10); // no reallocation during assign.
test(d1);
test(d2);
}
#if __cplusplus >= 201103L
{
typedef std::vector<int, min_allocator<int>> V;
V d1;
V d2;
d2.reserve(10); // no reallocation during assign.
test(d1);
test(d2);
}
#endif
}
| //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <vector>
// void assign(size_type n, const_reference v);
#include <vector>
#include <algorithm>
#include <cassert>
#include <iostream>
#include "min_allocator.h"
#include "asan_testing.h"
bool is6(int x) { return x == 6; }
template <typename Vec>
void test ( Vec &v )
{
v.assign(5, 6);
assert(v.size() == 5);
assert(is_contiguous_container_asan_correct(v));
assert(std::all_of(v.begin(), v.end(), is6));
}
int main()
{
{
typedef std::vector<int> V;
V d1;
V d2;
d2.reserve(10); // no reallocation during assign.
test(d1);
test(d2);
}
#if __cplusplus >= 201103L
{
typedef std::vector<int, min_allocator<int>> V;
V d1;
V d2;
d2.reserve(10); // no reallocation during assign.
test(d1);
test(d2);
}
#endif
}
|
Fix thinko In inroduced while importing the fuzzer | // Copyright 2016 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 <stddef.h>
#include <stdint.h>
#ifndef OTS_FUZZER_NO_MAIN
#include <fstream>
#include <iostream>
#include <iterator>
#endif
#include "opentype-sanitiser.h"
#include "ots-memory-stream.h"
// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
ots::OTSContext context;
ots::MemoryStream stream((void*)data, size);
context.Process(&stream, data, size);
return 0;
}
#ifndef OTS_FUZZER_NO_MAIN
int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
std::cout << argv[i] << std::endl;
std::ifstream f(argv[i]);
if (!f.good())
return 1;
std::string s((std::istreambuf_iterator<char>(f)),
(std::istreambuf_iterator<char>()));
LLVMFuzzerTestOneInput((const uint8_t*)s.data(), s.size());
}
return 0;
}
#endif
| // Copyright 2016 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 <stddef.h>
#include <stdint.h>
#ifndef OTS_FUZZER_NO_MAIN
#include <fstream>
#include <iostream>
#include <iterator>
#endif
#include "opentype-sanitiser.h"
#include "ots-memory-stream.h"
static uint8_t buffer[256 * 1024] = { 0 };
// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
ots::OTSContext context;
ots::MemoryStream stream(static_cast<void*>(buffer), sizeof(buffer));
context.Process(&stream, data, size);
return 0;
}
#ifndef OTS_FUZZER_NO_MAIN
int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
std::cout << argv[i] << std::endl;
std::ifstream f(argv[i]);
if (!f.good())
return 1;
std::string s((std::istreambuf_iterator<char>(f)),
(std::istreambuf_iterator<char>()));
LLVMFuzzerTestOneInput((const uint8_t*)s.data(), s.size());
}
return 0;
}
#endif
|
Rename std::sqrtf -> std::sqrt because gcc is not standards compliant on that for whatever reason. | #include "halley/maths/circle.h"
using namespace Halley;
bool Circle::contains(Vector2f point) const
{
return (point - centre).squaredLength() <= radius * radius;
}
bool Circle::overlaps(const Circle& circle) const
{
const float r = radius + circle.radius;
return (circle.centre - centre).squaredLength() <= r * r;
}
Circle Circle::getSpanningCircle(const std::vector<Vector2f>& points)
{
// TODO: should use Matousek, Sharir, Welzl's algorithm (https://en.wikipedia.org/wiki/Smallest-circle_problem#Matou%C5%A1ek,_Sharir,_Welzl's_algorithm)
Vector2f centre;
for (auto& p: points) {
centre += p;
}
centre /= float(points.size());
float radius2 = 0;
for (auto& p: points) {
const auto d = (p - centre).squaredLength();
if (d > radius2) {
radius2 = d;
}
}
return Circle(centre, std::sqrtf(radius2));
}
| #include "halley/maths/circle.h"
using namespace Halley;
bool Circle::contains(Vector2f point) const
{
return (point - centre).squaredLength() <= radius * radius;
}
bool Circle::overlaps(const Circle& circle) const
{
const float r = radius + circle.radius;
return (circle.centre - centre).squaredLength() <= r * r;
}
Circle Circle::getSpanningCircle(const std::vector<Vector2f>& points)
{
// TODO: should use Matousek, Sharir, Welzl's algorithm (https://en.wikipedia.org/wiki/Smallest-circle_problem#Matou%C5%A1ek,_Sharir,_Welzl's_algorithm)
Vector2f centre;
for (auto& p: points) {
centre += p;
}
centre /= float(points.size());
float radius2 = 0;
for (auto& p: points) {
const auto d = (p - centre).squaredLength();
if (d > radius2) {
radius2 = d;
}
}
return Circle(centre, std::sqrt(radius2));
}
|
Fix warning in tuple tests. The test suite should now run clean with most warnings enabled | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: c++98, c++03
// Tuples of smart pointers; based on bug #18350
// auto_ptr doesn't have a copy constructor that takes a const &, but tuple does.
#include <tuple>
#include <memory>
int main () {
{
std::tuple<std::unique_ptr<char>> up;
std::tuple<std::shared_ptr<char>> sp;
std::tuple<std::weak_ptr <char>> wp;
// std::tuple<std::auto_ptr <char>> ap;
}
{
std::tuple<std::unique_ptr<char[]>> up;
std::tuple<std::shared_ptr<char[]>> sp;
std::tuple<std::weak_ptr <char[]>> wp;
// std::tuple<std::auto_ptr <char[]>> ap;
}
{
std::tuple<std::unique_ptr<char[5]>> up;
std::tuple<std::shared_ptr<char[5]>> sp;
std::tuple<std::weak_ptr <char[5]>> wp;
// std::tuple<std::auto_ptr <char[5]>> ap;
}
} | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: c++98, c++03
// Tuples of smart pointers; based on bug #18350
// auto_ptr doesn't have a copy constructor that takes a const &, but tuple does.
#include <tuple>
#include <memory>
int main () {
{
std::tuple<std::unique_ptr<char>> up;
std::tuple<std::shared_ptr<char>> sp;
std::tuple<std::weak_ptr <char>> wp;
}
{
std::tuple<std::unique_ptr<char[]>> up;
std::tuple<std::shared_ptr<char[]>> sp;
std::tuple<std::weak_ptr <char[]>> wp;
}
// Smart pointers of type 'T[N]' are not tested here since they are not
// supported by the standard nor by libc++'s implementation.
// See http://reviews.llvm.org/D21320 for move information.
} |
Check that newly created has correct checksum | #include "catch.hpp"
//#define KASSERT REQUIRE
#include <Segment.hh>
#include <cstring>
#define SEGMENTSIZE 4096
SCENARIO("Memory segment representation", "[kernelheap]")
{
GIVEN("A memory segment")
{
char* memorySegment = new char[SEGMENTSIZE];
memset(memorySegment, 0x55, SEGMENTSIZE);
WHEN("Constructing a segment header for the segment")
{
Segment* segment = new(memorySegment) Segment();
THEN("The size is zero")
{
CHECK(segment->getSize() == 0);
}
THEN("The segment is marked as unallocated")
{
CHECK(segment->isAllocated() == false);
}
AND_WHEN("Updating the checksum")
{
segment->updateChecksum();
THEN("The checksum is valid")
{
CHECK(segment->verifyChecksum() == true);
}
AND_WHEN("The segment is mutated")
{
segment->setSize(1110);
THEN("The checksum is no longer valid")
{
CHECK(segment->verifyChecksum() == false);
}
}
}
}
}
}
| #include "catch.hpp"
//#define KASSERT REQUIRE
#include <Segment.hh>
#include <cstring>
#define SEGMENTSIZE 4096
SCENARIO("Memory segment representation", "[kernelheap]")
{
GIVEN("A memory segment")
{
char* memorySegment = new char[SEGMENTSIZE];
memset(memorySegment, 0x55, SEGMENTSIZE);
WHEN("Constructing a segment header for the segment")
{
Segment* segment = new(memorySegment) Segment();
THEN("The size is zero")
{
CHECK(segment->getSize() == 0);
}
THEN("The segment is marked as unallocated")
{
CHECK(segment->isAllocated() == false);
}
THEN("The segment checksum is valid")
{
CHECK(segment->verifyChecksum() == true);
}
AND_WHEN("Updating the checksum")
{
segment->updateChecksum();
THEN("The checksum is valid")
{
CHECK(segment->verifyChecksum() == true);
}
AND_WHEN("The segment is mutated")
{
segment->setSize(1110);
THEN("The checksum is no longer valid")
{
CHECK(segment->verifyChecksum() == false);
}
}
}
}
}
}
|
Initialize a variable in PrinterBasicInfo. | // 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 "printing/backend/print_backend.h"
namespace printing {
PrinterBasicInfo::PrinterBasicInfo() : printer_status(0) {}
PrinterBasicInfo::~PrinterBasicInfo() {}
PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}
PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}
PrintBackend::~PrintBackend() {}
} // namespace printing
| // 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 "printing/backend/print_backend.h"
namespace printing {
PrinterBasicInfo::PrinterBasicInfo()
: printer_status(0),
is_default(false) {}
PrinterBasicInfo::~PrinterBasicInfo() {}
PrinterCapsAndDefaults::PrinterCapsAndDefaults() {}
PrinterCapsAndDefaults::~PrinterCapsAndDefaults() {}
PrintBackend::~PrintBackend() {}
} // namespace printing
|
Disable call to WebPreferences::current_legacy_font_size_mode. Missing API. | #include "ewk_settings_private.h"
#include "net/http/http_stream_factory.h"
void Ewk_Settings::setSpdyEnabled(bool flag)
{
net::HttpStreamFactory::set_spdy_enabled(flag);
}
void Ewk_Settings::setCurrentLegacyFontSizeMode(tizen_webview::Legacy_Font_Size_Mode mode) {
m_currentLegacyFontSizeMode = mode;
m_preferences.current_legacy_font_size_mode = static_cast<content::LegacyFontSizeMode>(mode);
}
| #include "ewk_settings_private.h"
#include "net/http/http_stream_factory.h"
void Ewk_Settings::setSpdyEnabled(bool flag)
{
net::HttpStreamFactory::set_spdy_enabled(flag);
}
void Ewk_Settings::setCurrentLegacyFontSizeMode(tizen_webview::Legacy_Font_Size_Mode mode) {
m_currentLegacyFontSizeMode = mode;
#if !defined(EWK_BRINGUP)
m_preferences.current_legacy_font_size_mode = static_cast<content::LegacyFontSizeMode>(mode);
#endif
}
|
Print Preview: Fix typo from r78639. | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/print_preview_ui.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"
PrintPreviewUI::PrintPreviewUI(TabContents* contents)
: WebUI(contents),
html_source_(new PrintPreviewUIHTMLSource()) {
// PrintPreviewUI owns |handler|.
PrintPreviewHandler* handler = new PrintPreviewHandler();
AddMessageHandler(handler->Attach(this));
// Set up the chrome://print/ source.
contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}
PrintPreviewUI::~PrintPreviewUI() {
}
PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
return html_source_.get();
}
void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
FundamentalValue pages_count(expected_pages_count);
CallJavascriptFunction("createPDFPlugin", pages_count);
}
| // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/print_preview_ui.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"
PrintPreviewUI::PrintPreviewUI(TabContents* contents)
: WebUI(contents),
html_source_(new PrintPreviewUIHTMLSource()) {
// PrintPreviewUI owns |handler|.
PrintPreviewHandler* handler = new PrintPreviewHandler();
AddMessageHandler(handler->Attach(this));
// Set up the chrome://print/ source.
contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}
PrintPreviewUI::~PrintPreviewUI() {
}
PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
return html_source_.get();
}
void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
FundamentalValue pages_count(expected_pages_count);
CallJavascriptFunction("updatePrintPreview", pages_count);
}
|
Use Unicode compatible in Variant test |
#include <nstd/Debug.h>
#include <nstd/Variant.h>
void_t testVariant()
{
// test default constructor
{
Variant var;
ASSERT(var.isNull());
ASSERT(var.toBool() == false);
}
// test boolean constructor
{
Variant var(true);
ASSERT(var.toBool() == true);
}
// test map constructor
{
HashMap<String, Variant> map;
map.append("dasd", Variant(String("yes")));
Variant var(map);
ASSERT(((const Variant&)var).toMap().find("dasd")->toString() == "yes");
ASSERT(var.toMap().find("dasd")->toString() == "yes");
}
}
|
#include <nstd/Debug.h>
#include <nstd/Variant.h>
void_t testVariant()
{
// test default constructor
{
Variant var;
ASSERT(var.isNull());
ASSERT(var.toBool() == false);
}
// test boolean constructor
{
Variant var(true);
ASSERT(var.toBool() == true);
}
// test map constructor
{
HashMap<String, Variant> map;
map.append(_T("dasd"), Variant(String(_T("yes"))));
Variant var(map);
ASSERT(((const Variant&)var).toMap().find(_T("dasd"))->toString() == _T("yes"));
ASSERT(var.toMap().find(_T("dasd"))->toString() == _T("yes"));
}
}
|
Make sure failed tests actually fail. | #include "square.h"
#include <gtest/gtest.h>
TEST(TestSuite, squareTwo)
{
const double ret = square(2);
ASSERT_EQ(4, ret);
}
TEST(TestSuite, squareFour)
{
const double ret = square(4.1);
ASSERT_EQ(16.81, ret);
}
// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| #include "square.h"
#include <gtest/gtest.h>
TEST(TestSuite, squareTwo)
{
const double ret = square(2);
ASSERT_EQ(5, ret);
}
TEST(TestSuite, squareFour)
{
const double ret = square(4.1);
ASSERT_EQ(16.81, ret);
}
// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Fix integer overflow reported by gcc | /*
Copyright (C) 2010 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "../memutil.h"
namespace CS {
namespace Platform {
namespace Implementation {
size_t GetMaxVirtualSize()
{
// Guess available virtual address space ...
#if CS_PROCESSOR_SIZE == 32
// 32-bit: 2GiB virtual address space
return 2 * 1024 * 1024;
#else
// 64-bit: 8TiB virtual address space
return 8 * 1024 * 1024 * 1024;
#endif
}
} // End namespace Implementation
} // End namespace Platform
} // End namespace CS
| /*
Copyright (C) 2010 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "../memutil.h"
namespace CS {
namespace Platform {
namespace Implementation {
size_t GetMaxVirtualSize()
{
// Guess available virtual address space ...
#if CS_PROCESSOR_SIZE == 32
// 32-bit: 2GiB virtual address space
return 2 * 1024 * 1024;
#else
// 64-bit: 8TiB virtual address space
return 8 * size_t (1024 * 1024 * 1024);
#endif
}
} // End namespace Implementation
} // End namespace Platform
} // End namespace CS
|
Fix release build console bug | #include "Logger.h"
#include <string>
void Logger::Start() {
#ifdef ENABLE_3RVX_LOGTOFILE
/* Disable buffering */
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
FILE *out, *err;
_wfreopen_s(&out, L"3RVX_Log.txt", L"w", stdout);
_wfreopen_s(&err, L"3RVX_Log.txt", L"w", stderr);
#else
#ifdef ENABLE_3RVX_LOG
AllocConsole();
FILE *in, *out, *err;
freopen_s(&in, "CONIN$", "r", stdin);
freopen_s(&out, "CONOUT$", "w", stdout);
freopen_s(&err, "CONOUT$", "w", stderr);
#endif
#endif
}
void Logger::Stop() {
#ifdef ENABLE_3RVX_LOGTOFILE
CLOG(L"Logger stopped.");
fclose(stdout);
fclose(stderr);
#else
#ifdef ENABLE_3RVX_LOG
FreeConsole();
#endif
#endif
} | #include "Logger.h"
#include <string>
void Logger::Start() {
#ifdef ENABLE_3RVX_LOGTOFILE
/* Disable buffering */
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
FILE *out, *err;
_wfreopen_s(&out, L"3RVX_Log.txt", L"w", stdout);
_wfreopen_s(&err, L"3RVX_Log.txt", L"w", stderr);
#else
#if ENABLE_3RVX_LOG != 0
AllocConsole();
FILE *in, *out, *err;
freopen_s(&in, "CONIN$", "r", stdin);
freopen_s(&out, "CONOUT$", "w", stdout);
freopen_s(&err, "CONOUT$", "w", stderr);
#endif
#endif
}
void Logger::Stop() {
#ifdef ENABLE_3RVX_LOGTOFILE
CLOG(L"Logger stopped.");
fclose(stdout);
fclose(stderr);
#else
#if ENABLE_3RVX_LOG != 0
FreeConsole();
#endif
#endif
} |
Fix for Release build break | // 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/chromeos/status_area_button.h"
#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"
////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton
StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
: MenuButton(NULL, std::wstring(), menu_delegate, false) {
set_border(NULL);
SetShowHighlighted(true);
}
void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
int bitmap_id;
switch(state()) {
case BS_NORMAL:
bitmap_id = IDR_STATUSBAR_CONTAINER;
break;
case BS_HOT:
bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
break;
case BS_PUSHED:
bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
break;
default:
NOTREACHED();
}
SkBitmap* container =
ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
canvas->DrawBitmapInt(*container, 0, 0);
canvas->DrawBitmapInt(icon(), 0, 0);
}
| // 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/chromeos/status_area_button.h"
#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"
////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton
StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
: MenuButton(NULL, std::wstring(), menu_delegate, false) {
set_border(NULL);
SetShowHighlighted(true);
}
void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
int bitmap_id;
switch(state()) {
case BS_NORMAL:
bitmap_id = IDR_STATUSBAR_CONTAINER;
break;
case BS_HOT:
bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
break;
case BS_PUSHED:
bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
break;
default:
bitmap_id = IDR_STATUSBAR_CONTAINER;
NOTREACHED();
}
SkBitmap* container =
ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
canvas->DrawBitmapInt(*container, 0, 0);
canvas->DrawBitmapInt(icon(), 0, 0);
}
|
Create generator object on stack. Testing build system. | #include "generator.h"
int main()
{
QStringList l;
l
<< "kernel_metamodel.xml"
<< "basicbehaviors_metamodel.xml"
<< "trace.xml"
<< "requirements_metamodel.xml"
<< "class_metamodel.xml"
<< "usecase_metamodel.xml"
<< "sequence_metamodel.xml"
//<< "communication_metamodel.xml"
<< "statemachines_metamodel.xml"
//<< "deployment.xml"
//<< "component_metamodel.xml"
//<< "timing_metamodel.xml"
<< "activity_metamodel.xml"
<< "package.xml"
<< "bpel.xml"
<< "qrealparallel_metamodel.xml";
delete (new Generator(l));
return 0;
}
| #include "generator.h"
int main()
{
QStringList l;
l
<< "kernel_metamodel.xml"
<< "basicbehaviors_metamodel.xml"
<< "trace.xml"
<< "requirements_metamodel.xml"
<< "class_metamodel.xml"
<< "usecase_metamodel.xml"
<< "sequence_metamodel.xml"
//<< "communication_metamodel.xml"
<< "statemachines_metamodel.xml"
//<< "deployment.xml"
//<< "component_metamodel.xml"
//<< "timing_metamodel.xml"
<< "activity_metamodel.xml"
<< "package.xml"
<< "bpel.xml"
<< "qrealparallel_metamodel.xml";
Generator generator(l);
return 0;
}
|
Disable the warning on the nativetests.cpp | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "stdafx.h"
#define CATCH_CONFIG_RUNNER
#pragma warning(push)
// conversion from 'int' to 'char', possible loss of data
#pragma warning(disable:4244)
#include "catch.hpp"
#pragma warning(pop)
// Use nativetests.exe -? to get all command line options
int _cdecl main(int argc, char * const argv[])
{
return Catch::Session().run(argc, argv);
}
| //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "stdafx.h"
#define CATCH_CONFIG_RUNNER
#pragma warning(push)
// conversion from 'int' to 'char', possible loss of data
#pragma warning(disable:4242)
#pragma warning(disable:4244)
#include "catch.hpp"
#pragma warning(pop)
// Use nativetests.exe -? to get all command line options
int _cdecl main(int argc, char * const argv[])
{
return Catch::Session().run(argc, argv);
}
|
Change /bin/hostname to just hostname, and let sh figure out the path | //! @file test-getfullyqualifiedname.cpp
//! @author George Fleming <v-geflem@microsoft.com>
//! @brief Unit tests for GetFullyQualifiedName
#include <stdio.h>
#include <gtest/gtest.h>
#include "getfullyqualifiedname.h"
//! Test fixture for GetComputerNameTest
class GetFullyQualifiedNameTest : public ::testing::Test
{
};
TEST_F(GetFullyQualifiedNameTest, ValidateLinuxGetFullyQualifiedDomainName)
{
char expectedComputerName[HOST_NAME_MAX];
//Get expected result from using linux command
FILE *fPtr = popen("/bin/hostname --fqdn", "r");
ASSERT_TRUE(fPtr != NULL);
char *linePtr = fgets(expectedComputerName, sizeof(expectedComputerName), fPtr);
ASSERT_TRUE(linePtr != NULL);
// There's a tendency to have \n at end of fgets string, so remove it before compare
size_t sz = strlen(expectedComputerName);
if (sz > 0 && expectedComputerName[sz - 1] == '\n')
{
expectedComputerName[sz - 1] = '\0';
}
pclose(fPtr);
ASSERT_STREQ(GetFullyQualifiedName(), expectedComputerName);
}
| //! @file test-getfullyqualifiedname.cpp
//! @author George Fleming <v-geflem@microsoft.com>
//! @brief Unit tests for GetFullyQualifiedName
#include <stdio.h>
#include <gtest/gtest.h>
#include "getfullyqualifiedname.h"
//! Test fixture for GetComputerNameTest
class GetFullyQualifiedNameTest : public ::testing::Test
{
};
TEST_F(GetFullyQualifiedNameTest, ValidateLinuxGetFullyQualifiedDomainName)
{
char expectedComputerName[HOST_NAME_MAX];
//Get expected result from using linux command
FILE *fPtr = popen("hostname --fqdn", "r");
ASSERT_TRUE(fPtr != NULL);
char *linePtr = fgets(expectedComputerName, sizeof(expectedComputerName), fPtr);
ASSERT_TRUE(linePtr != NULL);
// There's a tendency to have \n at end of fgets string, so remove it before compare
size_t sz = strlen(expectedComputerName);
if (sz > 0 && expectedComputerName[sz - 1] == '\n')
{
expectedComputerName[sz - 1] = '\0';
}
pclose(fPtr);
ASSERT_STREQ(GetFullyQualifiedName(), expectedComputerName);
}
|
Optimize item set closure function | #include "compiler/build_tables/item_set_closure.h"
#include <algorithm>
#include <set>
#include "tree_sitter/compiler.h"
#include "compiler/build_tables/follow_sets.h"
#include "compiler/build_tables/item.h"
#include "compiler/prepared_grammar.h"
namespace tree_sitter {
using std::set;
using rules::ISymbol;
namespace build_tables {
static bool contains(const ParseItemSet *items, const ParseItem &item) {
if (items->empty()) return false;
return (std::find(items->begin(), items->end(), item) != items->end());
}
static void add_item(ParseItemSet *item_set,
const ParseItem &item,
const PreparedGrammar &grammar) {
if (!contains(item_set, item)) {
item_set->insert(item);
for (const auto &pair : follow_sets(item, grammar)) {
const ISymbol &non_terminal = pair.first;
const set<ISymbol> &terminals = pair.second;
for (const auto &terminal : terminals) {
ParseItem next_item(non_terminal, grammar.rule(non_terminal), 0, terminal);
add_item(item_set, next_item, grammar);
}
}
}
}
const ParseItemSet item_set_closure(const ParseItem &item,
const PreparedGrammar &grammar) {
ParseItemSet result;
add_item(&result, item, grammar);
return result;
}
}
} | #include "compiler/build_tables/item_set_closure.h"
#include <algorithm>
#include <set>
#include "tree_sitter/compiler.h"
#include "compiler/build_tables/follow_sets.h"
#include "compiler/build_tables/item.h"
#include "compiler/prepared_grammar.h"
namespace tree_sitter {
using std::set;
using rules::ISymbol;
using std::vector;
namespace build_tables {
const ParseItemSet item_set_closure(const ParseItem &item,
const PreparedGrammar &grammar) {
ParseItemSet result;
vector<ParseItem> items_to_add = { item };
while (!items_to_add.empty()) {
const ParseItem &item = items_to_add.back();
items_to_add.pop_back();
auto insertion_result = result.insert(item);
if (insertion_result.second) {
result.insert(item);
for (const auto &pair : follow_sets(item, grammar)) {
const ISymbol &non_terminal = pair.first;
const set<ISymbol> &terminals = pair.second;
for (const auto &terminal : terminals) {
items_to_add.push_back(ParseItem(non_terminal, grammar.rule(non_terminal), 0, terminal));
}
}
}
}
return result;
}
}
} |
Modify title for capture app | /* This file is part of the KDE project
* Copyright (C) 2010 Casian Andrei <skeletk13@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), Nokia Corporation
* (or its successors, if any) and the KDE Free Qt Foundation, which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "capture_test.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QApplication::setApplicationName("Primitive Phonon Application");
MediaPlayer mp(NULL);
mp.setWindowTitle("Primitive Phonon Application");
mp.show();
return app.exec();
}
| /* This file is part of the KDE project
* Copyright (C) 2010 Casian Andrei <skeletk13@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), Nokia Corporation
* (or its successors, if any) and the KDE Free Qt Foundation, which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "capture_test.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QApplication::setApplicationName("Phonon Capture Test Application");
MediaPlayer mp(NULL);
mp.setWindowTitle("Phonon Capture Test Application");
mp.show();
return app.exec();
}
|
Remove the comment that says b/34969189 blocking TruncateNormal. | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/framework/kernel_def.pb.h"
namespace tensorflow {
bool GpuOpFilter(KernelDef* kdef) {
// TODO(b/31361304): The GPU backend does not parallelize PRNG ops, leading to
// slow code.
// TODO(b/34969189) The implementation of TruncatedNormal generates illegal
// code on GPU.
if (kdef->op() == "RandomStandardNormal" || kdef->op() == "RandomUniform" ||
kdef->op() == "RandomUniformInt" || kdef->op() == "TruncatedNormal") {
return false;
}
return true;
}
REGISTER_XLA_BACKEND(DEVICE_GPU_XLA_JIT, kGpuAllTypes, GpuOpFilter);
} // namespace tensorflow
| /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/framework/kernel_def.pb.h"
namespace tensorflow {
bool GpuOpFilter(KernelDef* kdef) {
// TODO(b/31361304): The GPU backend does not parallelize PRNG ops, leading to
// slow code.
if (kdef->op() == "RandomStandardNormal" || kdef->op() == "RandomUniform" ||
kdef->op() == "RandomUniformInt" || kdef->op() == "TruncatedNormal") {
return false;
}
return true;
}
REGISTER_XLA_BACKEND(DEVICE_GPU_XLA_JIT, kGpuAllTypes, GpuOpFilter);
} // namespace tensorflow
|
Mark strstreams tests as being supported on all OS X versions | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <strstream>
// There was an overflow in the dylib on older macOS versions
// UNSUPPORTED: availability=macosx10.8
// UNSUPPORTED: availability=macosx10.7
// class strstreambuf
// int overflow(int c);
#include <iostream>
#include <string>
#include <strstream>
int main() {
std::ostrstream oss;
std::string s;
for (int i = 0; i < 4096; ++i)
s.push_back((i % 16) + 'a');
oss << s << std::ends;
std::cout << oss.str();
oss.freeze(false);
return 0;
}
| //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <strstream>
// class strstreambuf
// int overflow(int c);
#include <iostream>
#include <string>
#include <strstream>
int main() {
std::ostrstream oss;
std::string s;
for (int i = 0; i < 4096; ++i)
s.push_back((i % 16) + 'a');
oss << s << std::ends;
std::cout << oss.str();
oss.freeze(false);
return 0;
}
|
Update hierarchicalViewer content placeholder to follow target look | #include "hierarchical_viewer.hpp"
HierarchicalViewer::HierarchicalViewer(QWidget *parent) : QTreeWidget(parent)
{
/* Placeholders for testing purposes */
setColumnCount(1);
setHeaderLabel("Executable file");
QTreeWidgetItem *filename = addRoot("hacker.out");
QTreeWidgetItem *elf_header = addChild(filename, "ELF Header");
QTreeWidgetItem *pht = addChild(filename, "Program Header Table");
QTreeWidgetItem *sht = addChild(filename, "Section Header Table");
addChild(pht, "--------NoThIng here");
addChild(sht, "--------NoThIng here");
addChild(elf_header, "e_ident");
addChild(elf_header, "e_type");
addChild(elf_header, "e_machine");
addChild(elf_header, "e_e_version");
addChild(elf_header, "e_entry");
}
QTreeWidgetItem *HierarchicalViewer::addRoot(const char *name)
{
QTreeWidgetItem *item = new QTreeWidgetItem(this);
item->setText(0, QString(name));
addTopLevelItem(item);
return item;
}
QTreeWidgetItem *HierarchicalViewer::addChild(QTreeWidgetItem *parent, const char *name)
{
QTreeWidgetItem *item = new QTreeWidgetItem();
item->setText(0, QString(name));
parent->addChild(item);
return item;
}
| #include "hierarchical_viewer.hpp"
HierarchicalViewer::HierarchicalViewer(QWidget *parent) : QTreeWidget(parent)
{
/* Placeholders for testing purposes */
headerItem()->setHidden(true);
QTreeWidgetItem *elf_header = addRoot("ELF Header");
QTreeWidgetItem *pht = addRoot("Program Header Table");
QTreeWidgetItem *sht = addRoot("Section Header Table");
addChild(pht, "--------NoThIng here");
addChild(sht, "--------NoThIng here");
addChild(elf_header, "e_ident");
addChild(elf_header, "e_type");
addChild(elf_header, "e_machine");
addChild(elf_header, "e_e_version");
addChild(elf_header, "e_entry");
}
QTreeWidgetItem *HierarchicalViewer::addRoot(const char *name)
{
QTreeWidgetItem *item = new QTreeWidgetItem(this);
item->setText(0, QString(name));
addTopLevelItem(item);
return item;
}
QTreeWidgetItem *HierarchicalViewer::addChild(QTreeWidgetItem *parent, const char *name)
{
QTreeWidgetItem *item = new QTreeWidgetItem();
item->setText(0, QString(name));
parent->addChild(item);
return item;
}
|
Move unchanging lookup to outside of loop | #include "Genes/King_Protection_Gene.h"
#include <string>
#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"
#include "Game/Square.h"
#include "Moves/Move.h"
double King_Protection_Gene::score_board(const Board& board, Piece_Color perspective, size_t, double) const noexcept
{
auto square_count = 0;
for(size_t attack_index = 0; attack_index < 16; ++attack_index)
{
auto step = Move::attack_direction_from_index(attack_index);
for(auto square : Square::square_line_from(board.find_king(perspective), step))
{
if(board.piece_on_square(square))
{
break;
}
else
{
++square_count;
}
if(attack_index >= 8) // knight move
{
break;
}
}
}
constexpr const int max_square_count = 8 // knight attack
+ 7 + 7 // rooks/queen row/column attack
+ 7 + 6; // bishop/queen/pawn attack
return double(max_square_count - square_count)/max_square_count; // return score [0, 1]
}
std::string King_Protection_Gene::name() const noexcept
{
return "King Protection Gene";
}
| #include "Genes/King_Protection_Gene.h"
#include <string>
#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"
#include "Game/Square.h"
#include "Moves/Move.h"
double King_Protection_Gene::score_board(const Board& board, Piece_Color perspective, size_t, double) const noexcept
{
auto square_count = 0;
auto king_square = board.find_king(perspective);
for(size_t attack_index = 0; attack_index < 16; ++attack_index)
{
auto step = Move::attack_direction_from_index(attack_index);
for(auto square : Square::square_line_from(king_square, step))
{
if(board.piece_on_square(square))
{
break;
}
else
{
++square_count;
}
if(attack_index >= 8) // knight move
{
break;
}
}
}
constexpr const int max_square_count = 8 // knight attack
+ 7 + 7 // rooks/queen row/column attack
+ 7 + 6; // bishop/queen/pawn attack
return double(max_square_count - square_count)/max_square_count; // return score [0, 1]
}
std::string King_Protection_Gene::name() const noexcept
{
return "King Protection Gene";
}
|
Add in isStrict/setStrict to javascript bindings Parser class. | /*
Copyright libCellML Contributors
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 <emscripten/bind.h>
// To work around multiple inheritance we have to create a combined Units
// and ImportedEntity class that we can bind with Emscripten.
#define JAVASCRIPT_BINDINGS
#include "libcellml/parser.h"
using namespace emscripten;
EMSCRIPTEN_BINDINGS(libcellml_parser) {
class_<libcellml::Parser, base<libcellml::Logger>>("Parser")
.smart_ptr<std::shared_ptr<libcellml::Parser>>("ParserPtr")
.constructor(select_overload<libcellml::ParserPtr()>(&libcellml::Parser::create))
.constructor(select_overload<libcellml::ParserPtr(bool)>(&libcellml::Parser::create))
.function("parseModel", &libcellml::Parser::parseModel)
;
}
| /*
Copyright libCellML Contributors
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 <emscripten/bind.h>
// To work around multiple inheritance we have to create a combined Units
// and ImportedEntity class that we can bind with Emscripten.
#define JAVASCRIPT_BINDINGS
#include "libcellml/parser.h"
using namespace emscripten;
EMSCRIPTEN_BINDINGS(libcellml_parser) {
class_<libcellml::Parser, base<libcellml::Logger>>("Parser")
.smart_ptr<std::shared_ptr<libcellml::Parser>>("ParserPtr")
.constructor(select_overload<libcellml::ParserPtr()>(&libcellml::Parser::create))
.constructor(select_overload<libcellml::ParserPtr(bool)>(&libcellml::Parser::create))
.function("parseModel", &libcellml::Parser::parseModel)
.function("isStrict", &libcellml::Parser::isStrict)
.function("setStrict", &libcellml::Parser::setStrict)
;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.