Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix wrong number of max open files |
#include "ReadFileManager.h" // Own interface
#include "ReadFile.h" // engine::ReadFile
namespace engine {
ReadFileManager::ReadFileManager()
{
// Default number of open files
max_open_files = 10;
}
ReadFile *ReadFileManager::getReadFile( std::string fileName )
{
ReadFile *f = read_files.extractFromMap( fileName );
// Remove non-valid ReadFiles
if( f && !f->isValid() )
{
delete f;
f = NULL;
}
if( !f )
f = new ReadFile( fileName );
// Insert at front ( remove the last used at the back )
read_files.insertAtFront( fileName , f );
// Remove old File descriptors if necessary
while( (int)read_files.size() > max_open_files )
{
ReadFile *rf = read_files.extractFromBack();
if( rf == f )
LM_X(1, ("Internal error"));
rf->close();
delete rf;
}
return f;
}
} |
#include "ReadFileManager.h" // Own interface
#include "ReadFile.h" // engine::ReadFile
namespace engine {
ReadFileManager::ReadFileManager()
{
// Default number of open files
max_open_files = 100;
}
ReadFile *ReadFileManager::getReadFile( std::string fileName )
{
ReadFile *f = read_files.extractFromMap( fileName );
// Remove non-valid ReadFiles
if( f && !f->isValid() )
{
delete f;
f = NULL;
}
if( !f )
f = new ReadFile( fileName );
// Insert at front ( remove the last used at the back )
read_files.insertAtFront( fileName , f );
// Remove old File descriptors if necessary
while( (int)read_files.size() > max_open_files )
{
ReadFile *rf = read_files.extractFromBack();
if( rf == f )
LM_X(1, ("Internal error"));
rf->close();
delete rf;
}
return f;
}
}
|
Fix logging resolution as chars. | //
// WindowSettings.cpp
// Hume
//
// Created by Marshall Clyburn on 7/11/14.
// Copyright (c) 2014 Marshall Clyburn. All rights reserved.
//
#include "WindowSettings.h"
namespace hm
{
/*
Default to a fullscreen window at the maximum
resolution supported by the attached screen.
*/
WindowSettings::WindowSettings() : fullscreen(true), title("Hume Window")
{
setBestFullscreenMode();
}
WindowSettings::~WindowSettings()
{
}
/*
Set the window to fullscreen at the best possible
resolution attainable.
*/
void WindowSettings::setBestFullscreenMode()
{
fullscreen = true;
int display_mode_count = SDL_GetNumDisplayModes(0);
if(display_mode_count < 1)
{
Logger::getLogger()->log("No available display modes.", ERROR);
exit(0);
}
else
{
SDL_DisplayMode mode;
int success;
do
{
success = SDL_GetDisplayMode(0, 0, &mode);
}
while(success != 0);
if(Logger::getLogger()->getLogLevel() >= LogLevel::INFO)
{
std::string msg = "Using resolution of ";
msg += mode.w;
msg += "x";
msg += mode.h;
msg += ".";
Logger::getLogger()->log(msg);
}
}
}
}
| //
// WindowSettings.cpp
// Hume
//
// Created by Marshall Clyburn on 7/11/14.
// Copyright (c) 2014 Marshall Clyburn. All rights reserved.
//
#include "WindowSettings.h"
namespace hm
{
/*
Default to a fullscreen window at the maximum
resolution supported by the attached screen.
*/
WindowSettings::WindowSettings() : fullscreen(true), title("Hume Window")
{
setBestFullscreenMode();
}
WindowSettings::~WindowSettings()
{
}
/*
Set the window to fullscreen at the best possible
resolution attainable.
*/
void WindowSettings::setBestFullscreenMode()
{
fullscreen = true;
int display_mode_count = SDL_GetNumDisplayModes(0);
if(display_mode_count < 1)
{
Logger::getLogger()->log("No available display modes.", ERROR);
exit(0);
}
else
{
SDL_DisplayMode mode;
int success;
do
{
success = SDL_GetDisplayMode(0, 0, &mode);
}
while(success != 0);
if(Logger::getLogger()->getLogLevel() >= LogLevel::INFO)
{
std::string msg = "Using resolution of " +
std::to_string(mode.w) + "x" +
std::to_string(mode.h) + ".";
Logger::getLogger()->log(msg);
}
}
}
}
|
Update return datatype function 'createRandomPopulation'. | #include <iostream>
#include <cstdlib>
#include "population.h"
int **POPULATION::initializePopulation(int individuals, int genes, bool FILL_ZERO)
{
int **population;
if (!FILL_ZERO)
{
population = (int **) malloc(individuals * sizeof(int *));
for (int i = 0; i < individuals; i++)
population[i] = (int *) malloc(genes * sizeof(int));
}
else
{
population = (int **) calloc(individuals, sizeof(int *));
for (int i = 0; i < individuals; i++)
population[i] = (int *) calloc(genes, sizeof(int));
}
return population;
}
int **POPULATION::createRandomPopulation(int **population, int individuals, int genes)
{
// Fill the 2d array with random genes
for (int pop = 0; pop < individuals; pop++)
{
for (int gene = 0; gene < genes; gene++)
{
population[pop][gene] = rand() % 2;
}
}
return 0;
}
| #include <iostream>
#include <cstdlib>
#include "population.h"
int **POPULATION::initializePopulation(int individuals, int genes, bool FILL_ZERO)
{
int **population;
if (!FILL_ZERO)
{
population = (int **) malloc(individuals * sizeof(int *));
for (int i = 0; i < individuals; i++)
population[i] = (int *) malloc(genes * sizeof(int));
}
else
{
population = (int **) calloc(individuals, sizeof(int *));
for (int i = 0; i < individuals; i++)
population[i] = (int *) calloc(genes, sizeof(int));
}
return population;
}
int POPULATION::createRandomPopulation(int **population, int individuals, int genes)
{
// Fill the 2d array with random genes
for (int pop = 0; pop < individuals; pop++)
{
for (int gene = 0; gene < genes; gene++)
{
population[pop][gene] = rand() % 2;
}
}
return 1;
}
|
Fix case where received message was potentially dropped in C++ bot | #include "connection.h"
hwo_connection::hwo_connection(const std::string& host, const std::string& port)
: socket(io_service)
{
tcp::resolver resolver(io_service);
tcp::resolver::query query(host, port);
boost::asio::connect(socket, resolver.resolve(query));
response_buf.prepare(8192);
}
hwo_connection::~hwo_connection()
{
socket.close();
}
jsoncons::json hwo_connection::receive_response(boost::system::error_code& error)
{
boost::asio::read_until(socket, response_buf, "\n", error);
if (error)
{
return jsoncons::json();
}
std::istream s(&response_buf);
return jsoncons::json::parse(s);
}
void hwo_connection::send_requests(const std::vector<jsoncons::json>& msgs)
{
jsoncons::output_format format;
format.escape_all_non_ascii(true);
boost::asio::streambuf request_buf;
std::ostream s(&request_buf);
for (const auto& m : msgs) {
m.to_stream(s, format);
s << std::endl;
}
socket.send(request_buf.data());
}
| #include "connection.h"
hwo_connection::hwo_connection(const std::string& host, const std::string& port)
: socket(io_service)
{
tcp::resolver resolver(io_service);
tcp::resolver::query query(host, port);
boost::asio::connect(socket, resolver.resolve(query));
response_buf.prepare(8192);
}
hwo_connection::~hwo_connection()
{
socket.close();
}
jsoncons::json hwo_connection::receive_response(boost::system::error_code& error)
{
auto len = boost::asio::read_until(socket, response_buf, "\n", error);
if (error)
{
return jsoncons::json();
}
auto buf = response_buf.data();
std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len);
response_buf.consume(len);
return jsoncons::json::parse_string(reply);
}
void hwo_connection::send_requests(const std::vector<jsoncons::json>& msgs)
{
jsoncons::output_format format;
format.escape_all_non_ascii(true);
boost::asio::streambuf request_buf;
std::ostream s(&request_buf);
for (const auto& m : msgs) {
m.to_stream(s, format);
s << std::endl;
}
socket.send(request_buf.data());
}
|
Fix flashing in WebContents we create | #include "browser/inspectable_web_contents.h"
#include "browser/inspectable_web_contents_impl.h"
namespace brightray {
InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {
return Create(content::WebContents::Create(create_params));
}
InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {
return new InspectableWebContentsImpl(web_contents);
}
}
| #include "browser/inspectable_web_contents.h"
#include "browser/inspectable_web_contents_impl.h"
#include "content/public/browser/web_contents_view.h"
namespace brightray {
InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {
auto contents = content::WebContents::Create(create_params);
#if defined(OS_MACOSX)
// Work around http://crbug.com/279472.
contents->GetView()->SetAllowOverlappingViews(true);
#endif
return Create(contents);
}
InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {
return new InspectableWebContentsImpl(web_contents);
}
}
|
Disable one MSAN test in AArch64 until we have a proper fix | // RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out
// Test origin propagation through insertvalue IR instruction.
#include <stdio.h>
#include <stdint.h>
struct mypair {
int64_t x;
int y;
};
mypair my_make_pair(int64_t x, int y) {
mypair p;
p.x = x;
p.y = y;
return p;
}
int main() {
int64_t * volatile p = new int64_t;
mypair z = my_make_pair(*p, 0);
if (z.x)
printf("zzz\n");
// CHECK: MemorySanitizer: use-of-uninitialized-value
// CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-3]]
// CHECK: Uninitialized value was created by a heap allocation
// CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-8]]
delete p;
return 0;
}
| // RUN: %clangxx_msan -fsanitize-memory-track-origins -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -O3 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out
// Test origin propagation through insertvalue IR instruction.
// REQUIRES: stable-runtime
#include <stdio.h>
#include <stdint.h>
struct mypair {
int64_t x;
int y;
};
mypair my_make_pair(int64_t x, int y) {
mypair p;
p.x = x;
p.y = y;
return p;
}
int main() {
int64_t * volatile p = new int64_t;
mypair z = my_make_pair(*p, 0);
if (z.x)
printf("zzz\n");
// CHECK: MemorySanitizer: use-of-uninitialized-value
// CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-3]]
// CHECK: Uninitialized value was created by a heap allocation
// CHECK: {{in main .*insertvalue_origin.cc:}}[[@LINE-8]]
delete p;
return 0;
}
|
Remove missed use of config.h | //===------------------------- cxa_exception.cpp --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//
// This file implements the "Exception Handling APIs"
// http://mentorembedded.github.io/cxx-abi/abi-eh.html
//
//===----------------------------------------------------------------------===//
// Support functions for the no-exceptions libc++ library
#include "config.h"
#include "cxxabi.h"
#include <exception> // for std::terminate
#include "cxa_exception.hpp"
#include "cxa_handlers.hpp"
namespace __cxxabiv1 {
extern "C" {
void
__cxa_increment_exception_refcount(void *thrown_object) throw() {
if (thrown_object != nullptr)
std::terminate();
}
void
__cxa_decrement_exception_refcount(void *thrown_object) throw() {
if (thrown_object != nullptr)
std::terminate();
}
void *__cxa_current_primary_exception() throw() { return nullptr; }
void
__cxa_rethrow_primary_exception(void* thrown_object) {
if (thrown_object != nullptr)
std::terminate();
}
bool
__cxa_uncaught_exception() throw() { return false; }
unsigned int
__cxa_uncaught_exceptions() throw() { return 0; }
} // extern "C"
} // abi
| //===------------------------- cxa_exception.cpp --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//
// This file implements the "Exception Handling APIs"
// http://mentorembedded.github.io/cxx-abi/abi-eh.html
//
//===----------------------------------------------------------------------===//
// Support functions for the no-exceptions libc++ library
#include "cxxabi.h"
#include <exception> // for std::terminate
#include "cxa_exception.hpp"
#include "cxa_handlers.hpp"
namespace __cxxabiv1 {
extern "C" {
void
__cxa_increment_exception_refcount(void *thrown_object) throw() {
if (thrown_object != nullptr)
std::terminate();
}
void
__cxa_decrement_exception_refcount(void *thrown_object) throw() {
if (thrown_object != nullptr)
std::terminate();
}
void *__cxa_current_primary_exception() throw() { return nullptr; }
void
__cxa_rethrow_primary_exception(void* thrown_object) {
if (thrown_object != nullptr)
std::terminate();
}
bool
__cxa_uncaught_exception() throw() { return false; }
unsigned int
__cxa_uncaught_exceptions() throw() { return 0; }
} // extern "C"
} // abi
|
Adjust minor animated tiles transgression | #include <QtPlugin>
\
#include "animatedtilesplugin.h"
#include "animatedtilesitem.h"
AnimatedTilesPlugin::AnimatedTilesPlugin()
{
this->mName = "AnimatedTiles";
//This should not be an advertized plugin until it is implemented
//this->mRole = "animatedTiles";
}
Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)
void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)
{
qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles");
}
| #include <QtPlugin>
\
#include "animatedtilesplugin.h"
#include "animatedtilesitem.h"
AnimatedTilesPlugin::AnimatedTilesPlugin()
{
setName("AnimatedTiles");
//This should not be an advertized plugin until it is implemented
//setRole("animatedTiles");
}
Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)
void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)
{
qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles");
}
|
Fix altitude not being reported in metres to PFD | #include "AbsPositionOverview.h"
AbsPositionOverview::AbsPositionOverview(QObject *parent) :
QObject(parent)
{
}
void AbsPositionOverview::parseGpsRawInt(LinkInterface *link, const mavlink_message_t &message, const mavlink_gps_raw_int_t &state)
{
if (state.fix_type > 2)
{
this->setLat(state.lat);
this->setLon(state.lon);
this->setAlt(state.alt);
this->setVel(state.vel);
}
}
void AbsPositionOverview::parseGlobalPositionInt(LinkInterface *link, const mavlink_message_t &message, const mavlink_global_position_int_t &state)
{
this->setRelativeAlt(state.relative_alt);
}
void AbsPositionOverview::messageReceived(LinkInterface* link,mavlink_message_t message)
{
switch (message.msgid)
{
case MAVLINK_MSG_ID_GPS_RAW_INT:
{
mavlink_gps_raw_int_t state;
mavlink_msg_gps_raw_int_decode(&message, &state);
parseGpsRawInt(link,message,state);
break;
}
case MAVLINK_MSG_ID_GLOBAL_POSITION_INT:
{
mavlink_global_position_int_t state;
mavlink_msg_global_position_int_decode(&message, &state);
parseGlobalPositionInt(link,message,state);
break;
}
}
}
| #include "AbsPositionOverview.h"
AbsPositionOverview::AbsPositionOverview(QObject *parent) :
QObject(parent)
{
}
void AbsPositionOverview::parseGpsRawInt(LinkInterface *link, const mavlink_message_t &message, const mavlink_gps_raw_int_t &state)
{
if (state.fix_type > 2)
{
this->setLat(state.lat);
this->setLon(state.lon);
this->setAlt(state.alt);
this->setVel(state.vel);
}
}
void AbsPositionOverview::parseGlobalPositionInt(LinkInterface *link, const mavlink_message_t &message, const mavlink_global_position_int_t &state)
{
this->setRelativeAlt(state.relative_alt/1000.0);
}
void AbsPositionOverview::messageReceived(LinkInterface* link,mavlink_message_t message)
{
switch (message.msgid)
{
case MAVLINK_MSG_ID_GPS_RAW_INT:
{
mavlink_gps_raw_int_t state;
mavlink_msg_gps_raw_int_decode(&message, &state);
parseGpsRawInt(link,message,state);
break;
}
case MAVLINK_MSG_ID_GLOBAL_POSITION_INT:
{
mavlink_global_position_int_t state;
mavlink_msg_global_position_int_decode(&message, &state);
parseGlobalPositionInt(link,message,state);
break;
}
}
}
|
Modify a couple tests to use asserts. | #include "gtest/gtest.h"
#include "Console.hpp"
#include <memory>
using namespace warbler;
class ConsoleTest
{
public:
static void noopCommandHandler(const std::shared_ptr<const std::vector<ConsoleArg>> &args) {};
static const std::shared_ptr<std::vector<ConsoleArgType>> args;
};
const std::shared_ptr<std::vector<ConsoleArgType>> ConsoleTest::args = std::make_shared<std::vector<ConsoleArgType>>();
TEST(constructor, default_constructor)
{
Console c;
}
TEST(methods, registerCommand)
{
Console c;
c.registerCommand("test", ConsoleTest::noopCommandHandler, ConsoleTest::args);
}
TEST(methods, registerCommand_null_func_throws)
{
Console c;
ASSERT_ANY_THROW(c.registerCommand("test", nullptr, ConsoleTest::args));
}
TEST(methods, registerCommand_empty_name_throws)
{
Console c;
ASSERT_ANY_THROW(c.registerCommand("", ConsoleTest::noopCommandHandler, ConsoleTest::args));
} | #include "gtest/gtest.h"
#include "Console.hpp"
#include <memory>
using namespace warbler;
class ConsoleTest
{
public:
static void noopCommandHandler(const std::shared_ptr<const std::vector<ConsoleArg>> &args) {};
static const std::shared_ptr<std::vector<ConsoleArgType>> args;
};
const std::shared_ptr<std::vector<ConsoleArgType>> ConsoleTest::args = std::make_shared<std::vector<ConsoleArgType>>();
TEST(constructor, default_constructor)
{
ASSERT_NO_THROW(Console c);
}
TEST(methods, registerCommand)
{
Console c;
ASSERT_NO_THROW(c.registerCommand("test", ConsoleTest::noopCommandHandler, ConsoleTest::args));
}
TEST(methods, registerCommand_null_func_throws)
{
Console c;
ASSERT_ANY_THROW(c.registerCommand("test", nullptr, ConsoleTest::args));
}
TEST(methods, registerCommand_empty_name_throws)
{
Console c;
ASSERT_ANY_THROW(c.registerCommand("", ConsoleTest::noopCommandHandler, ConsoleTest::args));
} |
Add support for reading input files from the command line. | #include <iostream>
#include "version.h"
#include "parser.h"
using namespace lean;
int main() {
std::cout << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ")\n";
frontend f;
return parse_commands(f, std::cin) ? 0 : 1;
}
| #include <iostream>
#include <fstream>
#include "version.h"
#include "parser.h"
using namespace lean;
int main(int argc, char ** argv) {
std::cout << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ")\n";
frontend f;
if (argc == 1) {
return parse_commands(f, std::cin) ? 0 : 1;
} else {
bool ok = true;
for (int i = 1; i < argc; i++) {
std::ifstream in(argv[i]);
if (!parse_commands(f, in))
ok = false;
}
return ok ? 0 : 1;
}
}
|
Fix random drawing of cards | /*
* Deck.cpp
*
* Created on: 11.01.2017
* Author: Stefan
*/
#include <memory>
#include <random>
#include "Deck.h"
#include "Card.h"
#include "GlobalDeclarations.h"
void Deck::AddSets(std::size_t N)
{
for(std::size_t i = 0; i < N; ++i)
{
AddCompleteSet();
}
}
Deck::pCard Deck::Draw()
{
// Random generator, copied from http://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
std::mt19937 rng(_rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uniformDist(0, Base::NumCards()-1); // guaranteed unbiased
auto random_integer = uniformDist(rng);
return Base::RemoveCard(random_integer);
}
void Deck::PrintNumCards() const
{
std::cout << "Cards in Deck = " << Base::NumCards() << std::endl;
}
void Deck::AddCompleteSet()
{
for( const auto & suit : SUIT)
{
for(const auto & face : FACE)
{
AddCard(pCard(new Card(face.first, suit)));
}
}
}
| /*
* Deck.cpp
*
* Created on: 11.01.2017
* Author: Stefan
*/
#include <memory>
#include <random>
#include "Deck.h"
#include "Card.h"
#include "GlobalDeclarations.h"
#include <chrono>
void Deck::AddSets(std::size_t N)
{
for(std::size_t i = 0; i < N; ++i)
{
AddCompleteSet();
}
}
Deck::pCard Deck::Draw()
{
// Use the time for a new seed each time a card is darwn
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine rng(seed);
std::uniform_int_distribution<int> uniformDist(0, Base::NumCards()-1);
auto random_integer = uniformDist(rng);
return Base::RemoveCard(random_integer);
}
void Deck::PrintNumCards() const
{
std::cout << "Cards in Deck = " << Base::NumCards() << std::endl;
}
void Deck::AddCompleteSet()
{
for( const auto & suit : SUIT)
{
for(const auto & face : FACE)
{
AddCard(pCard(new Card(face.first, suit)));
}
}
}
|
Add extra argument to toggle board printing | #include <iostream>
#include <thread>
#include <vector>
#include "World.h"
using namespace std;
int main(int argc, char * argv[]) {
if (argc != 4) {
std::cerr << "use: " << argv[0] << " dim iterations nworkers\n";
return -1;
}
int dim = atoi(argv[1]);
int iterations = atoi(argv[2]);
int workers = atoi(argv[3]);
World world(dim, dim, workers);
//world.randomize_world(42, 3);
/* GLIDER */
world.set_cell(1, 2, ALIVE);
world.set_cell(2, 3, ALIVE);
world.set_cell(3, 1, ALIVE);
world.set_cell(3, 2, ALIVE);
world.set_cell(3, 3, ALIVE);
/**/
world.print_world();
world.update_world(iterations);
world.print_world();
return(0);
}
| #include <iostream>
#include <thread>
#include <vector>
#include "World.h"
using namespace std;
int main(int argc, char * argv[]) {
if (argc < 4) {
std::cerr << "use: " << argv[0] << " dim iterations nworkers ?[print: on]\n";
return -1;
}
int dim = atoi(argv[1]);
int iterations = atoi(argv[2]);
int workers = atoi(argv[3]);
int print = 0;
if (argc >= 5) print = (std::string(argv[4]) == "on");
World world(dim, dim, workers);
//world.randomize_world(42, 3);
/* GLIDER */
world.set_cell(1, 2, ALIVE);
world.set_cell(2, 3, ALIVE);
world.set_cell(3, 1, ALIVE);
world.set_cell(3, 2, ALIVE);
world.set_cell(3, 3, ALIVE);
if(print)
world.print_world();
world.update_world(iterations);
if(print)
world.print_world();
return(0);
}
|
Fix for Release build break | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status_area_button.h"
#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"
////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton
StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
: MenuButton(NULL, std::wstring(), menu_delegate, false) {
set_border(NULL);
SetShowHighlighted(true);
}
void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
int bitmap_id;
switch(state()) {
case BS_NORMAL:
bitmap_id = IDR_STATUSBAR_CONTAINER;
break;
case BS_HOT:
bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
break;
case BS_PUSHED:
bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
break;
default:
NOTREACHED();
}
SkBitmap* container =
ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
canvas->DrawBitmapInt(*container, 0, 0);
canvas->DrawBitmapInt(icon(), 0, 0);
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status_area_button.h"
#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"
////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton
StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
: MenuButton(NULL, std::wstring(), menu_delegate, false) {
set_border(NULL);
SetShowHighlighted(true);
}
void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
int bitmap_id;
switch(state()) {
case BS_NORMAL:
bitmap_id = IDR_STATUSBAR_CONTAINER;
break;
case BS_HOT:
bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
break;
case BS_PUSHED:
bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
break;
default:
bitmap_id = IDR_STATUSBAR_CONTAINER;
NOTREACHED();
}
SkBitmap* container =
ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
canvas->DrawBitmapInt(*container, 0, 0);
canvas->DrawBitmapInt(icon(), 0, 0);
}
|
Fix Tools compilation under OS X | #ifdef __unix__
#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include "Types.h"
#include "Tools.h"
void StartBotProcess(const BotConfig &Agent, const std::string& CommandLine, void **ProcessId)
{
FILE* pipe = popen(CommandLine.c_str(), "r");
if (!pipe)
{
std::cerr << "Can't launch command '" <<
CommandLine << "'" << std::endl;
return;
}
*ProcessId = pipe;
int returnCode = pclose(pipe);
if (returnCode != 0)
{
std::cerr << "Failed to finish command '" <<
CommandLine << "', code: " << returnCode << std::endl;
}
}
void SleepFor(int seconds)
{
sleep(seconds);
}
void KillSc2Process(unsigned long pid)
{
kill(pid, SIGKILL);
}
bool MoveReplayFile(const char* lpExistingFileName, const char* lpNewFileName)
{
// todo
throw "MoveFile is not implemented for linux yet.";
}
void KillBotProcess(void *ProcessStruct);
{
// This needs to be implemented
}
#endif | #if defined(__unix__) || defined(__APPLE__)
#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include "Types.h"
#include "Tools.h"
void StartBotProcess(const BotConfig &Agent, const std::string& CommandLine, void **ProcessId)
{
FILE* pipe = popen(CommandLine.c_str(), "r");
if (!pipe)
{
std::cerr << "Can't launch command '" <<
CommandLine << "'" << std::endl;
return;
}
*ProcessId = pipe;
int returnCode = pclose(pipe);
if (returnCode != 0)
{
std::cerr << "Failed to finish command '" <<
CommandLine << "', code: " << returnCode << std::endl;
}
}
void SleepFor(int seconds)
{
sleep(seconds);
}
void KillSc2Process(unsigned long pid)
{
kill(pid, SIGKILL);
}
bool MoveReplayFile(const char* lpExistingFileName, const char* lpNewFileName)
{
// todo
throw "MoveFile is not implemented for linux yet.";
}
void KillBotProcess(void *ProcessStruct);
{
// This needs to be implemented
}
#endif |
Fix weird undefined reference to HookNative (GCC 4.5.2) | // Copyright (c) 2011 Zeex
//
// 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 <cstring>
#include "hooknative.h"
AMX_NATIVE HookNative(AMX *amx, const char *nativeName, AMX_NATIVE native) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);
int numberOfNatives;
amx_NumNatives(amx, &numberOfNatives);
for (int i = 0; i < numberOfNatives; i++) {
char *currentName = reinterpret_cast<char*>(amx->base + natives[i].nameofs);
if (std::strcmp(currentName, nativeName) == 0) {
cell address = natives[i].address;
natives[i].address = reinterpret_cast<cell>(native);
return reinterpret_cast<AMX_NATIVE>(address);
}
}
return 0;
}
| // Copyright (c) 2011 Zeex
//
// 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 <cstring>
AMX_NATIVE HookNative(AMX *amx, const char *nativeName, AMX_NATIVE native) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);
int numberOfNatives;
amx_NumNatives(amx, &numberOfNatives);
for (int i = 0; i < numberOfNatives; i++) {
char *currentName = reinterpret_cast<char*>(amx->base + natives[i].nameofs);
if (std::strcmp(currentName, nativeName) == 0) {
cell address = natives[i].address;
natives[i].address = reinterpret_cast<cell>(native);
return reinterpret_cast<AMX_NATIVE>(address);
}
}
return 0;
}
|
Add further note to future self. | //
// SNA.cpp
// Clock Signal
//
// Created by Thomas Harte on 24/04/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "SNA.hpp"
using namespace Storage::State;
std::unique_ptr<Analyser::Static::Target> SNA::load(const std::string &file_name) {
// 0x1a byte header:
//
// 00 I
// 01 HL'
// 03 DE'
// 05 BC'
// 07 AF'
// 09 HL
// 0B DE
// 0D BC
// 0F IY
// 11 IX
// 13 IFF2 (in bit 2)
// 14 R
// 15 AF
// 17 SP
// 19 interrupt mode
// 1A border colour
// 1B– 48kb RAM contents
(void)file_name;
return nullptr;
}
| //
// SNA.cpp
// Clock Signal
//
// Created by Thomas Harte on 24/04/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "SNA.hpp"
using namespace Storage::State;
std::unique_ptr<Analyser::Static::Target> SNA::load(const std::string &file_name) {
// 0x1a byte header:
//
// 00 I
// 01 HL'
// 03 DE'
// 05 BC'
// 07 AF'
// 09 HL
// 0B DE
// 0D BC
// 0F IY
// 11 IX
// 13 IFF2 (in bit 2)
// 14 R
// 15 AF
// 17 SP
// 19 interrupt mode
// 1A border colour
// 1B– 48kb RAM contents
//
// (perform a POP to get the PC)
(void)file_name;
return nullptr;
}
|
Add missing call to begin() for MCP3208 object | /*
High_Temp.cpp
2014 Copyright (c) Seeed Technology Inc. All right reserved.
Loovee
2013-4-14
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include "High_Temp_MCP320x.h"
HighTempMCP320x::HighTempMCP320x(int _spiCS, int _pinTmp, int _pinThmc) : HighTemp(_pinTmp, _pinThmc)
{
spiChipSelect = _spiCS;
adc = MCP3208(spiChipSelect);
}
int HighTempMCP320x::getAnalog(int pin)
{
return adc.analogRead(pin);
}
| /*
High_Temp.cpp
2014 Copyright (c) Seeed Technology Inc. All right reserved.
Loovee
2013-4-14
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include "High_Temp_MCP320x.h"
HighTempMCP320x::HighTempMCP320x(int _spiCS, int _pinTmp, int _pinThmc) : HighTemp(_pinTmp, _pinThmc)
{
adc = MCP3208(_spiCS);
adc.begin();
}
int HighTempMCP320x::getAnalog(int pin)
{
return adc.analogRead(pin);
}
|
Write quaternion components instead of Euler angles | // Based on Euler.ino example
#include "NAxisMotion.h"
NAxisMotion imu;
unsigned long prevTime = 0;
const int streamPeriod = 20; // ms
void setup()
{
Serial.begin(115200);
I2C.begin();
imu.initSensor(); // I2C Address can be changed here if needed
imu.setOperationMode(OPERATION_MODE_NDOF);
// Default update mode is AUTO.
// MANUAL requires calling update functions prior to calling the read functions
// Setting to MANUAL requires fewer reads to the sensor
imu.setUpdateMode(MANUAL);
}
void loop()
{
if ((millis() - prevTime) >= streamPeriod)
{
prevTime = millis();
imu.updateEuler(); // Update the Euler data into the structure of the object
imu.updateCalibStatus(); // Update the Calibration Status
Serial.print("Time:");
Serial.print(prevTime); // ms
Serial.print(",H:");
Serial.print(imu.readEulerHeading()); // deg
Serial.print(",R:");
Serial.print(imu.readEulerRoll()); // deg
Serial.print(",P:");
Serial.print(imu.readEulerPitch()); // deg
// Calib status values range from 0 - 3
Serial.print(",A:");
Serial.print(imu.readAccelCalibStatus());
Serial.print(",M:");
Serial.print(imu.readMagCalibStatus());
Serial.print(",G:");
Serial.print(imu.readGyroCalibStatus());
Serial.print(",S:");
Serial.print(imu.readSystemCalibStatus());
Serial.println();
}
} |
#include "NAxisMotion.h"
NAxisMotion imu;
unsigned long prevTime = 0;
const int streamPeriod = 20; // ms
void setup()
{
Serial.begin(115200);
I2C.begin();
imu.initSensor(); // I2C Address can be changed here if needed
imu.setOperationMode(OPERATION_MODE_NDOF);
imu.setUpdateMode(MANUAL);
}
void loop()
{
if ((millis() - prevTime) >= streamPeriod)
{
prevTime = millis();
imu.updateQuat();
imu.updateCalibStatus();
Serial.print("Time:");
Serial.print(prevTime); // ms
// Quaternion values
Serial.print(",qw:");
Serial.print(imu.readQuatW());
Serial.print(",qx:");
Serial.print(imu.readQuatX());
Serial.print(",qy:");
Serial.print(imu.readQuatY());
Serial.print(",qz:");
Serial.print(imu.readQuatZ());
// Calib status values range from 0 - 3
Serial.print(",A:");
Serial.print(imu.readAccelCalibStatus());
Serial.print(",M:");
Serial.print(imu.readMagCalibStatus());
Serial.print(",G:");
Serial.print(imu.readGyroCalibStatus());
Serial.print(",S:");
Serial.print(imu.readSystemCalibStatus());
Serial.println();
}
} |
Check the output of this test. | // RUN: %clang_cc1 %s -emit-llvm-only -verify
// PR7291
struct Foo {
unsigned file_id;
Foo(unsigned arg);
};
Foo::Foo(unsigned arg) : file_id(arg = 42)
{ }
| // RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s
// PR7291
struct Foo {
unsigned file_id;
Foo(unsigned arg);
};
Foo::Foo(unsigned arg) : file_id(arg = 42)
{ }
// CHECK: define void @_ZN3FooC2Ej
// CHECK: [[ARG:%.*]] = alloca i32
// CHECK: store i32 42, i32* [[ARG]]
// CHECK: [[ARGVAL:%.*]] = load i32* [[ARG]]
// CHECK: store i32 [[ARGVAL]], i32* %{{.*}}
// CHECK: ret void
|
Fix bug in test; found by AddressSanitizer | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <random>
// template<class RealType = double>
// class piecewise_linear_distribution
// template <class charT, class traits>
// basic_ostream<charT, traits>&
// operator<<(basic_ostream<charT, traits>& os,
// const piecewise_linear_distribution& x);
//
// template <class charT, class traits>
// basic_istream<charT, traits>&
// operator>>(basic_istream<charT, traits>& is,
// piecewise_linear_distribution& x);
#include <random>
#include <sstream>
#include <cassert>
int main()
{
{
typedef std::piecewise_linear_distribution<> D;
double b[] = {10, 14, 16, 17};
double p[] = {25, 62.5, 12.5, 25};
const size_t Np = sizeof(p) / sizeof(p[0]);
D d1(b, b+Np+1, p);
std::ostringstream os;
os << d1;
std::istringstream is(os.str());
D d2;
is >> d2;
assert(d1 == d2);
}
}
| //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <random>
// template<class RealType = double>
// class piecewise_linear_distribution
// template <class charT, class traits>
// basic_ostream<charT, traits>&
// operator<<(basic_ostream<charT, traits>& os,
// const piecewise_linear_distribution& x);
//
// template <class charT, class traits>
// basic_istream<charT, traits>&
// operator>>(basic_istream<charT, traits>& is,
// piecewise_linear_distribution& x);
#include <random>
#include <sstream>
#include <cassert>
int main()
{
{
typedef std::piecewise_linear_distribution<> D;
double b[] = {10, 14, 16, 17};
double p[] = {25, 62.5, 12.5, 25};
const size_t Np = sizeof(p) / sizeof(p[0]);
D d1(b, b+Np, p);
std::ostringstream os;
os << d1;
std::istringstream is(os.str());
D d2;
is >> d2;
assert(d1 == d2);
}
}
|
Replace malloc / free by new / delete for MICROFEATURE | /******************************************************************************
** Filename: mfdefs.cpp
** Purpose: Basic routines for manipulating micro-features
** Author: Dan Johnson
**
** (c) Copyright Hewlett-Packard Company, 1988.
** 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 "mfdefs.h"
#include <cmath>
namespace tesseract {
/*----------------------------------------------------------------------------
Public Code
----------------------------------------------------------------------------**/
/**
* This routine allocates and returns a new micro-feature
* data structure.
* @return New MICROFEATURE
*/
MICROFEATURE NewMicroFeature() {
return (static_cast<MICROFEATURE>(malloc(sizeof(MFBLOCK))));
} /* NewMicroFeature */
/**
* This routine deallocates all of the memory consumed by
* a list of micro-features.
* @param MicroFeatures list of micro-features to be freed
*/
void FreeMicroFeatures(MICROFEATURES MicroFeatures) {
destroy_nodes(MicroFeatures, free);
} /* FreeMicroFeatures */
} // namespace tesseract
| /******************************************************************************
** Filename: mfdefs.cpp
** Purpose: Basic routines for manipulating micro-features
** Author: Dan Johnson
**
** (c) Copyright Hewlett-Packard Company, 1988.
** 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 "mfdefs.h"
#include <cmath>
namespace tesseract {
/*----------------------------------------------------------------------------
Public Code
----------------------------------------------------------------------------**/
/**
* This routine allocates and returns a new micro-feature
* data structure.
* @return New MICROFEATURE
*/
MICROFEATURE NewMicroFeature() {
return new MFBLOCK;
} /* NewMicroFeature */
/**
* This routine deallocates all of the memory consumed by
* a list of micro-features.
* @param MicroFeatures list of micro-features to be freed
*/
void FreeMicroFeatures(MICROFEATURES MicroFeatures) {
auto list = MicroFeatures;
while (list != NIL_LIST) {
delete first_node(list);
list = pop(list);
}
} /* FreeMicroFeatures */
} // namespace tesseract
|
Update : make the updates.enabled switch usefull | /*
* File: NetworkThread.cpp
* Author: matthieu
*
* Created on 6 février 2015, 11:40
*/
#include "NetworkThread.h"
#include "RecalboxSystem.h"
#include "guis/GuiMsgBox.h"
NetworkThread::NetworkThread(Window* window) : mWindow(window){
// creer le thread
mFirstRun = true;
mRunning = true;
mThreadHandle = new boost::thread(boost::bind(&NetworkThread::run, this));
}
NetworkThread::~NetworkThread() {
mThreadHandle->join();
}
void NetworkThread::run(){
while(mRunning){
if(mFirstRun){
boost::this_thread::sleep(boost::posix_time::seconds(15));
mFirstRun = false;
}else {
boost::this_thread::sleep(boost::posix_time::hours(1));
}
if(RecalboxSystem::getInstance()->canUpdate()){
if(RecalboxSystem::getInstance()->canUpdate()){
mWindow->displayMessage("AN UPDATE IS AVAILABLE FOR YOUR RECALBOX");
mRunning = false;
}
}
}
}
| /*
* File: NetworkThread.cpp
* Author: matthieu
*
* Created on 6 février 2015, 11:40
*/
#include "NetworkThread.h"
#include "RecalboxSystem.h"
#include "guis/GuiMsgBox.h"
NetworkThread::NetworkThread(Window* window) : mWindow(window){
// creer le thread
mFirstRun = true;
mRunning = true;
mThreadHandle = new boost::thread(boost::bind(&NetworkThread::run, this));
}
NetworkThread::~NetworkThread() {
mThreadHandle->join();
}
void NetworkThread::run(){
while(mRunning){
if(mFirstRun){
boost::this_thread::sleep(boost::posix_time::seconds(15));
mFirstRun = false;
}else {
boost::this_thread::sleep(boost::posix_time::hours(1));
}
if(RecalboxConf::getInstance()->get("updates.enabled") == "1") {
if(RecalboxSystem::getInstance()->canUpdate()){
mWindow->displayMessage("AN UPDATE IS AVAILABLE FOR YOUR RECALBOX");
mRunning = false;
}
}
}
}
|
Adjust tap throttle max persistence queue size up to 500k | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include "tapthrottle.hh"
const size_t MINIMUM_SPACE(1024 * 1024);
const size_t MAXIMUM_QUEUE(100000);
bool TapThrottle::persistenceQueueSmallEnough() const {
size_t queueSize = stats.queue_size.get() + stats.flusher_todo.get();
return queueSize < MAXIMUM_QUEUE;
}
bool TapThrottle::hasSomeMemory() const {
size_t currentSize = stats.currentSize.get() + stats.memOverhead.get();
size_t maxSize = stats.maxDataSize.get();
return currentSize < maxSize && (maxSize - currentSize) > MINIMUM_SPACE;
}
bool TapThrottle::shouldProcess() const {
return persistenceQueueSmallEnough() && hasSomeMemory();
}
| /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include "tapthrottle.hh"
const size_t MINIMUM_SPACE(1024 * 1024);
const size_t MAXIMUM_QUEUE(500000);
bool TapThrottle::persistenceQueueSmallEnough() const {
size_t queueSize = stats.queue_size.get() + stats.flusher_todo.get();
return queueSize < MAXIMUM_QUEUE;
}
bool TapThrottle::hasSomeMemory() const {
size_t currentSize = stats.currentSize.get() + stats.memOverhead.get();
size_t maxSize = stats.maxDataSize.get();
return currentSize < maxSize && (maxSize - currentSize) > MINIMUM_SPACE;
}
bool TapThrottle::shouldProcess() const {
return persistenceQueueSmallEnough() && hasSomeMemory();
}
|
Add sleep in WebSocket poll | #include "WebSocketWrapper.hpp"
#include <iostream>
using namespace rtcdcpp;
WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }
WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }
bool WebSocketWrapper::Initialize() {
this->ws = WebSocket::from_url(this->url);
return this->ws ? true : false;
}
void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }
void WebSocketWrapper::Start() {
this->stopping = false;
this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}
void WebSocketWrapper::Loop() {
while (!this->stopping) {
this->ws->poll();
if (!this->send_queue.empty()) {
ChunkPtr chunk = this->send_queue.wait_and_pop();
std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
this->ws->send(msg);
this->ws->poll();
}
this->ws->dispatch(this->onMessage);
}
}
void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }
void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }
| #include "WebSocketWrapper.hpp"
#include <thread>
#include <iostream>
using namespace rtcdcpp;
WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }
WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }
bool WebSocketWrapper::Initialize() {
this->ws = WebSocket::from_url(this->url);
return this->ws ? true : false;
}
void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }
void WebSocketWrapper::Start() {
this->stopping = false;
this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}
void WebSocketWrapper::Loop() {
while (!this->stopping) {
this->ws->poll();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (!this->send_queue.empty()) {
ChunkPtr chunk = this->send_queue.wait_and_pop();
std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
this->ws->send(msg);
this->ws->poll();
}
this->ws->dispatch(this->onMessage);
}
}
void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }
void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }
|
Add a TODO to not forget some tasks | #define SOFA_COMPONENT_COLLISION_CYLINDERMODEL_CPP
#include "CylinderModel.inl"
namespace sofa
{
namespace component
{
namespace collision
{
using namespace sofa::defaulttype;
using namespace sofa::core::collision;
using namespace helper;
SOFA_DECL_CLASS(Cylinder)
int RigidCylinderModelClass = core::RegisterObject("Collision model which represents a set of rigid cylinders")
#ifndef SOFA_FLOAT
.add< TCylinderModel<defaulttype::Rigid3dTypes> >()
#endif
#ifndef SOFA_DOUBLE
.add < TCylinderModel<defaulttype::Rigid3fTypes> >()
#endif
.addAlias("Cylinder")
.addAlias("CylinderModel")
//.addAlias("CylinderMesh")
//.addAlias("CylinderSet")
;
#ifndef SOFA_FLOAT
template class SOFA_BASE_COLLISION_API TCylinder<defaulttype::Rigid3dTypes>;
template class SOFA_BASE_COLLISION_API TCylinderModel<defaulttype::Rigid3dTypes>;
#endif
#ifndef SOFA_DOUBLE
template class SOFA_BASE_COLLISION_API TCylinder<defaulttype::Rigid3fTypes>;
template class SOFA_BASE_COLLISION_API TCylinderModel<defaulttype::Rigid3fTypes>;
#endif
}
}
}
| #define SOFA_COMPONENT_COLLISION_CYLINDERMODEL_CPP
#include "CylinderModel.inl"
namespace sofa
{
namespace component
{
namespace collision
{
using namespace sofa::defaulttype;
using namespace sofa::core::collision;
using namespace helper;
SOFA_DECL_CLASS(Cylinder)
int RigidCylinderModelClass = core::RegisterObject("Collision model which represents a set of rigid cylinders")
#ifndef SOFA_FLOAT
.add< TCylinderModel<defaulttype::Rigid3dTypes> >()
#endif
#ifndef SOFA_DOUBLE
.add < TCylinderModel<defaulttype::Rigid3fTypes> >()
#endif
//TODO(dmarchal): Fix deprecated management...
.addAlias("Cylinder")
.addAlias("CylinderModel")
//.addAlias("CylinderMesh")
//.addAlias("CylinderSet")
;
#ifndef SOFA_FLOAT
template class SOFA_BASE_COLLISION_API TCylinder<defaulttype::Rigid3dTypes>;
template class SOFA_BASE_COLLISION_API TCylinderModel<defaulttype::Rigid3dTypes>;
#endif
#ifndef SOFA_DOUBLE
template class SOFA_BASE_COLLISION_API TCylinder<defaulttype::Rigid3fTypes>;
template class SOFA_BASE_COLLISION_API TCylinderModel<defaulttype::Rigid3fTypes>;
#endif
}
}
}
|
Use the Fusion Qt Style on OS X | #include "Server.h"
#include "IgnoreDebugOutput.h"
#include "StdinNotifier.h"
#include <QApplication>
#include <iostream>
#ifdef Q_OS_UNIX
#include <unistd.h>
#endif
int main(int argc, char **argv) {
#ifdef Q_OS_UNIX
if (setpgid(0, 0) < 0) {
std::cerr << "Unable to set new process group." << std::endl;
return 1;
}
#endif
QApplication app(argc, argv);
app.setApplicationName("capybara-webkit");
app.setOrganizationName("thoughtbot, inc");
app.setOrganizationDomain("thoughtbot.com");
StdinNotifier notifier;
QObject::connect(¬ifier, SIGNAL(eof()), &app, SLOT(quit()));
ignoreDebugOutput();
Server server(0);
if (server.start()) {
std::cout << "Capybara-webkit server started, listening on port: " << server.server_port() << std::endl;
return app.exec();
} else {
std::cerr << "Couldn't start capybara-webkit server" << std::endl;
return 1;
}
}
| #include "Server.h"
#include "IgnoreDebugOutput.h"
#include "StdinNotifier.h"
#include <QApplication>
#include <iostream>
#ifdef Q_OS_UNIX
#include <unistd.h>
#endif
int main(int argc, char **argv) {
#ifdef Q_OS_UNIX
if (setpgid(0, 0) < 0) {
std::cerr << "Unable to set new process group." << std::endl;
return 1;
}
#endif
#ifdef Q_OS_MAC
QApplication::setStyle(QStyleFactory::create("Fusion"));
#endif
QApplication app(argc, argv);
app.setApplicationName("capybara-webkit");
app.setOrganizationName("thoughtbot, inc");
app.setOrganizationDomain("thoughtbot.com");
StdinNotifier notifier;
QObject::connect(¬ifier, SIGNAL(eof()), &app, SLOT(quit()));
ignoreDebugOutput();
Server server(0);
if (server.start()) {
std::cout << "Capybara-webkit server started, listening on port: " << server.server_port() << std::endl;
return app.exec();
} else {
std::cerr << "Couldn't start capybara-webkit server" << std::endl;
return 1;
}
}
|
Use QScopedPointer instead of std::auto_ptr, per Daniel's request | #include <QtCore/QSettings>
#include <QtCore/QVariant>
#include <QtGui/QApplication>
#include <QtGui/QFont>
#include <memory>
extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}
#include "DactMainWindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSettings settings("RUG", "Dact");
QVariant fontValue = settings.value("appFont", qApp->font().toString());
QFont appFont;
appFont.fromString(fontValue.toString());
qApp->setFont(appFont);
xmlInitMemory();
xmlInitParser();
// EXSLT extensions
exsltRegisterAll();
// XPath
xmlXPathInit();
std::auto_ptr<DactMainWindow> w(new DactMainWindow);
w->show();
if (qApp->arguments().size() == 2)
w->readCorpus(qApp->arguments().at(1));
int r = a.exec();
xsltCleanupGlobals();
xmlCleanupParser();
return r;
}
| #include <QtCore/QSettings>
#include <QtCore/QVariant>
#include <QtGui/QApplication>
#include <QtGui/QFont>
#include <QScopedPointer>
extern "C" {
#include <libxslt/xslt.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libexslt/exslt.h>
}
#include "DactMainWindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSettings settings("RUG", "Dact");
QVariant fontValue = settings.value("appFont", qApp->font().toString());
QFont appFont;
appFont.fromString(fontValue.toString());
qApp->setFont(appFont);
xmlInitMemory();
xmlInitParser();
// EXSLT extensions
exsltRegisterAll();
// XPath
xmlXPathInit();
QScopedPointer<DactMainWindow> w(new DactMainWindow);
w->show();
if (qApp->arguments().size() == 2)
w->readCorpus(qApp->arguments().at(1));
int r = a.exec();
xsltCleanupGlobals();
xmlCleanupParser();
return r;
}
|
Correct syntax error in line 25 | #include<cmath>
#include<iostream>
using namespace std;
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;
}
int main(int argc, char* argv[])
{
int number;
bool result;
cout << "Enter number to test if it's prime: ";
cin >> number;
result = isPrimeBruteForce(number);
if result {
cout << number << " is a prime number.";
} else {
cout << number << " is not a prime number.";
}
return 0;
}
| #include<cmath>
#include<iostream>
using namespace std;
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;
}
int main(int argc, char* argv[])
{
int number;
bool result;
cout << "Enter number to test if it's prime: ";
cin >> number;
result = isPrimeBruteForce(number);
if (result) {
cout << number << " is a prime number.";
} else {
cout << number << " is not a prime number.";
}
return 0;
}
|
Reduce WebSocket poll delay to 50ms | #include "WebSocketWrapper.hpp"
#include <thread>
#include <iostream>
using namespace rtcdcpp;
WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }
WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }
bool WebSocketWrapper::Initialize() {
this->ws = WebSocket::from_url(this->url);
return this->ws ? true : false;
}
void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }
void WebSocketWrapper::Start() {
this->stopping = false;
this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}
void WebSocketWrapper::Loop() {
while (!this->stopping) {
this->ws->poll();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (!this->send_queue.empty()) {
ChunkPtr chunk = this->send_queue.wait_and_pop();
std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
this->ws->send(msg);
this->ws->poll();
}
this->ws->dispatch(this->onMessage);
}
}
void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }
void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }
| #include "WebSocketWrapper.hpp"
#include <thread>
#include <iostream>
using namespace rtcdcpp;
WebSocketWrapper::WebSocketWrapper(std::string url) : url(url), send_queue() { ; }
WebSocketWrapper::~WebSocketWrapper() { delete this->ws; }
bool WebSocketWrapper::Initialize() {
this->ws = WebSocket::from_url(this->url);
return this->ws ? true : false;
}
void WebSocketWrapper::SetOnMessage(std::function<void(std::string)> onMessage) { this->onMessage = onMessage; }
void WebSocketWrapper::Start() {
this->stopping = false;
this->send_loop = std::thread(&WebSocketWrapper::Loop, this);
}
void WebSocketWrapper::Loop() {
while (!this->stopping) {
this->ws->poll();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
if (!this->send_queue.empty()) {
ChunkPtr chunk = this->send_queue.wait_and_pop();
std::string msg(reinterpret_cast<char const*>(chunk->Data()), chunk->Length());
this->ws->send(msg);
this->ws->poll();
}
this->ws->dispatch(this->onMessage);
}
}
void WebSocketWrapper::Send(std::string msg) { this->send_queue.push(std::shared_ptr<Chunk>(new Chunk((const void*)msg.c_str(), msg.length()))); }
void WebSocketWrapper::Close() { this->stopping = true; this->send_loop.join(); }
|
Add simple C++ stub for testing protobuf definitions | #include <iostream>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/util/json_util.h"
#include "src/protobuf/test.pb.h"
int main() {
// verify link and compile versions are the same
GOOGLE_PROTOBUF_VERIFY_VERSION;
// testing absl
std::cout << absl::StrCat("Hello ", "World!") << std::endl;
TestMessage test_message;
test_message.set_value(10);
test_message.set_name("My String");
// as a string
std::cout << "String debug:" << std::endl;
std::cout << test_message.DebugString() << std::endl;
// as JSON
std::string json_output;
google::protobuf::util::MessageToJsonString(test_message, &json_output);
std::cout << "JSON:" << std::endl;
std::cout << json_output << std::endl << std::endl;
// parsing JSON
TestMessage test_message_2;
google::protobuf::util::JsonStringToMessage(
"{\"value\":1, \"name\": \"Testing\" }",
&test_message_2);
std::cout << "Debug Reading:" << std::endl;
std::cout << test_message_2.DebugString() << std::endl;
return 0;
};
| #include <iostream>
#include <string>
// #include "absl/strings/str_cat.h"
// #include "absl/strings/string_view.h"
#include "google/protobuf/util/json_util.h"
#include "src/protobuf/bmv2/program.pb.h"
void ReadStdin(std::string& str) {
std::istreambuf_iterator<char> cin_iterator{std::cin};
std::istreambuf_iterator<char> end;
str = std::string(cin_iterator, end);
}
int main() {
// verify link and compile versions are the same
GOOGLE_PROTOBUF_VERIFY_VERSION;
std::string input;
ReadStdin(input);
// testing absl
// std::cout << absl::StrCat("Hello ", "World!") << std::endl;
// parsing JSON
P4Program program;
google::protobuf::util::JsonParseOptions parsing_options;
parsing_options.ignore_unknown_fields = true;
google::protobuf::util::JsonStringToMessage(input, &program, parsing_options);
// printing JSON
google::protobuf::util::JsonPrintOptions dumping_options;
dumping_options.add_whitespace = true;
dumping_options.always_print_primitive_fields = true;
dumping_options.preserve_proto_field_names = true;
std::string output;
google::protobuf::util::MessageToJsonString(program, &output, dumping_options);
std::cout << output << std::endl;
return 0;
};
|
Add missing header file for Ubuntu Jaunty and beyond | /*
* BasicLayout.cpp
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "PortabilityImpl.hh"
#include <log4cpp/BasicLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/FactoryParams.hh>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#endif
namespace log4cpp {
BasicLayout::BasicLayout() {
}
BasicLayout::~BasicLayout() {
}
std::string BasicLayout::format(const LoggingEvent& event) {
std::ostringstream message;
const std::string& priorityName = Priority::getPriorityName(event.priority);
message << event.timeStamp.getSeconds() << " " << priorityName << " "
<< event.categoryName << " " << event.ndc << ": "
<< event.message << std::endl;
return message.str();
}
std::auto_ptr<Layout> create_basic_layout(const FactoryParams& params)
{
return std::auto_ptr<Layout>(new BasicLayout);
}
}
| /*
* BasicLayout.cpp
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "PortabilityImpl.hh"
#include <log4cpp/BasicLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/FactoryParams.hh>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#endif
#include <memory>
namespace log4cpp {
BasicLayout::BasicLayout() {
}
BasicLayout::~BasicLayout() {
}
std::string BasicLayout::format(const LoggingEvent& event) {
std::ostringstream message;
const std::string& priorityName = Priority::getPriorityName(event.priority);
message << event.timeStamp.getSeconds() << " " << priorityName << " "
<< event.categoryName << " " << event.ndc << ": "
<< event.message << std::endl;
return message.str();
}
std::auto_ptr<Layout> create_basic_layout(const FactoryParams& params)
{
return std::auto_ptr<Layout>(new BasicLayout);
}
}
|
Use Parser module to parse a file | #include "Interpreter.hpp"
#include "modules/error-handler/ErrorHandler.hpp"
#include "modules/lexer/Lexer.hpp"
#include <iostream>
using Interpreter = tkom::Interpreter;
using ErrorHandler = tkom::modules::ErrorHandler;
using Lexer = tkom::modules::Lexer;
Interpreter::Interpreter(const std::vector<std::string>& arguments)
{
try
{
if (arguments.size() < 1)
{
ErrorHandler::error("No input file specified");
}
Lexer lexer(arguments.at(0));
Token token;
do
{
token = lexer.nextToken();
std::cout << tkom::modules::utils::getTokenTypeName(token.type) << " = " << token.value << std::endl;
}
while(token.type != TokenType::Invalid && token.type != TokenType::EndOfFile);
}
catch(ErrorHandler::Exception &e)
{
ErrorHandler::error("Terminating...", true);
}
}
| #include "Interpreter.hpp"
#include "modules/error-handler/ErrorHandler.hpp"
#include "modules/lexer/Lexer.hpp"
#include "modules/parser/Parser.hpp"
using Interpreter = tkom::Interpreter;
using ErrorHandler = tkom::modules::ErrorHandler;
using Lexer = tkom::modules::Lexer;
using Parser = tkom::modules::Parser;
Interpreter::Interpreter(const std::vector<std::string>& arguments)
{
try
{
if (arguments.size() < 1)
{
ErrorHandler::error("No input file specified");
}
Lexer lexer(arguments.at(0));
Parser parser(lexer);
parser.parse();
}
catch(ErrorHandler::Exception &e)
{
ErrorHandler::error("Terminating...", true);
}
}
|
Mark ExtensionApiTest.Popup as FLAKY, it is still flaky. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
// Flaky, http://crbug.com/46601.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}
|
Set mobile=true when calling setDeviceMetricsOverride | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chromedriver/chrome/device_metrics.h"
DeviceMetrics::DeviceMetrics(int width, int height, double device_scale_factor)
: width(width),
height(height),
device_scale_factor(device_scale_factor),
mobile(false),
fit_window(false),
text_autosizing(true),
font_scale_factor(1) {}
DeviceMetrics::~DeviceMetrics() {}
| // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chromedriver/chrome/device_metrics.h"
DeviceMetrics::DeviceMetrics(int width, int height, double device_scale_factor)
: width(width),
height(height),
device_scale_factor(device_scale_factor),
mobile(true),
fit_window(false),
text_autosizing(true),
font_scale_factor(1) {}
DeviceMetrics::~DeviceMetrics() {}
|
Add flushes to try to fix test | // RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: env ASAN_OPTIONS=handle_segv=0 %run %t 2>&1 | FileCheck %s --check-prefix=USER
// RUN: env ASAN_OPTIONS=handle_segv=1 not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN
// Test the default.
// RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN
// This test exits zero when its unhandled exception filter is set. ASan should
// not disturb it when handle_segv=0.
// USER: in main
// USER: in SEHHandler
// ASAN: in main
// ASAN: ERROR: AddressSanitizer: access-violation
#include <windows.h>
#include <stdio.h>
static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
DWORD exception_code = info->ExceptionRecord->ExceptionCode;
if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
fprintf(stderr, "in SEHHandler\n");
fflush(stdout);
TerminateProcess(GetCurrentProcess(), 0);
}
return EXCEPTION_CONTINUE_SEARCH;
}
int main() {
SetUnhandledExceptionFilter(SEHHandler);
fprintf(stderr, "in main\n");
volatile int *p = nullptr;
*p = 42;
}
| // RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: env ASAN_OPTIONS=handle_segv=0 %run %t 2>&1 | FileCheck %s --check-prefix=USER
// RUN: env ASAN_OPTIONS=handle_segv=1 not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN
// Test the default.
// RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN
// This test exits zero when its unhandled exception filter is set. ASan should
// not disturb it when handle_segv=0.
// USER: in main
// USER: in SEHHandler
// ASAN: in main
// ASAN: ERROR: AddressSanitizer: access-violation
#include <windows.h>
#include <stdio.h>
static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
DWORD exception_code = info->ExceptionRecord->ExceptionCode;
if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
fprintf(stderr, "in SEHHandler\n");
fflush(stderr);
TerminateProcess(GetCurrentProcess(), 0);
}
return EXCEPTION_CONTINUE_SEARCH;
}
int main() {
SetUnhandledExceptionFilter(SEHHandler);
fprintf(stderr, "in main\n");
fflush(stderr);
volatile int *p = nullptr;
*p = 42;
}
|
Add test for Example 1. | #define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE flatten_tests
#include <boost/test/unit_test.hpp>
#include "flatten/flatten.hpp"
BOOST_AUTO_TEST_CASE(flatten_tests)
{
}
| #define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE flatten_tests
#include <boost/test/unit_test.hpp>
#include <list>
#include <vector>
#include <map>
#include "flatten/flatten.hpp"
typedef std::vector<int> IntList;
typedef std::vector<IntList> IntListList;
typedef std::vector<IntListList> IntListListList;
IntListListList example1_values()
{
IntListListList values;
IntListList a;
IntList a1;
IntList a2;
IntList a3;
IntListList b;
IntList b1;
IntList b2;
IntList b3;
a1.push_back(1);
a1.push_back(2);
a1.push_back(3);
a2.push_back(4);
a2.push_back(5);
a2.push_back(6);
/* a3 empty */
b1.push_back(7);
b2.push_back(8);
b3.push_back(9);
a.push_back(a1);
a.push_back(a2);
a.push_back(a3);
b.push_back(b1);
b.push_back(b2);
b.push_back(b3);
values.push_back(a);
values.push_back(b);
return values;
}
BOOST_AUTO_TEST_CASE(example1)
{
IntListListList values = example1_values();
IntList result;
flatten::flatten<int>(
values.begin(), values.end(), std::back_inserter(result)
);
for (int i = 0; i < 9; ++i)
{
BOOST_REQUIRE(i < result.size());
BOOST_CHECK_EQUAL(result[i], i + 1);
}
}
|
Remove inclusion of unversioned header. | // ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// 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 <gtest/gtest.h>
#include <DO/Defines.hpp>
#include <DO/ImageProcessing/Deriche.hpp>
#include "utilities.hpp"
using namespace std;
using namespace DO;
TEST(TestDericheFilter, test_inplace_deriche_blur)
{
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | // ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// 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 <gtest/gtest.h>
#include <DO/Defines.hpp>
#include <DO/ImageProcessing/Deriche.hpp>
using namespace std;
using namespace DO;
TEST(TestDericheFilter, test_inplace_deriche_blur)
{
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} |
Add basic config file support | #include <iostream>
#include <cstdlib>
#include "NTClient.h"
using namespace std;
void initBot() {
NTClient nclient = NTClient(20, 0.89);
nclient.login("sascf3", "123asd123"); // Throw-away account
nclient.connect();
}
int main(int argc, char** argv) {
srand(static_cast<unsigned int>(time(0)));
initBot();
return 0;
} | #include <iostream>
#include <cstdlib>
#include <fstream>
#include "NTClient.h"
#include "colors.h"
#include "json.hpp"
using namespace std;
void initBot(string username, string password, int wpm, double acc) {
NTClient nclient = NTClient(wpm, acc);
nclient.login(username, password);
nclient.connect();
}
void initlog(string msg) {
cout << CLR_GRN << STYLE_BOLD << "[INIT] " << CLR_RESET << CLR_WHT << msg << CLR_RESET;
}
void errlog(string msg) {
cout << CLR_RED << STYLE_BOLD << "[ERR!] " << CLR_RESET << CLR_WHT << msg << CLR_RESET;
}
int main(int argc, char** argv) {
srand(static_cast<unsigned int>(time(0)));
ifstream configf;
configf.exceptions(std::ios::failbit | std::ios::badbit);
try {
configf.open("config.json");
} catch(const exception& e) {
errlog("Failed to open the JSON config. For help, read the UltraType++ repository README.\n");
return 1;
}
return 0;
} |
Implement first basic black window setup without any content | #include <iostream>
int main(int argc, char** argv) {
std::cout << "Hello Lamure Virtual Texture!\n";
return 0;
}
| #include <iostream>
// scism shit
#include <scm/core.h>
#include <scm/log.h>
#include <scm/core/pointer_types.h>
#include <scm/core/io/tools.h>
#include <scm/core/time/accum_timer.h>
#include <scm/core/time/high_res_timer.h>
#include <scm/gl_core.h>
#include <scm/gl_util/data/imaging/texture_loader.h>
#include <scm/gl_util/manipulators/trackball_manipulator.h>
#include <scm/gl_util/primitives/box.h>
#include <scm/gl_util/primitives/quad.h>
#include <scm/gl_util/primitives/wavefront_obj.h>
// Window library
#include <GL/freeglut.h>
static int winx = 1600;
static int winy = 1024;
int main(int argc, char** argv) {
// init GLUT and create Window
glutInit(&argc, argv);
glutInitContextVersion (4,2);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
// set properties from window
glutCreateWindow("First test with GLUT and SCHISM");
glutInitWindowPosition(0, 0);
glutInitWindowSize(winx, winy);
// register callbacks
glutDisplayFunc(display);
// enter GLUT event processing cycle
glutMainLoop();
return 0;
} |
Change tests in JPetAnalysisTools to use double instead of int | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>
#include "../JPetAnalysisTools/JPetAnalysisTools.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}
BOOST_AUTO_TEST_SUITE_END()
| #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>
#include "../JPetAnalysisTools/JPetAnalysisTools.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
double epsilon = 0.0001;
BOOST_REQUIRE_CLOSE(results[0].getTime(), 1, epsilon );
BOOST_REQUIRE_CLOSE(results[1].getTime(), 2, epsilon );
BOOST_REQUIRE_CLOSE(results[2].getTime(), 3, epsilon );
BOOST_REQUIRE_CLOSE(results[3].getTime(), 4, epsilon );
}
BOOST_AUTO_TEST_SUITE_END()
|
Fix TSan symbol lookup on Windows | //===--- ThreadSanitizer.cpp - Thread Sanitizer support -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Thread Sanitizer support for the Swift Task runtime
//
//===----------------------------------------------------------------------===//
#include "TaskPrivate.h"
#include <dlfcn.h>
using TSanFunc = void(void *);
void swift::_swift_tsan_acquire(void *addr) {
static auto ptr = (TSanFunc *)dlsym(RTLD_DEFAULT, "__tsan_acquire");
if (ptr) {
ptr(addr);
}
}
void swift::_swift_tsan_release(void *addr) {
static auto ptr = (TSanFunc *)dlsym(RTLD_DEFAULT, "__tsan_release");
if (ptr) {
ptr(addr);
}
}
| //===--- ThreadSanitizer.cpp - Thread Sanitizer support -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Thread Sanitizer support for the Swift Task runtime
//
//===----------------------------------------------------------------------===//
#include "TaskPrivate.h"
#if defined(_WIN32)
#define NOMINMAX
#include <windows.h>
#else
#include <dlfcn.h>
#endif
using TSanFunc = void(void *);
namespace {
static TSanFunc *loadSymbol(const char *name) {
#if defined(_WIN32)
return (TSanFunc *)GetProcAddress(GetModuleHandle(NULL), name);
#else
return (TSanFunc *)dlsym(RTLD_DEFAULT, name);
#endif
}
}
void swift::_swift_tsan_acquire(void *addr) {
static auto ptr = loadSymbol("__tsan_acquire");
if (ptr) {
ptr(addr);
}
}
void swift::_swift_tsan_release(void *addr) {
static auto ptr = loadSymbol("__tsan_release");
if (ptr) {
ptr(addr);
}
}
|
Fix vexing parse in test. | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <experimental/utility>
#include <experimental/utility>
int main()
{
std::experimental::erased_type e();
}
| //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <experimental/utility>
#include <experimental/utility>
int main()
{
std::experimental::erased_type e;
}
|
Extend slider use case test | // Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/config_descriptor.h>
#include <autowiring/config.h>
#include <autowiring/ConfigRegistry.h>
#include <autowiring/observable.h>
namespace aw = autowiring;
class AutoConfig_SliderTest :
public testing::Test
{};
namespace {
struct slider {
template<typename T>
struct valid {
static const bool value = std::is_integral<T>::value;
};
};
class ClassWithASlider {
public:
std::string api_path;
int timeout;
static aw::config_descriptor GetConfigDescriptor(void) {
return{
{ "api_path", &ClassWithASlider::api_path },
{ "timeout", &ClassWithASlider::timeout, slider{} }
};
}
};
}
| // Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include <autowiring/config_descriptor.h>
#include <autowiring/config.h>
#include <autowiring/ConfigRegistry.h>
#include <autowiring/observable.h>
namespace aw = autowiring;
class AutoConfig_SliderTest :
public testing::Test
{};
namespace {
struct slider {
template<typename T>
struct valid {
static const bool value = std::is_integral<T>::value;
};
};
class ClassWithASlider {
public:
std::string api_path;
int timeout;
static aw::config_descriptor GetConfigDescriptor(void) {
return{
{ "api_path", &ClassWithASlider::api_path, slider{} },
{ "timeout", &ClassWithASlider::timeout, slider{} }
};
}
};
class SliderManager {
SliderManager(void) {
AutoCurrentContext ctxt;
ctxt->Config.When([](const aw::config_field& field, const slider&) {
});
}
};
}
TEST_F(AutoConfig_SliderTest, CanFindAllSliders) {
// Get a full list of all sliders:
}
|
Improve main declaration to include runtime start | //=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include "il/Main.hpp"
#include "AssemblyFileWriter.hpp"
using namespace eddic;
void Main::write(AssemblyFileWriter& writer){
writer.stream() << ".text" << std::endl
<< ".globl main" << std::endl
<< "\t.type main, @function" << std::endl;
}
| //=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include "il/Main.hpp"
#include "AssemblyFileWriter.hpp"
using namespace eddic;
void Main::write(AssemblyFileWriter& writer){
writer.stream() << ".text" << std::endl
<< ".globl _start" << std::endl
<< "_start:" << std::endl
<< "call main" << std::endl
<< "movl $1, %eax" << std::endl
<< "xorl %ebx, %ebx" << std::endl
<< "int $0x80" << std::endl;
}
|
Fix build when libpfm is not available. | //===-- PerfHelperTest.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PerfHelper.h"
#include "llvm/Config/config.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace exegesis {
namespace pfm {
namespace {
using ::testing::IsEmpty;
using ::testing::Not;
TEST(PerfHelperTest, FunctionalTest) {
#ifdef HAVE_LIBPFM
ASSERT_FALSE(pfmInitialize());
const PerfEvent SingleEvent("CYCLES:u");
const auto &EmptyFn = []() {};
std::string CallbackEventName;
std::string CallbackEventNameFullyQualifed;
int64_t CallbackEventCycles;
Measure(llvm::makeArrayRef(SingleEvent),
[&](const PerfEvent &Event, int64_t Value) {
CallbackEventName = Event.name();
CallbackEventNameFullyQualifed = Event.getPfmEventString();
CallbackEventCycles = Value;
},
EmptyFn);
EXPECT_EQ(CallbackEventName, "CYCLES:u");
EXPECT_THAT(CallbackEventNameFullyQualifed, Not(IsEmpty()));
pfmTerminate();
#else
ASSERT_TRUE(PfmInitialize());
#endif
}
} // namespace
} // namespace pfm
} // namespace exegesis
| //===-- PerfHelperTest.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PerfHelper.h"
#include "llvm/Config/config.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace exegesis {
namespace pfm {
namespace {
using ::testing::IsEmpty;
using ::testing::Not;
TEST(PerfHelperTest, FunctionalTest) {
#ifdef HAVE_LIBPFM
ASSERT_FALSE(pfmInitialize());
const PerfEvent SingleEvent("CYCLES:u");
const auto &EmptyFn = []() {};
std::string CallbackEventName;
std::string CallbackEventNameFullyQualifed;
int64_t CallbackEventCycles;
Measure(llvm::makeArrayRef(SingleEvent),
[&](const PerfEvent &Event, int64_t Value) {
CallbackEventName = Event.name();
CallbackEventNameFullyQualifed = Event.getPfmEventString();
CallbackEventCycles = Value;
},
EmptyFn);
EXPECT_EQ(CallbackEventName, "CYCLES:u");
EXPECT_THAT(CallbackEventNameFullyQualifed, Not(IsEmpty()));
pfmTerminate();
#else
ASSERT_TRUE(pfmInitialize());
#endif
}
} // namespace
} // namespace pfm
} // namespace exegesis
|
Enable GPU support for Zeta and Polygamma ops. | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
REGISTER2(BinaryOp, CPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, CPU, "Polygamma", functor::polygamma, float, double);
} // namespace tensorflow
| /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
REGISTER2(BinaryOp, CPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, CPU, "Polygamma", functor::polygamma, float, double);
#if GOOGLE_CUDA
REGISTER2(BinaryOp, GPU, "Zeta", functor::zeta, float, double);
REGISTER2(BinaryOp, GPU, "Polygamma", functor::polygamma, float, double);
#endif
} // namespace tensorflow
|
Support to specify single QML file by argument | #include <QApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QFile>
#include <QFileInfo>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
if (argc < 2) {
printf("Usage: OwaViewer [directory]\n");
return 1;
}
QDir dirPath(argv[1]);
QString qmlPath;
// It's a directory
if (QFileInfo(dirPath.path()).isDir()) {
// Trying to read QML file in the directory
qmlPath = dirPath.filePath("app.qml");
if (!QFile(qmlPath).exists()) {
qmlPath = dirPath.filePath("App.qml");
if (!QFile(qmlPath).exists()) {
printf("OwaNEXT Application doesn't exist.\n");
return 1;
}
}
}
engine.load(QUrl(qmlPath));
return app.exec();
}
| #include <QApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QFile>
#include <QFileInfo>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
if (argc < 2) {
printf("Usage: OwaViewer [directory]\n");
printf(" or: OwaViewer [File]\n");
return 1;
}
QDir dirPath(argv[1]);
QString qmlPath;
// It's a directory
if (QFileInfo(dirPath.path()).isDir()) {
// Trying to read QML file in the directory
qmlPath = dirPath.filePath("app.qml");
if (!QFile(qmlPath).exists()) {
qmlPath = dirPath.filePath("App.qml");
if (!QFile(qmlPath).exists()) {
printf("Cannot find application in the directory.\n");
return 1;
}
}
} else {
// Whether does the QML file exists or not?
qmlPath = dirPath.path();
if (!QFile(qmlPath).exists()) {
printf("OwaNEXT Application doesn't exist.\n");
return 1;
}
}
// Run it
engine.load(QUrl(qmlPath));
return app.exec();
}
|
Remove comment and redundant include | #include "cameras/itf/pinhole_camera.h"
#include "core/itf/film.h"
#include "core/itf/ray.h"
#include "core/itf/sampling.h"
#include <iostream>
using namespace lb;
/// Constructs a pinhole camera, where the image plane's origin is pointed to
/// the by the look at vector relative from the camera's location. Together with
/// the look at vector, the up vector defines the camera's roll, pitch, and
/// tilt. Note: up vector should be a unit vector preferably.
PinholeCamera::PinholeCamera(std::unique_ptr<Film> film,
const Point3d& location, const Vector3d& lookAt, const Vector3d& up):
Camera(std::move(film), location),
lookAt_(lookAt),
left_(-cross(lookAt, up)),
top_(cross(lookAt.normalize(), left_)),
dx_(-2 * left_ / (film_->xResolution() - 1)),
dy_(-2 * top_ / (film_->yResolution() - 1))
{
}
void PinholeCamera::calculateRay(const Sample& s, Ray& r) const
{
r.o = location_;
r.d = ((r.o + lookAt_ + left_ + s.imageX * dx_ + top_ + s.imageY * dy_) - r.o).normalize();
// std::cout << r.o << "\n";
}
| #include "cameras/itf/pinhole_camera.h"
#include "core/itf/film.h"
#include "core/itf/ray.h"
#include "core/itf/sampling.h"
using namespace lb;
/// Constructs a pinhole camera, where the image plane's origin is pointed to
/// the by the look at vector relative from the camera's location. Together with
/// the look at vector, the up vector defines the camera's roll, pitch, and
/// tilt. Note: up vector should be a unit vector preferably.
PinholeCamera::PinholeCamera(std::unique_ptr<Film> film,
const Point3d& location, const Vector3d& lookAt, const Vector3d& up):
Camera(std::move(film), location),
lookAt_(lookAt),
left_(-cross(lookAt, up)),
top_(cross(lookAt.normalize(), left_)),
dx_(-2 * left_ / (film_->xResolution() - 1)),
dy_(-2 * top_ / (film_->yResolution() - 1))
{
}
void PinholeCamera::calculateRay(const Sample& s, Ray& r) const
{
r.o = location_;
r.d = ((r.o + lookAt_ + left_ + s.imageX * dx_ + top_ + s.imageY * dy_) - r.o).normalize();
}
|
Use __SIZE_TYPE__ as suggested by dgregor. | // RUN: %clang_cc1 -fsyntax-only -verify %s
// Various tests for -fno-exceptions
typedef __typeof(sizeof(int)) size_t;
namespace test0 {
// rdar://problem/7878149
class Foo {
public:
void* operator new(size_t x);
private:
void operator delete(void *x);
};
void test() {
// Under -fexceptions, this does access control for the associated
// 'operator delete'.
(void) new Foo();
}
}
| // RUN: %clang_cc1 -fsyntax-only -verify %s
// Various tests for -fno-exceptions
typedef __SIZE_TYPE__ size_t;
namespace test0 {
// rdar://problem/7878149
class Foo {
public:
void* operator new(size_t x);
private:
void operator delete(void *x);
};
void test() {
// Under -fexceptions, this does access control for the associated
// 'operator delete'.
(void) new Foo();
}
}
|
Increase the QImageReader allocation limit. | /*
Copyright (c), Helios
All rights reserved.
Distributed under a permissive license. See COPYING.txt for details.
*/
#include "ImageViewerApplication.h"
int main(int argc, char **argv){
try{
initialize_supported_extensions();
ImageViewerApplication app(argc, argv, "BorderlessViewer" + get_per_user_unique_id());
return app.exec();
}catch (ApplicationAlreadyRunningException &){
return 0;
}catch (NoWindowsException &){
return 0;
}
}
| /*
Copyright (c), Helios
All rights reserved.
Distributed under a permissive license. See COPYING.txt for details.
*/
#include "ImageViewerApplication.h"
#include <QImageReader>
int main(int argc, char **argv){
try{
//Set the limit to 1 GiB.
QImageReader::setAllocationLimit(1024);
initialize_supported_extensions();
ImageViewerApplication app(argc, argv, "BorderlessViewer" + get_per_user_unique_id());
return app.exec();
}catch (ApplicationAlreadyRunningException &){
return 0;
}catch (NoWindowsException &){
return 0;
}
}
|
Revert SAL_N_ELEMENTS change for one file | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// SOComWindowPeer.cpp : Implementation of CHelpApp and DLL registration.
#include "stdafx2.h"
#include "so_activex.h"
#include "SOComWindowPeer.h"
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP SOComWindowPeer::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_ISOComWindowPeer,
};
for (int i=0;i<SAL_N_ELEMENTS(arr);i++)
{
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
if (InlineIsEqualGUID(*arr[i],riid))
#else
if (::ATL::InlineIsEqualGUID(*arr[i],riid))
#endif
return S_OK;
}
return S_FALSE;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// SOComWindowPeer.cpp : Implementation of CHelpApp and DLL registration.
#include "stdafx2.h"
#include "so_activex.h"
#include "SOComWindowPeer.h"
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP SOComWindowPeer::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_ISOComWindowPeer,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
if (InlineIsEqualGUID(*arr[i],riid))
#else
if (::ATL::InlineIsEqualGUID(*arr[i],riid))
#endif
return S_OK;
}
return S_FALSE;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Fix a build error when OS_CHROMEOS is not defined. | // 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/extensions/extension_input_method_api.h"
#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
GetInputMethodFunction::GetInputMethodFunction() {
}
GetInputMethodFunction::~GetInputMethodFunction() {
}
bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
NOTREACHED();
#else
chromeos::ExtensionInputMethodEventRouter* router =
profile_->GetExtensionService()->input_method_event_router();
chromeos::input_method::InputMethodManager* manager =
chromeos::input_method::InputMethodManager::GetInstance();
const std::string input_method =
router->GetInputMethodForXkb(manager->current_input_method().id());
result_.reset(Value::CreateStringValue(input_method));
return true;
#endif
}
| // 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/extensions/extension_input_method_api.h"
#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
GetInputMethodFunction::GetInputMethodFunction() {
}
GetInputMethodFunction::~GetInputMethodFunction() {
}
bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
NOTREACHED();
return false;
#else
chromeos::ExtensionInputMethodEventRouter* router =
profile_->GetExtensionService()->input_method_event_router();
chromeos::input_method::InputMethodManager* manager =
chromeos::input_method::InputMethodManager::GetInstance();
const std::string input_method =
router->GetInputMethodForXkb(manager->current_input_method().id());
result_.reset(Value::CreateStringValue(input_method));
return true;
#endif
}
|
Remove unused finder on traceroute parse command | #include <iostream>
#include <string>
#include <maproute/ip.hpp>
#include <maproute/ip_convertor.hpp>
#include <maproute/stringhelp.hpp>
#include <maproute/tr_parser.hpp>
#include <maproute/ip_location_finder.hpp>
int main() {
IPLocationFinder finder{};
while (std::cin.good()) {
std::string line;
std::string ip_string;
IPV4Convertor convertor{};
TracerouteLineParser parser{};
IPV4 ip {0, 0, 0, 0};
std::getline(std::cin, line);
bool success = parser.parse(&line, &ip);
if (!success) {
std::cerr << "Failed to parse: '"
<< line
<< "' did the request timeout?"
<< std::endl;
} else {
convertor.ip_to_string(&ip, &ip_string);
std::cout << ip_string << std::endl;
}
}
finder.close();
return 0;
}
| #include <iostream>
#include <string>
#include <maproute/ip.hpp>
#include <maproute/ip_convertor.hpp>
#include <maproute/stringhelp.hpp>
#include <maproute/tr_parser.hpp>
#include <maproute/ip_location_finder.hpp>
int main() {
while (std::cin.good()) {
std::string line;
std::string ip_string;
IPV4Convertor convertor{};
TracerouteLineParser parser{};
IPV4 ip {0, 0, 0, 0};
std::getline(std::cin, line);
bool success = parser.parse(&line, &ip);
if (!success) {
std::cerr << "Failed to parse: '"
<< line
<< "' did the request timeout?"
<< std::endl;
} else {
convertor.ip_to_string(&ip, &ip_string);
std::cout << ip_string << std::endl;
}
}
return 0;
}
|
Change print to match actual content of ka, kd, ks. | #include "material.hpp"
Material::Material():
name{},
ka{0,0,0},
kd{0,0,0},
ks{0,0,0},
m{0}
{}
Material::Material(std::string const& name, Color const& ka, Color const& kd,
Color const& ks, float m):
name{name},
ka{ka},
kd{kd},
ks{ks},
m{m}
{}
std::string const& Material::getName() const {
return name;
}
Color const& Material::getColorKa() const {
return ka;
}
Color const& Material::getColorKd() const {
return kd;
}
Color const& Material::getColorKs() const {
return ks;
}
float const Material::getM() const {
return m;
}
std::ostream& operator<<(std::ostream& os, Material const& m) {
os << "--------" << "\n" << "Material " << "\n" << "--------" << "\n"
<< "Name: " << m.getName() << "\n" << "Colors (RGB):" << "\n"
<< " ka: " << m.getColorKa() << " kd: "
<< m.getColorKd() << " ks: " << m.getColorKs()
<< "m: " << m.getM();
return os;
} | #include "material.hpp"
Material::Material():
name{},
ka{0,0,0},
kd{0,0,0},
ks{0,0,0},
m{0}
{}
Material::Material(std::string const& name, Color const& ka, Color const& kd,
Color const& ks, float m):
name{name},
ka{ka},
kd{kd},
ks{ks},
m{m}
{}
std::string const& Material::getName() const {
return name;
}
Color const& Material::getColorKa() const {
return ka;
}
Color const& Material::getColorKd() const {
return kd;
}
Color const& Material::getColorKs() const {
return ks;
}
float const Material::getM() const {
return m;
}
std::ostream& operator<<(std::ostream& os, Material const& m) {
os << "--------" << "\n" << "Material " << "\n" << "--------" << "\n"
<< "Name: " << m.getName() << "\n" << "Light coefficients:" << "\n"
<< " ka: " << m.getColorKa() << " kd: "
<< m.getColorKd() << " ks: " << m.getColorKs()
<< "m: " << m.getM();
return os;
} |
Change sanity check for perfomance test of dft | #include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
#define MAT_TYPES_DFT CV_32FC1, CV_64FC1
#define MAT_SIZES_DFT sz1080p, sz2K
#define TEST_MATS_DFT testing::Combine(testing::Values(MAT_SIZES_DFT), testing::Values(MAT_TYPES_DFT))
PERF_TEST_P(Size_MatType, dft, TEST_MATS_DFT)
{
Size sz = get<0>(GetParam());
int type = get<1>(GetParam());
Mat src(sz, type);
Mat dst(sz, type);
declare.in(src, WARMUP_RNG).time(60);
TEST_CYCLE() dft(src, dst);
SANITY_CHECK(dst, 1e-5);
}
| #include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
#define MAT_TYPES_DFT CV_32FC1, CV_64FC1
#define MAT_SIZES_DFT sz1080p, sz2K
#define TEST_MATS_DFT testing::Combine(testing::Values(MAT_SIZES_DFT), testing::Values(MAT_TYPES_DFT))
PERF_TEST_P(Size_MatType, dft, TEST_MATS_DFT)
{
Size sz = get<0>(GetParam());
int type = get<1>(GetParam());
Mat src(sz, type);
Mat dst(sz, type);
declare.in(src, WARMUP_RNG).time(60);
TEST_CYCLE() dft(src, dst);
SANITY_CHECK(dst, 1e-5, ERROR_RELATIVE);
}
|
Add test to cover unable to open file | #include "test/catch.hpp"
#include <string>
#include <vector>
#include "main/exception/FileOpenException.hpp"
#include "main/exception/InvalidArgumentException.hpp"
#include "main/MainApp.hpp"
TEST_CASE("MainApp class") {
using std::string;
using std::vector;
using pyconv::exception::FileOpenException;
using pyconv::exception::InvalidArgumentException;
using pyconv::MainApp;
SECTION("Exceptions Thrown") {
vector<string> args;
try {
MainApp mainApp(args);
} catch (InvalidArgumentException const & e) {
CHECK(e.message() == "No arguments provided");
}
args.push_back("cpp");
try {
MainApp mainApp(args);
} catch (InvalidArgumentException const & e) {
CHECK(e.message() == "Only one argument provided");
}
args[0] = "java";
args.push_back("nonexistingfolder/nonexistingfile.py");
try {
MainApp mainApp(args);
} catch (InvalidArgumentException const & e) {
CHECK(e.message() == "Invalid language type: java");
}
}
SECTION("No Exceptions Thrown") {
vector<string> args {"cpp", "./src/PyConv/test/testfiles/properFile.py"};
MainApp mainApp(args);
CHECK_NOTHROW(mainApp.run());
args[0] = "python";
mainApp = MainApp(args);
CHECK_NOTHROW(mainApp.run());
}
}
| #include "test/catch.hpp"
#include <string>
#include <vector>
#include "main/exception/FileOpenException.hpp"
#include "main/exception/InvalidArgumentException.hpp"
#include "main/MainApp.hpp"
TEST_CASE("MainApp class") {
using std::string;
using std::vector;
using pyconv::exception::FileOpenException;
using pyconv::exception::InvalidArgumentException;
using pyconv::MainApp;
SECTION("Exceptions Thrown") {
vector<string> args;
try {
MainApp mainApp(args);
} catch (InvalidArgumentException const & e) {
CHECK(e.message() == "No arguments provided");
}
args.push_back("cpp");
try {
MainApp mainApp(args);
} catch (InvalidArgumentException const & e) {
CHECK(e.message() == "Only one argument provided");
}
args[0] = "java";
args.push_back("nonexistingfolder/nonexistingfile.py");
try {
MainApp mainApp(args);
} catch (InvalidArgumentException const & e) {
CHECK(e.message() == "Invalid language type: java");
}
}
SECTION("No Exceptions Thrown") {
vector<string> args {"cpp", "./src/PyConv/test/testfiles/properFile.py"};
MainApp mainApp(args);
CHECK_NOTHROW(mainApp.run());
args[1] = "nonexistingfolder/nonexistingfile.py";
mainApp = MainApp(args);
CHECK_NOTHROW(mainApp.run());
args[0] = "python";
mainApp = MainApp(args);
CHECK_NOTHROW(mainApp.run());
}
}
|
Fix sigaction to be more portable. | /* -*- mode:linux -*- */
/**
* \file timeout.cc
*
*
*
* \author Ethan Burns
* \date 2008-12-16
*/
#include <iostream>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
void alarm_action(int sig)
{
cout << "No Solution" << endl
<< "cost: infinity" << endl
<< "length: infinity" << endl
<< "wall_time: infinity" << endl
<< "CPU_time: infinity" << endl
<< "generated: infinity" << endl
<< "expanded: infinity" << endl;
exit(EXIT_SUCCESS);
}
void timeout(unsigned int sec)
{
struct sigaction sa;
sa.sa_flags = 0;
sa.sa_sigaction = NULL;
sa.sa_restorer = NULL;
sa.sa_handler = alarm_action;
sigfillset(&sa.sa_mask);
sigaction(SIGALRM, &sa, NULL);
alarm(sec);
}
| /* -*- mode:linux -*- */
/**
* \file timeout.cc
*
*
*
* \author Ethan Burns
* \date 2008-12-16
*/
#include <iostream>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
void alarm_action(int sig)
{
cout << "No Solution" << endl
<< "cost: infinity" << endl
<< "length: infinity" << endl
<< "wall_time: infinity" << endl
<< "CPU_time: infinity" << endl
<< "generated: infinity" << endl
<< "expanded: infinity" << endl;
exit(EXIT_SUCCESS);
}
void timeout(unsigned int sec)
{
struct sigaction sa;
memset(&sa, '\0', sizeof(sa));
sa.sa_handler = alarm_action;
sigfillset(&sa.sa_mask);
sigaction(SIGALRM, &sa, NULL);
alarm(sec);
}
|
Fix SkNWayCanvas cons call when creating null canvas. | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkNullCanvas.h"
#include "SkCanvas.h"
#include "SKNWayCanvas.h"
SkCanvas* SkCreateNullCanvas() {
// An N-Way canvas forwards calls to N canvas's. When N == 0 it's
// effectively a null canvas.
return SkNEW(SkNWayCanvas);
}
| /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkNullCanvas.h"
#include "SkCanvas.h"
#include "SKNWayCanvas.h"
SkCanvas* SkCreateNullCanvas() {
// An N-Way canvas forwards calls to N canvas's. When N == 0 it's
// effectively a null canvas.
return SkNEW(SkNWayCanvas(0,0));
}
|
Add simple memory model to consume latency of memory operations. Still needs them to be pushed. | #include "performance_model.h"
#include "log.h"
using std::endl;
SimplePerformanceModel::SimplePerformanceModel()
: m_instruction_count(0)
, m_cycle_count(0)
{
}
SimplePerformanceModel::~SimplePerformanceModel()
{
}
void SimplePerformanceModel::outputSummary(std::ostream &os)
{
os << " Instructions: " << getInstructionCount() << endl
<< " Cycles: " << getCycleCount() << endl;
}
void SimplePerformanceModel::handleInstruction(Instruction *instruction)
{
m_instruction_count++;
m_cycle_count += instruction->getCost();
}
| #include "performance_model.h"
#include "log.h"
using std::endl;
SimplePerformanceModel::SimplePerformanceModel()
: m_instruction_count(0)
, m_cycle_count(0)
{
}
SimplePerformanceModel::~SimplePerformanceModel()
{
}
void SimplePerformanceModel::outputSummary(std::ostream &os)
{
os << " Instructions: " << getInstructionCount() << endl
<< " Cycles: " << getCycleCount() << endl;
}
void SimplePerformanceModel::handleInstruction(Instruction *instruction)
{
// compute cost
UInt64 cost = 0;
const OperandList &ops = instruction->getOperands();
for (unsigned int i = 0; i < ops.size(); i++)
{
const Operand &o = ops[i];
if (o.m_type == Operand::MEMORY &&
o.m_direction == Operand::READ)
{
DynamicInstructionInfo &i = getDynamicInstructionInfo();
LOG_ASSERT_ERROR(i.type == DynamicInstructionInfo::INFO_MEMORY,
"Expected memory info.");
cost += i.memory_info.latency;
// ignore address
popDynamicInstructionInfo();
}
}
cost += instruction->getCost();
// update counters
m_instruction_count++;
m_cycle_count += cost;
}
|
Fix compilation with GCC 4.1.1. | /*
Copyright 2007 Albert Strasheim <fullung@gmail.com>
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.
*/
// TODO look at issues with the GIL here when multiple session threads
// call into the Python code (could happen with Openwire?)
#include <boost/python.hpp>
#include <cms/MessageListener.h>
using namespace boost::python;
using cms::MessageListener;
using cms::Message;
struct MessageListenerWrap : MessageListener, wrapper<MessageListener>
{
virtual void onMessage(const Message* message)
{
// should be: this->getOverride("onMessage")(message);
// but that doesn't work with Visual C++
call<void>(this->get_override("onMessage").ptr(), message);
}
};
void export_MessageListener()
{
class_<MessageListenerWrap, boost::noncopyable>("MessageListener")
.def("onMessage", pure_virtual(&MessageListener::onMessage))
;
}
| /*
Copyright 2007 Albert Strasheim <fullung@gmail.com>
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.
*/
// TODO look at issues with the GIL here when multiple session threads
// call into the Python code (could happen with Openwire?)
#include <boost/python.hpp>
#include <cms/MessageListener.h>
#include <cms/Message.h>
using namespace boost::python;
using cms::MessageListener;
using cms::Message;
struct MessageListenerWrap : MessageListener, wrapper<MessageListener>
{
virtual void onMessage(const Message* message)
{
// should be: this->getOverride("onMessage")(message);
// but that doesn't work with Visual C++
call<void>(this->get_override("onMessage").ptr(), message);
}
};
void export_MessageListener()
{
class_<MessageListenerWrap, boost::noncopyable>("MessageListener")
.def("onMessage", pure_virtual(&MessageListener::onMessage))
;
}
|
Fix occlusion tester segment ray creation to behave like before | #include "scene.h"
#include "geometry/differential_geometry.h"
#include "lights/occlusion_tester.h"
void OcclusionTester::set_points(const Point &a, const Point &b){
float dist = a.distance(b);
ray = Ray{a, (b - a) / dist, 1e-6f, dist * (1.f - 1e-6f)};
}
void OcclusionTester::set_ray(const Point &p, const Vector &d){
ray = Ray{p, d.normalized(), 1e-6f};
}
bool OcclusionTester::occluded(const Scene &scene){
DifferentialGeometry dg;
return scene.get_root().intersect(ray, dg);
}
| #include "scene.h"
#include "geometry/differential_geometry.h"
#include "lights/occlusion_tester.h"
void OcclusionTester::set_points(const Point &a, const Point &b){
ray = Ray{a, b - a, 1e-4f, 1};
}
void OcclusionTester::set_ray(const Point &p, const Vector &d){
ray = Ray{p, d.normalized(), 1e-4f};
}
bool OcclusionTester::occluded(const Scene &scene){
DifferentialGeometry dg;
return scene.get_root().intersect(ray, dg);
}
|
Fix use-after-free on database object | /*
* Copyright 2014 Cloudius Systems
*/
#include "database.hh"
#include "core/app-template.hh"
#include "core/smp.hh"
#include "thrift/server.hh"
namespace bpo = boost::program_options;
int main(int ac, char** av) {
app_template app;
app.add_options()
("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port")
("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory");
auto server = std::make_unique<distributed<thrift_server>>();;
return app.run(ac, av, [&] {
auto&& config = app.configuration();
uint16_t port = config["thrift-port"].as<uint16_t>();
sstring datadir = config["datadir"].as<std::string>();
database db(datadir);
auto server = new distributed<thrift_server>;
server->start(std::ref(db)).then([server = std::move(server), port] () mutable {
server->invoke_on_all(&thrift_server::listen, ipv4_addr{port});
}).then([port] {
std::cout << "Thrift server listening on port " << port << " ...\n";
});
});
}
| /*
* Copyright 2014 Cloudius Systems
*/
#include "database.hh"
#include "core/app-template.hh"
#include "core/smp.hh"
#include "thrift/server.hh"
namespace bpo = boost::program_options;
int main(int ac, char** av) {
app_template app;
app.add_options()
("thrift-port", bpo::value<uint16_t>()->default_value(9160), "Thrift port")
("datadir", bpo::value<std::string>()->default_value("/var/lib/cassandra/data"), "data directory");
auto server = std::make_unique<distributed<thrift_server>>();;
std::unique_ptr<database> db;
return app.run(ac, av, [&] {
auto&& config = app.configuration();
uint16_t port = config["thrift-port"].as<uint16_t>();
sstring datadir = config["datadir"].as<std::string>();
db.reset(std::make_unique<database>(datadir).release());
auto server = new distributed<thrift_server>;
server->start(std::ref(*db)).then([server = std::move(server), port] () mutable {
server->invoke_on_all(&thrift_server::listen, ipv4_addr{port});
}).then([port] {
std::cout << "Thrift server listening on port " << port << " ...\n";
});
});
}
|
Fix test from r346439 to also work on Windows due to path separator differences. | // RUN: rm -rf %t
// RUN: mkdir -p %t/prebuilt_modules
//
// RUN: %clang_cc1 -triple %itanium_abi_triple \
// RUN: -fmodules-ts -fprebuilt-module-path=%t/prebuilt-modules \
// RUN: -emit-module-interface -pthread -DBUILD_MODULE \
// RUN: %s -o %t/prebuilt_modules/mismatching_module.pcm
//
// RUN: not %clang_cc1 -triple %itanium_abi_triple -fmodules-ts \
// RUN: -fprebuilt-module-path=%t/prebuilt_modules -DCHECK_MISMATCH \
// RUN: %s 2>&1 | FileCheck %s
#ifdef BUILD_MODULE
export module mismatching_module;
#endif
#ifdef CHECK_MISMATCH
import mismatching_module;
// CHECK: error: POSIX thread support was enabled in PCH file but is currently disabled
// CHECK-NEXT: module file {{.*}}/mismatching_module.pcm cannot be loaded due to a configuration mismatch with the current compilation
#endif
| // RUN: rm -rf %t
// RUN: mkdir -p %t/prebuilt_modules
//
// RUN: %clang_cc1 -triple %itanium_abi_triple \
// RUN: -fmodules-ts -fprebuilt-module-path=%t/prebuilt-modules \
// RUN: -emit-module-interface -pthread -DBUILD_MODULE \
// RUN: %s -o %t/prebuilt_modules/mismatching_module.pcm
//
// RUN: not %clang_cc1 -triple %itanium_abi_triple -fmodules-ts \
// RUN: -fprebuilt-module-path=%t/prebuilt_modules -DCHECK_MISMATCH \
// RUN: %s 2>&1 | FileCheck %s
#ifdef BUILD_MODULE
export module mismatching_module;
#endif
#ifdef CHECK_MISMATCH
import mismatching_module;
// CHECK: error: POSIX thread support was enabled in PCH file but is currently disabled
// CHECK-NEXT: module file {{.*[/|\\\\]}}mismatching_module.pcm cannot be loaded due to a configuration mismatch with the current compilation
#endif
|
Fix a regex error breaking tests. | // RUN: %clang -### -Wlarge-by-value-copy %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_DEFAULT %s
// LARGE_VALUE_COPY_DEFAULT: -Wlarge-by-value-copy=64
// RUN: %clang -### -Wlarge-by-value-copy=128 %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_JOINED %s
// LARGE_VALUE_COPY_JOINED: -Wlarge-by-value-copy=128
// Check that -isysroot warns on nonexistent paths.
// RUN: %clang -### -c -target i386-apple-darwin10 -isysroot %T/warning-options %s 2>&1 | FileCheck --check-prefix=CHECK-ISYSROOT %s
// CHECK-ISYSROOT: warning: no such sysroot directory: '{{([A-Za-z]:.*)?}}/warning-options'
| // RUN: %clang -### -Wlarge-by-value-copy %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_DEFAULT %s
// LARGE_VALUE_COPY_DEFAULT: -Wlarge-by-value-copy=64
// RUN: %clang -### -Wlarge-by-value-copy=128 %s 2>&1 | FileCheck -check-prefix=LARGE_VALUE_COPY_JOINED %s
// LARGE_VALUE_COPY_JOINED: -Wlarge-by-value-copy=128
// Check that -isysroot warns on nonexistent paths.
// RUN: %clang -### -c -target i386-apple-darwin10 -isysroot %T/warning-options %s 2>&1 | FileCheck --check-prefix=CHECK-ISYSROOT %s
// CHECK-ISYSROOT: warning: no such sysroot directory: '{{.*}}/warning-options'
|
Fix SecRandomCopyBytes call with older OS X SDKs | /*
* Darwin SecRandomCopyBytes EntropySource
* (C) 2015 Daniel Seither (Kullo GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/darwin_secrandom.h>
#include <Security/Security.h>
namespace Botan {
/**
* Gather entropy from SecRandomCopyBytes
*/
void Darwin_SecRandom::poll(Entropy_Accumulator& accum)
{
secure_vector<byte>& buf = accum.get_io_buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);
if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data()))
{
accum.add(buf.data(), buf.size(), BOTAN_ENTROPY_ESTIMATE_STRONG_RNG);
}
}
}
| /*
* Darwin SecRandomCopyBytes EntropySource
* (C) 2015 Daniel Seither (Kullo GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/darwin_secrandom.h>
#include <Security/Security.h>
#include <Security/SecRandom.h>
namespace Botan {
/**
* Gather entropy from SecRandomCopyBytes
*/
void Darwin_SecRandom::poll(Entropy_Accumulator& accum)
{
secure_vector<byte>& buf = accum.get_io_buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);
if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data()))
{
accum.add(buf.data(), buf.size(), BOTAN_ENTROPY_ESTIMATE_STRONG_RNG);
}
}
}
|
Update clock delay for new 8-cycle instruction | #include "common.th"
_start:
bare_metal_init()
prologue
top:
d <- [rel(min0)]
e <- [rel(min1)]
f <- [rel(sec0)]
g <- [rel(sec1)]
h <- d << 4 + e
h <- h << 4 + f
h <- h << 4 + g
h -> [0x100]
c <- 1
call(sleep)
g <- g + 1
h <- g == 10
g <- g &~ h
f <- f - h
h <- f == 6
f <- f &~ h
e <- e - h
h <- e == 10
e <- e &~ h
d <- d - h
h <- d == 6
d <- d &~ h
d -> [rel(min0)]
e -> [rel(min1)]
f -> [rel(sec0)]
g -> [rel(sec1)]
goto(top)
illegal
sleep:
c <- c * 1070
c <- c * 1780
call(ticks)
ret
ticks:
pushall(d,e)
d <- 0
Lticks_loop:
e <- d < c
d <- d + 1
jnzrel(e,Lticks_loop)
popall_ret(d,e)
min0: .word 0
min1: .word 0
sec0: .word 0
sec1: .word 0
| #include "common.th"
_start:
bare_metal_init()
prologue
top:
d <- [rel(min0)]
e <- [rel(min1)]
f <- [rel(sec0)]
g <- [rel(sec1)]
h <- d << 4 + e
h <- h << 4 + f
h <- h << 4 + g
h -> [0x100]
c <- 1
call(sleep)
g <- g + 1
h <- g == 10
g <- g &~ h
f <- f - h
h <- f == 6
f <- f &~ h
e <- e - h
h <- e == 10
e <- e &~ h
d <- d - h
h <- d == 6
d <- d &~ h
d -> [rel(min0)]
e -> [rel(min1)]
f -> [rel(sec0)]
g -> [rel(sec1)]
goto(top)
illegal
sleep:
// 40MHz clock, 4-cycle ticks() loop, 8cpi
c <- c * 1000
c <- c * 1250
call(ticks)
ret
ticks:
pushall(d,e)
d <- 0
Lticks_loop:
e <- d < c
d <- d + 1
a <- a // delay to make the loop 4 cycles long
jnzrel(e,Lticks_loop)
popall_ret(d,e)
min0: .word 0
min1: .word 0
sec0: .word 0
sec1: .word 0
|
Use windows native look and feel | #include "MainWindow.h"
#include "SpritePackerProjectFile.h"
#include <QApplication>
int commandLine(QCoreApplication& app);
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
#ifdef Q_OS_WIN32
QApplication::setStyle(QStyleFactory::create("Fusion"));
#endif
QCoreApplication::setOrganizationName("amakaseev");
QCoreApplication::setOrganizationDomain("spicyminds-lab.com");
QCoreApplication::setApplicationName("SpriteSheetPacker");
QCoreApplication::setApplicationVersion("1.0.3");
//QDir::setCurrent(QApplication::applicationDirPath());
SpritePackerProjectFile::factory().set<SpritePackerProjectFile>("json");
SpritePackerProjectFile::factory().set<SpritePackerProjectFileOLD>("sp");
SpritePackerProjectFile::factory().set<SpritePackerProjectFileTPS>("tps");
if (argc > 1) {
return commandLine(app);
} else {
MainWindow w;
w.show();
return app.exec();
}
}
| #include "MainWindow.h"
#include "SpritePackerProjectFile.h"
#include <QApplication>
int commandLine(QCoreApplication& app);
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QCoreApplication::setOrganizationName("amakaseev");
QCoreApplication::setOrganizationDomain("spicyminds-lab.com");
QCoreApplication::setApplicationName("SpriteSheetPacker");
QCoreApplication::setApplicationVersion("1.0.3");
//QDir::setCurrent(QApplication::applicationDirPath());
SpritePackerProjectFile::factory().set<SpritePackerProjectFile>("json");
SpritePackerProjectFile::factory().set<SpritePackerProjectFileOLD>("sp");
SpritePackerProjectFile::factory().set<SpritePackerProjectFileTPS>("tps");
if (argc > 1) {
return commandLine(app);
} else {
MainWindow w;
w.show();
return app.exec();
}
}
|
Fix capacity check in BufAccessor test | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
#include <quic/common/BufAccessor.h>
#include <folly/portability/GTest.h>
namespace quic {
TEST(SimpleBufAccessor, BasicAccess) {
SimpleBufAccessor accessor(1000);
EXPECT_TRUE(accessor.ownsBuffer());
auto buf = accessor.obtain();
EXPECT_EQ(1000, buf->capacity());
EXPECT_FALSE(accessor.ownsBuffer());
auto empty = accessor.obtain();
EXPECT_EQ(nullptr, empty);
accessor.release(buf->clone());
EXPECT_TRUE(accessor.ownsBuffer());
EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
TEST(SimpleBufAccessor, CapacityMatch) {
SimpleBufAccessor accessor(1000);
auto buf = accessor.obtain();
buf = folly::IOBuf::create(2000);
EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
TEST(SimpleBufAccessor, RefuseChainedBuf) {
SimpleBufAccessor accessor(1000);
auto buf = accessor.obtain();
buf->prependChain(folly::IOBuf::create(0));
EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
} // namespace quic
| /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
#include <quic/common/BufAccessor.h>
#include <folly/portability/GTest.h>
namespace quic {
TEST(SimpleBufAccessor, BasicAccess) {
SimpleBufAccessor accessor(1000);
EXPECT_TRUE(accessor.ownsBuffer());
auto buf = accessor.obtain();
EXPECT_LE(1000, buf->capacity());
EXPECT_FALSE(accessor.ownsBuffer());
auto empty = accessor.obtain();
EXPECT_EQ(nullptr, empty);
accessor.release(buf->clone());
EXPECT_TRUE(accessor.ownsBuffer());
EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
TEST(SimpleBufAccessor, CapacityMatch) {
SimpleBufAccessor accessor(1000);
auto buf = accessor.obtain();
buf = folly::IOBuf::create(2000);
EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
TEST(SimpleBufAccessor, RefuseChainedBuf) {
SimpleBufAccessor accessor(1000);
auto buf = accessor.obtain();
buf->prependChain(folly::IOBuf::create(0));
EXPECT_DEATH(accessor.release(std::move(buf)), "");
}
} // namespace quic
|
Include config.h instead of windows.h in shared library test project. | #include <QtGui>
#include <sequanto/automation.h>
#include <sequanto/tree.h>
#include <sequanto/QtWrapper.h>
#include "../cxx/src/cxx_root.h"
#include <windows.h>
using namespace sequanto::automation;
int main ( int argc, char * argv[] )
{
SQServer server;
sq_init ();
sq_server_init ( &server, 4321 );
QApplication * application = new QApplication ( argc, argv );
ListNode * test = new ListNode ("test");
sq_get_cxx_root()->AddChild ( test );
QtWrapper::WrapApplication ( test );
sq_server_poll ( &server );
atexit ( sq_shutdown );
}
| #include <QtGui>
#include <sequanto/automation.h>
#include <sequanto/tree.h>
#include <sequanto/QtWrapper.h>
#include "../cxx/src/cxx_root.h"
#include "config.h"
using namespace sequanto::automation;
int main ( int argc, char * argv[] )
{
SQServer server;
sq_init ();
sq_server_init ( &server, 4321 );
QApplication * application = new QApplication ( argc, argv );
ListNode * test = new ListNode ("test");
sq_get_cxx_root()->AddChild ( test );
QtWrapper::WrapApplication ( test );
sq_server_poll ( &server );
atexit ( sq_shutdown );
}
|
Mark ExtensionApiTest.Popup as FLAKY, it is still flaky. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"
// Flaky, http://crbug.com/46601.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}
|
Rewrite c-string copy helper function cleanly | #include "insect/records.h"
static void
__record(Record *);
#include <assert.h>
#include <stdlib.h>
#include <string.h>
static void
__path_copy(RecordPath path, RecordPath *ref)
{
int len = strnlen(path, RECORD_PATH_MAX);
assert(ref);
*ref = malloc(len + 1);
assert(*ref);
(void) strncpy(*ref, path, len + 1);
}
Record *
record_new(RecordPath path)
{
Record *record;
assert(path);
record = malloc(sizeof(Record));
assert(record);
record->hits = 1;
record->path = NULL;
__path_copy(path, &record->path);
__record(record);
return record;
}
void
record_free(Record *record)
{
assert(record);
record->hits = 0;
free(record->path);
free(record);
}
| #include "insect/records.h"
static void
__record(Record *);
static void
__path_copy(Path, Path *);
/* FIMXE(teh): ^ inline? */
#include <assert.h>
#include <stdlib.h>
Record *
record_new(Path path)
{
Record *record;
assert(path);
record = malloc(sizeof(Record));
assert(record);
record->hits = 1;
record->path = NULL;
__path_copy(path, &record->path);
__record(record);
return record;
}
void
record_free(Record *record)
{
assert(record);
record->hits = 0;
free((void *) record->path);
free(record);
}
/* */
#include <string.h>
static void
__path_copy(Path old_path, Path *new_copy)
{
int len;
assert(old_path && new_copy);
len = strnlen(old_path, INSECT_PATH_MAX);
*new_copy = malloc(len + 1);
assert(*new_copy);
(void) strncpy((char *) *new_copy, old_path, len + 1);
}
|
Use a little type deduction | #include <functional>
#include <boost/optional.hpp>
#include "key_aliases.hh"
#include "file_contents.hh"
#include "contents.hh"
#include "mode.hh"
#include "show_message.hh"
std::map < char, std::function < void (contents&, boost::optional<int>) > >
global_normal_map,
global_insert_map;
mode::mode(const std::string& name, bool (*const handle)(char))
: name(name)
, handle(handle) { }
bool mode::operator()(char ch) const {
return handle(ch);
}
const std::string& mode::get_name() const {
return this->name;
}
static bool fundamental_handle(char ch) {
if(ch == _resize) return true;
std::map < char, fun > :: iterator
it = global_normal_map.find(ch);
if(it == global_normal_map.end()) return false;
clear_message();
it->second(get_contents(),boost::none);
return true;
}
mode mode::fundamental("Fundamental",fundamental_handle);
| #include <functional>
#include <boost/optional.hpp>
#include "key_aliases.hh"
#include "file_contents.hh"
#include "contents.hh"
#include "mode.hh"
#include "show_message.hh"
std::map < char, std::function < void (contents&, boost::optional<int>) > >
global_normal_map,
global_insert_map;
mode::mode(const std::string& name, bool (*const handle)(char))
: name(name)
, handle(handle) { }
bool mode::operator()(char ch) const {
return handle(ch);
}
const std::string& mode::get_name() const {
return this->name;
}
static bool fundamental_handle(char ch) {
if(ch == _resize) return true;
auto it = global_normal_map.find(ch);
if(it == global_normal_map.end()) return false;
clear_message();
it->second(get_contents(),boost::none);
return true;
}
mode mode::fundamental("Fundamental",fundamental_handle);
|
Add statement to show kernel |
#include <mlopen/hipoc_kernel.hpp>
#include <mlopen/errors.hpp>
namespace mlopen {
void HIPOCKernelInvoke::run(void* args, std::size_t size) const
{
hipEvent_t start = nullptr;
hipEvent_t stop = nullptr;
void *config[] = {
HIP_LAUNCH_PARAM_BUFFER_POINTER, args,
HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
HIP_LAUNCH_PARAM_END
};
if (callback)
{
hipEventCreate(&start);
hipEventCreate(&stop);
hipEventRecord(start, nullptr);
}
auto status = hipModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config);
if(status != hipSuccess) MLOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel");
if (callback)
{
hipEventRecord(stop, nullptr);
hipEventSynchronize(stop);
callback(start, stop);
}
}
HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback)
{
return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback};
}
}
|
#include <mlopen/hipoc_kernel.hpp>
#include <mlopen/errors.hpp>
namespace mlopen {
void HIPOCKernelInvoke::run(void* args, std::size_t size) const
{
hipEvent_t start = nullptr;
hipEvent_t stop = nullptr;
void *config[] = {
HIP_LAUNCH_PARAM_BUFFER_POINTER, args,
HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
HIP_LAUNCH_PARAM_END
};
if (callback)
{
hipEventCreate(&start);
hipEventCreate(&stop);
hipEventRecord(start, nullptr);
}
// std::cerr << "Launch kernel: " << name << std::endl;
auto status = hipModuleLaunchKernel(fun, gdims[0], gdims[1], gdims[2], ldims[0], ldims[1], ldims[2], 0, stream, nullptr, (void**)&config);
if(status != hipSuccess) MLOPEN_THROW_HIP_STATUS(status, "Failed to launch kernel");
if (callback)
{
hipEventRecord(stop, nullptr);
hipEventSynchronize(stop);
callback(start, stop);
}
}
HIPOCKernelInvoke HIPOCKernel::Invoke(hipStream_t stream, std::function<void(hipEvent_t, hipEvent_t)> callback)
{
return HIPOCKernelInvoke{stream, fun, ldims, gdims, name, callback};
}
}
|
Include "scale" parameter in calculations | //
// Created by dar on 2/11/16.
//
#include <gui/GuiText.h>
#include "TextManager.h"
TextManager::TextManager() : GuiElementRender() {
this->charRender = new CharRender();
}
TextManager::~TextManager() {
delete this->charRender;
}
void TextManager::render(const GuiElement *const element, glm::mat4 projectionMatrix, glm::mat4 viewMatrix, double scale) {
const GuiText *const text = (const GuiText *const) element;
int x = (int) text->getX();
for (int i = 0; i < text->getString().length(); i++) {
int j = this->charRender->getGlyphPos(text->getString().at(i));
if (j == -1) {
x += this->charRender->TEXT_SPACESIZE * scale;
continue;
}
this->charRender->render(text->getString().at(i), projectionMatrix, viewMatrix, x, (int) text->getY(), text->getScale(), text->getColor(), text->getFlags());
x += this->charRender->getGlyphSize(j) * scale + SPACING_PX;
}
}
| //
// Created by dar on 2/11/16.
//
#include <gui/GuiText.h>
#include "TextManager.h"
TextManager::TextManager() : GuiElementRender() {
this->charRender = new CharRender();
}
TextManager::~TextManager() {
delete this->charRender;
}
void TextManager::render(const GuiElement *const element, glm::mat4 projectionMatrix, glm::mat4 viewMatrix, double scale) {
const GuiText *const text = (const GuiText *const) element;
int x = (int) text->getX();
for (int i = 0; i < text->getString().length(); i++) {
int j = this->charRender->getGlyphPos(text->getString().at(i));
if (j == -1) {
x += this->charRender->TEXT_SPACESIZE * scale;
continue;
}
this->charRender->render(text->getString().at(i), projectionMatrix, viewMatrix, x, (int) text->getY(), text->getScale() * scale, text->getColor(), text->getFlags());
x += this->charRender->getGlyphSize(j) * scale + SPACING_PX;
}
}
|
Send more bytes per batch over serial. | #ifdef CHIPKIT
#include "serialutil.h"
#include "buffers.h"
#include "log.h"
void readFromSerial(SerialDevice* serial, bool (*callback)(uint8_t*)) {
int bytesAvailable = serial->device->available();
if(bytesAvailable > 0) {
for(int i = 0; i < bytesAvailable && !queue_full(&serial->receiveQueue);
i++) {
char byte = serial->device->read();
QUEUE_PUSH(uint8_t, &serial->receiveQueue, (uint8_t) byte);
}
processQueue(&serial->receiveQueue, callback);
}
}
void initializeSerial(SerialDevice* serial) {
serial->device->begin(115200);
queue_init(&serial->receiveQueue);
}
void processInputQueue(SerialDevice* device) {
int byteCount = 0;
char sendBuffer[MAX_MESSAGE_SIZE];
while(!queue_empty(&device->sendQueue) && byteCount < 64) {
sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue);
}
// Serial transfers are really, really slow, so we don't want to send unless
// explicitly set to do so at compile-time. Alternatively, we could send
// on serial whenever we detect below that we're probably not connected to a
// USB device, but explicit is better than implicit.
device->device->write((const uint8_t*)sendBuffer, byteCount);
}
#endif // CHIPKIT
| #ifdef CHIPKIT
#include "serialutil.h"
#include "buffers.h"
#include "log.h"
void readFromSerial(SerialDevice* serial, bool (*callback)(uint8_t*)) {
int bytesAvailable = serial->device->available();
if(bytesAvailable > 0) {
for(int i = 0; i < bytesAvailable && !queue_full(&serial->receiveQueue);
i++) {
char byte = serial->device->read();
QUEUE_PUSH(uint8_t, &serial->receiveQueue, (uint8_t) byte);
}
processQueue(&serial->receiveQueue, callback);
}
}
void initializeSerial(SerialDevice* serial) {
serial->device->begin(115200);
queue_init(&serial->receiveQueue);
}
void processInputQueue(SerialDevice* device) {
int byteCount = 0;
char sendBuffer[MAX_MESSAGE_SIZE];
while(!queue_empty(&device->sendQueue) && byteCount < MAX_MESSAGE_SIZE) {
sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &device->sendQueue);
}
device->device->write((const uint8_t*)sendBuffer, byteCount);
}
#endif // CHIPKIT
|
Remove comment from coroutines test, NFC | // test/SemaCXX/coroutine-traits-undefined-template.cpp
// This file contains references to sections of the Coroutines TS, which can be
// found at http://wg21.link/coroutines.
// RUN: %clang_cc1 -std=c++14 -fcoroutines-ts -verify %s -fcxx-exceptions -fexceptions -Wunused-result
namespace std {
namespace experimental {
template<typename ...T>
struct coroutine_traits {
struct promise_type {};
};
template<> struct coroutine_traits<void>; // expected-note {{forward declaration of 'std::experimental::coroutine_traits<void>'}}
}} // namespace std::experimental
void uses_forward_declaration() {
co_return; // expected-error {{this function cannot be a coroutine: missing definition of specialization 'coroutine_traits<void>'}}
}
| // This file contains references to sections of the Coroutines TS, which can be
// found at http://wg21.link/coroutines.
// RUN: %clang_cc1 -std=c++14 -fcoroutines-ts -verify %s -fcxx-exceptions -fexceptions -Wunused-result
namespace std {
namespace experimental {
template<typename ...T>
struct coroutine_traits {
struct promise_type {};
};
template<> struct coroutine_traits<void>; // expected-note {{forward declaration of 'std::experimental::coroutine_traits<void>'}}
}} // namespace std::experimental
void uses_forward_declaration() {
co_return; // expected-error {{this function cannot be a coroutine: missing definition of specialization 'coroutine_traits<void>'}}
}
|
Add 'std' prefix for printf() in blackbox::configure test | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <cstdio>
int main()
{
printf("%s..\n", TEXT);
return 0;
}
| /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <cstdio>
int main()
{
std::printf("%s..\n", TEXT);
return 0;
}
|
Update LinkList test2 (locate and traverse) | ///////////////////////////////////////
/// file: linklist_test.cpp
///////////////////////////////////////
#include <iostream>
#include "linklist.h"
using namespace std;
///
/// 打印链表
///
template<typename T>
void PrintList(LinkList<T> L)
{
cout << "(";
auto p = L->next;
while(p) {
cout << " " << p->data;
p = p->next;
}
cout << " )" << endl;
}
bool eq(int a, int b)
{
return a==b;
}
void print(int x)
{
cout << " " << x;
}
int main()
{
// 建立链表
LinkList<int> L;
// 初始化
InitList(L);
PrintList(L);
// 插入元素
ListInsert(L,1,3);
ListInsert(L,2,1);
ListInsert(L,3,4);
ListInsert(L,4,1);
ListInsert(L,5,5);
ListInsert(L,6,9);
PrintList(L);
// 元素定位
cout << "LocateElem 9 = ";
cout << "L(@" << LocateElem(L,9,eq) << ")" << endl;
// 遍历线性表
cout << "ListTraverse: ";
ListTraverse(L,print);
cout << endl;
// 销毁链表
DestroyList(L);
return 0;
} | ///////////////////////////////////////
/// file: linklist_test2.cpp
///////////////////////////////////////
#include <iostream>
#include "linklist.h"
using namespace std;
///
/// 打印链表
///
template<typename T>
void PrintList(LinkList<T> L)
{
cout << "(";
auto p = L->next;
while(p) {
cout << " " << p->data;
p = p->next;
}
cout << " )" << endl;
}
bool eq(int a, int b)
{
return a==b;
}
void print(int x)
{
cout << " " << x;
}
///
/// 在单链表中定位元素,遍历顺序表
///
int main()
{
// 建立链表
LinkList<int> L;
// 初始化
InitList(L);
PrintList(L);
// 插入元素
ListInsert(L,1,3);
ListInsert(L,2,1);
ListInsert(L,3,4);
ListInsert(L,4,1);
ListInsert(L,5,5);
ListInsert(L,6,9);
PrintList(L);
// 元素定位
cout << "LocateElem 9 = ";
cout << "L(@" << LocateElem(L,9,eq) << ")" << endl;
// 遍历线性表
cout << "ListTraverse: ";
ListTraverse(L,print);
cout << endl;
// 销毁链表
DestroyList(L);
return 0;
} |
Fix layout issue in details window | #include "viewer/details-window.h"
#include <QLabel>
#include <ui_details-window.h>
#include "helpers.h"
#include "models/image.h"
DetailsWindow::DetailsWindow(Profile *profile, QWidget *parent)
: QDialog(parent), ui(new Ui::DetailsWindow), m_profile(profile)
{
ui->setupUi(this);
}
DetailsWindow::~DetailsWindow()
{
delete ui;
}
void DetailsWindow::setImage(QSharedPointer<Image> image)
{
clearLayout(ui->formLayout);
for (QPair<QString, QString> row : image->detailsData())
{
if (row.first.isEmpty() && row.second.isEmpty())
{
ui->formLayout->addItem(new QSpacerItem(10, 10));
}
else
{
auto label = new QLabel(QString("<b>%1</b>").arg(row.first), this);
auto field = new QLabel(row.second, this);
field->setWordWrap(true);
ui->formLayout->addRow(label, field);
}
}
resize(QSize(400, 200));
}
| #include "viewer/details-window.h"
#include <QLabel>
#include <ui_details-window.h>
#include "helpers.h"
#include "models/image.h"
DetailsWindow::DetailsWindow(Profile *profile, QWidget *parent)
: QDialog(parent), ui(new Ui::DetailsWindow), m_profile(profile)
{
ui->setupUi(this);
}
DetailsWindow::~DetailsWindow()
{
delete ui;
}
void DetailsWindow::setImage(QSharedPointer<Image> image)
{
clearLayout(ui->formLayout);
for (QPair<QString, QString> row : image->detailsData())
{
if (row.first.isEmpty() && row.second.isEmpty())
{
ui->formLayout->addItem(new QSpacerItem(10, 10));
}
else
{
auto label = new QLabel(QString("<b>%1</b>").arg(row.first), this);
auto field = new QLabel(row.second, this);
field->setWordWrap(true);
ui->formLayout->addRow(label, field);
}
}
update();
resize(sizeHint());
}
|
Add code for function test. | #include <vector>
#include <string>
std::string createString(){
std::string hi("Hello world!");
return hi;
}
std::vector<std::string> createVector(){
std::vector<std::string> my_vector;
my_vector.push_back(createString());
my_vector.push_back(createString());
my_vector.push_back(createString());
return my_vector;
}
int putStringsInVector(int num){
std::vector<std::string> my_strings;
for(int i=0; i<num; i++){
my_strings.push_back(createString());
}
return my_strings.size();
}
| #include <vector>
#include <string>
std::string createString(){
std::string hi("Hello world!");
return hi;
}
std::vector<std::string> createVector(){
std::vector<std::string> my_vector;
my_vector.push_back(createString());
my_vector.push_back(createString());
my_vector.push_back(createString());
return my_vector;
}
int putStringsInVector(int num){
std::vector<std::string> my_strings;
for(int i=0; i<num; i++){
my_strings.push_back(createString());
}
return my_strings.size();
}
void modifyVector(std::vector<int> & vector){
int count = 0;
for(int i:vector){
if(count % 5 == 0){
i = 42;
}
}
}
|
Put the symbol requester func into the proper namespace! | // request symbols
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/DynamicExprInfo.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/UserInterface/UserInterface.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
namespace cling {
void libcling__symbol_requester() {
const char* const argv[] = {"libcling__symbol_requester", 0};
cling::Interpreter I(1, argv);
cling::UserInterface U(I);
cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call.
printValuePublicDefault(llvm::outs(), 0, VPI);
cling_PrintValue(0, 0, 0);
flushOStream(llvm::outs());
LookupHelper h(0);
h.findType("");
h.findScope("");
h.findFunctionProto(0, "", "");
h.findFunctionArgs(0, "", "");
cling::runtime::internal::DynamicExprInfo DEI(0,0,false);
DEI.getExpr();
cling::InterpreterCallbacks cb(0);
}
}
| // request symbols
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/CValuePrinter.h"
#include "cling/Interpreter/DynamicExprInfo.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Interpreter/ValuePrinter.h"
#include "cling/Interpreter/ValuePrinterInfo.h"
#include "cling/UserInterface/UserInterface.h"
#include "clang/AST/Type.h"
#include "llvm/Support/raw_ostream.h"
namespace cling {
namespace internal {
void libcling__symbol_requester() {
const char* const argv[] = {"libcling__symbol_requester", 0};
cling::Interpreter I(1, argv);
cling::UserInterface U(I);
cling::ValuePrinterInfo VPI(0, 0); // asserts, but we don't call.
printValuePublicDefault(llvm::outs(), 0, VPI);
cling_PrintValue(0, 0, 0);
flushOStream(llvm::outs());
LookupHelper h(0);
h.findType("");
h.findScope("");
h.findFunctionProto(0, "", "");
h.findFunctionArgs(0, "", "");
cling::runtime::internal::DynamicExprInfo DEI(0,0,false);
DEI.getExpr();
cling::InterpreterCallbacks cb(0);
}
}
}
|
Handle CAN interrupts on LPC. | #ifdef __LPC17XX__
#include "canread.h"
CanMessage receiveCanMessage(CanBus* bus) {
CAN_MSG_Type message;
CAN_ReceiveMsg(bus->controller, &message);
CanMessage result = {message.id, 0};
result.data = message.dataA[0];
result.data |= (message.dataA[1] << 8);
result.data |= (message.dataA[2] << 16);
result.data |= (message.dataA[3] << 24);
result.data |= (((uint64_t)message.dataB[0]) << 32);
result.data |= (((uint64_t)message.dataB[1]) << 40);
result.data |= (((uint64_t)message.dataB[2]) << 48);
result.data |= (((uint64_t)message.dataB[3]) << 56);
return result;
}
#endif // __LPC17XX__
| #ifdef __LPC17XX__
#include "canread.h"
#include "signals.h"
extern "C" {
void CAN_IRQHandler() {
if((CAN_IntGetStatus(LPC_CAN1) & 0x01) == 1) {
getCanBuses()[0].messageReceived = true;
} else if((CAN_IntGetStatus(LPC_CAN2) & 0x01) == 1) {
getCanBuses()[1].messageReceived = true;
}
}
}
CanMessage receiveCanMessage(CanBus* bus) {
CAN_MSG_Type message;
CAN_ReceiveMsg(bus->controller, &message);
CanMessage result = {message.id, 0};
result.data = message.dataA[0];
result.data |= (message.dataA[1] << 8);
result.data |= (message.dataA[2] << 16);
result.data |= (message.dataA[3] << 24);
result.data |= (((uint64_t)message.dataB[0]) << 32);
result.data |= (((uint64_t)message.dataB[1]) << 40);
result.data |= (((uint64_t)message.dataB[2]) << 48);
result.data |= (((uint64_t)message.dataB[3]) << 56);
return result;
}
#endif // __LPC17XX__
|
Remove usage of broken move constructor | #include <iostream>
#include <array>
#include <asio/steady_timer.hpp>
#include <asio.hpp>
#include <thread>
#include "node/raft_node.h"
using namespace std;
std::vector<raft_node_endpoint_t> peers{
{1ul, "localhost", 12345, 13001},
{2ul, "localhost", 12346, 13002},
{3ul, "localhost", 12347, 13003}
};
int main(int argc, char* argv[]) {
try {
// Start raft_nodes
std::vector<std::thread> workers;
std::vector<raft_node> nodes;
for (auto &peer : peers) {
nodes.emplace_back(peer.uuid, std::make_shared<raft::config>(peers));
}
for (auto &node : nodes) {
workers.push_back(std::thread([&node]() {
node.run();
}));
}
workers.push_back(std::thread([&nodes]() {
while (true) {
std::cout << "Assigned roles for cluster: " << std::endl;
for (auto &node : nodes) {
std::cout << node.describe() << std::endl;
}
std::this_thread::sleep_for(2s);
}
}));
// Wait for raft_nodes to finish
std::for_each(workers.begin(), workers.end(), [](std::thread &t){
t.join();
});
}
catch(std::exception& e) {
std::cerr << "Error" << std::endl;
std::cerr << e.what() << std::endl;
}
return 0;
}
| #include <iostream>
#include <array>
#include <asio/steady_timer.hpp>
#include <asio.hpp>
#include <thread>
#include "node/raft_node.h"
using namespace std;
std::vector<raft_node_endpoint_t> peers{
{1ul, "localhost", 12345, 13001},
{2ul, "localhost", 12346, 13002},
{3ul, "localhost", 12347, 13003}
};
int main(int argc, char* argv[]) {
try {
// Start raft_nodes
std::vector<std::thread> workers;
for (auto &peer : peers) {
workers.push_back(std::thread([&peer]() {
auto node = raft_node(peer.uuid, std::make_shared<raft::config>(peers));
node.run();
}));
}
// Wait for raft_nodes to finish
std::for_each(workers.begin(), workers.end(), [](std::thread &t){
t.join();
});
}
catch(std::exception& e) {
std::cerr << "Error" << std::endl;
std::cerr << e.what() << std::endl;
}
return 0;
}
|
Make planning respect world frame velocity | #include "planning/jet/filter_sim.hh"
#include "eigen_helpers.hh"
namespace planning {
namespace jet {
estimation::jet_filter::State kf_state_from_xlqr_state(const State& x,
const Controls& u,
const Parameters& z) {
estimation::jet_filter::State kf_state;
const SE3 world_from_body = SE3(x.R_world_from_body, x.x);
kf_state.T_body_from_world = world_from_body.inverse();
const jcc::Vec3 dR_dt = x.w;
const jcc::Vec3 dx_dt = x.v;
const jcc::Vec3 net_force = x.R_world_from_body * (jcc::Vec3::UnitZ() * x.throttle_pct);
const jcc::Vec3 dv_dt = (z.external_force + net_force) / z.mass;
const jcc::Vec3 dw_dt = u.q;
kf_state.eps_dot = jcc::vstack(dx_dt, (-dR_dt).eval());
kf_state.eps_ddot = jcc::vstack(dv_dt, dw_dt);
return kf_state;
}
} // namespace jet
} // namespace planning | #include "planning/jet/filter_sim.hh"
#include "eigen_helpers.hh"
namespace planning {
namespace jet {
estimation::jet_filter::State kf_state_from_xlqr_state(const State& x,
const Controls& u,
const Parameters& z) {
estimation::jet_filter::State kf_state;
const SE3 world_from_body = SE3(x.R_world_from_body, x.x);
kf_state.R_world_from_body = x.R_world_from_body;
kf_state.x_world = x.x;
const jcc::Vec3 dR_dt = x.w;
const jcc::Vec3 dx_dt = x.v;
const jcc::Vec3 net_force = x.R_world_from_body * (jcc::Vec3::UnitZ() * x.throttle_pct);
const jcc::Vec3 dv_dt = (z.external_force + net_force) / z.mass;
const jcc::Vec3 dw_dt = u.q;
kf_state.eps_dot = jcc::vstack(dx_dt, (-dR_dt).eval());
kf_state.eps_ddot = jcc::vstack(dv_dt, dw_dt);
return kf_state;
}
} // namespace jet
} // namespace planning |
Fix changes where the default value was always being returned for many of the robot state status functions. | #include "RobotState.h"
RobotStateInterface* RobotState::impl = 0;
void RobotState::SetImplementation(RobotStateInterface* i) {
impl = i;
}
bool RobotState::IsDisabled() {
if (impl != 0) {
return impl->IsDisabled();
}
return true;
}
bool RobotState::IsEnabled() {
if (impl != 0) {
impl->IsEnabled();
}
return false;
}
bool RobotState::IsOperatorControl() {
if (impl != 0) {
impl->IsOperatorControl();
}
return true;
}
bool RobotState::IsAutonomous() {
if (impl != 0) {
impl->IsAutonomous();
}
return false;
}
bool RobotState::IsTest() {
if (impl != 0) {
impl->IsTest();
}
return false;
}
| #include "RobotState.h"
RobotStateInterface* RobotState::impl = 0;
void RobotState::SetImplementation(RobotStateInterface* i) {
impl = i;
}
bool RobotState::IsDisabled() {
if (impl != 0) {
return impl->IsDisabled();
}
return true;
}
bool RobotState::IsEnabled() {
if (impl != 0) {
return impl->IsEnabled();
}
return false;
}
bool RobotState::IsOperatorControl() {
if (impl != 0) {
return impl->IsOperatorControl();
}
return true;
}
bool RobotState::IsAutonomous() {
if (impl != 0) {
return impl->IsAutonomous();
}
return false;
}
bool RobotState::IsTest() {
if (impl != 0) {
return impl->IsTest();
}
return false;
}
|
Make sure the pointer in PageData::html remains valid while PageData is called. | // Copyright (c) 2008-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_publisher.h"
#include "base/utf_string_conversions.h"
namespace history {
const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";
void HistoryPublisher::PublishPageThumbnail(
const std::vector<unsigned char>& thumbnail, const GURL& url,
const base::Time& time) const {
PageData page_data = {
time,
url,
NULL,
NULL,
kThumbnailImageFormat,
&thumbnail,
};
PublishDataToIndexers(page_data);
}
void HistoryPublisher::PublishPageContent(const base::Time& time,
const GURL& url,
const std::wstring& title,
const string16& contents) const {
PageData page_data = {
time,
url,
UTF16ToWide(contents).c_str(),
title.c_str(),
NULL,
NULL,
};
PublishDataToIndexers(page_data);
}
} // namespace history
| // Copyright (c) 2008-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_publisher.h"
#include "base/utf_string_conversions.h"
namespace history {
const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";
void HistoryPublisher::PublishPageThumbnail(
const std::vector<unsigned char>& thumbnail, const GURL& url,
const base::Time& time) const {
PageData page_data = {
time,
url,
NULL,
NULL,
kThumbnailImageFormat,
&thumbnail,
};
PublishDataToIndexers(page_data);
}
void HistoryPublisher::PublishPageContent(const base::Time& time,
const GURL& url,
const std::wstring& title,
const string16& contents) const {
std::wstring wide_contents = UTF16ToWide(contents);
PageData page_data = {
time,
url,
wide_contents.c_str(),
title.c_str(),
NULL,
NULL,
};
PublishDataToIndexers(page_data);
}
} // namespace history
|
Edit the validate multiple reads sample | // Validate multiple reads
#include <sstream>
#include <string>
int main()
{
std::istringstream stream{"John Smith 32"};
std::string first_name;
std::string family_name;
int age;
if (stream >> first_name &&
stream >> family_name &&
stream >> age) {
// Use values
}
}
// Validate reading multiple values from an input stream.
//
// We create a [`std::istringstream`](cpp/io/basic_istringstream) as
// the example input stream, which contains some values that we wish
// to read ([8]). This stream could be replaced by any other
// input stream, such as [`std::cin`](cpp/io/cin) or a file stream.
// We then create some objects on [10-11] into which we will read
// values from the stream.
//
// In the condition of the `if` statement on [14-16], we perform the
// extractions. The `&&` operators ensure that the condition
// is `true` only when all extractions succeed. Short-circuiting
// also ensures that an extraction is only evaluated if the previous
// extractions were successful.
//
// If you are reading values on multiple lines, consider [reading
// from the stream line-by-line](/common-tasks/input-streams/read-lines-from-stream.html)
// and then parsing each line.
| // Validate multiple reads
#include <sstream>
#include <string>
int main()
{
std::istringstream stream{"John Smith 32"};
std::string first_name;
std::string family_name;
int age;
if (stream >> first_name &&
stream >> family_name &&
stream >> age) {
// Use values
}
}
// Ensure that multiple stream reads are successful before using the
// extracted values.
//
// We create a [`std::istringstream`](cpp/io/basic_istringstream) as
// the example input stream, which contains some values that we wish
// to read ([8]). This stream could be replaced by any other
// input stream, such as [`std::cin`](cpp/io/cin) or a file stream.
// We then create some objects on [10-11] into which we will read
// values from the stream.
//
// In the condition of the `if` statement on [14-16], we perform the
// extractions. The `&&` operators ensure that the condition
// is `true` only when all extractions succeed. Short-circuiting
// also ensures that an extraction is only evaluated if the previous
// extractions were successful.
//
// If you are reading values on multiple lines, consider [reading
// from the stream line-by-line](/common-tasks/input-streams/read-lines-from-stream.html)
// and then parsing each line.
|
Add oriented tests for facingNorth |
#include <gtest/gtest.h>
#include "../c_oriented.h"
#include "../c_moveable.h"
using aronnax::Vector2d;
using spacegun::Moveable;
using spacegun::Oriented;
class OrientedTest : public testing::Test {
protected:
virtual void SetUp() {
expectedAngle_ = 15.0;
moveable_ = new Moveable(Vector2d(), Vector2d(), expectedAngle_);
oriented_ = new Oriented(*moveable_);
}
virtual void TearDown() {
delete oriented_;
delete moveable_;
}
Oriented* oriented_;
Moveable* moveable_;
float expectedAngle_;
};
#define radiansToDegrees(angleRadians) (angleRadians * 180.0 / M_PI)
TEST_F(OrientedTest, Constructor) {
auto expected = 139.43671;
EXPECT_FLOAT_EQ(expected, oriented_->getNormalizedAngle());
}
TEST_F(OrientedTest, getType) {
using spacegun::COMPONENT_TYPE_ORIENTED;
auto actual = oriented_->getType();
EXPECT_EQ(COMPONENT_TYPE_ORIENTED, actual);
}
|
#include <gtest/gtest.h>
#include "../c_oriented.h"
#include "../c_moveable.h"
using aronnax::Vector2d;
using spacegun::Moveable;
using spacegun::Oriented;
class OrientedTest : public testing::Test {
protected:
virtual void SetUp() {
expectedAngle_ = 15.0;
moveable_ = new Moveable(Vector2d(), Vector2d(), expectedAngle_);
oriented_ = new Oriented(*moveable_);
}
virtual void TearDown() {
delete oriented_;
delete moveable_;
}
Oriented* oriented_;
Moveable* moveable_;
float expectedAngle_;
};
#define radiansToDegrees(angleRadians) (angleRadians * 180.0 / M_PI)
TEST_F(OrientedTest, Constructor) {
auto expected = 139.43671;
EXPECT_FLOAT_EQ(expected, oriented_->getNormalizedAngle());
}
TEST_F(OrientedTest, getType) {
using spacegun::COMPONENT_TYPE_ORIENTED;
auto actual = oriented_->getType();
EXPECT_EQ(COMPONENT_TYPE_ORIENTED, actual);
}
TEST_F(OrientedTest, facingNorth) {
auto actual = oriented_->facingNorth();
EXPECT_FALSE(actual);
}
|
Update init writing to universal init | /******************************************************
* This is CIR-KIT 3rd robot control driver.
* Author : Arita Yuta(Kyutech)
******************************************************/
#include "cirkit_unit03_driver.hpp"
#include <string>
#include <utility>
int main(int argc, char** argv)
{
ros::init(argc, argv, "cirkit_unit03_driver_node");
ROS_INFO("cirkit unit03 robot driver for ROS.");
ros::NodeHandle n {"~"};
std::string imcs01_port {"/dev/urbtc0"};
n.param<std::string>("imcs01_port", imcs01_port, imcs01_port);
cirkit::CirkitUnit03Driver driver(std::move(imcs01_port), ros::NodeHandle {});
driver.run();
return 0;
}
| /******************************************************
* This is CIR-KIT 3rd robot control driver.
* Author : Arita Yuta(Kyutech)
******************************************************/
#include "cirkit_unit03_driver.hpp"
#include <string>
#include <utility>
int main(int argc, char** argv)
{
ros::init(argc, argv, "cirkit_unit03_driver_node");
ROS_INFO("cirkit unit03 robot driver for ROS.");
ros::NodeHandle n {"~"};
std::string imcs01_port {"/dev/urbtc0"};
n.param<std::string>("imcs01_port", imcs01_port, imcs01_port);
cirkit::CirkitUnit03Driver driver {std::move(imcs01_port), ros::NodeHandle {}};
driver.run();
return 0;
}
|
ADD print the saved data to the save file | #include "Progression.h"
Progression* Progression::m_instance = nullptr;
Progression::Progression()
{
this->m_currentLevel = 0;
this->m_currentCheckpoint = 0;
this->m_unlockedLevels = 0;
}
Progression::~Progression()
{
}
bool Progression::WriteToFile(std::string filename)
{
std::ofstream saveFile;
saveFile.open("..\\Debug\\Saves\\" + filename + ".txt");
if (!saveFile.is_open()) {
return false;
}
else
{
saveFile << "Allhuakbar" << "\r\n";
saveFile.close();
}
return true;
}
bool Progression::ReadFromFile(std::string filename)
{
return false;
}
| #include "Progression.h"
Progression* Progression::m_instance = nullptr;
Progression::Progression()
{
this->m_currentLevel = 0;
this->m_currentCheckpoint = 0;
this->m_unlockedLevels = 0;
}
Progression::~Progression()
{
}
bool Progression::WriteToFile(std::string filename)
{
std::ofstream saveFile;
saveFile.open("..\\Debug\\Saves\\" + filename + ".txt");
if (!saveFile.is_open()) {
return false;
}
else
{
saveFile << this->m_currentLevel << "\r\n";
saveFile << this->m_currentCheckpoint << "\r\n";
saveFile << this->m_unlockedLevels << "\r\n";
saveFile.close();
}
return true;
}
bool Progression::ReadFromFile(std::string filename)
{
return false;
}
|
Change 4 spaces to tab | #include <iostream>
#include "list.h"
int List::numberOfNodes = 0;
void List::addToHead(int value) {
node *temp=new node;
temp->data=value;
temp->next=head;
head=temp;
numberOfNodes++;
}
void List::addToTail(int value) {
node *temp = new node;
temp->data = value;
temp->next = NULL;
if(head == NULL) {
head = temp;
tail = temp;
temp = NULL;
} else {
tail->next = temp;
tail = temp;
}
numberOfNodes++;
}
void List::toString() {
node *temp = new node;
temp=head;
while(temp!=NULL) {
std::cout << temp->data <<"\t";
temp = temp->next;
}
std::cout << std::endl;
}
| #include <iostream>
#include "list.h"
int List::numberOfNodes = 0;
void List::addToHead(int value) {
node *temp=new node;
temp->data=value;
temp->next=head;
head=temp;
numberOfNodes++;
}
void List::addToTail(int value) {
node *temp = new node;
temp->data = value;
temp->next = NULL;
if(head == NULL) {
head = temp;
tail = temp;
temp = NULL;
} else {
tail->next = temp;
tail = temp;
}
numberOfNodes++;
}
void List::toString() {
node *temp = new node;
temp=head;
while(temp!=NULL) {
std::cout << temp->data <<"\t";
temp = temp->next;
}
std::cout << std::endl;
}
|
Add constexpr keyword to inline inited variable | #include <Ab/Config.hpp>
#include <Ab/Memory.hpp>
namespace Ab {
const MemoryConfig Memory::defaultConfig_;
} // namespace Ab
| #include <Ab/Config.hpp>
#include <Ab/Memory.hpp>
namespace Ab {
constexpr const MemoryConfig Memory::defaultConfig_;
} // namespace Ab
|
Add a trivial write only GLSL test. | #include <Halide.h>
#include <stdio.h>
#include <stdlib.h>
using namespace Halide;
int main() {
// This test must be run with an OpenGL target
const Target &target = get_jit_target_from_environment();
if (!target.has_feature(Target::OpenGL)) {
fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
return 1;
}
Func f;
Var x, y, c;
f(x, y, c) = cast<uint8_t>(select(c == 0, 10*x + y,
c == 1, 127, 12));
Image<uint8_t> out(10, 10, 3);
f.bound(c, 0, 3).glsl(x, y, c);
f.realize(out);
out.copy_to_host();
for (int y=0; y<out.height(); y++) {
for (int x=0; x<out.width(); x++) {
if (!(out(x, y, 0) == 10*x+y && out(x, y, 1) == 127 && out(x, y, 2) == 12)) {
fprintf(stderr, "Incorrect pixel (%d, %d, %d) at x=%d y=%d.\n",
out(x, y, 0), out(x, y, 1), out(x, y, 2),
x, y);
return 1;
}
}
}
printf("Success!\n");
return 0;
}
| #include <Halide.h>
#include <stdio.h>
#include <stdlib.h>
using namespace Halide;
int main() {
// This test must be run with an OpenGL target
const Target &target = get_jit_target_from_environment();
if (!target.has_feature(Target::OpenGL)) {
fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
return 1;
}
Func f;
Var x, y, c;
f(x, y, c) = cast<uint8_t>(42);
Image<uint8_t> out(10, 10, 3);
f.bound(c, 0, 3).glsl(x, y, c);
f.realize(out);
out.copy_to_host();
for (int y=0; y<out.height(); y++) {
for (int x=0; x<out.width(); x++) {
for (int z=0; x<out.channels(); x++) {
if (!(out(x, y, z) == 42)) {
fprintf(stderr, "Incorrect pixel (%d) at x=%d y=%d z=%d.\n",
out(x, y, z), x, y, z);
return 1;
}
}
}
}
printf("Success!\n");
return 0;
}
|
Return code of driver program now non-zero on error. | /**
* @file
*
* The driver program.
*/
#include "bi/build/Driver.hpp"
#include "bi/exception/DriverException.hpp"
#include "bi/build/misc.hpp"
#include <iostream>
int main(int argc, char** argv) {
using namespace bi;
try {
/* first option (should be a program name) */
std::string prog;
if (argc > 1) {
prog = argv[1];
} else {
throw DriverException("No command given.");
}
Driver driver(argc - 1, argv + 1);
if (prog.compare("build") == 0) {
driver.build();
} else if (prog.compare("install") == 0) {
driver.install();
} else if (prog.compare("uninstall") == 0) {
driver.uninstall();
} else if (prog.compare("dist") == 0) {
driver.dist();
} else if (prog.compare("clean") == 0) {
driver.clean();
} else if (prog.compare("init") == 0) {
driver.init();
} else if (prog.compare("check") == 0) {
driver.check();
} else if (prog.compare("docs") == 0) {
driver.docs();
} else {
driver.run(prog + "_"); // underscore suffix for user-specified names
}
} catch (Exception& e) {
std::cerr << e.msg << std::endl;
}
return 0;
}
| /**
* @file
*
* The driver program.
*/
#include "bi/build/Driver.hpp"
#include "bi/exception/DriverException.hpp"
#include "bi/build/misc.hpp"
#include <iostream>
int main(int argc, char** argv) {
using namespace bi;
try {
/* first option (should be a program name) */
std::string prog;
if (argc > 1) {
prog = argv[1];
} else {
throw DriverException("No command given.");
}
Driver driver(argc - 1, argv + 1);
if (prog.compare("build") == 0) {
driver.build();
} else if (prog.compare("install") == 0) {
driver.install();
} else if (prog.compare("uninstall") == 0) {
driver.uninstall();
} else if (prog.compare("dist") == 0) {
driver.dist();
} else if (prog.compare("clean") == 0) {
driver.clean();
} else if (prog.compare("init") == 0) {
driver.init();
} else if (prog.compare("check") == 0) {
driver.check();
} else if (prog.compare("docs") == 0) {
driver.docs();
} else {
driver.run(prog + "_"); // underscore suffix for user-specified names
}
return 0;
} catch (Exception& e) {
std::cerr << e.msg << std::endl;
return 1;
}
}
|
Fix the windows allocator to behave properly on realloc. | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is a simple allocator based on the windows heap.
extern "C" {
HANDLE win_heap;
bool win_heap_init(bool use_lfh) {
win_heap = HeapCreate(0, 0, 0);
if (win_heap == NULL)
return false;
if (use_lfh) {
ULONG enable_lfh = 2;
HeapSetInformation(win_heap, HeapCompatibilityInformation,
&enable_lfh, sizeof(enable_lfh));
// NOTE: Setting LFH may fail. Vista already has it enabled.
// And under the debugger, it won't use LFH. So we
// ignore any errors.
}
return true;
}
void* win_heap_malloc(size_t s) {
return HeapAlloc(win_heap, 0, s);
}
void* win_heap_realloc(void* p, size_t s) {
if (!p)
return win_heap_malloc(s);
return HeapReAlloc(win_heap, 0, p, s);
}
void win_heap_free(void* s) {
HeapFree(win_heap, 0, s);
}
size_t win_heap_msize(void* p) {
return HeapSize(win_heap, 0, p);
}
} // extern "C"
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is a simple allocator based on the windows heap.
extern "C" {
HANDLE win_heap;
bool win_heap_init(bool use_lfh) {
win_heap = HeapCreate(0, 0, 0);
if (win_heap == NULL)
return false;
if (use_lfh) {
ULONG enable_lfh = 2;
HeapSetInformation(win_heap, HeapCompatibilityInformation,
&enable_lfh, sizeof(enable_lfh));
// NOTE: Setting LFH may fail. Vista already has it enabled.
// And under the debugger, it won't use LFH. So we
// ignore any errors.
}
return true;
}
void* win_heap_malloc(size_t size) {
return HeapAlloc(win_heap, 0, size);
}
void win_heap_free(void* size) {
HeapFree(win_heap, 0, size);
}
void* win_heap_realloc(void* ptr, size_t size) {
if (!ptr)
return win_heap_malloc(size);
if (!size) {
win_heap_free(ptr);
return NULL;
}
return HeapReAlloc(win_heap, 0, ptr, size);
}
size_t win_heap_msize(void* ptr) {
return HeapSize(win_heap, 0, ptr);
}
} // extern "C"
|
Put fast legality checks first | #include "Moves/Queenside_Castle.h"
#include "Moves/Move.h"
#include "Game/Board.h"
#include "Pieces/Piece.h"
Queenside_Castle::Queenside_Castle() : Move(-2, 0)
{
}
bool Queenside_Castle::move_specific_legal(const Board& board, char file_start, int rank_start) const
{
return ! board.piece_has_moved(file_start, rank_start)
&& ! board.piece_has_moved('a', rank_start)
&& ! board.king_is_in_check(board.whose_turn())
&& board.safe_for_king('d', rank_start, board.whose_turn())
&& ! board.view_piece_on_square('b', rank_start);
}
bool Queenside_Castle::can_capture() const
{
return false;
}
void Queenside_Castle::side_effects(Board& board, char /* file_start */, int rank_start) const
{
board.make_move('a', rank_start, 'd', rank_start); // move Rook
}
std::string Queenside_Castle::name() const
{
return "Queenside Castle";
}
std::string Queenside_Castle::game_record_item(const Board&, char, int) const
{
return "O-O-O";
}
| #include "Moves/Queenside_Castle.h"
#include "Moves/Move.h"
#include "Game/Board.h"
#include "Pieces/Piece.h"
Queenside_Castle::Queenside_Castle() : Move(-2, 0)
{
}
bool Queenside_Castle::move_specific_legal(const Board& board, char file_start, int rank_start) const
{
return ! board.piece_has_moved(file_start, rank_start)
&& ! board.piece_has_moved('a', rank_start)
&& ! board.view_piece_on_square('b', rank_start)
&& ! board.king_is_in_check(board.whose_turn())
&& board.safe_for_king('d', rank_start, board.whose_turn());
}
bool Queenside_Castle::can_capture() const
{
return false;
}
void Queenside_Castle::side_effects(Board& board, char /* file_start */, int rank_start) const
{
board.make_move('a', rank_start, 'd', rank_start); // move Rook
}
std::string Queenside_Castle::name() const
{
return "Queenside Castle";
}
std::string Queenside_Castle::game_record_item(const Board&, char, int) const
{
return "O-O-O";
}
|
Add quick test for logging worker. | /*
@ 0xCCCCCCCC
*/
int main()
{
return 0;
} | /*
@ 0xCCCCCCCC
*/
#include <conio.h>
#include <random>
#include <sstream>
#include "klog/klog_worker.h"
void WorkerTest()
{
klog::LogWorker worker(std::wstring(L"test.log"), std::chrono::seconds(3));
std::random_device rd;
std::default_random_engine engine(rd());
std::uniform_int_distribution<> dist(100, 1000);
int count = 10;
for (auto i = 0; i < count; ++i) {
std::ostringstream ss;
ss << "This is the " << i << "th trial\n";
worker.Send(ss.str());
ss.clear();
std::this_thread::sleep_for(std::chrono::milliseconds(dist(engine)));
}
}
int main()
{
_getch();
return 0;
} |
Fix normal calculation for scaled spheres. | #include "./ShapeSphere.hpp"
#include "math/misc.hpp"
#include "math/Sphere.hpp"
#include <cmath>
using namespace yks;
Optional<float> ShapeSphere::hasIntersection(const Ray& r) const {
const Ray local_ray = transform.localFromParent * r;
return intersect_with_sphere(vec3_0, 1.0f, local_ray);
}
Optional<Intersection> ShapeSphere::intersect(const Ray& r) const {
const Ray local_ray = transform.localFromParent * r;
const Optional<float> intersection = intersect_with_sphere(vec3_0, 1.0f, local_ray);
if (!intersection) {
return Optional<Intersection>();
}
const float t = *intersection;
Intersection i;
i.t = t;
i.position = r(t);
vec3 local_pos = local_ray(t);
i.uv = mvec2(std::atan2(local_pos[2], local_pos[0]) / (2*pi) + 0.5f, std::acos(local_pos[1]) / pi);
i.normal = mvec3(transpose(transform.localFromParent) * mvec4(normalized(local_ray(t)), 0.0f));
return make_optional<Intersection>(i);
}
| #include "./ShapeSphere.hpp"
#include "math/misc.hpp"
#include "math/Sphere.hpp"
#include <cmath>
using namespace yks;
Optional<float> ShapeSphere::hasIntersection(const Ray& r) const {
const Ray local_ray = transform.localFromParent * r;
return intersect_with_sphere(vec3_0, 1.0f, local_ray);
}
Optional<Intersection> ShapeSphere::intersect(const Ray& r) const {
const Ray local_ray = transform.localFromParent * r;
const Optional<float> intersection = intersect_with_sphere(vec3_0, 1.0f, local_ray);
if (!intersection) {
return Optional<Intersection>();
}
const float t = *intersection;
Intersection i;
i.t = t;
i.position = r(t);
vec3 local_pos = local_ray(t);
i.uv = mvec2(std::atan2(local_pos[2], local_pos[0]) / (2*pi) + 0.5f, std::acos(local_pos[1]) / pi);
i.normal = normalized(mvec3(transpose(transform.localFromParent) * mvec4(local_ray(t), 0.0f)));
return make_optional<Intersection>(i);
}
|
Modify Level tests to focus on boundaries. | #include <stdexcept>
#include "gtest/gtest.h"
#include "map/Level.h"
#include "map/Tile.h"
TEST(LevelTest, DefaultLevelIsWalls)
{
Level l1(10, 10);
EXPECT_EQ(WallTile, l1.getTile(5, 5));
}
TEST(LevelTest, LevelGetTile)
{
Level l1(10, 10);
EXPECT_NO_THROW(l1.getTile(5, 5));
EXPECT_THROW(l1.getTile(50, 50), std::out_of_range);
}
TEST(LevelTest, LevelArrayAccess)
{
Level l1(10, 10);
EXPECT_NO_THROW(l1[5][5]);
EXPECT_THROW(l1[50][50], std::out_of_range);
}
| #include <stdexcept>
#include "gtest/gtest.h"
#include "map/Level.h"
#include "map/Tile.h"
TEST(LevelTest, DefaultLevelIsWalls)
{
Level l1(10, 10);
EXPECT_EQ(WallTile, l1.getTile(5, 5));
}
TEST(LevelTest, LevelGetTile)
{
Level l1(10, 10);
EXPECT_NO_THROW(l1.getTile(9, 9));
EXPECT_THROW(l1.getTile(10, 10), std::out_of_range);
}
TEST(LevelTest, LevelArrayAccess)
{
Level l1(10, 10);
EXPECT_NO_THROW(l1[9][9]);
EXPECT_THROW(l1[10][10], std::out_of_range);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.