Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix ID's of strings with spaces | /** \file
* File for the string fonts.
*
* @author Nathan Samson
*/
#include <sstream>
#include "resources/stringfontresource.h"
#include "resources/fontresource.h"
namespace Zabbr {
/**
* Constructor.
*
* @param surface The surface.
* @param id The ID of the string fonts.
*/
StringFontResource::StringFontResource(SDL_Surface* surface, std::string id)
: SDLSurfaceResource(id, surface) {
}
/**
* Destructor.
*/
StringFontResource::~StringFontResource() {
}
/**
* ID Generator.
*
* @param text The text to print
* @param font The font the string should be drawn in.
* @param c The color of the string.
*/
std::string StringFontResource::getID(std::string text, FontResource* font, SDL_Color c) {
std::stringstream sID;
sID << text << font->getName() << c.r << "_" << c.g << "_" << c.b;
std::string id;
sID >> id;
return id;
}
}
| /** \file
* File for the string fonts.
*
* @author Nathan Samson
*/
#include <sstream>
#include "resources/stringfontresource.h"
#include "resources/fontresource.h"
namespace Zabbr {
/**
* Constructor.
*
* @param surface The surface.
* @param id The ID of the string fonts.
*/
StringFontResource::StringFontResource(SDL_Surface* surface, std::string id)
: SDLSurfaceResource(id, surface) {
}
/**
* Destructor.
*/
StringFontResource::~StringFontResource() {
}
/**
* ID Generator.
*
* @param text The text to print
* @param font The font the string should be drawn in.
* @param c The color of the string.
*/
std::string StringFontResource::getID(std::string text, FontResource* font, SDL_Color c) {
std::stringstream sID;
sID << "_" << c.r << "_" << c.g << "_" << c.b;
std::string rgb;
sID >> rgb;
std::string id = text + font->getName() + rgb;
return id;
}
}
|
Use getBody() to get the function definition when the decl referenced is not definition. | //===--- CallInliner.cpp - Transfer function that inlines callee ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the callee inlining transfer function.
//
//===----------------------------------------------------------------------===//
#include "clang/Checker/PathSensitive/CheckerVisitor.h"
#include "clang/Checker/PathSensitive/GRState.h"
#include "clang/Checker/Checkers/LocalCheckers.h"
using namespace clang;
namespace {
class CallInliner : public Checker {
public:
static void *getTag() {
static int x;
return &x;
}
virtual bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
};
}
void clang::RegisterCallInliner(GRExprEngine &Eng) {
Eng.registerCheck(new CallInliner());
}
bool CallInliner::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
const GRState *state = C.getState();
const Expr *Callee = CE->getCallee();
SVal L = state->getSVal(Callee);
const FunctionDecl *FD = L.getAsFunctionDecl();
if (!FD)
return false;
if (!FD->isThisDeclarationADefinition())
return false;
// Now we have the definition of the callee, create a CallEnter node.
CallEnter Loc(CE, FD, C.getPredecessor()->getLocationContext());
C.addTransition(state, Loc);
return true;
}
| //===--- CallInliner.cpp - Transfer function that inlines callee ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the callee inlining transfer function.
//
//===----------------------------------------------------------------------===//
#include "clang/Checker/PathSensitive/CheckerVisitor.h"
#include "clang/Checker/PathSensitive/GRState.h"
#include "clang/Checker/Checkers/LocalCheckers.h"
using namespace clang;
namespace {
class CallInliner : public Checker {
public:
static void *getTag() {
static int x;
return &x;
}
virtual bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
};
}
void clang::RegisterCallInliner(GRExprEngine &Eng) {
Eng.registerCheck(new CallInliner());
}
bool CallInliner::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
const GRState *state = C.getState();
const Expr *Callee = CE->getCallee();
SVal L = state->getSVal(Callee);
const FunctionDecl *FD = L.getAsFunctionDecl();
if (!FD)
return false;
if (!FD->getBody(FD))
return false;
// Now we have the definition of the callee, create a CallEnter node.
CallEnter Loc(CE, FD, C.getPredecessor()->getLocationContext());
C.addTransition(state, Loc);
return true;
}
|
Fix an undefined behavior when storing an empty StringRef. | //===-- StringSaver.cpp ---------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/StringSaver.h"
using namespace llvm;
StringRef StringSaver::save(StringRef S) {
char *P = Alloc.Allocate<char>(S.size() + 1);
memcpy(P, S.data(), S.size());
P[S.size()] = '\0';
return StringRef(P, S.size());
}
StringRef UniqueStringSaver::save(StringRef S) {
auto R = Unique.insert(S);
if (R.second) // cache miss, need to actually save the string
*R.first = Strings.save(S); // safe replacement with equal value
return *R.first;
}
| //===-- StringSaver.cpp ---------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/StringSaver.h"
using namespace llvm;
StringRef StringSaver::save(StringRef S) {
char *P = Alloc.Allocate<char>(S.size() + 1);
if (!S.empty())
memcpy(P, S.data(), S.size());
P[S.size()] = '\0';
return StringRef(P, S.size());
}
StringRef UniqueStringSaver::save(StringRef S) {
auto R = Unique.insert(S);
if (R.second) // cache miss, need to actually save the string
*R.first = Strings.save(S); // safe replacement with equal value
return *R.first;
}
|
Fix setting server on restart | #include "Arduino.h"
#include "Game.h"
Game::Game() {
}
void Game::init() {
restart(1);
}
int Game::p1Score() { return _p1Score; }
int Game::p2Score() { return _p2Score; }
int Game::server() { return _server; }
bool Game::over() {
return (_p1Score >= 11 || _p2Score >= 11) && abs(_p1Score - _p2Score) >= 2;
}
void Game::updateScore(int p1, int p2) {
// The loop will constantly update the score, so we only act if it has changed
if ((p1 != _p1Score) || (p2 != _p2Score)) {
_p1Score = p1;
_p2Score = p2;
_serves++;
Serial.print("Updating scores ");
Serial.print(_p1Score);
Serial.print(" ");
Serial.print(_p2Score);
Serial.print(" ");
Serial.println(over());
if (_serves == 2) {
_serves = 0;
_server = _server == 1 ? 2 : 1;
}
}
}
void Game::restart(int serve) {
_p1Score = 0;
_p2Score = 0;
_server = 1;
_serves = 0;
}
| #include "Arduino.h"
#include "Game.h"
Game::Game() {
}
void Game::init() {
restart(1);
}
int Game::p1Score() { return _p1Score; }
int Game::p2Score() { return _p2Score; }
int Game::server() { return _server; }
bool Game::over() {
return (_p1Score >= 11 || _p2Score >= 11) && abs(_p1Score - _p2Score) >= 2;
}
void Game::updateScore(int p1, int p2) {
// The loop will constantly update the score, so we only act if it has changed
if ((p1 != _p1Score) || (p2 != _p2Score)) {
_p1Score = p1;
_p2Score = p2;
_serves++;
Serial.print("Updating scores ");
Serial.print(_p1Score);
Serial.print(" ");
Serial.print(_p2Score);
Serial.print(" ");
Serial.println(over());
if (_serves == 2) {
_serves = 0;
_server = _server == 1 ? 2 : 1;
}
}
}
void Game::restart(int serve) {
_p1Score = 0;
_p2Score = 0;
_server = serve;
_serves = 0;
}
|
Rewrite into async like server. | #include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include "common/CLOpts.h"
#include "common/config.h"
#include "common/file_operations.h"
#include "common/packets.h"
// Shorten the crazy long namespacing to asio tcp
using boost::asio::ip::tcp;
int main(int argc, char **argv) {
// Parse out command line options
sc2tm::CLOpts opts;
if (!opts.parseOpts(argc, argv))
return 0;
try {
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query("localhost", sc2tm::serverPortStr);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
sc2tm::SHAFileMap mapMap;
sc2tm::SHAFileMap botMap;
sc2tm::hashMapDirectory(opts.getOpt("maps"), mapMap);
sc2tm::hashBotDirectory(opts.getOpt("bots"), botMap);
for (const auto &mapInfo : mapMap)
std::cout << mapInfo.first.filename() << " SHA256: " << mapInfo.second << "\n";
for (const auto &botInfo : botMap)
std::cout << botInfo.first.filename() << " SHA256: " << botInfo.second << "\n";
// Make a handshake packet from the
sc2tm::ClientHandshakePacket handshake(botMap, mapMap);
// Write the packet to the buffer
boost::asio::streambuf buffer;
handshake.toBuffer(buffer);
auto noopFn = [&] (const boost::system::error_code& error, std::size_t bytes_transferred) {
assert(buffer.size() == 0);
};
boost::asio::async_write(socket, buffer, noopFn);
}
catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
| #include <iostream>
#include <boost/asio.hpp>
#include "client/Client.h"
#include "common/CLOpts.h"
#include "common/config.h"
// Shorten the crazy long namespacing to asio tcp
using boost::asio::ip::tcp;
int main(int argc, char **argv) {
// Parse out command line options
sc2tm::CLOpts opts;
if (!opts.parseOpts(argc, argv))
return 0;
try {
boost::asio::io_service service;
sc2tm::Client s(service, "localhost", sc2tm::serverPortStr, opts.getOpt("bots"),
opts.getOpt("maps"));
service.run();
}
catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
|
Fix initialization race in MSVC2013 | // Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "descriptors.h"
#include <atomic>
using namespace leap;
descriptor_entry::descriptor_entry(const std::type_info& ti, const descriptor& (*pfnDesc)()) :
Next(descriptors::Link(*this)),
ti(ti),
pfnDesc(pfnDesc)
{}
const descriptor_entry* descriptors::s_pHead = nullptr;
const descriptor_entry* descriptors::Link(descriptor_entry& entry) {
auto retVal = s_pHead;
s_pHead = &entry;
return retVal;
}
| // Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "descriptors.h"
#include <atomic>
using namespace leap;
descriptor_entry::descriptor_entry(const std::type_info& ti, const descriptor& (*pfnDesc)()) :
Next(descriptors::Link(*this)),
ti(ti),
pfnDesc(pfnDesc)
{}
const descriptor_entry* descriptors::s_pHead = nullptr;
#if _MSC_VER <= 1800
// Used for MSVC2013 because it doesn't have magic statics, so we have to initialize all
// of our cached descriptors to ensure that we don't wind up with initialization races.
static bool global_initializer = [] {
for (auto& cur : descriptors{})
cur.pfnDesc();
return true;
}();
#endif
const descriptor_entry* descriptors::Link(descriptor_entry& entry) {
auto retVal = s_pHead;
s_pHead = &entry;
return retVal;
}
|
Fix broken compilation for trees without the PISTACHE_USE_SSL option | /* utils.cc
Louis Solofrizzo 2019-10-17
Utilities for pistache
*/
#include <pistache/peer.h>
#include <unistd.h>
ssize_t SSL_sendfile(SSL *out, int in, off_t *offset, size_t count)
{
unsigned char buffer[4096] = { 0 };
ssize_t ret;
ssize_t written;
size_t to_read;
if (in == -1)
return -1;
to_read = sizeof(buffer) > count ? count : sizeof(buffer);
if (offset != NULL)
ret = pread(in, buffer, to_read, *offset);
else
ret = read(in, buffer, to_read);
if (ret == -1)
return -1;
written = SSL_write(out, buffer, ret);
if (offset != NULL)
*offset += written;
return written;
}
| /* utils.cc
Louis Solofrizzo 2019-10-17
Utilities for pistache
*/
#include <pistache/peer.h>
#include <unistd.h>
#ifdef PISTACHE_USE_SSL
ssize_t SSL_sendfile(SSL *out, int in, off_t *offset, size_t count)
{
unsigned char buffer[4096] = { 0 };
ssize_t ret;
ssize_t written;
size_t to_read;
if (in == -1)
return -1;
to_read = sizeof(buffer) > count ? count : sizeof(buffer);
if (offset != NULL)
ret = pread(in, buffer, to_read, *offset);
else
ret = read(in, buffer, to_read);
if (ret == -1)
return -1;
written = SSL_write(out, buffer, ret);
if (offset != NULL)
*offset += written;
return written;
}
#endif /* PISTACHE_USE_SSL */
|
Mark down todo for HydraxConfigFile support. | // For conditions of distribution and use, see copyright notice in license.txt
#if SKYX_ENABLED
#include "EC_SkyX.h"
#endif
#if HYDRAX_ENABLED
#include "EC_Hydrax.h"
#endif
#include "Framework.h"
#include "SceneAPI.h"
#include "IComponentFactory.h"
extern "C"
{
DLLEXPORT void TundraPluginMain(Framework *fw)
{
Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object.
#if SKYX_ENABLED
fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_SkyX>));
#endif
#if HYDRAX_ENABLED
fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Hydrax>));
#endif
}
} // ~extern "C"
| // For conditions of distribution and use, see copyright notice in license.txt
#if SKYX_ENABLED
#include "EC_SkyX.h"
#endif
#if HYDRAX_ENABLED
#include "EC_Hydrax.h"
#endif
#include "Framework.h"
#include "SceneAPI.h"
#include "IComponentFactory.h"
///\todo HydraxConfigFile support
//#include "AssetAPI.h"
//#include "HydraxConfigAsset.h"
extern "C"
{
DLLEXPORT void TundraPluginMain(Framework *fw)
{
Framework::SetInstance(fw); // Inside this DLL, remember the pointer to the global framework object.
#if SKYX_ENABLED
fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_SkyX>));
#endif
#if HYDRAX_ENABLED
fw->Scene()->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EC_Hydrax>));
///\todo HydraxConfigFile support
// fw->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<HydraxConfigAsset>("HydraxConfigFile")));
#endif
}
} // ~extern "C"
|
Fix crash when going straight to benchmark | #include "env.hpp"
#include "java_classes.hpp"
#include <atomic>
#include <fmo/benchmark.hpp>
#include <thread>
namespace {
struct {
Reference<Callback> callbackRef;
JavaVM* javaVM;
JNIEnv* threadEnv;
std::atomic<bool> stop;
} global;
}
void Java_cz_fmo_Lib_benchmarkingStart(JNIEnv* env, jclass, jobject cbObj) {
global.callbackRef = {env, cbObj};
global.stop = false;
env->GetJavaVM(&global.javaVM);
std::thread thread([]() {
Env threadEnv{global.javaVM, "benchmarking"};
global.threadEnv = threadEnv.get();
fmo::Registry::get().runAll([](const char* cStr) {
Callback cb{global.callbackRef.get(global.threadEnv)};
cb.log(cStr);
},
[]() {
return bool(global.stop);
});
global.callbackRef.release(global.threadEnv);
});
thread.detach();
}
void Java_cz_fmo_Lib_benchmarkingStop(JNIEnv* env, jclass) {
global.stop = true;
}
| #include "env.hpp"
#include "java_classes.hpp"
#include <atomic>
#include <fmo/benchmark.hpp>
#include <thread>
namespace {
struct {
Reference<Callback> callbackRef;
JavaVM* javaVM;
JNIEnv* threadEnv;
std::atomic<bool> stop;
} global;
}
void Java_cz_fmo_Lib_benchmarkingStart(JNIEnv* env, jclass, jobject cbObj) {
initJavaClasses(env);
global.callbackRef = {env, cbObj};
global.stop = false;
env->GetJavaVM(&global.javaVM);
std::thread thread([]() {
Env threadEnv{global.javaVM, "benchmarking"};
global.threadEnv = threadEnv.get();
fmo::Registry::get().runAll([](const char* cStr) {
Callback cb{global.callbackRef.get(global.threadEnv)};
cb.log(cStr);
},
[]() {
return bool(global.stop);
});
global.callbackRef.release(global.threadEnv);
});
thread.detach();
}
void Java_cz_fmo_Lib_benchmarkingStop(JNIEnv* env, jclass) {
global.stop = true;
}
|
Make a test more explicit. NFC. | // Tests for instrumentation of C++ constructors and destructors.
//
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.11.0 -x c++ %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck %s
struct Foo {
Foo() {}
Foo(int) {}
~Foo() {}
};
struct Bar : public Foo {
Bar() {}
Bar(int x) : Foo(x) {}
~Bar();
};
Foo foo;
Foo foo2(1);
Bar bar;
// Profile data for complete constructors and destructors must absent.
// CHECK-NOT: @__profc__ZN3FooC1Ev
// CHECK-NOT: @__profc__ZN3FooC1Ei
// CHECK-NOT: @__profc__ZN3FooD1Ev
// CHECK-NOT: @__profc__ZN3BarC1Ev
// CHECK-NOT: @__profc__ZN3BarD1Ev
// CHECK-NOT: @__profc__ZN3FooD1Ev
int main() {
}
| // Tests for instrumentation of C++ constructors and destructors.
//
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.11.0 -x c++ %s -o %t -emit-llvm -fprofile-instrument=clang
// RUN: FileCheck %s -input-file=%t -check-prefix=INSTR
// RUN: FileCheck %s -input-file=%t -check-prefix=NOINSTR
struct Foo {
Foo() {}
Foo(int) {}
~Foo() {}
};
struct Bar : public Foo {
Bar() {}
Bar(int x) : Foo(x) {}
~Bar();
};
Foo foo;
Foo foo2(1);
Bar bar;
// Profile data for complete constructors and destructors must absent.
// INSTR: @__profc_main =
// INSTR: @__profc__ZN3FooC2Ev =
// INSTR: @__profc__ZN3FooD2Ev =
// INSTR: @__profc__ZN3FooC2Ei =
// INSTR: @__profc__ZN3BarC2Ev =
// NOINSTR-NOT: @__profc__ZN3FooC1Ev
// NOINSTR-NOT: @__profc__ZN3FooC1Ei
// NOINSTR-NOT: @__profc__ZN3FooD1Ev
// NOINSTR-NOT: @__profc__ZN3BarC1Ev
// NOINSTR-NOT: @__profc__ZN3BarD1Ev
// NOINSTR-NOT: @__profc__ZN3FooD1Ev
int main() {
}
|
Add a missing include in test. | // RUN: %clangxx -O0 -g %s -o %t -lcrypt && %run %t
// crypt() is missing from Android and -lcrypt from darwin.
// UNSUPPORTED: android, darwin
#include <assert.h>
#include <unistd.h>
#include <cstring>
int
main (int argc, char** argv)
{
{
char *p = crypt("abcdef", "xz");
volatile size_t z = strlen(p);
}
{
char *p = crypt("abcdef", "$1$");
volatile size_t z = strlen(p);
}
{
char *p = crypt("abcdef", "$5$");
volatile size_t z = strlen(p);
}
{
char *p = crypt("abcdef", "$6$");
volatile size_t z = strlen(p);
}
}
| // RUN: %clangxx -O0 -g %s -o %t -lcrypt && %run %t
// crypt() is missing from Android and -lcrypt from darwin.
// UNSUPPORTED: android, darwin
#include <assert.h>
#include <unistd.h>
#include <cstring>
#include <crypt.h>
int
main (int argc, char** argv)
{
{
char *p = crypt("abcdef", "xz");
volatile size_t z = strlen(p);
}
{
char *p = crypt("abcdef", "$1$");
volatile size_t z = strlen(p);
}
{
char *p = crypt("abcdef", "$5$");
volatile size_t z = strlen(p);
}
{
char *p = crypt("abcdef", "$6$");
volatile size_t z = strlen(p);
}
}
|
Clarify reason for failing tests | #include <test/unit/math/test_ad.hpp>
#include <limits>
TEST(mathMixScalFun, std_normal_cdf_derivatives) {
auto f = [](const auto& y) { return stan::math::std_normal_cdf(y); };
stan::test::expect_ad(f, -50.0);
// stan::test::expect_ad(f, -20.0 * stan::math::SQRT_TWO);
// stan::test::expect_ad(f, -10.0);
stan::test::expect_ad(f, -5.5);
stan::test::expect_ad(f, 0.0);
stan::test::expect_ad(f, 0.15);
stan::test::expect_ad(f, 1.14);
stan::test::expect_ad(f, 3.00);
stan::test::expect_ad(f, 10.00);
}
| #include <test/unit/math/test_ad.hpp>
#include <limits>
TEST(mathMixScalFun, std_normal_cdf_derivatives) {
auto f = [](const auto& y) { return stan::math::std_normal_cdf(y); };
stan::test::expect_ad(f, -50.0);
// the following fails because AD returns -nan in the Hessian
// stan::test::expect_ad(f, -20.0 * stan::math::SQRT_TWO);
// the following fails because AD returns inf in the Hessian
// stan::test::expect_ad(f, -20.0);
stan::test::expect_ad(f, -19);
stan::test::expect_ad(f, -5.5);
stan::test::expect_ad(f, 0.0);
stan::test::expect_ad(f, 0.15);
stan::test::expect_ad(f, 1.14);
stan::test::expect_ad(f, 3.00);
stan::test::expect_ad(f, 10.00);
}
|
Call OnSlide when the slider position changes programmatically | // Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "Slider.h"
void Slider::Buddy(Control *buddy, bool bottomOrRight) {
_buddyWnd = buddy->Handle();
SendMessage(_hWnd, TBM_SETBUDDY,
(WPARAM) bottomOrRight ? FALSE : TRUE, (LPARAM) _buddyWnd);
}
int Slider::Position() {
return (int) SendMessage(_hWnd, TBM_GETPOS, 0, 0);
}
void Slider::Position(int position) {
SendMessage(_hWnd, TBM_SETPOS, (WPARAM) TRUE, (LPARAM) position);
}
void Slider::Range(int lo, int hi) {
SendMessage(_hWnd, TBM_SETRANGE, (WPARAM) TRUE, MAKELPARAM(lo, hi));
}
BOOL Slider::Notification(NMHDR *nHdr) {
switch (nHdr->code) {
case TRBN_THUMBPOSCHANGING:
if (OnSlide) {
NMTRBTHUMBPOSCHANGING *pc
= reinterpret_cast<NMTRBTHUMBPOSCHANGING *>(nHdr);
OnSlide(pc);
}
}
return FALSE;
}
| // Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "Slider.h"
void Slider::Buddy(Control *buddy, bool bottomOrRight) {
_buddyWnd = buddy->Handle();
SendMessage(_hWnd, TBM_SETBUDDY,
(WPARAM) bottomOrRight ? FALSE : TRUE, (LPARAM) _buddyWnd);
}
int Slider::Position() {
return (int) SendMessage(_hWnd, TBM_GETPOS, 0, 0);
}
void Slider::Position(int position) {
SendMessage(_hWnd, TBM_SETPOS, (WPARAM) TRUE, (LPARAM) position);
if (OnSlide) {
OnSlide();
}
}
void Slider::Range(int lo, int hi) {
SendMessage(_hWnd, TBM_SETRANGE, (WPARAM) TRUE, MAKELPARAM(lo, hi));
}
BOOL Slider::Notification(NMHDR *nHdr) {
switch (nHdr->code) {
case TRBN_THUMBPOSCHANGING:
if (OnSlide) {
NMTRBTHUMBPOSCHANGING *pc
= reinterpret_cast<NMTRBTHUMBPOSCHANGING *>(nHdr);
OnSlide(pc);
}
}
return FALSE;
}
|
Add in support for when there is no system store support. | /*
* qca_systemstore_flatfile.cpp - Qt Cryptographic Architecture
* Copyright (C) 2004,2005 Justin Karneges
*
* 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) 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
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "qca_systemstore.h"
#include <QtCore>
namespace QCA {
bool qca_have_systemstore()
{
QFile f(QCA_SYSTEMSTORE_PATH);
return f.open(QFile::ReadOnly);
}
CertificateCollection qca_get_systemstore(const QString &provider)
{
return CertificateCollection::fromFlatTextFile(QCA_SYSTEMSTORE_PATH, 0, provider);
}
}
| /*
* qca_systemstore_flatfile.cpp - Qt Cryptographic Architecture
* Copyright (C) 2004,2005 Justin Karneges
*
* 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) 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
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "qca_systemstore.h"
#include <QtCore>
namespace QCA {
bool qca_have_systemstore()
{
#ifdef QCA_NO_SYSTEMSTORE
return false;
#else
QFile f(QCA_SYSTEMSTORE_PATH);
return f.open(QFile::ReadOnly);
#endif
}
CertificateCollection qca_get_systemstore(const QString &provider)
{
#ifdef QCA_NO_SYSTEMSTORE
Q_UNUSED(provider);
return CertificateCollection();
#else
return CertificateCollection::fromFlatTextFile(QCA_SYSTEMSTORE_PATH, 0, provider);
#endif
}
}
|
Fix a stack corruption bug in Consume hook module. | //The injector source file for the Consume hook module.
#include "consume.h"
#include <hook_tools.h>
namespace {
void __declspec(naked) consumeHitWrapper() {
CUnit *target, *caster;
__asm {
PUSHAD
MOV caster, ESI
MOV target, EAX
}
hooks::consumeHitHook(target, caster);
__asm {
POPAD
RETN
}
}
} //Unnamed namespace
namespace hooks {
void injectConsumeHooks() {
callPatch(consumeHitWrapper, 0x0048BB27);
}
} //hooks | //The injector source file for the Consume hook module.
#include "consume.h"
#include <hook_tools.h>
namespace {
void __declspec(naked) consumeHitWrapper() {
static CUnit *target, *caster;
__asm {
PUSHAD
MOV caster, ESI
MOV target, EAX
}
hooks::consumeHitHook(target, caster);
__asm {
POPAD
RETN
}
}
} //Unnamed namespace
namespace hooks {
void injectConsumeHooks() {
callPatch(consumeHitWrapper, 0x0048BB27);
}
} //hooks |
Make compile_flags.txt negative test more hermetic | // RUN: rm -rf %t
// RUN: mkdir -p %t/Src
// RUN: cp "%s" "%t/Src/test.cpp"
// RUN: mkdir -p %t/Include
// RUN: cp "%S/Inputs/fixed-header.h" "%t/Include/"
// -I flag is relative to %t (where compile_flags is), not Src/.
// RUN: echo '-IInclude/' >> %t/compile_flags.txt
// RUN: echo "-Dklazz=class" >> %t/compile_flags.txt
// RUN: echo '-std=c++11' >> %t/compile_flags.txt
// RUN: clang-check "%t/Src/test.cpp" 2>&1
// RUN: not clang-check "%s" 2>&1 | FileCheck "%s" -check-prefix=NODB
// NODB: unknown type name 'klazz'
klazz F{};
// NODB: 'fixed-header.h' file not found
#include "fixed-header.h"
static_assert(SECRET_SYMBOL == 1, "");
| // RUN: rm -rf %t
// RUN: mkdir -p %t/Src
// RUN: cp "%s" "%t/Src/test.cpp"
// RUN: mkdir -p %t/Include
// RUN: cp "%S/Inputs/fixed-header.h" "%t/Include/"
// -I flag is relative to %t (where compile_flags is), not Src/.
// RUN: echo '-IInclude/' >> %t/compile_flags.txt
// RUN: echo "-Dklazz=class" >> %t/compile_flags.txt
// RUN: echo '-std=c++11' >> %t/compile_flags.txt
// RUN: clang-check "%t/Src/test.cpp" 2>&1
// RUN: echo > %t/compile_flags.txt
// RUN: not clang-check "%t/Src/test.cpp" 2>&1 | FileCheck "%s" -check-prefix=NODB
// NODB: unknown type name 'klazz'
klazz F{};
// NODB: 'fixed-header.h' file not found
#include "fixed-header.h"
static_assert(SECRET_SYMBOL == 1, "");
|
Use the local variable instead of a global accessor. | /************************************************************************
*
* Flood Project (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#include "GameRuntime/API.h"
#include "GameRuntime/Game.h"
//-----------------------------------//
int main(int argc, char** argv)
{
Game gameInstance;
game()->run();
return 0;
}
| /************************************************************************
*
* Flood Project (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#include "GameRuntime/API.h"
#include "GameRuntime/Game.h"
//-----------------------------------//
int main(int argc, char** argv)
{
Game gameInstance;
gameInstance.run();
return 0;
} |
Fix an OSS build error. | // Copyright 2010-2021, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| // Copyright 2010-2021, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
int main(int argc, char* argv[]) {
return 0;
}
|
Add comment to sqrt calculation | #include<math.h>
bool isPrimeBruteForce(int x) {
if (x < 2)
return false;
float sqroot_x = sqrt(x);
for(int i=0; i <= sqroot_x; i++) {
if (x%i==0)
return false;
}
return true;
}
| #include<math.h>
bool isPrimeBruteForce(int x) {
if (x < 2)
return false;
float sqroot_x = sqrt(x);
for(int i=0; i <= sqroot_x; i++) { /* If there were only factors above the square root of x, they would be bigger than x itself. */
if (x%i==0)
return false;
}
return true;
}
|
Add newline at the end of file, to silence compiler warning. | //===--- RewriteTest.cpp - Rewriter playground ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a testbed.
//
//===----------------------------------------------------------------------===//
#include "clang.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Rewrite/TokenRewriter.h"
#include <iostream>
void clang::DoRewriteTest(Preprocessor &PP, const std::string &InFileName,
const std::string &OutFileName) {
SourceManager &SM = PP.getSourceManager();
const LangOptions &LangOpts = PP.getLangOptions();
TokenRewriter Rewriter(SM.getMainFileID(), SM, LangOpts);
// Throw <i> </i> tags around comments.
for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
E = Rewriter.token_end(); I != E; ++I) {
if (I->isNot(tok::comment)) continue;
Rewriter.AddTokenBefore(I, "<i>");
Rewriter.AddTokenAfter(I, "</i>");
}
// Print out the output.
for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
E = Rewriter.token_end(); I != E; ++I)
std::cout << PP.getSpelling(*I);
} | //===--- RewriteTest.cpp - Rewriter playground ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a testbed.
//
//===----------------------------------------------------------------------===//
#include "clang.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Rewrite/TokenRewriter.h"
#include <iostream>
void clang::DoRewriteTest(Preprocessor &PP, const std::string &InFileName,
const std::string &OutFileName) {
SourceManager &SM = PP.getSourceManager();
const LangOptions &LangOpts = PP.getLangOptions();
TokenRewriter Rewriter(SM.getMainFileID(), SM, LangOpts);
// Throw <i> </i> tags around comments.
for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
E = Rewriter.token_end(); I != E; ++I) {
if (I->isNot(tok::comment)) continue;
Rewriter.AddTokenBefore(I, "<i>");
Rewriter.AddTokenAfter(I, "</i>");
}
// Print out the output.
for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
E = Rewriter.token_end(); I != E; ++I)
std::cout << PP.getSpelling(*I);
}
|
Modify to initialize one time. | #include "geometry/vertex.h"
namespace aten
{
std::vector<int> VertexManager::s_indices;
std::vector<vertex> VertexManager::s_vertices;
GeomVertexBuffer VertexManager::s_vb;
void VertexManager::build()
{
s_vb.init(
sizeof(vertex),
s_vertices.size(),
0,
&s_vertices[0]);
}
}
| #include "geometry/vertex.h"
namespace aten
{
std::vector<int> VertexManager::s_indices;
std::vector<vertex> VertexManager::s_vertices;
GeomVertexBuffer VertexManager::s_vb;
void VertexManager::build()
{
if (!s_vertices.empty()
&& !s_vb.isInitialized())
{
s_vb.init(
sizeof(vertex),
s_vertices.size(),
0,
&s_vertices[0]);
}
}
}
|
Test them all. Fix interval | #include <TimerMessage.h>
#include <QDebug>
TimerMessage::TimerMessage(QObject *parent) :
QObject(parent),
m_pTimer(new QTimer(this)),
m_counter(0)
{
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(printCounter()) );
m_pTimer->setInterval(1000);
m_pTimer->start();
}
void TimerMessage::printCounter()
{
print(QString("Message counter # %1").arg(m_counter++));
if(m_counter >= 1024)
m_counter = 0;
}
void TimerMessage::print(const QString &msg)
{
qDebug() << qPrintable(msg);
}
| #include <TimerMessage.h>
#include <QDebug>
TimerMessage::TimerMessage(QObject *parent) :
QObject(parent),
m_pTimer(new QTimer(this)),
m_counter(0)
{
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(printCounter()) );
m_pTimer->setInterval(750);
m_pTimer->start();
}
void TimerMessage::printCounter()
{
print(QString("Message counter # %1").arg(m_counter++));
if(m_counter >= 1024)
m_counter = 0;
}
void TimerMessage::print(const QString &msg)
{
qDebug() << qPrintable(msg);
}
|
Add bubbleSort() to stable sort. | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int length, count = 0;
cin >> length;
vector<string> vector(length);
for (int i = 0; i < length; i++)
{
cin >> vector[i];
}
//sort logic
cout << vector[0];
for (int i = 1; i < length; i++)
{
cout << ' '<< vector[i];
}
cout << endl << count << endl;
} | #include <iostream>
#include <vector>
using namespace std;
class Card
{
private:
string name_;
int value_;
public:
Card(string card)
{
name_ = card;
value_ = stoi(card.substr(1, 1));
};
string name(){return name_;};
int value(){return value_;};
};
void bubbleSort(vector<Card *> &cards);
void shellSort(vector<Card *> &cards);
int main()
{
int length, count = 0;
cin >> length;
vector<Card*> cards(length);
for (int i = 0; i < length; i++)
{
string card;
cin >> card;
cards[i] = new Card(card);
}
bubbleSort(cards);
shellSort(cards);
}
void bubbleSort(vector<Card *> &cards)
{
for(int i = 0; i < cards.size(); i++)
{
for(int j = cards.size() - 1; j > i; j--)
{
if(cards[j-1]->value() > cards[j]->value())
{
Card* temp = cards[j-1];
cards[j-1] = cards[j];
cards[j] = temp;
}
}
}
cout << cards[0]->name();
for(int i = 1; i < cards.size(); i++)
{
cout << ' ' << cards[i]->name();
}
cout << endl << "Stable" << endl;
}
void shellSort(vector<Card *> &cards)
{
}
|
Add a stub function to init the module. | #include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"
| #include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"
PyObject* PyInit_pyQuantuccia(void){
return NULL;
} |
Make test images look better | #include <orz/types.h>
#include "hw3d_opengl_common.h"
namespace Hw3D
{
GLint GetGlInternalFormat(Format fmt)
{
return GL_RGBA;
}
GLenum GetGlFormat(Format)
{
return GL_RGBA;
}
GLenum GetGlDataType(Format)
{
return GL_UNSIGNED_BYTE;
}
::std::string GetGlErrorString(GLenum error)
{
switch (error)
{
case GL_NO_ERROR:
return "No error";
case GL_INVALID_ENUM:
return "Invalid enum";
case GL_INVALID_VALUE:
return "Invalid value";
case GL_INVALID_OPERATION:
return "Invalid operation";
case GL_INVALID_FRAMEBUFFER_OPERATION:
return "Invalid framebuffer operation";
case GL_OUT_OF_MEMORY:
return "Out of memory";
case GL_STACK_UNDERFLOW:
return "Stack underflow";
case GL_STACK_OVERFLOW:
return "Stack overflow";
default:
return "Unknown error code:" + ToAString(error);
}
}
}
| #include <orz/types.h>
#include "hw3d_opengl_common.h"
namespace Hw3D
{
GLint GetGlInternalFormat(Format fmt)
{
return GL_RGBA;
}
GLenum GetGlFormat(Format)
{
return GL_BGRA;
}
GLenum GetGlDataType(Format)
{
return GL_UNSIGNED_BYTE;
}
::std::string GetGlErrorString(GLenum error)
{
switch (error)
{
case GL_NO_ERROR:
return "No error";
case GL_INVALID_ENUM:
return "Invalid enum";
case GL_INVALID_VALUE:
return "Invalid value";
case GL_INVALID_OPERATION:
return "Invalid operation";
case GL_INVALID_FRAMEBUFFER_OPERATION:
return "Invalid framebuffer operation";
case GL_OUT_OF_MEMORY:
return "Out of memory";
case GL_STACK_UNDERFLOW:
return "Stack underflow";
case GL_STACK_OVERFLOW:
return "Stack overflow";
default:
return "Unknown error code:" + ToAString(error);
}
}
}
|
Fix "warning: returning reference to local temporary object" | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include <stddef.h>
#include "chrome/browser/safe_browsing/ui_manager.h"
namespace safe_browsing {
const scoped_refptr<SafeBrowsingUIManager>&
SafeBrowsingService::ui_manager() const {
return nullptr;
}
void SafeBrowsingService::DisableQuicOnIOThread() {}
} // namespace safe_browsing
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include <stddef.h>
#include "chrome/browser/safe_browsing/ui_manager.h"
namespace safe_browsing {
const scoped_refptr<SafeBrowsingUIManager>&
SafeBrowsingService::ui_manager() const {
static scoped_refptr<SafeBrowsingUIManager> empty;
return empty;
}
void SafeBrowsingService::DisableQuicOnIOThread() {}
} // namespace safe_browsing
|
Write test results to a file for easier examination | #include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include "Suite.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{
setUpSuite();
// Create the event manager and test controller
CPPUNIT_NS::TestResult controller;
// Add a listener that colllects test result
CPPUNIT_NS::TestResultCollector result;
controller.addListener( &result );
// Add a listener that print dots as test run.
CPPUNIT_NS::BriefTestProgressListener progress;
controller.addListener( &progress );
// Add the top suite to the test runner
CPPUNIT_NS::TestRunner runner;
runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
runner.run( controller );
// Print test in a compiler compatible format.
CPPUNIT_NS::CompilerOutputter* outputter =
CPPUNIT_NS::CompilerOutputter::defaultOutputter(&result, std::cout);
outputter->write();
delete outputter;
tearDownSuite();
return result.wasSuccessful() ? 0 : 1;
}
| #include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include "Suite.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{
setUpSuite();
// Create the event manager and test controller
CPPUNIT_NS::TestResult controller;
// Add a listener that colllects test result
CPPUNIT_NS::TestResultCollector result;
controller.addListener( &result );
// Add a listener that print dots as test run.
CPPUNIT_NS::BriefTestProgressListener progress;
controller.addListener( &progress );
// Add the top suite to the test runner
CPPUNIT_NS::TestRunner runner;
runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
runner.run( controller );
// Print test results to a file
std::ofstream ofile("OgreTestResults.log");
CPPUNIT_NS::CompilerOutputter* outputter =
CPPUNIT_NS::CompilerOutputter::defaultOutputter(&result, ofile);
outputter->write();
delete outputter;
tearDownSuite();
return result.wasSuccessful() ? 0 : 1;
}
|
Fix bug with country group name. | #include "country_decl.hpp"
string storage::CountryInfo::FileName2FullName(string fName)
{
size_t const i = fName.find('_');
if (i != string::npos)
{
// replace '_' with ", "
fName[i] = ',';
fName.insert(i+1, " ");
}
return fName;
}
void storage::CountryInfo::FullName2GroupAndMap(string const & fName, string & group, string & map)
{
size_t pos = fName.find(",");
if (pos == string::npos)
{
map = fName;
}
else
{
map = fName.substr(pos + 2);
group = fName.substr(0, pos);
}
}
| #include "country_decl.hpp"
string storage::CountryInfo::FileName2FullName(string fName)
{
size_t const i = fName.find('_');
if (i != string::npos)
{
// replace '_' with ", "
fName[i] = ',';
fName.insert(i+1, " ");
}
return fName;
}
void storage::CountryInfo::FullName2GroupAndMap(string const & fName, string & group, string & map)
{
size_t pos = fName.find(",");
if (pos == string::npos)
{
map = fName;
group.clear();
}
else
{
map = fName.substr(pos + 2);
group = fName.substr(0, pos);
}
}
|
Improve output of standard exceptions. | #include "Output.h"
#include "Parameters.h"
#include "Parser.h"
#include "PerformanceTracker.h"
#include "Simulation.h"
#include <iostream>
#include <map>
#include <string>
using namespace pica;
using namespace std;
int realMain(int argc, char* argv[]);
int main(int argc, char* argv[])
{
try {
return realMain(argc, argv);
}
catch (...) {
cout << "ERROR: Unhandled exception, benchmark terminated\n";
return EXIT_FAILURE;
}
}
int realMain(int argc, char* argv[])
{
printHeader();
Parameters parameters = readParameters(argc, argv);
printParameters(parameters);
PerformanceTracker tracker;
runSimulation(parameters, tracker);
printPerformance(tracker);
return 0;
}
| #include "Output.h"
#include "Parameters.h"
#include "Parser.h"
#include "PerformanceTracker.h"
#include "Simulation.h"
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
using namespace pica;
using namespace std;
int realMain(int argc, char* argv[]);
int main(int argc, char* argv[])
{
try {
return realMain(argc, argv);
}
catch (std::exception& e) {
cout << "ERROR: Unhandled exception with message '" << e.what()
<< "', benchmark terminated\n";
return EXIT_FAILURE;
}
catch (...) {
cout << "ERROR: Unhandled exception, benchmark terminated\n";
return EXIT_FAILURE;
}
}
int realMain(int argc, char* argv[])
{
printHeader();
Parameters parameters = readParameters(argc, argv);
printParameters(parameters);
PerformanceTracker tracker;
runSimulation(parameters, tracker);
printPerformance(tracker);
return 0;
}
|
Revert this, we have a better way to do this. | // RUN: clang-cc -fsyntax-only -verify %s
void f1() {
struct X {
struct Y;
};
struct X::Y {
void f() {}
};
}
void f2() {
struct X {
struct Y;
struct Y {
void f() {}
};
};
}
// A class nested within a local class is a local class.
void f3(int a) { // expected-note{{'a' declared here}}
struct X {
struct Y {
int f() {
return a; // expected-error{{reference to local variable 'a' declared in enclosed function 'f3'}}
return 1;
}
};
};
}
| // RUN: clang-cc -fsyntax-only -verify %s
void f1() {
struct X {
struct Y;
};
struct X::Y {
void f() {}
};
}
void f2() {
struct X {
struct Y;
struct Y {
void f() {}
};
};
}
// A class nested within a local class is a local class.
void f3(int a) { // expected-note{{'a' declared here}}
struct X {
struct Y {
int f() { return a; } // expected-error{{reference to local variable 'a' declared in enclosed function 'f3'}}
};
};
}
|
Improve hex encoder unit test | /*
* SOPMQ - Scalable optionally persistent message queue
* Copyright 2014 InWorldz, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gtest/gtest.h"
#include "util.h"
#include <string>
using sopmq::shared::util;
TEST(UtilTest, HexEncoderWorks)
{
std::string testStr("abcde");
std::string result = util::hex_encode((const unsigned char*)testStr.c_str(), testStr.size());
ASSERT_EQ("6162636465", result);
}
TEST(UtilTest, RandomBytes)
{
std::string bytes = util::random_bytes(1024);
ASSERT_EQ(1024, bytes.length());
} | /*
* SOPMQ - Scalable optionally persistent message queue
* Copyright 2014 InWorldz, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gtest/gtest.h"
#include "util.h"
#include <string>
using sopmq::shared::util;
TEST(UtilTest, HexEncoderWorks)
{
std::string testStr("abcdeO");
std::string result = util::hex_encode((const unsigned char*)testStr.c_str(), testStr.size());
ASSERT_EQ("61626364654F", result);
}
TEST(UtilTest, RandomBytes)
{
std::string bytes = util::random_bytes(1024);
ASSERT_EQ(1024, bytes.length());
} |
Fix solution to problem 31 | // Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 31
// Coin sums
namespace problem_31 {
constexpr long n_denoms = 8;
constexpr long denom_values[n_denoms] = {
1, 2, 5, 10, 20, 50, 100, 200
};
long n_coin_sums(const long sum, const long index) {
if (sum < 0 || index < 0) {
return 0;
}
if (sum == 0) {
return 1;
}
const long value = denom_values[index];
const long with = n_coin_sums(sum - value, index);
const long without = n_coin_sums(sum, index - 1);
return with + without;
}
long solve() {
return n_coin_sums(200, n_denoms);
}
} // namespace problem_31
| // Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 31
// Coin sums
namespace problem_31 {
constexpr long n_denoms = 8;
constexpr long denom_values[n_denoms] = {
1, 2, 5, 10, 20, 50, 100, 200
};
long n_coin_sums(const long sum, const long index) {
if (sum < 0 || index < 0) {
return 0;
}
if (sum == 0) {
return 1;
}
const long value = denom_values[index];
const long with = n_coin_sums(sum - value, index);
const long without = n_coin_sums(sum, index - 1);
return with + without;
}
long solve() {
return n_coin_sums(200, n_denoms - 1);
}
} // namespace problem_31
|
Add null c constructor test. | #include "ReQL-test.hpp"
#include "catch.h"
#include <limits>
using namespace ReQL;
TEST_CASE("Connection", "[c++][connect]") {
Connection conn = connect();
REQUIRE(conn.isOpen());
}
TEST_CASE("Expr", "[c][expr]") {
SECTION("number") {
_ReQL_Op_t num;
const double val = 42.0;
_reql_number_init(&num, val);
CHECK(val == _reql_to_number(&num));
}
SECTION("number edges") {
_ReQL_Op_t num;
const double val = std::numeric_limits<std::double_t>::max();
_reql_number_init(&num, val);
CHECK(val == _reql_to_number(&num));
}
SECTION("string") {
_ReQL_Op_t string;
const uint32_t size = 12;
uint8_t buf[size] = "Hello World";
std::string orig = std::string((char *)buf, size);
_reql_string_init(&string, buf, size, size);
CHECK(orig.compare(0, size, (char *)_reql_string_buf(&string), size) == 0);
CHECK(size == _reql_string_size(&string));
}
}
| #include "ReQL-test.hpp"
#include "catch.h"
#include <limits>
using namespace ReQL;
TEST_CASE("Connection", "[c++][connect]") {
Connection conn = connect();
REQUIRE(conn.isOpen());
}
TEST_CASE("Expr", "[c][expr]") {
SECTION("null") {
_ReQL_Op_t null;
_reql_null_init(&null);
CHECK(_reql_datum_type(&null) == _REQL_R_NULL);
}
SECTION("number") {
_ReQL_Op_t num;
const double val = 42.0;
_reql_number_init(&num, val);
CHECK(val == _reql_to_number(&num));
}
SECTION("number edges") {
_ReQL_Op_t num;
const double val = std::numeric_limits<std::double_t>::max();
_reql_number_init(&num, val);
CHECK(val == _reql_to_number(&num));
}
SECTION("string") {
_ReQL_Op_t string;
const uint32_t size = 12;
uint8_t buf[size] = "Hello World";
std::string orig = std::string((char *)buf, size);
_reql_string_init(&string, buf, size, size);
CHECK(orig.compare(0, size, (char *)_reql_string_buf(&string), size) == 0);
CHECK(size == _reql_string_size(&string));
}
}
|
Fix compile issue on Qt5 | #include <QtGui/QApplication>
#include "mainwindow.h"
#include "fvupdater.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Prerequisite for the Fervor updater
QApplication::setOrganizationName("pypt");
QApplication::setOrganizationDomain("pypt.lt");
// Set feed URL before doing anything else
FvUpdater::sharedUpdater()->SetFeedURL("http://pypt.github.com/fervor/Appcast.xml");
// Check for updates automatically
FvUpdater::sharedUpdater()->CheckForUpdatesSilent();
// Show main window
MainWindow w;
w.show();
return a.exec();
}
| #include <QApplication>
#include "mainwindow.h"
#include "fvupdater.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Prerequisite for the Fervor updater
QApplication::setOrganizationName("pypt");
QApplication::setOrganizationDomain("pypt.lt");
// Set feed URL before doing anything else
FvUpdater::sharedUpdater()->SetFeedURL("http://pypt.github.com/fervor/Appcast.xml");
// Check for updates automatically
FvUpdater::sharedUpdater()->CheckForUpdatesSilent();
// Show main window
MainWindow w;
w.show();
return a.exec();
}
|
Fix parameter of the Twist | #include <ros/ros.h>
#include <geometry_msgs/Twist.h>
int main(int argc, char *argv[]){
ros::init(argc, argv, "quadrotor_obstacle_avoidance");
ros::NodeHandle node;
ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 5;
cmd_pub.publish(cmd);
ros::Duration(5).sleep();
cmd.linear.z = 0.0;
cmd_pub.publish(cmd);
ros::Duration(5).sleep();
return 0;
}
| #include <ros/ros.h>
#include <geometry_msgs/Twist.h>
int main(int argc, char *argv[]){
ros::init(argc, argv, "quadrotor_obstacle_avoidance");
ros::NodeHandle node;
ros::Publisher cmd_pub = node.advertise<geometry_msgs::Twist>("cmd_vel", 10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 1;
cmd_pub.publish(cmd);
ros::Duration(5).sleep();
cmd.linear.z = 0.0;
cmd_pub.publish(cmd);
ros::Duration(5).sleep();
return 0;
}
|
Fix client for not executing fileworker | #include<iostream>
#include<stdlib.h>
#include"filecopy.h"
int main(int argc, char *argv[])
{
if(argc != 3)
{
std::cout << "USAGE: " << argv[0] << " <filesource> <filedestination>" << std::endl;
return 1;
}
else
{
filecopy target1(argv[2], argv[1]);
std::cout << "TARGET ASSIGNED" << std::endl;
std::cout << "EXECUTE FILEWORKER" << std::endl;
}
return 0;
}
| #include<iostream>
#include<stdlib.h>
#include"filecopy.h"
int main(int argc, char *argv[])
{
if(argc != 3)
{
std::cout << "USAGE: " << argv[0] << " <filesource> <filedestination>" << std::endl;
return 1;
}
else
{
filecopy target1(argv[2], argv[1]);
std::cout << "TARGET ASSIGNED" << std::endl;
target1.filecopy_worker();
std::cout << "EXECUTE FILEWORKER" << std::endl;
}
return 0;
}
|
Hide info on startup, but leave commented code | #include "ofApp.h"
void ofApp::setup() {
ofBackground(0);
// Add our CustomSource to list of fbo sources of the piMapper
// FBO sources should be added before piMapper.setup() so the
// piMapper is able to load the source if it is assigned to
// a surface in XML settings.
piMapper.addFboSource(customSource);
piMapper.setup();
// The info layer is hidden by default, press <i> to toggle
piMapper.showInfo();
}
void ofApp::draw() {
piMapper.draw();
} | #include "ofApp.h"
void ofApp::setup() {
ofBackground(0);
// Add our CustomSource to list of fbo sources of the piMapper
// FBO sources should be added before piMapper.setup() so the
// piMapper is able to load the source if it is assigned to
// a surface in XML settings.
piMapper.addFboSource(customSource);
piMapper.setup();
// The info layer is hidden by default, press <i> to toggle
// piMapper.showInfo();
}
void ofApp::draw() {
piMapper.draw();
} |
Fix the path of header file | #include <iostream>
#include <string>
#include "hash_table.cpp"
#include <time.h>
void randstr(const int length, std::string &out);
int main(void)
{
srand(time(NULL));
hash_set<std::string> hs_str(10, 0.8,
[] (const std::string entry) -> unsigned int
{
unsigned int hash = 0;
for(char c : entry) hash = c + (13 * hash);
return hash;
}
);
const int s_count = 30;
std::string arr[s_count];
for(int i = 0; i < s_count; ++i)
{
randstr(10, arr[i]);
std::cout << arr[i] << std::endl;
}
for(std::string s : arr)
{
hs_str.add(s);
hs_str.print();
std::cout << std::endl
<< "count: " << hs_str.size() << std::endl
<< "capacity: " << hs_str.get_capacity() << std::endl;
}
}
void randstr(const int length, std::string &out)
{
char range[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
for (int n = 0; n < length; ++n)
out.push_back(range[rand() % sizeof(range - 1)]);
out.push_back('\0');
}
| #include <iostream>
#include <string>
#include "hash_table.hpp"
#include <time.h>
void randstr(const int length, std::string &out);
int main(void)
{
srand(time(NULL));
hash_set<std::string> hs_str(10, 0.8,
[] (const std::string entry) -> unsigned int
{
unsigned int hash = 0;
for(char c : entry) hash = c + (13 * hash);
return hash;
}
);
const int s_count = 30;
std::string arr[s_count];
for(int i = 0; i < s_count; ++i)
{
randstr(10, arr[i]);
std::cout << arr[i] << std::endl;
}
for(std::string s : arr)
{
hs_str.add(s);
hs_str.print();
std::cout << std::endl
<< "count: " << hs_str.size() << std::endl
<< "capacity: " << hs_str.get_capacity() << std::endl;
}
}
void randstr(const int length, std::string &out)
{
char range[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
for (int n = 0; n < length; ++n)
out.push_back(range[rand() % sizeof(range - 1)]);
out.push_back('\0');
}
|
Update for move of BuildUserAgentFromProduct in Chrome 35 | // 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/strings/stringprintf.h"
#include "base/strings/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();
base::RemoveChars(name, base::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);
}
} // 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 "common/content_client.h"
#include "common/application_info.h"
#include "base/strings/stringprintf.h"
#include "base/strings/string_util.h"
#include "content/public/common/user_agent.h"
#include "ui/base/resource/resource_bundle.h"
namespace brightray {
ContentClient::ContentClient() {
}
ContentClient::~ContentClient() {
}
std::string ContentClient::GetProduct() const {
auto name = GetApplicationName();
base::RemoveChars(name, base::kWhitespaceASCII, &name);
return base::StringPrintf("%s/%s",
name.c_str(), GetApplicationVersion().c_str());
}
std::string ContentClient::GetUserAgent() const {
return content::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);
}
} // namespace brightray
|
Add in a missing stdint.h include | #include <QInputDialog>
#include "QGCTCPLinkConfiguration.h"
#include "ui_QGCTCPLinkConfiguration.h"
QGCTCPLinkConfiguration::QGCTCPLinkConfiguration(TCPLink* link, QWidget *parent) :
QWidget(parent),
link(link),
ui(new Ui::QGCTCPLinkConfiguration)
{
ui->setupUi(this);
uint16_t port = link->getPort();
ui->portSpinBox->setValue(port);
QString addr = link->getHostAddress().toString();
ui->hostAddressLineEdit->setText(addr);
connect(ui->portSpinBox, SIGNAL(valueChanged(int)), link, SLOT(setPort(int)));
connect(ui->hostAddressLineEdit, SIGNAL(textChanged (const QString &)), link, SLOT(setAddress(const QString &)));
}
QGCTCPLinkConfiguration::~QGCTCPLinkConfiguration()
{
delete ui;
}
void QGCTCPLinkConfiguration::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
} | #include <QInputDialog>
#include "QGCTCPLinkConfiguration.h"
#include "ui_QGCTCPLinkConfiguration.h"
#include <stdint.h>
QGCTCPLinkConfiguration::QGCTCPLinkConfiguration(TCPLink* link, QWidget *parent) :
QWidget(parent),
link(link),
ui(new Ui::QGCTCPLinkConfiguration)
{
ui->setupUi(this);
uint16_t port = link->getPort();
ui->portSpinBox->setValue(port);
QString addr = link->getHostAddress().toString();
ui->hostAddressLineEdit->setText(addr);
connect(ui->portSpinBox, SIGNAL(valueChanged(int)), link, SLOT(setPort(int)));
connect(ui->hostAddressLineEdit, SIGNAL(textChanged (const QString &)), link, SLOT(setAddress(const QString &)));
}
QGCTCPLinkConfiguration::~QGCTCPLinkConfiguration()
{
delete ui;
}
void QGCTCPLinkConfiguration::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
|
Fix conversion warning in range tests | #include <mart-common/experimental/ranges.h>
#include <catch2/catch.hpp>
TEST_CASE( "experimental_frange_compiles", "[experimental][ranges]" )
{
auto r = mart::experimental::frange( 0.1, 0.3 ).step( 0.1 );
(void)r;
}
TEST_CASE( "experimental_vrange_compiles", "[experimental][ranges]" )
{
auto r = mart::experimental::vrange<float>( 0.1, 0.3 ).step( 0.1 );
(void)r;
}
| #include <mart-common/experimental/ranges.h>
#include <catch2/catch.hpp>
TEST_CASE( "experimental_frange_compiles", "[experimental][ranges]" )
{
auto r = mart::experimental::frange( 0.1, 0.3 ).step( 0.1 );
(void)r;
}
TEST_CASE( "experimental_vrange_compiles", "[experimental][ranges]" )
{
auto r = mart::experimental::vrange<float>( 0.1f, 0.3f ).step( 0.1f );
(void)r;
}
|
Add missing include for linux build | #include "fly/logger/log.h"
#include "fly/logger/logger_config.h"
namespace fly {
//==============================================================================
Log::Log() :
m_level(NUM_LEVELS),
m_time(-1.0),
m_gameId(-1),
m_line(-1),
m_message()
{
::memset(m_file, 0, sizeof(m_file));
::memset(m_function, 0, sizeof(m_file));
}
//==============================================================================
Log::Log(const LoggerConfigPtr &spConfig, const std::string &message) :
m_level(NUM_LEVELS),
m_time(-1.0),
m_gameId(-1),
m_line(-1),
m_message(message, 0, spConfig->MaxMessageSize())
{
::memset(m_file, 0, sizeof(m_file));
::memset(m_function, 0, sizeof(m_file));
}
//==============================================================================
std::ostream &operator << (std::ostream &stream, const Log &log)
{
stream << log.m_level << "\t";
stream << log.m_time << "\t";
stream << log.m_gameId << "\t";
stream << log.m_file << "\t";
stream << log.m_function << "\t";
stream << log.m_line << "\t";
stream << log.m_message << "\n";
return stream;
}
}
| #include "fly/logger/log.h"
#include <cstring>
#include "fly/logger/logger_config.h"
namespace fly {
//==============================================================================
Log::Log() :
m_level(NUM_LEVELS),
m_time(-1.0),
m_gameId(-1),
m_line(-1),
m_message()
{
::memset(m_file, 0, sizeof(m_file));
::memset(m_function, 0, sizeof(m_file));
}
//==============================================================================
Log::Log(const LoggerConfigPtr &spConfig, const std::string &message) :
m_level(NUM_LEVELS),
m_time(-1.0),
m_gameId(-1),
m_line(-1),
m_message(message, 0, spConfig->MaxMessageSize())
{
::memset(m_file, 0, sizeof(m_file));
::memset(m_function, 0, sizeof(m_file));
}
//==============================================================================
std::ostream &operator << (std::ostream &stream, const Log &log)
{
stream << log.m_level << "\t";
stream << log.m_time << "\t";
stream << log.m_gameId << "\t";
stream << log.m_file << "\t";
stream << log.m_function << "\t";
stream << log.m_line << "\t";
stream << log.m_message << "\n";
return stream;
}
}
|
Move the to_string method into the proper namespace. | #include <prelude/runtime/tags.h>
using namespace copperhead;
bool system_variant_less::operator()(const system_variant& x,
const system_variant& y) const {
return x.which() < y.which();
}
std::string detail::system_variant_to_string::operator()(const omp_tag&) const {
return "omp_tag";
}
#ifdef CUDA_SUPPORT
std::string detail::system_variant_to_string::operator()(const cuda_tag&) const {
return "cuda_tag";
}
#endif
std::string to_string(const system_variant& x) {
return boost::apply_visitor(detail::system_variant_to_string(), x);
}
bool system_variant_equal(const system_variant& x,
const system_variant& y) {
return x.which() == y.which();
}
| #include <prelude/runtime/tags.h>
using namespace copperhead;
bool system_variant_less::operator()(const system_variant& x,
const system_variant& y) const {
return x.which() < y.which();
}
std::string detail::system_variant_to_string::operator()(const omp_tag&) const {
return "omp_tag";
}
#ifdef CUDA_SUPPORT
std::string detail::system_variant_to_string::operator()(const cuda_tag&) const {
return "cuda_tag";
}
#endif
std::string copperhead::to_string(const system_variant& x) {
return boost::apply_visitor(detail::system_variant_to_string(), x);
}
bool system_variant_equal(const system_variant& x,
const system_variant& y) {
return x.which() == y.which();
}
|
Fix macro in unittest example. | /*
* Copyright (C) 2008 <Your Name>
* See COPYING for license details.
*/
#include <QObject>
#include <QtTest/QtTest>
#include "qttestutil/qttestutil.h"
class MyClassTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase() {
}
void cleanupTestCase() {
}
void testMyMethod() {
//QCOMPARE(foo, bar);
//QVERIFY(baz);
}
};
REGISTER_TEST(MyClassTest);
#include "myclasstest.moc"
| /*
* Copyright (C) 2008 <Your Name>
* See COPYING for license details.
*/
#include <QObject>
#include <QtTest/QtTest>
#include "qttestutil/qttestutil.h"
class MyClassTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase() {
}
void cleanupTestCase() {
}
void testMyMethod() {
//QCOMPARE(foo, bar);
//QVERIFY(baz);
}
};
QTTESTUTIL_REGISTER_TEST(MyClassTest);
#include "myclasstest.moc"
|
Clean up file listener code | #include <thread>
#include <chrono>
#include <iostream>
#include "file_listener.hpp"
namespace fs = std::experimental::filesystem;
namespace amer {
void file_listener::run() {
m_listener_thread = std::thread{[this] { this->do_run(); }};
}
void file_listener::do_run() {
while (true) {
for (auto&& f : fs::recursive_directory_iterator(m_config.get_source_dir()/"content")) {
try {
auto new_write_time = fs::last_write_time(f);
if (!m_mod_times.count(f) || new_write_time != m_mod_times[f]) {
m_mod_times[f] = new_write_time;
m_renderer.render_content(f);
m_server.refresh();
}
} catch(...) {}
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
}
| #include <thread>
#include <chrono>
#include <iostream>
#include "file_listener.hpp"
namespace fs = std::experimental::filesystem;
static constexpr auto sleep_time = std::chrono::milliseconds(100)
namespace amer {
void file_listener::run() {
m_listener_thread = std::thread{[this] { this->do_run(); }};
}
void file_listener::do_run() {
while (true) {
for (auto&& f : fs::recursive_directory_iterator(m_config.get_source_dir()/"content")) {
try {
auto new_write_time = fs::last_write_time(f);
auto file_is_new = !m_mod_times.count(f);
auto file_has_been_updated = new_write_time != m_mod_times[f];
auto should_rerender = file_is_new || file_has_been_updated;
if (should_rerender) {
record_modification_time(f, new_write_time);
m_renderer.render_content(f);
m_server.refresh();
}
} catch(...) {}
}
std::this_thread::sleep_for(sleep_time);
}
}
}
|
Support integer parameters that fit in a single buffer | #include <turbodbc_numpy/set_numpy_parameters.h>
#include <turbodbc/errors.h>
#include <iostream>
namespace turbodbc_numpy {
void set_numpy_parameters(turbodbc::bound_parameter_set & parameters, std::vector<pybind11::array> const & columns)
{
pybind11::dtype const np_int64("int64");
pybind11::dtype const np_int16("int16");
auto const & column = columns.front();
auto const dtype = column.dtype();
if (dtype == np_int64) {
return;
}
throw turbodbc::interface_error("Encountered unsupported NumPy dtype '" +
static_cast<std::string>(pybind11::str(dtype)) + "'");
}
} | #include <turbodbc_numpy/set_numpy_parameters.h>
#include <turbodbc/errors.h>
#include <turbodbc/make_description.h>
#include <turbodbc/type_code.h>
#include <iostream>
#include <algorithm>
#ifdef _WIN32
#include <windows.h>
#endif
#include <sql.h>
namespace turbodbc_numpy {
void set_numpy_parameters(turbodbc::bound_parameter_set & parameters, std::vector<pybind11::array> const & columns)
{
pybind11::dtype const np_int64("int64");
auto const & column = columns.front();
auto const dtype = column.dtype();
if (dtype == np_int64) {
auto unchecked = column.unchecked<std::int64_t, 1>();
auto data_ptr = unchecked.data(0);
parameters.rebind(0, turbodbc::make_description(turbodbc::type_code::integer, 0));
auto & buffer = parameters.get_parameters()[0]->get_buffer();
std::memcpy(buffer.data_pointer(), data_ptr, unchecked.size() * sizeof(std::int64_t));
std::fill_n(buffer.indicator_pointer(), unchecked.size(), static_cast<intptr_t>(sizeof(std::int64_t)));
parameters.execute_batch(unchecked.size());
} else {
throw turbodbc::interface_error("Encountered unsupported NumPy dtype '" +
static_cast<std::string>(pybind11::str(dtype)) + "'");
}
}
} |
Make halide_printf output to LOG_INFO, not LOG_FATAL | #include "mini_stdint.h"
#define WEAK __attribute__((weak))
extern "C" {
extern int __android_log_vprint(int, const char *, const char *, __builtin_va_list);
WEAK int halide_printf(void *user_context, const char * fmt, ...) {
__builtin_va_list args;
__builtin_va_start(args,fmt);
int result = __android_log_vprint(7, "halide", fmt, args);
__builtin_va_end(args);
return result;
}
}
| #include "mini_stdint.h"
#define WEAK __attribute__((weak))
extern "C" {
extern int __android_log_vprint(int, const char *, const char *, __builtin_va_list);
#define ANDROID_LOG_INFO 4
WEAK int halide_printf(void *user_context, const char * fmt, ...) {
__builtin_va_list args;
__builtin_va_start(args,fmt);
int result = __android_log_vprint(ANDROID_LOG_INFO, "halide", fmt, args);
__builtin_va_end(args);
return result;
}
}
|
Test cut in all axis | #include <iostream>
#include "img_vol.h"
#include "operations.h"
#include "img2d.h"
int main(int argc, char **argv) {
ImgVol img("/home/alex/Downloads/libmo815-3dvis/data/brain.scn");
std::cout << img << "\n";
std::cout << img(57, 9, 35) << "\n";
Img2D img2d = Cut(img, ImgVol::Axis::Z, 40);
std::cout << img2d;
}
| #include <iostream>
#include "img_vol.h"
#include "operations.h"
#include "img2d.h"
int main(int argc, char **argv) {
ImgVol img("/home/alex/Downloads/libmo815-3dvis/data/brain.scn");
std::cout << img << "\n";
std::cout << img(57, 9, 35) << "\n";
Img2D img2dz = Cut(img, ImgVol::Axis::Z, 40);
std::cout << img2dz << "\n";
Img2D img2dy = Cut(img, ImgVol::Axis::Y, 40);
std::cout << img2dy << "\n";
Img2D img2dx = Cut(img, ImgVol::Axis::X, 40);
std::cout << img2dx << "\n";
}
|
Use of range-based for loop. | /* Copyright (C) 2008 The goocanvasmm Development Team
*
* 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) 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
* 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, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "window.h"
#include "primitives.h"
DemoWindow::DemoWindow()
{
set_title("goocanvasmm Demo");
set_default_size(640, 600);
_pages.push_back(new Primitives());
auto nb = Gtk::manage(new Gtk::Notebook());
std::vector< Page* >::iterator iter ;
for(iter = _pages.begin(); iter != _pages.end(); iter++)
{
auto p = *iter ;
nb->append_page(*(p->getWidget()), p->getName());
}
add(*nb);
show_all_children();
}
| /* Copyright (C) 2008 The goocanvasmm Development Team
*
* 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) 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
* 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, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "window.h"
#include "primitives.h"
DemoWindow::DemoWindow()
{
set_title("goocanvasmm Demo");
set_default_size(640, 600);
_pages.push_back(new Primitives());
auto nb = Gtk::manage(new Gtk::Notebook());
for(const auto& p : _pages)
{
nb->append_page(*(p->getWidget()), p->getName());
}
add(*nb);
show_all_children();
}
|
Fix the KeyEvent unit test failure due to the aura implementation of GetUnmodifiedCharacter(). | // 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 "views/events/event.h"
#include "base/logging.h"
#include "ui/aura/event.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// LocatedEvent, protected:
LocatedEvent::LocatedEvent(const NativeEvent& native_event)
: Event(native_event, native_event->type(), native_event->flags()),
location_(static_cast<aura::LocatedEvent*>(native_event)->location()) {
}
////////////////////////////////////////////////////////////////////////////////
// KeyEvent, public:
KeyEvent::KeyEvent(const NativeEvent& native_event)
: Event(native_event, native_event->type(), native_event->flags()),
key_code_(static_cast<aura::KeyEvent*>(native_event)->key_code()),
character_(GetCharacterFromKeyCode(key_code_, flags())),
unmodified_character_(0) {
}
uint16 KeyEvent::GetCharacter() const {
return character_;
}
uint16 KeyEvent::GetUnmodifiedCharacter() const {
return unmodified_character_;
}
////////////////////////////////////////////////////////////////////////////////
// MouseWheelEvent, public:
MouseWheelEvent::MouseWheelEvent(const NativeEvent& native_event)
: MouseEvent(native_event),
offset_(ui::GetMouseWheelOffset(native_event->native_event())) {
}
} // namespace views
| // 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 "views/events/event.h"
#include "base/logging.h"
#include "ui/aura/event.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// LocatedEvent, protected:
LocatedEvent::LocatedEvent(const NativeEvent& native_event)
: Event(native_event, native_event->type(), native_event->flags()),
location_(static_cast<aura::LocatedEvent*>(native_event)->location()) {
}
////////////////////////////////////////////////////////////////////////////////
// KeyEvent, public:
KeyEvent::KeyEvent(const NativeEvent& native_event)
: Event(native_event, native_event->type(), native_event->flags()),
key_code_(static_cast<aura::KeyEvent*>(native_event)->key_code()),
character_(GetCharacterFromKeyCode(key_code_, flags())),
unmodified_character_(0) {
}
uint16 KeyEvent::GetCharacter() const {
return character_;
}
uint16 KeyEvent::GetUnmodifiedCharacter() const {
if (unmodified_character_)
return unmodified_character_;
return GetCharacterFromKeyCode(key_code_, flags() & ui::EF_SHIFT_DOWN);
}
////////////////////////////////////////////////////////////////////////////////
// MouseWheelEvent, public:
MouseWheelEvent::MouseWheelEvent(const NativeEvent& native_event)
: MouseEvent(native_event),
offset_(ui::GetMouseWheelOffset(native_event->native_event())) {
}
} // namespace views
|
Initialize common flags to default values in unit tests. | //===-- sanitizer_test_main.cc --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer/AddressSanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
const char *argv0;
int main(int argc, char **argv) {
argv0 = argv[0];
testing::GTEST_FLAG(death_test_style) = "threadsafe";
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| //===-- sanitizer_test_main.cc --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer/AddressSanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "sanitizer_common/sanitizer_flags.h"
const char *argv0;
int main(int argc, char **argv) {
argv0 = argv[0];
testing::GTEST_FLAG(death_test_style) = "threadsafe";
testing::InitGoogleTest(&argc, argv);
SetCommonFlagsDefaults();
return RUN_ALL_TESTS();
}
|
Use ``size_t`` for array types | #include <string>
#include "configuration.hh"
namespace vick {
int from_visual(const std::string& cont, int x) {
if(cont.size() == 0) return 0;
int count = 0,
til = 0;
int numTab = 0;
for(unsigned int i = 0; i < cont.length(); i++) {
unsigned int len;
if(cont[i] == '\t') {
len = TAB_SIZE - 1 - til;
til = 0;
numTab++;
} else {
len = 1;
til++;
til %= TAB_SIZE;
}
count += len;
if(count > x - numTab) return i;
}
return -1;
}
int to_visual(const std::string& cont, int x) {
int til = 0,
xx = -1;
for(std::string::const_iterator i = cont.begin();
i <= cont.begin() + x; ++i) {
if(*i == '\t') {
xx += TAB_SIZE - til;
til = 0;
} else {
til++;
til %= TAB_SIZE;
xx++;
}
}
return xx;
}
}
| #include <string>
#include "configuration.hh"
namespace vick {
int from_visual(const std::string& cont, int x) {
if(cont.size() == 0) return 0;
int count = 0,
til = 0;
int numTab = 0;
for(size_t i = 0; i < cont.length(); i++) {
size_t len;
if(cont[i] == '\t') {
len = TAB_SIZE - 1 - til;
til = 0;
numTab++;
} else {
len = 1;
til++;
til %= TAB_SIZE;
}
count += len;
if(count > x - numTab) return i;
}
return -1;
}
int to_visual(const std::string& cont, int x) {
int til = 0,
xx = -1;
for(std::string::const_iterator i = cont.begin();
i <= cont.begin() + x; ++i) {
if(*i == '\t') {
xx += TAB_SIZE - til;
til = 0;
} else {
til++;
til %= TAB_SIZE;
xx++;
}
}
return xx;
}
}
|
Fix non-portable include path in senion broadcast receiver include. Buddy: Blair | // Copyright eeGeo Ltd (2012-2017), All Rights Reserved
#include <jni.h>
#include "AndroidAppThreadAssertionMacros.h"
#include "SenionLabBroadCastReceiver.h"
#include "SenionLabBroadCastReceiverJni.h"
extern "C"
{
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_senionlab_SenionLabBroadcastReceiverJniMethods_DidUpdateLocation(
JNIEnv *jenv, jclass jobj,
jlong nativeObjectPtr,
jdouble latitude,
jdouble longitude,
jint floorNumber)
{
using ExampleApp::InteriorsPosition::View::SenionLab::SenionLabBroadcastReceiver;
reinterpret_cast<SenionLabBroadcastReceiver *>(nativeObjectPtr)->DidUpdateLocation(latitude,
longitude,
floorNumber);
}
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_senionlab_SenionLabBroadcastReceiverJniMethods_SetIsAuthorized(
JNIEnv *jenv, jclass obj,
jlong nativeObjectPtr,
jboolean isAuthorized)
{
using ExampleApp::InteriorsPosition::View::SenionLab::SenionLabBroadcastReceiver;
reinterpret_cast<SenionLabBroadcastReceiver *>(nativeObjectPtr)->SetIsAuthorized(isAuthorized);
}
}
| // Copyright eeGeo Ltd (2012-2017), All Rights Reserved
#include <jni.h>
#include "AndroidAppThreadAssertionMacros.h"
#include "SenionLabBroadcastReceiver.h"
#include "SenionLabBroadcastReceiverJni.h"
extern "C"
{
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_senionlab_SenionLabBroadcastReceiverJniMethods_DidUpdateLocation(
JNIEnv *jenv, jclass jobj,
jlong nativeObjectPtr,
jdouble latitude,
jdouble longitude,
jint floorNumber)
{
using ExampleApp::InteriorsPosition::View::SenionLab::SenionLabBroadcastReceiver;
reinterpret_cast<SenionLabBroadcastReceiver *>(nativeObjectPtr)->DidUpdateLocation(latitude,
longitude,
floorNumber);
}
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_senionlab_SenionLabBroadcastReceiverJniMethods_SetIsAuthorized(
JNIEnv *jenv, jclass obj,
jlong nativeObjectPtr,
jboolean isAuthorized)
{
using ExampleApp::InteriorsPosition::View::SenionLab::SenionLabBroadcastReceiver;
reinterpret_cast<SenionLabBroadcastReceiver *>(nativeObjectPtr)->SetIsAuthorized(isAuthorized);
}
}
|
Update example file extensions (.h to .cpp). | #include "user.h"
// This is a hack.
// Otherwise, we will need to create a target for each user application.
#include "examples/user_audio_beat.cpp"
//#include "examples/user_color_sensor.h"
//#include "examples/user_accelerometer_gestures.h"
//#include "examples/user_accelerometer_poses.h"
//#include "examples/user_capacitive_sensing.h"
//#include "examples/user_sudden_motion.h"
| #include "user.h"
// This is a hack.
// Otherwise, we will need to create a target for each user application.
#include "examples/user_audio_beat.cpp"
//#include "examples/user_color_sensor.cpp"
//#include "examples/user_accelerometer_gestures.cpp"
//#include "examples/user_accelerometer_poses.cpp"
//#include "examples/user_capacitive_sensing.cpp"
//#include "examples/user_sudden_motion.cpp"
|
Fix hnc version and codename test | // Copyright © 2012 Lénaïc Bagnères, hnc@singularity.fr
// 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 <iostream>
#include <hnc/hnc.hpp>
int main()
{
std::cout << "Just test hnc.hpp include" << std::endl;
std::cout << "hnc version = " << hnc::version << std::endl;
std::cout << "hnc codename = " << hnc::codename << std::endl;
return 0;
}
| // Copyright © 2012 Lénaïc Bagnères, hnc@singularity.fr
// 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 <iostream>
#include <hnc/hnc.hpp>
int main()
{
std::cout << "Just test hnc.hpp include" << std::endl;
std::cout << "hnc version = " << hnc::version() << std::endl;
std::cout << "hnc codename = " << hnc::codename() << std::endl;
return 0;
}
|
Update for changes to content::ContentMain | #include "common/library_main.h"
#include "common/main_delegate.h"
#include "content/public/app/content_main.h"
int BrightrayExampleMain(int argc, const char* argv[]) {
brightray_example::MainDelegate delegate;
return content::ContentMain(argc, argv, &delegate);
}
| #include "common/library_main.h"
#include "common/main_delegate.h"
#include "content/public/app/content_main.h"
int BrightrayExampleMain(int argc, const char* argv[]) {
brightray_example::MainDelegate delegate;
content::ContentMainParams params(&delegate);
params.argc = argc;
params.argv = argv;
return content::ContentMain(params);
}
|
Prepare 0.8.0 Beta 2 release | //
// Copyright (C) 2016 University of Amsterdam
//
// 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, see <http://www.gnu.org/licenses/>.
//
#include "appinfo.h"
const Version AppInfo::version = Version(0, 8, 0, 101);
const std::string AppInfo::name = "JASP";
const std::string AppInfo::builddate = "Thu Apr 21 2016 13:04:43 GMT+0100 (CET)";
std::string AppInfo::getShortDesc()
{
return AppInfo::name + " " + AppInfo::version.asString();
}
| //
// Copyright (C) 2016 University of Amsterdam
//
// 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, see <http://www.gnu.org/licenses/>.
//
#include "appinfo.h"
const Version AppInfo::version = Version(0, 8, 0, 102);
const std::string AppInfo::name = "JASP";
const std::string AppInfo::builddate = "Thu Jul 14 2016 13:30:41 GMT+0100 (CET)";
std::string AppInfo::getShortDesc()
{
return AppInfo::name + " " + AppInfo::version.asString();
}
|
Make every JS function call is wrapped with V8RecursionScope | // Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/event_emitter_caller.h"
#include "atom/common/node_includes.h"
namespace mate {
namespace internal {
v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
ValueVector* args) {
return node::MakeCallback(
isolate, obj, "emit", args->size(), &args->front());
}
} // namespace internal
} // namespace mate
| // Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/event_emitter_caller.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
#include "atom/common/node_includes.h"
namespace mate {
namespace internal {
namespace {
// Returns whether current process is browser process, currently we detect it
// by checking whether current has used V8 Lock, but it might be a bad idea.
inline bool IsBrowserProcess() {
return v8::Locker::IsActive();
}
} // namespace
v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
ValueVector* args) {
// Perform microtask checkpoint after running JavaScript.
scoped_ptr<blink::WebScopedRunV8Script> script_scope(
IsBrowserProcess() ? nullptr : new blink::WebScopedRunV8Script(isolate));
// Use node::MakeCallback to call the callback, and it will also run pending
// tasks in Node.js.
return node::MakeCallback(
isolate, obj, "emit", args->size(), &args->front());
}
} // namespace internal
} // namespace mate
|
Make sure rank/nprocs is set for serial runs | #include "message_passing.h"
namespace openmc {
namespace mpi {
int rank;
int n_procs;
#ifdef OPENMC_MPI
MPI_Comm intracomm;
MPI_Datatype bank;
#endif
} // namespace mpi
} // namespace openmc
| #include "message_passing.h"
namespace openmc {
namespace mpi {
int rank {0};
int n_procs {1};
#ifdef OPENMC_MPI
MPI_Comm intracomm;
MPI_Datatype bank;
#endif
} // namespace mpi
} // namespace openmc
|
Enable Android executables (like skia_launcher) to redirect SkDebugf output to stdout as well as the system logs. |
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
static const size_t kBufferSize = 256;
#define LOG_TAG "skia"
#include <android/log.h>
void SkDebugf(const char format[], ...) {
va_list args;
va_start(args, format);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
va_end(args);
}
|
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
static const size_t kBufferSize = 256;
#define LOG_TAG "skia"
#include <android/log.h>
static bool gSkDebugToStdOut = false;
extern "C" void AndroidSkDebugToStdOut(bool debugToStdOut) {
gSkDebugToStdOut = debugToStdOut;
}
void SkDebugf(const char format[], ...) {
va_list args;
va_start(args, format);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
// Print debug output to stdout as well. This is useful for command
// line applications (e.g. skia_launcher)
if (gSkDebugToStdOut) {
vprintf(format, args);
}
va_end(args);
}
|
Print error message header in red. | //===- Error.cpp ----------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Error.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/raw_ostream.h"
namespace lld {
namespace coff {
void fatal(const Twine &Msg) {
llvm::errs() << Msg << "\n";
exit(1);
}
void fatal(std::error_code EC, const Twine &Msg) {
fatal(Msg + ": " + EC.message());
}
void fatal(llvm::Error &Err, const Twine &Msg) {
fatal(errorToErrorCode(std::move(Err)), Msg);
}
} // namespace coff
} // namespace lld
| //===- Error.cpp ----------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Error.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace lld {
namespace coff {
void fatal(const Twine &Msg) {
if (sys::Process::StandardErrHasColors()) {
errs().changeColor(raw_ostream::RED, /*bold=*/true);
errs() << "error: ";
errs().resetColor();
} else {
errs() << "error: ";
}
errs() << Msg << "\n";
exit(1);
}
void fatal(std::error_code EC, const Twine &Msg) {
fatal(Msg + ": " + EC.message());
}
void fatal(llvm::Error &Err, const Twine &Msg) {
fatal(errorToErrorCode(std::move(Err)), Msg);
}
} // namespace coff
} // namespace lld
|
Call base class activation routine. | #include <config/config_class.h>
#include <config/config_object.h>
#include <config/config_value.h>
#include "wanproxy_config_class_interface.h"
WANProxyConfigClassInterface wanproxy_config_class_interface;
bool
WANProxyConfigClassInterface::activate(ConfigObject *)
{
/* Eventually would like to do something more useful here. */
return (true);
}
| #include <config/config_class.h>
#include <config/config_object.h>
#include <config/config_value.h>
#include "wanproxy_config_class_interface.h"
WANProxyConfigClassInterface wanproxy_config_class_interface;
bool
WANProxyConfigClassInterface::activate(ConfigObject *co)
{
if (!ConfigClassAddress::activate(co))
return (false);
/* Eventually would like to do something more useful here. */
return (true);
}
|
Use more complicated dummy code to silence ranlib on MacOS. | /*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.
=============================================================================*/
namespace {
// This is dummy code to silence some linkers warning about
// empty object files.
struct CMakeResourceDependencies {};
}
| /*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 <iostream>
namespace {
// This is dummy code to silence some linkers warning about
// empty object files.
struct CMakeResourceDependencies { CMakeResourceDependencies() { std::cout << std::flush; } };
}
|
FIX example nlohman_json include changed with V2.1.1 | #include <iostream>
#include <nlohmann/json.hpp>
int main (int argc, char** argv) {
// for convenience
using json = nlohmann::json;
json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}},
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};
std::cout << j2 << std::endl;
return 0;
}
| #include <iostream>
#include <json.hpp>
int main (int argc, char** argv) {
// for convenience
using json = nlohmann::json;
json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}},
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};
std::cout << j2 << std::endl;
return 0;
}
|
Support accrus pour la compilation avec MinGW | #include <iostream>
#include <stdexcept>
#include "Badger.hpp"
int main()
{
try
{
badger::Badger b;
b.run();
return EXIT_SUCCESS;
}
catch(const std::exception &e)
{
std::cout << e.what() << std::endl;
}
}
| #include <iostream>
#include <stdexcept>
#include "Badger.hpp"
// Include cstdlib for EXIT_SUCCESS with MinGW
#include <cstdlib>
int main()
{
try
{
badger::Badger b;
b.run();
return EXIT_SUCCESS;
}
catch(const std::exception &e)
{
std::cout << e.what() << std::endl;
}
}
|
Make Google style include order | #include "paddle/platform/place.h"
#include "gtest/gtest.h"
#include <sstream>
TEST(Place, Equality) {
paddle::platform::CpuPlace cpu;
paddle::platform::GpuPlace g0(0), g1(1), gg0(0);
EXPECT_EQ(cpu, cpu);
EXPECT_EQ(g0, g0);
EXPECT_EQ(g1, g1);
EXPECT_EQ(g0, gg0);
EXPECT_NE(g0, g1);
EXPECT_TRUE(paddle::platform::places_are_same_class(g0, gg0));
EXPECT_FALSE(paddle::platform::places_are_same_class(g0, cpu));
}
TEST(Place, Default) {
EXPECT_TRUE(paddle::platform::is_gpu_place(paddle::platform::get_place()));
EXPECT_TRUE(paddle::platform::is_gpu_place(paddle::platform::default_gpu()));
EXPECT_TRUE(paddle::platform::is_cpu_place(paddle::platform::default_cpu()));
paddle::platform::set_place(paddle::platform::CpuPlace());
EXPECT_TRUE(paddle::platform::is_cpu_place(paddle::platform::get_place()));
}
TEST(Place, Print) {
{
std::stringstream ss;
ss << paddle::platform::GpuPlace(1);
EXPECT_EQ("GpuPlace(1)", ss.str());
}
{
std::stringstream ss;
ss << paddle::platform::CpuPlace();
EXPECT_EQ("CpuPlace", ss.str());
}
}
| #include "paddle/platform/place.h"
#include <sstream>
#include "gtest/gtest.h"
TEST(Place, Equality) {
paddle::platform::CpuPlace cpu;
paddle::platform::GpuPlace g0(0), g1(1), gg0(0);
EXPECT_EQ(cpu, cpu);
EXPECT_EQ(g0, g0);
EXPECT_EQ(g1, g1);
EXPECT_EQ(g0, gg0);
EXPECT_NE(g0, g1);
EXPECT_TRUE(paddle::platform::places_are_same_class(g0, gg0));
EXPECT_FALSE(paddle::platform::places_are_same_class(g0, cpu));
}
TEST(Place, Default) {
EXPECT_TRUE(paddle::platform::is_gpu_place(paddle::platform::get_place()));
EXPECT_TRUE(paddle::platform::is_gpu_place(paddle::platform::default_gpu()));
EXPECT_TRUE(paddle::platform::is_cpu_place(paddle::platform::default_cpu()));
paddle::platform::set_place(paddle::platform::CpuPlace());
EXPECT_TRUE(paddle::platform::is_cpu_place(paddle::platform::get_place()));
}
TEST(Place, Print) {
{
std::stringstream ss;
ss << paddle::platform::GpuPlace(1);
EXPECT_EQ("GpuPlace(1)", ss.str());
}
{
std::stringstream ss;
ss << paddle::platform::CpuPlace();
EXPECT_EQ("CpuPlace", ss.str());
}
}
|
Fix time source for emscripten | // Copyright (c) 2013-2021 mogemimi. Distributed under the MIT license.
#include "TimeSourceEmscripten.hpp"
#include <emscripten.h>
namespace Pomdog::Detail::Emscripten {
TimePoint TimeSourceEmscripten::Now() const
{
const auto now = ::emscripten_get_now();
return TimePoint{Duration{static_cast<double>(now)}};
}
} // namespace Pomdog::Detail::Emscripten
| // Copyright (c) 2013-2021 mogemimi. Distributed under the MIT license.
#include "TimeSourceEmscripten.hpp"
#include <emscripten.h>
#include <type_traits>
namespace Pomdog::Detail::Emscripten {
TimePoint TimeSourceEmscripten::Now() const
{
const auto now = ::emscripten_get_now();
static_assert(std::is_same_v<std::remove_const_t<decltype(now)>, double>);
return TimePoint{Duration{now * 0.001}};
}
} // namespace Pomdog::Detail::Emscripten
|
Print hostname where hellompi runs | #include <mpi.h>
#include <iostream>
using namespace std;
int main()
{
MPI::Init();
int rank = MPI::COMM_WORLD.Get_rank();
int size = MPI::COMM_WORLD.Get_size();
cout << "Hello from rank " << rank << " of " << size << "!" << endl;
MPI::Finalize();
}
| #include <cstdlib>
#include <iostream>
#include <mpi.h>
#include <string>
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 256
#endif
using namespace std;
int main()
{
MPI::Init();
int rank = MPI::COMM_WORLD.Get_rank();
int size = MPI::COMM_WORLD.Get_size();
char host[HOST_NAME_MAX];
int status = gethostname(host, HOST_NAME_MAX);
string hostname;
if (status == -1)
hostname = "<unknown>";
else
hostname = host;
cout << "Hello from rank " << rank << " of " << size << "! (I'm on host " << hostname << ".)" << endl;
MPI::Finalize();
}
|
Comment white noise test for now | /**
* \ file WhiteNoiseGeneratorFilter.cpp
*/
#include <cmath>
#include <ATK/Tools/WhiteNoiseGeneratorFilter.h>
#include <array>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
const size_t PROCESSSIZE = 1024*1024;
BOOST_AUTO_TEST_CASE( WhiteNoiseGeneratorFilter_volume_test )
{
ATK::WhiteNoiseGeneratorFilter<double> noisefilter;
noisefilter.set_volume(10);
BOOST_CHECK_EQUAL(noisefilter.get_volume(), 10);
}
BOOST_AUTO_TEST_CASE( WhiteNoiseGeneratorFilter_offset_test )
{
ATK::WhiteNoiseGeneratorFilter<double> noisefilter;
noisefilter.set_offset(10);
BOOST_CHECK_EQUAL(noisefilter.get_offset(), 10);
}
BOOST_AUTO_TEST_CASE( WhiteNoiseGeneratorFilter_mean_test )
{
ATK::WhiteNoiseGeneratorFilter<double> noisefilter;
noisefilter.set_output_sampling_rate(PROCESSSIZE);
noisefilter.process(PROCESSSIZE);
auto noise = noisefilter.get_output_array(0);
BOOST_CHECK_CLOSE(std::accumulate(noise, noise + PROCESSSIZE, 0.) / PROCESSSIZE, 0, 0.0001);
}
| /**
* \ file WhiteNoiseGeneratorFilter.cpp
*/
#include <cmath>
#include <ATK/Tools/WhiteNoiseGeneratorFilter.h>
#include <array>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
const size_t PROCESSSIZE = 1024*1024;
BOOST_AUTO_TEST_CASE( WhiteNoiseGeneratorFilter_volume_test )
{
ATK::WhiteNoiseGeneratorFilter<double> noisefilter;
noisefilter.set_volume(10);
BOOST_CHECK_EQUAL(noisefilter.get_volume(), 10);
}
BOOST_AUTO_TEST_CASE( WhiteNoiseGeneratorFilter_offset_test )
{
ATK::WhiteNoiseGeneratorFilter<double> noisefilter;
noisefilter.set_offset(10);
BOOST_CHECK_EQUAL(noisefilter.get_offset(), 10);
}
BOOST_AUTO_TEST_CASE( WhiteNoiseGeneratorFilter_mean_test )
{
ATK::WhiteNoiseGeneratorFilter<double> noisefilter;
noisefilter.set_output_sampling_rate(PROCESSSIZE);
noisefilter.process(PROCESSSIZE);
auto noise = noisefilter.get_output_array(0);
//BOOST_CHECK_CLOSE(std::accumulate(noise, noise + PROCESSSIZE, 0.) / PROCESSSIZE, 0, 0.0001);
}
|
Add upper bound on partitioning block size | #include "RoundRobinPartitioner.hpp"
#include <vector>
#include <iostream>
#include "LogicalProcess.hpp"
namespace warped {
std::vector<std::vector<LogicalProcess*>> RoundRobinPartitioner::partition(
const std::vector<LogicalProcess*>& lps,
const unsigned int num_partitions) const {
std::vector<std::vector<LogicalProcess*>> partitions(num_partitions);
if (block_size_ == 0) {
block_size_ = lps.size()/num_partitions;
}
unsigned int num_blocks = lps.size()/block_size_;
unsigned int i = 0, j = 0;
for (i = 0; i < num_blocks; i++) {
for (j = 0; j < block_size_; j++) {
partitions[i % num_partitions].push_back(lps[block_size_*i+j]);
}
}
i--;
while ((block_size_*i+j) < lps.size()) {
partitions[j % num_partitions].push_back(lps[block_size_*i+j]);
j++;
}
return partitions;
}
} // namespace warped
| #include "RoundRobinPartitioner.hpp"
#include <vector>
#include <iostream>
#include "LogicalProcess.hpp"
namespace warped {
std::vector<std::vector<LogicalProcess*>> RoundRobinPartitioner::partition(
const std::vector<LogicalProcess*>& lps,
const unsigned int num_partitions) const {
std::vector<std::vector<LogicalProcess*>> partitions(num_partitions);
if ((block_size_ == 0) || block_size_ > lps.size()/num_partitions) {
block_size_ = lps.size()/num_partitions;
}
unsigned int num_blocks = lps.size()/block_size_;
unsigned int i = 0, j = 0;
for (i = 0; i < num_blocks; i++) {
for (j = 0; j < block_size_; j++) {
partitions[i % num_partitions].push_back(lps[block_size_*i+j]);
}
}
i--;
while ((block_size_*i+j) < lps.size()) {
partitions[j % num_partitions].push_back(lps[block_size_*i+j]);
j++;
}
return partitions;
}
} // namespace warped
|
Rename Error call to GLError | // This file is part of the GLERI project
//
// Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
#include "rglrp.h"
#define N(n,s) "\0" #n "\0" #s "\0"
/*static*/ const char PRGLR::_cmdNames[] =
N(Error,s)
N(Restate,(qqqqyyyy))
N(Expose,)
N(Event,(uqquqq))
;
#undef N
/*static*/ inline const char* PRGLR::LookupCmdName (ECmd cmd, size_type& sz) noexcept
{
return (CCmdBuf::LookupCmdName((unsigned)cmd,sz,ArrayBlock(_cmdNames)-1));
}
/*static*/ PRGLR::ECmd PRGLR::LookupCmd (const char* name, size_type bleft) noexcept
{
return (ECmd(CCmdBuf::LookupCmd(name,bleft,ArrayBlock(_cmdNames)-1)));
}
bstro PRGLR::CreateCmd (ECmd cmd, size_type sz) noexcept
{
size_type msz;
const char* m = LookupCmdName (cmd, msz);
return (CCmdBuf::CreateCmd (RGLRObject, m, msz, sz));
}
| // This file is part of the GLERI project
//
// Copyright (c) 2012 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
#include "rglrp.h"
#define N(n,s) "\0" #n "\0" #s "\0"
/*static*/ const char PRGLR::_cmdNames[] =
N(GLError,s)
N(Restate,(qqqqyyyy))
N(Expose,)
N(Event,(uqquqq))
;
#undef N
/*static*/ inline const char* PRGLR::LookupCmdName (ECmd cmd, size_type& sz) noexcept
{
return (CCmdBuf::LookupCmdName((unsigned)cmd,sz,ArrayBlock(_cmdNames)-1));
}
/*static*/ PRGLR::ECmd PRGLR::LookupCmd (const char* name, size_type bleft) noexcept
{
return (ECmd(CCmdBuf::LookupCmd(name,bleft,ArrayBlock(_cmdNames)-1)));
}
bstro PRGLR::CreateCmd (ECmd cmd, size_type sz) noexcept
{
size_type msz;
const char* m = LookupCmdName (cmd, msz);
return (CCmdBuf::CreateCmd (RGLRObject, m, msz, sz));
}
|
Exit program on lexical errors | #include "lexical/Lexical.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using namespace ecc;
int main() {
Lexical lexical(
"/home/amir/github/EasyCC-CPP/lexical/state_machine.json",
"/home/amir/github/EasyCC-CPP/lexical/config.json",
"/home/amir/github/EasyCC-CPP/lexical/errors.json");
std::vector<std::shared_ptr<LexicalToken>> lexicalTokens;
std::vector<std::string> errorMessages;
lexical.generateLexicalTokens("/home/amir/github/EasyCC-CPP/input.txt", lexicalTokens, errorMessages);
for(auto token : lexicalTokens)
cout << *token << endl;
for(auto token : errorMessages)
cout << token << endl;
return 0;
}
| #include "lexical/Lexical.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using namespace ecc;
int main() {
Lexical lexical(
"/home/amir/github/EasyCC-CPP/lexical/state_machine.json",
"/home/amir/github/EasyCC-CPP/lexical/config.json",
"/home/amir/github/EasyCC-CPP/lexical/errors.json");
std::vector<std::shared_ptr<LexicalToken>> lexicalTokens;
std::vector<std::string> errorMessages;
lexical.generateLexicalTokens("/home/amir/github/EasyCC-CPP/input.txt", lexicalTokens, errorMessages);
for(auto token : lexicalTokens)
cout << *token << endl;
for(auto token : errorMessages)
cerr << token << endl;
if(errorMessages.size() != 0) {
// A lexical error exist, exit
cerr << "Exiting program with code 1" << endl;
return 1;
}
return 0;
}
|
Add tests for generating random integer numbers | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "EasyRandom.hpp"
using namespace EasyRandom;
TEST_CASE( "TEST_TEST", "RANDOM" ) {
const auto randomNumber = Random::get( );
REQUIRE( randomNumber >= -10 );
REQUIRE( randomNumber <= 10 );
} | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "EasyRandom.hpp"
#include <limits>
using namespace EasyRandom;
TEST_CASE( "Test random random" ) {
const auto firstRandomNumber = Random::get( std::numeric_limits<std::intmax_t>::min( ),
std::numeric_limits<std::intmax_t>::max( ) );
const auto secondRandomNumber = Random::get( std::numeric_limits<std::intmax_t>::min( ),
std::numeric_limits<std::intmax_t>::max( ) );
CHECK( firstRandomNumber != secondRandomNumber );
}
TEST_CASE( "Test range" ) {
for( std::uint8_t i{ 0u }; i < std::numeric_limits<std::uint8_t>::max( ); ++i ) {
const auto randomNumber = Random::get( -1, 1 );
REQUIRE( randomNumber >= -1 );
REQUIRE( randomNumber <= 1 );
}
for( std::uint8_t i{ 0u }; i < std::numeric_limits<std::uint8_t>::max( ); ++i ) {
const auto randomNumber = Random::get( 1, -1 );
REQUIRE( randomNumber >= -1 );
REQUIRE( randomNumber <= 1 );
}
const auto randomNumber = Random::get( 1, 1 );
REQUIRE( 1 == randomNumber );
}
TEST_CASE( "Test type deduction" ) {
static_assert( std::is_same<int, decltype( Random::get( -10, 10 ) )>::value, "" );
static_assert( std::is_same<unsigned, decltype( Random::get( 10u, 10u ) )>::value, "" );
static_assert( std::is_same<long, decltype( Random::get( 10, 10l ) )>::value, "" );
static_assert( std::is_same<long long, decltype( Random::get( 10ll , 10l ) ) >::value, "" );
static_assert( std::is_same<unsigned long long, decltype( Random::get( 10llu, 10lu ) ) >::value, "" );
static_assert( std::is_same<short, decltype( Random::get<short, short>( 10llu, 10lu ) ) >::value, "" );
static_assert( std::is_same<unsigned short,
decltype( Random::get<unsigned short, unsigned short>( 10llu, 10lu ) ) >::value, "" );
} |
Create the GraphicsManager after the GameStateManager | /* The Halfling Project - A Graphics Engine and Projects
*
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "halfling/halfling_engine.h"
#include "crate_demo/graphics_manager.h"
#include "crate_demo/game_state_manager.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
CrateDemo::GraphicsManager graphicsManager;
CrateDemo::GameStateManager gameStateManager;
Halfling::HalflingEngine engine(hInstance, &graphicsManager, &gameStateManager);
engine.Initialize(L"Crate Demo", 800, 600, false);
engine.Run();
engine.Shutdown();
return 0;
}
| /* The Halfling Project - A Graphics Engine and Projects
*
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "halfling/halfling_engine.h"
#include "crate_demo/graphics_manager.h"
#include "crate_demo/game_state_manager.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
CrateDemo::GameStateManager gameStateManager;
CrateDemo::GraphicsManager graphicsManager(&gameStateManager);
Halfling::HalflingEngine engine(hInstance, &graphicsManager, &gameStateManager);
engine.Initialize(L"Crate Demo", 800, 600, false);
engine.Run();
engine.Shutdown();
return 0;
}
|
Remove namespace from around WinMain | /* The Halfling Project - A Graphics Engine and Projects
*
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "halfling/halfling_engine.h"
#include "crate_demo/graphics_manager.h"
#include "crate_demo/game_state_manager.h"
namespace CrateDemo {
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
GraphicsManager graphicsManager;
GameStateManager gameStateManager;
Halfling::HalflingEngine engine(&graphicsManager, &gameStateManager);
engine.Initialize(L"Crate Demo", 800, 600, false);
engine.Run();
engine.Shutdown();
}
} // End of namespace CrateDemo
| /* The Halfling Project - A Graphics Engine and Projects
*
* The Halfling Project is the legal property of Adrian Astley
* Copyright Adrian Astley 2013
*/
#include "halfling/halfling_engine.h"
#include "crate_demo/graphics_manager.h"
#include "crate_demo/game_state_manager.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
CrateDemo::GraphicsManager graphicsManager;
CrateDemo::GameStateManager gameStateManager;
Halfling::HalflingEngine engine(&graphicsManager, &gameStateManager);
engine.Initialize(L"Crate Demo", 800, 600, false);
engine.Run();
engine.Shutdown();
return 0;
}
|
Delete a dead store found by PVS-Studio. | //===-- HexagonMCAsmInfo.cpp - Hexagon asm properties ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the HexagonMCAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "HexagonMCAsmInfo.h"
using namespace llvm;
// Pin the vtable to this file.
void HexagonMCAsmInfo::anchor() {}
HexagonMCAsmInfo::HexagonMCAsmInfo(const Triple &TT) {
Data16bitsDirective = "\t.half\t";
Data32bitsDirective = "\t.word\t";
Data64bitsDirective = nullptr; // .xword is only supported by V9.
ZeroDirective = "\t.skip\t";
CommentString = "//";
LCOMMDirectiveAlignmentType = LCOMM::ByteAlignment;
InlineAsmStart = "# InlineAsm Start";
InlineAsmEnd = "# InlineAsm End";
ZeroDirective = "\t.space\t";
AscizDirective = "\t.string\t";
SupportsDebugInformation = true;
MinInstAlignment = 4;
UsesELFSectionDirectiveForBSS = true;
ExceptionsType = ExceptionHandling::DwarfCFI;
}
| //===-- HexagonMCAsmInfo.cpp - Hexagon asm properties ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the HexagonMCAsmInfo properties.
//
//===----------------------------------------------------------------------===//
#include "HexagonMCAsmInfo.h"
using namespace llvm;
// Pin the vtable to this file.
void HexagonMCAsmInfo::anchor() {}
HexagonMCAsmInfo::HexagonMCAsmInfo(const Triple &TT) {
Data16bitsDirective = "\t.half\t";
Data32bitsDirective = "\t.word\t";
Data64bitsDirective = nullptr; // .xword is only supported by V9.
CommentString = "//";
LCOMMDirectiveAlignmentType = LCOMM::ByteAlignment;
InlineAsmStart = "# InlineAsm Start";
InlineAsmEnd = "# InlineAsm End";
ZeroDirective = "\t.space\t";
AscizDirective = "\t.string\t";
SupportsDebugInformation = true;
MinInstAlignment = 4;
UsesELFSectionDirectiveForBSS = true;
ExceptionsType = ExceptionHandling::DwarfCFI;
}
|
Update the solution for the classic binary search problem | // Author: Shengjia Yan
// Date: 2017年7月1日
// Email: sjyan@seu.edu.cn
// Time Complexity: O(logn)
// Space Complexity: O(1)
class Solution {
public:
/**
* @param A an integer array sorted in ascending order
* @param target an integer
* @return an integer
*/
int findPosition(vector<int>& A, int target) {
// Write your code here
int size = A.size();
int mid = size / 2;
int index = mid;
bool flag = false;
if (size == 0) return -1;
if (A[mid] == target) {
flag = true;
return index;
}
else if (A[mid] > target) {
// <-
index--;
while (index >= 0) {
if (A[index] == target) {
flag = true;
return index;
}
index--;
}
}
else {
// ->
index++;
while (index < size) {
if (A[index] == target) {
flag = true;
return index;
}
index++;
}
}
if (!flag) return -1;
}
}; | // Author: Shengjia Yan
// Date: 2017年7月1日
// Email: sjyan@seu.edu.cn
// Time Complexity: O(logn)
// Space Complexity: O(1)
// 经典二分查找问题
class Solution {
public:
/**
* @param A an integer array sorted in ascending order
* @param target an integer
* @return an integer
*/
int findPosition(vector<int>& A, int target) {
// Write your code here
int size = A.size();
int low = 0, high = size-1, mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (target == A[mid]) {
return mid;
}
else if (target > A[mid]){
low = mid + 1;
}
else {
high = mid -1;
}
}
return -1;
}
}; |
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();
}
|
Fix bug: Search result should be empty for specific keyword. However, when the condition is set, search result become not empty. | #include "DocumentIteratorContainer.h"
#include "DocumentIterator.h"
#include "CombinedDocumentIterator.h"
using namespace sf1r;
DocumentIteratorContainer::~DocumentIteratorContainer()
{
for (std::vector<DocumentIterator*>::iterator it = docIters_.begin();
it != docIters_.end(); ++it)
{
delete *it;
}
}
void DocumentIteratorContainer::add(DocumentIterator* docIter)
{
if (docIter == NULL)
return;
docIters_.push_back(docIter);
}
DocumentIterator* DocumentIteratorContainer::combine()
{
if (docIters_.empty())
return NULL;
DocumentIterator* result = NULL;
if (docIters_.size() == 1)
{
result = docIters_[0];
}
else
{
result = new CombinedDocumentIterator;
for (std::vector<DocumentIterator*>::iterator it = docIters_.begin();
it != docIters_.end(); ++it)
{
result->add(*it);
}
}
docIters_.clear();
return result;
}
| #include "DocumentIteratorContainer.h"
#include "DocumentIterator.h"
#include "CombinedDocumentIterator.h"
using namespace sf1r;
DocumentIteratorContainer::~DocumentIteratorContainer()
{
for (std::vector<DocumentIterator*>::iterator it = docIters_.begin();
it != docIters_.end(); ++it)
{
delete *it;
}
}
void DocumentIteratorContainer::add(DocumentIterator* docIter)
{
docIters_.push_back(docIter);
}
DocumentIterator* DocumentIteratorContainer::combine()
{
if (docIters_.empty())
return NULL;
DocumentIterator* result = NULL;
if (docIters_.size() == 1)
{
result = docIters_[0];
}
else
{
result = new CombinedDocumentIterator;
for (std::vector<DocumentIterator*>::iterator it = docIters_.begin();
it != docIters_.end(); ++it)
{
if (NULL == *it)
{
delete result;
docIters_.clear();
return NULL;
}
result->add(*it);
}
}
docIters_.clear();
return result;
}
|
Extend log when connected to the IoT platform | #include "shiftrConnector.h"
#include <Bridge.h>
void ShiftrConnector::init(const char* deviceLogin, const char* pwd)
{
client.begin("broker.shiftr.io");
this->deviceLogin = deviceLogin;
this->pwd = pwd;
connect();
client.subscribe("/bottle-openner");
// client.unsubscribe("/bottle-openner");
}
void ShiftrConnector::connect() {
while (!client.connect("arduino", this->deviceLogin, this->pwd)) {
Serial.print(".");
delay(500);
}
Serial.println("\nconnected to Shiftr!");
}
void ShiftrConnector::loop()
{
client.loop();
if (!client.connected()) {
connect();
}
}
void ShiftrConnector::sendCounter(int counter)
{
char buf[5];
itoa(counter, buf, 10);
client.publish("/bottle-openner", buf);
}
| #include "shiftrConnector.h"
#include <Bridge.h>
void ShiftrConnector::init(const char* deviceLogin, const char* pwd)
{
client.begin("broker.shiftr.io");
this->deviceLogin = deviceLogin;
this->pwd = pwd;
connect();
client.subscribe("/bottle-openner");
// client.unsubscribe("/bottle-openner");
}
void ShiftrConnector::connect() {
while (!client.connect("arduino", this->deviceLogin, this->pwd)) {
Serial.print(".");
delay(500);
}
Serial.println("\nBottle-Opener is now connected to Shiftr!");
}
void ShiftrConnector::loop()
{
client.loop();
if (!client.connected()) {
connect();
}
}
void ShiftrConnector::sendCounter(int counter)
{
char buf[5];
itoa(counter, buf, 10);
client.publish("/bottle-openner", buf);
}
|
Switch to GNU-style strerror_r when needed on Android. | // Copyright 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/posix/safe_strerror.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "base/stl_util.h"
namespace base {
void safe_strerror_r(int err, char* buf, size_t len) {
#if defined(__GLIBC__)
char* ret = strerror_r(err, buf, len);
if (ret != buf) {
snprintf(buf, len, "%s", ret);
}
#else
int result = strerror_r(err, buf, len);
if (result != 0) {
snprintf(buf,
len,
"Error %d while retrieving error %d",
result > 0 ? result : errno,
err);
}
#endif
}
std::string safe_strerror(int err) {
char buf[256];
safe_strerror_r(err, buf, size(buf));
return std::string(buf);
}
} // namespace base
| // Copyright 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/posix/safe_strerror.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "base/stl_util.h"
#include "build/build_config.h"
#if defined(OS_ANDROID)
#include <android/api-level.h>
#endif
namespace base {
void safe_strerror_r(int err, char* buf, size_t len) {
#if defined(__GLIBC__) || \
(defined(OS_ANDROID) && defined(_GNU_SOURCE) && __ANDROID_API__ >= 23)
char* ret = strerror_r(err, buf, len);
if (ret != buf) {
snprintf(buf, len, "%s", ret);
}
#else
int result = strerror_r(err, buf, len);
if (result != 0) {
snprintf(buf,
len,
"Error %d while retrieving error %d",
result > 0 ? result : errno,
err);
}
#endif
}
std::string safe_strerror(int err) {
char buf[256];
safe_strerror_r(err, buf, size(buf));
return std::string(buf);
}
} // namespace base
|
Add test cases and comments | #include <gtest/gtest.h>
#include "OnOffSwitch.h"
TEST(TestOnOffSwitch, main) {
using namespace antoniocoratelli;
OnOffSwitch on_off_switch;
std::cout << on_off_switch.info() << std::endl;
EXPECT_EQ(true, on_off_switch.in<StateOff>());
EXPECT_EQ(false, on_off_switch.in<StateOn>());
on_off_switch.update();
std::cout << on_off_switch.info() << std::endl;
EXPECT_EQ(true, on_off_switch.in<StateOff>());
EXPECT_EQ(false, on_off_switch.in<StateOn>());
on_off_switch.trigger<EventTurnOn>();
std::cout << on_off_switch.info() << std::endl;
EXPECT_EQ(false, on_off_switch.in<StateOff>());
EXPECT_EQ(true, on_off_switch.in<StateOn>());
}
| #include <gtest/gtest.h>
#include "OnOffSwitch.h"
TEST(TestOnOffSwitch, main) {
using namespace antoniocoratelli;
// Initializing the switch: it's Off by default.
OnOffSwitch on_off_switch;
std::cout << on_off_switch.info() << std::endl;
EXPECT_EQ(true, on_off_switch.in<StateOff>());
EXPECT_EQ(false, on_off_switch.in<StateOn>());
// This simple switch doesn't have non-controllable events in any state,
// thus any call to the update() method will have no effect.
on_off_switch.update();
std::cout << on_off_switch.info() << std::endl;
EXPECT_EQ(true, on_off_switch.in<StateOff>());
EXPECT_EQ(false, on_off_switch.in<StateOn>());
// Turning on the switch, we expect that the state changes to On
on_off_switch.trigger<EventTurnOn>();
std::cout << on_off_switch.info() << std::endl;
EXPECT_EQ(false, on_off_switch.in<StateOff>());
EXPECT_EQ(true, on_off_switch.in<StateOn>());
// Trying to trigger an event that can't be triggered in this state
EXPECT_THROW(on_off_switch.trigger<EventTurnOn>(), std::logic_error);
// Turning off the switch, we expect that the state changes to Off
on_off_switch.trigger<EventTurnOff>();
std::cout << on_off_switch.info() << std::endl;
EXPECT_EQ(true, on_off_switch.in<StateOff>());
EXPECT_EQ(false, on_off_switch.in<StateOn>());
// Trying to trigger an event that can't be triggered in this state
EXPECT_THROW(on_off_switch.trigger<EventTurnOff>(), std::logic_error);
}
|
Remove boilerplate anchors.fill parent from artists | #include "qniteartist.h"
QniteArtist::QniteArtist(QQuickItem* parent):
QQuickItem(parent),
m_axes{nullptr},
m_selectable{false}
{
}
QniteArtist::~QniteArtist()
{
}
QniteAxes* QniteArtist::axes() const
{
return m_axes;
}
void QniteArtist::setAxes(QniteAxes* axes)
{
if (m_axes != axes) {
m_axes = axes;
emit axesChanged();
updateAxes();
}
}
void QniteArtist::updateAxes()
{
}
void QniteArtist::setSelectable(bool selectable)
{
if (selectable != m_selectable) {
if (!selectable && selected()) {
clearSelection();
}
m_selectable = selectable;
emit selectableChanged();
}
}
/*!
If the artist is not selectable, completely skip the logic determining
the selection state.
*/
bool QniteArtist::selected() const
{
return selectable() && isSelected();
}
| #include "qniteartist.h"
#include "qniteaxes.h"
QniteArtist::QniteArtist(QQuickItem* parent):
QQuickItem(parent),
m_axes{nullptr},
m_selectable{false}
{
}
QniteArtist::~QniteArtist()
{
}
QniteAxes* QniteArtist::axes() const
{
return m_axes;
}
void QniteArtist::setAxes(QniteAxes* axes)
{
if (m_axes != axes) {
m_axes = axes;
emit axesChanged();
updateAxes();
}
}
void QniteArtist::updateAxes()
{
disconnect(m_axes, SIGNAL(widthChanged()), this, 0);
disconnect(m_axes, SIGNAL(heightChanged()), this, 0);
if (m_axes != nullptr) {
setWidth(m_axes->width());
setHeight(m_axes->height());
connect(m_axes, &QQuickItem::widthChanged, [=](){ this->setWidth(m_axes->width()); });
connect(m_axes, &QQuickItem::heightChanged, [=](){ this->setHeight(m_axes->height()); });
}
}
void QniteArtist::setSelectable(bool selectable)
{
if (selectable != m_selectable) {
if (!selectable && selected()) {
clearSelection();
}
m_selectable = selectable;
emit selectableChanged();
}
}
/*!
If the artist is not selectable, completely skip the logic determining
the selection state.
*/
bool QniteArtist::selected() const
{
return selectable() && isSelected();
}
|
Fix size of dot product | #include <numeric>
#include <vector>
#include "bulk/bulk.hpp"
#include "set_backend.hpp"
int main() {
environment env;
env.spawn(env.available_processors(), [](bulk::world& world, int s, int p) {
// block distribution
int size = 10;
std::vector<int> xs(size);
std::vector<int> ys(size);
std::iota(xs.begin(), xs.end(), s * size);
std::iota(ys.begin(), ys.end(), s * size);
// compute local dot product
bulk::var<int> result(world);
for (int i = 0; i < size; ++i) {
result.value() += xs[i] * ys[i];
}
world.sync();
// reduce to find global dot product
auto alpha = bulk::foldl(result, [](int& lhs, int rhs) { lhs += rhs; });
world.log("%d/%d: alpha = %d", s, p, alpha);
});
return 0;
}
| #include <numeric>
#include <vector>
#include "bulk/bulk.hpp"
#include "set_backend.hpp"
int main() {
environment env;
env.spawn(env.available_processors(), [](bulk::world& world, int s, int p) {
// block distribution
int size = 1000;
int local_size = size / p;
std::vector<int> xs(local_size);
std::vector<int> ys(local_size);
std::iota(xs.begin(), xs.end(), s * local_size);
std::iota(ys.begin(), ys.end(), s * local_size);
// compute local dot product
bulk::var<int> result(world);
for (int i = 0; i < local_size; ++i) {
result.value() += xs[i] * ys[i];
}
world.sync();
// reduce to find global dot product
auto alpha = bulk::foldl(result, [](int& lhs, int rhs) { lhs += rhs; });
world.log("%d/%d: alpha = %d", s, p, alpha);
});
return 0;
}
|
Fix overflow bug in edge detector | #include "Halide.h"
namespace {
class EdgeDetect : public Halide::Generator<EdgeDetect> {
public:
ImageParam input{ UInt(8), 2, "input" };
Func build() {
Var x, y;
Func clamped = Halide::BoundaryConditions::repeat_edge(input);
// Gradients in x and y.
Func gx("gx");
Func gy("gy");
gx(x, y) = (clamped(x + 1, y) - clamped(x - 1, y)) / 2;
gy(x, y) = (clamped(x, y + 1) - clamped(x, y - 1)) / 2;
Func result("result");
result(x, y) = gx(x, y) * gx(x, y) + gy(x, y) * gy(x, y) + 128;
// CPU schedule:
// Parallelize over scan lines, 4 scanlines per task.
// Independently, vectorize in x.
result
.parallel(y, 4)
.vectorize(x, natural_vector_size(UInt(8)));
return result;
}
};
Halide::RegisterGenerator<EdgeDetect> register_edge_detect{ "edge_detect" };
} // namespace
| #include "Halide.h"
namespace {
class EdgeDetect : public Halide::Generator<EdgeDetect> {
public:
ImageParam input{ UInt(8), 2, "input" };
Func build() {
Var x, y;
Func clamped = Halide::BoundaryConditions::repeat_edge(input);
// Gradients in x and y.
Func gx("gx");
Func gy("gy");
gx(x, y) = cast<uint16_t>(clamped(x + 1, y)) - clamped(x - 1, y);
gy(x, y) = cast<uint16_t>(clamped(x, y + 1)) - clamped(x, y - 1);
Func result("result");
result(x, y) = cast<uint8_t>(min(255, gx(x, y) * gx(x, y) + gy(x, y) * gy(x, y)));
// CPU schedule:
// Parallelize over scan lines, 4 scanlines per task.
// Independently, vectorize in x.
result
.parallel(y, 4)
.vectorize(x, natural_vector_size(UInt(8)));
return result;
}
};
Halide::RegisterGenerator<EdgeDetect> register_edge_detect{ "edge_detect" };
} // namespace
|
Implement with gnome-keyring on Linux. | #include "keytar.h"
namespace keytar {
bool AddPassword(const std::string& service,
const std::string& account,
const std::string& password) {
return false;
}
bool GetPassword(const std::string& service,
const std::string& account,
std::string* password) {
return false;
}
bool DeletePassword(const std::string& service, const std::string& account) {
return false;
}
bool FindPassword(const std::string& service, std::string* password) {
return false;
}
} // namespace keytar
| #include "keytar.h"
#include <gnome-keyring.h>
namespace keytar {
namespace {
const GnomeKeyringPasswordSchema kGnomeSchema = {
GNOME_KEYRING_ITEM_GENERIC_SECRET, {
{ "service", GNOME_KEYRING_ATTRIBUTE_TYPE_STRING },
{ "account", GNOME_KEYRING_ATTRIBUTE_TYPE_STRING },
{ NULL }
}
};
} // namespace
bool AddPassword(const std::string& service,
const std::string& account,
const std::string& password) {
return gnome_keyring_store_password_sync(
&kGnomeSchema,
NULL, // Default keyring.
(service + "/" + account).c_str(), // Display name.
password.c_str(),
"service", service.c_str(),
"account", account.c_str(),
NULL) == GNOME_KEYRING_RESULT_OK;
}
bool GetPassword(const std::string& service,
const std::string& account,
std::string* password) {
gchar* raw_passwords;
GnomeKeyringResult result = gnome_keyring_find_password_sync(
&kGnomeSchema,
&raw_passwords,
"service", service.c_str(),
"account", account.c_str(),
NULL);
if (result != GNOME_KEYRING_RESULT_OK)
return false;
if (raw_passwords != NULL)
*password = raw_passwords;
gnome_keyring_free_password(raw_passwords);
return true;
}
bool DeletePassword(const std::string& service, const std::string& account) {
return gnome_keyring_delete_password_sync(
&kGnomeSchema,
"service", service.c_str(),
"account", account.c_str(),
NULL) == GNOME_KEYRING_RESULT_OK;
}
bool FindPassword(const std::string& service, std::string* password) {
gchar* raw_passwords;
GnomeKeyringResult result = gnome_keyring_find_password_sync(
&kGnomeSchema,
&raw_passwords,
"service", service.c_str(),
NULL);
if (result != GNOME_KEYRING_RESULT_OK)
return false;
if (raw_passwords != NULL)
*password = raw_passwords;
gnome_keyring_free_password(raw_passwords);
return true;
}
} // namespace keytar
|
Use strerror_s for SysErrorString on Windows | // Copyright (c) 2020-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <tinyformat.h>
#include <util/syserror.h>
#include <cstring>
std::string SysErrorString(int err)
{
char buf[256];
buf[0] = 0;
/* Too bad there are two incompatible implementations of the
* thread-safe strerror. */
const char *s;
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
s = buf;
if (strerror_r(err, buf, sizeof(buf)))
buf[0] = 0;
#endif
return strprintf("%s (%d)", s, err);
}
| // Copyright (c) 2020-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <tinyformat.h>
#include <util/syserror.h>
#include <cstring>
std::string SysErrorString(int err)
{
char buf[256];
buf[0] = 0;
/* Too bad there are three incompatible implementations of the
* thread-safe strerror. */
const char *s;
#ifdef WIN32
s = buf;
if (strerror_s(buf, sizeof(buf), err) != 0)
buf[0] = 0;
#else
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
s = buf;
if (strerror_r(err, buf, sizeof(buf)))
buf[0] = 0;
#endif
#endif
return strprintf("%s (%d)", s, err);
}
|
Test some things in ADSR. | #include <iostream>
#include "../src/ADSR.h"
using namespace std;
int main() {
homu::ADSR adsr(10000);
adsr.setAttack(0);
adsr.setDecay(0);
adsr.setSustain(1);
adsr.setRelease(0);
adsr.start();
for (int i = 0; i < 10000; ++i) {
float s = adsr.nextSample();
if (i >= 5000) {
adsr.stopSustain();
}
if (s > 1 || s < -1) {
cerr << "Warning: s = " << s << endl;
}
cout << s << endl;
}
return 0;
}
| #include <iostream>
#include "../src/ADSR.h"
using namespace std;
int main() {
homu::ADSR adsr(10000);
adsr.setAttack(0);
adsr.setDecay(0);
adsr.setSustain(1);
adsr.setRelease(0);
adsr.start();
for (int i = 0; i < 1000; ++i) {
float s = adsr.nextSample();
if (i >= 500) {
adsr.stopSustain();
}
if (s > 1 || s < -1) {
cerr << "Warning: s = " << s << endl;
}
cout << s << endl;
}
adsr.setAttack(0.1);
adsr.setDecay(0.2);
adsr.setSustain(0.7);
adsr.setRelease(0.3);
adsr.start();
while (true) {
if (adsr.secondsPlayed() >= 0.5) { adsr.stopSustain(); }
if (adsr.finished()) { break; }
float s = adsr.nextSample();
if (s > 1 || s < -1) {
cerr << "Warning: s = " << s << endl;
}
cout << s << endl;
}
adsr.setAttack(0.1);
adsr.setDecay(0.2);
adsr.setSustain(0.7);
adsr.setRelease(0.3);
adsr.start();
while (true) {
if (adsr.secondsPlayed() >= 0.05) { adsr.stopSustain(); }
if (adsr.finished()) { break; }
float s = adsr.nextSample();
if (s > 1 || s < -1) {
cerr << "Warning: s = " << s << endl;
}
cout << s << endl;
}
return 0;
}
|
Create test with wrong id type. | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE state
#include <boost/test/unit_test.hpp>
#include "response.h"
BOOST_AUTO_TEST_CASE(boolean_success_false)
{
cJSON *id = cJSON_CreateString("request1");
cJSON *response = create_boolean_success_response(id, 0);
cJSON *result = cJSON_GetObjectItem(response, "result");
BOOST_CHECK(result->type == cJSON_False);
cJSON_Delete(id);
cJSON_Delete(response);
}
BOOST_AUTO_TEST_CASE(boolean_success_true)
{
cJSON *id = cJSON_CreateString("request1");
cJSON *response = create_boolean_success_response(id, 1);
cJSON *result = cJSON_GetObjectItem(response, "result");
BOOST_CHECK(result->type == cJSON_True);
cJSON_Delete(id);
cJSON_Delete(response);
}
| #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE state
#include <boost/test/unit_test.hpp>
#include "response.h"
BOOST_AUTO_TEST_CASE(boolean_success_false)
{
cJSON *id = cJSON_CreateString("request1");
cJSON *response = create_boolean_success_response(id, 0);
cJSON *result = cJSON_GetObjectItem(response, "result");
BOOST_CHECK(result->type == cJSON_False);
cJSON_Delete(id);
cJSON_Delete(response);
}
BOOST_AUTO_TEST_CASE(boolean_success_true)
{
cJSON *id = cJSON_CreateString("request1");
cJSON *response = create_boolean_success_response(id, 1);
cJSON *result = cJSON_GetObjectItem(response, "result");
BOOST_CHECK(result->type == cJSON_True);
cJSON_Delete(id);
cJSON_Delete(response);
}
BOOST_AUTO_TEST_CASE(boolean_success_true_wrong_id_type)
{
cJSON *id = cJSON_CreateBool(0);
cJSON *response = create_boolean_success_response(id, 1);
BOOST_CHECK(response == NULL);
cJSON_Delete(id);
}
|
Add hand written preconditioned bicgstab | #include <Spark/SparseLinearSolvers.hpp>
#include <iostream>
Eigen::VectorXd spark::sparse_linear_solvers::DfeBiCgSolver::solve(
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& b)
{
Eigen::VectorXd vd(b.size());
return vd;
}
| #include <Spark/SparseLinearSolvers.hpp>
#include <iostream>
#include <stdexcept>
using Vd = Eigen::VectorXd;
Eigen::VectorXd spark::sparse_linear_solvers::DfeBiCgSolver::solve(
const Eigen::SparseMatrix<double>& A,
const Eigen::VectorXd& b)
{
std::cout << "Running bicgstab!!!" << std::endl;
Vd x(b.size());
Vd p(b.size());
Vd v(b.size());
double rho, alpha, omega, beta;
double rho_prev, omega_prev;
Vd r = b - A * x;
Vd rhat = r;
rho = rho_prev = alpha = omega = omega_prev = 1;
x.setZero();
v.setZero();
p.setZero();
int maxIter = 2000000;
double normErr = 1E-15;
Vd precon(b.size());
for (int i = 0; i < b.size(); i++) {
if (A.diagonal()(i) == 0)
throw std::invalid_argument("Main diagonal contains zero elements");
precon[i] = 1/A.diagonal()(i);
}
for (int i = 0; i < maxIter; i++) {
std::cout << "Iteration " << i << std::endl;
rho = rhat.dot(r);
beta = rho / rho_prev * alpha / omega_prev;
p = r + beta * (p - omega_prev * v);
Vd y = precon.cwiseProduct(p);
v = A * y;
alpha = rho / rhat.dot(v);
Vd s = r - alpha * v;
if (s.norm() < normErr) {
return x + alpha * p;
}
Vd z = precon.cwiseProduct(s);
Vd t = A * z;
Vd tmp = precon.cwiseProduct(t);
omega = tmp.dot(z) / tmp.dot(tmp);
x = x + alpha * y + omega * z;
r = s - omega * t;
omega_prev = omega;
rho_prev = rho;
}
return x;
}
|
Add code to process windfury game tag | // This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/SetGameTagTask.hpp>
namespace RosettaStone::SimpleTasks
{
SetGameTagTask::SetGameTagTask(EntityType entityType, GameTag tag, int amount)
: ITask(entityType), m_gameTag(tag), m_amount(amount)
{
// Do nothing
}
TaskID SetGameTagTask::GetTaskID() const
{
return TaskID::SET_GAME_TAG;
}
TaskStatus SetGameTagTask::Impl(Player& player)
{
auto entities =
IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
for (auto& entity : entities)
{
entity->SetGameTag(m_gameTag, m_amount);
}
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::SimpleTasks
| // This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/SetGameTagTask.hpp>
namespace RosettaStone::SimpleTasks
{
SetGameTagTask::SetGameTagTask(EntityType entityType, GameTag tag, int amount)
: ITask(entityType), m_gameTag(tag), m_amount(amount)
{
// Do nothing
}
TaskID SetGameTagTask::GetTaskID() const
{
return TaskID::SET_GAME_TAG;
}
TaskStatus SetGameTagTask::Impl(Player& player)
{
auto entities =
IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
for (auto& entity : entities)
{
entity->SetGameTag(m_gameTag, m_amount);
// Process windfury
if (m_gameTag == GameTag::WINDFURY && m_amount == 1)
{
auto m = dynamic_cast<Minion*>(entity);
if (m != nullptr && m->numAttacked == 1 &&
m->GetGameTag(GameTag::EXHAUSTED) == 1)
{
m->SetGameTag(GameTag::EXHAUSTED, 0);
}
}
}
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::SimpleTasks
|
Update input generator to be in line with description | #ifndef WARGEN_CPP
#define WARGEN_CPP
#include <algorithm>
#include <vector>
#include <iostream>
#include <fstream>
int main() {
std::vector<char> cards = {'1','1','1','1','2','2','2','2','3','3','3','3','4','4','4','4','5','5','5','5','6','6','6','6','7','7','7','7','8','8','8','8','9','9','9','9','T','T','T','T','J','J','J','J','Q','Q','Q','Q','K','K','K','K'};
std::ofstream myFile;
myFile.open("input1.txt");
std::random_shuffle(cards.begin(), cards.end());
for(int i = 0; i < 52; i++) {
myFile << cards[i];
if(i==25) {
myFile << "\n";
}
}
};
#endif
| #ifndef WARGEN_CPP
#define WARGEN_CPP
#include <algorithm>
#include <vector>
#include <iostream>
#include <fstream>
int main() {
std::vector<char> cards = {'1','1','1','1','2','2','2','2','3','3','3','3','4','4','4','4','5','5','5','5','6','6','6','6','7','7','7','7','8','8','8','8','9','9','9','9','T','T','T','T','J','J','J','J','Q','Q','Q','Q','K','K','K','K'};
std::vector<int> thresholds = {6,7,8,9,10,11,12};
std::ofstream myFile;
myFile.open("input1.txt");
std::random_shuffle(cards.begin(), cards.end());
std::random_shuffle(thresholds.begin(), thresholds.end());
for(int i = 0; i < 52; i++) {
myFile << cards[i];
if(i==25) {
myFile << "\n";
}
}
myFile << "\n";
for(int i = 0; i < 7; i++) {
myFile << thresholds[i];
}
std::random_shuffle(thresholds.begin(), thresholds.end());
myFile << "\n";
for(int i = 0; i < 7; i++) {
myFile << thresholds[i];
}
myFile.close9);
};
#endif
|
Fix bug with comparing SearchParams. | #include "params.hpp"
#include "../coding/multilang_utf8_string.hpp"
namespace search
{
SearchParams::SearchParams()
: m_inputLanguageCode(StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE),
m_searchMode(ALL), m_validPos(false)
{
}
void SearchParams::SetPosition(double lat, double lon)
{
m_lat = lat;
m_lon = lon;
m_validPos = true;
}
void SearchParams::SetInputLanguage(string const & language)
{
/// @todo take into an account zh_pinyin, ko_rm and ja_rm
size_t const delimPos = language.find_first_of("-_");
m_inputLanguageCode = StringUtf8Multilang::GetLangIndex(
delimPos == string::npos ? language : language.substr(0, delimPos));
}
bool SearchParams::IsLanguageValid() const
{
return (m_inputLanguageCode != StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE);
}
bool SearchParams::IsEqualCommon(SearchParams const & rhs) const
{
// do not compare m_mode
return (m_query == rhs.m_query &&
m_inputLanguageCode == rhs.m_inputLanguageCode &&
m_validPos == rhs.m_validPos &&
m_searchMode == rhs.m_searchMode);
}
string DebugPrint(SearchParams const & params)
{
string s("search::SearchParams: ");
s = s + "Query = " + params.m_query;
return s;
}
} // namespace search
| #include "params.hpp"
#include "../coding/multilang_utf8_string.hpp"
namespace search
{
SearchParams::SearchParams()
: m_inputLanguageCode(StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE),
m_searchMode(ALL), m_validPos(false)
{
}
void SearchParams::SetPosition(double lat, double lon)
{
m_lat = lat;
m_lon = lon;
m_validPos = true;
}
void SearchParams::SetInputLanguage(string const & language)
{
/// @todo take into an account zh_pinyin, ko_rm and ja_rm
size_t const delimPos = language.find_first_of("-_");
m_inputLanguageCode = StringUtf8Multilang::GetLangIndex(
delimPos == string::npos ? language : language.substr(0, delimPos));
}
bool SearchParams::IsLanguageValid() const
{
return (m_inputLanguageCode != StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE);
}
bool SearchParams::IsEqualCommon(SearchParams const & rhs) const
{
return (m_query == rhs.m_query &&
m_inputLanguageCode == rhs.m_inputLanguageCode &&
m_validPos == rhs.m_validPos &&
m_searchMode == rhs.m_searchMode);
}
string DebugPrint(SearchParams const & params)
{
string s("search::SearchParams: ");
s = s + "Query = " + params.m_query;
return s;
}
} // namespace search
|
Add test separation for generation tests. | #include "grune/all.hpp"
#include <boost/filesystem.hpp>
#include <fstream>
#define ADD_TEST(name) \
extern void name(std::ostream&);
ADD_TEST(test_anbncn);
ADD_TEST(test_numbers);
ADD_TEST(test_numbers_simple);
ADD_TEST(test_tdh);
ADD_TEST(test_turtle);
typedef void (*test_fcn_t)(std::ostream&);
void run_test(test_fcn_t test, const std::string& name)
{
std::cout << "Running test " << name << "..." << std::endl;
std::ofstream results("./results/" + name + ".results");
test(results);
}
#define RUN_TEST(name) run_test(name, #name)
int main()
{
RUN_TEST(test_anbncn);
RUN_TEST(test_numbers_simple);
RUN_TEST(test_numbers);
RUN_TEST(test_turtle);
RUN_TEST(test_tdh);
return 0;
}
| #include "grune/all.hpp"
#include <boost/filesystem.hpp>
#include <fstream>
#define ADD_TEST(name) \
extern void name(std::ostream&);
ADD_TEST(test_anbncn);
ADD_TEST(test_numbers);
ADD_TEST(test_numbers_simple);
ADD_TEST(test_tdh);
ADD_TEST(test_turtle);
typedef void (*test_fcn_t)(std::ostream&);
void run_test(test_fcn_t test, const std::string& name)
{
std::cout << "Running test " << name << "..." << std::endl;
std::ofstream results("./results/" + name + ".results");
test(results);
}
#ifndef COVERITY_BUILD
#define RUN_TEST(name) run_test(name, #name)
#else
#include <coverity-test-separation.h>
#define RUN_TEST(name) \
do { \
COVERITY_TS_START_TEST(#name); \
run_test(name, #name); \
COVERITY_TS_END_TEST(); \
} while (0)
#endif
int main()
{
#ifdef COVERITY_BUILD
COVERITY_TS_SET_SUITE_NAME("generation_tests");
#endif
RUN_TEST(test_anbncn);
RUN_TEST(test_numbers_simple);
RUN_TEST(test_numbers);
RUN_TEST(test_turtle);
RUN_TEST(test_tdh);
return 0;
}
|
Remove a stray debug line | //
// Gyroid.cpp
// VolumeRenderer
//
// Created by Calvin Loncaric on 6/26/11.
//
#include "Gyroid.h"
#include <cmath>
float Gyroid::valueAt(float x, float y, float z) const
{
return (cosf(x) * sinf(y) + cosf(y) * sinf(z) + cosf(z) * sinf(x));
}
vector Gyroid::gradientAt(float x, float y, float z) const
{
return Isosurface::gradientAt(x, y, z);
float gx = cosf(x) * cosf(z) - sinf(x) * sinf(y);
float gy = cosf(x) * cosf(y) - sinf(y) * sinf(z);
float gz = cosf(y) * cosf(z) - sinf(x) * sinf(z);
vector result = { gx, gy, gz };
normalize(result);
return result;
}
| //
// Gyroid.cpp
// VolumeRenderer
//
// Created by Calvin Loncaric on 6/26/11.
//
#include "Gyroid.h"
#include <cmath>
float Gyroid::valueAt(float x, float y, float z) const
{
return (cosf(x) * sinf(y) + cosf(y) * sinf(z) + cosf(z) * sinf(x));
}
vector Gyroid::gradientAt(float x, float y, float z) const
{
float gx = cosf(x) * cosf(z) - sinf(x) * sinf(y);
float gy = cosf(x) * cosf(y) - sinf(y) * sinf(z);
float gz = cosf(y) * cosf(z) - sinf(x) * sinf(z);
vector result = { gx, gy, gz };
normalize(result);
return result;
}
|
Use stack instead of malloc | #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <excpt.h>
#include "sapi4.hpp"
int main(int argc, char** argv)
{
VOICE_INFO VoiceInfo;
if (!InitializeForVoice(argv[1], &VoiceInfo)) {
return 0;
}
UINT64 Len;
LPSTR outFile = (LPSTR)malloc(17);
GetTTS(&VoiceInfo, atoi(argv[2]), atoi(argv[3]), argv[4], &Len, &outFile);
printf("%s\n", outFile);
free(outFile);
} | #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <excpt.h>
#include "sapi4.hpp"
int main(int argc, char** argv)
{
VOICE_INFO VoiceInfo;
if (!InitializeForVoice(argv[1], &VoiceInfo)) {
return 0;
}
UINT64 Len;
LPSTR outFile[17];
GetTTS(&VoiceInfo, atoi(argv[2]), atoi(argv[3]), argv[4], &Len, &outFile);
printf("%s\n", outFile);
} |
Make MSVC release build actually work | #pragma warning( disable : 4350 )
#pragma warning(push, 3)
#include <iostream>
#pragma warning(pop)
int main(int , char **) {
std::cout << "Hello CI!" << std::endl;
return 0;
}
#pragma warning( disable : 4710 4514)
| #pragma warning( disable : 4350 4710 )
#pragma warning(push, 3)
#include <iostream>
#pragma warning(pop)
int main(int , char **) {
std::cout << "Hello CI!" << std::endl;
return 0;
}
#pragma warning( disable : 4514)
|
Fix missing include in the example | #include <spdlog/spdlog.h>
int main(int argc, char* argv[]) {
auto console = spdlog::stdout_logger_mt("console");
console->info("Hello from INFO");
}
| #include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_sinks.h>
int main(int argc, char* argv[]) {
auto console = spdlog::stdout_logger_mt("console");
console->info("Hello from INFO");
return 0;
}
|
Test for { escaping in format() | //
// Created by Jan de Visser on 2021-09-22.
//
#include <core/Format.h>
#include <core/StringUtil.h>
#include <gtest/gtest.h>
TEST(Format, format_int) {
std::string formatted = Obelix::format("{}", 42);
EXPECT_EQ(formatted, "42");
}
TEST(Format, format_string) {
std::string formatted = Obelix::format("{}", std::string("Hello World!"));
EXPECT_EQ(formatted, "Hello World!");
}
TEST(Format, format_char)
{
std::string formatted = Obelix::format("{}","Hello World!");
EXPECT_EQ(formatted, "Hello World!");
}
TEST(Format, format_char_and_int)
{
std::string formatted = Obelix::format("String: '{}' int: {}-", "Hello World!", 42);
EXPECT_EQ(formatted, "String: 'Hello World!' int: 42-");
}
| //
// Created by Jan de Visser on 2021-09-22.
//
#include <core/Format.h>
#include <core/StringUtil.h>
#include <gtest/gtest.h>
TEST(Format, format_int) {
std::string formatted = Obelix::format("{}", 42);
EXPECT_EQ(formatted, "42");
}
TEST(Format, format_string) {
std::string formatted = Obelix::format("{}", std::string("Hello World!"));
EXPECT_EQ(formatted, "Hello World!");
}
TEST(Format, format_char)
{
std::string formatted = Obelix::format("{}", "Hello World!");
EXPECT_EQ(formatted, "Hello World!");
}
TEST(Format, format_char_and_int)
{
std::string formatted = Obelix::format("String: '{}' int: {}-", "Hello World!", 42);
EXPECT_EQ(formatted, "String: 'Hello World!' int: 42-");
}
TEST(Format, format_escape)
{
std::string formatted = Obelix::format("String: '{}' Escaped brace: {{ and a close } int: {}-", "Hello World!", 42);
EXPECT_EQ(formatted, "String: 'Hello World!' Escaped brace: { and a close } int: 42-");
}
|
Enable flash prefetch in low-level initialization for STM32F0 | /**
* \file
* \brief chip::lowLevelInitialization() implementation for STM32F0
*
* \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/chip/lowLevelInitialization.hpp"
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
void lowLevelInitialization()
{
}
} // namespace chip
} // namespace distortos
| /**
* \file
* \brief chip::lowLevelInitialization() implementation for STM32F0
*
* \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/chip/lowLevelInitialization.hpp"
#include "distortos/chip/STM32F0-FLASH.hpp"
#include "distortos/distortosConfiguration.h"
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
void lowLevelInitialization()
{
#ifdef CONFIG_CHIP_STM32F0_FLASH_PREFETCH_ENABLE
configurePrefetchBuffer(true);
#else // !def CONFIG_CHIP_STM32F0_FLASH_PREFETCH_ENABLE
configurePrefetchBuffer(false);
#endif // !def CONFIG_CHIP_STM32F0_FLASH_PREFETCH_ENABLE
}
} // namespace chip
} // namespace distortos
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.